--!optimize 2 --!nocheck -- rosetta (Roblox bundle): GENERATED by tools/bundle.py from src/Rosetta - do not edit. -- require(this) -> the API (docs/API.md); Rosetta._internal("codecs/video/Mpeg1") -> an internal module. -- Error lines map back to the sources through Rosetta.luau.linemap.json (python3 -I tools/bundle.py --where). local __FILES = {} 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 __FILES[""] = function() -- Rosetta: read, write and convert file formats in pure Luau, on Roblox and on LuaJIT / LÖVE (through tools/build.py). -- Formats are found through the generated Registry: by content (each format's sniff), then by extension. Never throws -- on bad data or bad arguments: every function returns nil, Err. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Input = __include("core/Input") local Types = __include("Types") local Registry = __include("Registry") local Video = __include("codecs/video/Video") local AudioWrap = __include("containers/AudioWrap") local Rbx = __include("codecs/model/Rbx") local ImageOps = __include("ops/ImageOps") local host = __include("host") local F = {} F.version = "0.1.0" F.Err = Err F.Types = Types F.Bytes = Bytes F.Rbx = Rbx F.null = Types.null F.host = host F.plugins = {} :: { [string]: any } -- injected optional dependencies (plugins.brep for cad/step) local KIND_CATEGORY: { [string]: string } = { image = "image", audio = "audio", video = "video", scene = "model", rbxtree = "model", -- codecs/model/Rbx trees (model/rbxm, model/rbxmx) cad = "cad", font = "font", archive = "archive", vector = "vector", tilemap = "vector", layered = "layered", subtitles = "subtitle", music = "music", midi = "music", playlist = "playlist", } local loaded: { [string]: any } = {} local function module(entry: Registry.Entry): (any, Err.Err?) local m = loaded[entry.path] if m then return m end local ok, res = pcall(entry.load) if not ok then return nil, Err.new(Err.UNSUPPORTED, "format " .. entry.name .. " failed to load: " .. tostring(res)) end loaded[entry.path] = res return res end local function inCategory(entry: Registry.Entry, category: string?): boolean return category == nil or entry.category == category end local function find(key: string, category: string?): Registry.Entry? local k = string.lower(key) for _, e in Registry do if e.name == k and inCategory(e, category) then return e end end for _, e in Registry do if inCategory(e, category) and table.find(e.extensions, k) then return e end end return nil end local function detect(buf: buffer, name: string?, category: string?, format: string?): (Registry.Entry?, Err.Err?) if format then local e = find(format, category) if not e then return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. format .. (if category then " in " .. category else "")) end return e, nil end local ext = Input.extension(name) local best: Registry.Entry? = nil local bestScore = 0 for _, e in Registry do if inCategory(e, category) and (e.caps.decode or e.caps.open) then local m = module(e) if m and m.sniff then local ok, score = pcall(m.sniff, Bytes.reader(buf)) if ok and type(score) == "number" and score > 0 then if ext and table.find(e.extensions, ext) then score += 0.01 -- ties go to the extension end if score > bestScore then best, bestScore = e, score end end end end end if best then return best, nil end if ext then local e = find(ext, category) if e then return e, nil end end return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. (if name then " (" .. name .. ")" else "") .. (if category then " for " .. category else "")) end -- music that renders (MOD, S3M, XM, IT, MIDI) is also audio: an audio lookup falls back to it (rendered = true) local function detectFor(buf: buffer, name: string?, o: { [string]: any }): (Registry.Entry?, Err.Err?, boolean) local entry, err = detect(buf, name, o.category, o.format) if not entry and o.category == "audio" then local e = detect(buf, name, "music", o.format) if e and e.caps.render then return e, nil, true end end return entry, err, false end local function tag(value: any, formatName: string) if type(value) == "table" then local meta = value.meta if type(meta) == "table" then if meta.source == nil then meta.source = { format = formatName } elseif type(meta.source) == "table" and meta.source.format == nil then meta.source.format = formatName end end end end local function drain(dec: any): any local channels = dec.channels local parts, total = {}, 0 while true do local out, n = dec:read(65536) if not out or n == 0 then break end local copy = buffer.create(n * channels * 4) buffer.copy(copy, 0, out, 0, n * channels * 4) table.insert(parts, copy) total += n end local a = Types.Audio.new(dec.sampleRate, channels, total) local o = 0 for _, p in parts do buffer.copy(a.samples, o, p) o += buffer.len(p) end a.tags = dec.tags or {} return a end -- siblings resolve relative to path's directory only (no absolute paths, no "..", no URLs) local function siblings(path: string): (uri: string) -> buffer? local dir = string.match(path, "^(.*[/\\])") or "" return function(uri: string): buffer? if type(uri) ~= "string" or uri == "" or string.find(uri, "^%a[%w+.-]*:") or string.sub(uri, 1, 1) == "/" then return nil end local u = string.gsub(uri, "%%(%x%x)", function(h: string): string return string.char(tonumber(h, 16) :: number) end) for part in string.gmatch(u, "[^/\\]+") do if part == ".." then return nil end end local b = host.readFile(dir .. u) return b end end type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options local load: (src: any, opts: Options?) -> (any, Err.Err?) local function pageLoader(value: any, name: string?, o: Options) if type(value) ~= "table" or value.kind ~= "font" or type(value.meta) ~= "table" or type(value.meta.pageFiles) ~= "table" then return end local user: any = o.loadPage if value.pages or (value.meta.pageLoader and type(user) ~= "function") then return end local dir = if name then string.match(name, "^(.*[/\\])") or "" else nil if type(user) ~= "function" and not (dir and host.hasFiles) then return end value.meta.pageLoader = function(file: string, page: number): (any, Err.Err?) local src: any if type(user) == "function" then src = (user :: any)(file, page) else src = (dir :: string) .. file end if type(src) == "table" then return src end if src == nil then return nil, Err.new(Err.IO, "no data for page " .. file) end return load(src, { category = "image", name = file, path = type(user) ~= "function" }) end end -- a single-stream archive (meta.stream) holding another archive or a .pcf / .psf(u) / .bdf font loads as that, with -- meta.compression = the outer format; package archives load as meta.payload (meta.container / meta.outer) local function unwrap(value: any, formatName: string, o: Options): any if o.unwrap == false or o.format ~= nil or (o._depth or 0) >= 3 then return value end if type(value) ~= "table" or value.kind ~= "archive" or type(value.meta) ~= "table" then return value end local payload = value.meta.payload if not value.meta.stream and type(payload) ~= "string" then return value end local ok, list = pcall(value.list, value) if not ok or type(list) ~= "table" or (#list ~= 1 and type(payload) ~= "string") or #list == 0 then return value end local entryName = if type(payload) == "string" then payload else list[1].name local rok, inner = pcall(value.read, value, entryName) if not rok or type(inner) ~= "buffer" then return value end local category = "archive" local e = detect(inner, nil, "archive", nil) local innerExt = Input.extension(entryName) or "" if not e and value.meta.stream and (innerExt == "pcf" or innerExt == "psf" or innerExt == "psfu" or innerExt == "bdf") then -- compressed bitmap fonts (.pcf.gz, .psf.gz, .bdf.gz: X11 and console font directories) load as the font e = detect(inner, entryName, "font", nil) category = "font" end if not e then return value end local io = table.clone(o) io.category = category io.name = entryName io._depth = (o._depth or 0) + 1 local v = load(inner, io) if type(v) ~= "table" or type(v.meta) ~= "table" then return value end if type(payload) == "string" then v.meta.container = formatName v.meta.outer = value else v.meta.compression = formatName end return v end -- api hooks (a format never requires another format): opts.decodeImage / encodeImage, opts.plugins, opts.decodeModule, -- opts.openAudio (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / FLAC / AC-3 as they are) local function openAudio(demuxer: any, track: any): (any, Err.Err?) local buf, fmt, err = AudioWrap.wrap(demuxer, track) if not buf then return nil, err end local dec, oerr = F.open(buf, { format = fmt, category = "audio" }) -- Matroska CodecDelay: ffmpeg drops it for MPEG audio / AAC; Opus has its own pre-skip and Vorbis's delay is -- already the decoder's own (its first packet returns nothing) -- MP4 edit lists add the play length (the encoder's end padding is cut, as ffmpeg does) if dec and fmt ~= "opus" and fmt ~= "vorbis" then local skip = if type(track.codecDelay) == "number" and track.codecDelay > 0 then math.floor(track.codecDelay * dec.sampleRate + 0.5) else 0 local length = if type(track.playDuration) == "number" and track.playDuration > 0 then math.floor(track.playDuration * dec.sampleRate + 0.5) else nil if skip > 0 or length then dec = AudioWrap.trim(dec, skip, length) end end return dec, oerr end local function withHooks(o: Options): Options if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil and o.decodeModule ~= nil then return o end local c = table.clone(o) if c.plugins == nil then c.plugins = F.plugins end if c.openAudio == nil then c.openAudio = openAudio end if c.decodeImage == nil then c.decodeImage = function(b: buffer): (any, Err.Err?) return F.load(b, { category = "image" }) end end if c.encodeImage == nil then c.encodeImage = function(img: any, format: string): (any, Err.Err?) return F.save(img, nil, { format = format, category = "image" }) end end if c.decodeModule == nil then c.decodeModule = function(b: buffer, format: string?): (any, Err.Err?) return F.load(b, { category = "music", format = format }) end end return c end function F.load(src: any, opts: Options?): (any, Err.Err?) local o: Options = opts or {} local buf, ierr, name = Input.resolve(src, o, host) if not buf then return nil, ierr end if name and o.name == nil then o = table.clone(o) o.name = name -- formats may use the file name (single-stream archives name their entry after it) end local entry, derr, rendered = detectFor(buf, name, o) if not entry then return nil, derr end local m, merr = module(entry) if not m then return nil, merr end if o.resolve == nil and name and name == (type(src) == "string" and src or nil) and host.hasFiles then o = table.clone(o) o.resolve = siblings(name) end local value, err if m.decode and not rendered then local ok, v, e = pcall(m.decode, Bytes.reader(buf), withHooks(o)) if not ok then return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name) end value, err = v, e elseif m.open then local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o)) if not ok then return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) end if dec then value = if type(dec) == "table" and dec.kind == "video" then dec else drain(dec) end err = e else return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no decoder"), entry.name) end if value == nil then return nil, Err.wrap(err or Err.new(Err.CORRUPT, "decode failed"), entry.name) end tag(value, entry.name) pageLoader(value, name, o) return unwrap(value, entry.name, o) end load = F.load function F.open(src: any, opts: Options?): (any, Err.Err?) local o: Options = opts or {} local buf, ierr, name = Input.resolve(src, o, host) if not buf then return nil, ierr end local entry, derr = detectFor(buf, name, o) if not entry and o.category == "video" and o.format == nil then entry = detect(buf, name, "image", nil) -- animated images open as frames-backed videos end if not entry then return nil, derr end local m, merr = module(entry) if not m then return nil, merr end if not m.open and entry.category == "image" and o.category == "video" then local io = table.clone(o) io.category = "image" io.format = entry.name local img, lerr = F.load(buf, io) if not img then return nil, lerr end return F.video.fromImage(img, o) end if not m.open then return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no streaming decoder (use load)"), entry.name) end local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o)) if not ok then return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) end if dec == nil then return nil, Err.wrap(e or Err.new(Err.CORRUPT, "open failed"), entry.name) end return dec end local encodeTextures: (scene: any) -> Err.Err? local function videoToImage(v: any, o: Options): (any, Err.Err?) if type(v.nextFrame) ~= "function" or type(v.toRGBA) ~= "function" then return nil, Err.new(Err.ARG, "save: not a VideoDecoder") end local cap = o.maxFrames or 300 local want = o.frames local fps = o.fps if type(cap) ~= "number" or cap < 1 or (want ~= nil and (type(want) ~= "number" or want < 1)) or (fps ~= nil and (type(fps) ~= "number" or fps <= 0 or fps > 1000)) then return nil, Err.new(Err.ARG, "save: frames / maxFrames must be >= 1 and fps 0..1000") end local limit = math.floor(if want then math.min(want, cap) else cap) local w, h = math.max(1, tonumber(v.width) or 1), math.max(1, tonumber(v.height) or 1) limit = math.max(1, math.min(limit, math.floor((o.maxPixels or 2 ^ 25) / (w * h)))) local defaultDur = if type(v.frameRate) == "number" and v.frameRate > 0 then 1 / v.frameRate else 0.1 local images: { any }, delays: { number } = {}, {} local t0: number? = nil local taken = 0 -- output slots used (fps mode) while #images < limit do local ok, f, ferr = pcall(v.nextFrame, v) if not ok then return nil, Err.new(Err.CORRUPT, "video decoder threw: " .. tostring(f)) end if f == nil then if ferr then return nil, ferr end break end local dur = if type(f.duration) == "number" and f.duration > 0 then f.duration else defaultDur local delay = dur if fps then local start: number = t0 or f.pts t0 = start local slots = math.ceil((f.pts - start + dur) * fps - 1e-6) - taken delay = slots / fps taken += math.max(0, slots) end if delay > 0 then local rok, img = pcall(v.toRGBA, v, f) if not rok or type(img) ~= "table" then return nil, Err.new(Err.CORRUPT, "frame " .. tostring(f.index) .. " did not convert to rgba8") end table.insert(images, img) table.insert(delays, delay) end end if #images == 0 then return nil, Err.new(Err.ARG, "save: the video has no frames") end local img, ierr = ImageOps.fromFrames(images, delays) if not img then return nil, ierr end img.loops = if type(v.loops) == "number" then v.loops else 0 img.meta.source = { format = v.format } return img, nil end local TRACKER_FAMILY = { mod = true, s3m = true, xm = true, it = true } local function renderMusic(value: any, o: Options): (any, Err.Err?) local ok, dec, err if value.kind == "midi" then local m, merr = F.format("midi") if not m then return nil, merr end ok, dec, err = pcall(m.render, value, o) elseif TRACKER_FAMILY[value.engine or value.format] == nil and type(value.render) == "function" then -- AHX / HVL render through the Module's own method (a failed render is an empty Decoder carrying .err) ok, dec = pcall(value.render, value, o) if ok and type(dec) == "table" and dec.err then return nil, dec.err end else local Tracker: any = __include("codecs/audio/Tracker") ok, dec, err = pcall(Tracker.render, value, o) end if not ok then return nil, Err.new(Err.ARG, "render threw: " .. tostring(dec)) end if dec == nil then return nil, err or Err.new(Err.ARG, "render failed") end return dec, nil end local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?, string?) local category = o.category if category == nil and type(value) == "table" and type(value.kind) == "string" then category = KIND_CATEGORY[value.kind] end local key = o.format or Input.extension(dest) if key == nil and type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" then key = value.meta.source.format end if key == nil then return nil, nil, Err.new(Err.ARG, "save: no format (pass opts.format or a destination with an extension)") end local entry = find(key, category) if not entry and category == "image" and type(value) == "table" and value.kind == "image" then entry = find(key, "video") -- an (animated) image written as a video: F.convert(gif, "avi") end if not entry and category == "video" and type(value) == "table" and value.kind == "video" then entry = find(key, "image") -- a video written as an animated image (F.save): F.convert(avi, "gif") end if not entry and category == "music" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then entry = find(key, "audio") -- a Module / Midi saved as audio is rendered first (F.save): F.convert(mod, "wav") end if not entry then return nil, nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. key .. (if category then " for " .. category else "")) end local m, merr = module(entry) if not m then return nil, nil, merr end if not m.encode then local alt = nil for _, e in Registry do if e.category == entry.category and e.caps.encode then alt = e.name break end end return nil, nil, Err.wrap(Err.new(Err.UNSUPPORTED, "read-only format" .. (if alt then "; try " .. alt else "")), entry.name) end return entry, m, nil, key end -- scene textures with only a decoded image get PNG bytes before a model writer sees them (writers never encode images) function encodeTextures(scene: any): Err.Err? if type(scene.textures) ~= "table" then return nil end for _, tex in scene.textures do if type(tex) == "table" and tex.data == nil and type(tex.image) == "table" and tex.uri == nil then local png, err = F.save(tex.image, nil, { format = "png" }) if not png then return err end tex.data, tex.mime = png, "image/png" end end return nil end function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?, { [string]: any }?) local o: Options = opts or {} local entry, m, err, key = encoderFor(value, dest, o) if not entry then return nil, err end o = table.clone(o) o.format = o.format or key if dest then o.name = o.name or string.match(dest, "([^/\\]+)$") if o.files == nil then o.files = {} end elseif o.files == nil and entry.caps.extraFiles then o.files = {} end if entry.category == "video" and type(value) == "table" and value.kind == "image" then local v, verr = F.video.fromImage(value) if not v then return nil, verr end value = v end if entry.category == "image" and type(value) == "table" and value.kind == "video" then local img, ierr = videoToImage(value, o) if not img then return nil, ierr end value = img end if entry.category == "audio" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then local dec, rerr = renderMusic(value, o) if not dec then return nil, rerr end value = dec end if type(value) == "table" and value.kind == "scene" then local terr = encodeTextures(value) if terr then return nil, terr end end local ok, buf, e = pcall(m.encode, value, withHooks(o)) if not ok then return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name) end if buf == nil then return nil, Err.wrap(e or Err.new(Err.ARG, "encode failed"), entry.name) end if dest then local wok, werr = host.writeFile(dest, buf) if not wok then return nil, werr end if type(o.files) == "table" and o.files ~= (opts and opts.files) then local dir = string.match(dest, "^(.*[/\\])") or "" for fname, data in o.files do local fok, ferr = host.writeFile(dir .. fname, if type(data) == "string" then buffer.fromstring(data) else data) if not fok then return nil, ferr end end end return true end if type(o.files) == "table" and o.files ~= (opts and opts.files) and next(o.files) ~= nil then return buf, nil, o.files end return buf end function F.saveString(value: any, opts: Options?): (string?, Err.Err?) local buf, err = F.save(value, nil, opts) if not buf then return nil, err end return buffer.tostring(buf), nil end function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?, { [string]: any }?) local o: Options = opts or {} local value, err = F.load(src, o) if value == nil then return nil, err end local so = table.clone(o) so.format = format so.category = nil return F.save(value, o.out, so) end function F.detect(src: any, opts: Options?): (string?, Err.Err?) local o: Options = opts or {} local buf, ierr, name = Input.resolve(src, o, host) if not buf then return nil, ierr end local entry, err = detect(buf, name, o.category, o.format) if not entry then return nil, err end -- a format may name the file's flavour more precisely (video/mkv: "webm" for DocType webm) local m = module(entry) if m and type(m.variant) == "function" then local ok, v = pcall(m.variant, Bytes.reader(buf)) if ok and type(v) == "string" then return v, nil end end return entry.name, nil end type FormatInfo = { name: string, category: string, extensions: { string }, mime: { string }, caps: { [string]: any } } function F.formats(category: string?): { FormatInfo } local out = {} for _, e in Registry do if inCategory(e, category) then table.insert(out, { name = e.name, category = e.category, extensions = e.extensions, mime = e.mime, caps = e.caps }) end end return out end function F.format(name: string): (any, Err.Err?) local e = find(name) if not e then return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. name) end return module(e) end local function with(opts: Options?, category: string): Options local o: Options = if opts then table.clone(opts) else {} o.category = category return o end for category in Types.CATEGORIES do local cat: string = category F[cat] = { load = function(src: any, opts: Options?): (any, Err.Err?) return F.load(src, with(opts, cat)) end, open = function(src: any, opts: Options?): (any, Err.Err?) return F.open(src, with(opts, cat)) end, save = function(value: any, dest: string?, opts: Options?): (any, Err.Err?) return F.save(value, dest, with(opts, cat)) end, formats = function(): { FormatInfo } return F.formats(cat) end, } end F.data.null = Types.null for _, fn in { "toBodies", "fromBodies", "tessellate" } do local name: string = fn F.cad[name] = function(value: any, opts: Options?): (any, any) local o: Options = if opts then table.clone(opts) else {} if o.plugins == nil then o.plugins = F.plugins end local m, err = F.format("step") if not m then return nil, err end local ok, a, b = pcall(m[name], value, o) if not ok then return nil, Err.wrap(Err.new(Err.CORRUPT, name .. " threw: " .. tostring(a)), "step") end if a == nil and type(b) == "table" and b.code then return nil, Err.wrap(b, "step") end return a, b end end for _, fn in { "new", "addPattern", "setCell", "getCell", "addSample", "addInstrument", "note" } do local name: string = fn F.music[name] = function(...: any): (any, Err.Err?) return (F.ops.music :: any)[name](...) end end F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?) if type(img) ~= "table" or img.kind ~= "image" then return nil, Err.new(Err.ARG, "fromImage: expected an Image") end local frames, delays = { img }, { 0.1 } if type(img.frames) == "table" and #img.frames > 0 then local list, cerr = ImageOps.coalesce(img) if not list then return nil, cerr end frames = list delays = {} for i, f in img.frames do delays[i] = if type(f.delay) == "number" and f.delay > 0 then f.delay else 0.1 end elseif img.format ~= "rgba8" and img.format ~= "yuv420p" then local c, cerr = ImageOps.convert(img, "rgba8") if not c then return nil, cerr end frames = { c } end local src = type(img.meta) == "table" and img.meta.source return Video.fromFrames(frames, delays, { format = type(src) == "table" and src.format or "image", loops = img.loops, meta = img.meta }) end F.video.fromFrames = function(images: any, delays: any?, opts: Options?): (any, Err.Err?) return Video.fromFrames(images, delays, opts) end F.video.codecs = Video F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: Err.Err }) local errs: { [number]: Err.Err } = {} if type(scene) ~= "table" or type(scene.textures) ~= "table" then return scene, errs end local resolve: ((any) -> any)? = opts and opts.resolve for i, tex in scene.textures do if type(tex) == "table" and tex.image == nil then local data = tex.data if data == nil and tex.uri and resolve then data = resolve(tex.uri) end if data ~= nil then local img, err = F.load(data, { category = "image", name = tex.uri, data = true }) if img then tex.image = img elseif err then errs[i] = err end end end end return scene, errs end local OPS: { [string]: () -> any } = { image = function() return ImageOps end, mesh = function() return __include("ops/MeshOps") end, layers = function() return __include("ops/LayerOps") end, audio = function() return __include("ops/AudioOps") end, music = function() return __include("ops/MusicOps") end, vector = function() return { rasterize = function(v: any, w: number?, h: number?, opts: any?): (any, Err.Err?) local svg, err = F.format("svg") if not svg then return nil, err end local ok, img, rerr = pcall(svg.rasterize, v, w, h, opts) if not ok then return nil, Err.wrap(Err.new(Err.CORRUPT, "rasterize threw: " .. tostring(img)), "svg") end if img == nil and rerr then return nil, Err.wrap(rerr, "svg") end return img, rerr end, } end, } F.ops = setmetatable({}, { __index = function(t: any, k: string): any local make = OPS[k] if not make then return nil end local m = make() rawset(t, k, m) return m end, }) :: any return F end __FILES["Registry"] = function() -- Registry: GENERATED by tools/gen_registry.py from the format folders - do not edit. -- One entry per format: the contract metadata (copied from its init.luau) and load(), which requires the format -- module on first use (a static require, as Roblox needs). Order: category, then name. type Entry = { name: string, category: string, path: string, extensions: { string }, mime: { string }, deps: { string }, caps: { [string]: any }, load: () -> any, } local list: { Entry } = { { name = "ani", category = "image", path = "image/ani", extensions = { "ani" }, mime = { "application/x-navi-animation" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, caps = { decode = true, encode = true, alpha = true, animation = true, frames = true }, load = function() return __include("image/ani") end, }, { name = "blp", category = "image", path = "image/blp", extensions = { "blp" }, mime = { "image/x-blp" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" }, caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } }, load = function() return __include("image/blp") end, }, { name = "bmp", category = "image", path = "image/bmp", extensions = { "bmp", "dib" }, mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, caps = { decode = true, encode = true, alpha = true, depths = { 1, 2, 4, 8, 16, 24, 32 }, rle = true }, load = function() return __include("image/bmp") end, }, { name = "dds", category = "image", path = "image/dds", extensions = { "dds" }, mime = { "image/vnd-ms.dds", "image/x-dds" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "codecs/image/Texel", "codecs/image/Texture" }, caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" } }, load = function() return __include("image/dds") end, }, { name = "exr", category = "image", path = "image/exr", extensions = { "exr" }, mime = { "image/x-exr", "image/aces" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" }, caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true }, load = function() return __include("image/exr") end, }, { name = "gif", category = "image", path = "image/gif", extensions = { "gif" }, mime = { "image/gif" }, deps = { "core/Err", "core/Bytes", "codecs/compress/Lzw", "codecs/image/Quantize", "Types" }, caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } }, load = function() return __include("image/gif") end, }, { name = "hdr", category = "image", path = "image/hdr", extensions = { "hdr", "pic", "rgbe" }, mime = { "image/vnd.radiance", "image/x-hdr" }, deps = { "core/Err", "core/Bytes", "Types" }, caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } }, load = function() return __include("image/hdr") end, }, { name = "icns", category = "image", path = "image/icns", extensions = { "icns" }, mime = { "image/icns", "image/x-icns" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" }, caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } }, load = function() return __include("image/icns") end, }, { name = "ico", category = "image", path = "image/ico", extensions = { "ico", "cur" }, mime = { "image/vnd.microsoft.icon", "image/x-icon" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } }, load = function() return __include("image/ico") end, }, { name = "ilbm", category = "image", path = "image/ilbm", extensions = { "iff", "ilbm", "lbm", "pbm" }, mime = { "image/x-ilbm", "image/x-iff" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" }, caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } }, load = function() return __include("image/ilbm") end, }, { name = "jpeg", category = "image", path = "image/jpeg", extensions = { "jpg", "jpeg", "jpe", "jfif" }, mime = { "image/jpeg" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg" }, caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true }, load = function() return __include("image/jpeg") end, }, { name = "ktx", category = "image", path = "image/ktx", extensions = { "ktx2", "ktx" }, mime = { "image/ktx2", "image/ktx" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" }, caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } }, load = function() return __include("image/ktx") end, }, { name = "pcx", category = "image", path = "image/pcx", extensions = { "pcx", "pcc", "dcx" }, mime = { "image/vnd.zbrush.pcx", "image/x-pcx" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } }, load = function() return __include("image/pcx") end, }, { name = "png", category = "image", path = "image/png", extensions = { "png", "apng" }, mime = { "image/png", "image/apng" }, deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "Types", "containers/Chunks" }, caps = { decode = true, encode = true, animation = true, alpha = true, depths = { 1, 2, 4, 8, 16 } }, load = function() return __include("image/png") end, }, { name = "pnm", category = "image", path = "image/pnm", extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" }, mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" }, deps = { "core/Err", "core/Bytes", "Types" }, caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true }, load = function() return __include("image/pnm") end, }, { name = "qoi", category = "image", path = "image/qoi", extensions = { "qoi" }, mime = { "image/qoi", "image/x-qoi" }, deps = { "core/Err", "core/Bytes", "Types" }, caps = { decode = true, encode = true, alpha = true, depths = { 8 } }, load = function() return __include("image/qoi") end, }, { name = "sgi", category = "image", path = "image/sgi", extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" }, mime = { "image/sgi", "image/x-rgb" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } }, load = function() return __include("image/sgi") end, }, { name = "sunras", category = "image", path = "image/sunras", extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" }, mime = { "image/x-sun-raster", "image/x-cmu-raster" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" }, caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } }, load = function() return __include("image/sunras") end, }, { name = "tga", category = "image", path = "image/tga", extensions = { "tga", "icb", "vda", "vst", "tpic" }, mime = { "image/x-tga", "image/x-targa" }, deps = { "core/Err", "core/Bytes", "Types" }, caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } }, load = function() return __include("image/tga") end, }, { name = "tiff", category = "image", path = "image/tiff", extensions = { "tif", "tiff" }, mime = { "image/tiff" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/compress/Lzw", "codecs/compress/PackBits" }, caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true }, load = function() return __include("image/tiff") end, }, { name = "tim", category = "image", path = "image/tim", extensions = { "tim" }, mime = { "image/x-tim" }, deps = { "core/Err", "core/Bytes", "Types" }, caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 4, 8, 16, 24 } }, load = function() return __include("image/tim") end, }, { name = "vtf", category = "image", path = "image/vtf", extensions = { "vtf" }, mime = { "image/x-vtf" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Bcn", "codecs/image/Texel" }, caps = { decode = true, encode = false, alpha = true, animation = true, versions = { "7.0", "7.1", "7.2", "7.3", "7.4", "7.5" } }, load = function() return __include("image/vtf") end, }, { name = "webp", category = "image", path = "image/webp", extensions = { "webp" }, mime = { "image/webp" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Vp8", "codecs/image/Vp8L", "containers/Riff" }, caps = { decode = true, encode = true, animation = true, alpha = true, lossy = true, lossless = true, depths = { 8 } }, load = function() return __include("image/webp") end, }, { name = "xbm", category = "image", path = "image/xbm", extensions = { "xbm", "bm" }, mime = { "image/x-xbitmap", "image/x-xbm" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, caps = { decode = true, encode = true, depths = { 1 } }, load = function() return __include("image/xbm") end, }, { name = "xpm", category = "image", path = "image/xpm", extensions = { "xpm", "pm" }, mime = { "image/x-xpixmap", "image/x-xpm" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } }, load = function() return __include("image/xpm") end, }, { name = "aac", category = "audio", path = "audio/aac", extensions = { "aac", "adts" }, mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Pcm", "codecs/audio/Stream" }, caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, load = function() return __include("audio/aac") end, }, { name = "ac3", category = "audio", path = "audio/ac3", extensions = { "ac3", "a52" }, mime = { "audio/ac3", "audio/x-ac3" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, load = function() return __include("audio/ac3") end, }, { name = "adpcm", category = "audio", path = "audio/adpcm", extensions = { "adpcm", "ima" }, mime = { "audio/x-adpcm" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } }, load = function() return __include("audio/adpcm") end, }, { name = "adx", category = "audio", path = "audio/adx", extensions = { "adx" }, mime = { "audio/x-adx" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 }, load = function() return __include("audio/adx") end, }, { name = "aiff", category = "audio", path = "audio/aiff", extensions = { "aiff", "aif", "aifc", "afc" }, mime = { "audio/aiff", "audio/x-aiff" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, load = function() return __include("audio/aiff") end, }, { name = "ape", category = "audio", path = "audio/ape", extensions = { "ape" }, mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" }, caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } }, load = function() return __include("audio/ape") end, }, { name = "au", category = "audio", path = "audio/au", extensions = { "au", "snd" }, mime = { "audio/basic", "audio/x-au" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, load = function() return __include("audio/au") end, }, { name = "brstm", category = "audio", path = "audio/brstm", extensions = { "brstm", "bcstm", "bfstm" }, mime = { "audio/x-brstm" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" }, caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } }, load = function() return __include("audio/brstm") end, }, { name = "caf", category = "audio", path = "audio/caf", extensions = { "caf", "caff" }, mime = { "audio/x-caf" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" }, caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, load = function() return __include("audio/caf") end, }, { name = "flac", category = "audio", path = "audio/flac", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Flac/Frame", "codecs/audio/Flac/Encode" }, caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, load = function() return __include("audio/flac") end, }, { name = "m4a", category = "audio", path = "audio/m4a", extensions = { "m4a", "m4b", "m4r" }, mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream" }, caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, load = function() return __include("audio/m4a") end, }, { name = "mp3", category = "audio", path = "audio/mp3", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/Mpa/Header", "codecs/audio/Mpa/Core", "codecs/audio/Mpa/Encode3", "codecs/audio/Mpa/Encode2" }, caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 }, load = function() return __include("audio/mp3") end, }, { name = "mpc", category = "audio", path = "audio/mpc", extensions = { "mpc", "mp+", "mpp" }, mime = { "audio/x-musepack", "audio/musepack" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" }, caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true }, load = function() return __include("audio/mpc") end, }, { name = "opus", category = "audio", path = "audio/opus", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/entropy/RangeCoder/Decoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment", "codecs/audio/Opus/CeltEncoder", "codecs/audio/Opus/Decoder", "codecs/audio/Opus/Packet", "codecs/audio/Opus/Celt", "codecs/audio/Opus/Silk" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 }, load = function() return __include("audio/opus") end, }, { name = "qoa", category = "audio", path = "audio/qoa", extensions = { "qoa" }, mime = { "audio/qoa" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" }, caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 }, load = function() return __include("audio/qoa") end, }, { name = "tta", category = "audio", path = "audio/tta", extensions = { "tta" }, mime = { "audio/x-tta", "audio/tta" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" }, caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } }, load = function() return __include("audio/tta") end, }, { name = "vag", category = "audio", path = "audio/vag", extensions = { "vag" }, mime = { "audio/x-vag" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 }, load = function() return __include("audio/vag") end, }, { name = "voc", category = "audio", path = "audio/voc", extensions = { "voc" }, mime = { "audio/x-voc" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, load = function() return __include("audio/voc") end, }, { name = "vorbis", category = "audio", path = "audio/vorbis", extensions = { "ogg", "oga" }, mime = { "audio/ogg", "audio/vorbis" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Vorbis/Tables", "codecs/audio/Vorbis/Setup", "codecs/audio/Vorbis/Packet" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, load = function() return __include("audio/vorbis") end, }, { name = "wav", category = "audio", path = "audio/wav", extensions = { "wav", "wave", "rf64", "bw64" }, mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, load = function() return __include("audio/wav") end, }, { name = "wavpack", category = "audio", path = "audio/wavpack", extensions = { "wv" }, mime = { "audio/x-wavpack", "audio/wavpack" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" }, caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } }, load = function() return __include("audio/wavpack") end, }, { name = "avi", category = "video", path = "video/avi", extensions = { "avi" }, mime = { "video/x-msvideo", "video/avi" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, odml = true }, load = function() return __include("video/avi") end, }, { name = "fli", category = "video", path = "video/fli", extensions = { "fli", "flc", "flx" }, mime = { "video/x-fli", "video/fli", "video/x-flc" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" }, caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } }, load = function() return __include("video/fli") end, }, { name = "flv", category = "video", path = "video/flv", extensions = { "flv" }, mime = { "video/x-flv", "video/flv" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H263", "codecs/video/H264", "codecs/audio/Aac" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "flv1", "h264" }, audio = true, metadata = true }, load = function() return __include("video/flv") end, }, { name = "h264", category = "video", path = "video/h264", extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" }, mime = { "video/h264" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H264" }, caps = { decode = true, encode = true, streaming = true, video = { "h264" }, depths = { 8 } }, load = function() return __include("video/h264") end, }, { name = "mkv", category = "video", path = "video/mkv", extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo" }, audio = true, subtitles = true }, load = function() return __include("video/mkv") end, }, { name = "mp4", category = "video", path = "video/mp4", extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" }, mime = { "video/mp4", "video/quicktime", "video/3gpp" }, deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true }, load = function() return __include("video/mp4") end, }, { name = "mpegps", category = "video", path = "video/mpegps", extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, mime = { "video/mpeg" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true }, load = function() return __include("video/mpegps") end, }, { name = "mpegts", category = "video", path = "video/mpegts", extensions = { "ts", "m2ts", "mts", "tsv" }, mime = { "video/mp2t" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true }, load = function() return __include("video/mpegts") end, }, { name = "ogv", category = "video", path = "video/ogv", extensions = { "ogv", "ogg" }, mime = { "video/ogg" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, load = function() return __include("video/ogv") end, }, { name = "smk", category = "video", path = "video/smk", extensions = { "smk" }, mime = { "video/vnd.radgamettools.smacker" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, load = function() return __include("video/smk") end, }, { name = "y4m", category = "video", path = "video/y4m", extensions = { "y4m" }, mime = { "video/x-yuv4mpeg" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, video = { "rawvideo" }, depths = { 8, 10, 12, 16 } }, load = function() return __include("video/y4m") end, }, { name = "3ds", category = "model", path = "model/3ds", extensions = { "3ds" }, mime = { "application/x-3ds", "image/x-3ds" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Sampler" }, caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true }, load = function() return __include("model/3ds") end, }, { name = "3mf", category = "model", path = "model/3mf", extensions = { "3mf" }, mime = { "model/3mf" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "containers/Zip" }, caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true }, load = function() return __include("model/3mf") end, }, { name = "b3d", category = "model", path = "model/b3d", extensions = { "b3d" }, mime = { "model/x-b3d" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" }, caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true }, load = function() return __include("model/b3d") end, }, { name = "bsp", category = "model", path = "model/bsp", extensions = { "bsp" }, mime = { "model/x-bsp" }, deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, load = function() return __include("model/bsp") end, }, { name = "dae", category = "model", path = "model/dae", extensions = { "dae", "zae" }, mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Base64", "containers/Zip", "codecs/model/Mat4" }, caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true }, load = function() return __include("model/dae") end, }, { name = "fbx", category = "model", path = "model/fbx", extensions = { "fbx" }, mime = { "application/vnd.autodesk.fbx", "model/fbx" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "core/Base64", "codecs/model/Mat4" }, caps = { decode = true, encode = true, binary = true, ascii = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true }, load = function() return __include("model/fbx") end, }, { name = "gltf", category = "model", path = "model/gltf", extensions = { "gltf", "glb" }, mime = { "model/gltf+json", "model/gltf-binary" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff", "codecs/model/Draco" }, caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, draco = true }, load = function() return __include("model/gltf") end, }, { name = "iqm", category = "model", path = "model/iqm", extensions = { "iqm" }, mime = { "model/x-iqm" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" }, caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true }, load = function() return __include("model/iqm") end, }, { name = "ldraw", category = "model", path = "model/ldraw", extensions = { "ldr", "mpd", "dat" }, mime = { "application/x-ldraw", "application/x-multi-part-ldraw" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, caps = { decode = true, encode = false, materials = true, lines = true, instancing = true }, load = function() return __include("model/ldraw") end, }, { name = "lwo", category = "model", path = "model/lwo", extensions = { "lwo", "lxo" }, mime = { "image/x-lwo", "model/x-lwo" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" }, caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true }, load = function() return __include("model/lwo") end, }, { name = "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 = "proc", category = "model", path = "model/proc", extensions = { "proc" }, mime = { "model/x-doom3-proc" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/text/Lexer" }, caps = { decode = true, encode = false, portals = true }, load = function() return __include("model/proc") 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 = "udmf", category = "model", path = "model/udmf", extensions = { "udmf", "textmap" }, mime = { "text/x-udmf" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/DoomMap" }, caps = { decode = true, encode = false, maps = true }, load = function() return __include("model/udmf") end, }, { name = "usda", category = "model", path = "model/usda", extensions = { "usda", "usd", "usdz" }, mime = { "model/vnd.usda", "model/vnd.usdz+zip" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/model/Mat4" }, caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false }, load = function() return __include("model/usda") end, }, { name = "vox", category = "model", path = "model/vox", extensions = { "vox" }, mime = { "model/x-vox" }, deps = { "core/Err", "core/Bytes", "Types" }, caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true }, load = function() return __include("model/vox") end, }, { name = "vrml", category = "model", path = "model/vrml", extensions = { "wrl", "wrz", "vrml" }, mime = { "model/vrml", "x-world/x-vrml" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true }, load = function() return __include("model/vrml") end, }, { name = "x", category = "model", path = "model/x", extensions = { "x" }, mime = { "model/x-directx", "text/x-directx" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" }, caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true }, load = function() return __include("model/x") end, }, { name = "x3d", category = "model", path = "model/x3d", extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" }, mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true }, load = function() return __include("model/x3d") end, }, { name = "step", category = "cad", path = "cad/step", extensions = { "step", "stp", "p21" }, mime = { "model/step", "application/step", "application/p21" }, deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, load = function() return __include("cad/step") end, }, { name = "bdf", category = "font", path = "font/bdf", extensions = { "bdf" }, mime = { "application/x-font-bdf" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, caps = { decode = true, encode = true, bitmap = true }, load = function() return __include("font/bdf") end, }, { name = "bmfont", category = "font", path = "font/bmfont", extensions = { "fnt" }, mime = { "application/x-bmfont" }, deps = { "core/Err", "core/Bytes", "Types" }, caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" }, extraFiles = true }, load = function() return __include("font/bmfont") end, }, { name = "eot", category = "font", path = "font/eot", extensions = { "eot" }, mime = { "application/vnd.ms-fontobject" }, deps = { "core/Err", "core/Bytes", "codecs/text/Text", "codecs/font/TrueType" }, caps = { decode = true, encode = true, variants = { "1.0", "2.1", "2.2" } }, load = function() return __include("font/eot") end, }, { name = "fon", category = "font", path = "font/fon", extensions = { "fon", "fnt" }, mime = { "application/x-font-fnt" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/font/Bitmap" }, caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } }, load = function() return __include("font/fon") end, }, { name = "hershey", category = "font", path = "font/hershey", extensions = { "jhf" }, mime = { "application/x-hershey-font" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster" }, caps = { decode = true, encode = false, strokes = true }, load = function() return __include("font/hershey") end, }, { name = "pcf", category = "font", path = "font/pcf", extensions = { "pcf" }, mime = { "application/x-font-pcf" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, caps = { decode = true, encode = false, bitmap = true }, load = function() return __include("font/pcf") end, }, { name = "psf", category = "font", path = "font/psf", extensions = { "psf", "psfu" }, mime = { "application/x-font-linux-psf" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, caps = { decode = true, encode = true, bitmap = true, variants = { "psf1", "psf2" } }, load = function() return __include("font/psf") end, }, { name = "ttf", category = "font", path = "font/ttf", extensions = { "ttf", "otf", "ttc", "otc" }, mime = { "font/ttf", "font/otf", "font/collection" }, deps = { "core/Err", "core/Bytes", "codecs/font/TrueType" }, caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true }, load = function() return __include("font/ttf") end, }, { name = "type1", category = "font", path = "font/type1", extensions = { "pfb", "pfa", "t1" }, mime = { "application/x-font-type1" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" }, caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } }, load = function() return __include("font/type1") end, }, { name = "woff", category = "font", path = "font/woff", extensions = { "woff" }, mime = { "font/woff" }, deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/font/TrueType" }, caps = { decode = true, encode = false, outlines = { "truetype", "cff" } }, load = function() return __include("font/woff") end, }, { name = "woff2", category = "font", path = "font/woff2", extensions = { "woff2" }, mime = { "font/woff2" }, deps = { "core/Err", "core/Bytes", "codecs/font/TrueType", "codecs/compress/Brotli" }, caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, transforms = { "glyf", "loca", "hmtx" } }, load = function() return __include("font/woff2") end, }, { name = "7z", category = "archive", path = "archive/7z", extensions = { "7z" }, mime = { "application/x-7z-compressed" }, deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/compress/Lzma", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Zstd", "containers/Archive", "codecs/text/Text" }, caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false }, load = function() return __include("archive/7z") end, }, { name = "adf", category = "archive", path = "archive/adf", extensions = { "adf" }, mime = { "application/x-amiga-disk-format" }, deps = { "core/Err", "core/Bytes", "containers/Archive" }, caps = { decode = true, encode = false, variants = { "ofs", "ffs" } }, load = function() return __include("archive/adf") end, }, { name = "applesingle", category = "archive", path = "archive/applesingle", extensions = { "as", "applesingle", "appledouble" }, mime = { "application/applefile", "multipart/appledouble" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/MacFile" }, caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } }, load = function() return __include("archive/applesingle") end, }, { name = "ar", category = "archive", path = "archive/ar", extensions = { "a", "ar", "deb", "lib" }, mime = { "application/x-archive", "application/vnd.debian.binary-package" }, deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" }, caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true }, load = function() return __include("archive/ar") end, }, { name = "arj", category = "archive", path = "archive/arj", extensions = { "arj" }, mime = { "application/x-arj" }, deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Lzh", "containers/Archive" }, caps = { decode = true, encode = false, methods = { "store", "arj1", "arj2", "arj3", "arj4" } }, load = function() return __include("archive/arj") end, }, { name = "binhex", category = "archive", path = "archive/binhex", extensions = { "hqx", "hcx" }, mime = { "application/mac-binhex40" }, deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, caps = { decode = true, encode = true, forks = true }, load = function() return __include("archive/binhex") end, }, { name = "br", category = "archive", path = "archive/br", extensions = { "br" }, mime = { "application/x-brotli" }, deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" }, caps = { decode = true, encode = false, stream = true }, load = function() return __include("archive/br") end, }, { name = "bz2", category = "archive", path = "archive/bz2", extensions = { "bz2", "tbz2", "tbz" }, mime = { "application/x-bzip2" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" }, caps = { decode = true, encode = false, stream = true }, load = function() return __include("archive/bz2") end, }, { name = "cab", category = "archive", path = "archive/cab", extensions = { "cab" }, mime = { "application/vnd.ms-cab-compressed" }, deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" }, caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } }, load = function() return __include("archive/cab") end, }, { name = "cpio", category = "archive", path = "archive/cpio", extensions = { "cpio" }, mime = { "application/x-cpio" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" }, caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } }, load = function() return __include("archive/cpio") end, }, { name = "d64", category = "archive", path = "archive/d64", extensions = { "d64", "d71", "d81" }, mime = { "application/x-d64" }, deps = { "core/Err", "core/Bytes", "containers/Archive" }, caps = { decode = true, encode = true, variants = { "d64", "d71", "d81" } }, load = function() return __include("archive/d64") end, }, { name = "fat", category = "archive", path = "archive/fat", extensions = { "img", "ima", "vfd", "flp", "fat" }, mime = { "application/x-fat-image" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Fat" }, caps = { decode = true, encode = true, variants = { "fat12", "fat16", "fat32" } }, load = function() return __include("archive/fat") end, }, { name = "grp", category = "archive", path = "archive/grp", extensions = { "grp" }, mime = { "application/x-build-grp" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, caps = { decode = true, encode = true }, load = function() return __include("archive/grp") end, }, { name = "gzip", category = "archive", path = "archive/gzip", extensions = { "gz", "tgz", "gzip" }, mime = { "application/gzip" }, deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" }, caps = { decode = true, encode = true, stream = true }, load = function() return __include("archive/gzip") end, }, { name = "iso", category = "archive", path = "archive/iso", extensions = { "iso" }, mime = { "application/x-iso9660-image" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" }, caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } }, load = function() return __include("archive/iso") end, }, { name = "lha", category = "archive", path = "archive/lha", extensions = { "lzh", "lha", "lzs" }, mime = { "application/x-lzh-compressed" }, deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" }, caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } }, load = function() return __include("archive/lha") end, }, { name = "lz4", category = "archive", path = "archive/lz4", extensions = { "lz4", "tlz4" }, mime = { "application/x-lz4" }, deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" }, caps = { decode = true, encode = true, stream = true, legacy = true }, load = function() return __include("archive/lz4") end, }, { name = "macbinary", category = "archive", path = "archive/macbinary", extensions = { "bin", "macbin" }, mime = { "application/x-macbinary" }, deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, caps = { decode = true, encode = true, forks = true, variants = { "I", "II", "III" } }, load = function() return __include("archive/macbinary") end, }, { name = "mpq", category = "archive", path = "archive/mpq", extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" }, mime = { "application/x-mpq" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" }, caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true }, load = function() return __include("archive/mpq") end, }, { name = "pak", category = "archive", path = "archive/pak", extensions = { "pak", "sin" }, mime = { "application/x-pak" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, caps = { decode = true, encode = true, variants = { "quake", "sin" } }, load = function() return __include("archive/pak") end, }, { name = "rpm", category = "archive", path = "archive/rpm", extensions = { "rpm" }, mime = { "application/x-rpm" }, deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" }, caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } }, load = function() return __include("archive/rpm") end, }, { name = "tar", category = "archive", path = "archive/tar", extensions = { "tar" }, mime = { "application/x-tar" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" }, caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } }, load = function() return __include("archive/tar") end, }, { name = "uu", category = "archive", path = "archive/uu", extensions = { "uu", "uue", "xxe", "b64" }, mime = { "text/x-uuencode" }, deps = { "core/Err", "core/Bytes", "core/Base64", "containers/Archive" }, caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } }, load = function() return __include("archive/uu") end, }, { name = "vpk", category = "archive", path = "archive/vpk", extensions = { "vpk" }, mime = { "application/x-vpk" }, deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" }, caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true }, load = function() return __include("archive/vpk") end, }, { name = "vswap", category = "archive", path = "archive/vswap", extensions = { "wl6", "wl1", "sod", "sdm", "vswap" }, mime = { "application/x-wolf3d-vswap" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels" }, caps = { decode = true, encode = false, images = true, sounds = true }, load = function() return __include("archive/vswap") 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/DoomMap" }, caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } }, load = function() return __include("archive/wad") end, }, { name = "xz", category = "archive", path = "archive/xz", extensions = { "xz", "txz", "lzma" }, mime = { "application/x-xz", "application/x-lzma" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "containers/Archive" }, caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } }, load = function() return __include("archive/xz") end, }, { name = "yenc", category = "archive", path = "archive/yenc", extensions = { "yenc", "ync" }, mime = { "application/x-yenc" }, deps = { "core/Err", "core/Bytes", "core/Crc32", "containers/Archive" }, caps = { decode = true, encode = true, multipart = true }, load = function() return __include("archive/yenc") end, }, { name = "z", category = "archive", path = "archive/z", extensions = { "z", "taz", "tz" }, mime = { "application/x-compress" }, deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" }, caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } }, load = function() return __include("archive/z") end, }, { name = "zip", category = "archive", path = "archive/zip", extensions = { "zip", "wsz" }, mime = { "application/zip", "application/x-zip-compressed" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, caps = { decode = true, encode = true, methods = { "store", "deflate" }, zip64 = true }, load = function() return __include("archive/zip") end, }, { name = "zoo", category = "archive", path = "archive/zoo", extensions = { "zoo" }, mime = { "application/x-zoo" }, deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzw", "codecs/compress/Lzh", "containers/Archive" }, caps = { decode = true, encode = false, methods = { "store", "lzw", "lzh" } }, load = function() return __include("archive/zoo") end, }, { name = "zst", category = "archive", path = "archive/zst", extensions = { "zst", "tzst" }, mime = { "application/zstd" }, deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" }, caps = { decode = true, encode = false, stream = true }, load = function() return __include("archive/zst") end, }, { name = "cbor", category = "data", path = "data/cbor", extensions = { "cbor" }, mime = { "application/cbor", "application/cbor-seq" }, deps = { "core/Err", "core/Bytes", "Types" }, caps = { decode = true, encode = true, binary = true, ordered = true, tags = true }, load = function() return __include("data/cbor") end, }, { name = "csv", category = "data", path = "data/csv", extensions = { "csv", "tsv" }, mime = { "text/csv", "text/tab-separated-values" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, caps = { decode = true, encode = true, header = true }, load = function() return __include("data/csv") end, }, { name = "ini", category = "data", path = "data/ini", extensions = { "ini", "cfg", "conf", "inf", "desktop" }, mime = { "text/plain" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true }, load = function() return __include("data/ini") end, }, { name = "json", category = "data", path = "data/json", extensions = { "json", "jsonl", "ndjson", "geojson" }, mime = { "application/json", "application/x-ndjson" }, deps = { "core/Err", "core/Bytes", "codecs/text/Json", "core/Sniff" }, caps = { decode = true, encode = true, ordered = true, streaming = true }, load = function() return __include("data/json") end, }, { name = "msgpack", category = "data", path = "data/msgpack", extensions = { "msgpack", "mpk" }, mime = { "application/msgpack", "application/x-msgpack" }, deps = { "core/Err", "core/Bytes", "Types" }, caps = { decode = true, encode = true, binary = true, ordered = true }, load = function() return __include("data/msgpack") end, }, { name = "nbt", category = "data", path = "data/nbt", extensions = { "nbt", "dat", "mcstructure", "dat_old" }, mime = { "application/x-minecraft-nbt" }, deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" }, caps = { decode = true, encode = true, binary = true, ordered = true, typed = true }, load = function() return __include("data/nbt") end, }, { name = "plist", category = "data", path = "data/plist", extensions = { "plist" }, mime = { "application/x-plist", "application/x-bplist" }, deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Xml", "codecs/text/Json" }, caps = { decode = true, encode = true, binary = "read", ordered = true }, load = function() return __include("data/plist") end, }, { name = "snbt", category = "data", path = "data/snbt", extensions = { "snbt" }, mime = { "text/x-minecraft-snbt" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" }, caps = { decode = true, encode = true, ordered = true, typed = true }, load = function() return __include("data/snbt") end, }, { name = "toml", category = "data", path = "data/toml", extensions = { "toml" }, mime = { "application/toml" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "codecs/text/Text" }, caps = { decode = true, encode = true, ordered = true, dates = true }, load = function() return __include("data/toml") end, }, { name = "xml", category = "data", path = "data/xml", extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, mime = { "application/xml", "text/xml" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Sniff" }, caps = { decode = true, encode = true, namespaces = true, streaming = true }, load = function() return __include("data/xml") end, }, { name = "yaml", category = "data", path = "data/yaml", extensions = { "yaml", "yml" }, mime = { "application/yaml", "application/x-yaml", "text/yaml" }, deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Text" }, caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true }, load = function() return __include("data/yaml") end, }, { name = "gamemaps", category = "vector", path = "vector/gamemaps", extensions = { "wl6", "wl1", "sod", "sdm" }, mime = { "application/x-wolf3d-gamemaps" }, deps = { "core/Err", "core/Bytes", "core/Input", "Types" }, caps = { decode = true, encode = false, tilemap = true }, load = function() return __include("vector/gamemaps") end, }, { name = "svg", category = "vector", path = "vector/svg", extensions = { "svg" }, mime = { "image/svg+xml" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "codecs/image/Raster", "codecs/image/Blend", "core/Sniff" }, caps = { decode = true, encode = true, rasterize = true, text = false }, load = function() return __include("vector/svg") end, }, { name = "tiled", category = "vector", path = "vector/tiled", extensions = { "tmx", "tmj", "tsx", "tsj" }, mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" }, deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/text/Xml", "codecs/text/Json", "codecs/compress/Deflate", "core/Sniff" }, caps = { decode = true, encode = true, tilesets = true, infinite = true }, load = function() return __include("vector/tiled") end, }, { name = "aseprite", category = "layered", path = "layered/aseprite", extensions = { "aseprite", "ase" }, mime = { "image/x-aseprite" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate" }, caps = { decode = true, encode = true, layers = true, groups = true, animation = true, depths = { 8, 16, 32 } }, load = function() return __include("layered/aseprite") end, }, { name = "ora", category = "layered", path = "layered/ora", extensions = { "ora" }, mime = { "image/openraster" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" }, caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } }, load = function() return __include("layered/ora") end, }, { name = "psd", category = "layered", path = "layered/psd", extensions = { "psd", "psb" }, mime = { "image/vnd.adobe.photoshop" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Blend", "codecs/compress/Deflate", "codecs/compress/PackBits", "codecs/text/Text" }, caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } }, load = function() return __include("layered/psd") end, }, { name = "ass", category = "subtitle", path = "subtitle/ass", extensions = { "ass", "ssa" }, mime = { "text/x-ssa", "text/x-ass" }, deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = true }, load = function() return __include("subtitle/ass") end, }, { name = "srt", category = "subtitle", path = "subtitle/srt", extensions = { "srt" }, mime = { "application/x-subrip", "text/srt" }, deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = false }, load = function() return __include("subtitle/srt") end, }, { name = "vtt", category = "subtitle", path = "subtitle/vtt", extensions = { "vtt", "webvtt" }, mime = { "text/vtt" }, deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = true }, load = function() return __include("subtitle/vtt") end, }, { name = "669", category = "music", path = "music/669", extensions = { "669" }, mime = { "audio/x-669" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, caps = { decode = true, encode = false, render = true, channels = { 8, 8 } }, load = function() return __include("music/669") end, }, { name = "ahx", category = "music", path = "music/ahx", extensions = { "ahx", "thx" }, mime = { "audio/x-ahx" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, caps = { decode = true, encode = false, render = true, channels = { 4, 4 }, subsongs = true }, load = function() return __include("music/ahx") end, }, { name = "far", category = "music", path = "music/far", extensions = { "far" }, mime = { "audio/x-far" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, caps = { decode = true, encode = false, render = true, channels = { 16, 16 } }, load = function() return __include("music/far") end, }, { name = "hmp", category = "music", path = "music/hmp", extensions = { "hmp", "hmi" }, mime = { "audio/x-hmp" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, caps = { decode = true, encode = false, render = true, hmi = true }, load = function() return __include("music/hmp") end, }, { name = "hvl", category = "music", path = "music/hvl", extensions = { "hvl" }, mime = { "audio/x-hvl" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, caps = { decode = true, encode = false, render = true, channels = { 4, 16 }, subsongs = true }, load = function() return __include("music/hvl") end, }, { name = "it", category = "music", path = "music/it", extensions = { "it" }, mime = { "audio/it", "audio/x-it" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, load = function() return __include("music/it") end, }, { name = "med", category = "music", path = "music/med", extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" }, mime = { "audio/x-med" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, caps = { decode = true, encode = false, render = true, channels = { 1, 64 } }, load = function() return __include("music/med") end, }, { name = "midi", category = "music", path = "music/midi", extensions = { "mid", "midi", "smf", "kar", "rmi" }, mime = { "audio/midi", "audio/x-midi" }, deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" }, caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, load = function() return __include("music/midi") end, }, { name = "mod", category = "music", path = "music/mod", extensions = { "mod", "m15", "stk", "nst" }, mime = { "audio/x-mod", "audio/mod" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, load = function() return __include("music/mod") end, }, { name = "mtm", category = "music", path = "music/mtm", extensions = { "mtm" }, mime = { "audio/x-mtm" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, load = function() return __include("music/mtm") end, }, { name = "mus", category = "music", path = "music/mus", extensions = { "mus" }, mime = { "audio/x-mus" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, caps = { decode = true, encode = false, render = true }, load = function() return __include("music/mus") end, }, { name = "okt", category = "music", path = "music/okt", extensions = { "okt", "okta" }, mime = { "audio/x-okt" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, caps = { decode = true, encode = false, render = true, channels = { 4, 8 } }, load = function() return __include("music/okt") end, }, { name = "ptm", category = "music", path = "music/ptm", extensions = { "ptm" }, mime = { "audio/x-ptm" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, load = function() return __include("music/ptm") end, }, { name = "s3m", category = "music", path = "music/s3m", extensions = { "s3m" }, mime = { "audio/s3m", "audio/x-s3m" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, load = function() return __include("music/s3m") end, }, { name = "sf2", category = "music", path = "music/sf2", extensions = { "sf2" }, mime = { "audio/x-soundfont" }, deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont" }, caps = { decode = true, encode = false, sm24 = true, sf3 = false }, load = function() return __include("music/sf2") end, }, { name = "stm", category = "music", path = "music/stm", extensions = { "stm" }, mime = { "audio/x-stm" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, caps = { decode = true, encode = false, render = true, channels = { 4, 4 } }, load = function() return __include("music/stm") end, }, { name = "ult", category = "music", path = "music/ult", extensions = { "ult" }, mime = { "audio/x-ult" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, load = function() return __include("music/ult") end, }, { name = "umx", category = "music", path = "music/umx", extensions = { "umx" }, mime = { "audio/x-umx" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, caps = { decode = true, encode = false, render = true, container = true }, load = function() return __include("music/umx") end, }, { name = "xm", category = "music", path = "music/xm", extensions = { "xm" }, mime = { "audio/xm", "audio/x-xm" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" }, caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, load = function() return __include("music/xm") end, }, { name = "xmi", category = "music", path = "music/xmi", extensions = { "xmi", "xmidi" }, mime = { "audio/x-xmidi" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" }, caps = { decode = true, encode = false, render = true, songs = true }, load = function() return __include("music/xmi") end, }, { name = "m3u", category = "playlist", path = "playlist/m3u", extensions = { "m3u", "m3u8" }, mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, caps = { decode = true, encode = true, hls = true }, load = function() return __include("playlist/m3u") end, }, { name = "pls", category = "playlist", path = "playlist/pls", extensions = { "pls" }, mime = { "audio/x-scpls", "audio/scpls" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, caps = { decode = true, encode = true }, load = function() return __include("playlist/pls") end, }, { name = "xspf", category = "playlist", path = "playlist/xspf", extensions = { "xspf" }, mime = { "application/xspf+xml" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Xml" }, caps = { decode = true, encode = true }, load = function() return __include("playlist/xspf") end, }, } return list end __FILES["Types"] = function() -- Types: the standard value types each category decodes to and encodes from, plus small constructors. Every -- top-level value has a `kind` ("image", "audio", "scene", ...). Shared enums are plain strings; buffers are tightly -- packed, rows top to bottom, channels interleaved. local Err = __include("core/Err") local Types = {} type Err = Err.Err -- pixel formats: bytes per pixel. rgba8 is the default every decoder produces unless opts.native asks to keep the -- source layout. yuv420p: Y plane (w*h) then U and V planes (ceil(w/2) * ceil(h/2) each). type PixelFormat = "rgba8" | "rgba16" | "rgbaf32" | "rgb8" | "gray8" | "gray16" | "graya8" | "alpha8" | "yuv420p" local BPP: { [string]: number } = { rgba8 = 4, rgba16 = 8, rgbaf32 = 16, rgb8 = 3, gray8 = 1, gray16 = 2, graya8 = 2, alpha8 = 1, } Types.BPP = table.freeze(BPP) :: { [string]: number } type ImageMeta = { colorSpace: string?, -- "srgb" (default), "linear", "display-p3", ... gamma: number?, icc: buffer?, -- the raw ICC profile exif: buffer?, -- the raw EXIF block (TIFF header onwards) dpi: { x: number, y: number }?, palette: { { number } }?, -- { r, g, b, a } 0..255 per entry, for palette sources text: { [string]: string }?, -- tEXt / comments source: { format: string, bitDepth: number?, colorType: string?, [string]: any }?, [string]: any, } -- one frame of an animation (GIF, APNG, WebP): the image is the frame's own rectangle, composited at x, y type Frame = { image: Image, delay: number, -- seconds x: number, y: number, dispose: "none" | "background" | "previous", blend: "source" | "over", } type Image = { kind: "image", width: number, height: number, format: PixelFormat, pixels: buffer, frames: { Frame }?, -- animations: frame 1 is also width x height pixels (the composited first frame) loops: number, -- play count: how many times the animation plays, 0 = forever (GIF stores repeats: plays - 1; APNG -- num_plays and the WebP ANIM loop count are play counts) meta: ImageMeta, } local Image = {} function Image.new(width: number, height: number, format: PixelFormat?): Image local f: PixelFormat = format or "rgba8" local size if f == "yuv420p" then local cw, ch = (width + 1) // 2, (height + 1) // 2 size = width * height + 2 * cw * ch else size = width * height * (BPP[f] or 4) end return { kind = "image", width = width, height = height, format = f, pixels = buffer.create(size), frames = nil, loops = 0, meta = {}, } end function Image.bpp(format: string): number? return BPP[format] end Types.Image = Image type Tags = { [string]: string } -- title, artist, album, date, genre, track, comment, ... type Decoder = { sampleRate: number, channels: number, frames: number, -- total sample frames (estimate for VBR streams without an index), 0 = unknown duration: number, -- seconds bitrate: number, -- bits per second (average) tags: Tags, -- read: interleaved f32, frames read (0 at the end); out is reused when big enough read: (self: any, n: number, out: buffer?) -> (buffer, number), seek: (self: any, seconds: number) -> (), position: (self: any) -> number, -- seconds } type Audio = { kind: "audio", sampleRate: number, channels: number, frames: number, samples: buffer, -- interleaved f32, frames * channels * 4 bytes tags: Tags, meta: { source: { format: string, [string]: any }?, [string]: any }, } local Audio = {} function Audio.new(sampleRate: number, channels: number, frames: number): Audio return { kind = "audio", sampleRate = sampleRate, channels = channels, frames = frames, samples = buffer.create(frames * channels * 4), tags = {}, meta = {}, } end Types.Audio = Audio type Module = { kind: "music", title: string, format: string, -- "mod", "s3m", "xm", "it" (codecs/audio/Tracker); "ahx", "hvl" (codecs/audio/Hively, own render) channels: number, patterns: { any }, order: { number }, instruments: { any }, samples: { any }, render: (self: any, opts: any?) -> Decoder, -- every music file is also audio meta: { [string]: any }, } type MidiEvent = { tick: number, type: string, channel: number?, data: { number }?, meta: any? } type Midi = { kind: "midi", format: number, -- SMF 0 / 1 / 2 division: number, -- ticks per quarter note (or SMPTE, negative) tracks: { { events: { MidiEvent }, name: string? } }, meta: { [string]: any }, render: ((self: any, opts: any?) -> Decoder)?, -- set by music/midi decode: the SoundFont synth as an audio Decoder } local Midi = {} function Midi.new(division: number?): Midi return { kind = "midi", format = 1, division = division or 480, tracks = {}, meta = {} } end Types.Midi = Midi -- Times: Packet pts / dts / duration are integer ticks of the track's timescale (exact, for remuxing); VideoFrame pts -- / duration and every `duration` / `seek` argument are seconds. type Track = { id: number, -- the container's track number (Matroska TrackNumber, AVI stream index + 1, TS PID, ...) kind: "video" | "audio" | "subtitle" | "data", codec: string, -- our codec id: "vp8", "mjpeg", "mpeg1", "h264", "rawvideo"; "pcm_s16le", "mp3", "opus", "vorbis", ... codecTag: string?, -- the container's own id ("V_VP8", "MJPG", stream_type "0x01", "avc1", ...) timescale: number, -- ticks per second for pts / dts / duration duration: number?, -- seconds default: boolean?, language: string?, name: string?, -- video width: number?, height: number?, frameRate: number?, -- frames per second (nominal; 0 / nil when unknown) pixelFormat: string?, -- raw video: "yuv420p", "rgb24", "bgr24", ... -- audio sampleRate: number?, channels: number?, bitsPerSample: number?, codecDelay: number?, -- seconds of decoder output to drop at the start (encoder priming: Matroska CodecDelay, the -- first edit's media time of an MP4 audio track) playDuration: number?, -- seconds to play after the codec delay (an MP4 edit list's length: the end padding cut) config: buffer?, -- codec configuration (CodecPrivate, avcC, OpusHead, Vorbis headers, AVI strf extra, ...) [string]: any, } type Packet = { track: number, -- Track.id pts: number, -- presentation time, ticks dts: number?, -- decode time, ticks (nil = pts) duration: number?, -- ticks keyframe: boolean, data: buffer, -- the packet's bytes (its own buffer) } type Demuxer = { kind: "demuxer", format: string, -- the container format name tracks: { Track }, duration: number, -- seconds (0 = unknown) startTime: number, -- seconds: the first video / audio packet's presentation time (VideoFrame times count from it) meta: { [string]: any }, -- title, tags, ... packets: (self: any, track: number?) -> () -> Packet?, read: (self: any, track: number?) -> Packet?, -- seek: every track to its last keyframe at or before the time seek: (self: any, seconds: number) -> (), track: (self: any, kind: string) -> Track?, -- the first (default) track of a kind } type VideoFrame = { image: Image, -- yuv420p (the codecs' native output) or rgba8 (opts.rgba = true, MJPEG without yuv, frames-backed) pts: number, -- seconds from the start of the stream (the demuxer's startTime) duration: number, -- seconds keyframe: boolean?, index: number, -- 1-based, in output order } type VideoDecoder = { kind: "video", format: string, -- the container format name ("mkv", "avi", "gif", ...) codec: string, -- the video codec id ("vp8", "mjpeg", "frames" for animated images) width: number, height: number, frameRate: number, -- frames per second (nominal) frames: number, -- frame count when known (0 = unknown) duration: number, -- seconds track: Track?, -- the video track decoded nextFrame: (self: any) -> (VideoFrame?, Err?), -- nil, nil at the end toRGBA: (self: any, frame: VideoFrame | Image) -> Image, -- an rgba8 Image (the frame's own image if already rgba8) seek: (self: any, seconds: number) -> (), -- the next frame is the first at or after the time (decoded from the keyframe before it) reset: (self: any) -> (), -- back to the start audio: Decoder?, -- the first audio track, decoded (nil if none or its codec is unavailable: see audioError) audioError: Err?, demuxer: Demuxer?, -- nil for frames-backed videos (animated images) meta: { [string]: any }, } -- a codec's decoder instance (codecs/video/Video registry entries create them): packets in, pictures out type VideoCodecDecoder = { decode: (self: any, packet: Packet) -> Err?, -- feed one packet (decode order) receive: (self: any) -> (Image?, number?, boolean?), -- the next picture, the pts (ticks) it carries, keyframe | nil flush: (self: any) -> (), -- end of stream: pictures held for reordering become available to receive() reset: (self: any) -> (), -- after a seek: drop references / held pictures } -- Indices are 1-based everywhere (node, mesh, material, texture, ...). Accessor data is tightly packed (no stride, no -- padding, sparse accessors already applied). unorm / snorm types are glTF's normalized integers (value / 255, -- max(value / 127, -1), ...). Positions are in scene units (meta.unit = metres per unit when known), meta.up is the -- source's up axis ("y" for glTF / OBJ, "z" for STL / VOX / most CAD) - no format rotates the data on load. type Accessor = { data: buffer, -- tightly packed, little endian type: "f32" | "f64" | "u8" | "u16" | "u32" | "i8" | "i16" | "i32" | "unorm8" | "unorm16" | "snorm8" | "snorm16", components: number, -- 1 (SCALAR) .. 4 (VEC4), 4 (MAT2), 9 (MAT3), 16 (MAT4) count: number, matrix: boolean?, -- components 4 / 9 / 16 are MAT2 / MAT3 / MAT4 (glTF), not VEC4 name: string?, } type Primitive = { attributes: { [string]: Accessor }, -- POSITION, NORMAL, TANGENT, TEXCOORD_n, COLOR_n, JOINTS_n, WEIGHTS_n; custom -- attributes start with "_" (glTF convention: PLY extra vertex properties, ...) indices: Accessor?, -- "polygons": faces (u32, one size per face) splits indices into n-gons (OBJ / PLY / OFF with triangulate = false; -- MeshOps.triangulate turns them into triangles) mode: "triangles" | "lines" | "points" | "triangle_strip" | "triangle_fan" | "line_strip" | "line_loop" | "polygons", faces: Accessor?, material: number?, -- index into scene.materials (1-based) targets: { { [string]: Accessor } }?, -- morph targets (POSITION / NORMAL / TANGENT deltas) extras: { [string]: any }?, } type Mesh = { name: string?, primitives: { Primitive }, weights: { number }?, extras: { [string]: any }? } type Sampler = { wrapS: ("repeat" | "clamp" | "mirror")?, -- default "repeat" wrapT: ("repeat" | "clamp" | "mirror")?, filter: ("linear" | "nearest")?, -- magnification minFilter: string?, -- "nearest" | "linear" | "nearest_mipmap_nearest" | ... (glTF names, lower case) } type Texture = { name: string?, image: Image?, -- decoded (F.model.loadTextures or the caller), never by a model format data: buffer?, -- the encoded image bytes (embedded / GLB / data: URI / resolved external file) mime: string?, -- "image/png", "image/jpeg", "image/webp", "image/ktx2", ... uri: string?, -- the external file name (relative to the model) when the data was not available or not embedded sampler: Sampler?, extras: { [string]: any }?, } type TextureRef = { texture: number, -- index into scene.textures (1-based) texCoord: number?, -- TEXCOORD_n set (default 0) scale: number?, -- normalTexture scale strength: number?, -- occlusionTexture strength -- KHR_texture_transform (texCoord overrides the ref's texCoord) transform: { offset: { number }?, scale: { number }?, rotation: number?, texCoord: number? }?, } type Material = { name: string?, baseColor: { number }, -- r, g, b, a linear 0..1 baseColorTexture: TextureRef?, metallic: number, roughness: number, metallicRoughnessTexture: TextureRef?, normalTexture: TextureRef?, occlusionTexture: TextureRef?, emissive: { number }, emissiveTexture: TextureRef?, alphaMode: "opaque" | "mask" | "blend", alphaCutoff: number, doubleSided: boolean, -- glTF material extensions by name (KHR_materials_emissive_strength = { emissiveStrength = 5 }, KHR_materials_unlit -- = {}, ...), their fields as in glTF except textureInfo objects, which are TextureRefs extensions: { [string]: any }?, extras: { [string]: any }?, -- classic Phong (OBJ / FBX): ambient, diffuse, specular, shininess, ... } type Node = { name: string?, children: { number }, -- node indices (1-based) mesh: number?, camera: number?, light: number?, skin: number?, voxels: number?, -- index into scene.voxels (MagicaVoxel shapes; MeshOps.meshVoxels gives them meshes) translation: { number }?, -- TRS, or matrix (column-major 4x4), not both rotation: { number }?, -- quaternion x, y, z, w scale: { number }?, matrix: { number }?, weights: { number }?, -- morph target weights extras: { [string]: any }?, } type Camera = { name: string?, type: "perspective" | "orthographic", yfov: number?, aspect: number?, xmag: number?, ymag: number?, znear: number, zfar: number? } type Light = { name: string?, type: "directional" | "point" | "spot", color: { number }, intensity: number, range: number?, innerCone: number?, outerCone: number? } type Skin = { name: string?, joints: { number }, inverseBindMatrices: Accessor?, skeleton: number? } type Channel = { node: number, path: "translation" | "rotation" | "scale" | "weights", input: Accessor, output: Accessor, interpolation: "LINEAR" | "STEP" | "CUBICSPLINE" } type Animation = { name: string?, channels: { Channel } } -- a voxel grid (MagicaVoxel): one byte per cell, 0 = empty, 1..255 = palette index type VoxelMaterial = { type: string, [string]: any } -- "diffuse" | "metal" | "glass" | "emit" | "blend" | "media" | ..., MATL properties (numbers when numeric) type Voxels = { kind: "voxels", name: string?, size: { number }, -- x, y, z cells data: buffer, -- size x * y * z bytes, cell (x, y, z) at x + sx * (y + sy * z) palette: { { number } }, -- palette[i] = { r, g, b, a } 0..255 (sRGB) for i = 1 .. 255 (shared between a file's models) materials: { [number]: VoxelMaterial }?, -- by palette index -- block grids (Minecraft schematics / regions): the exact block state of every cell, data / palette being its -- colour view (block colours from a default table) blocks: VoxelBlocks?, -- true-colour grids (Qubicle): the exact 32-bit colour of every cell as r, g, b, a bytes (u32 little-endian, -- a = 0 empty), data / palette being an indexed view of it colors: buffer?, } type VoxelBlocks = { palette: { string }, -- block states ("minecraft:oak_stairs[facing=east,half=bottom]"), palette[1] is index 0 data: buffer, -- u16 little-endian per cell (same cell order as Voxels.data): 0-based index into palette blockEntities: { any }?, -- the format's block entity records (NBT compounds; positions relative to the grid) entities: { any }?, -- entity records (NBT compounds) } local Voxels = {} function Voxels.new(sx: number, sy: number, sz: number, palette: { { number } }?): Voxels local pal = palette if not pal then local p = table.create(255) for i = 1, 255 do p[i] = { i, i, i, 255 } end pal = p end return { kind = "voxels", size = { sx, sy, sz }, data = buffer.create(sx * sy * sz), palette = pal :: { { number } }, materials = nil } end function Voxels.get(v: Voxels, x: number, y: number, z: number): number return buffer.readu8(v.data, x + v.size[1] * (y + v.size[2] * z)) end function Voxels.set(v: Voxels, x: number, y: number, z: number, index: number) buffer.writeu8(v.data, x + v.size[1] * (y + v.size[2] * z), index) end Types.Voxels = Voxels type Scene = { kind: "scene", nodes: { Node }, roots: { number }, -- top-level node indices meshes: { Mesh }, materials: { Material }, textures: { Texture }, cameras: { Camera }, lights: { Light }, skins: { Skin }, animations: { Animation }, voxels: { Voxels }?, -- voxel grids (VOX), referenced by node.voxels meta: { up: "y" | "z"?, unit: number?, source: { format: string, [string]: any }?, [string]: any }, } local Scene = {} function Scene.new(): Scene return { kind = "scene", nodes = {}, roots = {}, meshes = {}, materials = {}, textures = {}, cameras = {}, lights = {}, skins = {}, animations = {}, voxels = nil, meta = {}, } end local COMPONENT_SIZE: { [string]: number } = { f32 = 4, f64 = 8, u8 = 1, u16 = 2, u32 = 4, i8 = 1, i16 = 2, i32 = 4, unorm8 = 1, unorm16 = 2, snorm8 = 1, snorm16 = 2, } Types.COMPONENT_SIZE = table.freeze(COMPONENT_SIZE) :: { [string]: number } function Scene.accessor(data: buffer?, type: any, components: number, count: number): Accessor local d = data or buffer.create(count * components * (COMPONENT_SIZE[type] or 4)) return { data = d, type = type, components = components, count = count } end function Scene.material(name: string?): Material return { name = name, baseColor = { 1, 1, 1, 1 }, metallic = 1, roughness = 1, emissive = { 0, 0, 0 }, alphaMode = "opaque", alphaCutoff = 0.5, doubleSided = false, } end function Scene.fromPrimitive(prim: Primitive, name: string?): Scene local s = Scene.new() s.meshes[1] = { name = name, primitives = { prim } } s.nodes[1] = { name = name, children = {}, mesh = 1 } s.roots[1] = 1 return s end Types.Scene = Scene function Scene.reader(acc: Accessor): ((i: number, c: number) -> number)? local d, n, t = acc.data, acc.components, acc.type local size = COMPONENT_SIZE[t] if not size or type(d) ~= "buffer" then return nil end local stride = n * size local rb = buffer if t == "f32" then local f = rb.readf32 return function(i: number, c: number): number return f(d, i * stride + c * 4) end elseif t == "f64" then local f = rb.readf64 return function(i: number, c: number): number return f(d, i * stride + c * 8) end elseif t == "u8" or t == "unorm8" then local f, k = rb.readu8, if t == "unorm8" then 1 / 255 else 1 return function(i: number, c: number): number return f(d, i * stride + c) * k end elseif t == "u16" or t == "unorm16" then local f, k = rb.readu16, if t == "unorm16" then 1 / 65535 else 1 return function(i: number, c: number): number return f(d, i * stride + c * 2) * k end elseif t == "u32" then local f = rb.readu32 return function(i: number, c: number): number return f(d, i * stride + c * 4) end elseif t == "i8" then local f = rb.readi8 return function(i: number, c: number): number return f(d, i * stride + c) end elseif t == "snorm8" then local f = rb.readi8 return function(i: number, c: number): number return math.max(f(d, i * stride + c) / 127, -1) end elseif t == "i16" then local f = rb.readi16 return function(i: number, c: number): number return f(d, i * stride + c * 2) end elseif t == "snorm16" then local f = rb.readi16 return function(i: number, c: number): number return math.max(f(d, i * stride + c * 2) / 32767, -1) end elseif t == "i32" then local f = rb.readi32 return function(i: number, c: number): number return f(d, i * stride + c * 4) end end return nil end local IDENTITY = table.freeze({ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }) Scene.IDENTITY = IDENTITY function Scene.mul(a: { number }, b: { number }): { number } local m = table.create(16, 0) for col = 0, 3 do for row = 0, 3 do local s = 0 for k = 0, 3 do s += a[k * 4 + row + 1] * b[col * 4 + k + 1] end m[col * 4 + row + 1] = s end end return m end function Scene.nodeMatrix(node: Node): { number } if node.matrix and #node.matrix == 16 then return node.matrix end local t, r, sc = node.translation, node.rotation, node.scale if not t and not r and not sc then return IDENTITY end local tx, ty, tz = 0, 0, 0 if t then tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0 end local x, y, z, w = 0, 0, 0, 1 if r then x, y, z, w = r[1] or 0, r[2] or 0, r[3] or 0, r[4] or 1 end local sx, sy, sz = 1, 1, 1 if sc then sx, sy, sz = sc[1] or 1, sc[2] or 1, sc[3] or 1 end local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z return { (1 - 2 * (yy + zz)) * sx, (2 * (xy + wz)) * sx, (2 * (xz - wy)) * sx, 0, (2 * (xy - wz)) * sy, (1 - 2 * (xx + zz)) * sy, (2 * (yz + wx)) * sy, 0, (2 * (xz + wy)) * sz, (2 * (yz - wx)) * sz, (1 - 2 * (xx + yy)) * sz, 0, tx, ty, tz, 1, } end type Placed = { primitive: Primitive, matrix: { number }, node: number, mesh: number } function Scene.flatten(scene: Scene): { Placed } local out: { Placed } = {} local nodes = scene.nodes or {} local roots = scene.roots if not roots or #roots == 0 then local child = {} for _, n in nodes do for _, c in n.children or {} do child[c] = true end end roots = {} for i in nodes do if not child[i] then table.insert(roots, i) end end end local seen: { [number]: boolean } = {} local function visit(i: number, parent: { number }) local node = nodes[i] if not node or seen[i] then return end seen[i] = true local m = Scene.nodeMatrix(node) local world = if parent == IDENTITY then m elseif m == IDENTITY then parent else Scene.mul(parent, m) local mesh = node.mesh and scene.meshes[node.mesh] if mesh then for _, p in mesh.primitives do table.insert(out, { primitive = p, matrix = world, node = i, mesh = node.mesh :: number }) end end for _, c in node.children or {} do visit(c, world) end end for _, r in roots do visit(r, IDENTITY) end return out end -- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Rosetta.plugins.brep) -- complex (external mapping) instances: type = "COMPLEX", args = {}, parts = { { type, args } } in file order; -- section = the DATA section index when a file has more than one (edition 3) type StepEntity = { id: number, type: string, args: { any }, parts: { { type: string, args: { any } } }?, section: number? } type Cad = { kind: "cad", schema: string, -- "AP203", "AP214", "AP242", ... header: { [string]: any }, entities: { [number]: StepEntity }, meta: { [string]: any }, } type Font = { kind: "font", info: { family: string?, style: string?, fullName: string?, [string]: any }, unitsPerEm: number, ascent: number, descent: number, lineGap: number, glyphIndex: (self: any, codepoint: number) -> number, -- 0 = .notdef advance: (self: any, glyph: number) -> number, -- font units kern: (self: any, a: number, b: number) -> number, outline: (self: any, glyph: number) -> { { op: string, [number]: number } }?, -- moveTo / lineTo / quadTo / cubicTo rasterize: (self: any, glyph: number, px: number) -> Image?, -- alpha8 pages: { Image }?, -- bitmap fonts (BMFont) bitmap: BitmapStrike?, -- bitmap fonts with per-glyph bitmaps (BDF, PCF, PSF, FON): codecs/font/Bitmap meta: { [string]: any }, } -- one bitmap glyph: a 1-bit (or grey) image in pixels with y down, placed relative to the pen on the baseline type BitmapGlyph = { codepoint: number?, -- Unicode (nil for unencoded glyphs) name: string?, -- glyph name (BDF STARTCHAR, PCF glyph names, PostScript names) width: number, -- bitmap width / height in pixels height: number, left: number, -- x of the bitmap's left column relative to the pen top: number, -- y of the bitmap's top row above the baseline (BDF: BBXoff + BBh) advance: number, -- pen advance in pixels pixels: buffer, -- u8 per pixel (width * height, rows top down): 0 = off, 255 = on (grey fonts use 1..254) } type BitmapStrike = { size: number, -- pixel size (em height in pixels) ascent: number, -- pixels above the baseline descent: number, -- pixels below the baseline (positive) glyphs: { BitmapGlyph }, -- glyph index i + 1 is font glyph i (glyph 0 = the default / .notdef glyph) default: number?, -- glyph index (0-based) used for unmapped code points map: { [number]: number }?, -- extra code point -> glyph index (0-based) mappings (several code points on one glyph) } type ArchiveEntry = { name: string, size: number, compressedSize: number?, method: string?, mtime: number?, dir: boolean } type Archive = { kind: "archive", format: string, list: (self: any) -> { ArchiveEntry }, read: (self: any, name: string) -> (buffer?, Err?), add: (self: any, name: string, data: buffer | string, opts: any?) -> (), write: (self: any, opts: any?) -> (buffer?, Err?), meta: { [string]: any }, } -- data formats decode to plain Luau values; JSON null / YAML ~ / CBOR null is this sentinel (nil cannot sit in a -- table). XML decodes to XmlNode trees. Byte strings (msgpack bin, CBOR bytes, plist data) are buffers. local nullMeta = { __tostring = function() return "null" end } Types.null = table.freeze(setmetatable({}, nullMeta)) -- Objects (maps) whose key order matters, and empty objects (which would otherwise read back as empty arrays), carry -- an "object" metatable with their key order. Decoders mark empty objects always and every object when asked -- (opts.ordered); encoders write an object's keys in that order (keys added later, or plain tables: sorted). local OBJECT = { __object = true } local objectMeta: { [any]: { any } } = setmetatable({}, { __mode = "k" }) :: any -- object -> its key order function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any } local o: { [any]: any } = t or {} if getmetatable(o) == nil then setmetatable(o, OBJECT) end objectMeta[o] = keys or {} return o end function Types.isObject(v: any): boolean return type(v) == "table" and objectMeta[v] ~= nil end function Types.set(o: { [any]: any }, k: any, v: any) local order = objectMeta[o] if order and o[k] == nil and v ~= nil then table.insert(order, k) end o[k] = v end local function keyLess(a: any, b: any): boolean local ta, tb = type(a), type(b) if ta ~= tb then return ta < tb end if ta == "number" or ta == "string" then return a < b end return tostring(a) < tostring(b) end Types.keyLess = keyLess function Types.isArray(t: { [any]: any }, emptyIsMap: boolean?): boolean if Types.isObject(t) then return false end local n = #t if n == 0 then return next(t) == nil and not emptyIsMap end if next(t, n) ~= nil then return false end local c = 0 for _ in next, t do c += 1 end return c == n end function Types.keys(t: { [any]: any }): { any } local order = objectMeta[t] local out, seen = {}, {} if order then for _, k in order do if t[k] ~= nil and not seen[k] then seen[k] = true table.insert(out, k) end end end local rest = {} for k in next, t do if not seen[k] then table.insert(rest, k) end end if #rest > 0 then table.sort(rest, keyLess) table.move(rest, 1, #rest, #out + 1, out) end return out end -- Dates and times (TOML datetimes, plist , CBOR tags 0 / 1, msgpack timestamps). Fields present depend on the -- kind: "datetime" (with offset: an instant), "datetime-local", "date-local", "time-local". offset is in minutes -- east of UTC (nil = local time). tostring gives RFC 3339 ("1979-05-27T07:32:00.5-07:00", "07:32:00", ...). type Date = { kind: "datetime" | "datetime-local" | "date-local" | "time-local", year: number?, month: number?, day: number?, hour: number?, minute: number?, second: number?, nanosecond: number?, -- 0 .. 999999999 offset: number?, -- minutes east of UTC } local DateMeta = {} local function p2(n: number): string return string.format("%02d", n) end local function fmtDate(d: any): string local s: string = "" if d.year then s = string.format("%04d-%02d-%02d", d.year, d.month or 1, d.day or 1) end if d.hour then if s ~= "" then s = s .. "T" end s ..= p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0) local ns = d.nanosecond or 0 if ns > 0 then local f = string.format("%09d", ns) s ..= "." .. (string.gsub(f, "0+$", "")) end if d.offset then if d.offset == 0 then s ..= "Z" else local o = math.abs(d.offset) s ..= (if d.offset < 0 then "-" else "+") .. p2(o // 60) .. ":" .. p2(o % 60) end end end return s end DateMeta.__tostring = fmtDate DateMeta.__eq = function(a: any, b: any): boolean return fmtDate(a) == fmtDate(b) and a.kind == b.kind end local DateLib = {} -- days since 1970-01-01 of a civil date (proleptic Gregorian; Howard Hinnant's algorithm) local function daysFromCivil(y: number, m: number, d: number): number y = if m <= 2 then y - 1 else y local era = (if y >= 0 then y else y - 399) // 400 local yoe = y - era * 400 local mp = (m + 9) % 12 local doy = (153 * mp + 2) // 5 + d - 1 local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy return era * 146097 + doe - 719468 end local function civilFromDays(z: number): (number, number, number) z += 719468 local era = (if z >= 0 then z else z - 146096) // 146097 local doe = z - era * 146097 local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365 local y = yoe + era * 400 local doy = doe - (365 * yoe + yoe // 4 - yoe // 100) local mp = (5 * doy + 2) // 153 local d = doy - (153 * mp + 2) // 5 + 1 local m = if mp < 10 then mp + 3 else mp - 9 return (if m <= 2 then y + 1 else y), m, d end DateLib.civilFromDays = civilFromDays -- days since 1970-01-01 -> year, month, day (proleptic Gregorian) DateLib.daysFromCivil = daysFromCivil -- year, month, day -> days since 1970-01-01 local MDAYS = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } function DateLib.new(f: { [string]: any }): Date local d: any = {} for k, v in f do d[k] = v end if d.kind == nil then d.kind = if d.year and d.hour then (if d.offset then "datetime" else "datetime-local") elseif d.year then "date-local" else "time-local" end return setmetatable(d, DateMeta) :: any end function DateLib.is(v: any): boolean return type(v) == "table" and getmetatable(v) == DateMeta end function DateLib.valid(d: Date): boolean if d.year then local y, m, dd = d.year, d.month or 0, d.day or 0 if y < 0 or y > 9999 or m < 1 or m > 12 or dd < 1 or dd > MDAYS[m] then return false end if m == 2 and dd == 29 and not (y % 4 == 0 and (y % 100 ~= 0 or y % 400 == 0)) then return false end end if d.hour then if d.hour > 23 or (d.minute or 0) > 59 or (d.second or 0) > 60 then return false end end if d.offset and math.abs(d.offset) >= 24 * 60 then return false end return true end -- parse: RFC 3339 / ISO 8601 date-times and the TOML partial forms; lower-case t / z accepted function DateLib.parse(s: string): Date? local d: any = {} local rest: string = s local y, mo, dd, r1 = string.match(rest, "^(%d%d%d%d)%-(%d%d)%-(%d%d)(.*)$") if y then d.year, d.month, d.day = tonumber(y), tonumber(mo), tonumber(dd) rest = r1 :: string if rest == "" then return if DateLib.valid(d) then DateLib.new(d) else nil end local sep = string.sub(rest, 1, 1) if sep ~= "T" and sep ~= "t" and sep ~= " " then return nil end rest = string.sub(rest, 2) end local h, mi, r2 = string.match(rest, "^(%d%d):(%d%d)(.*)$") if not h then return nil end d.hour, d.minute = tonumber(h), tonumber(mi) rest = r2 :: string local sec, r3 = string.match(rest, "^:(%d%d)(.*)$") if not sec then return nil end d.second = tonumber(sec) rest = r3 :: string local frac, r4 = string.match(rest, "^%.(%d+)(.*)$") if frac then d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9)) rest = r4 :: string else d.nanosecond = 0 end if rest ~= "" then if not d.year then return nil end if rest == "Z" or rest == "z" then d.offset = 0 else local sign, oh, om = string.match(rest, "^([%+%-])(%d%d):(%d%d)$") if not sign then return nil end local oh_n, om_n = tonumber(oh) :: number, tonumber(om) :: number if oh_n > 23 or om_n > 59 then return nil end d.offset = (oh_n * 60 + om_n) * (if sign == "-" then -1 else 1) end end return if DateLib.valid(d) then DateLib.new(d) else nil end function DateLib.toUnix(d: Date): number local days = if d.year then daysFromCivil(d.year, d.month or 1, d.day or 1) else 0 local s = days * 86400 + (d.hour or 0) * 3600 + (d.minute or 0) * 60 + (d.second or 0) - (d.offset or 0) * 60 return s + (d.nanosecond or 0) / 1e9 end function DateLib.fromUnix(t: number, offset: number?): Date local off = offset or 0 local whole = math.floor(t) local ns = math.floor((t - whole) * 1e9 + 0.5) if ns >= 1e9 then whole += 1 ns -= 1e9 end local lt = whole + off * 60 local days = lt // 86400 local secs = lt - days * 86400 local y, m, dd = civilFromDays(days) return DateLib.new({ kind = "datetime", year = y, month = m, day = dd, hour = secs // 3600, minute = (secs // 60) % 60, second = secs % 60, nanosecond = ns, offset = off, }) end Types.Date = table.freeze(DateLib) -- XML: an element, or (name starting with "#") a "#document" / "#comment" / "#cdata" / "#pi" / "#doctype" node with -- its content in text. attrs is a Types.object (attribute order kept). Text children are plain strings. type XmlNode = { name: string, attrs: { [string]: string }, children: { XmlNode | string }, parent: XmlNode?, text: string?, -- "#comment" / "#cdata" / "#pi" (the data after the target) / "#doctype" content target: string?, -- "#pi": the target ns: string?, -- the namespace URI (opts.namespaces) [string]: any, } type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any } type VectorPath = { d: { { op: string, [number]: number } }, -- absolute M / L / C / Q / Z commands fill: Paint?, fillRule: "nonzero" | "evenodd", stroke: Paint?, strokeWidth: number, transform: { number }?, -- a, b, c, d, e, f opacity: number, group: number?, -- index into meta.groups (svg nesting: opacity / clip-path per group) clip: number?, -- index into meta.clips (a clip-path) id: string?, strokeDashArray: { number }?, strokeDashOffset: number?, strokeLineJoin: ("miter" | "round" | "bevel")?, -- default "miter" strokeLineCap: ("butt" | "round" | "square")?, -- default "butt" strokeMiterLimit: number?, } type Vector = { kind: "vector", width: number, height: number, viewBox: { number }, -- x, y, w, h paths: { VectorPath }, meta: { [string]: any }, } local Vector = {} function Vector.new(width: number, height: number): Vector return { kind = "vector", width = width, height = height, viewBox = { 0, 0, width, height }, paths = {}, meta = {} } end Types.Vector = Vector -- blend: a codecs/image/Blend mode name ("normal", "multiply", ...; groups also "passThrough"). Optional: children (a group: -- its layers bottom to top; its image is 0 x 0), clip (clipped to the alpha of the layer below), mask (a grey mask in -- canvas coordinates; outside its rectangle the mask is `default`). type LayerMask = { image: Image, x: number, y: number, default: number, disabled: boolean? } type Layer = { name: string, image: Image, x: number, y: number, opacity: number, blend: string, visible: boolean, children: { Layer }?, clip: boolean?, mask: LayerMask? } type Layered = { kind: "layered", width: number, height: number, layers: { Layer }, -- bottom to top (a tree: groups have children); animations: frame 1's layers frames: { { layers: { Layer }, delay: number } }?, -- animations (Aseprite): every frame's layers, delay in seconds meta: { [string]: any }, } local Layered = {} function Layered.new(width: number, height: number): Layered return { kind = "layered", width = width, height = height, layers = {}, frames = nil, meta = {} } end function Layered.layer(name: string, image: Image, x: number?, y: number?): Layer return { name = name, image = image, x = x or 0, y = y or 0, opacity = 1, blend = "normal", visible = true } end function Layered.group(name: string, children: { Layer }): Layer return { name = name, image = Image.new(0, 0), x = 0, y = 0, opacity = 1, blend = "passThrough", visible = true, children = children } end Types.Layered = Layered -- gids are Tiled's: 0 = empty, the tile's firstGid-relative index, flip / rotation flags in the top bits (kept). -- Tilesets keep their image as a reference (imageSource: the path as written; image: an Image only if a caller -- loads it). Extra Tiled fields sit next to these (offsetX / offsetY, parallax, tintColor, class, chunks of infinite -- maps, objects' shapes, per-tile data, ...: see vector/tiled). type Tileset = { name: string, firstGid: number, tileWidth: number, tileHeight: number, columns: number, count: number, image: Image?, source: string?, [string]: any } type TileLayer = { name: string, type: "tiles" | "objects" | "image" | "group", width: number?, height: number?, data: { number }?, objects: { any }?, visible: boolean, opacity: number, properties: { [string]: any }, [string]: any } type TileMap = { kind: "tilemap", width: number, height: number, tileWidth: number, tileHeight: number, orientation: string, tilesets: { Tileset }, layers: { TileLayer }, properties: { [string]: any }, meta: { [string]: any }, [string]: any, } local TileMap = {} function TileMap.new(width: number, height: number, tileWidth: number, tileHeight: number): TileMap return { kind = "tilemap", width = width, height = height, tileWidth = tileWidth, tileHeight = tileHeight, orientation = "orthogonal", tilesets = {}, layers = {}, properties = {}, meta = {} } end Types.TileMap = TileMap type Cue = { start: number, stop: number, text: string, style: string?, id: string?, [string]: any } -- seconds type Subtitles = { kind: "subtitles", cues: { Cue }, styles: { [string]: any }, meta: { [string]: any } } local Subtitles = {} function Subtitles.new(): Subtitles return { kind = "subtitles", cues = {}, styles = {}, meta = {} } end Types.Subtitles = Subtitles -- the playlist-luau shape type PlaylistEntry = { url: string, title: string?, duration: number?, playable: boolean, reason: string?, bandwidth: number?, codecs: string?, attributes: { [string]: string }?, byteRange: { length: number, offset: number? }?, } type Playlist = { kind: "playlist", format: string, -- "m3u", "pls", "hls", "xspf" entries: { PlaylistEntry }, warnings: { string }, title: string?, hls: { [string]: any }?, meta: { [string]: any }, } -- what every format folder's init.luau returns (checked by tools/lint.sh CONTRACT; see docs/STYLE.md) type Caps = { decode: boolean, encode: boolean, [string]: any } type Format = { name: string, category: string, extensions: { string }, mime: { string }, deps: { string }, sniff: (r: any) -> number, -- confidence 0..1 from the first bytes (a core/Bytes Reader); must not consume / throw decode: ((r: any, opts: any?) -> (any, Err?))?, encode: ((value: any, opts: any?) -> (buffer?, Err?))?, open: ((r: any, opts: any?) -> (any, Err?))?, -- streaming categories (audio / video) caps: Caps, } -- the categories, in the order F.formats() lists them; kind = the `kind` of the values they decode to Types.CATEGORIES = table.freeze({ image = "image", audio = "audio", video = "video", model = "scene", cad = "cad", font = "font", archive = "archive", data = "data", vector = "vector", layered = "layered", subtitle = "subtitles", music = "music", playlist = "playlist", } :: { [string]: string }) return Types end __FILES["archive/7z"] = function() -- archive/7z: 7z (7zFormat.txt, LZMA SDK, public domain). Supports: encoded headers, solid folders, copy / LZMA / -- LZMA2 / Deflate / BZip2 / Zstd (7-Zip-zstd frames) with BCJ and delta filters, anti items (skipped), CRC-32s. -- Not supported: PPMd, BCJ2, Deflate64, other plug-in codecs, AES, multi-volume, external header references, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Crc32 = __include("core/Crc32") local Types = __include("Types") local Lzma = __include("codecs/compress/Lzma") local Deflate = __include("codecs/compress/Deflate") local Bzip2 = __include("codecs/compress/Bzip2") local Zstd = __include("codecs/compress/Zstd") local Archive = __include("containers/Archive") local Header = __include("archive/7z/Header") -- ------------------------------------------------------------------------------------------------ contract local SevenZip = { name = "7z", category = "archive", extensions = { "7z" }, mime = { "application/x-7z-compressed" }, deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/compress/Lzma", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Zstd", "containers/Archive", "codecs/text/Text" }, caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false }, } type DecodeOptions = { maxBytes: number?, -- default 2^30, per folder or header checkCrc: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ constants local MAGIC = "7z\188\175\39\28" -- method id -> xz filter id (BCJ / delta) local FILTERS: { [string]: number } = { ["\3\3\1\3"] = 0x04, -- x86 ["\3\3\2\5"] = 0x05, -- PowerPC ["\3\3\5\1"] = 0x07, -- ARM ["\3\3\7\1"] = 0x08, -- ARM-Thumb ["\3\3\8\5"] = 0x09, -- SPARC ["\10"] = 0x0A, -- ARM64 ["\3"] = 0x03, -- delta } local NAMES: { [string]: string } = { ["\0"] = "copy", ["\3\1\1"] = "lzma", ["\33"] = "lzma2", ["\4\1\8"] = "deflate", ["\4\1\9"] = "deflate64", ["\4\2\2"] = "bzip2", ["\3\4\1"] = "ppmd", ["\3\3\1\27"] = "bcj2", ["\6\241\7\1"] = "aes", ["\4\247\17\1"] = "zstd", ["\4\247\17\2"] = "brotli", ["\3\3\1\3"] = "bcj", ["\3\3\2\5"] = "ppc", ["\3\3\5\1"] = "arm", ["\3\3\7\1"] = "armt", ["\3\3\8\5"] = "sparc", ["\10"] = "arm64", ["\3"] = "delta", } local function methodName(id: string): string local n = NAMES[id] if n then return n end local hex = {} for i = 1, #id do table.insert(hex, string.format("%02x", string.byte(id, i))) end return "method " .. table.concat(hex) end -- ------------------------------------------------------------------------------------------------ sniff function SevenZip.sniff(r: Bytes.Reader): number return if r:peek(6) == MAGIC then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode -- folder decoding: evaluate the coder graph from the main out stream; every coder here has one in and one out stream type Ctx = { buf: buffer, base: number, limit: number, maxBytes: number } local function packStart(ctx: Ctx, s: Header.Streams, index: number): number local p = ctx.base + 32 + s.packPos for i = 1, index do p += s.packSizes[i] end return p end local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buffer?, Err.Err?) local inBase, outBase = {}, {} local ni, no = 0, 0 for i, c in f.coders do inBase[i], outBase[i] = ni, no ni += c.numIn no += c.numOut end local depth = 0 local function out(outIdx: number): (buffer?, Err.Err?) depth += 1 if depth > 32 then return nil, Err.new(Err.CORRUPT, "coder graph too deep") end local ci for i, c in f.coders do if outIdx >= outBase[i] and outIdx < outBase[i] + c.numOut then ci = i end end if not ci then return nil, Err.new(Err.CORRUPT, "bad bind pair") end local c = f.coders[ci] if c.numIn ~= 1 or c.numOut ~= 1 then return nil, Err.new(Err.UNSUPPORTED, methodName(c.id) .. " (multi-stream coder)") end local size = f.unpackSizes[outIdx + 1] or 0 if size > ctx.maxBytes then return nil, Err.new(Err.LIMIT, string.format("folder of %d bytes is over maxBytes", size)) end local inIdx = inBase[ci] local src: buffer, so: number, sl: number local bound = nil for _, bp in f.bindPairs do if bp.inIndex == inIdx then bound = bp.outIndex end end if bound then local b, e = out(bound) if not b then return nil, e end src = b so = 0 sl = buffer.len(b) else local k = table.find(f.packed, inIdx) if not k then return nil, Err.new(Err.CORRUPT, "unbound coder input") end local pi = f.firstPack + k - 1 if pi >= #s.packSizes then return nil, Err.new(Err.CORRUPT, "missing pack stream") end so = packStart(ctx, s, pi) sl = s.packSizes[pi + 1] if so + sl > ctx.limit or so < ctx.base then return nil, Err.new(Err.TRUNCATED, "pack stream past the end of the archive", so) end src = ctx.buf end local id = c.id local opts: { maxBytes: number?, verify: boolean? } = { maxBytes = ctx.maxBytes } if id == "\0" then if sl < size then return nil, Err.new(Err.TRUNCATED, "short stored stream") end local b = buffer.create(size) buffer.copy(b, 0, src, so, size) return b, nil elseif id == "\3\1\1" then if buffer.len(c.props) < 5 then return nil, Err.new(Err.CORRUPT, "bad LZMA properties") end local b, e = Lzma.lzma(src, so, sl, c.props, size, opts) return b, if b then nil else e elseif id == "\33" then local b, e = Lzma.lzma2(src, so, sl, nil, size, opts) return b, if b then nil else e elseif id == "\4\1\8" then local b, e = Deflate.inflate(src, so, sl, size) return b, if b then nil else e elseif id == "\4\2\2" or id == "\4\247\17\1" then -- BZip2, Zstd (7-Zip-zstd: plain zstd frames) local b, e if id == "\4\2\2" then b, e = Bzip2.decompress(src, so, sl, opts) else b, e = Zstd.decompress(src, so, sl, opts) end if not b then return nil, e end if buffer.len(b) ~= size then return nil, Err.new(Err.CORRUPT, methodName(id) .. " stream decodes to the wrong size") end return b, nil elseif FILTERS[id] then if sl ~= size then return nil, Err.new(Err.CORRUPT, "filter size mismatch") end local b = buffer.create(size) buffer.copy(b, 0, src, so, size) local ok, e = Lzma.filter(FILTERS[id], b, 0, size, c.props) if not ok then return nil, e end return b, nil end return nil, Err.new(Err.UNSUPPORTED, methodName(id) .. " is not supported") end local main = Header.mainOut(f) if not main then return nil, Err.new(Err.CORRUPT, "folder without a main output") end return out(main) end local function folderMethod(f: Header.Folder): string local names = {} for _, c in f.coders do table.insert(names, methodName(c.id)) end return table.concat(names, "+") end function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) local o: DecodeOptions = opts or {} local maxBytes = if type(o.maxBytes) == "number" then o.maxBytes else 2 ^ 30 local checkCrc = o.checkCrc ~= false local b, base, limit = r.buf, r.base, r.limit if limit - base < 32 then return nil, Err.new(Err.TRUNCATED, "truncated signature header", base) end if buffer.readstring(b, base, 6) ~= MAGIC then return nil, Err.new(Err.CORRUPT, "bad 7z signature", base) end if buffer.readu8(b, base + 6) ~= 0 then return nil, Err.new(Err.UNSUPPORTED, "7z major version " .. buffer.readu8(b, base + 6), base + 6) end if Crc32.raw(b, base + 12, 20) ~= buffer.readu32(b, base + 8) then return nil, Err.new(Err.CHECKSUM, "start header CRC-32 mismatch", base + 8) end local hr = Bytes.reader(b, base + 12, 20) local nextOff, nextSize, nextCrc = hr:u64le(), hr:u64le(), hr:u32le() local ctx: Ctx = { buf = b, base = base, limit = limit, maxBytes = maxBytes } local a = Archive.new("7z") if nextSize == 0 then return a, nil -- an empty archive end local ho = base + 32 + nextOff if nextOff < 0 or ho + nextSize > limit then return nil, Err.new(Err.TRUNCATED, "header past the end of the archive", base + 12) end if Crc32.raw(b, ho, nextSize) ~= nextCrc then return nil, Err.new(Err.CHECKSUM, "header CRC-32 mismatch", ho) end local hbuf, hoff, hlen = b, ho, nextSize local parsed for _ = 1, 4 do local p, perr = Header.parse(hbuf, hoff, hlen) if not p then return nil, perr end if not p.encoded then parsed = p break end -- an encoded header: decode folder 1 of its streams, then parse again local es = p.encoded local f = es.folders[1] if not f then return nil, Err.new(Err.CORRUPT, "encoded header without a folder") end local hb, herr = decodeFolder(ctx, es, f) if not hb then return nil, herr end if f.crc and Crc32.raw(hb, 0, buffer.len(hb)) ~= f.crc then return nil, Err.new(Err.CHECKSUM, "encoded header CRC-32 mismatch") end hbuf = hb hoff = 0 hlen = buffer.len(hb) end if not parsed then return nil, Err.new(Err.CORRUPT, "nested encoded headers") end local s: Header.Streams = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } a.meta.folders = #s.folders a.meta.solid = false local cache: { [number]: buffer } = {} local subFolder: { number }, subOffset: { number } = {}, {} do local si = 1 for fi, f in s.folders do if f.numSub > 1 then a.meta.solid = true end local off = 0 for _ = 1, f.numSub do subFolder[si], subOffset[si] = fi, off off += s.subSizes[si] or 0 si += 1 end if off > Header.unpackSize(f) then return nil, Err.new(Err.CORRUPT, "substreams exceed their folder") end end end local function folderData(fi: number): (buffer?, Err.Err?) local c = cache[fi] if c then return c, nil end local f = s.folders[fi] local d, e = decodeFolder(ctx, s, f) if not d then return nil, e end if checkCrc and f.crc and Crc32.raw(d, 0, buffer.len(d)) ~= f.crc then return nil, Err.new(Err.CHECKSUM, "folder CRC-32 mismatch") end cache[fi] = d return d, nil end local si = 0 for _, file in parsed.files do if file.anti then continue end local attr = file.attributes local isDir = file.emptyStream and not file.emptyFile if attr and bit32.band(attr, 0x10) ~= 0 then isDir = true end local mode = if attr and bit32.band(attr, 0x8000) ~= 0 then bit32.rshift(attr, 16) else nil local e: Archive.Entry = { name = file.name, size = 0, dir = isDir, mtime = file.mtime, attributes = attr, mode = mode, } if not file.emptyStream then si += 1 local idx = si local fi = subFolder[idx] if not fi then return nil, Err.new(Err.CORRUPT, "more files than streams") end local size = s.subSizes[idx] e.size = size e.method = folderMethod(s.folders[fi]) if s.folders[fi].numSub == 1 then local pk = 0 for k = 1, #s.folders[fi].packed do pk += s.packSizes[s.folders[fi].firstPack + k] or 0 end e.compressedSize = pk end e.crc = s.subCrcs[idx] e.load = function(): (buffer?, Err.Err?) local d, derr = folderData(fi) if not d then return nil, derr end local off = subOffset[idx] if off + size > buffer.len(d) then return nil, Err.new(Err.CORRUPT, "substream past its folder") end local out = buffer.create(size) buffer.copy(out, 0, d, off, size) local want = s.subCrcs[idx] if checkCrc and want and Crc32.raw(out, 0, size) ~= want then return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch in " .. file.name) end return out, nil end end Archive.put(a, e) end return a, nil end return SevenZip end __FILES["archive/7z/Header"] = function() -- archive/7z/Header: the 7z header parser (7zFormat.txt, LZMA SDK, Igor Pavlov, public domain): streams, files info. local Text = __include("codecs/text/Text") local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Header = {} type Coder = { id: string, numIn: number, numOut: number, props: buffer } type Folder = { coders: { Coder }, bindPairs: { { inIndex: number, outIndex: number } }, packed: { number }, -- in-stream index of each packed stream unpackSizes: { number }, -- per out stream crc: number?, firstPack: number, -- index of the folder's first pack stream (0-based) numSub: number, -- substreams (files) in the folder } type Streams = { packPos: number, packSizes: { number }, folders: { Folder }, subSizes: { number }, -- every substream, folder by folder subCrcs: { [number]: number }, -- 1-based substream index -> CRC } type File = { name: string, emptyStream: boolean, emptyFile: boolean, anti: boolean, mtime: number?, attributes: number?, } type Parsed = { streams: Streams?, files: { File }, encoded: Streams? } local K = { End = 0x00, Header = 0x01, ArchiveProperties = 0x02, AdditionalStreamsInfo = 0x03, MainStreamsInfo = 0x04, FilesInfo = 0x05, PackInfo = 0x06, UnPackInfo = 0x07, SubStreamsInfo = 0x08, Size = 0x09, CRC = 0x0A, Folder = 0x0B, CodersUnPackSize = 0x0C, NumUnPackStream = 0x0D, EmptyStream = 0x0E, EmptyFile = 0x0F, Anti = 0x10, Name = 0x11, MTime = 0x14, WinAttributes = 0x15, EncodedHeader = 0x17, Dummy = 0x19, } Header.K = K local Fail = {} local function bad(r: Bytes.Reader, msg: string, code: string?): never error(setmetatable({ err = Err.new(code or Err.CORRUPT, msg, r.pos) }, Fail), 0) end local function check(r: Bytes.Reader) if r.err then error(setmetatable({ err = r.err }, Fail), 0) end end local function byte(r: Bytes.Reader): number local v = r:u8() check(r) return v end -- NUMBER: the first byte's leading 1 bits count the extra (little-endian) bytes local function number(r: Bytes.Reader): number local first = byte(r) local mask = 0x80 local value = 0 for i = 0, 7 do if bit32.band(first, mask) == 0 then local high = bit32.band(first, mask - 1) return value + high * 2 ^ (8 * i) end value += byte(r) * 2 ^ (8 * i) mask = bit32.rshift(mask, 1) end return value end -- a count bounded by the bytes left (every counted item takes at least `min` bytes) local function count(r: Bytes.Reader, min: number?): number local n = number(r) if n * (min or 1) > r:remaining() + 1 then bad(r, "count " .. n .. " is larger than the header") end return n end local function bits(r: Bytes.Reader, n: number): { boolean } local out = table.create(n, false) local cur, mask = 0, 0 for i = 1, n do if mask == 0 then cur = byte(r) mask = 0x80 end out[i] = bit32.band(cur, mask) ~= 0 mask = bit32.rshift(mask, 1) end return out end -- bits preceded by an "all defined" byte local function defined(r: Bytes.Reader, n: number): { boolean } if byte(r) ~= 0 then return table.create(n, true) end return bits(r, n) end local function digests(r: Bytes.Reader, n: number): { [number]: number } local def = defined(r, n) local out = {} for i = 1, n do if def[i] then out[i] = r:u32le() end end check(r) return out end local function packInfo(r: Bytes.Reader, s: Streams) s.packPos = number(r) local n = count(r) while true do local t = byte(r) if t == K.End then break elseif t == K.Size then for i = 1, n do s.packSizes[i] = number(r) end elseif t == K.CRC then digests(r, n) else bad(r, "unexpected property " .. t .. " in pack info") end end if #s.packSizes ~= n then bad(r, "missing pack sizes") end end local function folder(r: Bytes.Reader): Folder local ncoders = count(r) if ncoders == 0 or ncoders > 64 then bad(r, "bad coder count " .. ncoders) end local f: Folder = { coders = {}, bindPairs = {}, packed = {}, unpackSizes = {}, crc = nil, firstPack = 0, numSub = 1 } local totalIn, totalOut = 0, 0 for _ = 1, ncoders do local flags = byte(r) if bit32.band(flags, 0x80) ~= 0 then bad(r, "alternative coder methods", Err.UNSUPPORTED) end local idSize = bit32.band(flags, 0x0F) local id = r:string(idSize) check(r) local nin, nout = 1, 1 if bit32.band(flags, 0x10) ~= 0 then nin = number(r) nout = number(r) if nin > 64 or nout > 64 then bad(r, "bad coder stream count") end end local props = buffer.create(0) if bit32.band(flags, 0x20) ~= 0 then local n = count(r) props = r:bytes(n) check(r) end table.insert(f.coders, { id = id, numIn = nin, numOut = nout, props = props }) totalIn += nin totalOut += nout end if totalOut == 0 then bad(r, "a folder without output") end for _ = 1, totalOut - 1 do local i, o = number(r), number(r) table.insert(f.bindPairs, { inIndex = i, outIndex = o }) end local npacked = totalIn - (totalOut - 1) if npacked < 1 then bad(r, "bad bind pairs") end if npacked == 1 then for i = 0, totalIn - 1 do local bound = false for _, bp in f.bindPairs do if bp.inIndex == i then bound = true end end if not bound then table.insert(f.packed, i) break end end if #f.packed ~= 1 then bad(r, "no packed stream") end else for _ = 1, npacked do table.insert(f.packed, number(r)) end end return f end -- the folder's main out stream: the one no bind pair consumes function Header.mainOut(f: Folder): number? local total = 0 for _, c in f.coders do total += c.numOut end for o = 0, total - 1 do local bound = false for _, bp in f.bindPairs do if bp.outIndex == o then bound = true end end if not bound then return o end end return nil end function Header.unpackSize(f: Folder): number local m = Header.mainOut(f) return if m then f.unpackSizes[m + 1] or 0 else 0 end local function unpackInfo(r: Bytes.Reader, s: Streams) if byte(r) ~= K.Folder then bad(r, "expected the folder list") end local n = count(r) if byte(r) ~= 0 then bad(r, "external folders", Err.UNSUPPORTED) end for i = 1, n do s.folders[i] = folder(r) end if byte(r) ~= K.CodersUnPackSize then bad(r, "expected the coder unpack sizes") end for _, f in s.folders do local total = 0 for _, c in f.coders do total += c.numOut end for k = 1, total do f.unpackSizes[k] = number(r) end end while true do local t = byte(r) if t == K.End then break elseif t == K.CRC then local d = digests(r, n) for i = 1, n do s.folders[i].crc = d[i] end else bad(r, "unexpected property " .. t .. " in unpack info") end end end local function subStreamsInfo(r: Bytes.Reader, s: Streams) local t = byte(r) if t == K.NumUnPackStream then for _, f in s.folders do f.numSub = count(r, 0) end t = byte(r) end local sizes = s.subSizes if t == K.Size then for _, f in s.folders do if f.numSub > 0 then local sum = 0 for _ = 1, f.numSub - 1 do local v = number(r) sum += v table.insert(sizes, v) end local total = Header.unpackSize(f) if sum > total then bad(r, "substream sizes exceed the folder") end table.insert(sizes, total - sum) end end t = byte(r) else for _, f in s.folders do if f.numSub > 1 then bad(r, "missing substream sizes") elseif f.numSub == 1 then table.insert(sizes, Header.unpackSize(f)) end end end -- CRCs for the streams whose folder CRC does not already cover them local unknown = 0 for _, f in s.folders do if not (f.numSub == 1 and f.crc) then unknown += f.numSub end end while t ~= K.End do if t == K.CRC then local d = digests(r, unknown) local k, si = 1, 1 for _, f in s.folders do if f.numSub == 1 and f.crc then s.subCrcs[si] = f.crc si += 1 else for _ = 1, f.numSub do s.subCrcs[si] = d[k] k += 1 si += 1 end end end else bad(r, "unexpected property " .. t .. " in substreams info") end t = byte(r) end end local function streamsInfo(r: Bytes.Reader): Streams local s: Streams = { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } local sawSub = false while true do local t = byte(r) if t == K.End then break elseif t == K.PackInfo then packInfo(r, s) elseif t == K.UnPackInfo then unpackInfo(r, s) elseif t == K.SubStreamsInfo then subStreamsInfo(r, s) sawSub = true else bad(r, "unexpected property " .. t .. " in streams info") end end if not sawSub then for i, f in s.folders do f.numSub = 1 table.insert(s.subSizes, Header.unpackSize(f)) if f.crc then s.subCrcs[i] = f.crc end end end local p = 0 for _, f in s.folders do f.firstPack = p p += #f.packed end if p > #s.packSizes then bad(r, "folders use more pack streams than exist") end return s end local function utf16(b: buffer, o: number, n: number): string return Text.utf16(b, o, n, false) end local function filesInfo(r: Bytes.Reader): { File } local n = count(r, 0) if n > 1000000 then bad(r, "too many files", Err.LIMIT) end local files: { File } = table.create(n) :: { File } for i = 1, n do files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false } end local empties: { number } = {} while true do local t = byte(r) if t == K.End then break end local size = number(r) if size > r:remaining() then bad(r, "file property past the header") end local pr = r:slice(size) check(r) if t == K.EmptyStream then local v = bits(pr, n) empties = {} for i = 1, n do files[i].emptyStream = v[i] if v[i] then table.insert(empties, i) end end elseif t == K.EmptyFile or t == K.Anti then local v = bits(pr, #empties) for k, i in empties do if t == K.EmptyFile then files[i].emptyFile = v[k] else files[i].anti = v[k] end end elseif t == K.Name then if byte(pr) ~= 0 then bad(pr, "external names", Err.UNSUPPORTED) end local b = pr.buf local p = pr.pos for i = 1, n do local q = p while q + 1 < pr.limit and buffer.readu16(b, q) ~= 0 do q += 2 end if q + 1 >= pr.limit then bad(pr, "unterminated name") end files[i].name = utf16(b, p, q - p) p = q + 2 end elseif t == K.MTime or t == K.WinAttributes then local def = defined(pr, n) if byte(pr) ~= 0 then bad(pr, "external file properties", Err.UNSUPPORTED) end for i = 1, n do if def[i] then if t == K.MTime then local ft = pr:u64le() files[i].mtime = math.floor(ft / 1e7 - 11644473600) else files[i].attributes = pr:u32le() end end end check(pr) end -- other properties (CTime, ATime, StartPos, Dummy, ...) are skipped end return files end local function header(r: Bytes.Reader): Parsed local p: Parsed = { streams = nil, files = {}, encoded = nil } while true do local t = byte(r) if t == K.End then break elseif t == K.ArchiveProperties then while true do local pt = byte(r) if pt == 0 then break end r:skip(number(r)) check(r) end elseif t == K.AdditionalStreamsInfo then streamsInfo(r) elseif t == K.MainStreamsInfo then p.streams = streamsInfo(r) elseif t == K.FilesInfo then p.files = filesInfo(r) else bad(r, "unexpected property " .. t .. " in the header") end end return p end function Header.parse(b: buffer, o: number, n: number): (Parsed?, Err.Err?) local r = Bytes.reader(b, o, n) local ok, res = pcall(function(): Parsed local t = byte(r) if t == K.Header then return header(r) elseif t == K.EncodedHeader then return { streams = nil, files = {}, encoded = streamsInfo(r) } end return bad(r, "bad header type " .. t) end) if ok then return res, nil end if type(res) == "table" and getmetatable(res :: any) == Fail then return nil, (res :: any).err end error(res, 0) end return Header end __FILES["archive/adf"] = function() -- archive/adf: Amiga disk images (AmigaDOS OFS / FFS, intl, dircache; ADF-FAQ by Laurent Clévy): 72-slot hash tables, -- extension blocks / OFS chains, soft and hard links, protection bits, comments, dates since 1978-01-01, ISO-8859-1 -- names, header checksums. Not supported: writing, DOS\6 / DOS\7, RDB hard-disk images, dircache blocks. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Adf = { name = "adf", category = "archive", extensions = { "adf" }, mime = { "application/x-amiga-disk-format" }, deps = { "core/Err", "core/Bytes", "containers/Archive" }, caps = { decode = true, encode = false, variants = { "ofs", "ffs" } }, } type DecodeOptions = { maxEntries: number? } -- default 65536 -- ------------------------------------------------------------------------------------------------ constants local BS = 512 local HT = 72 -- hash table slots in a 512-byte block local T_HEADER, T_DATA, T_LIST = 2, 8, 16 local ST_ROOT, ST_USERDIR, ST_SOFTLINK, ST_LINKDIR, ST_FILE, ST_LINKFILE = 1, 2, 3, 4, -3, -4 local EPOCH = 252460800 -- 1978-01-01 in unix seconds -- ------------------------------------------------------------------------------------------------ sniff function Adf.sniff(r: Bytes.Reader): number local n = r:size() if n < 4 * BS or n % BS ~= 0 then return 0 end local h = r:peek(4) if string.sub(h, 1, 3) ~= "DOS" or string.byte(h, 4) > 5 then return 0 end return if n == 901120 or n == 1802240 then 0.95 else 0.6 end -- ------------------------------------------------------------------------------------------------ decode local function latin1(s: string): string if not string.find(s, "[\128-\255]") then return s end local out = table.create(#s) for i = 1, #s do out[i] = utf8.char(string.byte(s, i)) end return table.concat(out) end type Disk = { b: buffer, base: number, blocks: number } local function u32(d: Disk, blk: number, off: number): number local o = d.base + blk * BS + off return buffer.readu8(d.b, o) * 16777216 + buffer.readu8(d.b, o + 1) * 65536 + buffer.readu8(d.b, o + 2) * 256 + buffer.readu8(d.b, o + 3) end local function i32(d: Disk, blk: number, off: number): number local v = u32(d, blk, off) return if v >= 0x80000000 then v - 0x100000000 else v end local function bstr(d: Disk, blk: number, off: number, max: number): string local o = d.base + blk * BS + off local n = math.min(buffer.readu8(d.b, o), max) return latin1(buffer.readstring(d.b, o + 1, n)) end local function checksumOk(d: Disk, blk: number): boolean local sum = 0 for i = 0, BS - 4, 4 do sum = (sum + u32(d, blk, i)) % 0x100000000 end return sum == 0 end local function date(d: Disk, blk: number, off: number): number return (u32(d, blk, off) * 86400 + u32(d, blk, off + 4) * 60 + u32(d, blk, off + 8) // 50) + EPOCH end local function dataBlocks(d: Disk, hdr: number, maxBlocks: number): ({ number }?, string?) local out = {} local blk = hdr local seen: { [number]: boolean } = {} while blk ~= 0 do if blk < 2 or blk >= d.blocks or seen[blk] then return nil, "bad extension block " .. blk end seen[blk] = true if blk ~= hdr and (u32(d, blk, 0) ~= T_LIST or not checksumOk(d, blk)) then return nil, "bad extension block " .. blk end local n = u32(d, blk, 8) if n > HT then return nil, "bad block count in " .. blk end for k = 0, n - 1 do local db = u32(d, blk, 24 + (HT - 1 - k) * 4) if db < 2 or db >= d.blocks then return nil, "bad data block " .. db end table.insert(out, db) if #out > maxBlocks then return nil, "more data blocks than the disk has" end end blk = u32(d, blk, BS - 8) end return out, nil end local function readFile(d: Disk, hdr: number, ofs: boolean): (buffer?, string?) local size = u32(d, hdr, BS - 188) if size > d.blocks * BS then return nil, "file larger than the disk" end local list, err = dataBlocks(d, hdr, d.blocks) if not list then return nil, err end local out = buffer.create(size) local o = 0 for _, db in list do if o >= size then break end if ofs then if u32(d, db, 0) ~= T_DATA then return nil, "data block " .. db .. " is not an OFS data block" end local n = math.min(u32(d, db, 12), 488, size - o) buffer.copy(out, o, d.b, d.base + db * BS + 24, n) o += n else local n = math.min(BS, size - o) buffer.copy(out, o, d.b, d.base + db * BS, n) o += n end end if o < size then return nil, "file data ends early" end return out, nil end function Adf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local n = r:size() if n < 4 * BS or n % BS ~= 0 then return nil, Err.new(Err.CORRUPT, "not a whole number of 512-byte blocks") end local h = r:peek(4) if string.sub(h, 1, 3) ~= "DOS" then return nil, Err.new(Err.CORRUPT, "no DOS boot block") end local flags = string.byte(h, 4) if flags > 5 then return nil, Err.new(Err.UNSUPPORTED, "DOS\\" .. flags .. " (long names) file systems") end local d: Disk = { b = r.buf, base = r.base, blocks = n // BS } local ofs = bit32.band(flags, 1) == 0 local root = (d.blocks - 1 + 2) // 2 if u32(d, root, 0) ~= T_HEADER or i32(d, root, BS - 4) ~= ST_ROOT then return nil, Err.new(Err.CORRUPT, "no root block at " .. root) end if not checksumOk(d, root) then return nil, Err.new(Err.CHECKSUM, "root block checksum") end local a = Archive.new("adf") a.meta.volume = bstr(d, root, BS - 80, 30) a.meta.fs = if ofs then "ofs" else "ffs" a.meta.intl = flags >= 2 a.meta.dircache = flags >= 4 a.meta.dosType = flags a.meta.modified = date(d, root, BS - 92) a.meta.created = date(d, root, BS - 28) a.meta.source = { format = "adf", fs = a.meta.fs, blocks = d.blocks } local maxEntries = o.maxEntries or 65536 local count = 0 local pathOf: { [number]: string } = {} local links: { { entry: any, target: number } } = {} local visited: { [number]: boolean } = { [root] = true } local function walk(dir: number, prefix: string): (boolean, Err.Err?) for slot = 0, HT - 1 do local blk = u32(d, dir, 24 + slot * 4) while blk ~= 0 do if blk < 2 or blk >= d.blocks or visited[blk] then return false, Err.new(Err.CORRUPT, "bad or looping hash chain at block " .. blk) end visited[blk] = true count += 1 if count > maxEntries then return false, Err.new(Err.LIMIT, "more than maxEntries entries") end if u32(d, blk, 0) ~= T_HEADER then return false, Err.new(Err.CORRUPT, "block " .. blk .. " is not a header block") end if not checksumOk(d, blk) then return false, Err.new(Err.CHECKSUM, "header block " .. blk .. " checksum") end local name = prefix .. bstr(d, blk, BS - 80, 30) local st = i32(d, blk, BS - 4) local e: any = { name = name, size = 0, dir = false, mtime = date(d, blk, BS - 92), protect = u32(d, blk, BS - 192), comment = bstr(d, blk, BS - 184, 79), method = "store", } if e.comment == "" then e.comment = nil end if st == ST_USERDIR then e.name = name .. "/" e.dir = true pathOf[blk] = e.name Archive.put(a, e) local ok, err = walk(blk, e.name) if not ok then return false, err end elseif st == ST_FILE then e.size = u32(d, blk, BS - 188) pathOf[blk] = name local hb = blk e.load = function(): (buffer?, Err.Err?) local data, err = readFile(d, hb, ofs) if not data then return nil, Err.new(Err.CORRUPT, tostring(err)) end return data, nil end Archive.put(a, e) elseif st == ST_SOFTLINK then local lo = d.base + blk * BS + 24 local s = buffer.readstring(d.b, lo, BS - 24 - 200) e.link = latin1(string.match(s, "^[^%z]*") or "") e.type = "symlink" Archive.put(a, e) elseif st == ST_LINKFILE or st == ST_LINKDIR then e.type = "hardlink" e.dir = st == ST_LINKDIR if e.dir then e.name = name .. "/" end Archive.put(a, e) table.insert(links, { entry = e, target = u32(d, blk, BS - 44) }) end blk = u32(d, blk, BS - 16) end end return true, nil end local ok, err = walk(root, "") if not ok then return nil, err end -- hard links: the linked path, and a file link reads its target's data for _, l in links do local target = pathOf[l.target] l.entry.hardlink = target if target and not l.entry.dir then local te = a._byName[target] if te then l.entry.size = te.size l.entry.load = te.load end end end return a, nil end return Adf end __FILES["archive/applesingle"] = function() -- archive/applesingle: AppleSingle (0x00051600) / AppleDouble (0x00051607) v1 and v2 (RFC 1740): data fork (1), -- resource fork (2), real name (3), comment (4), dates (8; v1 file info 7), Finder info (9), as containers/MacFile. -- Supports: read, write v2. Not supported: icon, ProDOS / MS-DOS / AFP info entries (kept in meta.entries). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Archive = __include("containers/Archive") local MacFile = __include("containers/MacFile") -- ------------------------------------------------------------------------------------------------ contract local AppleSingle = { name = "applesingle", category = "archive", extensions = { "as", "applesingle", "appledouble" }, mime = { "application/applefile", "multipart/appledouble" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/MacFile" }, caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } }, } type DecodeOptions = { name: string?, maxBytes: number? } type EncodeOptions = { double: boolean?, -- default false name: string?, } -- ------------------------------------------------------------------------------------------------ constants local SINGLE, DOUBLE = 0x00051600, 0x00051607 local Y2K = 946684800 -- 2000-01-01 in unix seconds -- ------------------------------------------------------------------------------------------------ sniff function AppleSingle.sniff(r: Bytes.Reader): number local h = r:peek(8) if #h < 8 then return 0 end local magic = string.sub(h, 1, 4) local ver = string.sub(h, 5, 8) if (magic == "\0\5\22\0" or magic == "\0\5\22\7") and (ver == "\0\1\0\0" or ver == "\0\2\0\0") then return 1 end return 0 end -- ------------------------------------------------------------------------------------------------ decode local function encoder(a: any, o: any?): (buffer?, Err.Err?) return AppleSingle.encode(a, o) end local function i32(v: number): number return if v >= 0x80000000 then v - 0x100000000 else v end function AppleSingle.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local magic, ver = r:u32be(), r:u32be() r:skip(16) local count = r:u16be() if r.err then return nil, r.err end if (magic ~= SINGLE and magic ~= DOUBLE) or (ver ~= 0x10000 and ver ~= 0x20000) then return nil, Err.new(Err.CORRUPT, "not AppleSingle / AppleDouble") end local size = r:size() local info: MacFile.Info = { name = "", data = buffer.create(0), rsrc = buffer.create(0), type = "\0\0\0\0", creator = "\0\0\0\0", flags = 0 } local others = {} local total = 0 for _ = 1, count do local id, off, len = r:u32be(), r:u32be(), r:u32be() if r.err then return nil, r.err end if off + len > size then return nil, Err.new(Err.TRUNCATED, "entry " .. id .. " past the end") end total += len if total > (o.maxBytes or 2 ^ 30) then return nil, Err.new(Err.LIMIT, "entries larger than maxBytes") end local e = r:sub(off, len) if id == 1 then info.data = e:bytes(len) elseif id == 2 then info.rsrc = e:bytes(len) elseif id == 3 then info.name = MacFile.name(e:string(len)) elseif id == 4 then info.comment = MacFile.name(e:string(len)) elseif id == 8 and len >= 8 then local c, m = e:u32be(), e:u32be() info.created = if c == 0x80000000 then nil else i32(c) + Y2K info.modified = if m == 0x80000000 then nil else i32(m) + Y2K elseif id == 7 and len >= 12 and ver == 0x10000 then local c, m = e:u32be(), e:u32be() info.created, info.modified = MacFile.fromMac(c), MacFile.fromMac(m) elseif id == 9 and len >= 10 then info.type, info.creator = e:string(4), e:string(4) info.flags = e:u16be() else table.insert(others, { id = id, length = len }) end end if info.name == "" then local n = if type(o.name) == "string" then string.match(o.name, "([^/\\]+)$") else nil info.name = if n then (string.match(n, "^%._(.+)$") or n) else "data" end local a = Archive.new("applesingle", encoder) MacFile.put(a, info, magic == DOUBLE) a.meta.double = magic == DOUBLE a.meta.entries = others a.meta.stream = magic == SINGLE and buffer.len(info.rsrc) == 0 a.meta.source = { format = "applesingle", variant = if magic == DOUBLE then "appledouble" else "applesingle", version = ver // 0x10000 } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function AppleSingle.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local files, err = MacFile.collect(value, o.name) if not files then return nil, err end local f = files[1] if not f then return nil, Err.new(Err.ARG, "nothing to encode") end local name = MacFile.roman(f.name) local function date(t: number?): number if type(t) ~= "number" then return 0x80000000 end return math.clamp(math.floor(t - Y2K), -0x80000000, 0x7FFFFFFF) % 0x100000000 end local dates = Bytes.writer(16) dates:u32be(date(f.created or f.modified)) dates:u32be(date(f.modified)) dates:u32be(0x80000000) dates:u32be(0x80000000) local finder = Bytes.writer(32) finder:string(f.type) finder:string(f.creator) finder:u16be(f.flags) finder:string(string.rep("\0", 22)) local entries: { { any } } = { { 3, buffer.fromstring(name) } } if f.comment then table.insert(entries, { 4, buffer.fromstring(MacFile.roman(f.comment)) }) end table.insert(entries, { 8, dates:finish() }) table.insert(entries, { 9, finder:finish() }) if not o.double then table.insert(entries, { 1, f.data }) end if buffer.len(f.rsrc) > 0 or o.double then table.insert(entries, { 2, f.rsrc }) end local w = Bytes.writer() w:u32be(if o.double then DOUBLE else SINGLE) w:u32be(0x20000) w:string(string.rep("\0", 16)) w:u16be(#entries) local off = 26 + 12 * #entries for _, e in entries do w:u32be(e[1]) w:u32be(off) w:u32be(buffer.len(e[2])) off += buffer.len(e[2]) end for _, e in entries do w:bytes(e[2]) end return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras -- new() -> an empty AppleSingle Archive: a:add(name, data); add "name.rsrc" for a resource fork function AppleSingle.new(): any local a = Archive.new("applesingle", encoder) a.meta.source = { format = "applesingle" } return a end return AppleSingle end __FILES["archive/ar"] = function() -- archive/ar: Unix ar ("!\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 }, } type DecodeOptions = { maxEntries: number?, -- default 1e6 maxBytes: number?, -- .deb control.tar limit (default 2^26) } type EncodeOptions = { variant: ("gnu" | "bsd")?, -- default: the source's ("bsd" for a .deb), else "gnu" } -- ------------------------------------------------------------------------------------------------ constants local MAGIC = "!\n" local HEADER = 60 -- ------------------------------------------------------------------------------------------------ sniff function Ar.sniff(r: Bytes.Reader): number if r:peek(8) == MAGIC then return if r:peek(13, 68) == "debian-binary" then 1 else 0.9 end return if r:peek(8) == "!\n" then 0.5 else 0 end -- ------------------------------------------------------------------------------------------------ decode local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?) return function(): (buffer?, Err.Err?) local out = buffer.create(n) buffer.copy(out, 0, b, at, n) return out, nil end end local function decimal(s: string): number? local d = string.match(s, "^%s*(%d+)%s*$") return if d then tonumber(d) else (if string.find(s, "^%s*$") then 0 else nil) end -- the System V symbol table: a big-endian count, the member offsets, then the NUL-terminated names local function sysvSymbols(b: buffer, o: number, n: number, wide: boolean): { { name: string, offset: number } } local out = {} local w = if wide then 8 else 4 if n < w then return out end local count = if wide then bit32.byteswap(buffer.readu32(b, o + 4)) else bit32.byteswap(buffer.readu32(b, o)) if count * w + w > n then return out end local s = o + w + count * w local e = o + n for i = 0, count - 1 do local off = bit32.byteswap(buffer.readu32(b, o + w + i * w + (w - 4))) local q = s while q < e and buffer.readu8(b, q) ~= 0 do q += 1 end table.insert(out, { name = buffer.readstring(b, s, q - s), offset = off }) s = q + 1 if s > e then break end end return out end -- the BSD __.SYMDEF table: a byte count of { name index, member offset } u32 pairs, the string table size, the strings local function bsdSymbols(b: buffer, o: number, n: number): { { name: string, offset: number } } local out = {} if n < 8 then return out end local rb = buffer.readu32(b, o) if rb % 8 ~= 0 or rb + 8 > n then return out end local strs = o + 8 + rb local strn = math.min(buffer.readu32(b, o + 4 + rb), o + n - strs) for i = 0, rb // 8 - 1 do local sx = buffer.readu32(b, o + 4 + i * 8) if sx < strn then local q = strs + sx while q < strs + strn and buffer.readu8(b, q) ~= 0 do q += 1 end table.insert(out, { name = buffer.readstring(b, strs + sx, q - strs - sx), offset = buffer.readu32(b, o + 8 + i * 8) }) end end return out end -- the fields of a deb control file ("Field: value", continuation lines start with a space or tab) local function controlFields(s: string): { [string]: string } local out: { [string]: string } = {} local last: string? = nil for line in string.gmatch(s, "([^\n]*)\n?") do local c = string.sub(line, 1, 1) if (c == " " or c == "\t") and last then out[last] ..= "\n" .. string.sub(line, 2) else local k, v = string.match(line, "^([^:%s]+):%s*(.-)%s*$") if k then out[k], last = v :: string, k end end end return out end local function debControl(b: buffer, o: number, n: number, name: string, maxBytes: number): { [string]: string }? local ext = string.match(name, "^control%.tar%.?(%w*)$") local raw: buffer? local opts: any = { maxBytes = maxBytes } if ext == "" then raw = buffer.create(n) buffer.copy(raw :: buffer, 0, b, o, n) elseif ext == "gz" then raw = Deflate.gunzip(b, o, n) elseif ext == "xz" then raw = Lzma.xz(b, o, n, opts) elseif ext == "lzma" then raw = Lzma.alone(b, o, n, opts) elseif ext == "zst" then raw = Zstd.decompress(b, o, n, opts) elseif ext == "bz2" then raw = Bzip2.decompress(b, o, n, opts) end if not raw then return nil end local list = Tar.read(raw) for _, e in list or {} do if (e.name == "./control" or e.name == "control") and e.type == "0" then return controlFields(buffer.readstring(raw, e.offset, e.size)) end end return nil end local function encode(archive: any, opts: any?): (buffer?, Err.Err?) return Ar.encode(archive, opts) end function Ar.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local maxEntries = o.maxEntries or 1e6 local b, base, e = r.buf, r.base, r.limit if r:peek(8) == "!\n" then return nil, Err.new(Err.UNSUPPORTED, "thin archives (members are outside the file)", base) end if r:peek(8) ~= MAGIC then return nil, Err.new(Err.CORRUPT, "bad magic", base) end local a = Archive.new("ar", encode) local variant = "gnu" local longNames: string? = nil local symbols: { { name: string, offset: number } }? = nil local offsets: { [number]: string } = {} local count = 0 local p = base + 8 while p < e do local c = buffer.readu8(b, p) if (c == 0 or c == 10) and not string.find(buffer.readstring(b, p, math.min(e - p, 65536)), "[^%z\n]") then break -- trailing padding (bsdtar fills its last 10240-byte block with zeros) end if p + HEADER > e then return nil, Err.new(Err.TRUNCATED, "member header past the end", p) end if buffer.readstring(b, p + 58, 2) ~= "`\n" then return nil, Err.new(Err.CORRUPT, "bad member header", p + 58) end local rawName = buffer.readstring(b, p, 16) local mtime = decimal(buffer.readstring(b, p + 16, 12)) local uid = decimal(buffer.readstring(b, p + 28, 6)) local gid = decimal(buffer.readstring(b, p + 34, 6)) local modeS = string.match(buffer.readstring(b, p + 40, 8), "^%s*([0-7]*)%s*$") local size = decimal(buffer.readstring(b, p + 48, 10)) if not (mtime and uid and gid and modeS and size) then return nil, Err.new(Err.CORRUPT, "bad member header field", p) end local mode = if modeS == "" then 0 else tonumber(modeS, 8) :: number local data = p + HEADER if data + size > e then return nil, Err.new(Err.TRUNCATED, "member data past the end", data) end local nextP = data + size + size % 2 local name = string.gsub(rawName, " +$", "") local dataSize = size if string.sub(name, 1, 3) == "#1/" then local n = tonumber(string.sub(name, 4)) if not n or n > size then return nil, Err.new(Err.CORRUPT, "bad BSD name length", p) end name = buffer.readstring(b, data, n) local z = string.find(name, "\0", 1, true) if z then name = string.sub(name, 1, z - 1) end data += n dataSize -= n variant = "bsd" elseif name == "//" then longNames = buffer.readstring(b, data, size) p = nextP continue elseif name == "/" or name == "/SYM64/" then symbols = sysvSymbols(b, data, size, name == "/SYM64/") p = nextP continue elseif string.match(name, "^/%d+$") then local off = tonumber(string.sub(name, 2)) :: number if not longNames or off >= #longNames then return nil, Err.new(Err.CORRUPT, "long name outside the name table", p) end local s = string.match(longNames, "^([^\n]*)", off + 1) :: string name = string.gsub(s, "/$", "") elseif string.sub(name, -1) == "/" then name = string.sub(name, 1, -2) end if name == "__.SYMDEF" or name == "__.SYMDEF SORTED" or name == "__.SYMDEF_64" or name == "__.SYMDEF_64 SORTED" then symbols = bsdSymbols(b, data, dataSize) variant = "bsd" p = nextP continue end if name == "" then return nil, Err.new(Err.CORRUPT, "empty member name", p) end offsets[p - base] = name count += 1 if count > maxEntries then return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") end Archive.put(a, { name = name, size = dataSize, dir = false, mtime = mtime, uid = uid, gid = gid, mode = bit32.band(mode, 0xFFF), armode = modeS, method = "store", load = if dataSize > 0 then lazy(b, data, dataSize) else nil, }) p = nextP end if symbols then local out = {} for _, s in symbols do table.insert(out, { name = s.name, member = offsets[s.offset] }) end a.meta.symbols = out end a.meta.source = { format = "ar", variant = variant } local list = a._entries if list[1] and list[1].name == "debian-binary" then a.meta.source.variant = "deb" local v = a:read("debian-binary") a.meta.debian = if v then (string.match(buffer.tostring(v), "^%s*(.-)%s*$")) else nil for _, ent in list do if string.match(ent.name, "^data%.tar") then a.meta.payload = ent.name elseif string.match(ent.name, "^control%.tar") then local cb = a:read(ent.name) if cb then a.meta.control = debControl(cb, 0, buffer.len(cb), ent.name, o.maxBytes or 2 ^ 26) end end end end return a, nil end -- ------------------------------------------------------------------------------------------------ encode local function pad(s: string, n: number): string return s .. string.rep(" ", n - #s) end local function header(name: string, e: any, size: number): string? local mtime = math.floor(if type(e.mtime) == "number" then e.mtime else 0) local uid = if type(e.uid) == "number" then e.uid else 0 local gid = if type(e.gid) == "number" then e.gid else 0 local mode: string = if type(e.armode) == "string" and string.find(e.armode, "^[0-7]+$") then e.armode else string.format("%o", if type(e.mode) == "number" then bit32.band(e.mode, 0xFFF) else 0x1A4) local f: { string } = { tostring(mtime), tostring(uid), tostring(gid), mode, tostring(size) } local w = { 12, 6, 6, 8, 10 } for i, s in f do if #s > w[i] or string.find(s, "[^%d]") then return nil end end return pad(name, 16) .. pad(f[1], 12) .. pad(f[2], 6) .. pad(f[3], 6) .. pad(f[4], 8) .. pad(f[5], 10) .. "`\n" end function Ar.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) local items = Archive.entries(archive) if not items then return nil, Err.new(Err.ARG, "expected an Archive") end local o: EncodeOptions = opts or {} local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source local variant = o.variant or (if src and src.format == "ar" and (src.variant == "bsd" or src.variant == "deb") then "bsd" else "gnu") if variant ~= "gnu" and variant ~= "bsd" then return nil, Err.new(Err.ARG, "variant must be gnu or bsd") end local files = {} for _, it in items do local e: any = it.entry if not e.dir and (e.type == nil or e.type == "0") then local data, err = it.read() if not data then return nil, err end table.insert(files, { e = e, data = data }) end end local w = Bytes.writer(1024) w:string(MAGIC) -- GNU: names over 15 bytes (or holding "/" or a space) go into the "//" table local table_: { string } = {} local nameOf: { string } = {} local tsize = 0 for i, f in files do local name: string = f.e.name if string.find(name, "\n") or name == "" then return nil, Err.new(Err.ARG, "entry " .. i .. ": bad name for ar") end if variant == "gnu" then if #name > 15 or string.find(name, "[/ ]") then nameOf[i] = "/" .. tsize table.insert(table_, name .. "/\n") tsize += #name + 2 else nameOf[i] = name .. "/" end end end if #table_ > 0 then local t = table.concat(table_) if #t % 2 == 1 then t ..= "\n" end w:string(pad("//", 48) .. pad(tostring(#t), 10) .. "`\n" .. t) end for i, f in files do local name: string = f.e.name local size = buffer.len(f.data) local prefix = "" local field = nameOf[i] if variant == "bsd" then if #name > 16 or string.find(name, " ") then field = "#1/" .. #name prefix = name else field = name end end local h = header(field, f.e, size + #prefix) if not h then return nil, Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the ar header") end w:string(h) w:string(prefix) w:bytes(f.data) if (size + #prefix) % 2 == 1 then w:string("\n") end end return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras function Ar.new(): any local a = Archive.new("ar", encode) a.meta.source = { format = "ar", variant = "gnu" } return a end return Ar end __FILES["archive/arj"] = function() -- archive/arj: ARJ (Robert Jung; arj's technote.txt): headers CRC-32 checked, methods 0 stored, 1..3 Lzh "lh6", 4 Lzh -- "arj4", directories (file type 3), DOS times as UTC; file CRC-32 verified. Not supported: garbled (encrypted) files, -- multi-volume archives, chapters, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Crc32 = __include("core/Crc32") local Lzh = __include("codecs/compress/Lzh") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Arj = { name = "arj", category = "archive", extensions = { "arj" }, mime = { "application/x-arj" }, deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Lzh", "containers/Archive" }, caps = { decode = true, encode = false, methods = { "store", "arj1", "arj2", "arj3", "arj4" } }, } type DecodeOptions = { maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 65536 } -- ------------------------------------------------------------------------------------------------ constants local OS = { [0] = "msdos", "primos", "unix", "amiga", "macos", "os2", "appleiigs", "atarist", "next", "vaxvms", "win95", "win32" } -- ------------------------------------------------------------------------------------------------ sniff function Arj.sniff(r: Bytes.Reader): number local h = r:peek(4) if #h == 4 and string.byte(h, 1) == 0x60 and string.byte(h, 2) == 0xEA then local size = string.byte(h, 3) + string.byte(h, 4) * 256 return if size > 0 and size <= 2600 then 0.9 else 0 end return 0 end -- ------------------------------------------------------------------------------------------------ decode type Header = { fields: Bytes.Reader, name: string, comment: string, size: number, at: number, next: number } -- the header block at p: 60 EA, size, the basic header, its CRC-32, extended headers; nil at the end marker local function block(r: Bytes.Reader, p: number): (Header?, string?) local h = r:sub(p, 4) local id1, id2, size = h:u8(), h:u8(), h:u16le() if h.err then return nil, "truncated header" end if id1 ~= 0x60 or id2 ~= 0xEA then return nil, "bad header id" end if size == 0 then return nil, nil end if size > 2600 then return nil, "header too large" end if p + 4 + size + 4 > r:size() then return nil, "truncated header" end local crc = r:sub(p + 4 + size, 4):u32le() if Crc32.of(r.buf, r.base + p + 4, size) ~= crc then return nil, "checksum: header CRC-32 mismatch" end local f = r:sub(p + 4, size) local first = f:u8() if first < 30 or first > size then return nil, "bad first header size" end f:seek(first) local name = f:cstring() local comment = f:cstring() -- extended headers local q = p + 4 + size + 4 local guard = 0 while true do local e = r:sub(q, 2) local n = e:u16le() if e.err then return nil, "truncated extended header" end q += 2 if n == 0 then break end q += n + 4 guard += 1 if guard > 256 or q > r:size() then return nil, "truncated extended header" end end f:seek(0) return { fields = f, name = name, comment = comment, size = size, at = p, next = q }, nil end function Arj.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local maxBytes = o.maxBytes or 2 ^ 30 local maxEntries = o.maxEntries or 65536 local main, err = block(r, 0) if not main then return nil, Err.from(err or "no main header", r.base) end local a = Archive.new("arj") local mf = main.fields mf:skip(1) local version, minVersion, host = mf:u8(), mf:u8(), mf:u8() local flags = mf:u8() mf:skip(3) local created = mf:u32le() a.meta.archive = main.name a.meta.comment = if main.comment ~= "" then main.comment else nil a.meta.os = OS[host] a.meta.created = Archive.fromDos(created) a.meta.source = { format = "arj", version = version, minVersion = minVersion, flags = flags } local p = main.next local count = 0 while true do local h, herr = block(r, p) if herr then return nil, Err.from(herr, r.base + p) end if not h then break end count += 1 if count > maxEntries then return nil, Err.new(Err.LIMIT, "more than maxEntries entries") end local f = h.fields f:skip(1) f:skip(2) local hostOs = f:u8() local fl = f:u8() local method = f:u8() local ftype = f:u8() f:skip(1) local stamp = f:u32le() local packed, size, crc = f:u32le(), f:u32le(), f:u32le() f:skip(2) local mode = f:u16le() local dataAt = h.next if dataAt + packed > r:size() then return nil, Err.new(Err.TRUNCATED, "entry " .. h.name .. " data past the end", r.base + dataAt) end local name = string.gsub(h.name, "\\", "/") local isDir = ftype == 3 if isDir and string.sub(name, -1) ~= "/" then name ..= "/" end local e: any = { name = name, size = if isDir then 0 else size, compressedSize = packed, method = if method == 0 then "store" else "arj" .. method, mtime = Archive.fromDos(stamp), dir = isDir, mode = mode, os = OS[hostOs], comment = if h.comment ~= "" then h.comment else nil, fileType = ftype, } if ftype ~= 4 then -- 4: a volume label, not a file if not isDir and size > 0 then if size > maxBytes then return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") end local buf, at = r.buf, r.base + dataAt e.load = function(): (buffer?, Err.Err?) if bit32.band(fl, 0x01) ~= 0 then return nil, Err.new(Err.UNSUPPORTED, "garbled (encrypted) entries") end if bit32.band(fl, 0x0C) ~= 0 then return nil, Err.new(Err.UNSUPPORTED, "an entry split across volumes") end local out: buffer?, derr: string? if method == 0 then if packed < size then return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size") end out = buffer.create(size) buffer.copy(out :: buffer, 0, buf, at, size) elseif method >= 1 and method <= 3 then out, derr = Lzh.decode(buf, at, packed, size, "lh6") elseif method == 4 then out, derr = Lzh.decode(buf, at, packed, size, "arj4") else return nil, Err.new(Err.UNSUPPORTED, "method " .. method) end if not out then return nil, Err.from(derr) end if Crc32.of(out) ~= crc then return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch") end return out, nil end end Archive.put(a, e) end p = dataAt + packed end return a, nil end return Arj end __FILES["archive/binhex"] = function() -- archive/binhex: BinHex 4.0 (.hqx; RFC 1741 notes): 6-bit text, RLE90, header and forks each with CRC-16/XMODEM, as -- containers/MacFile; writes 64 characters a line, as BinHex 4.0 tools do. Not supported: BinHex 2 / 3 / 5, several -- files in one .hqx (the first is read). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Crc16 = __include("core/Crc16") local Archive = __include("containers/Archive") local MacFile = __include("containers/MacFile") -- ------------------------------------------------------------------------------------------------ contract local Binhex = { name = "binhex", category = "archive", extensions = { "hqx", "hcx" }, mime = { "application/mac-binhex40" }, deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, caps = { decode = true, encode = true, forks = true }, } type DecodeOptions = { maxBytes: number? } -- default 2^30 type EncodeOptions = { name: string? } -- ------------------------------------------------------------------------------------------------ constants local ALPHABET = "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr" local VALUE: { [number]: number } = {} for i = 1, 64 do VALUE[string.byte(ALPHABET, i)] = i - 1 end local BANNER = "(This file must be converted with BinHex" -- ------------------------------------------------------------------------------------------------ sniff function Binhex.sniff(r: Bytes.Reader): number local head = r:peek(2048) local at = string.find(head, BANNER, 1, true) if not at then return 0 end return if at == 1 then 1 else 0.8 end -- ------------------------------------------------------------------------------------------------ decode local function unhex(text: string, maxBytes: number): (buffer?, string?) local banner = string.find(text, BANNER, 1, true) if not banner then return nil, "no BinHex banner" end local start = string.find(text, ":", banner, true) if not start then return nil, "truncated: no data start" end local raw = Bytes.writer(#text) local acc, nbits = 0, 0 local closed = false for i = start + 1, #text do local c = string.byte(text, i) if c == 58 then -- ":" closed = true break end local v = VALUE[c] if v then acc = bit32.bor(bit32.lshift(bit32.band(acc, 0xFFFF), 6), v) nbits += 6 if nbits >= 8 then nbits -= 8 raw:u8(bit32.band(bit32.rshift(acc, nbits), 255)) end elseif c ~= 10 and c ~= 13 and c ~= 9 and c ~= 32 then return nil, string.format("bad character 0x%02x", c) end end if not closed then return nil, "truncated: no closing colon" end local src = raw:finish() -- RLE90: 0x90 n repeats the previous byte n - 1 more times; 0x90 0 is a literal 0x90 local out = Bytes.writer(buffer.len(src) * 2) local n = buffer.len(src) local prev = 0 local i = 0 while i < n do local c = buffer.readu8(src, i) if c == 0x90 and i + 1 < n then local count = buffer.readu8(src, i + 1) i += 2 if count == 0 then out:u8(0x90) prev = 0x90 else if out:tell() + count > maxBytes then return nil, "limit: data larger than maxBytes" end for _ = 2, count do out:u8(prev) end end else out:u8(c) prev = c i += 1 end end return out:finish(), nil end local function encoder(a: any, o: any?): (buffer?, Err.Err?) return Binhex.encode(a, o) end function Binhex.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local maxBytes = o.maxBytes or 2 ^ 30 local b, err = unhex(buffer.readstring(r.buf, r.base, r.limit - r.base), maxBytes) if not b then return nil, Err.from(err) end local h = Bytes.reader(b) local nameLen = h:u8() local name = h:string(nameLen) h:skip(1) -- version local ftype, creator = h:string(4), h:string(4) local flags = h:u16be() local dlen, rlen = h:u32be(), h:u32be() local hcrc = h:u16be() if h.err then return nil, h.err end if Crc16.ccitt(b, 0, h:tell() - 2) ~= hcrc then return nil, Err.new(Err.CHECKSUM, "header CRC mismatch") end if dlen + rlen > maxBytes then return nil, Err.new(Err.LIMIT, "forks larger than maxBytes") end local forks = {} for k, len in { dlen, rlen } do local at = h:tell() local fork = h:bytes(len) local crc = h:u16be() if h.err then return nil, h.err end if Crc16.ccitt(b, at, len) ~= crc then return nil, Err.new(Err.CHECKSUM, (if k == 1 then "data" else "resource") .. " fork CRC mismatch") end forks[k] = fork end local a = Archive.new("binhex", encoder) MacFile.put(a, { name = MacFile.name(name), data = forks[1], rsrc = forks[2], type = ftype, creator = creator, flags = flags }) a.meta.stream = rlen == 0 a.meta.source = { format = "binhex" } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Binhex.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local files, err = MacFile.collect(value, o.name) if not files then return nil, err end local f = files[1] if not f then return nil, Err.new(Err.ARG, "nothing to encode") end local name = MacFile.roman(f.name) if #name < 1 or #name > 63 then return nil, Err.new(Err.ARG, "the name must be 1..63 bytes") end local w = Bytes.writer() w:u8(#name) w:string(name) w:u8(0) w:string(f.type) w:string(f.creator) w:u16be(f.flags) w:u32be(buffer.len(f.data)) w:u32be(buffer.len(f.rsrc)) local hdr = w:finish() local body = Bytes.writer() for _, part in { hdr, f.data, f.rsrc } do body:bytes(part) body:u16be(Crc16.ccitt(part, 0, buffer.len(part))) end local src = body:finish() local rle = Bytes.writer(buffer.len(src) + 16) local n = buffer.len(src) local i = 0 while i < n do local c = buffer.readu8(src, i) local run = 1 while i + run < n and run < 255 and buffer.readu8(src, i + run) == c do run += 1 end if c == 0x90 then rle:u8(0x90) rle:u8(0) run = 1 else rle:u8(c) if run >= 3 then rle:u8(0x90) rle:u8(run) else run = 1 end end i += run end local bytes = rle:finish() -- 6-bit characters, 64 to a line (the first line includes the colon) local chars = { ":" } local col = 1 local acc, nbits = 0, 0 local function put(v: number) table.insert(chars, string.sub(ALPHABET, v + 1, v + 1)) col += 1 if col == 64 then table.insert(chars, "\n") col = 0 end end for k = 0, buffer.len(bytes) - 1 do acc = bit32.bor(bit32.lshift(bit32.band(acc, 0xFF), 8), buffer.readu8(bytes, k)) nbits += 8 while nbits >= 6 do nbits -= 6 put(bit32.band(bit32.rshift(acc, nbits), 63)) end end if nbits > 0 then put(bit32.band(bit32.lshift(acc, 6 - nbits), 63)) end table.insert(chars, ":\n") return buffer.fromstring("(This file must be converted with BinHex 4.0)\n" .. table.concat(chars)), nil end -- ------------------------------------------------------------------------------------------------ extras function Binhex.new(): any local a = Archive.new("binhex", encoder) a.meta.source = { format = "binhex" } return a end return Binhex end __FILES["archive/br"] = function() -- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (codecs/compress/Brotli). Supports: read. -- Not supported: write. No magic number: sniff accepts only data that decodes cleanly, at a low confidence. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Brotli = __include("codecs/compress/Brotli") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Br = { name = "br", category = "archive", extensions = { "br" }, mime = { "application/x-brotli" }, deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" }, caps = { decode = true, encode = false, stream = true }, } type DecodeOptions = { name: string?, maxBytes: number?, -- default 2^30 } -- ------------------------------------------------------------------------------------------------ constants local SNIFF_WHOLE = 262144 -- streams up to this size are decoded whole by sniff local SNIFF_PREFIX = 65536 -- ------------------------------------------------------------------------------------------------ sniff function Br.sniff(r: Bytes.Reader): number local n = r:remaining() if n == 0 then return 0 end if n <= SNIFF_WHOLE then local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = 2 ^ 26 }) if out and consumed == r.limit then return if buffer.len(out) > 0 then 0.3 else 0.05 end return 0 end local _, err = Brotli.decompress(r.buf, r.pos, SNIFF_PREFIX, { maxBytes = 2 ^ 22 }) if err and (err.code == Err.TRUNCATED or err.code == Err.LIMIT) then return 0.05 end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Br.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local n = r:remaining() local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = opts and opts.maxBytes }) if not out then local e: Err.Err = consumed e.message = string.gsub(e.message, "^brotli: ", "") return nil, e end local a = Archive.new("br") a.meta.stream = true a.meta.compressedSize = consumed - r.pos Archive.put(a, { name = Archive.streamName(opts, Br.extensions), size = buffer.len(out), compressedSize = consumed - r.pos, method = "brotli", dir = false, data = out, }) return a, nil end return Br end __FILES["archive/bz2"] = function() -- archive/bz2: a .bz2 file as a single-stream archive of one entry (codecs/compress/Bzip2). Supports: read, -- concatenated streams joined as bzip2 -d does. Not supported: writing, randomised blocks (bzip2 0.9.0 and older). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Archive = __include("containers/Archive") local Bzip2 = __include("codecs/compress/Bzip2") -- ------------------------------------------------------------------------------------------------ contract local Bz2 = { name = "bz2", category = "archive", extensions = { "bz2", "tbz2", "tbz" }, mime = { "application/x-bzip2" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" }, caps = { decode = true, encode = false, stream = true }, } type DecodeOptions = { maxBytes: number?, -- default 2^30 name: string?, } -- ------------------------------------------------------------------------------------------------ sniff function Bz2.sniff(r: Bytes.Reader): number local h = r:peek(10) if #h < 10 or string.sub(h, 1, 3) ~= "BZh" then return 0 end local lv = string.byte(h, 4) if lv < 0x31 or lv > 0x39 then return 0 end local magic = string.sub(h, 5, 10) if magic == "\x31\x41\x59\x26\x53\x59" or magic == "\x17\x72\x45\x38\x50\x90" then return 1 end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Bz2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local out, consumed = Bzip2.decompress(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes }) if not out then return nil, consumed end local a = Archive.new("bz2") a.meta.stream = true Archive.put(a, { name = Archive.streamName(opts, Bz2.extensions), size = buffer.len(out), compressedSize = consumed - r.base, method = "bzip2", dir = false, data = out, }) return a, nil end return Bz2 end __FILES["archive/cab"] = function() -- archive/cab: Microsoft Cabinet (MSCF 1.3, [MS-CAB]): folders none / MSZIP ("CK" + raw deflate, dictionary carried -- over between blocks) / LZX (2^15..2^21) / Quantum (2^10..2^21), DOS times as UTC, checksums verified; writes one -- stored or MSZIP folder. Not supported: files spanning cabinets of a set, signed / self-extracting stubs. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Deflate = __include("codecs/compress/Deflate") local Lzx = __include("codecs/compress/Lzx") local Quantum = __include("codecs/compress/Quantum") local Archive = __include("containers/Archive") local Sum = __include("archive/cab/Sum") -- ------------------------------------------------------------------------------------------------ contract local Cab = { name = "cab", category = "archive", extensions = { "cab" }, mime = { "application/vnd.ms-cab-compressed" }, deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" }, caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } }, } type DecodeOptions = { maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 65535 verify: boolean?, -- default true } type EncodeOptions = { compression: ("mszip" | "none")?, -- default "mszip" level: number?, -- 0..9 (default 6) setId: number?, -- default 0 } -- ------------------------------------------------------------------------------------------------ constants local FLAG_PREV, FLAG_NEXT, FLAG_RESERVE = 0x0001, 0x0002, 0x0004 local ATTR_UTF8 = 0x80 local METHOD = { [0] = "store", "mszip", "quantum", "lzx" } local BLOCK = 32768 -- ------------------------------------------------------------------------------------------------ sniff function Cab.sniff(r: Bytes.Reader): number if r:peek(8) == "MSCF\0\0\0\0" then return 1 end return 0 end -- ------------------------------------------------------------------------------------------------ decode type Folder = { dataAt: number, -- offset of the first CFDATA (relative to the reader) blocks: number, type: number, -- typeCompress index: number, } type Block = { at: number, len: number, size: number } -- a block with cbUncomp 0 runs into the next cabinet local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: boolean, maxBytes: number): ({ Block }?, any, boolean?) local list: { Block } = {} local p = f.dataAt local total = 0 for i = 1, f.blocks do local h = r:sub(p, 8) local csum, cbData, cbUncomp = h:u32le(), h:u16le(), h:u16le() if h.err then return nil, Err.new(Err.TRUNCATED, "data block header past the end", r.base + p) end local at = p + 8 + dataReserve if at + cbData > r:size() then return nil, Err.new(Err.TRUNCATED, "data block past the end", r.base + p) end if cbUncomp == 0 then return list, total, true end if verify and csum ~= 0 and Sum.block(r.buf, r.base + at, cbData, cbUncomp) ~= csum then return nil, Err.new(Err.CHECKSUM, "data block " .. i .. " checksum mismatch", r.base + p) end total += cbUncomp if total > maxBytes then return nil, Err.new(Err.LIMIT, "folder larger than maxBytes") end table.insert(list, { at = r.base + at, len = cbData, size = cbUncomp }) p = at + cbData end return list, total, false end local function inflateFolder(buf: buffer, list: { Block }, total: number, typ: number): (buffer?, Err.Err?) local method = bit32.band(typ, 15) local out = buffer.create(total) if method == 0 then local o = 0 for _, b in list do if b.len ~= b.size then return nil, Err.new(Err.CORRUPT, "stored block with different sizes", b.at) end buffer.copy(out, o, buf, b.at, b.len) o += b.len end return out, nil elseif method == 1 then local spans: { { offset: number, length: number, size: number } } = {} for _, b in list do table.insert(spans, { offset = b.at, length = b.len, size = b.size }) end return Deflate.mszip(buf, spans) elseif method == 3 then local bits = bit32.band(bit32.rshift(typ, 8), 31) local n = 0 for _, b in list do n += b.len end local src = buffer.create(n) local o = 0 for _, b in list do buffer.copy(src, o, buf, b.at, b.len) o += b.len end local res, err = Lzx.decode(src, 0, n, total, bits) if not res then return nil, Err.from(err) end return res, nil elseif method == 2 then local res, err = Quantum.decode(buf, list, total, bit32.band(bit32.rshift(typ, 8), 31)) if not res then return nil, Err.from(err) end return res, nil end return nil, Err.new(Err.UNSUPPORTED, "compression type " .. method) end local function encode(archive: any, opts: any?): (buffer?, Err.Err?) return Cab.encode(archive, opts) end function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local maxBytes = o.maxBytes or 2 ^ 30 local maxEntries = o.maxEntries or 65535 local verify = o.verify ~= false if not r:match("MSCF") then return nil, Err.new(Err.CORRUPT, "no MSCF signature", r.base) end r:skip(4) local cbCabinet = r:u32le() r:skip(4) local coffFiles = r:u32le() r:skip(4) local minor, major = r:u8(), r:u8() local cFolders, cFiles, flags = r:u16le(), r:u16le(), r:u16le() local setId, iCabinet = r:u16le(), r:u16le() local headerReserve, folderReserve, dataReserve = 0, 0, 0 if bit32.band(flags, FLAG_RESERVE) ~= 0 then headerReserve, folderReserve, dataReserve = r:u16le(), r:u8(), r:u8() end local a = Archive.new("cab", encode) local meta: any = a.meta if headerReserve > 0 then meta.reserve = r:bytes(headerReserve) end if bit32.band(flags, FLAG_PREV) ~= 0 then meta.prevCabinet, meta.prevDisk = r:cstring(256), r:cstring(256) end if bit32.band(flags, FLAG_NEXT) ~= 0 then meta.nextCabinet, meta.nextDisk = r:cstring(256), r:cstring(256) end if r.err then return nil, r.err end if major ~= 1 then return nil, Err.new(Err.UNSUPPORTED, "cabinet version " .. major .. "." .. minor) end meta.setId, meta.cabinet = setId, iCabinet meta.source = { format = "cab", version = major .. "." .. minor, size = cbCabinet, flags = flags, reserve = { header = headerReserve, folder = folderReserve, data = dataReserve }, } local folders: { Folder } = {} local methods = {} for i = 1, cFolders do local dataAt, nblocks, typ = r:u32le(), r:u16le(), r:u16le() r:skip(folderReserve) if r.err then return nil, r.err end folders[i] = { dataAt = dataAt, blocks = nblocks, type = typ, index = i } local m = METHOD[bit32.band(typ, 15)] methods[i] = { method = m or ("type " .. bit32.band(typ, 15)), window = if m == "lzx" or m == "quantum" then bit32.band(bit32.rshift(typ, 8), 31) else nil, level = if m == "quantum" then bit32.band(bit32.rshift(typ, 4), 15) else nil, blocks = nblocks, } end meta.folders = methods if cFiles == 0 or cFolders == 0 then return nil, Err.new(Err.CORRUPT, "a cabinet without files or folders") end if cFiles > maxEntries then return nil, Err.new(Err.LIMIT, "more than maxEntries files") end local cachedIndex, cachedData, cachedRuns = 0, nil :: buffer?, false local function folderData(f: Folder): (buffer?, Err.Err?, boolean?) if cachedIndex == f.index then return cachedData, nil, cachedRuns end local list, total, runs = blocks(r, f, dataReserve, verify, maxBytes) if not list then return nil, total, false end local data, err = inflateFolder(r.buf, list, total, f.type) if not data then return nil, err, false end cachedIndex, cachedData, cachedRuns = f.index, data, runs == true return data, nil, runs end local fr = r:sub(coffFiles) for _ = 1, cFiles do local size, offset, iFolder = fr:u32le(), fr:u32le(), fr:u16le() local date, time, attribs = fr:u16le(), fr:u16le(), fr:u16le() local raw = fr:cstring(65536) if fr.err then return nil, fr.err end local name = string.gsub(raw, "\\", "/") local spanned: string? = nil local folder: Folder? if iFolder == 0xFFFD or iFolder == 0xFFFF then spanned = "a file continued from the previous cabinet" folder = folders[1] elseif iFolder == 0xFFFE then spanned = "a file continued in the next cabinet" folder = folders[#folders] else folder = folders[iFolder + 1] if iFolder == 0 and bit32.band(flags, FLAG_PREV) ~= 0 then spanned = "a folder continued from the previous cabinet" end end if not folder then return nil, Err.new(Err.CORRUPT, "file " .. name .. " in a missing folder " .. iFolder) end local fo = folder :: Folder if size > maxBytes then return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") end local e: any = { name = name, size = size, method = METHOD[bit32.band(fo.type, 15)] or "unknown", mtime = Archive.fromDos(date * 65536 + time), dir = false, attributes = bit32.band(attribs, 0xFF7F), utf8 = bit32.band(attribs, ATTR_UTF8) ~= 0, folder = fo.index, offset = offset, readonly = bit32.band(attribs, 0x01) ~= 0, executable = bit32.band(attribs, 0x40) ~= 0, } if spanned then e.spanned = true end if size > 0 or spanned then e.load = function(): (buffer?, Err.Err?) if spanned then return nil, Err.new(Err.UNSUPPORTED, spanned :: string) end local data, err, runs = folderData(fo) if not data then return nil, err end if offset + size > buffer.len(data) then if runs then return nil, Err.new(Err.UNSUPPORTED, "a file continued in the next cabinet") end return nil, Err.new(Err.CORRUPT, "file past the end of its folder") end local out = buffer.create(size) buffer.copy(out, 0, data, offset, size) return out, nil end end Archive.put(a, e) end return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local compression = o.compression or "mszip" if compression ~= "mszip" and compression ~= "none" then return nil, Err.new(Err.ARG, "compression must be \"mszip\" or \"none\"") end local level = o.level or 6 if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then return nil, Err.new(Err.ARG, "level must be 0..9") end local files, ferr = Archive.files(archive) if not files then return nil, ferr end if #files == 0 then return nil, Err.new(Err.ARG, "a cabinet needs at least one file") end if #files > 65535 then return nil, Err.new(Err.ARG, "more than 65535 files") end local total = 0 for _, f in files do total += buffer.len(f.data) end if total > 0x7FFF8000 then return nil, Err.new(Err.ARG, "more than 2 GB of data") end local folder = buffer.create(total) local p = 0 for _, f in files do buffer.copy(folder, p, f.data, 0, buffer.len(f.data)) p += buffer.len(f.data) end local data = Bytes.writer(total // 2 + 64) local nblocks = 0 local s = 0 while s < total do local n = math.min(BLOCK, total - s) local chunk = buffer.create(n) buffer.copy(chunk, 0, folder, s, n) local payload: buffer if compression == "mszip" then local z, zerr = Deflate.compress(chunk, { level = level }) if not z then return nil, zerr end payload = buffer.create(buffer.len(z) + 2) buffer.writeu16(payload, 0, 0x4B43) buffer.copy(payload, 2, z, 0, buffer.len(z)) else payload = chunk end local len = buffer.len(payload) data:u32le(Sum.block(payload, 0, len, n)) data:u16le(len) data:u16le(n) data:bytes(payload) nblocks += 1 s += n end local blob = data:finish() local table_ = Bytes.writer(64 + #files * 32) local offset = 0 for _, f in files do local e: any = f.entry local name = string.gsub(f.name, "/", "\\") local attribs = if type(e.attributes) == "number" then bit32.band(e.attributes, 0x7F) else 0x20 if string.find(name, "[\128-\255]") then attribs = bit32.bor(attribs, ATTR_UTF8) end local stamp = Archive.toDos(e.mtime) table_:u32le(buffer.len(f.data)) table_:u32le(offset) table_:u16le(0) table_:u16le(stamp // 65536) table_:u16le(stamp % 65536) table_:u16le(attribs) table_:cstring(name) offset += buffer.len(f.data) end local fileTable = table_:finish() local nfolders = 1 local coffFiles = 36 + 8 * nfolders local dataAt = coffFiles + buffer.len(fileTable) local size = dataAt + buffer.len(blob) local w = Bytes.writer(size) w:string("MSCF") w:u32le(0) w:u32le(size) w:u32le(0) w:u32le(coffFiles) w:u32le(0) w:u8(3) w:u8(1) w:u16le(nfolders) w:u16le(#files) w:u16le(0) w:u16le(o.setId or 0) w:u16le(0) w:u32le(dataAt) w:u16le(nblocks) w:u16le(if compression == "mszip" then 1 else 0) w:bytes(fileTable) w:bytes(blob) return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras function Cab.new(): any local a = Archive.new("cab", encode) a.meta.source = { format = "cab" } return a end return Cab end __FILES["archive/cab/Sum"] = @native function() -- archive/cab/Sum: the CFDATA.csum checksum ([MS-CAB] 2.4): XOR of LE u32 words, the last 1..3 bytes packed most -- significant first, then the cbData / cbUncomp word. local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift local Sum = {} @native function Sum.of(buf: buffer, off: number, len: number, seed: number): number if off < 0 or len <= 0 or off + len > blen(buf) then return seed end local s = seed local p = off local stop = off + len - len % 4 while p < stop do s = bxor(s, readu32(buf, p)) p += 4 end local rem = len % 4 local tail = 0 if rem == 3 then tail = bor(lshift(readu8(buf, p), 16), lshift(readu8(buf, p + 1), 8), readu8(buf, p + 2)) elseif rem == 2 then tail = bor(lshift(readu8(buf, p), 8), readu8(buf, p + 1)) elseif rem == 1 then tail = readu8(buf, p) end return bxor(s, tail) end @native function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536) end return Sum end __FILES["archive/cpio"] = function() -- archive/cpio: cpio (newc, crc, odc, old binary in both byte orders; containers/Cpio). Supports: read (lazy), write as -- newc / crc / odc; tar hard links ("1") share an inode with their target. Not supported: uname / gname (dropped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Archive = __include("containers/Archive") local Cpio = __include("containers/Cpio") -- ------------------------------------------------------------------------------------------------ contract local CpioFormat = { name = "cpio", category = "archive", extensions = { "cpio" }, mime = { "application/x-cpio" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" }, caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } }, } type DecodeOptions = { maxEntries: number?, -- default 1e6 verify: boolean?, -- default true } type EncodeOptions = { variant: ("newc" | "crc" | "odc")?, -- default: the source archive's (old binary: newc), else "newc" format: string?, -- any other value (the api's "cpio") means the variant default block: number?, -- default 512, as GNU cpio; 1 = none } -- ------------------------------------------------------------------------------------------------ sniff function CpioFormat.sniff(r: Bytes.Reader): number local m = r:peek(6) if m == "070701" or m == "070702" or m == "070707" then return 1 end local b2 = r:peek(2) if (b2 == "\199\113" or b2 == "\113\199") and r:remaining() >= 26 then return 0.5 end return 0 end -- ------------------------------------------------------------------------------------------------ decode local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?) return function(): (buffer?, Err.Err?) local out = buffer.create(n) buffer.copy(out, 0, b, at, n) return out, nil end end local function encode(archive: any, opts: any?): (buffer?, Err.Err?) return CpioFormat.encode(archive, opts) end function CpioFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local list, info = Cpio.read(r.buf, r.base, r.limit - r.base, opts) if not list then return nil, info end local a = Archive.new("cpio", encode) for _, e in list do local data = e.type == "0" and e.size > 0 Archive.put(a, { name = e.name, size = if data then e.size else 0, dir = e.dir, mtime = e.mtime, mode = bit32.band(e.mode, 0xFFF), uid = e.uid, gid = e.gid, type = e.type, link = e.link, hardlink = e.hardlink, nlink = e.nlink, ino = e.ino, devmajor = e.devmajor, devminor = e.devminor, rdevmajor = e.rdevmajor, rdevminor = e.rdevminor, method = "store", load = if data then lazy(r.buf, e.offset, e.size) else nil, }) end a.meta.source = { format = "cpio", variant = info.format } return a, nil end -- ------------------------------------------------------------------------------------------------ encode local function num(v: any): number? return if type(v) == "number" then v else nil end function CpioFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) local items = Archive.entries(archive) if not items then return nil, Err.new(Err.ARG, "expected an Archive") end local index: { [string]: number } = {} for i, it in items do index[it.entry.name] = index[it.entry.name] or i end -- tar hard links ("1"): the same inode as their target, which counts the links local links: { [number]: number } = {} local target: { [number]: number } = {} for i, it in items do local e: any = it.entry if e.type == "1" and type(e.link) == "string" and index[e.link] then local t = index[e.link] target[i] = t links[t] = (links[t] or 1) + 1 end end local list: { Cpio.WriteEntry } = {} for i, it in items do local e: any = it.entry local typ = if type(e.type) == "string" and Cpio.TYPE_MODE[e.type] then e.type elseif e.dir then "5" else "0" local src = target[i] local ino, nlink = num(e.ino), num(e.nlink) if src then typ, ino, nlink = "0", src, links[src] elseif links[i] then ino, nlink = i, links[i] end local data: buffer? = nil if typ == "0" then local b, err = (items[src or i] :: any).read() if not b then return nil, err end data = b end local mode = num(e.mode) table.insert(list, { name = e.name, data = data, type = typ, link = if type(e.link) == "string" and typ == "2" then e.link else nil, mode = if mode then bit32.band(mode, 0xFFF) else nil, uid = num(e.uid), gid = num(e.gid), nlink = nlink, mtime = num(e.mtime), ino = ino, devmajor = num(e.devmajor), devminor = num(e.devminor), rdevmajor = num(e.rdevmajor), rdevminor = num(e.rdevminor), }) end local o: any = opts or {} local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source local own = if src and src.format == "cpio" and (src.variant == "crc" or src.variant == "odc") then src.variant else "newc" local variant = o.variant or (if o.format == "crc" or o.format == "odc" or o.format == "newc" then o.format else own) return Cpio.write(list, { format = variant, block = o.block }) end -- ------------------------------------------------------------------------------------------------ extras function CpioFormat.new(): any local a = Archive.new("cpio", encode) a.meta.source = { format = "cpio" } return a end return CpioFormat end __FILES["archive/d64"] = function() -- archive/d64: Commodore D64 (1541: 35 / 40 / 42 tracks, error block), D71, D81 (Peter Schepers' notes); PETSCII names -- as VICE's c1541 (0x41..0x5A -> a..z, 0xC1..0xDA / 0x61..0x7A -> A..Z, else U+E0xx); writes with interleave 10 as -- CBM DOS (not a real drive's sectors). Not supported: GEOS VLIR files (first chain), 1581 partition contents. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local D64 = { name = "d64", category = "archive", extensions = { "d64", "d71", "d81" }, mime = { "application/x-d64" }, deps = { "core/Err", "core/Bytes", "containers/Archive" }, caps = { decode = true, encode = true, variants = { "d64", "d71", "d81" } }, } type DecodeOptions = { maxEntries: number? } -- default 4096 type EncodeOptions = { variant: ("d64" | "d71" | "d81")?, -- default: the variant read, else "d64" disk: string?, -- default "rosetta" / the name read id: string?, -- default "fl" } -- ------------------------------------------------------------------------------------------------ constants local TYPES = { [0] = "del", "seq", "prg", "usr", "rel", "cbm", "dir" } local TYPE_CODE: { [string]: number } = { del = 0, seq = 1, prg = 2, usr = 3, rel = 4 } type Geometry = { kind: string, tracks: number, offsets: { number }, spt: { number }, dirTrack: number, total: number } local function geometry(kind: string, tracks: number): Geometry local offsets, spt = {}, {} local o = 0 for t = 1, tracks do local n if kind == "d81" then n = 40 else local s = if kind == "d71" and t > 35 then t - 35 else t n = if s <= 17 then 21 elseif s <= 24 then 19 elseif s <= 30 then 18 else 17 end offsets[t], spt[t] = o, n o += n * 256 end return { kind = kind, tracks = tracks, offsets = offsets, spt = spt, dirTrack = if kind == "d81" then 40 else 18, total = o } end -- image sizes -> geometry (sizes with the error-info block appended too) local function detect(len: number): Geometry? for _, g in { { "d64", 35 }, { "d64", 40 }, { "d64", 42 }, { "d71", 70 }, { "d81", 80 } } :: { { any } } do local geo = geometry(g[1] :: string, g[2] :: number) local sectors = geo.total // 256 if len == geo.total or (g[1] ~= "d81" and len == geo.total + sectors) then return geo end end return nil end -- ------------------------------------------------------------------------------------------------ sniff function D64.sniff(r: Bytes.Reader): number local geo = detect(r:size()) if not geo then return 0 end -- the BAM / header sector: dir track link and DOS version byte local h = r:sub(geo.offsets[geo.dirTrack], 256) local t, s, v = h:u8(), h:u8(), h:u8() if geo.kind == "d81" then return if t == 40 and s == 3 and v == 0x44 then 0.9 else 0.3 end return if t == 18 and s == 1 and (v == 0x41 or v == 0) then 0.9 else 0.3 end -- ------------------------------------------------------------------------------------------------ decode local function petscii(raw: string): string local out = table.create(#raw) for i = 1, #raw do local c = string.byte(raw, i) if c >= 0x41 and c <= 0x5A then out[i] = string.char(c + 32) elseif c >= 0xC1 and c <= 0xDA then out[i] = string.char(c - 0x80) elseif c >= 0x61 and c <= 0x7A then out[i] = string.char(c - 32) elseif c >= 0x20 and c <= 0x40 and c ~= 0x2F then out[i] = string.char(c) else out[i] = utf8.char(0xE000 + c) end end return table.concat(out) end local function toPetscii(name: string): string local out = {} if not utf8.len(name) then return string.sub(name, 1, 16) end for _, c in utf8.codes(name) do local b if c >= 0x61 and c <= 0x7A then b = c - 32 elseif c >= 0x41 and c <= 0x5A then b = c + 0x80 elseif c >= 0xE000 and c <= 0xE0FF then b = c - 0xE000 elseif c >= 0x20 and c <= 0x40 and c ~= 0x2F then b = c else b = 0x3F end table.insert(out, string.char(b)) end return string.sub(table.concat(out), 1, 16) end local function encoder(a: any, o: any?): (buffer?, Err.Err?) return D64.encode(a, o) end local function chain(b: buffer, base: number, geo: Geometry, t: number, s: number): (buffer?, string?) local w = Bytes.writer() local seen: { [number]: boolean } = {} while t ~= 0 do if t < 1 or t > geo.tracks or s >= geo.spt[t] then return nil, string.format("chain leaves the disk at %d/%d", t, s) end local key = t * 256 + s if seen[key] then return nil, string.format("chain loops at %d/%d", t, s) end seen[key] = true local o = base + geo.offsets[t] + s * 256 local nt, ns = buffer.readu8(b, o), buffer.readu8(b, o + 1) if nt == 0 then local last = math.max(ns, 1) if last >= 2 then w:bytes(buffer.fromstring(buffer.readstring(b, o + 2, last - 1))) end else w:bytes(buffer.fromstring(buffer.readstring(b, o + 2, 254))) end t, s = nt, ns end return w:finish(), nil end function D64.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local geo = detect(r:size()) if not geo then return nil, Err.new(Err.CORRUPT, "not a D64 / D71 / D81 image size (" .. r:size() .. " bytes)") end local b, base = r.buf, r.base local hdr = base + geo.offsets[geo.dirTrack] local nameAt, idAt = if geo.kind == "d81" then 0x04 else 0x90, if geo.kind == "d81" then 0x16 else 0xA2 local diskRaw = buffer.readstring(b, hdr + nameAt, 16) local a = Archive.new("d64", encoder) a.meta.disk = petscii((string.gsub(diskRaw, "\160+$", ""))) a.meta.id = petscii(buffer.readstring(b, hdr + idAt, 2)) a.meta.variant = geo.kind a.meta.tracks = geo.tracks a.meta.errorInfo = r:size() ~= geo.total a.meta.source = { format = "d64", variant = geo.kind, tracks = geo.tracks } local t, s = buffer.readu8(b, hdr), buffer.readu8(b, hdr + 1) local seen: { [number]: boolean } = {} local count = 0 local maxEntries = o.maxEntries or 4096 while t ~= 0 do if t < 1 or t > geo.tracks or s >= geo.spt[t] or seen[t * 256 + s] then return nil, Err.new(Err.CORRUPT, string.format("bad directory sector %d/%d", t, s)) end seen[t * 256 + s] = true local so = base + geo.offsets[t] + s * 256 for k = 0, 7 do local e = so + k * 32 local ft = buffer.readu8(b, e + 2) local kind = bit32.band(ft, 15) if ft ~= 0 and kind ~= 0 then count += 1 if count > maxEntries then return nil, Err.new(Err.LIMIT, "more than maxEntries directory entries") end local raw = buffer.readstring(b, e + 5, 16) local name = petscii((string.gsub(raw, "\160+$", ""))) local base_name, n = name, 2 while a._byName[name] do name = base_name .. ";" .. n n += 1 end local ty = TYPES[kind] or "?" local entry: any = { name = name, rawName = raw, type = ty, closed = bit32.band(ft, 0x80) ~= 0, locked = bit32.band(ft, 0x40) ~= 0, blocks = buffer.readu16(b, e + 30), dir = false, method = "store", } if ty == "cbm" or ty == "dir" then entry.size = 0 else local data, err = chain(b, base, geo, buffer.readu8(b, e + 3), buffer.readu8(b, e + 4)) if not data then return nil, Err.new(Err.CORRUPT, name .. ": " .. tostring(err)) end entry.size = buffer.len(data) entry.data = data if ty == "rel" then entry.recordLength = buffer.readu8(b, e + 23) end end Archive.put(a, entry) end end t, s = buffer.readu8(b, so), buffer.readu8(b, so + 1) end return a, nil end -- ------------------------------------------------------------------------------------------------ encode -- BAM layout per variant: where each track's free count + bitmap lives local function bamEntry(geo: Geometry, img: buffer, t: number): (number, number, number) local dir = geo.offsets[geo.dirTrack] if geo.kind == "d81" then local side = if t <= 40 then 1 else 2 local tt = if t <= 40 then t else t - 40 local o = dir + side * 256 + 0x10 + (tt - 1) * 6 return o, o + 1, 5 end if t <= 35 then local o = dir + 4 + (t - 1) * 4 return o, o + 1, 3 end -- d71 side 2: counts at 18/0 0xDD.., bitmaps on track 53 sector 0 return dir + 0xDD + (t - 36), geo.offsets[53] + (t - 36) * 3, 3 end local function setFree(geo: Geometry, img: buffer, t: number, s: number, free: boolean) local co, bo = bamEntry(geo, img, t) local byte = bo + bit32.rshift(s, 3) local mask = bit32.lshift(1, bit32.band(s, 7)) local cur = buffer.readu8(img, byte) local isFree = bit32.band(cur, mask) ~= 0 if free and not isFree then buffer.writeu8(img, byte, bit32.bor(cur, mask)) buffer.writeu8(img, co, buffer.readu8(img, co) + 1) elseif not free and isFree then buffer.writeu8(img, byte, bit32.band(cur, bit32.bnot(mask))) buffer.writeu8(img, co, buffer.readu8(img, co) - 1) end end function D64.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local variant = o.variant or (if type(value) == "table" and type(value.meta) == "table" and value.meta.variant then value.meta.variant else "d64") if variant ~= "d64" and variant ~= "d71" and variant ~= "d81" then return nil, Err.new(Err.ARG, "variant must be d64, d71 or d81") end local files, err = Archive.files(value, "data") if not files then return nil, err end local geo = geometry(variant, if variant == "d64" then 35 elseif variant == "d71" then 70 else 80) local img = buffer.create(geo.total) local dirT = geo.dirTrack local dir = geo.offsets[dirT] local diskName = toPetscii(o.disk or (if type(value) == "table" and type(value.meta) == "table" and type(value.meta.disk) == "string" then value.meta.disk else "rosetta")) local id = toPetscii(o.id or "fl") local function pad16(s: string): string return s .. string.rep("\160", 16 - #s) end local firstDir if variant == "d81" then buffer.writestring(img, dir, "\40\3\68\0") buffer.writestring(img, dir + 4, pad16(diskName) .. "\160\160" .. string.sub(id .. " ", 1, 2) .. "\160" .. "3D" .. "\160\160") for side = 1, 2 do local bo = dir + side * 256 buffer.writestring(img, bo, if side == 1 then "\40\2\68\187" else "\0\255\68\187") buffer.writestring(img, bo + 4, string.sub(id .. " ", 1, 2) .. "\192\0") end firstDir = 3 else buffer.writestring(img, dir, "\18\1\65" .. (if variant == "d71" then "\128" else "\0")) buffer.writestring(img, dir + 0x90, pad16(diskName) .. "\160\160" .. string.sub(id .. " ", 1, 2) .. "\160" .. "2A" .. "\160\160\160\160") firstDir = 1 end for t = 1, geo.tracks do for s = 0, geo.spt[t] - 1 do setFree(geo, img, t, s, true) end end -- system sectors: the header / BAM sectors and the first directory sector local used = { [dirT * 256 + 0] = true, [dirT * 256 + firstDir] = true } if variant == "d81" then used[dirT * 256 + 1], used[dirT * 256 + 2] = true, true elseif variant == "d71" then for s = 0, geo.spt[53] - 1 do used[53 * 256 + s] = true end end for k in used do setFree(geo, img, k // 256, k % 256, false) end local maxDirSectors = geo.spt[dirT] - firstDir if #files > maxDirSectors * 8 then return nil, Err.new(Err.LIMIT, "too many files for one directory track") end -- allocation: tracks nearest the directory track first, interleave 10 local order = {} for d = 1, geo.tracks do for _, t in { dirT - d, dirT + d } do if t >= 1 and t <= geo.tracks and t ~= dirT and not (variant == "d71" and t == 53) then table.insert(order, t) end end end local ti, lastS = 1, -10 local function alloc(): (number?, number?) while ti <= #order do local t = order[ti] local n = geo.spt[t] for k = 0, n - 1 do local s = (lastS + 10 + k) % n if not used[t * 256 + s] then used[t * 256 + s] = true setFree(geo, img, t, s, false) lastS = s return t, s end end ti += 1 lastS = -10 end return nil, nil end local dirSector, slot = firstDir, 0 local dirSectors = { firstDir } for _, f in files do local data = f.data local n = buffer.len(data) local blocks = math.max(1, math.ceil(n / 254)) local first_t, first_s = 0, 0 local prev = -1 for k = 0, blocks - 1 do local t, s = alloc() if not t or not s then return nil, Err.new(Err.LIMIT, "disk full") end local so = geo.offsets[t] + s * 256 if prev < 0 then first_t, first_s = t, s else buffer.writeu8(img, prev, t) buffer.writeu8(img, prev + 1, s) end local len = math.min(254, n - k * 254) if len > 0 then buffer.copy(img, so + 2, data, k * 254, len) end buffer.writeu8(img, so + 1, if k == blocks - 1 then len + 1 else 0) prev = so end if slot == 8 then -- next directory sector on the directory track (interleave 3) local nextS = nil for k = 0, geo.spt[dirT] - 1 do local s = (dirSector + 3 + k) % geo.spt[dirT] if not used[dirT * 256 + s] then nextS = s break end end if not nextS then return nil, Err.new(Err.LIMIT, "directory full") end used[dirT * 256 + nextS] = true setFree(geo, img, dirT, nextS, false) buffer.writeu8(img, dir + dirSector * 256, dirT) buffer.writeu8(img, dir + dirSector * 256 + 1, nextS) dirSector, slot = nextS, 0 table.insert(dirSectors, nextS) end local e = dir + dirSector * 256 + slot * 32 local ty: number = if type(f.entry.type) == "string" and TYPE_CODE[f.entry.type] then TYPE_CODE[f.entry.type] :: number else 2 buffer.writeu8(img, e + 2, 0x80 + ty) buffer.writeu8(img, e + 3, first_t) buffer.writeu8(img, e + 4, first_s) local raw = if type(f.entry.rawName) == "string" and #f.entry.rawName == 16 then (string.gsub(f.entry.rawName, "\160+$", "")) else toPetscii(f.name) buffer.writestring(img, e + 5, pad16(raw)) buffer.writeu16(img, e + 30, blocks) slot += 1 end buffer.writeu8(img, dir + dirSector * 256 + 1, 0xFF) return img, nil end -- ------------------------------------------------------------------------------------------------ extras function D64.new(variant: string?): any local a = Archive.new("d64", encoder) a.meta.variant = variant or "d64" a.meta.source = { format = "d64" } return a end return D64 end __FILES["archive/fat"] = function() -- archive/fat: FAT12 / FAT16 / FAT32 images (floppy, or the first FAT partition of an MBR) through containers/Fat. -- Supports: VFAT long names, NT lower-case 8.3, DOS dates as UTC; writes FAT12 floppies (360..2880 KB) that mtools and -- fsck.fat read. Not supported: writing FAT16 / FAT32, exFAT, boot code. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Archive = __include("containers/Archive") local Fat = __include("containers/Fat") -- ------------------------------------------------------------------------------------------------ contract local FatFormat = { name = "fat", category = "archive", extensions = { "img", "ima", "vfd", "flp", "fat" }, mime = { "application/x-fat-image" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Fat" }, caps = { decode = true, encode = true, variants = { "fat12", "fat16", "fat32" } }, } type DecodeOptions = { partition: number?, -- 1..4 (default: the first FAT partition, or the image itself) maxEntries: number?, -- default 65536 } type EncodeOptions = { size: number?, -- KB: 360 / 720 / 1200 / 1440 / 2880 (default 1440) label: string?, } -- ------------------------------------------------------------------------------------------------ sniff function FatFormat.sniff(r: Bytes.Reader): number if r:remaining() < 512 then return 0 end local v = Fat.open(r.buf, r.base + r.pos, r.limit - r.base - r.pos) if not v then return 0 end return if v.partition then 0.6 else 0.8 end -- ------------------------------------------------------------------------------------------------ decode local function encoder(a: any, o: any?): (buffer?, Err.Err?) return FatFormat.encode(a, o) end function FatFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local v, err = Fat.open(r.buf, r.base, r.limit - r.base, { partition = o.partition }) if not v then return nil, Err.from(err) end local list, lerr = Fat.list(v, o.maxEntries) if not list then return nil, Err.from(lerr) end local a = Archive.new("fat", encoder) for _, e in list do local entry = e Archive.put(a, { name = e.name, size = e.size, dir = e.dir, mtime = e.mtime, attr = e.attr, shortName = e.shortName, method = "store", load = if e.dir or e.size == 0 then nil else function(): (buffer?, Err.Err?) local b, rerr = Fat.read(v :: Fat.Volume, entry) if not b then return nil, Err.from(rerr) end return b, nil end, }) end a.meta.fat = v.bits a.meta.label = v.label a.meta.oem = v.oem a.meta.partition = v.partition a.meta.source = { format = "fat", bits = v.bits, clusterSize = v.spc * v.bps } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function FatFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local items = Archive.entries(value) if not items then return nil, Err.new(Err.ARG, "expected an Archive") end local files: { Fat.WriteFile } = {} for _, it in items do local e: any = it.entry local data: buffer? = nil if not e.dir then local b, err = it.read() if not b then return nil, err end data = b end table.insert(files, { name = e.name, data = data, dir = e.dir, mtime = e.mtime }) end local img, err = Fat.write(files, { size = o.size, label = o.label }) if not img then return nil, if string.match(tostring(err), "^limit") then Err.from(err) else Err.new(Err.ARG, tostring(err)) end return img, nil end -- ------------------------------------------------------------------------------------------------ extras function FatFormat.new(): any local a = Archive.new("fat", encoder) a.meta.source = { format = "fat" } return a end return FatFormat end __FILES["archive/grp"] = function() -- archive/grp: Build engine GRP ("KenSilverman", u32 count, 16-byte entries: 12-byte name + u32 size, then the data), -- from Ken Silverman's description; no code taken. Supports: read (lazy), write (names stored as given, at most 12 -- bytes). Not supported: the "GRP 2" / RFF / SSI variants. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Sniff = __include("core/Sniff") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Grp = { name = "grp", category = "archive", extensions = { "grp" }, mime = { "application/x-build-grp" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, caps = { decode = true, encode = true }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { maxEntries: number? } -- default 1e6 type EncodeOptions = { upper: boolean? } -- Build looks names up case-insensitively; default false -- ------------------------------------------------------------------------------------------------ constants local MAGIC = "KenSilverman" -- ------------------------------------------------------------------------------------------------ sniff function Grp.sniff(r: Bytes.Reader): number return Sniff.magic(r, MAGIC) end -- ------------------------------------------------------------------------------------------------ decode local function encode(archive: any, opts: any?): (buffer?, Err.Err?) return Grp.encode(archive, opts) end function Grp.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if not r:match(MAGIC) then return nil, Err.new(Err.CORRUPT, "bad magic", 0) end local count = r:u32le() if r.err then return nil, r.err end if count > (opts and opts.maxEntries or 1e6) then return nil, Err.new(Err.LIMIT, "too many entries: " .. count) end if count * 16 > r:remaining() then return nil, Err.new(Err.TRUNCATED, "directory past the end", 12) end local a = Archive.new("grp", encode) local at = 16 + count * 16 local size = r.limit - r.base for i = 0, count - 1 do local name = r:fixed(12) local n = r:u32le() if at + n > size then return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", 16 + i * 16) end Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) }) at += n end if r.err then return nil, r.err end a.meta.source = { format = "grp", entries = count } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Grp.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) local items, err = Archive.collect(archive) if not items then return nil, err end local files: { { name: string, data: buffer } } = {} for _, it in items do if not it.entry.dir then local name = it.entry.name if opts and opts.upper then name = string.upper(name) end if #name > 12 then return nil, Err.new(Err.ARG, "name longer than 12 bytes: " .. name) end table.insert(files, { name = name, data = it.data }) end end local w = Bytes.writer() w:string(MAGIC) w:u32le(#files) for _, f in files do w:string(f.name) w:fill(0, 12 - #f.name) w:u32le(buffer.len(f.data)) end for _, f in files do w:bytes(f.data) end return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras function Grp.new(): any local a = Archive.new("grp", encode) a.meta.source = { format = "grp" } return a end return Grp end __FILES["archive/gzip"] = function() -- archive/gzip: gzip (RFC 1952) as a single-stream archive of one entry (FNAME, MTIME; codecs/compress/Deflate). -- Supports: concatenated members as one stream (as gzip -d); write (several entries: a .tar.gz). -- Not supported: FHCRC verification. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Crc32 = __include("core/Crc32") local Deflate = __include("codecs/compress/Deflate") local Archive = __include("containers/Archive") local Tar = __include("containers/Tar") -- ------------------------------------------------------------------------------------------------ contract local Gzip = { name = "gzip", category = "archive", extensions = { "gz", "tgz", "gzip" }, mime = { "application/gzip" }, deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" }, caps = { decode = true, encode = true, stream = true }, } type DecodeOptions = { name: string? } type EncodeOptions = { level: number?, -- 0..9, default 6 name: string?, -- default: the entry's name; none for a buffer mtime: number?, -- default: the entry's mtime, else 0 } -- ------------------------------------------------------------------------------------------------ sniff function Gzip.sniff(r: Bytes.Reader): number return if r:peek(3) == "\31\139\8" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode local function header(b: buffer, o: number, e: number): { [string]: any } local h: { [string]: any } = {} if o + 10 > e then return h end local flg = buffer.readu8(b, o + 3) h.mtime = buffer.readu32(b, o + 4) h.os = buffer.readu8(b, o + 9) local q = o + 10 if bit32.band(flg, 4) ~= 0 and q + 2 <= e then q += 2 + buffer.readu16(b, q) end for _, f in { { 8, "name" }, { 16, "comment" } } :: { { any } } do if bit32.band(flg, f[1]) ~= 0 then local s = q while q < e and buffer.readu8(b, q) ~= 0 do q += 1 end if q < e then h[f[2]] = buffer.readstring(b, s, q - s) end q += 1 end end return h end function Gzip.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local out, err = Deflate.gunzip(r.buf, r.base, r.limit - r.base) if not out then return nil, err end local h = header(r.buf, r.base, r.limit) local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?) return Gzip.encode(arc, o) end) a.meta.stream = true a.meta.source = { format = "gzip", os = h.os } a.meta.comment = h.comment local name = h.name if not name or name == "" or string.find(name, "[/\\]") then name = Archive.streamName(opts, Gzip.extensions) end Archive.put(a, { name = name, size = buffer.len(out), compressedSize = r.limit - r.base, method = "deflate", mtime = if h.mtime and h.mtime > 0 then h.mtime :: number else nil, dir = false, data = out, }) return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local level = if o.level == nil then 6 else o.level if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then return nil, Err.new(Err.ARG, "level must be 0..9") end local data: buffer local name: string? = o.name local mtime: number = o.mtime or 0 if type(value) == "buffer" then data = value elseif type(value) == "string" then data = buffer.fromstring(value) else local items = Archive.entries(value) if not items then return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") end local files: typeof(items) = {} for _, it in items do if not it.entry.dir then table.insert(files, it) end end if #files == 1 and #items == 1 then local b, err = files[1].read() if not b then return nil, err end data = b name = name or files[1].entry.name mtime = o.mtime or files[1].entry.mtime or 0 else -- several entries: a tar inside local list = {} for _, it in items do local e: any = it.entry local b = nil if not e.dir then local rb, err = it.read() if not rb then return nil, err end b = rb end table.insert(list, { name = e.name, data = b, dir = e.dir, mtime = e.mtime, mode = e.mode }) end local t, terr = Tar.write(list) if not t then return nil, terr end data = t end end if type(mtime) ~= "number" or mtime < 0 or mtime >= 2 ^ 32 then mtime = 0 end local raw, cerr = Deflate.compress(data, { level = level }) if not raw then return nil, cerr end local w = Bytes.writer(buffer.len(raw) + 32 + (if name then #name else 0)) w:string("\31\139\8") w:u8(if name then 8 else 0) w:u32le(math.floor(mtime)) w:u8(if level >= 9 then 2 elseif level <= 1 then 4 else 0) w:u8(255) if name then local z = string.find(name, "\0", 1, true) w:cstring(if z then string.sub(name, 1, z - 1) else name) end w:bytes(raw) w:u32le(Crc32.raw(data, 0, buffer.len(data))) w:u32le(buffer.len(data) % 4294967296) return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras function Gzip.new(data: (buffer | string)?, name: string?): any local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?) return Gzip.encode(arc, o) end) a.meta.stream = true a.meta.source = { format = "gzip" } if data then a:add(name or "data", data) end return a end return Gzip end __FILES["archive/iso"] = function() -- archive/iso: ISO 9660 images through containers/Iso9660. Supports: plain names, Joliet, Rock Ridge (RR, else Joliet, -- else plain), multi-extent files, El Torito boot catalog (meta.boot). Not supported: writing, UDF, interleaved files -- (UNSUPPORTED), zisofs (stored bytes), multi-session images (the first session). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Archive = __include("containers/Archive") local Iso9660 = __include("containers/Iso9660") -- ------------------------------------------------------------------------------------------------ contract local Iso = { name = "iso", category = "archive", extensions = { "iso" }, mime = { "application/x-iso9660-image" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" }, caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } }, } type DecodeOptions = { prefer: ("rockridge" | "joliet" | "iso9660")?, -- default: Rock Ridge, else Joliet, else plain maxEntries: number?, -- default 1e6 } -- ------------------------------------------------------------------------------------------------ sniff function Iso.sniff(r: Bytes.Reader): number return if r:peek(5, 16 * 2048 + 1) == "CD001" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode function Iso.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local list, info = Iso9660.read(r.buf, r.base, r.limit - r.base, opts) if not list then return nil, info end local a = Archive.new("iso") local b, limit = r.buf, r.limit for _, e in list do local data = e.type == "0" and e.size > 0 Archive.put(a, { name = e.name, size = e.size, dir = e.dir, mtime = e.mtime, type = e.type, mode = e.mode, uid = e.uid, gid = e.gid, nlink = e.nlink, link = e.link, rdev = e.rdev, hidden = e.hidden, method = if e.zisofs then "zisofs" else "store", load = if data then function(): (buffer?, Err.Err?) return Iso9660.extract(b, e, limit) end else nil, }) end a.meta.boot = info.boot info.boot = nil a.meta.iso = info a.meta.source = { format = "iso", tree = info.tree } return a, nil end return Iso end __FILES["archive/lha"] = function() -- archive/lha: LHA / LZH (and LArc .lzs; Yoshizaki's LHa notes, lhasa's lha_file_header.c, ISC): header levels 0-3, -- methods lh0 / lz4 / lhd / lh1 / lh4-lh7 / lhx / lzs / lz5, CRC-16 (ARC), "name|target" symlinks; writes level 2, -- stored. Not supported: PMarc pm0-pm2, compression when writing, multi-volume, stubs beyond the first 64 KB. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Crc16 = __include("core/Crc16") local Lzh = __include("codecs/compress/Lzh") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Lha = { name = "lha", category = "archive", extensions = { "lzh", "lha", "lzs" }, mime = { "application/x-lzh-compressed" }, deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" }, caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } }, } type DecodeOptions = { maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 65536 } type EncodeOptions = {} -- ------------------------------------------------------------------------------------------------ constants local METHODS: { [string]: boolean } = { ["-lh0-"] = true, ["-lz4-"] = true, ["-lhd-"] = true, ["-lh1-"] = true, ["-lh4-"] = true, ["-lh5-"] = true, ["-lh6-"] = true, ["-lh7-"] = true, ["-lhx-"] = true, ["-lzs-"] = true, ["-lz5-"] = true, ["-lh2-"] = true, ["-lh3-"] = true, ["-pm0-"] = true, ["-pm1-"] = true, ["-pm2-"] = true, ["-lk7-"] = true, } -- ------------------------------------------------------------------------------------------------ sniff local function isHeader(s: string): boolean if #s < 22 then return false end local m = string.sub(s, 3, 7) local level = string.byte(s, 21) return METHODS[m] == true and level <= 3 end function Lha.sniff(r: Bytes.Reader): number if isHeader(r:peek(22)) then return 0.95 end return 0 end -- ------------------------------------------------------------------------------------------------ decode -- "." / ".." collapsed as lhasa does local function path(s: string): string s = string.gsub(s, "[\\\255]", "/") local parts = {} for part in string.gmatch(s, "[^/]+") do if part ~= "." and part ~= ".." then table.insert(parts, part) end end return table.concat(parts, "/") .. (if string.sub(s, -1) == "/" and #parts > 0 then "/" else "") end type Header = { method: string, packed: number, size: number, mtime: number?, level: number, name: string, dir: string?, crc: number?, mode: number?, uid: number?, gid: number?, uname: string?, gname: string?, attr: number?, comment: string?, os: string?, dataAt: number, } local function extended(r: Bytes.Reader, p: number, w: number, first: number, h: Header, limit: number): (number?, string?) local size = first local guard = 0 while size ~= 0 do guard += 1 if guard > 4096 or size < w + 1 or p + size > limit then return nil, "bad extended header" end local e = r:sub(p, size) local kind = e:u8() local body = size - 1 - w if kind == 0x01 then h.name = e:string(body) elseif kind == 0x02 then h.dir = e:string(body) elseif kind == 0x3F or kind == 0x71 then h.comment = e:string(body) elseif kind == 0x40 and body >= 2 then h.attr = e:u16le() elseif kind == 0x50 and body >= 2 then h.mode = e:u16le() elseif kind == 0x51 and body >= 4 then h.gid, h.uid = e:u16le(), e:u16le() elseif kind == 0x52 then h.gname = e:string(body) elseif kind == 0x53 then h.uname = e:string(body) elseif kind == 0x54 and body >= 4 then h.mtime = e:u32le() elseif kind == 0x42 and body >= 16 then h.packed, h.size = e:u64le(), e:u64le() end e:seek(size - w) local nextSize = if w == 2 then e:u16le() else e:u32le() if e.err then return nil, "truncated extended header" end p += size size = nextSize end return p, nil end local OS = { [0x4D] = "msdos", [0x55] = "unix", [0x32] = "os2", [0x39] = "os9", [0x4B] = "os68k", [0x33] = "os386", [0x48] = "human68k", [0x43] = "cpm", [0x46] = "flex", [0x6D] = "mac", [0x77] = "windows95", [0x57] = "windowsnt", [0x52] = "runser", [0x54] = "townsos", [0x58] = "xosk", [0x41] = "amiga", [0x61] = "atari", [0x4A] = "java" } local function header(r: Bytes.Reader, p: number): (Header?, string?) local limit = r:size() if p >= limit or r:sub(p, 1):u8() == 0 then return nil, nil end if p + 22 > limit then return nil, "truncated header" end local s = r:sub(p, 26) local b0 = s:u8() s:u8() local method = s:string(5) local packed, size, stamp = s:u32le(), s:u32le(), s:u32le() s:u8() local level = s:u8() if not METHODS[method] then return nil, "bad method " .. method end local h: Header = { method = string.sub(method, 2, 4), packed = packed, size = size, level = level, name = "", dataAt = 0 } if level == 0 or level == 1 then local hsize = b0 + 2 if p + hsize > limit or hsize < 24 then return nil, "truncated header" end local hr = r:sub(p + 21, hsize - 21) local nlen = hr:u8() h.name = hr:string(nlen) h.crc = hr:u16le() h.mtime = Archive.fromDos(stamp) if level == 0 then -- an optional Unix extension: 'U', mtime, mode, uid, gid if hr:remaining() >= 11 and (hr:peekU8() == 0x55 or hr:peekU8() == 0x4B) then h.os = if hr:u8() == 0x55 then "unix" else "os68k" h.mtime = hr:u32le() h.mode = hr:u16le() h.uid, h.gid = hr:u16le(), hr:u16le() end h.dataAt = p + hsize else h.os = OS[hr:u8()] local first = r:sub(p + hsize - 2, 2):u16le() local e, err = extended(r, p + hsize, 2, first, h, limit) if not e then return nil, err end h.packed = packed - (e - (p + hsize)) h.dataAt = e end if hr.err then return nil, "truncated header" end elseif level == 2 then local total = r:sub(p, 2):u16le() local hr = r:sub(p + 21, 5) h.crc = hr:u16le() local osByte = hr:u8() h.os = OS[osByte] if osByte == 0x4B then total += 2 -- LHa for OS-9/68k writes the header length without its own two bytes (as lhasa compensates) end local first = hr:u16le() h.mtime = stamp local e, err = extended(r, p + 26, 2, first, h, limit) if not e or hr.err then return nil, err or "truncated header" end h.dataAt = p + total if total < 26 or h.dataAt > limit then return nil, "bad level 2 header size" end elseif level == 3 then local hr = r:sub(p + 21, 11) h.crc = hr:u16le() h.os = OS[hr:u8()] local total = hr:u32le() local first = hr:u32le() h.mtime = stamp local e, err = extended(r, p + 32, 4, first, h, limit) if not e or hr.err then return nil, err or "truncated header" end h.dataAt = p + total if total < 32 or h.dataAt > limit then return nil, "bad level 3 header size" end else return nil, "unsupported: header level " .. level end return h, nil end local LZH_METHOD = { lh1 = "lh1", lh4 = "lh4", lh5 = "lh5", lh6 = "lh6", lh7 = "lh7", lhx = "lhx", lzs = "lzs", lz5 = "lz5" } local function encoder(a: any, o: any?): (buffer?, Err.Err?) return Lha.encode(a, o) end function Lha.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local maxBytes = o.maxBytes or 2 ^ 30 local maxEntries = o.maxEntries or 65536 local p = 0 if not isHeader(r:peek(22)) then local head = r:peek(65536) local at = nil for k = 1, #head - 22 do if string.byte(head, k + 2) == 45 and isHeader(string.sub(head, k, k + 21)) then at = k - 1 break end end if not at then return nil, Err.new(Err.CORRUPT, "no LHA header") end p = at end local a = Archive.new("lha", encoder) local count = 0 local levels = {} while true do local h, err = header(r, p) if err then return nil, Err.from(err, r.base + p) end if not h then break end count += 1 if count > maxEntries then return nil, Err.new(Err.LIMIT, "more than maxEntries entries") end levels[h.level] = true if h.packed < 0 or h.dataAt + h.packed > r:size() then return nil, Err.new(Err.TRUNCATED, "entry " .. path(h.name) .. " data past the end", r.base + h.dataAt) end -- MS-DOS-like archives store names in capitals: all-caps names read in lower case, as lhasa / LHa do local os = h.os if os == nil or os == "msdos" or os == "atari" or os == "os2" then if not string.find(h.name .. (h.dir or ""), "%l") then h.name = string.lower(h.name) h.dir = if h.dir then string.lower(h.dir) else nil end end -- the full path (a Unix symlink "name|target" may be split across the directory and file name headers) local name = path(h.name) if h.dir and h.dir ~= "" then local d = path(h.dir) if string.sub(d, -1) ~= "/" then d ..= "/" end name = d .. name end local link: string? = nil local bar = string.find(name, "|", 1, true) if bar then name, link = string.sub(name, 1, bar - 1), string.sub(name, bar + 1) end local isDir = h.method == "lhd" if isDir and link == nil and string.sub(name, -1) ~= "/" then name ..= "/" end local e: any = { name = name, size = if isDir or link then 0 else h.size, compressedSize = h.packed, method = h.method, mtime = h.mtime, dir = isDir and link == nil, mode = h.mode, uid = h.uid, gid = h.gid, uname = h.uname, gname = h.gname, attr = h.attr, comment = h.comment, os = h.os, level = h.level, crc = h.crc, } if link then e.link = link e.type = "symlink" elseif not isDir and h.size > 0 then if h.size > maxBytes then return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") end local at, packed, size, method, crc = h.dataAt, h.packed, h.size, h.method, h.crc local buf, base = r.buf, r.base e.load = function(): (buffer?, Err.Err?) local out: buffer?, derr: string? if method == "lh0" or method == "lz4" then if packed < size then return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size") end out = buffer.create(size) buffer.copy(out :: buffer, 0, buf, base + at, size) elseif LZH_METHOD[method] then out, derr = Lzh.decode(buf, base + at, packed, size, LZH_METHOD[method]) else return nil, Err.new(Err.UNSUPPORTED, "method " .. method) end if not out then return nil, Err.from(derr) end if crc and Crc16.arc(out, 0, size) ~= crc then return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch") end return out, nil end end Archive.put(a, e) p = h.dataAt + h.packed end a.meta.source = { format = "lha", levels = levels } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Lha.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local items = Archive.entries(value) if not items then return nil, Err.new(Err.ARG, "expected an Archive") end local out = Bytes.writer() for _, it in items do local e: any = it.entry local data = buffer.create(0) if not e.dir then local b, err = it.read() if not b then return nil, err end data = b end local full = string.gsub(e.name, "/+$", "") local dirPart, base = string.match(full, "^(.*/)([^/]*)$") if not dirPart then dirPart, base = "", full end if e.dir then dirPart, base = full .. "/", "" end local h = Bytes.writer() h:u16le(0) h:string(if e.dir then "-lhd-" else "-lh0-") h:u32le(buffer.len(data)) h:u32le(buffer.len(data)) h:u32le(if type(e.mtime) == "number" and e.mtime >= 0 then math.floor(e.mtime) % 4294967296 else 0) h:u8(0x20) h:u8(2) h:u16le(Crc16.arc(data, 0, buffer.len(data))) h:u8(0x55) -- 'U'nix -- extended headers: [type][body][size of the next one]; the first size ends the base header local exts: { { any } } = { { 0x00, "\0\0" }, { 0x01, base } } if dirPart ~= "" then table.insert(exts, { 0x02, (string.gsub(dirPart :: string, "/", "\255")) }) end if type(e.mode) == "number" then local m = bit32.band(e.mode, 0xFFF) + (if e.dir then 0x4000 else 0x8000) table.insert(exts, { 0x50, string.char(m % 256, m // 256) }) end h:u16le(#exts[1][2] + 3) for i, x in exts do h:u8(x[1]) h:string(x[2]) h:u16le(if exts[i + 1] then #exts[i + 1][2] + 3 else 0) end local hb = h:finish() local total = buffer.len(hb) if total > 65535 then return nil, Err.new(Err.ARG, "header too long for " .. e.name) end buffer.writeu16(hb, 0, total) -- the header CRC covers the whole header with its own field zero local crcAt = 24 + 2 + 1 -- first ext: size (2) at 24, type at 26, CRC at 27 buffer.writeu16(hb, crcAt, Crc16.arc(hb, 0, total)) out:bytes(hb) out:bytes(data) end out:u8(0) return out:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras function Lha.new(): any local a = Archive.new("lha", encoder) a.meta.source = { format = "lha" } return a end return Lha end __FILES["archive/lz4"] = function() -- archive/lz4: LZ4 frames (lz4_Frame_format.md 1.6.x) as a single-stream archive. Supports: concatenated, skippable -- (0x184D2A50..5F) and legacy (0x184C2102, 8 MB blocks) frames, linked blocks, 64 KB .. 4 MB, XXH32 checksums; writes -- one frame of independent blocks. Not supported: dictionaries, writing linked blocks or legacy frames. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Lz4 = __include("codecs/compress/Lz4") local Xxh32 = __include("codecs/compress/Xxh32") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Lz4Format = { name = "lz4", category = "archive", extensions = { "lz4", "tlz4" }, mime = { "application/x-lz4" }, deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" }, caps = { decode = true, encode = true, stream = true, legacy = true }, } type DecodeOptions = { maxBytes: number?, -- default 2^30 verify: boolean?, -- default true; the header checksum is always checked name: string?, } type EncodeOptions = { blockSize: number?, -- 65536, 262144, 1048576 or 4194304 (default 4 MB, as the lz4 tool) blockChecksum: boolean?, -- default false contentChecksum: boolean?, -- default true contentSize: boolean?, -- default false } -- ------------------------------------------------------------------------------------------------ constants local MAGIC = 0x184D2204 local LEGACY = 0x184C2102 local LEGACY_BLOCK = 8 * 1048576 local SIZES: { [number]: number } = { [4] = 65536, [5] = 262144, [6] = 1048576, [7] = 4194304 } -- ------------------------------------------------------------------------------------------------ sniff function Lz4Format.sniff(r: Bytes.Reader): number local m = r:peek(4) if m == "\4\34\77\24" then return 1 elseif m == "\2\33\76\24" then return 0.9 elseif #m == 4 and string.byte(m, 1) >= 0x50 and string.byte(m, 1) <= 0x5F and string.sub(m, 2) == "\42\77\24" then -- a skippable frame (zstd shares the magic): an LZ4 frame after it local h = r:peek(4, 4) if #h == 4 then local n = string.byte(h, 1) + string.byte(h, 2) * 256 + string.byte(h, 3) * 65536 + string.byte(h, 4) * 16777216 if r:peek(4, 8 + n) == "\4\34\77\24" then return 1 end end end return 0 end -- ------------------------------------------------------------------------------------------------ decode local function skippable(m: number): boolean return m >= 0x184D2A50 and m <= 0x184D2A5F end type Out = { buf: buffer, n: number, max: number } local function room(out: Out, k: number): boolean local need = out.n + k if need > out.max then return false end if need > buffer.len(out.buf) then local nb = buffer.create(math.min(math.max(buffer.len(out.buf) * 2, need), out.max)) buffer.copy(nb, 0, out.buf, 0, out.n) out.buf = nb end return true end local function frame(b: buffer, p: number, e: number, out: Out, verify: boolean): (number?, Err.Err?) if p + 7 > e then return nil, Err.new(Err.TRUNCATED, "frame header past the end", p) end local flg, bd = buffer.readu8(b, p + 4), buffer.readu8(b, p + 5) if bit32.rshift(flg, 6) ~= 1 then return nil, Err.new(Err.UNSUPPORTED, "frame version " .. bit32.rshift(flg, 6), p + 4) end if bit32.band(flg, 2) ~= 0 or bit32.band(bd, 0x8F) ~= 0 then return nil, Err.new(Err.CORRUPT, "reserved descriptor bits set", p + 4) end local independent = bit32.band(flg, 0x20) ~= 0 local blockSum = bit32.band(flg, 0x10) ~= 0 local hasSize = bit32.band(flg, 0x08) ~= 0 local contentSum = bit32.band(flg, 0x04) ~= 0 local hasDict = bit32.band(flg, 0x01) ~= 0 local bmax = SIZES[bit32.rshift(bd, 4)] if not bmax then return nil, Err.new(Err.CORRUPT, "bad block maximum size", p + 5) end local q = p + 6 local size: number? = nil if hasSize then if q + 8 > e then return nil, Err.new(Err.TRUNCATED, "frame header past the end", q) end size = buffer.readu32(b, q) + buffer.readu32(b, q + 4) * 4294967296 q += 8 end if hasDict then return nil, Err.new(Err.UNSUPPORTED, "frames with a dictionary", q) end if q + 1 > e then return nil, Err.new(Err.TRUNCATED, "frame header past the end", q) end local hc = bit32.band(bit32.rshift(Xxh32.hash(b, p + 4, q - p - 4), 8), 255) if hc ~= buffer.readu8(b, q) then return nil, Err.new(Err.CHECKSUM, "frame header checksum mismatch", q) end q += 1 if size and out.n + size > out.max then return nil, Err.new(Err.LIMIT, "content over " .. out.max .. " bytes", p) end local start = out.n while true do if q + 4 > e then return nil, Err.new(Err.TRUNCATED, "block header past the end", q) end local bs = buffer.readu32(b, q) q += 4 if bs == 0 then break end local raw = bit32.band(bs, 0x80000000) ~= 0 local n = bit32.band(bs, 0x7FFFFFFF) if n > bmax then return nil, Err.new(Err.CORRUPT, "block larger than the maximum", q - 4) end if q + n + (if blockSum then 4 else 0) > e then return nil, Err.new(Err.TRUNCATED, "block past the end", q) end if blockSum and verify and Xxh32.hash(b, q, n) ~= buffer.readu32(b, q + n) then return nil, Err.new(Err.CHECKSUM, "block checksum mismatch", q + n) end if not room(out, if raw then n else bmax) and not room(out, if raw then n else math.min(bmax, out.max - out.n)) then return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) end if raw then buffer.copy(out.buf, out.n, b, q, n) out.n += n else local lim = math.min(out.n + bmax, buffer.len(out.buf)) local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim, if independent then out.n else start) if not dEnd then if msg and string.sub(msg, 1, 6) == "limit:" and lim < out.n + bmax then return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) end return nil, Err.from(msg, q) end out.n = dEnd end q += n + (if blockSum then 4 else 0) end if contentSum then if q + 4 > e then return nil, Err.new(Err.TRUNCATED, "content checksum past the end", q) end if verify and Xxh32.hash(out.buf, start, out.n - start) ~= buffer.readu32(b, q) then return nil, Err.new(Err.CHECKSUM, "content checksum mismatch", q) end q += 4 end if size and out.n - start ~= size then return nil, Err.new(Err.CORRUPT, "content size mismatch", p + 6) end return q, nil end -- a legacy frame at p: blocks of up to 8 MB until the input ends or a magic number follows local function legacy(b: buffer, p: number, e: number, out: Out): (number?, Err.Err?) local q = p + 4 while q + 4 <= e do local n = buffer.readu32(b, q) if n == MAGIC or n == LEGACY or skippable(n) then break end q += 4 if q + n > e then return nil, Err.new(Err.TRUNCATED, "block past the end", q) end if not room(out, LEGACY_BLOCK) and not room(out, math.min(LEGACY_BLOCK, out.max - out.n)) then return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) end local lim = math.min(out.n + LEGACY_BLOCK, buffer.len(out.buf)) local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim) if not dEnd then return nil, Err.from(msg, q) end out.n = dEnd q += n end return q, nil end function Lz4Format.decompress(src: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (buffer?, Err.Err?) local b, o, n, aerr = Bytes.span("Lz4.decompress", src, offset, length) if not b then return nil, aerr end local maxBytes = (opts and opts.maxBytes) or 2 ^ 30 local verify = not (opts and opts.verify == false) local out: Out = { buf = buffer.create(math.min(math.max(n * 3, 256), maxBytes)), n = 0, max = maxBytes } local p, e = o, o + n local frames = 0 while p + 4 <= e do local m = buffer.readu32(b, p) local q, err if m == MAGIC then q, err = frame(b, p, e, out, verify) frames += 1 elseif m == LEGACY then q, err = legacy(b, p, e, out) frames += 1 elseif skippable(m) then if p + 8 > e then return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p) end q = p + 8 + buffer.readu32(b, p + 4) if q > e then return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p) end elseif frames > 0 then break -- trailing data after the frames (as lz4 -d, which warns) else return nil, Err.new(Err.CORRUPT, "bad magic", p) end if not q then return nil, err end p = q :: number end if frames == 0 then return nil, Err.new(if n < 4 then Err.TRUNCATED else Err.CORRUPT, "no LZ4 frame", o) end local res = buffer.create(out.n) buffer.copy(res, 0, out.buf, 0, out.n) return res, nil end local function encode(value: any, opts: any?): (buffer?, Err.Err?) return Lz4Format.encode(value, opts) end function Lz4Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local n = r.limit - r.base local out, err = Lz4Format.decompress(r.buf, r.base, n, o) if not out then return nil, err end local a = Archive.new("lz4", encode) a.meta.stream = true a.meta.source = { format = "lz4", legacy = r:peek(4) == "\2\33\76\24" } local name = Archive.streamName(o, { "lz4" }) local stem, ext = string.match(name, "^(.+)%.(%w+)$") if stem and ext and string.lower(ext) == "tlz4" then name = stem .. ".tar" end Archive.put(a, { name = name, size = buffer.len(out), compressedSize = n, method = "lz4", dir = false, data = out }) return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffer?, Err.Err?) local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil) if not b then return nil, aerr end local op: EncodeOptions = opts or {} local bsize = op.blockSize or 4194304 local bd = nil for k, v in SIZES do if v == bsize then bd = k end end if not bd then return nil, Err.new(Err.ARG, "blockSize must be 65536, 262144, 1048576 or 4194304") end local blockSum = op.blockChecksum == true local contentSum = op.contentChecksum ~= false local withSize = op.contentSize == true local w = Bytes.writer(n + n // 200 + 64) w:u32le(MAGIC) local flg = 0x40 + 0x20 + (if blockSum then 0x10 else 0) + (if withSize then 0x08 else 0) + (if contentSum then 0x04 else 0) w:u8(flg) w:u8(bd * 16) if withSize then w:u32le(n % 4294967296) w:u32le(n // 4294967296) end local hc = bit32.band(bit32.rshift(Xxh32.hash(w.buf, 4, w.pos - 4), 8), 255) w:u8(hc) local scratch = buffer.create(Lz4.bound(math.min(bsize, math.max(n, 1)))) local p = o while p < o + n do local k = math.min(bsize, o + n - p) local c = Lz4.encodeInto(b, p, k, scratch, 0) local at = w.pos if c < k then w:u32le(c) local q = w:reserve(c) buffer.copy(w.buf, q, scratch, 0, c) w.pos = q + c else w:u32le(k + 0x80000000) local q = w:reserve(k) buffer.copy(w.buf, q, b, p, k) w.pos = q + k end if blockSum then local len = w.pos - at - 4 w:u32le(Xxh32.hash(w.buf, at + 4, len)) end p += k end w:u32le(0) if contentSum then w:u32le(Xxh32.hash(b, o, n)) end return w:finish(), nil end function Lz4Format.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local data, err = Archive.streamData(value) if not data then return nil, err end return Lz4Format.compress(data, opts) end return Lz4Format end __FILES["archive/macbinary"] = function() -- archive/macbinary: MacBinary I / II / III (128-byte header, forks padded to 128, Get Info comment; II / III -- CRC-16/XMODEM, III 'mBIN'), from the MacBinary II / III specs (Lempereur et al.), as containers/MacFile. -- Supports: read, write III. Not supported: the secondary header's content (skipped). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Crc16 = __include("core/Crc16") local Archive = __include("containers/Archive") local MacFile = __include("containers/MacFile") -- ------------------------------------------------------------------------------------------------ contract local MacBinary = { name = "macbinary", category = "archive", extensions = { "bin", "macbin" }, mime = { "application/x-macbinary" }, deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, caps = { decode = true, encode = true, forks = true, variants = { "I", "II", "III" } }, } type DecodeOptions = { maxBytes: number? } -- default 2^30 type EncodeOptions = { name: string? } -- ------------------------------------------------------------------------------------------------ sniff local function version(b: buffer, o: number, len: number): string? if len < 128 then return nil end local u8 = function(i: number): number return buffer.readu8(b, o + i) end if u8(0) ~= 0 or u8(74) ~= 0 then return nil end local nameLen = u8(1) if nameLen < 1 or nameLen > 63 then return nil end local function be32(i: number): number return u8(i) * 16777216 + u8(i + 1) * 65536 + u8(i + 2) * 256 + u8(i + 3) end local dlen, rlen = be32(83), be32(87) if dlen > 0x7FFFFFFF or rlen > 0x7FFFFFFF then return nil end local crc = u8(124) * 256 + u8(125) if crc == Crc16.ccitt(b, o, 124) and (crc ~= 0 or u8(122) >= 129) then return if buffer.readstring(b, o + 102, 4) == "mBIN" then "III" else "II" end if buffer.readstring(b, o + 102, 4) == "mBIN" then return nil -- III with a bad CRC end -- MacBinary I: byte 82 zero, bytes 99..125 zero, the forks within the file if u8(82) ~= 0 then return nil end for i = 99, 125 do if u8(i) ~= 0 then return nil end end local need = 128 + math.ceil(dlen / 128) * 128 + rlen return if need <= len + 127 then "I" else nil end function MacBinary.sniff(r: Bytes.Reader): number local n = math.min(r:remaining(), 128) if n < 128 then return 0 end local v = version(r.buf, r.base + r.pos, r.limit - r.base - r.pos) return if v == "III" then 0.95 elseif v == "II" then 0.8 elseif v == "I" then 0.3 else 0 end -- ------------------------------------------------------------------------------------------------ decode local function encoder(a: any, o: any?): (buffer?, Err.Err?) return MacBinary.encode(a, o) end local function pad(n: number): number return math.ceil(n / 128) * 128 end function MacBinary.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local len = r.limit - r.base local v = version(r.buf, r.base, len) if not v then if len >= 128 and buffer.readstring(r.buf, r.base + 102, 4) == "mBIN" then return nil, Err.new(Err.CHECKSUM, "header CRC mismatch") end return nil, Err.new(if len < 128 then Err.TRUNCATED else Err.CORRUPT, "not a MacBinary header") end local h = r:sub(0, 128) h:seek(1) local name = h:string(h:u8()) h:seek(65) local ftype, creator = h:string(4), h:string(4) local flagsHi = h:u8() h:seek(83) local dlen, rlen = h:u32be(), h:u32be() local created, modified = h:u32be(), h:u32be() local commentLen = h:u16be() local flagsLo = h:u8() h:seek(120) local secondary = h:u16be() if v == "I" then commentLen, flagsLo, secondary = 0, 0, 0 end if dlen + rlen > (o.maxBytes or 2 ^ 30) then return nil, Err.new(Err.LIMIT, "forks larger than maxBytes") end r:seek(128 + pad(secondary)) local data = r:bytes(dlen) r:seek(128 + pad(secondary) + pad(dlen)) local rsrc = r:bytes(rlen) local comment: string? = nil if commentLen > 0 and r:seek(128 + pad(secondary) + pad(dlen) + pad(rlen)) then comment = MacFile.name(r:string(math.min(commentLen, r:remaining()))) end if r.err then return nil, r.err end local a = Archive.new("macbinary", encoder) MacFile.put(a, { name = MacFile.name(name), data = data, rsrc = rsrc, type = ftype, creator = creator, flags = flagsHi * 256 + flagsLo, created = MacFile.fromMac(created), modified = MacFile.fromMac(modified), comment = comment, }) a.meta.stream = rlen == 0 a.meta.source = { format = "macbinary", version = v } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function MacBinary.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local files, err = MacFile.collect(value, o.name) if not files then return nil, err end local f = files[1] if not f then return nil, Err.new(Err.ARG, "nothing to encode") end local name = MacFile.roman(f.name) if #name < 1 or #name > 63 then return nil, Err.new(Err.ARG, "the name must be 1..63 bytes") end local dlen, rlen = buffer.len(f.data), buffer.len(f.rsrc) local comment = if f.comment then MacFile.roman(f.comment) else "" local out = buffer.create(128 + pad(dlen) + pad(rlen) + #comment) buffer.writeu8(out, 1, #name) buffer.writestring(out, 2, name) buffer.writestring(out, 65, f.type) buffer.writestring(out, 69, f.creator) buffer.writeu8(out, 73, bit32.rshift(f.flags, 8)) local function be32(at: number, v: number) buffer.writeu32(out, at, bit32.byteswap(v)) end be32(83, dlen) be32(87, rlen) be32(91, MacFile.toMac(f.created or f.modified)) be32(95, MacFile.toMac(f.modified)) buffer.writeu8(out, 99, bit32.rshift(#comment, 8)) buffer.writeu8(out, 100, bit32.band(#comment, 255)) buffer.writeu8(out, 101, bit32.band(f.flags, 255)) buffer.writestring(out, 102, "mBIN") buffer.writeu8(out, 122, 130) buffer.writeu8(out, 123, 129) local crc = Crc16.ccitt(out, 0, 124) buffer.writeu8(out, 124, bit32.rshift(crc, 8)) buffer.writeu8(out, 125, bit32.band(crc, 255)) buffer.copy(out, 128, f.data) buffer.copy(out, 128 + pad(dlen), f.rsrc) buffer.writestring(out, 128 + pad(dlen) + pad(rlen), comment) return out, nil end -- ------------------------------------------------------------------------------------------------ extras -- new() -> an empty MacBinary Archive: a:add(name, data); add "name.rsrc" for a resource fork function MacBinary.new(): any local a = Archive.new("macbinary", encoder) a.meta.source = { format = "macbinary" } return a end return MacBinary end __FILES["archive/mpq"] = function() -- archive/mpq: Blizzard MPQ ("The MoPaQ Archive Format", Olbrantz / Roy; StormLib docs; no code taken). Supports: -- header v1-4, hash / block / hi-block tables, prefixed archives, (listfile), encrypted files, imploded and zlib / -- PKWARE / bzip2 / LZMA / sparse sectors. Not supported: Huffman / ADPCM sectors, patch files, HET / BET, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Archive = __include("containers/Archive") local Deflate = __include("codecs/compress/Deflate") local Bzip2 = __include("codecs/compress/Bzip2") local Lzma = __include("codecs/compress/Lzma") local Explode = __include("codecs/compress/Explode") local Crypt = __include("archive/mpq/Crypt") -- ------------------------------------------------------------------------------------------------ contract local Mpq = { name = "mpq", category = "archive", extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" }, mime = { "application/x-mpq" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" }, caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { names: { string }?, maxEntries: number?, -- default 1e6 maxBytes: number?, -- default 2^30 } -- ------------------------------------------------------------------------------------------------ constants local FLAG_IMPLODE, FLAG_COMPRESS, FLAG_ENCRYPTED, FLAG_FIX_KEY = 0x100, 0x200, 0x10000, 0x20000 local FLAG_PATCH, FLAG_SINGLE, FLAG_DELETE, FLAG_CRC, FLAG_EXISTS = 0x100000, 0x1000000, 0x2000000, 0x4000000, 0x80000000 local KEY_HASH_TABLE, KEY_BLOCK_TABLE = Crypt.hash("(hash table)", 3), Crypt.hash("(block table)", 3) local TWO32 = 4294967296 local band = bit32.band -- ------------------------------------------------------------------------------------------------ sniff function Mpq.sniff(r: Bytes.Reader): number local m = r:peek(4) if m == "MPQ\x1A" or m == "MPQ\x1B" then return 1 end -- a prefixed archive (an installer stub): the header on a 512-byte boundary in the first 64 KB for at = 512, math.min(65536, r:remaining() - 32), 512 do if r:peek(4, at) == "MPQ\x1A" then return 0.6 end end return 0 end -- ------------------------------------------------------------------------------------------------ decode -- sparse: a big-endian u32 size, then runs: 0x80 | (n - 1) followed by n bytes, or n - 3 meaning n zeros local function unsparse(b: buffer, at: number, n: number, want: number): (buffer?, string?) local out = buffer.create(want) local p, stop, o = at + 4, at + n, 0 while p < stop and o < want do local c = buffer.readu8(b, p) p += 1 if c >= 0x80 then local k = c - 0x7F if p + k > stop then return nil, "sparse run past the end" end k = math.min(k, want - o) buffer.copy(out, o, b, p, k) p += k o += k else o = math.min(want, o + c + 3) end end return out, nil end local function decompress(b: buffer, at: number, n: number, want: number): (buffer?, Err.Err?) if n < 1 then return nil, Err.new(Err.CORRUPT, "empty compressed sector") end local mask = buffer.readu8(b, at) local cur: buffer, cat: number, cn: number = b, at + 1, n - 1 if mask == 0x12 then if cn < 14 or buffer.readu8(b, cat) ~= 0 then return nil, Err.new(Err.UNSUPPORTED, "LZMA sector with a filter") end local props = buffer.readstring(b, cat + 1, 5) local out, e = Lzma.lzma(b, cat + 14, cn - 14, props, want, { maxBytes = want }) if not out then return nil, e end return out, nil end if band(mask, 0xC1) ~= 0 then return nil, Err.new(Err.UNSUPPORTED, string.format("Huffman / ADPCM sector (mask 0x%02x)", mask)) end if band(mask, 0x10) ~= 0 then local out, e = Bzip2.decompress(cur, cat, cn, { maxBytes = want }) if not out then return nil, e end cur, cat, cn = out, 0, buffer.len(out) end if band(mask, 0x08) ~= 0 then local out, e = Explode.decompress(cur, cat, cn, want) if not out then return nil, e end cur, cat, cn = out, 0, buffer.len(out) end if band(mask, 0x02) ~= 0 then local out, e = Deflate.zlib(cur, cat, cn) if not out then return nil, e end cur, cat, cn = out, 0, buffer.len(out) end if band(mask, 0x20) ~= 0 then local out, msg = unsparse(cur, cat, cn, want) if not out then return nil, Err.from(msg) end cur, cat, cn = out, 0, buffer.len(out) end if band(mask, 0x3A) ~= mask then return nil, Err.new(Err.UNSUPPORTED, string.format("compression mask 0x%02x", mask)) end if cn ~= want then return nil, Err.new(Err.CORRUPT, "sector decompressed to " .. tostring(cn) .. " bytes, expected " .. tostring(want)) end if cur == b then local len = cn :: number local copy = buffer.create(len) buffer.copy(copy, 0, b, cat, len) return copy, nil end return cur, nil end type Block = { offset: number, csize: number, size: number, flags: number } local function readFile(b: buffer, limit: number, blk: Block, at: number, name: string?, sectorSize: number, maxBytes: number): (buffer?, Err.Err?) local flags = blk.flags if band(flags, FLAG_PATCH) ~= 0 then return nil, Err.new(Err.UNSUPPORTED, "patch files") end if blk.size > maxBytes then return nil, Err.new(Err.LIMIT, "file of " .. blk.size .. " bytes") end if at + blk.csize > limit then return nil, Err.new(Err.TRUNCATED, "file data past the end") end local encrypted = band(flags, FLAG_ENCRYPTED) ~= 0 local key = 0 if encrypted then if not name then return nil, Err.new(Err.UNSUPPORTED, "encrypted file without a known name") end key = Crypt.hash(Crypt.baseName(name), 3) if band(flags, FLAG_FIX_KEY) ~= 0 then key = bit32.bxor((key + blk.offset) % TWO32, blk.size % TWO32) end end local compressed = band(flags, FLAG_COMPRESS + FLAG_IMPLODE) ~= 0 local imploded = band(flags, FLAG_IMPLODE) ~= 0 local function sector(src: buffer, sat: number, sn: number, want: number, k: number): (buffer?, Err.Err?) local raw = buffer.create(sn) buffer.copy(raw, 0, src, sat, sn) if encrypted then Crypt.decrypt(raw, 0, sn, k) end if compressed and sn < want then if imploded then return Explode.decompress(raw, 0, sn, want) end return decompress(raw, 0, sn, want) end if sn ~= want then if sn > want then local cut = buffer.create(want) buffer.copy(cut, 0, raw, 0, want) return cut, nil end return nil, Err.new(Err.CORRUPT, "stored sector of " .. sn .. " bytes, expected " .. want) end return raw, nil end if band(flags, FLAG_SINGLE) ~= 0 then local out, e = sector(b, at, blk.csize, blk.size, key) if out and buffer.len(out) ~= blk.size then return nil, Err.new(Err.CORRUPT, "file size mismatch") end return out, e end local out = buffer.create(blk.size) local nsec = (blk.size + sectorSize - 1) // sectorSize if not compressed then -- stored in sectors (each decrypted with key + its index) for i = 0, nsec - 1 do local want = math.min(sectorSize, blk.size - i * sectorSize) local s, e = sector(b, at + i * sectorSize, want, want, key + i) if not s then return nil, e end buffer.copy(out, i * sectorSize, s, 0, want) end return out, nil end local entries = nsec + 1 + (if band(flags, FLAG_CRC) ~= 0 then 1 else 0) if entries * 4 > blk.csize then return nil, Err.new(Err.CORRUPT, "sector table larger than the file") end local tbl = buffer.create(entries * 4) buffer.copy(tbl, 0, b, at, entries * 4) if encrypted then Crypt.decrypt(tbl, 0, entries * 4, (key - 1) % TWO32) end for i = 0, nsec - 1 do local s0, s1 = buffer.readu32(tbl, i * 4), buffer.readu32(tbl, i * 4 + 4) if s1 < s0 or s1 > blk.csize then return nil, Err.new(Err.CORRUPT, "bad sector offset table") end local want = math.min(sectorSize, blk.size - i * sectorSize) local s, e = sector(b, at + s0, s1 - s0, want, key + i) if not s then return nil, e end if buffer.len(s) ~= want then return nil, Err.new(Err.CORRUPT, "sector " .. i .. " decompressed to " .. buffer.len(s) .. " bytes, expected " .. want) end buffer.copy(out, i * sectorSize, s, 0, want) end return out, nil end local function encode(_archive: any, _opts: any?): (buffer?, Err.Err?) return nil, Err.new(Err.UNSUPPORTED, "MPQ archives are read-only") end local function findHeader(r: Bytes.Reader): number? local size = r.limit - r.base local p = 0 while p + 32 <= size do local m = buffer.readstring(r.buf, r.base + p, 4) if m == "MPQ\x1A" then return p elseif m == "MPQ\x1B" and p + 12 <= size then local at = p + buffer.readu32(r.buf, r.base + p + 8) if at + 32 <= size and buffer.readstring(r.buf, r.base + at, 4) == "MPQ\x1A" then return at end end p += 512 end return nil end function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local found = findHeader(r) if not found then return nil, Err.new(if r:remaining() < 32 then Err.TRUNCATED else Err.CORRUPT, "no MPQ header", 0) end local h: number = found local hr = r:sub(h) hr:skip(4) local headerSize, archiveSize = hr:u32le(), hr:u32le() local version, shift = hr:u16le(), hr:u16le() local hashPos, blockPos, hashCount, blockCount = hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() local hiBlockPos, hashHi, blockHi = 0, 0, 0 if version >= 1 and headerSize >= 44 then hiBlockPos = hr:u64le() hashHi, blockHi = hr:u16le(), hr:u16le() end if hr.err then return nil, hr.err end if shift > 20 then return nil, Err.new(Err.CORRUPT, "bad sector size shift " .. shift, h + 14) end local sectorSize = 512 * 2 ^ shift if hashCount == 0 then return nil, Err.new(Err.UNSUPPORTED, "no classic hash table (HET / BET only)") end local maxEntries: number = opts and opts.maxEntries or 1e6 if hashCount > maxEntries * 4 or blockCount > maxEntries then return nil, Err.new(Err.LIMIT, "too many entries") end local size = r.limit - r.base local hashAt = h + hashPos + hashHi * TWO32 local blockAt = h + blockPos + blockHi * TWO32 if hashAt + hashCount * 16 > size or blockAt + blockCount * 16 > size then return nil, Err.new(Err.TRUNCATED, "hash / block table past the end", h + 16) end local hashes = buffer.create(hashCount * 16) buffer.copy(hashes, 0, r.buf, r.base + hashAt, hashCount * 16) Crypt.decrypt(hashes, 0, hashCount * 16, KEY_HASH_TABLE) local blocksBuf = buffer.create(blockCount * 16) buffer.copy(blocksBuf, 0, r.buf, r.base + blockAt, blockCount * 16) Crypt.decrypt(blocksBuf, 0, blockCount * 16, KEY_BLOCK_TABLE) local hiAt = if hiBlockPos > 0 then h + hiBlockPos else -1 if hiAt >= 0 and hiAt + blockCount * 2 > size then hiAt = -1 end local blocks: { Block } = {} for i = 0, blockCount - 1 do local hi = if hiAt >= 0 then buffer.readu16(r.buf, r.base + hiAt + i * 2) else 0 blocks[i + 1] = { offset = buffer.readu32(blocksBuf, i * 16) + hi * TWO32, csize = buffer.readu32(blocksBuf, i * 16 + 4), size = buffer.readu32(blocksBuf, i * 16 + 8), flags = buffer.readu32(blocksBuf, i * 16 + 12), } end local maxBytes = opts and opts.maxBytes or 2 ^ 30 local mask = hashCount - 1 local pow2 = band(hashCount, mask) == 0 local function lookup(name: string): number? local h0, h1, h2 = Crypt.hash(name, 0), Crypt.hash(name, 1), Crypt.hash(name, 2) local start = if pow2 then band(h0, mask) else h0 % hashCount for k = 0, hashCount - 1 do local o = ((start + k) % hashCount) * 16 local bi = buffer.readu32(hashes, o + 12) if bi == 0xFFFFFFFF then return nil end if bi ~= 0xFFFFFFFE and buffer.readu32(hashes, o) == h1 and buffer.readu32(hashes, o + 4) == h2 and bi < blockCount then return bi + 1 end end return nil end local function usable(bi: number): boolean local f = blocks[bi].flags return band(f, FLAG_EXISTS) ~= 0 and band(f, FLAG_DELETE) == 0 end local function blockData(bi: number, name: string?): (buffer?, Err.Err?) local blk = blocks[bi] return readFile(r.buf, r.limit, blk, r.base + h + blk.offset, name, sectorSize, maxBytes) end local names: { string } = {} for _, internal in { "(attributes)", "(signature)", "(user data)" } do table.insert(names, internal) end local lf = lookup("(listfile)") if lf and usable(lf) then table.insert(names, "(listfile)") local data = blockData(lf, "(listfile)") if data then for line in string.gmatch(buffer.tostring(data), "[^\r\n;]+") do local nm = string.match(line, "^%s*(.-)%s*$") if nm and nm ~= "" then table.insert(names, nm) end end end end if opts and type(opts.names) == "table" then for _, nm in opts.names do if type(nm) == "string" then table.insert(names, nm) end end end local a = Archive.new("mpq", encode) local named: { [number]: string } = {} local function add(bi: number, name: string?) local blk = blocks[bi] local entryName = name or string.format("File%08d.xxx", bi - 1) Archive.put(a, { name = entryName, size = blk.size, compressedSize = blk.csize, dir = false, method = if band(blk.flags, FLAG_IMPLODE) ~= 0 then "implode" elseif band(blk.flags, FLAG_COMPRESS) ~= 0 then "compress" else "store", encrypted = band(blk.flags, FLAG_ENCRYPTED) ~= 0, flags = blk.flags, block = bi - 1, load = function(): (buffer?, Err.Err?) return blockData(bi, name) end, }) end for _, nm in names do local bi = lookup(nm) if bi and usable(bi) and not named[bi] then named[bi] = nm add(bi, nm) end end for bi = 1, blockCount do if not named[bi] and usable(bi) and blocks[bi].size > 0 then add(bi, nil) end end a.meta.source = { format = "mpq", version = version + 1, sectorSize = sectorSize, offset = h, archiveSize = archiveSize, hashTable = hashCount, blockTable = blockCount } return a, nil end -- ------------------------------------------------------------------------------------------------ extras Mpq.hash = Crypt.hash return Mpq end __FILES["archive/mpq/Crypt"] = @native function() -- archive/mpq/Crypt: the MPQ encryption table, name hash (0 = table index, 1 / 2 = name check, 3 = file key) and -- block decryption, from "The MoPaQ Archive Format" (Olbrantz / Roy) and StormLib's docs; no code taken. Mod 2^32. local readu32, writeu32 = buffer.readu32, buffer.writeu32 local bxor, band, bor, lshift, rshift, bnot = bit32.bxor, bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.bnot local Crypt = {} local TWO32 = 4294967296 local TABLE = buffer.create(0x500 * 4) do local seed = 0x00100001 for i1 = 0, 255 do local i2 = i1 for _ = 0, 4 do seed = (seed * 125 + 3) % 0x2AAAAB local t1 = band(seed, 0xFFFF) * 65536 seed = (seed * 125 + 3) % 0x2AAAAB local t2 = band(seed, 0xFFFF) writeu32(TABLE, i2 * 4, t1 + t2) i2 += 0x100 end end end -- name hash: ASCII upper case, '/' as '\' @native function Crypt.hash(name: string, kind: number): number local s1, s2 = 0x7FED7FED, 0xEEEEEEEE local base = kind * 0x100 for i = 1, #name do local c = string.byte(name, i) if c >= 97 and c <= 122 then c -= 32 elseif c == 47 then c = 92 end s1 = bxor(readu32(TABLE, (base + c) * 4), (s1 + s2) % TWO32) s2 = (c + s1 + s2 + lshift(s2, 5) + 3) % TWO32 end return s1 end -- whole u32s; a trailing partial word is left as is @native function Crypt.decrypt(buf: buffer, at: number, n: number, key: number) local s2 = 0xEEEEEEEE local k = key % TWO32 for i = 0, n // 4 - 1 do local o = at + i * 4 s2 = (s2 + readu32(TABLE, (0x400 + band(k, 0xFF)) * 4)) % TWO32 local ch = bxor(readu32(buf, o), (k + s2) % TWO32) k = bor((lshift(bnot(k), 0x15) + 0x11111111) % TWO32, rshift(k, 0x0B)) s2 = (ch + s2 + lshift(s2, 5) + 3) % TWO32 writeu32(buf, o, ch) end end -- the file key uses the base name @native function Crypt.baseName(name: string): string return string.match(name, "([^\\/]*)$") or name end return Crypt end __FILES["archive/pak"] = function() -- archive/pak: Quake / Quake II / Half-Life PAK ("PACK": 56-byte names, 64-byte entries) and SiN ("SPAK": 120-byte -- names), from Quake's common.c (dpackheader_t / dpackfile_t) and the Quake specs; no code taken. Supports: read -- (lazy), write. Not supported: Daikatana's compressed entries. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Sniff = __include("core/Sniff") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Pak = { name = "pak", category = "archive", extensions = { "pak", "sin" }, mime = { "application/x-pak" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, caps = { decode = true, encode = true, variants = { "quake", "sin" } }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { maxEntries: number? } -- default 1e6 type EncodeOptions = { variant: ("quake" | "sin")? } -- default: the source variant, else "quake" -- ------------------------------------------------------------------------------------------------ constants local VARIANTS = { quake = { magic = "PACK", nameLen = 56 }, sin = { magic = "SPAK", nameLen = 120 } } -- ------------------------------------------------------------------------------------------------ sniff function Pak.sniff(r: Bytes.Reader): number if r:remaining() < 12 then return 0 end return math.max(Sniff.magic(r, "PACK", 0, 0.9), Sniff.magic(r, "SPAK", 0, 0.9)) end -- ------------------------------------------------------------------------------------------------ decode local function encode(archive: any, opts: any?): (buffer?, Err.Err?) return Pak.encode(archive, opts) end function Pak.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local magic = r:string(4) local dirOfs, dirLen = r:u32le(), r:u32le() if r.err then return nil, r.err end local variant = if magic == "PACK" then "quake" elseif magic == "SPAK" then "sin" else nil if not variant then return nil, Err.new(Err.CORRUPT, "bad magic", 0) end local nameLen = VARIANTS[variant].nameLen local entrySize = nameLen + 8 local size = r.limit - r.base if dirOfs + dirLen > size then return nil, Err.new(Err.TRUNCATED, "directory past the end", 4) end if dirLen % entrySize ~= 0 then return nil, Err.new(Err.CORRUPT, "directory size is not a multiple of " .. entrySize, 8) end local count = dirLen // entrySize if count > (opts and opts.maxEntries or 1e6) then return nil, Err.new(Err.LIMIT, "too many entries: " .. count) end local a = Archive.new("pak", encode) local d = r:sub(dirOfs, dirLen) for i = 0, count - 1 do local name = d:fixed(nameLen) local at, n = d:u32le(), d:u32le() if d.err then return nil, d.err end if at + n > size then return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", dirOfs + i * entrySize) end Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) }) end a.meta.source = { format = "pak", variant = variant, entries = count } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Pak.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) local items, err = Archive.collect(archive) if not items then return nil, err end local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source local variant = opts and opts.variant or (if type(src) == "table" and src.format == "pak" then src.variant else nil) or "quake" local v = VARIANTS[variant] if not v then return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant)) end local files: { { name: string, data: buffer } } = {} for _, it in items do if not it.entry.dir then local name = string.gsub(it.entry.name, "\\", "/") if #name >= v.nameLen then return nil, Err.new(Err.ARG, "name longer than " .. (v.nameLen - 1) .. " bytes: " .. name) end table.insert(files, { name = name, data = it.data }) end end local w = Bytes.writer() w:string(v.magic) w:u32le(0) w:u32le(0) local offsets: { number } = {} for i, f in files do offsets[i] = w:tell() w:bytes(f.data) end local dirOfs = w:tell() for i, f in files do w:string(f.name) w:fill(0, v.nameLen - #f.name) w:u32le(offsets[i]) w:u32le(buffer.len(f.data)) end w:setU32le(4, dirOfs) w:setU32le(8, w:tell() - dirOfs) return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras function Pak.new(variant: ("quake" | "sin")?): any local a = Archive.new("pak", encode) a.meta.source = { format = "pak", variant = variant or "quake" } return a end return Pak end __FILES["archive/rpm"] = function() -- archive/rpm: RPM v3 / v4 (rpm.org, LSB package format; no code ported): 96-byte lead, signature header (8-byte -- aligned), main header; the payload (gzip / bzip2 / xz / lzma / zstd / none) is cpio; %ghost files not listed. -- Not supported: writing, signature / digest checks, "stripped cpio" (files over 4 GiB), delta rpms. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Deflate = __include("codecs/compress/Deflate") local Lzma = __include("codecs/compress/Lzma") local Zstd = __include("codecs/compress/Zstd") local Bzip2 = __include("codecs/compress/Bzip2") local Archive = __include("containers/Archive") local Cpio = __include("containers/Cpio") -- ------------------------------------------------------------------------------------------------ contract local Rpm = { name = "rpm", category = "archive", extensions = { "rpm" }, mime = { "application/x-rpm" }, deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" }, caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } }, } type DecodeOptions = { maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 1e6 } -- ------------------------------------------------------------------------------------------------ constants local LEAD_MAGIC = "\237\171\238\219" local HEADER_MAGIC = "\142\173\232\1" local RPMFILE_GHOST = 64 local NAMES: { [number]: string } = { [1000] = "name", [1001] = "version", [1002] = "release", [1003] = "epoch", [1004] = "summary", [1005] = "description", [1006] = "buildtime", [1007] = "buildhost", [1009] = "size", [1010] = "distribution", [1011] = "vendor", [1014] = "license", [1015] = "packager", [1016] = "group", [1020] = "url", [1021] = "os", [1022] = "arch", [1044] = "sourcerpm", [1047] = "provides", [1049] = "requires", [1124] = "payloadFormat", [1125] = "payloadCompressor", [1126] = "payloadFlags", [5009] = "longsize", } -- ------------------------------------------------------------------------------------------------ sniff function Rpm.sniff(r: Bytes.Reader): number return if r:peek(4) == LEAD_MAGIC then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode local function header(b: buffer, p: number, e: number): (any, any) if p + 16 > e then return nil, Err.new(Err.TRUNCATED, "header past the end", p) end if buffer.readstring(b, p, 4) ~= HEADER_MAGIC then return nil, Err.new(Err.CORRUPT, "bad header magic", p) end local n = bit32.byteswap(buffer.readu32(b, p + 8)) local hsize = bit32.byteswap(buffer.readu32(b, p + 12)) local index = p + 16 local store = index + n * 16 if n > 0x10000 or hsize > 0x10000000 then return nil, Err.new(Err.LIMIT, "header too large", p) end if store + hsize > e then return nil, Err.new(Err.TRUNCATED, "header data past the end", p) end local tags: { [number]: any } = {} local se = store + hsize for i = 0, n - 1 do local q = index + i * 16 local tag = bit32.byteswap(buffer.readu32(b, q)) local typ = bit32.byteswap(buffer.readu32(b, q + 4)) local off = bit32.byteswap(buffer.readu32(b, q + 8)) local count = bit32.byteswap(buffer.readu32(b, q + 12)) local d = store + off if off > hsize then return nil, Err.new(Err.CORRUPT, "tag data outside the header", q) end local width = if typ == 2 or typ == 1 then 1 elseif typ == 3 then 2 elseif typ == 4 then 4 elseif typ == 5 then 8 else 0 if width > 0 then if d + count * width > se then return nil, Err.new(Err.CORRUPT, "tag data outside the header", q) end local v = table.create(count) for k = 0, count - 1 do local x = d + k * width v[k + 1] = if width == 1 then buffer.readu8(b, x) elseif width == 2 then bit32.bor(bit32.lshift(buffer.readu8(b, x), 8), buffer.readu8(b, x + 1)) elseif width == 4 then bit32.byteswap(buffer.readu32(b, x)) else bit32.byteswap(buffer.readu32(b, x)) * 4294967296 + bit32.byteswap(buffer.readu32(b, x + 4)) end tags[tag] = v elseif typ == 7 then if d + count > se then return nil, Err.new(Err.CORRUPT, "tag data outside the header", q) end tags[tag] = buffer.readstring(b, d, count) elseif typ == 6 or typ == 8 or typ == 9 then local v = {} local s = d local want = if typ == 6 then 1 else count if want > hsize then return nil, Err.new(Err.CORRUPT, "bad string count", q) end for _ = 1, want do local z = s while z < se and buffer.readu8(b, z) ~= 0 do z += 1 end if z >= se then return nil, Err.new(Err.CORRUPT, "unterminated string", s) end table.insert(v, buffer.readstring(b, s, z - s)) s = z + 1 end tags[tag] = if typ == 6 then v[1] else v end end return tags, se end local function files(tags: { [number]: any }): { any } local names: { string } = {} local bn, dn, di = tags[1117], tags[1118], tags[1116] if type(bn) == "table" and type(dn) == "table" and type(di) == "table" then for i, base in bn do local d = dn[(di[i] or 0) + 1] names[i] = (if type(d) == "string" then d else "") .. base end elseif type(tags[1027]) == "table" then names = tags[1027] end local sizes = tags[5008] or tags[1028] or {} local modes, mtimes, links = tags[1030] or {}, tags[1034] or {}, tags[1036] or {} local users, groups, flags = tags[1039] or {}, tags[1040] or {}, tags[1037] or {} local out = {} for i, n in names do table.insert(out, { name = n, size = sizes[i] or 0, mode = modes[i] or 0, mtime = mtimes[i] or 0, link = if links[i] and links[i] ~= "" then links[i] else nil, user = users[i], group = groups[i], flags = flags[i] or 0, }) end return out end local function strip(name: string): string return (string.gsub(name, "^%.?/+", "")) end local function payload(b: buffer, p: number, e: number, compressor: string?, o: DecodeOptions): (any, Err.Err?) local n = e - p local opts: any = { maxBytes = o.maxBytes or 2 ^ 30 } local raw: buffer?, err: any local m = if n >= 6 then buffer.readstring(b, p, 6) else "" if string.sub(m, 1, 2) == "\31\139" then raw, err = Deflate.gunzip(b, p, n) elseif m == "\253" .. "7zXZ\0" then raw, err = Lzma.xz(b, p, n, opts) elseif string.sub(m, 1, 3) == "BZh" then raw, err = Bzip2.decompress(b, p, n, opts) elseif string.sub(m, 1, 4) == "\40\181\47\253" then raw, err = Zstd.decompress(b, p, n, opts) elseif compressor == "lzma" then raw, err = Lzma.alone(b, p, n, opts) elseif string.sub(m, 1, 5) == "07070" then raw = buffer.create(n) buffer.copy(raw :: buffer, 0, b, p, n) else return nil, Err.new(Err.UNSUPPORTED, "payload compressor " .. tostring(compressor), p) end if not raw then return nil, err end if buffer.len(raw) >= 6 and buffer.readstring(raw, 0, 6) == "07070X" then return nil, Err.new(Err.UNSUPPORTED, "stripped cpio payload (files over 4 GiB)") end local list, cerr = Cpio.read(raw, 0, nil, { maxEntries = o.maxEntries }) if not list then return nil, cerr end local by = {} for _, ent in list do by[strip(ent.name)] = ent end return { buf = raw, by = by }, nil end function Rpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local b, base, e = r.buf, r.base, r.limit if e - base < 96 then return nil, Err.new(Err.TRUNCATED, "lead past the end", base) end if buffer.readstring(b, base, 4) ~= LEAD_MAGIC then return nil, Err.new(Err.CORRUPT, "bad lead magic", base) end local major, minor = buffer.readu8(b, base + 4), buffer.readu8(b, base + 5) local kind = bit32.bor(bit32.lshift(buffer.readu8(b, base + 6), 8), buffer.readu8(b, base + 7)) local leadName = buffer.readstring(b, base + 10, 66) leadName = string.match(leadName, "^[^%z]*") :: string if major < 3 then return nil, Err.new(Err.UNSUPPORTED, "rpm format version " .. major, base + 4) end local sig, sigEnd = header(b, base + 96, e) if not sig then return nil, sigEnd end local hp = base + (sigEnd - base + 7) // 8 * 8 local tags, hEnd = header(b, hp, e) if not tags then return nil, hEnd end local a = Archive.new("rpm") local info: { [string]: any } = { tags = tags, signature = sig, type = if kind == 1 then "source" else "binary", lead = { major = major, minor = minor, name = leadName } } for tag, key in NAMES do local v = tags[tag] if type(v) == "table" and tag ~= 1047 and tag ~= 1049 then -- numbers and i18n strings: the first value v = v[1] end info[key] = v end a.meta.rpm = info a.meta.source = { format = "rpm", compressor = info.payloadCompressor } if info.payloadFormat and info.payloadFormat ~= "cpio" then return nil, Err.new(Err.UNSUPPORTED, "payload format " .. tostring(info.payloadFormat), hEnd) end local cache: any = nil local cacheErr: Err.Err? = nil local function entry(name: string): (any, Err.Err?) if not cache and not cacheErr then cache, cacheErr = payload(b, hEnd, e, info.payloadCompressor, o) end if not cache then return nil, cacheErr end local ent = cache.by[name] if not ent then return nil, Err.new(Err.CORRUPT, "file " .. name .. " is not in the payload") end return ent, nil end local list = files(tags) if #list > (o.maxEntries or 1e6) then return nil, Err.new(Err.LIMIT, "too many files") end for _, f in list do if bit32.band(f.flags, RPMFILE_GHOST) ~= 0 then continue end local name = strip(f.name) local typ = Cpio.TYPE_OF[bit32.band(f.mode, 0xF000)] or "0" local data = typ == "0" and f.size > 0 Archive.put(a, { name = name, size = if data then f.size else 0, dir = typ == "5", mtime = f.mtime, mode = bit32.band(f.mode, 0xFFF), type = typ, link = if typ == "2" then f.link else nil, uname = f.user, gname = f.group, method = if info.payloadCompressor then info.payloadCompressor else "store", load = if data then function(): (buffer?, Err.Err?) local ent, err = entry(name) if not ent then return nil, err end local out = buffer.create(ent.size) buffer.copy(out, 0, cache.buf, ent.offset, ent.size) return out, nil end else nil, }) end return a, nil end -- ------------------------------------------------------------------------------------------------ extras function Rpm.cpio(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?) local a, err = Rpm.decode(r, opts) if not a then return nil, err end local p = r.base + 96 local _, sigEnd = header(r.buf, p, r.limit) local hp = r.base + (sigEnd - r.base + 7) // 8 * 8 local _, hEnd = header(r.buf, hp, r.limit) local pl, perr = payload(r.buf, hEnd, r.limit, a.meta.rpm.payloadCompressor, opts or {}) if not pl then return nil, perr end return pl.buf, nil end return Rpm end __FILES["archive/tar"] = function() -- archive/tar: tar archives (ustar, pax, GNU long names; containers/Tar). Supports: read (lazy), write from any -- Archive. Not supported: sparse files, multi-volume archives. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Archive = __include("containers/Archive") local Tar = __include("containers/Tar") -- ------------------------------------------------------------------------------------------------ contract local TarFormat = { name = "tar", category = "archive", extensions = { "tar" }, mime = { "application/x-tar" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" }, caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } }, } type DecodeOptions = { maxEntries: number? } -- default 1e6 type EncodeOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax": ustar + pax records when needed -- ------------------------------------------------------------------------------------------------ sniff function TarFormat.sniff(r: Bytes.Reader): number if r:remaining() < 512 then return 0 end if not Tar.valid(r.buf, r.pos) then return 0 end return if r:peek(5, 257) == "ustar" then 0.95 else 0.6 end -- ------------------------------------------------------------------------------------------------ decode local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?) return function(): (buffer?, Err.Err?) local out = buffer.create(n) buffer.copy(out, 0, b, at, n) return out, nil end end local function encode(archive: any, opts: any?): (buffer?, Err.Err?) return TarFormat.encode(archive, opts) end function TarFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local list, err = Tar.read(r.buf, r.base, r.limit - r.base, opts) if not list then return nil, err end local a = Archive.new("tar", encode) for _, e in list do Archive.put(a, { name = e.name, size = e.size, dir = e.dir, mtime = e.mtime, mode = e.mode, uid = e.uid, gid = e.gid, uname = e.uname, gname = e.gname, type = e.type, link = e.link, method = "store", load = if e.dir or e.size == 0 then nil else lazy(r.buf, e.offset, e.size), }) end a.meta.source = { format = "tar" } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function TarFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) local items = Archive.entries(archive) if not items then return nil, Err.new(Err.ARG, "expected an Archive") end local list: { Tar.WriteEntry } = {} for _, it in items do local e: any = it.entry local data: buffer? = nil if not e.dir and e.type ~= "1" and e.type ~= "2" then local b, err = it.read() if not b then return nil, err end data = b end table.insert(list, { name = e.name, data = data, dir = e.dir, type = if type(e.type) == "string" and #e.type == 1 then e.type else nil, link = if type(e.link) == "string" then e.link else nil, mode = if type(e.mode) == "number" then e.mode else nil, uid = if type(e.uid) == "number" then e.uid else nil, gid = if type(e.gid) == "number" then e.gid else nil, uname = if type(e.uname) == "string" then e.uname else nil, gname = if type(e.gname) == "string" then e.gname else nil, mtime = if type(e.mtime) == "number" then e.mtime else nil, }) end return Tar.write(list, opts) end -- ------------------------------------------------------------------------------------------------ extras function TarFormat.new(): any local a = Archive.new("tar", encode) a.meta.source = { format = "tar" } return a end return TarFormat end __FILES["archive/uu"] = function() -- archive/uu: uuencode (POSIX), xxencode and GNU "begin-base64" blocks, one entry each (variant detected per block); -- written as GNU sharutils does (45 bytes a line, "`" for zero; base64 60 characters + "===="). Not supported: postings -- split over several files, yEnc (archive/yenc), BinHex (archive/binhex). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Base64 = __include("core/Base64") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Uu = { name = "uu", category = "archive", extensions = { "uu", "uue", "xxe", "b64" }, mime = { "text/x-uuencode" }, deps = { "core/Err", "core/Bytes", "core/Base64", "containers/Archive" }, caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } }, } type DecodeOptions = { maxBytes: number?, name: string? } -- default 2^30 type EncodeOptions = { variant: ("uu" | "xx" | "base64")?, -- default "uu" mode: number?, -- default 0o644 name: string?, } -- ------------------------------------------------------------------------------------------------ constants local XX = "+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" local XX_VALUE: { [number]: number } = {} for i = 1, 64 do XX_VALUE[string.byte(XX, i)] = i - 1 end -- ------------------------------------------------------------------------------------------------ sniff function Uu.sniff(r: Bytes.Reader): number local head = r:peek(4096) if string.match(head, "^begin%-base64 [0-7]+ [^\r\n]") or string.match(head, "^begin [0-7]+ [^\r\n]") then return 0.9 end if string.match(head, "\nbegin%-base64 [0-7]+ [^\r\n]") or string.match(head, "\nbegin [0-7][0-7][0-7]+ [^\r\n]") then return 0.5 end return 0 end -- ------------------------------------------------------------------------------------------------ decode local function value(c: number, xx: boolean): number? if xx then return XX_VALUE[c] end if c >= 32 and c <= 96 then return bit32.band(c - 32, 63) end return nil end local function fits(line: string, xx: boolean): boolean local n = value(string.byte(line, 1) or 0, xx) if not n then return false end local need = math.ceil(n / 3) * 4 if #line - 1 < need or #line - 1 > need + 2 then return false end for i = 2, need + 1 do if not value(string.byte(line, i), xx) then return false end end return true end local function decodeLines(lines: { string }, xx: boolean, maxBytes: number): (buffer?, string?) local total = 0 for _, l in lines do total += value(string.byte(l, 1) or 0, xx) or 0 end if total > maxBytes then return nil, "limit: data larger than maxBytes" end local out = buffer.create(total) local o = 0 for li, l in lines do local n = value(string.byte(l, 1) or 0, xx) or 0 local p = 2 local left = n while left > 0 do local a = value(string.byte(l, p) or 0, xx) local b = value(string.byte(l, p + 1) or 0, xx) local c = value(string.byte(l, p + 2) or 0, xx) or 0 local d = value(string.byte(l, p + 3) or 0, xx) or 0 if not a or not b then return nil, "bad character in line " .. li end local v = a * 262144 + b * 4096 + c * 64 + d for k = 2, 0, -1 do if left > 0 then buffer.writeu8(out, o, bit32.band(bit32.rshift(v, k * 8), 255)) o += 1 left -= 1 end end p += 4 end end return out, nil end type Block = { name: string, mode: number, variant: string, data: buffer } local function parse(text: string, maxBytes: number): ({ Block }?, string?) local lines = string.split(text, "\n") local blocks: { Block } = {} local i = 1 while i <= #lines do local line = string.gsub(lines[i], "\r$", "") local b64, mode, name = string.match(line, "^begin(%-base64) ([0-7]+) (.+)$") if not b64 then mode, name = string.match(line, "^begin ([0-7]+) (.+)$") end if mode and name then local body: { string } = {} local closed = false i += 1 while i <= #lines do local l = string.gsub(lines[i], "\r$", "") if (b64 and l == "====") or (not b64 and l == "end") then closed = true break end table.insert(body, l) i += 1 end if not closed then return nil, "truncated: block " .. name .. " has no end line" end local data, variant if b64 then local d, err = Base64.decode(table.concat(body)) if not d then return nil, "block " .. name .. ": " .. tostring(err) end data, variant = d, "base64" else -- drop the empty-line terminator ("`" / " " in uu, "+" in xx) and blank lines local data_lines: { string } = {} for _, l in body do if l ~= "" then table.insert(data_lines, l) end end local uuOk, xxOk = true, true for _, l in data_lines do uuOk = uuOk and fits(l, false) xxOk = xxOk and fits(l, true) end local xx = xxOk and not uuOk if not uuOk and not xxOk then return nil, "block " .. name .. ": lines are neither uuencode nor xxencode" end local d, err = decodeLines(data_lines, xx, maxBytes) if not d then return nil, err end data, variant = d, if xx then "xx" else "uu" end table.insert(blocks, { name = name, mode = tonumber(mode, 8) or 0, variant = variant, data = data }) end i += 1 end if #blocks == 0 then return nil, "no begin line" end return blocks, nil end local function encoder(a: any, o: any?): (buffer?, Err.Err?) return Uu.encode(a, o) end function Uu.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local blocks, err = parse(buffer.readstring(r.buf, r.base, r.limit - r.base), o.maxBytes or 2 ^ 30) if not blocks then return nil, Err.from(err) end local a = Archive.new("uu", encoder) for _, b in blocks do Archive.put(a, { name = b.name, size = buffer.len(b.data), dir = false, mode = b.mode, variant = b.variant, method = b.variant, data = b.data }) end a.meta.stream = #a:list() == 1 a.meta.source = { format = "uu", variant = blocks[1].variant } return a, nil end -- ------------------------------------------------------------------------------------------------ encode local function encodeLines(data: buffer, xx: boolean, out: { string }) local n = buffer.len(data) local function ch(v: number): string if xx then return string.sub(XX, v + 1, v + 1) end return if v == 0 then "`" else string.char(v + 32) end local p = 0 while p < n do local len = math.min(45, n - p) local parts = { ch(len) } for q = p, p + len - 1, 3 do local b0 = buffer.readu8(data, q) local b1 = if q + 1 < p + len then buffer.readu8(data, q + 1) else 0 local b2 = if q + 2 < p + len then buffer.readu8(data, q + 2) else 0 local v = b0 * 65536 + b1 * 256 + b2 table.insert(parts, ch(bit32.rshift(v, 18)) .. ch(bit32.band(bit32.rshift(v, 12), 63)) .. ch(bit32.band(bit32.rshift(v, 6), 63)) .. ch(bit32.band(v, 63))) end table.insert(out, table.concat(parts)) p += len end table.insert(out, ch(0)) end function Uu.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local variant = o.variant or "uu" if variant ~= "uu" and variant ~= "xx" and variant ~= "base64" then return nil, Err.new(Err.ARG, "variant must be uu, xx or base64") end local files, err = Archive.files(value, o.name) if not files then return nil, err end if #files == 0 then return nil, Err.new(Err.ARG, "nothing to encode") end local out: { string } = {} for _, f in files do if string.find(f.name, "[\r\n]") then return nil, Err.new(Err.ARG, "file names may not contain line breaks") end local mode = if type(f.entry.mode) == "number" then f.entry.mode else (o.mode or 0x1A4) local m = string.format("%o", bit32.band(mode, 0xFFF)) if variant == "base64" then table.insert(out, "begin-base64 " .. m .. " " .. f.name) local s = Base64.encode(f.data) for p = 1, #s, 60 do table.insert(out, string.sub(s, p, p + 59)) end table.insert(out, "====") else table.insert(out, "begin " .. m .. " " .. f.name) encodeLines(f.data, variant == "xx", out) table.insert(out, "end") end end return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil end -- ------------------------------------------------------------------------------------------------ extras function Uu.new(): any local a = Archive.new("uu", encoder) a.meta.source = { format = "uu" } return a end return Uu end __FILES["archive/vpk"] = function() -- archive/vpk: Valve VPK v1 / v2 directory files (Valve Developer Community page; no code taken): preload bytes, -- embedded (index 0x7fff) or part-file data ("_NNN.vpk"), CRC-32 checked; writes one self-contained v2 file -- with its MD5s. Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Input = __include("core/Input") local Crc32 = __include("core/Crc32") local Md5 = __include("core/Md5") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Vpk = { name = "vpk", category = "archive", extensions = { "vpk" }, mime = { "application/x-vpk" }, deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" }, caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { verify: boolean?, -- default true resolve: ((name: string) -> (buffer | string)?)?, files: { [string]: buffer | string }?, name: string?, -- "pak01_dir.vpk" -> "pak01_000.vpk" maxEntries: number?, -- default 1e6 } type EncodeOptions = { version: number? } -- 1 or 2 (default: the source's, else 2) -- ------------------------------------------------------------------------------------------------ constants local SIGNATURE = 0x55AA1234 local EMBEDDED = 0x7FFF -- ------------------------------------------------------------------------------------------------ sniff function Vpk.sniff(r: Bytes.Reader): number if r:remaining() < 12 or r:peek(4) ~= "\x34\x12\xAA\x55" then return 0 end local v = r:peekU8(4) return if v == 1 or v == 2 then 1 else 0.5 end -- ------------------------------------------------------------------------------------------------ decode local function encode(archive: any, opts: any?): (buffer?, Err.Err?) return Vpk.encode(archive, opts) end local function partLoader(opts: DecodeOptions?): (number) -> (buffer?, Err.Err?) local cache: { [number]: buffer } = {} local prefix = "pak01" if opts and type(opts.name) == "string" then local base = string.match(opts.name, "([^/\\]+)$") or opts.name prefix = string.match(base, "^(.*)_dir%.[vV][pP][kK]$") or string.match(base, "^(.*)%.[vV][pP][kK]$") or base end return function(index: number): (buffer?, Err.Err?) local hit = cache[index] if hit then return hit, nil end local name = string.format("%s_%03d.vpk", prefix, index) local b = Input.sibling(opts, name) if not b then return nil, Err.new(Err.UNSUPPORTED, "part file " .. name .. " not available (opts.resolve / opts.files)") end cache[index] = b return b, nil end end local function loader(r: Bytes.Reader, e: any, dataBase: number, part: (number) -> (buffer?, Err.Err?), verify: boolean): () -> (buffer?, Err.Err?) return function(): (buffer?, Err.Err?) local src: buffer, at: number if e.archiveIndex == EMBEDDED then src, at = r.buf, r.base + dataBase + e.archiveOffset if dataBase + e.archiveOffset + e.length > r.limit - r.base then return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end") end else local b, err = part(e.archiveIndex) if not b then return nil, err end src, at = b, e.archiveOffset if at + e.length > buffer.len(b) then return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end of part " .. e.archiveIndex) end end local out = buffer.create(e.preloadLength + e.length) buffer.copy(out, 0, r.buf, e.preloadAt, e.preloadLength) buffer.copy(out, e.preloadLength, src, at, e.length) if verify and Crc32.of(out) ~= e.crc32 then return nil, Err.new(Err.CHECKSUM, "entry " .. e.name .. ": CRC-32 mismatch") end return out, nil end end function Vpk.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local sig, version, treeSize = r:u32le(), r:u32le(), r:u32le() if r.err then return nil, r.err end if sig ~= SIGNATURE then return nil, Err.new(Err.CORRUPT, "bad signature", 0) end if version ~= 1 and version ~= 2 then return nil, Err.new(Err.UNSUPPORTED, "VPK version " .. version, 4) end local v2: any = nil if version == 2 then v2 = { fileDataSize = r:u32le(), archiveMd5Size = r:u32le(), otherMd5Size = r:u32le(), signatureSize = r:u32le() } if r.err then return nil, r.err end end local headerLen = r:tell() - r.base if headerLen + treeSize > r.limit - r.base then return nil, Err.new(Err.TRUNCATED, "tree past the end", 8) end local t = r:sub(headerLen, treeSize) local a = Archive.new("vpk", encode) local part = partLoader(opts) local verify = not (opts and opts.verify == false) local maxEntries = opts and opts.maxEntries or 1e6 local count = 0 local parts: { [number]: boolean } = {} local dataBase = headerLen + treeSize while true do local ext = t:cstring() if t.err then return nil, t.err end if ext == "" then break end while true do local path = t:cstring() if t.err then return nil, t.err end if path == "" then break end while true do local name = t:cstring() if t.err then return nil, t.err end if name == "" then break end local e: any = { crc32 = t:u32le(), preloadLength = t:u16le(), archiveIndex = t:u16le(), archiveOffset = t:u32le(), length = t:u32le() } local term = t:u16le() e.preloadAt = t.pos t:skip(e.preloadLength) if t.err then return nil, t.err end if term ~= 0xFFFF then return nil, Err.new(Err.CORRUPT, "bad entry terminator", t:tell() + headerLen) end count += 1 if count > maxEntries then return nil, Err.new(Err.LIMIT, "too many entries") end local full = (if path == " " then "" else path .. "/") .. name .. (if ext == " " then "" else "." .. ext) e.name = full if e.archiveIndex ~= EMBEDDED then parts[e.archiveIndex] = true end Archive.put(a, { name = full, size = e.preloadLength + e.length, dir = false, method = "store", crc32 = e.crc32, archiveIndex = if e.archiveIndex == EMBEDDED then nil else e.archiveIndex, preload = e.preloadLength, load = loader(r, e, dataBase, part, verify), }) end end end local partList: { number } = {} for k in parts do table.insert(partList, k) end table.sort(partList) a.meta.source = { format = "vpk", version = version, entries = count, parts = partList } if v2 then local md5At = dataBase + v2.fileDataSize if v2.otherMd5Size == 48 and md5At + v2.archiveMd5Size + 48 <= r.limit - r.base then local m = r:sub(md5At + v2.archiveMd5Size, 48) v2.treeMd5, v2.chunkHashesMd5, v2.fileMd5 = m:string(16), m:string(16), m:string(16) end a.meta.source.v2 = v2 end return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Vpk.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) local items, err = Archive.collect(archive) if not items then return nil, err end local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source local version = opts and opts.version or (if type(src) == "table" and src.format == "vpk" then src.version else nil) or 2 if version ~= 1 and version ~= 2 then return nil, Err.new(Err.ARG, "version must be 1 or 2") end -- group by extension, then path, keeping first-seen order local exts: { string } = {} local byExt: { [string]: { paths: { string }, byPath: { [string]: { { name: string, data: buffer } } } } } = {} for _, it in items do if not it.entry.dir then local full = string.gsub(it.entry.name, "\\", "/") local dir, file = string.match(full, "^(.*)/([^/]*)$") if not dir then dir, file = " ", full end local stem, ext = string.match(file :: string, "^(.*)%.([^.]*)$") if not stem or stem == "" then stem, ext = file, " " end if stem == "" or dir == "" or string.find(full, "\0", 1, true) then return nil, Err.new(Err.ARG, "bad entry name: " .. it.entry.name) end local g = byExt[ext :: string] if not g then g = { paths = {}, byPath = {} } byExt[ext :: string] = g table.insert(exts, ext :: string) end local l = g.byPath[dir :: string] if not l then l = {} g.byPath[dir :: string] = l table.insert(g.paths, dir :: string) end table.insert(l, { name = stem :: string, data = it.data }) end end local tree = Bytes.writer() local data = Bytes.writer() for _, ext in exts do tree:cstring(ext) local g = byExt[ext] for _, path in g.paths do tree:cstring(path) for _, f in g.byPath[path] do tree:cstring(f.name) tree:u32le(Crc32.of(f.data)) tree:u16le(0) tree:u16le(EMBEDDED) tree:u32le(data:tell()) tree:u32le(buffer.len(f.data)) tree:u16le(0xFFFF) data:bytes(f.data) end tree:u8(0) end tree:u8(0) end tree:u8(0) local tb, db = tree:finish(), data:finish() local w = Bytes.writer(buffer.len(tb) + buffer.len(db) + 128) w:u32le(SIGNATURE) w:u32le(version) w:u32le(buffer.len(tb)) if version == 2 then w:u32le(buffer.len(db)) w:u32le(0) w:u32le(48) w:u32le(0) end w:bytes(tb) w:bytes(db) if version == 2 then local treeMd5 = Md5.new() treeMd5:update(tb) local tmd = treeMd5:digest() local chunkMd5 = Md5.new():digest() local file = Md5.new() local sofar = w:finish() file:update(sofar) file:update(buffer.fromstring(tmd .. chunkMd5)) local out = Bytes.writer(buffer.len(sofar) + 48) out:bytes(sofar) out:string(tmd) out:string(chunkMd5) out:string(file:digest()) return out:finish(), nil end return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras function Vpk.new(version: number?): any local a = Archive.new("vpk", encode) a.meta.source = { format = "vpk", version = version or 2 } return a end return Vpk end __FILES["archive/vswap"] = function() -- archive/vswap: Wolfenstein 3D / Spear of Destiny page files (VSWAP.WL1 / .WL6 / .SOD / .SDM: u16 chunks, sprite -- start, sound start; u32 offsets, u16 lengths; ModdingWiki "VSWAP Format", no code taken), read only. Pages load as -- entries walls/NNN, sprites/NNN, sounds/NNN and soundinfo; Vswap.image turns walls (64 x 64 column-major) and -- sprites (t_compshape posts) into Images through a palette passed in (the game's palette is not redistributable), -- Vswap.sound the digitized sounds into Audio (u8 PCM, 7042 Hz). Not supported: writing, Blake Stone / Corridor 7. -- ------------------------------------------------------------------------------------------------ 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") -- ------------------------------------------------------------------------------------------------ contract local Vswap = { name = "vswap", category = "archive", extensions = { "wl6", "wl1", "sod", "sdm", "vswap" }, mime = { "application/x-wolf3d-vswap" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels" }, caps = { decode = true, encode = false, images = true, sounds = true }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { maxChunks: number? } -- default 65535 type ImageOptions = { palette: (buffer | string)?, -- 768 bytes RGB (6-bit VGA values are scaled up when no byte is above 63); default grey sixBit: boolean?, -- force the 6-bit reading of the palette } type Page = { kind: "wall" | "sprite" | "sound" | "soundinfo", index: number, offset: number, size: number } -- ------------------------------------------------------------------------------------------------ constants local readu8, readu16, readi16, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.writeu32 local SAMPLE_RATE = 7042 -- the digitized sounds' rate (wolf4sdl ORIGSAMPLERATE) -- ------------------------------------------------------------------------------------------------ sniff local function header(r: Bytes.Reader): (number?, number, number) if r:remaining() < 6 then return nil, 0, 0 end local n, ss, so = readu16(r.buf, r.base), readu16(r.buf, r.base + 2), readu16(r.buf, r.base + 4) if n == 0 or ss > so or so > n or 6 + n * 6 > r:remaining() then return nil, 0, 0 end return n, ss, so end function Vswap.sniff(r: Bytes.Reader): number local n = header(r) if not n then return 0 end local size = r.limit - r.base local b = r.buf local last = 6 + n * 6 local nonzero = 0 for i = 0, n - 1 do local o = buffer.readu32(b, r.base + 6 + i * 4) local l = readu16(b, r.base + 6 + n * 4 + i * 2) if o ~= 0 then if o < last or o + l > size then return 0 end last = o nonzero += 1 end end return if nonzero > 0 then 0.6 else 0 end -- ------------------------------------------------------------------------------------------------ decode function Vswap.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if r:remaining() < 6 then return nil, Err.new(Err.TRUNCATED, "header", 0) end local n, ss, so = header(r) if not n then return nil, Err.new(if 6 + readu16(r.buf, r.base) * 6 > r:remaining() then Err.TRUNCATED else Err.CORRUPT, "bad page directory", 0) end if n > (opts and opts.maxChunks or 65535) then return nil, Err.new(Err.LIMIT, "too many pages: " .. n) end local size = r.limit - r.base local b = r.buf local a = Archive.new("vswap") local pages: { Page } = {} local counts: { [string]: number } = { wall = 0, sprite = 0, sound = 0 } for i = 0, n - 1 do local o = buffer.readu32(b, r.base + 6 + i * 4) local l = readu16(b, r.base + 6 + n * 4 + i * 2) if o == 0 then l = 0 -- a sparse page (Spear of Destiny) elseif o + l > size then return nil, Err.new(Err.TRUNCATED, "page " .. i .. " past the end", 6 + i * 4) end local kind: string, idx: number = "sound", i - so if i < ss then kind, idx = "wall", i elseif i < so then kind, idx = "sprite", i - ss elseif i == n - 1 and so < n then kind, idx = "soundinfo", 0 end local name = if kind == "soundinfo" then "soundinfo" else kind .. "s/" .. string.format("%03d", idx) if kind ~= "soundinfo" then counts[kind] += 1 end table.insert(pages, { kind = kind :: any, index = idx, offset = o, size = l }) Archive.put(a, { name = name, size = l, dir = false, method = "store", page = i, kind = kind, load = Archive.slice(b, r.base + o, l) }) end a.meta.source = { format = "vswap", chunks = n, spriteStart = ss, soundStart = so, walls = counts.wall, sprites = counts.sprite, soundPages = counts.sound } a.meta.vswap = { pages = pages, buf = b, base = r.base, spriteStart = ss, soundStart = so } return a, nil end -- ------------------------------------------------------------------------------------------------ extras local function info(a: any): any return type(a) == "table" and type(a.meta) == "table" and a.meta.vswap or nil end local function palette(opts: ImageOptions?): (buffer, boolean) local p = opts and opts.palette if p == nil then local g = buffer.create(768) for i = 0, 255 do buffer.fill(g, i * 3, i, 3) end return Pixels.palette(g, 0, 256), false end local src = if type(p) == "string" then buffer.fromstring(p) else p local n = math.min(buffer.len(src), 768) local six = opts and opts.sixBit if six == nil then six = true for i = 0, n - 1 do if readu8(src, i) > 63 then six = false break end end end if six then local s = buffer.create(768) for i = 0, n - 1 do local v = bit32.band(readu8(src, i), 63) buffer.writeu8(s, i, bit32.bor(bit32.lshift(v, 2), bit32.rshift(v, 4))) end src = s end return Pixels.palette(src, 0, n // 3), true end function Vswap.pages(a: any): { Page }? local v = info(a) return v and v.pages end function Vswap.image(a: any, kind: "wall" | "sprite", index: number, opts: ImageOptions?): (Types.Image?, Err.Err?) local v = info(a) if not v then return nil, Err.new(Err.ARG, "expected a decoded VSWAP archive") end local page: Page? = nil for _, p in v.pages do if p.kind == kind and p.index == index then page = p break end end if not page then return nil, Err.new(Err.ARG, "no " .. tostring(kind) .. " " .. tostring(index)) end local pal, given = palette(opts) local b, at, n = v.buf, v.base + page.offset, page.size local img = Types.Image.new(64, 64) local px = img.pixels if kind == "wall" then if n < 4096 then return nil, Err.new(Err.CORRUPT, "wall page shorter than 4096 bytes", page.offset) end for x = 0, 63 do for y = 0, 63 do writeu32(px, (y * 64 + x) * 4, buffer.readu32(pal, readu8(b, at + x * 64 + y) * 4)) end end else if n < 4 then return nil, Err.new(Err.CORRUPT, "sprite page too short", page.offset) end local left, right = readu16(b, at), readu16(b, at + 2) if right < left or right > 63 or 4 + (right - left + 1) * 2 > n then return nil, Err.new(Err.CORRUPT, "bad sprite columns", page.offset) end for x = left, right do local p = readu16(b, at + 4 + (x - left) * 2) for _ = 1, 64 do if p + 2 > n then return nil, Err.new(Err.CORRUPT, "sprite post past the page", page.offset + p) end local endy = readu16(b, at + p) // 2 if endy == 0 then break end if p + 6 > n then return nil, Err.new(Err.CORRUPT, "sprite post past the page", page.offset + p) end local src, starty = readi16(b, at + p + 2), readu16(b, at + p + 4) // 2 if endy > 64 or starty > endy or src + starty < 0 or src + endy > n then return nil, Err.new(Err.CORRUPT, "bad sprite post", page.offset + p) end for y = starty, endy - 1 do writeu32(px, (y * 64 + x) * 4, buffer.readu32(pal, readu8(b, at + src + y) * 4)) end p += 6 end end end img.meta.source = { format = "vswap", kind = kind, index = index, palette = given } return img, nil end function Vswap.sounds(a: any): number local v = info(a) if not v then return 0 end local last = v.pages[#v.pages] return if last and last.kind == "soundinfo" then last.size // 4 else 0 end function Vswap.sound(a: any, index: number): (Types.Audio?, Err.Err?) local v = info(a) if not v then return nil, Err.new(Err.ARG, "expected a decoded VSWAP archive") end local si = v.pages[#v.pages] if not si or si.kind ~= "soundinfo" or index < 1 or index > si.size // 4 or index % 1 ~= 0 then return nil, Err.new(Err.ARG, "no sound " .. tostring(index)) end local b = v.buf local start = readu16(b, v.base + si.offset + (index - 1) * 4) local len = readu16(b, v.base + si.offset + (index - 1) * 4 + 2) local au = Types.Audio.new(SAMPLE_RATE, 1, len) local s = au.samples local got = 0 local p = v.soundStart + start + 1 while got < len do local page = v.pages[p] if not page or page.kind ~= "sound" then return nil, Err.new(Err.CORRUPT, "sound " .. index .. " runs past the sound pages") end local take = math.min(page.size, len - got) local at = v.base + page.offset for i = 0, take - 1 do buffer.writef32(s, (got + i) * 4, (readu8(b, at + i) - 128) / 128) end got += take p += 1 if page.size == 0 then return nil, Err.new(Err.CORRUPT, "empty sound page in sound " .. index) end end au.meta.source = { format = "vswap", sound = index, startPage = start, bytes = len, encoding = "u8" } return au, nil end return Vswap end __FILES["archive/wad"] = function() -- archive/wad: Doom-engine WADs (IWAD / PWAD; Unofficial Doom Specs, w_wad.c / r_data.c; no code taken), plus lumps, -- palettes, pictures, wall textures and maps (binary and UDMF TEXTMAP). Entry names: "/", repeats -- "~". Not supported: 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("codecs/model/DoomMap") -- ------------------------------------------------------------------------------------------------ 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/DoomMap" }, caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { maxEntries: number? } -- default 1e6 type EncodeOptions = { type: ("IWAD" | "PWAD")? } -- default: the source's, else "PWAD" type Lump = { name: string, entry: string, index: number, offset: number, size: number, namespace: string?, -- between *_START / *_END markers map: string?, marker: boolean?, -- a zero-size marker (F_START, MAP01, ...) } type MapOptions = { textures: boolean?, -- default true palette: number?, -- default 0 maxBlocks: number?, -- UDMF, default 2^22 } -- ------------------------------------------------------------------------------------------------ constants local MAP_LUMPS: { [string]: boolean } = { THINGS = true, LINEDEFS = true, SIDEDEFS = true, VERTEXES = true, SEGS = true, SSECTORS = true, NODES = true, SECTORS = true, REJECT = true, BLOCKMAP = true, BEHAVIOR = true, SCRIPTS = true, LEAFS = true, LIGHTS = true, MACROS = true, GL_VERT = true, GL_SEGS = true, GL_SSECT = true, GL_NODES = true, GL_PVS = true, } -- namespace markers: first letter(s) before _START / _END local NAMESPACES: { [string]: string } = { S = "sprites", SS = "sprites", P = "patches", PP = "patches", P1 = "patches", P2 = "patches", P3 = "patches", F = "flats", FF = "flats", F1 = "flats", F2 = "flats", F3 = "flats", C = "colormaps", TX = "textures", HI = "hires", A = "acs", V = "voices" } -- ------------------------------------------------------------------------------------------------ sniff function Wad.sniff(r: Bytes.Reader): number if r:remaining() < 12 then return 0 end local m = r:peek(4) if m ~= "IWAD" and m ~= "PWAD" then return 0 end return 0.9 end -- ------------------------------------------------------------------------------------------------ decode local function encode(archive: any, opts: any?): (buffer?, Err.Err?) return Wad.encode(archive, opts) end local function nameAt(b: buffer, at: number): string local s = buffer.readstring(b, at, 8) local z = string.find(s, "\0", 1, true) return string.upper(if z then string.sub(s, 1, z - 1) else s) end function Wad.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local kind = r:string(4) local count, dirOfs = r:i32le(), r:i32le() if r.err then return nil, r.err end if kind ~= "IWAD" and kind ~= "PWAD" then return nil, Err.new(Err.CORRUPT, "bad magic", 0) end local size = r.limit - r.base if count < 0 or dirOfs < 0 then return nil, Err.new(Err.CORRUPT, "negative directory field", 4) end if count > (opts and opts.maxEntries or 1e6) then return nil, Err.new(Err.LIMIT, "too many lumps: " .. count) end if dirOfs + count * 16 > size then return nil, Err.new(Err.TRUNCATED, "directory past the end", 8) end local a = Archive.new("wad", encode) local lumps: { Lump } = {} local seen: { [string]: number } = {} local b = r.buf local ns: string? = nil local map: string? = nil local udmf = false for i = 0, count - 1 do local o = r.base + dirOfs + i * 16 local at, n = buffer.readi32(b, o), buffer.readi32(b, o + 4) local name = nameAt(b, o + 8) if n < 0 or at < 0 or (n > 0 and at + n > size) then return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dirOfs + i * 16) end -- map membership: a lump followed by THINGS (binary) or TEXTMAP (UDMF) starts a map local nextName = if i + 1 < count then nameAt(b, o + 24) else "" local inMap: string? = nil if map then if udmf then inMap = map if name == "ENDMAP" then map = nil end elseif MAP_LUMPS[name] then inMap = map else map = nil end end local isMapMarker = not inMap and (nextName == "THINGS" or nextName == "TEXTMAP") if isMapMarker then map, udmf = name, nextName == "TEXTMAP" end local marker: boolean = false local pre = string.match(name, "^(%w+)_START$") local post = string.match(name, "^(%w+)_END$") if pre and NAMESPACES[pre] then ns = NAMESPACES[pre] marker = true elseif post and NAMESPACES[post] then ns = if #post > 1 and NAMESPACES[string.sub(post, 1, 1)] == ns and (string.match(post, "%d$")) then ns else nil marker = true end local entry = if inMap then inMap .. "/" .. name else name local k = seen[entry] if k then k += 1 seen[entry] = k entry = entry .. "~" .. k else seen[entry] = 1 end local lump: Lump = { name = name, entry = entry, index = i + 1, offset = at, size = n, namespace = if marker then nil else ns, map = inMap, marker = (n == 0 and (marker or isMapMarker)) or nil } table.insert(lumps, lump) Archive.put(a, { name = entry, size = n, dir = false, method = "store", lump = name, namespace = lump.namespace, map = inMap, load = Archive.slice(b, r.base + at, n) }) end a.meta.source = { format = "wad", type = kind, lumps = count } a.meta.wad = { lumps = lumps, buf = b, base = r.base } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Wad.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) local items, err = Archive.collect(archive) if not items then return nil, err end local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source local kind = opts and opts.type or (if type(src) == "table" and src.format == "wad" then src.type else nil) or "PWAD" if kind ~= "IWAD" and kind ~= "PWAD" then return nil, Err.new(Err.ARG, "type must be IWAD or PWAD") end local list: { { name: string, data: buffer } } = {} for _, it in items do if not it.entry.dir then local base = string.match(it.entry.name, "([^/\\]*)$") or it.entry.name base = string.upper((string.gsub(base, "~%d+$", ""))) if #base > 8 or #base == 0 then return nil, Err.new(Err.ARG, "lump name must be 1..8 bytes: " .. it.entry.name) end table.insert(list, { name = base, data = it.data }) end end local w = Bytes.writer() w:string(kind) w:u32le(#list) w:u32le(0) local offs: { number } = {} for i, l in list do offs[i] = w:tell() w:bytes(l.data) end local dirOfs = w:tell() for i, l in list do w:u32le(offs[i]) w:u32le(buffer.len(l.data)) w:string(l.name) w:fill(0, 8 - #l.name) end w:setU32le(8, dirOfs) return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras local function info(a: any): any return type(a) == "table" and type(a.meta) == "table" and a.meta.wad or nil end -- the last lump named name (PWAD order: later lumps override) local function find(w: any, name: string, ns: string?): Lump? local up = string.upper(name) local best: Lump? = nil for _, l in w.lumps do if l.name == up and not l.map then if ns == nil or l.namespace == ns then best = l elseif not best then best = l end end end if best and ns and best.namespace ~= ns then for _, l in w.lumps do if l.name == up and l.namespace == ns then best = l end end end return best end function Wad.new(kind: ("IWAD" | "PWAD")?): any local a = Archive.new("wad", encode) a.meta.source = { format = "wad", type = kind or "PWAD" } return a end function Wad.lumps(a: any): { Lump }? local w = info(a) return w and w.lumps end function Wad.palette(a: any, index: number?): (buffer?, Err.Err?) local w = info(a) if not w then return nil, Err.new(Err.ARG, "expected a decoded WAD archive") end local l = find(w, "PLAYPAL") local i = index or 0 if not l or l.size < (i + 1) * 768 then return nil, Err.new(Err.UNSUPPORTED, "no PLAYPAL palette " .. i) end return Pixels.palette(w.buf, w.base + l.offset + i * 768, 256), nil end function Wad.image(a: any, name: string, opts: { palette: number?, kind: string? }?): (Types.Image?, Err.Err?) local w = info(a) if not w then return nil, Err.new(Err.ARG, "expected a decoded WAD archive") end local kind = opts and opts.kind local l = find(w, name, if kind == "flat" then "flats" else nil) if not l then return nil, Err.new(Err.ARG, "no lump named " .. tostring(name)) end local pal, perr = Wad.palette(a, opts and opts.palette) if not pal then return nil, perr end local at = w.base + l.offset local pw, ph, left, top = Picture.header(w.buf, at, l.size) local asFlat = kind == "flat" or (kind ~= "picture" and (l.namespace == "flats" or not pw)) if asFlat then local fw, fh = Picture.flatSize(l.size) if not fw then return nil, Err.new(Err.UNSUPPORTED, "lump " .. l.name .. " is neither a picture nor a flat") end local img = Types.Image.new(fw, fh) Picture.flat(w.buf, at, fw, fh, pal, img.pixels) img.meta.source = { format = "wad", kind = "flat", lump = l.name } return img, nil end if not pw then return nil, Err.new(Err.CORRUPT, "lump " .. l.name .. " is not a valid picture") end local img = Types.Image.new(pw, ph) local ok, msg = Picture.decode(w.buf, at, l.size, pal, img.pixels, pw, ph) if not ok then return nil, Err.from(msg, l.offset) end img.meta.offset = { left, top } img.meta.source = { format = "wad", kind = "picture", lump = l.name, left = left, top = top } return img, nil end local function textureDefs(w: any): { [string]: any } if w.textures then return w.textures end local defs: { [string]: any } = {} w.textures = defs local pn = find(w, "PNAMES") local names: { string } = {} if pn and pn.size >= 4 then local at = w.base + pn.offset local n = math.min(buffer.readi32(w.buf, at), (pn.size - 4) // 8) for i = 0, n - 1 do names[i + 1] = nameAt(w.buf, at + 4 + i * 8) end end for _, tl in { "TEXTURE1", "TEXTURE2" } do local l = find(w, tl) if l and l.size >= 4 then local r = Bytes.reader(w.buf, w.base + l.offset, l.size) local n = r:i32le() if n > 0 and n * 4 <= l.size - 4 then for i = 0, n - 1 do r:seek(4 + i * 4) local o = r:i32le() if o > 0 and o + 22 <= l.size then r:seek(o) local tname = string.upper(r:fixed(8)) r:skip(4) local tw, th = r:i16le(), r:i16le() r:skip(4) local pc = r:i16le() local patches = {} for _ = 1, math.max(0, pc) do local px, py, pi = r:i16le(), r:i16le(), r:i16le() r:skip(4) if names[pi + 1] then table.insert(patches, { x = px, y = py, patch = names[pi + 1] }) end end if not r.err and tw > 0 and th > 0 and defs[tname] == nil then defs[tname] = { width = tw, height = th, patches = patches } end r.err = nil end end end end end return defs end function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types.Image?, Err.Err?) local w = info(a) if not w then return nil, Err.new(Err.ARG, "expected a decoded WAD archive") end local def = textureDefs(w)[string.upper(name)] if not def then return nil, Err.new(Err.ARG, "no texture named " .. tostring(name)) end if def.width * def.height > 4096 * 4096 then return nil, Err.new(Err.LIMIT, "texture too big") end local img = Types.Image.new(def.width, def.height) for _, p in def.patches do local pimg = Wad.image(a, p.patch, { palette = opts and opts.palette, kind = "picture" }) if pimg then Picture.blit(pimg.pixels, pimg.width, pimg.height, img.pixels, def.width, def.height, p.x, p.y) end end img.meta.source = { format = "wad", kind = "texture", texture = string.upper(name), patches = #def.patches } return img, nil end function Wad.maps(a: any): { string } local w = info(a) local out: { string } = {} if w then local seen: { [string]: boolean } = {} for _, l in w.lumps do if l.map and not seen[l.map] then seen[l.map] = true table.insert(out, l.map) end end end return out end function Wad.mapData(a: any, name: string, opts: MapOptions?): (Map.MapData?, Err.Err?) local w = info(a) if not w then return nil, Err.new(Err.ARG, "expected a decoded WAD archive") end local up = string.upper(name) local lumps: { [string]: Map.Lump } = {} for _, l in w.lumps do if l.map == up and lumps[l.name] == nil then lumps[l.name] = { buf = w.buf, at = w.base + l.offset, size = l.size } end end if not next(lumps) then return nil, Err.new(Err.ARG, "no map named " .. tostring(name)) end local m, msg local tm = lumps.TEXTMAP if tm then m, msg = Map.udmf(buffer.readstring(tm.buf, tm.at, tm.size), opts and opts.maxBlocks) else m, msg = Map.parse(lumps, lumps.BEHAVIOR ~= nil) end if not m then return nil, Err.from(msg) end return m, nil end function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Err?) local m, err = Wad.mapData(a, name, opts) if not m then return nil, err end local w = info(a) local defs = textureDefs(w) local images = not (opts and opts.textures == false) local cache: { [string]: any } = {} local pal = opts and opts.palette local function image(kind: string, tname: string): Types.Image? local key = kind .. ":" .. tname local c = cache[key] if c == nil then local img = if kind == "flat" then Wad.image(a, tname, { kind = "flat", palette = pal }) else Wad.texture(a, tname, { palette = pal }) c = img or false cache[key] = c end return if c then c else nil end local tex: Map.Textures = { size = function(kind: string, tname: string): (number?, number?) if kind == "texture" then local d = defs[tname] if d then return d.width, d.height end return nil, nil end local l = find(w, tname, "flats") if l then local fw, fh = Picture.flatSize(l.size) return fw, fh end return nil, nil end, image = if images then image else nil, } local scene = Map.scene(m, tex, string.upper(name)) scene.meta.source = { format = "wad", map = string.upper(name), mapFormat = m.format, namespace = m.namespace, things = #m.things, linedefs = #m.linedefs, sectors = #m.sectors, vertices = #m.vertices // 2 } return scene, nil end return Wad end __FILES["archive/wad/Picture"] = @native function() -- archive/wad/Picture: Doom picture lumps (column posts: topdelta / length / pad / pixels / pad; DeePsea tall patches: -- a topdelta not above the previous is relative) and raw flats to rgba8, from the Unofficial Doom Specs and r_data.c; -- no code taken. Transparent pixels are 0. local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.writeu32 local Picture = {} @native function Picture.header(b: buffer, at: number, n: number): (number?, number, number, number) if n < 8 then return nil, 0, 0, 0 end local w, h = readu16(b, at), readu16(b, at + 2) if w == 0 or h == 0 or w > 4096 or h > 4096 or 8 + w * 4 > n then return nil, 0, 0, 0 end for x = 0, w - 1 do local o = readu32(b, at + 8 + x * 4) if o < 8 + w * 4 or o >= n then return nil, 0, 0, 0 end end return w, h, readi16(b, at + 4), readi16(b, at + 6) end @native function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buffer, w: number, h: number): (boolean, string?) local stop = at + n for x = 0, w - 1 do local p = at + readu32(b, at + 8 + x * 4) local top = -1 while true do if p >= stop then return false, "column " .. x .. " runs past the end" end local delta = readu8(b, p) if delta == 255 then break end if p + 3 > stop then return false, "post header past the end" end local len = readu8(b, p + 1) top = if delta <= top then top + delta else delta if p + 4 + len > stop then return false, "post past the end" end local src = p + 3 for k = 0, len - 1 do local y = top + k if y < h then writeu32(out, (y * w + x) * 4, readu32(pal, readu8(b, src + k) * 4)) end end p += 4 + len end end return true, nil end @native function Picture.flatSize(n: number): (number?, number) if n == 4096 then return 64, 64 elseif n == 4160 then return 64, 64 -- Heretic / Hexen: 64 x 65, the last row is padding elseif n == 8192 then return 64, 128 elseif n == 12800 then return 64, 200 -- Heretic / Hexen scrolling flats end local s = math.floor(math.sqrt(n) + 0.5) if s * s == n and s > 0 then return s, s end if n > 0 and n % 64 == 0 then return 64, n // 64 end return nil, 0 end @native function Picture.flat(b: buffer, at: number, w: number, h: number, pal: buffer, out: buffer) for i = 0, w * h - 1 do writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4)) end end @native function Picture.blit(src: buffer, sw: number, sh: number, dst: buffer, dw: number, dh: number, ox: number, oy: number) local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1 for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do local so, d = y * sw, (y + oy) * dw + ox for x = x0, x1 do local v = readu32(src, (so + x) * 4) if v ~= 0 then writeu32(dst, (d + x) * 4, v) end end end end return Picture end __FILES["archive/xz"] = function() -- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") as single-stream archives (codecs/compress/Lzma). -- Supports: concatenated streams, padding, checks none / CRC-32 / CRC-64 (SHA-256 unverified), LZMA2, delta, BCJ -- x86 / PowerPC / ARM / ARM-Thumb / SPARC / ARM64. Not supported: writing, IA-64 / RISC-V filters. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Lzma = __include("codecs/compress/Lzma") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Xz = { name = "xz", category = "archive", extensions = { "xz", "txz", "lzma" }, mime = { "application/x-xz", "application/x-lzma" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "containers/Archive" }, caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } }, } type DecodeOptions = { maxBytes: number?, -- default 2^30 name: string?, } -- ------------------------------------------------------------------------------------------------ constants local XZ_MAGIC = "\253" .. "7zXZ\0" -- ------------------------------------------------------------------------------------------------ sniff -- .lzma files have no magic: props byte < 225 (0x5D for every preset), a dictionary size of 2^n or 2^n + 2^(n-1), -- a size of -1 or under 2^40, and a 0 range coder byte local function aloneScore(r: Bytes.Reader): number local h = r:peek(14) if #h < 14 then return 0 end local d = string.byte(h, 1) if d >= 225 or string.byte(h, 14) ~= 0 then return 0 end local dict = string.byte(h, 2) + string.byte(h, 3) * 256 + string.byte(h, 4) * 65536 + string.byte(h, 5) * 16777216 local okDict = false for n = 12, 31 do if dict == 2 ^ n or (n < 31 and dict == 2 ^ n + 2 ^ (n - 1)) then okDict = true break end end if not okDict then return 0 end local s = string.sub(h, 6, 13) if s ~= string.rep("\255", 8) and (string.byte(h, 11) ~= 0 or string.byte(h, 12) ~= 0 or string.byte(h, 13) ~= 0) then return 0 end return if d == 0x5D then 0.4 else 0.2 end function Xz.sniff(r: Bytes.Reader): number if r:peek(6) == XZ_MAGIC then return 1 end return aloneScore(r) end -- ------------------------------------------------------------------------------------------------ decode function Xz.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) local o: DecodeOptions = opts or {} local n = r.limit - r.base local out, res local method if r:peek(6) == XZ_MAGIC then out, res = Lzma.xz(r.buf, r.base, n, o) method = "lzma2" else out, res = Lzma.alone(r.buf, r.base, n, o) method = "lzma" end if not out then return nil, res end local a = Archive.new("xz") a.meta.stream = true a.meta.container = if method == "lzma" then "lzma" else "xz" Archive.put(a, { name = Archive.streamName(o, Xz.extensions), size = buffer.len(out), compressedSize = n, method = method, dir = false, data = out, }) return a, nil end return Xz end __FILES["archive/yenc"] = function() -- archive/yenc: yEnc 1.3 (=ybegin / =ypart / =yend, byte + 42, "=" escapes; Jürgen Helbing's draft): parts in one text -- joined, pcrc32 / crc32 / size verified; writes one 128-character-line part per file, escaping NUL, LF, CR, "=" and a -- leading / trailing TAB, space or ".", as uuenview / yencode do. Not supported: parts spread over several files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Crc32 = __include("core/Crc32") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Yenc = { name = "yenc", category = "archive", extensions = { "yenc", "ync" }, mime = { "application/x-yenc" }, deps = { "core/Err", "core/Bytes", "core/Crc32", "containers/Archive" }, caps = { decode = true, encode = true, multipart = true }, } type DecodeOptions = { maxBytes: number?, name: string? } -- default 2^30 type EncodeOptions = { line: number?, -- default 128 name: string?, } -- ------------------------------------------------------------------------------------------------ sniff function Yenc.sniff(r: Bytes.Reader): number local head = r:peek(4096) if string.match(head, "^=ybegin ") then return 0.95 end return if string.find(head, "\n=ybegin [^\n]*name=") then 0.6 else 0 end -- ------------------------------------------------------------------------------------------------ decode -- key=value fields of a keyword line; name= runs to the end of the line local function fields(line: string): { [string]: string } local f: { [string]: string } = {} local s, name = string.match(line, "^(.-)name=(.*)$") if s then f.name = string.gsub(name :: string, "%s+$", "") line = s end for k, v in string.gmatch(line, "(%w+)=(%S+)") do f[k] = v end return f end local function decodeData(src: buffer, i: number, j: number, out: buffer, o: number): number local lim = buffer.len(out) local esc = false for p = i, j - 1 do local c = buffer.readu8(src, p) if c == 13 or c == 10 then continue end if c == 61 and not esc then esc = true continue end if esc then c -= 64 esc = false end if o < lim then buffer.writeu8(out, o, (c - 42) % 256) end o += 1 end return o end local function countData(src: buffer, i: number, j: number): number local n, esc = 0, false for p = i, j - 1 do local c = buffer.readu8(src, p) if c ~= 13 and c ~= 10 then if c == 61 and not esc then esc = true else esc = false n += 1 end end end return n end type Part = { first: number, last: number, from: number, to: number, pcrc: number?, part: number? } type File = { name: string, size: number, crc: number?, parts: { Part }, total: number? } local function hex(s: string?): number? return if s and string.match(s, "^%x+$") and #s <= 8 then tonumber(s, 16) else nil end local function parse(b: buffer, base: number, limit: number): ({ File }?, string?) local files: { File } = {} local byName: { [string]: File } = {} local p = base local cur: File? = nil local part: Part? = nil while p < limit do local nl = p while nl < limit and buffer.readu8(b, nl) ~= 10 do nl += 1 end local isKey = nl - p >= 2 and buffer.readu8(b, p) == 61 and buffer.readu8(b, p + 1) == 121 -- "=y" if isKey then local line = string.gsub(buffer.readstring(b, p, nl - p), "\r$", "") local kw = string.match(line, "^=y(%a+)") local f = fields(line) if kw == "begin" then local name = f.name local size = tonumber(f.size or "") if not name or name == "" or not size or size < 0 then return nil, "=ybegin without name or size" end local file: File? = byName[name] if not file then local nf: File = { name = name :: string, size = size, parts = {}, total = tonumber(f.total or "") } byName[name] = nf table.insert(files, nf) file = nf end cur = file part = { first = 0, last = size, from = nl + 1, to = nl + 1, part = tonumber(f.part or "") } elseif kw == "part" and part then local first, last = tonumber(f.begin or ""), tonumber(f["end"] or "") if not first or not last or first < 1 or last < first - 1 then return nil, "bad =ypart range" end part.first, part.last = first - 1, last part.from, part.to = nl + 1, nl + 1 elseif kw == "end" and part and cur then part.pcrc = hex(f.pcrc32) if f.crc32 then cur.crc = hex(f.crc32) end local size = tonumber(f.size or "") if size and size ~= part.last - part.first then return nil, "=yend size " .. size .. " does not match the part (" .. (part.last - part.first) .. ")" end table.insert(cur.parts, part) part = nil end elseif part then part.to = nl + 1 end p = nl + 1 end if part then return nil, "truncated: no =yend" end if #files == 0 then return nil, "no =ybegin line" end return files, nil end local function encoder(a: any, o: any?): (buffer?, Err.Err?) return Yenc.encode(a, o) end function Yenc.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local maxBytes = o.maxBytes or 2 ^ 30 local b = r.buf local files, perr = parse(b, r.base, math.min(r.limit, buffer.len(b))) if not files then return nil, Err.from(perr) end local a = Archive.new("yenc", encoder) local incomplete = {} for _, f in files do if f.size > maxBytes then return nil, Err.new(Err.LIMIT, f.name .. ": size over maxBytes") end local out = buffer.create(f.size) local covered = 0 for _, pt in f.parts do local n = countData(b, pt.from, pt.to) if n ~= pt.last - pt.first or pt.last > f.size then return nil, Err.new(Err.CORRUPT, f.name .. ": part data is " .. n .. " bytes, the header says " .. (pt.last - pt.first)) end local tmp = buffer.create(n) decodeData(b, pt.from, pt.to, tmp, 0) if pt.pcrc and Crc32.of(tmp) ~= pt.pcrc then return nil, Err.new(Err.CHECKSUM, f.name .. ": part CRC mismatch") end buffer.copy(out, pt.first, tmp, 0, n) covered += n end local whole = covered == f.size if whole and f.crc and Crc32.of(out) ~= f.crc then return nil, Err.new(Err.CHECKSUM, f.name .. ": CRC mismatch") end if not whole then table.insert(incomplete, f.name) end Archive.put(a, { name = f.name, size = f.size, dir = false, method = "yenc", data = out, complete = whole }) end a.meta.stream = #files == 1 a.meta.incomplete = if #incomplete > 0 then incomplete else nil a.meta.source = { format = "yenc" } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Yenc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local lineLen = o.line or 128 if type(lineLen) ~= "number" or lineLen < 2 or lineLen > 997 then return nil, Err.new(Err.ARG, "line must be 2..997") end local files, err = Archive.files(value, o.name) if not files then return nil, err end if #files == 0 then return nil, Err.new(Err.ARG, "nothing to encode") end local w = Bytes.writer() for _, f in files do if string.find(f.name, "[\r\n]") then return nil, Err.new(Err.ARG, "file names may not contain line breaks") end local data = f.data local n = buffer.len(data) w:string(string.format("=ybegin line=%d size=%d name=%s\r\n", lineLen, n, f.name)) local col = 0 for i = 0, n - 1 do local c = (buffer.readu8(data, i) + 42) % 256 local critical = c == 0 or c == 10 or c == 13 or c == 61 if not critical and (c == 9 or c == 32) and (col == 0 or col >= lineLen - 1 or i == n - 1) then critical = true elseif not critical and c == 46 and col == 0 then critical = true end if critical then w:u8(61) w:u8((c + 64) % 256) col += 2 else w:u8(c) col += 1 end if col >= lineLen and i < n - 1 then w:string("\r\n") col = 0 end end if n > 0 then w:string("\r\n") end w:string(string.format("=yend size=%d crc32=%08x\r\n", n, Crc32.of(data))) end return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras function Yenc.new(): any local a = Archive.new("yenc", encoder) a.meta.source = { format = "yenc" } return a end return Yenc end __FILES["archive/z"] = function() -- archive/z: Unix compress (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream archive of one -- entry (codecs/compress/UnixCompress). Supports: read; write byte for byte as ncompress (several entries: a .tar.Z). -- Not supported: pack (.z, 1F 1E) and compact (1F FF) files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local UnixCompress = __include("codecs/compress/UnixCompress") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Z = { name = "z", category = "archive", extensions = { "z", "taz", "tz" }, mime = { "application/x-compress" }, deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" }, caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } }, } type DecodeOptions = { maxBytes: number?, -- default 2^30 name: string?, } type EncodeOptions = { maxBits: number?, -- 9..16 (compress -b), default 16 } -- ------------------------------------------------------------------------------------------------ sniff function Z.sniff(r: Bytes.Reader): number if r:peek(2) ~= "\31\157" then return 0 end local f = r:peekU8(2) return if f >= 0 and bit32.band(f, 0x60) == 0 and bit32.band(f, 0x1F) >= 9 and bit32.band(f, 0x1F) <= 16 then 1 else 0.3 end -- ------------------------------------------------------------------------------------------------ decode local function entryName(opts: DecodeOptions): string local name = Archive.streamName(opts, { "z" }) local stem, ext = string.match(name, "^(.+)%.(%w+)$") if stem and ext and (string.lower(ext) == "taz" or string.lower(ext) == "tz") then return stem .. ".tar" end return name end local function encode(value: any, opts: any?): (buffer?, Err.Err?) return Z.encode(value, opts) end function Z.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local n = r.limit - r.base local out, err = UnixCompress.decompress(r.buf, r.base, n, o) if not out then return nil, err end local a = Archive.new("z", encode) a.meta.stream = true a.meta.source = { format = "z", maxBits = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x1F), blockMode = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x80) ~= 0 } Archive.put(a, { name = entryName(o), size = buffer.len(out), compressedSize = n, method = "lzw", dir = false, data = out, }) return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Z.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local data, err = Archive.streamData(value) if not data then return nil, err end return UnixCompress.compress(data, 0, buffer.len(data), { maxBits = opts and opts.maxBits }) end -- ------------------------------------------------------------------------------------------------ extras function Z.new(data: (buffer | string)?, name: string?): any local a = Archive.new("z", encode) a.meta.stream = true a.meta.source = { format = "z" } if data then a:add(name or "data", data) end return a end return Z end __FILES["archive/zip"] = function() -- archive/zip: ZIP archives on containers/Zip, absorbed from zip-luau 121d4b0 (same author) plus a new writer. -- Supports: stored / deflated entries (CRC-checked), ZIP64, data descriptors, comments, self-extractors, UTF-8 names; -- writing, unchanged entries copied. Not supported: encryption, methods other than store / deflate, multi-disk. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Container = __include("containers/Zip") -- ------------------------------------------------------------------------------------------------ contract local Zip = { name = "zip", category = "archive", extensions = { "zip", "wsz" }, mime = { "application/zip", "application/x-zip-compressed" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, caps = { decode = true, encode = true, methods = { "store", "deflate" }, zip64 = true }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { verify: boolean?, -- default true } type AddOptions = Container.AddOptions type WriteOptions = Container.FinishOptions -- ------------------------------------------------------------------------------------------------ constants local METHODS = { [0] = "store", [8] = "deflate", [9] = "deflate64", [12] = "bzip2", [14] = "lzma", [93] = "zstd", [95] = "xz", [99] = "aes" } local Archive = {} Archive.__index = Archive local function new(zip: any, verify: boolean): any local a = setmetatable({ kind = "archive", format = "zip", meta = { source = { format = "zip" }, comment = if zip then zip.comment else nil, zip64 = if zip then zip.zip64 else nil }, _zip = zip, _verify = verify, _order = {} :: { string }, _items = {} :: { [string]: any }, }, Archive) if zip then for _, e in zip:list() do if a._items[e.name] == nil then table.insert(a._order, e.name) end a._items[e.name] = { raw = e } end end return a end -- ------------------------------------------------------------------------------------------------ sniff function Zip.sniff(r: Bytes.Reader): number local s = r:peek(4) -- ZIP-based formats (docx, jar, 3mf, ...) score higher in their own sniff if s == "PK\3\4" or s == "PK\5\6" then return 0.6 end if string.sub(s, 1, 2) == "MZ" then return 0 -- a self-extractor opens with Zip.decode / opts.format = "zip" end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Zip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) local zip, err = Container.open(r) if not zip then return nil, err end return new(zip, not (opts and opts.verify == false)), nil end function Zip.create(): Types.Archive return new(nil, true) end -- ------------------------------------------------------------------------------------------------ encode function Zip.encode(value: any, opts: WriteOptions?): (buffer?, Err.Err?) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs an Archive or a { name = data } table") end if getmetatable(value) == Archive then return value:write(opts) end local a = new(nil, true) if value.kind == "archive" and type(value.list) == "function" and type(value.read) == "function" then for _, e in value:list() do if e.dir then a:add(e.name, nil, { mtime = e.mtime }) else local data, err = value:read(e.name) if not data then return nil, err end a:add(e.name, data, { mtime = e.mtime }) end end else local names = {} for k, v in value do if type(k) ~= "string" or (type(v) ~= "buffer" and type(v) ~= "string") then return nil, Err.new(Err.ARG, "encode: a { name = data } table needs string names and buffer / string data") end table.insert(names, k) end table.sort(names) for _, k in names do a:add(k, value[k]) end end return a:write(opts) end -- ------------------------------------------------------------------------------------------------ extras function Archive.list(self: any): { Types.ArchiveEntry } local out = {} for _, name in self._order do local it = self._items[name] if it.raw then local e = it.raw table.insert(out, { name = e.name, size = e.size, compressedSize = e.compressedSize, method = METHODS[e.method] or ("method " .. e.method), mtime = e.mtime, dir = e.isDir, crc32 = e.crc32, comment = e.comment, }) else table.insert(out, { name = name, size = buffer.len(it.data), compressedSize = nil, method = it.opts.method or "deflate", mtime = it.opts.mtime, dir = string.sub(name, -1) == "/", }) end end return out end function Archive.read(self: any, name: string): (buffer?, Err.Err?) if type(name) ~= "string" then return nil, Err.new(Err.ARG, "read: name must be a string") end local it = self._items[name] if it and not it.raw then local copy = buffer.create(buffer.len(it.data)) buffer.copy(copy, 0, it.data) return copy, nil end if it then return self._zip:read(it.raw, self._verify) end if self._zip then local e = self._zip:find(name) if e and self._items[e.name] and self._items[e.name].raw == e then return self._zip:read(e, self._verify) end end return nil, Err.new(Err.ARG, "no entry " .. name) end function Archive.add(self: any, name: string, data: any, opts: AddOptions?) local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0) if self._items[name] == nil then table.insert(self._order, name) end self._items[name] = { data = b, opts = opts or {} } end function Archive.remove(self: any, name: string): boolean if self._items[name] == nil then return false end self._items[name] = nil local i = table.find(self._order, name) if i then table.remove(self._order, i) end return true end function Archive.write(self: any, opts: WriteOptions?): (buffer?, Err.Err?) local w = Container.writer() for _, name in self._order do local it = self._items[name] local ok, err if it.raw then ok, err = w:addRaw(it.raw, self._zip) else ok, err = w:add(name, it.data, it.opts) end if not ok then return nil, err end end local o: WriteOptions = opts or {} if o.comment == nil and self.meta.comment and self.meta.comment ~= "" then o = table.clone(o) o.comment = self.meta.comment end return w:finish(o) end Zip.Container = Container return Zip end __FILES["archive/zoo"] = function() -- archive/zoo: Zoo 1.x / 2.x (zoo 2.10's zoo.h / ar.h): directory entries type 1 and 2, methods 0 stored, 1 LZW -- (13-bit), 2 lh5; CRC-16 (ARC) verified; MS-DOS dates as UTC. Not supported: writing, file generations beyond the -- newest (older versions of a name get ";"). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Crc16 = __include("core/Crc16") local Lzw = __include("codecs/compress/Lzw") local Lzh = __include("codecs/compress/Lzh") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Zoo = { name = "zoo", category = "archive", extensions = { "zoo" }, mime = { "application/x-zoo" }, deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzw", "codecs/compress/Lzh", "containers/Archive" }, caps = { decode = true, encode = false, methods = { "store", "lzw", "lzh" } }, } type DecodeOptions = { maxBytes: number?, -- default 2^30 maxEntries: number?, -- default 65536 } -- ------------------------------------------------------------------------------------------------ constants local TAG = 0xFDC4A7DC -- ------------------------------------------------------------------------------------------------ sniff function Zoo.sniff(r: Bytes.Reader): number local h = r:peek(24) if #h < 24 then return 0 end local tag = string.byte(h, 21) + string.byte(h, 22) * 256 + string.byte(h, 23) * 65536 + string.byte(h, 24) * 16777216 if tag ~= TAG then return 0 end return if string.sub(h, 1, 4) == "ZOO " then 1 else 0.8 end -- ------------------------------------------------------------------------------------------------ decode function Zoo.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local maxBytes = o.maxBytes or 2 ^ 30 local maxEntries = o.maxEntries or 65536 local h = r:sub(0, 34) local text = h:string(20) local tag, start = h:u32le(), h:u32le() h:skip(4) local major, minor = h:u8(), h:u8() if h.err then return nil, h.err end if tag ~= TAG then return nil, Err.new(Err.CORRUPT, "no zoo tag") end local a = Archive.new("zoo") a.meta.text = string.match(text, "^[^%z\26]*") a.meta.source = { format = "zoo", version = major .. "." .. minor } local p = start local count = 0 local seen: { [number]: boolean } = {} local size = r:size() while true do if seen[p] or p < 34 or p + 51 > size then return nil, Err.new(if p + 51 > size then Err.TRUNCATED else Err.CORRUPT, "bad directory entry offset " .. p) end seen[p] = true local e = r:sub(p, size - p) local etag = e:u32le() local etype, method = e:u8(), e:u8() local nextP, dataAt = e:u32le(), e:u32le() local date, time = e:u16le(), e:u16le() local crc = e:u16le() local orig, packed = e:u32le(), e:u32le() e:skip(2) local deleted = e:u8() e:skip(1) local commentAt, commentLen = e:u32le(), e:u16le() local fname = e:fixed(13) if e.err then return nil, e.err end if etag ~= TAG then return nil, Err.new(Err.CORRUPT, "bad directory entry tag", r.base + p) end if nextP == 0 then break end count += 1 if count > maxEntries then return nil, Err.new(Err.LIMIT, "more than maxEntries entries") end local name, dir = fname, "" local entry: any = {} if etype == 2 then local varLen = e:u16le() e:skip(3) -- tz, dir_crc if varLen > 0 then local v = e:slice(varLen) local nlen, dlen = v:u8(), v:u8() local lname = v:string(nlen) dir = v:string(dlen) if nlen > 0 then name = string.match(lname, "^[^%z]*") or lname end if v:remaining() >= 2 then entry.system = v:u16le() end if v:remaining() >= 3 then local f0, f1, f2 = v:u8(), v:u8(), v:u8() local attr = f0 + f1 * 256 + f2 * 65536 if bit32.band(attr, 0x400000) ~= 0 then entry.mode = bit32.band(attr, 0xFFFF) end end if v:remaining() >= 4 then local vflag, ver = v:u16le(), v:u16le() if bit32.band(vflag, 0x40) ~= 0 then entry.version = ver end end end if e.err then return nil, e.err end end dir = string.match(dir, "^[^%z]*") or dir dir = string.gsub(dir, "\\", "/") local full = if dir ~= "" then (string.gsub(dir, "/+$", "")) .. "/" .. name else name full = string.gsub(full, "^/+", "") if deleted == 0 then local key = full if a._byName[key] then key = full .. ";" .. tostring(entry.version or count) end entry.name = key entry.size = orig entry.compressedSize = packed entry.method = if method == 0 then "store" elseif method == 1 then "lzw" elseif method == 2 then "lzh" else "method" .. method entry.mtime = Archive.fromDos(date * 65536 + time) entry.dir = false if commentLen > 0 and commentAt + commentLen <= size then entry.comment = r:sub(commentAt, commentLen):string(commentLen) end if dataAt + packed > size then return nil, Err.new(Err.TRUNCATED, full .. ": data past the end") end if orig > maxBytes then return nil, Err.new(Err.LIMIT, full .. ": larger than maxBytes") end if orig > 0 then local buf, at = r.buf, r.base + dataAt entry.load = function(): (buffer?, Err.Err?) local out: buffer?, derr: string? if method == 0 then if packed < orig then return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size") end out = buffer.create(orig) buffer.copy(out :: buffer, 0, buf, at, orig) elseif method == 1 then local ob = buffer.create(orig) local n, lerr = Lzw.decode(buf, at, packed, ob, 0, orig, "zoo") if n ~= orig then return nil, Err.from(lerr or "corrupt: LZW data ends early") end out = ob elseif method == 2 then out, derr = Lzh.decode(buf, at, packed, orig, "lh5") else return nil, Err.new(Err.UNSUPPORTED, "packing method " .. method) end if not out then return nil, Err.from(derr) end if Crc16.arc(out, 0, orig) ~= crc then return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch") end return out, nil end end Archive.put(a, entry) end p = nextP end return a, nil end return Zoo end __FILES["archive/zst"] = function() -- archive/zst: a Zstandard file (.zst, RFC 8878) as a single-stream archive of one entry (codecs/compress/Zstd). -- Supports: read; the entry is named after the file without its extension (".tzst" -> ".tar"), else "data". -- Not supported: dictionaries, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Zstd = __include("codecs/compress/Zstd") local Archive = __include("containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Zst = { name = "zst", category = "archive", extensions = { "zst", "tzst" }, mime = { "application/zstd" }, deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" }, caps = { decode = true, encode = false, stream = true }, } type DecodeOptions = { maxBytes: number?, -- default 2^30 verify: boolean?, -- default true name: string?, } -- ------------------------------------------------------------------------------------------------ sniff function Zst.sniff(r: Bytes.Reader): number local m = r:peek(4) if m == Zstd.MAGIC then return 1 end -- a skippable frame (0x184D2A50 .. 0x184D2A5F) is usually followed by a zstd frame if #m == 4 and string.sub(m, 2, 4) == "\42\77\24" and bit32.band(string.byte(m, 1), 0xF0) == 0x50 then return 0.5 end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Zst.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local len = r.limit - r.base local out, err = Zstd.decompress(r.buf, r.base, len, { maxBytes = o.maxBytes, verify = o.verify }) if not out then return nil, err end local a = Archive.new("zst") a.meta.stream = true Archive.put(a, { name = Archive.streamName(o, Zst.extensions), size = buffer.len(out), compressedSize = len, method = "zstd", dir = false, data = out, }) return a, nil end return Zst end __FILES["audio/aac"] = function() -- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3). Supports: AAC-LC via codecs/audio/Aac (1-8 -- channels, every rate), CRC-protected headers, a leading ID3v2 tag, resync, seeking by frame; HE-AAC plays its -- AAC-LC core. Not supported: writing, ADIF, LATM. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") local Stream = __include("codecs/audio/Stream") local Aac = __include("codecs/audio/Aac") -- ------------------------------------------------------------------------------------------------ contract local AacFormat = { name = "aac", category = "audio", extensions = { "aac", "adts" }, mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Pcm", "codecs/audio/Stream" }, caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { maxFrames: number?, -- default 2^22 } -- ------------------------------------------------------------------------------------------------ constants local readu8 = buffer.readu8 local function id3Size(b: buffer, p: number, limit: number): number if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then return 0 end local s = 0 for i = 6, 9 do s = s * 128 + bit32.band(readu8(b, p + i), 127) end local footer = if bit32.band(readu8(b, p + 5), 0x10) ~= 0 then 10 else 0 return 10 + s + footer end local ID3_TAGS: { [string]: string } = { TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track", COMM = "comment", TCOM = "composer", TPE2 = "albumartist", } local function id3Tags(b: buffer, p: number, size: number): Types.Tags local tags: Types.Tags = {} local ver = readu8(b, p + 3) if ver < 3 then return tags end local q, stop = p + 10, p + size while q + 10 <= stop do local id = buffer.readstring(b, q, 4) if not string.match(id, "^[A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9]$") then break end local n = 0 for i = 4, 7 do n = if ver == 4 then n * 128 + bit32.band(readu8(b, q + i), 127) else n * 256 + readu8(b, q + i) end if n < 1 or q + 10 + n > stop then break end local key = ID3_TAGS[id] local enc = readu8(b, q + 10) if key and (enc == 0 or enc == 3) then local s = buffer.readstring(b, q + 11, n - 1) if id == "COMM" and #s > 3 then s = string.sub(s, 4) local z = string.find(s, "\0", 1, true) if z then s = string.sub(s, z + 1) end end s = (string.gsub(s, "%z+$", "")) tags[key] = s end q += 10 + n end return tags end -- ------------------------------------------------------------------------------------------------ sniff function AacFormat.sniff(r: Bytes.Reader): number local b, p, limit = r.buf, r.pos, r.limit p += id3Size(b, p, limit) local h = Aac.adts(b, p, limit) if not h then return 0 end local h2 = Aac.adts(b, p + h.frameSize, limit) if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then return 0.9 end return if p + h.frameSize >= limit then 0.7 else 0.4 end -- ------------------------------------------------------------------------------------------------ decode local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Aac.Adts?, Err.Err?) local b, limit = r.buf, r.limit local p = r.base + id3Size(b, r.base, limit) local offs, sizes = {}, {} local first: Aac.Adts? = nil while p + 7 <= limit do local h = Aac.adts(b, p, limit) if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then h = nil end if not h then p += 1 continue end if p + h.frameSize > limit then break end if not first then first = h end if h.blocks ~= 1 then return offs, sizes, first, Err.new(Err.UNSUPPORTED, "ADTS frames with " .. h.blocks .. " raw data blocks", p) end table.insert(offs, p + h.headerSize) table.insert(sizes, h.frameSize - h.headerSize) if #offs > maxFrames then return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames") end p += h.frameSize end return offs, sizes, first, nil end function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) local o: DecodeOptions = opts or {} local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) if ierr then return nil, ierr end if not first then return nil, Err.new(Err.CORRUPT, "no ADTS frame", r.base) end local h = first :: Aac.Adts if h.objectType ~= 2 then return nil, Err.new(Err.UNSUPPORTED, "ADTS profile " .. h.objectType .. " (only AAC-LC)") end if h.channelConfig == 0 then return nil, Err.new(Err.UNSUPPORTED, "ADTS with a program config element (channel configuration 0)") end local channels = ({ 1, 2, 3, 4, 5, 6, 8 })[h.channelConfig] :: number local dec, derr = Aac.decoder({ sfIndex = h.sfIndex, channels = channels, channelConfig = h.channelConfig }) if not dec then return nil, derr end local d = dec :: Aac.Decoder local sr = d.sampleRate local nframes = #offs local total = nframes * 1024 local bytes = 0 for _, s in sizes do bytes += s end local id3 = id3Size(r.buf, r.base, r.limit) local tags = if id3 > 0 then id3Tags(r.buf, r.base, id3) else {} local buf = r.buf local out: any = { sampleRate = sr, channels = channels, frames = total, duration = total / sr, bitrate = if total > 0 then math.floor(bytes * 8 * sr / total) else 0, tags = tags, codec = "aac", } -- 1024 samples per ADTS frame; one frame of pre-roll for the overlap return Stream.packets(out, { count = nframes, start = function(i: number): number return (i - 1) * 1024 end, decode = function(i: number): (number?, Err.Err?) return d:decode(buf, offs[i], sizes[i]) end, pcm = function(): { number } return d.pcm end, reset = function() d:reset() end, preroll = 1, }) end function AacFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = AacFormat.open(r, opts) if not dec then return nil, err end local d: any = dec return Pcm.drain(d, { format = "aac", codec = "aac", bitrate = d.bitrate }) end return AacFormat end __FILES["audio/ac3"] = function() -- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) via codecs/audio/Ac3. Supports: every channel layout (WAVE order, no -- downmix), 32 / 44.1 / 48 kHz, every bit rate, the CRC check, resync, exact seeking; drc 0 .. 1, off by default. -- Not supported: writing, E-AC-3 (UNSUPPORTED), bsid 9 / 10 reduced-rate streams. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") local Stream = __include("codecs/audio/Stream") local Ac3 = __include("codecs/audio/Ac3") -- ------------------------------------------------------------------------------------------------ contract local Ac3Format = { name = "ac3", category = "audio", extensions = { "ac3", "a52" }, mime = { "audio/ac3", "audio/x-ac3" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { maxFrames: number?, -- default 2^22 drc: number?, -- 0 = off (default), 1 = full crc: boolean?, -- default true; a bad frame ends the stream with Err.CHECKSUM } -- ------------------------------------------------------------------------------------------------ sniff -- E-AC-3 sniffs too, so it reports UNSUPPORTED rather than an unknown format function Ac3Format.sniff(r: Bytes.Reader): number local b, p, limit = r.buf, r.pos, r.limit local h = Ac3.header(b, p, limit) if not h then return 0 end local h2 = Ac3.header(b, p + h.frameSize, limit) if h2 and h2.sampleRate == h.sampleRate then return 0.9 end return if p + h.frameSize >= limit then 0.6 else 0.3 end -- ------------------------------------------------------------------------------------------------ decode -- a header counts when the next one follows it, or the data ends local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Ac3.Header?, Err.Err?) local b, limit = r.buf, r.limit local p = r.base local offs, sizes = {}, {} local first: Ac3.Header? = nil while p + 8 <= limit do local h = Ac3.header(b, p, limit) if h and first and (h.sampleRate ~= first.sampleRate or h.bsid > 10) then h = nil end if h and not first and p + h.frameSize + 8 <= limit then local h2 = Ac3.header(b, p + h.frameSize, limit) if not h2 then h = nil end end if not h then p += 1 continue end if not first then first = h if h.bsid > 10 then return offs, sizes, first, Err.new(Err.UNSUPPORTED, "E-AC-3 (Dolby Digital Plus)", p) elseif h.bsid > 8 then return offs, sizes, first, Err.new(Err.UNSUPPORTED, "reduced sample rate AC-3 (bsid " .. h.bsid .. ")", p) end end if p + h.frameSize > limit then break end table.insert(offs, p) table.insert(sizes, h.frameSize) if #offs > maxFrames then return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames") end p += h.frameSize end return offs, sizes, first, nil end function Ac3Format.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) local o: DecodeOptions = opts or {} local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) if ierr then return nil, ierr end if not first or #offs == 0 then return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", r.base) end local h = first :: Ac3.Header local d = Ac3.decoder({ drc = o.drc, crc = o.crc }) local buf = r.buf local n = #offs local out = { sampleRate = h.sampleRate, channels = h.channels, frames = n * 1536, duration = n * 1536 / h.sampleRate, bitrate = h.bitrate, tags = {}, codec = "ac3", acmod = h.acmod, lfe = h.lfeon, } return Stream.packets(out, { count = n, start = function(i: number): number return (i - 1) * 1536 end, decode = function(i: number): (number?, Err.Err?) local frames, err = d:decode(buf, offs[i], sizes[i]) if frames and d.channels ~= h.channels then return nil, Err.new(Err.UNSUPPORTED, "channel layout change inside the stream", offs[i]) end return frames, err end, pcm = function(): { number } return d.pcm end, reset = function() d:reset() end, preroll = 1, }) end function Ac3Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = Ac3Format.open(r, opts) if not dec then return nil, err end local d: any = dec return Pcm.drain(d, { format = "ac3", codec = "ac3", acmod = d.acmod, lfe = d.lfe, bitrate = d.bitrate }) end return Ac3Format end __FILES["audio/adpcm"] = function() -- audio/adpcm: headerless ADPCM (.adpcm / .ima / .vox) via codecs/audio/Adpcm; sniff is 0, the layout comes from opts. -- "ima": DVI nibbles, high first; "ima_wav": MS IMA blocks; "ms": MS ADPCM, 7 standard coefficient pairs; "ima_qt": -- Apple ima4 (34-byte packets, 64 frames); "psx": PS-ADPCM (16-byte frames, 28 samples). Encode: ima, ima_wav, ms. -- Not supported: raw DSP / ADX (their coefficients live in a header). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") local Adpcm = __include("codecs/audio/Adpcm") local Decoder = __include("codecs/audio/Adpcm/Decoder") -- ------------------------------------------------------------------------------------------------ contract local Raw = { name = "adpcm", category = "audio", extensions = { "adpcm", "ima" }, mime = { "audio/x-adpcm" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } }, } -- ------------------------------------------------------------------------------------------------ types type Codec = "ima" | "ima_wav" | "ms" | "ima_qt" | "psx" type Options = { codec: Codec?, -- default "ima" sampleRate: number?, -- default 22050 (decode) channels: number?, -- default 1 (decode) blockAlign: number?, -- ima_wav / ms; default 1024 decoding, 256 * channels encoding lowFirst: boolean?, interleave: number?, -- psx: bytes per channel (default 16) maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ constants local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = true } -- ------------------------------------------------------------------------------------------------ sniff function Raw.sniff(_r: Bytes.Reader): number return 0 end -- ------------------------------------------------------------------------------------------------ decode function Raw.decode(r: Bytes.Reader, opts: Options?): (Types.Audio?, Err.Err?) local dec, err = Raw.open(r, opts) if not dec then return nil, err end local limit = opts and opts.maxFrames or 2 ^ 28 if dec.frames > limit or dec.frames * dec.channels > 2 ^ 28 then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", dec.frames)) end return Pcm.drain(dec, { format = "adpcm", codec = (dec :: any).codec }, limit) end -- ------------------------------------------------------------------------------------------------ encode function Raw.encode(value: any, opts: Options?): (buffer?, Err.Err?) local o: Options = opts or {} local codec = o.codec or "ima" if codec ~= "ima" and codec ~= "ima_wav" and codec ~= "ms" then return nil, Err.new(Err.ARG, "encode: codec must be ima, ima_wav or ms") end local src, serr = Pcm.source(value) if not src then return nil, serr end local a, cerr = Pcm.collect(src) if not a then return nil, cerr end local ch, n, x = a.channels, a.frames, a.samples if codec == "ima" then local out = buffer.create((n * ch + 1) // 2) local st = buffer.create(8 * ch) for c = 0, ch - 1 do Adpcm.imaEncode(x, c, ch, n, st, c * 8, out, 0, c, ch, not o.lowFirst) end return out, nil end local ba = o.blockAlign or 256 * ch local spb = Decoder.blockFrames(codec, ba, ch) if type(ba) ~= "number" or ba ~= math.floor(ba) or ba > 65535 or not spb or spb < 2 then return nil, Err.new(Err.ARG, "bad blockAlign " .. tostring(ba)) end if codec == "ima_wav" and (ba % (4 * ch) ~= 0) then return nil, Err.new(Err.ARG, "ima_wav: blockAlign must be a multiple of 4 * channels") end local blocks = (n + spb - 1) // spb local out = buffer.create(blocks * ba) local st = buffer.create(8 * ch) for b = 0, blocks - 1 do local f0 = b * spb if codec == "ms" then Adpcm.msEncode(x, f0, n - f0, ch, spb, out, b * ba) else Adpcm.imaWavEncode(x, f0, n - f0, ch, spb, st, out, b * ba) end end return out, nil end -- ------------------------------------------------------------------------------------------------ open function Raw.open(r: Bytes.Reader, opts: Options?): (Types.Decoder?, Err.Err?) if type(r) ~= "table" or type(r.buf) ~= "buffer" then return nil, Err.new(Err.ARG, "open: expected a Reader") end local o: Options = opts or {} local codec = o.codec or "ima" local rate, ch = o.sampleRate or 22050, o.channels or 1 if not CODECS[codec] then return nil, Err.new(Err.ARG, "unknown codec " .. tostring(codec)) end if type(rate) ~= "number" or rate <= 0 or rate ~= rate or type(ch) ~= "number" or ch < 1 or ch > 255 or ch ~= math.floor(ch) then return nil, Err.new(Err.ARG, "bad sampleRate or channels") end local size = r.limit - r.base local dec: any = { sampleRate = rate, channels = ch, tags = {}, codec = codec, frames = 0, duration = 0 } local d, err if codec == "ima" then d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base, size = size, hi = not o.lowFirst }) elseif codec == "psx" then local il = o.interleave or 16 if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then return nil, Err.new(Err.ARG, "interleave must be a multiple of 16") end d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = r.base, size = size, interleave = if ch == 1 then 16 else il }) else local ba = o.blockAlign or 1024 if type(ba) ~= "number" or ba < 1 or ba ~= math.floor(ba) then return nil, Err.new(Err.ARG, "bad blockAlign") end d, err = Decoder.blocks(dec, { kind = codec :: any, buf = r.buf, offset = r.base, size = size, blockAlign = ba }) end if not d then return nil, err end d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0 return d, nil end return Raw end __FILES["audio/adx"] = function() -- audio/adx: CRI ADX via codecs/audio/Adpcm; header and decoder follow vgmstream r2117 (ISC, -- licenses/vgmstream-LICENSE.txt), bit-exact with it. Supports: encoding type 3, versions 3-5, 1-8 channels, loop -- points; encode as version 4. Not supported: encrypted ADX (0x0408 / 0x0409), encoding types 2 and 4, AHX. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") local Adpcm = __include("codecs/audio/Adpcm") local Decoder = __include("codecs/audio/Adpcm/Decoder") -- ------------------------------------------------------------------------------------------------ contract local Adx = { name = "adx", category = "audio", extensions = { "adx" }, mime = { "audio/x-adx" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 }, } -- ------------------------------------------------------------------------------------------------ types type Loop = { start: number, stop: number } type DecodeOptions = { maxFrames: number?, -- default 2^28 } type EncodeOptions = { loop: Loop?, -- frames, stop exclusive; default the source's meta.source.loop cutoff: number?, -- Hz, default 500 (as CRI's encoders) } -- ------------------------------------------------------------------------------------------------ constants local FRAME = 18 -- ------------------------------------------------------------------------------------------------ sniff function Adx.sniff(r: Bytes.Reader): number if r:peekU8(0) ~= 0x80 or r:peekU8(1) ~= 0 then return 0 end local off = r:peekU8(2) * 256 + r:peekU8(3) return if r:peek(6, off - 2) == "(c)CRI" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode function Adx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = Adx.open(r) if not dec then return nil, err end local d = dec :: any local limit = opts and opts.maxFrames or 2 ^ 28 if d.frames > limit or d.frames * d.channels > 2 ^ 28 then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) end return Pcm.drain(d, { format = "adx", version = d.version, cutoff = d.cutoff, loop = d.loop }, limit) end -- ------------------------------------------------------------------------------------------------ encode function Adx.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local src, serr = Pcm.source(value) if not src then return nil, serr end local ch, rate = src.channels, src.sampleRate if ch > 8 then return nil, Err.new(Err.ARG, "ADX holds at most 8 channels") end if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 31 then return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") end local loop = o.loop if loop == nil then local v = value :: any local m = type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.loop loop = if type(m) == "table" then m else (if type(v.loop) == "table" then v.loop else nil) end local a, cerr = Pcm.collect(src) if not a then return nil, cerr end local n = a.frames if loop and (type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop <= loop.start or loop.stop > n) then return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio") end local cutoff = o.cutoff or 500 if type(cutoff) ~= "number" or cutoff < 1 or cutoff >= rate / 2 or cutoff > 65535 then return nil, Err.new(Err.ARG, "bad cutoff") end cutoff = math.floor(cutoff) local c1, c2 = Adpcm.adxCoefs(cutoff, rate) local hist = if ch > 1 then 4 * ch else 8 local start = 0x18 + hist + (if loop then 0x18 else 0) + 6 start = (start + 3) // 4 * 4 local nframes = (n + 31) // 32 local w = Bytes.writer(start + (nframes + 1) * FRAME * ch) w:u16be(0x8000) w:u16be(start - 4) w:u8(3) w:u8(FRAME) w:u8(4) w:u8(ch) w:u32be(rate) w:u32be(n) w:u16be(cutoff) w:u16be(0x0400) w:u32be(0) w:fill(0, hist) if loop then local bytesAt = function(f: number): number return start + (f // 32) * FRAME * ch end w:u16be(0) w:u16be(1) w:u32be(1) w:u32be(loop.start) w:u32be(bytesAt(loop.start)) w:u32be(loop.stop) w:u32be(bytesAt(loop.stop + 31)) end w:fill(0, start - 6 - w.pos) w:string("(c)CRI") local at = w:reserve(nframes * FRAME * ch) local st = buffer.create(8 * ch) for c = 0, ch - 1 do Adpcm.adxEncode(a.samples, c, ch, n, c1, c2, st, c * 8, w.buf, at + c * FRAME, FRAME * ch) end w.pos = at + nframes * FRAME * ch -- the end marker: scale 0x8001, then the padding size w:u16be(0x8001) w:u16be(FRAME - 4) w:fill(0, FRAME - 4) return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ open function Adx.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) if type(r) ~= "table" or type(r.buf) ~= "buffer" then return nil, Err.new(Err.ARG, "open: expected a Reader") end if Adx.sniff(r) == 0 then return nil, Err.new(Err.CORRUPT, "not an ADX file") end local h = r:sub(0) local copyright = (h:seek(2) and h:u16be()) or 0 local start = copyright + 4 local enc, fsize, bits, ch = h:u8(), h:u8(), h:u8(), h:u8() local rate, frames, cutoff, version = h:u32be(), h:u32be(), h:u16be(), h:u16be() if h.err then return nil, h.err end if version == 0x0408 or version == 0x0409 then return nil, Err.new(Err.UNSUPPORTED, "encrypted ADX (keys needed)") end if enc ~= 3 then return nil, Err.new(Err.UNSUPPORTED, "encoding type " .. enc .. (if enc == 0x10 or enc == 0x11 then " (AHX)" else "")) end if fsize ~= FRAME or bits ~= 4 then return nil, Err.new(Err.UNSUPPORTED, string.format("frame size %d, %d bits", fsize, bits)) end if ch < 1 or ch > 8 then return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch) end if rate < 1 or rate >= 2 ^ 31 then return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) end if version ~= 0x0300 and version ~= 0x0400 and version ~= 0x0500 then return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%04X", version)) end local size = r.limit - r.base - start if size < 0 then return nil, Err.new(Err.TRUNCATED, "the header runs past the end") end -- loop points and the initial history (vgmstream's reading of the extra header fields) local hist: { number }? = nil local loopsAt: number? = nil if version == 0x0300 then if start - 6 >= 0x14 + 0x18 then loopsAt = 0x14 end elseif version == 0x0400 then local hsize = if ch > 1 then 4 * ch else 8 hist = {} for c = 0, ch - 1 do local hh = r:sub(0x18 + c * 4, 4) local h1, h2 = hh:i16be(), hh:i16be() hist[c * 2 + 1], hist[c * 2 + 2] = if hh.err then 0 else h1, if hh.err then 0 else h2 end local ainf = 0 local ai = r:sub(0x18 + hsize + 4, 8) if ai:string(4) == "AINF" then ainf = ai:u32be() end if start - ainf - 6 >= 0x18 + hsize + 0x18 then loopsAt = 0x18 + hsize end end local loopTable: { start: number, stop: number }? = nil if loopsAt then local l = r:sub(loopsAt + 4, 0x14) local flag, ls, _, le = l:u32be(), l:u32be(), l:u32be(), l:u32be() if not l.err and flag ~= 0 and le > ls then loopTable = { start = ls, stop = le } end end local c1, c2 = Adpcm.adxCoefs(cutoff, rate) local dec: any = { sampleRate = rate, channels = ch, tags = {}, version = version, cutoff = cutoff, loop = loopTable } local d, err = Decoder.interleaved(dec, { kind = "adx", buf = r.buf, offset = r.base + start, size = size, interleave = FRAME, frames = frames, c1 = c1, c2 = c2, v3 = version == 0x0300, hist = hist, }) if not d then return nil, err end d.bitrate = rate * FRAME * ch * 8 // 32 return d, nil end return Adx end __FILES["audio/aiff"] = function() -- audio/aiff: AIFF / AIFF-C (Apple AIFF 1.3, AIFF-C draft 1991). Supports: PCM 1-32 bits; AIFF-C NONE / twos / -- sowt / raw / in24 / in32 / fl32 / fl64 / ulaw / alaw / ima4; text chunks as tags; truncated SSND; encode 8-32 bit, -- sowt, fl32, fl64, ulaw, alaw. Not supported: other compressed AIFF-C codecs, MARK / INST, the ID3 chunk. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Chunks = __include("containers/Chunks") local Pcm = __include("codecs/audio/Pcm") local Adpcm = __include("codecs/audio/Adpcm/Decoder") -- ------------------------------------------------------------------------------------------------ contract local Aiff = { name = "aiff", category = "audio", extensions = { "aiff", "aif", "aifc", "afc" }, mime = { "audio/aiff", "audio/x-aiff" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, } type DecodeOptions = { maxFrames: number?, -- default 2^28 } type EncodeOptions = { sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" littleEndian: boolean?, -- 16-bit only, as AIFF-C "sowt" (ffmpeg reads no other sowt); default false aifc: boolean?, -- default: only when the sample format needs it } -- ------------------------------------------------------------------------------------------------ constants local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANNO = "comment" } local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } } local AIFC_VERSION = 0xA2805140 local function ext80(b: buffer, o: number): number local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) local hi = bit32.byteswap(buffer.readu32(b, o + 2)) local lo = bit32.byteswap(buffer.readu32(b, o + 6)) local e = bit32.band(se, 0x7FFF) if e == 0 and hi == 0 and lo == 0 then return 0 end if e == 0x7FFF then return math.huge end local v = (hi * 4294967296 + lo) * 2 ^ (e - 16383 - 63) return if se >= 0x8000 then -v else v end local function writeExt80(w: Bytes.Writer, x: number) if x <= 0 or x ~= x then w:fill(0, 10) return end local e = 0 while x >= 2 ^ (e + 1) do e += 1 end while x < 2 ^ e do e -= 1 end local m = x * 2 ^ (63 - e) local hi = math.floor(m / 4294967296) local lo = m - hi * 4294967296 w:u16be(e + 16383) w:u32be(hi) w:u32be(math.floor(lo)) end local function sampleFormat(comp: string, bits: number): (string?, string?) if comp == "NONE" or comp == "twos" or comp == "" then if bits >= 1 and bits <= 8 then return "s8", nil elseif bits <= 16 then return "s16be", nil elseif bits <= 24 then return "s24be", nil elseif bits <= 32 then return "s32be", nil end return nil, "bad sample size " .. bits elseif comp == "sowt" then if bits >= 1 and bits <= 8 then return "s8", nil elseif bits <= 16 then return "s16le", nil elseif bits <= 24 then return "s24le", nil elseif bits <= 32 then return "s32le", nil end return nil, "bad sample size " .. bits elseif comp == "raw " then return "u8", nil elseif comp == "in24" then return "s24be", nil elseif comp == "in32" then return "s32be", nil elseif comp == "42ni" then return "s32le", nil elseif comp == "fl32" or comp == "FL32" then return "f32be", nil elseif comp == "fl64" or comp == "FL64" then return "f64be", nil elseif comp == "ulaw" or comp == "ULAW" then return "ulaw", nil elseif comp == "alaw" or comp == "ALAW" then return "alaw", nil elseif comp == "ima4" then return "ima4", nil end return nil, "compression " .. string.format("%q", comp) end -- ------------------------------------------------------------------------------------------------ sniff function Aiff.sniff(r: Bytes.Reader): number if r:remaining() < 12 or r:peek(4) ~= "FORM" then return 0 end local form = buffer.readstring(r.buf, r.pos + 8, 4) return if form == "AIFF" or form == "AIFC" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode type Info = { channels: number, frames: number, sampleRate: number, bits: number, format: string, compression: string, aifc: boolean, dataOffset: number, -- absolute in r.buf dataSize: number, truncated: boolean, tags: Types.Tags, } local function parse(r: Bytes.Reader): (Info?, Err.Err?) local b = r.buf local base, limit = r.base, r.limit if limit - base < 12 or buffer.readstring(b, base, 4) ~= "FORM" then return nil, Err.new(Err.CORRUPT, "not a FORM file", base) end local form = buffer.readstring(b, base + 8, 4) if form ~= "AIFF" and form ~= "AIFC" then return nil, Err.new(Err.CORRUPT, "FORM type " .. string.format("%q", form) .. " is not AIFF / AIFC", base + 8) end local aifc = form == "AIFC" local formEnd = math.min(limit, base + 8 + bit32.byteswap(buffer.readu32(b, base + 4))) local info: Info? = nil local comm = false local ssnd: number? = nil local ssndLen = 0 local tags: Types.Tags = {} -- a FORM size that undercounts still reads the last chunk's body for _, c in Chunks.walk(b, base + 12, limit, Chunks.IFF) do local id, len, d, avail, p = c.id, c.declared, c.offset, c.avail, c.start if p + 8 > formEnd then break end if id == "COMM" then if avail < 18 or (aifc and avail < 22) then return nil, Err.new(Err.TRUNCATED, "COMM chunk too short", p) end local ch = buffer.readu8(b, d) * 256 + buffer.readu8(b, d + 1) local frames = bit32.byteswap(buffer.readu32(b, d + 2)) local bits = buffer.readu8(b, d + 6) * 256 + buffer.readu8(b, d + 7) local rate = ext80(b, d + 8) local comp = if aifc then buffer.readstring(b, d + 18, 4) else "NONE" if ch < 1 then return nil, Err.new(Err.CORRUPT, "no channels", d) end if not (rate > 0 and rate < 2 ^ 31) then return nil, Err.new(Err.CORRUPT, "bad sample rate", d + 8) end local fmt, why = sampleFormat(comp, bits) if not fmt then return nil, Err.new(if comp == "NONE" or comp == "twos" or comp == "sowt" then Err.CORRUPT else Err.UNSUPPORTED, why :: string, d + 18) end info = { channels = ch, frames = frames, sampleRate = rate, bits = bits, format = fmt, compression = comp, aifc = aifc, dataOffset = 0, dataSize = 0, truncated = false, tags = tags, } comm = true elseif id == "SSND" then if avail < 8 then return nil, Err.new(Err.TRUNCATED, "SSND chunk too short", p) end local off = bit32.byteswap(buffer.readu32(b, d)) ssnd = d + 8 + off ssndLen = math.max(0, avail - 8 - off) if len >= 8 + off then ssndLen = math.min(ssndLen, len - 8 - off) end elseif TEXT_TAGS[id] then local s = buffer.readstring(b, d, avail) local z = string.find(s, "\0", 1, true) if z then s = string.sub(s, 1, z - 1) end local key = TEXT_TAGS[id] tags[key] = if tags[key] then tags[key] .. "\n" .. s else s end if len > formEnd - d then break end end if not comm or not info then return nil, Err.new(Err.CORRUPT, "no COMM chunk", base) end local fi = info :: Info if fi.frames > 0 and not ssnd then return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base) end local present if fi.format == "ima4" then fi.frames *= 64 -- COMM counts packets present = if ssnd then ssndLen // (34 * fi.channels) * 64 else 0 else present = if ssnd then ssndLen // (fi.channels * Pcm.Convert.SIZE[fi.format]) else 0 end if present < fi.frames then fi.frames = present fi.truncated = true end fi.dataOffset = ssnd or base fi.dataSize = ssndLen return fi, nil end function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?) return parse(r) end function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = Aiff.open(r, opts) if not dec then return nil, err end return Pcm.drain(dec) end -- ------------------------------------------------------------------------------------------------ encode local FORMATS = { s8 = { "s8", 8, "NONE" }, s16 = { "s16be", 16, "NONE" }, s24 = { "s24be", 24, "NONE" }, s32 = { "s32be", 32, "NONE" }, f32 = { "f32be", 32, "fl32" }, f64 = { "f64be", 64, "fl64" }, ulaw = { "ulaw", 16, "ulaw" }, alaw = { "alaw", 16, "alaw" }, } local LE = { s16be = "s16le" } local COMP_NAMES = { NONE = "not compressed", sowt = "", fl32 = "32-bit floating point", fl64 = "64-bit floating point", ulaw = "\181Law 2:1", alaw = "ALaw 2:1" } function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then return nil, serr end local o: EncodeOptions = opts or {} local spec = FORMATS[o.sampleFormat or "s16"] if not spec then return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) end local fmt, bits, comp = spec[1], spec[2], spec[3] if o.littleEndian then if not LE[fmt] then return nil, Err.new(Err.ARG, "littleEndian needs 16-bit samples") end fmt, comp = LE[fmt], "sowt" end if src.channels > 65535 then return nil, Err.new(Err.ARG, "too many channels") end local aifc = o.aifc or comp ~= "NONE" local w = Bytes.writer(65536) w:string("FORM") w:u32be(0) w:string(if aifc then "AIFC" else "AIFF") if aifc then w:string("FVER") w:u32be(4) w:u32be(AIFC_VERSION) end for _, pair in TEXT_ORDER do local id, key = pair[1], pair[2] local s = src.tags[key] if type(s) == "string" and #s > 0 then w:string(id) w:u32be(#s) w:string(s) if #s % 2 == 1 then w:u8(0) end end end local commAt = w:tell() w:string("COMM") if aifc then local name = COMP_NAMES[comp] or "" local plen = 1 + #name plen += plen % 2 w:u32be(22 + plen) else w:u32be(18) end w:u16be(src.channels) w:u32be(0) -- frames, patched w:u16be(bits) writeExt80(w, src.sampleRate) if aifc then w:string(comp) local name = COMP_NAMES[comp] or "" w:u8(#name) w:string(name) if (1 + #name) % 2 == 1 then w:u8(0) end end local ssndAt = w:tell() w:string("SSND") w:u32be(0) -- patched w:u32be(0) -- offset w:u32be(0) -- block size local frames, perr = Pcm.encode(src, fmt, w) if not frames then return nil, perr end local dataLen = w:tell() - ssndAt - 16 if dataLen % 2 == 1 then w:u8(0) end w:setU32be(ssndAt + 4, dataLen + 8) w:setU32be(commAt + 10, frames) w:setU32be(4, w:tell() - 8) return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ open function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) local info, err = parse(r) if not info then return nil, err end local maxFrames = opts and opts.maxFrames or 2 ^ 28 if info.frames > maxFrames then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames)) end local dec, derr if info.format == "ima4" then local base = { sampleRate = info.sampleRate, channels = info.channels, tags = info.tags } dec, derr = Adpcm.blocks(base, { kind = "ima_qt", buf = r.buf, offset = info.dataOffset, size = info.dataSize, frames = info.frames }) if dec then (dec :: any).bitrate = math.floor(info.sampleRate * 34 * 8 * info.channels / 64) end else dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags) end if not dec then return nil, derr end local d = dec :: any d.source = { format = "aiff", aifc = info.aifc, compression = info.compression, bitDepth = info.bits, sampleFormat = info.format, truncated = info.truncated or nil, } return dec, nil end return Aiff end __FILES["audio/ape"] = function() -- audio/ape: Monkey's Audio (.ape) via codecs/audio/Ape and ApeTag, from the Monkey's Audio SDK 13.28 (BSD 3-clause, -- licenses/monkeys-audio-LICENSE.txt). Supports: versions 3.95+, every level, 8-32-bit integer and 32-bit float, 1-32 -- channels, an ID3v2 prefix, seeking by the seek table. Not supported: files before 3.95, encoding. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") local Stream = __include("codecs/audio/Stream") local ApeTag = __include("codecs/audio/ApeTag") local ApeCodec = __include("codecs/audio/Ape") -- ------------------------------------------------------------------------------------------------ contract local Ape = { name = "ape", category = "audio", extensions = { "ape" }, mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" }, caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } }, } -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ constants local LEVELS = { [1000] = "fast", [2000] = "normal", [3000] = "high", [4000] = "extra high", [5000] = "insane" } -- ------------------------------------------------------------------------------------------------ sniff function Ape.sniff(r: Bytes.Reader): number local head = r:peek(4) if head == "MAC " or head == "MACF" then -- MACF: float samples return 1 end if string.sub(head, 1, 3) == "ID3" then local sz = 0 for i = 6, 9 do local v = r:peekU8(i) if v < 0 then return 0 end sz = sz * 128 + bit32.band(v, 127) end local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 local id = r:peek(4, 10 + sz + (if footer then 10 else 0)) return if id == "MAC " or id == "MACF" then 1 else 0 end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Ape.open(r, opts) if not dec then return nil, err end local d = dec :: any local limit = opts and opts.maxFrames or 2 ^ 28 if d.frames > limit or d.frames * d.channels > 2 ^ 28 then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) end return Pcm.drain(d, d.source, limit) end -- ------------------------------------------------------------------------------------------------ open function Ape.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) if type(r) == "buffer" then r = Bytes.reader(r :: any) end if type(r) ~= "table" or type(r.buf) ~= "buffer" then return nil, Err.new(Err.ARG, "open: expected a Reader") end local buf, base, limit = r.buf, r.base, r.limit local tags, tagInfo = ApeTag.find(buf, base, limit) local stop = if tagInfo then tagInfo.start else limit local info, err = ApeCodec.info(buf, base, stop) if not info then return nil, err end if info.channels * info.blocksPerFrame > 2 ^ 24 then return nil, Err.new(Err.LIMIT, "frames of " .. info.blocksPerFrame .. " blocks") end local codec, cerr = ApeCodec.decoder(info) if not codec then return nil, cerr end local frames = info.totalBlocks local bpf = info.blocksPerFrame local dec: any = { sampleRate = info.sampleRate, channels = info.channels, frames = frames, duration = frames / info.sampleRate, bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, tags = tags or {}, bitsPerSample = info.bitsPerSample, float = info.float, level = LEVELS[info.level] or tostring(info.level), version = info.version, md5 = info.md5, source = { format = "ape", bitDepth = info.bitsPerSample, float = info.float, level = info.level, version = info.version, programVersion = info.programVersion, tags = tagInfo and tagInfo.items }, } local count = info.totalFrames return Stream.packets(dec, { count = count, start = function(i: number): number return if i > count then frames else (i - 1) * bpf end, decode = function(i: number): (number?, Err.Err?) return codec:frame(buf, i) end, pcm = function(): { number } return codec.pcm end, reset = function() end, stop = frames, scale = if info.float then 1 else 1 / 2 ^ (info.bitsPerSample - 1), ints = not info.float, }) end return Ape end __FILES["audio/au"] = function() -- audio/au: Sun / NeXT audio (.au / .snd), big endian. Supports: encodings 1 (mu-law), 2-5 (8-32-bit linear), 6 / 7 -- (float), 27 (A-law), data size 0xFFFFFFFF (to the end), the annotation as tags.comment; encode to any of them. -- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Au = { name = "au", category = "audio", extensions = { "au", "snd" }, mime = { "audio/basic", "audio/x-au" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, } type DecodeOptions = { maxFrames: number?, -- default 2^28 } type EncodeOptions = { sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" } -- ------------------------------------------------------------------------------------------------ constants local ENCODINGS: { [number]: string } = { [1] = "ulaw", [2] = "s8", [3] = "s16be", [4] = "s24be", [5] = "s32be", [6] = "f32be", [7] = "f64be", [27] = "alaw", } local WRITE = { ulaw = { 1, "ulaw" }, s8 = { 2, "s8" }, s16 = { 3, "s16be" }, s24 = { 4, "s24be" }, s32 = { 5, "s32be" }, f32 = { 6, "f32be" }, f64 = { 7, "f64be" }, alaw = { 27, "alaw" }, } local BITS = { ulaw = 8, alaw = 8, s8 = 8, s16be = 16, s24be = 24, s32be = 32, f32be = 32, f64be = 64 } local function be32(b: buffer, o: number): number return bit32.byteswap(buffer.readu32(b, o)) end -- ------------------------------------------------------------------------------------------------ sniff function Au.sniff(r: Bytes.Reader): number return if r:peek(4) == ".snd" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode function Au.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = Au.open(r, opts) if not dec then return nil, err end return Pcm.drain(dec) end -- ------------------------------------------------------------------------------------------------ encode function Au.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then return nil, serr end local o: EncodeOptions = opts or {} local spec = WRITE[o.sampleFormat or "s16"] if not spec then return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) end if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then return nil, Err.new(Err.ARG, "the sample rate must be an integer") end -- annotation: the comment tag, NUL-terminated, padded to a multiple of 8 (at least 4 bytes, as Sun requires) local note = if type(src.tags.comment) == "string" then src.tags.comment else "" local alen = #note + 1 alen = math.max(8, alen + (8 - alen % 8) % 8) local w = Bytes.writer(65536) w:string(".snd") w:u32be(24 + alen) w:u32be(0xFFFFFFFF) w:u32be(spec[1]) w:u32be(src.sampleRate) w:u32be(src.channels) w:string(note) w:fill(0, alen - #note) local frames, perr = Pcm.encode(src, spec[2], w) if not frames then return nil, perr end w:setU32be(8, w:tell() - 24 - alen) return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ open function Au.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) local b, base, limit = r.buf, r.base, r.limit if limit - base < 24 or buffer.readstring(b, base, 4) ~= ".snd" then return nil, Err.new(Err.CORRUPT, "bad magic", base) end local off, size, enc, rate, ch = be32(b, base + 4), be32(b, base + 8), be32(b, base + 12), be32(b, base + 16), be32(b, base + 20) local fmt = ENCODINGS[enc] if not fmt then return nil, Err.new(Err.UNSUPPORTED, "encoding " .. enc, base + 12) end if ch < 1 or ch > 65535 then return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch, base + 20) end if rate < 1 then return nil, Err.new(Err.CORRUPT, "bad sample rate", base + 16) end if off < 24 or off > limit - base then return nil, Err.new(Err.CORRUPT, "bad data offset", base + 4) end local tags: Types.Tags = {} if off > 24 then local s = buffer.readstring(b, base + 24, off - 24) local z = string.find(s, "\0", 1, true) if z then s = string.sub(s, 1, z - 1) end if #s > 0 then tags.comment = s end end local avail = limit - base - off local truncated = false if size == 0xFFFFFFFF then size = avail elseif size > avail then size = avail truncated = true end local frameBytes = ch * Pcm.Convert.SIZE[fmt] local frames = size // frameBytes local maxFrames = opts and opts.maxFrames or 2 ^ 28 if frames > maxFrames then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", frames, maxFrames)) end local dec, derr = Pcm.rawDecoder(b, base + off, frames, ch, rate, fmt, tags) if not dec then return nil, derr end local d = dec :: any d.source = { format = "au", encoding = enc, sampleFormat = fmt, bitDepth = BITS[fmt], truncated = truncated or nil } return dec, nil end return Au end __FILES["audio/brstm"] = function() -- audio/brstm: Nintendo BRSTM (Wii, "RSTM", BE), BCSTM (3DS, "CSTM", LE), BFSTM (Wii U BE / Switch LE, "FSTM"); layouts -- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), bit-exact. Supports: DSP ADPCM, PCM16 / PCM8, 1-255 -- channels, loop points. Read only. Not supported: BCSTM IMA ADPCM, BRSTM 0.1, BFSTM regions, the track table. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") local Decoder = __include("codecs/audio/Adpcm/Decoder") -- ------------------------------------------------------------------------------------------------ contract local Brstm = { name = "brstm", category = "audio", extensions = { "brstm", "bcstm", "bfstm" }, mime = { "audio/x-brstm" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" }, caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ constants local CODECS = { [0] = "pcm8", [1] = "pcm16", [2] = "dsp", [3] = "ima" } -- ------------------------------------------------------------------------------------------------ sniff function Brstm.sniff(r: Bytes.Reader): number local m = r:peek(4) if m ~= "RSTM" and m ~= "CSTM" and m ~= "FSTM" then return 0 end local bom = r:peek(2, 4) return if bom == "\254\255" or bom == "\255\254" then 1 else 0 end function Brstm.variant(r: Bytes.Reader): string? local m = r:peek(4) return if m == "RSTM" then "brstm" elseif m == "CSTM" then "bcstm" elseif m == "FSTM" then "bfstm" else nil end -- ------------------------------------------------------------------------------------------------ decode function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = Brstm.open(r) if not dec then return nil, err end local d = dec :: any local limit = opts and opts.maxFrames or 2 ^ 28 if d.frames > limit or d.frames * d.channels > 2 ^ 28 then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) end return Pcm.drain(d, { format = "brstm", container = d.container, codec = d.codec, loop = d.loop }, limit) end -- ------------------------------------------------------------------------------------------------ open local function view(r: Bytes.Reader, be: boolean) local v = { err = nil :: string? } local size = r.limit - r.base local function at(o: number, n: number): Bytes.Reader? if o < 0 or o + n > size then v.err = "an offset points past the end" return nil end return r:sub(o, n) end function v.u8(o: number): number local s = at(o, 1) return if s then s:u8() else 0 end function v.u16(o: number): number local s = at(o, 2) return if s then (if be then s:u16be() else s:u16le()) else 0 end function v.i16(o: number): number local s = at(o, 2) return if s then (if be then s:i16be() else s:i16le()) else 0 end function v.u32(o: number): number local s = at(o, 4) return if s then (if be then s:u32be() else s:u32le()) else 0 end function v.i32(o: number): number local s = at(o, 4) return if s then (if be then s:i32be() else s:i32le()) else 0 end return v end type Layout = { codec: number, loop: boolean, ch: number, rate: number, loopStart: number, frames: number, blockSize: number, lastPadded: number, data: number, -- absolute adp: { number }, -- each channel's DSP info offset (coefficients, then gain, ps, yn1, yn2) hist: number?, -- the per-block history table: (yn1, yn2) per channel per block histEntries: number, } local function parseRstm(v: any): (Layout?, string?) if v.u16(0x06) ~= 0x0100 then return nil, string.format("unsupported: BRSTM version %d.%d", v.u8(0x06), v.u8(0x07)) end local head = v.u32(0x10) local adpc = v.u32(0x18) if v.u32(head) ~= 0x48454144 then -- "HEAD", read big-endian return nil, "no HEAD chunk" end local base = head + 8 local info = base + v.u32(base + 4) local chans = base + v.u32(base + 20) local ch = v.u8(info + 2) local L: Layout = { codec = v.u8(info), loop = v.u8(info + 1) ~= 0, ch = ch, rate = v.u16(info + 4), loopStart = v.u32(info + 8), frames = v.u32(info + 12), data = v.u32(info + 16), blockSize = v.u32(info + 24), lastPadded = v.u32(info + 40), adp = {}, hist = nil, histEntries = 0, } for c = 0, ch - 1 do local ci = base + v.u32(chans + 4 + c * 8 + 4) L.adp[c + 1] = base + v.u32(ci + 4) end if adpc > 0 and v.u32(adpc) == 0x41445043 then -- "ADPC" L.hist = adpc + 8 L.histEntries = (v.u32(adpc + 4) - 8) // math.max(1, 4 * ch) end return L, nil end local function parseFstm(v: any): (Layout?, string?) local info: number, seek: number, data: number = 0, 0, 0 local seekSize: number = 0 for i = 0, math.min(v.u16(0x10), 16) - 1 do local id, off = v.u16(0x14 + i * 12), v.u32(0x14 + i * 12 + 4) if id == 0x4000 then info = off elseif id == 0x4001 then seek = off seekSize = v.u32(0x14 + i * 12 + 8) :: number elseif id == 0x4002 then data = off end end if info == 0 or data == 0 then return nil, "no INFO or DATA block" end local stream = info + 8 + v.i32(info + 0x0C) local chans = info + 8 + v.i32(info + 0x1C) local ch = v.u8(stream + 2) local dataRef = stream + 0x30 local L: Layout = { codec = v.u8(stream), loop = v.u8(stream + 1) ~= 0, ch = ch, rate = v.u32(stream + 4), loopStart = v.u32(stream + 8), frames = v.u32(stream + 12), blockSize = v.u32(stream + 20), lastPadded = v.u32(stream + 36), data = if v.u16(dataRef) == 0x1F00 then data + 8 + v.i32(dataRef + 4) else data + 0x20, adp = {}, hist = nil, histEntries = 0, } for c = 0, ch - 1 do local ci = chans + v.i32(chans + 4 + c * 8 + 4) L.adp[c + 1] = ci + v.i32(ci + 4) end if seek > 0 and seekSize > 8 then L.hist = seek + 8 L.histEntries = (seekSize - 8) // math.max(1, 4 * ch) end return L, nil end function Brstm.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) if type(r) ~= "table" or type(r.buf) ~= "buffer" then return nil, Err.new(Err.ARG, "open: expected a Reader") end if r.limit - r.base < 0x40 then return nil, Err.new(Err.TRUNCATED, "the header runs past the end") end if Brstm.sniff(r) == 0 then return nil, Err.new(Err.CORRUPT, "not a BRSTM / BCSTM / BFSTM file") end local magic = r:peek(4) local be = r:peek(2, 4) == "\254\255" local v = view(r, be) local parsed: Layout?, msg: string? if magic == "RSTM" then if not be then return nil, Err.new(Err.CORRUPT, "a little-endian BRSTM") end parsed, msg = parseRstm(v) else parsed, msg = parseFstm(v) end if v.err then return nil, Err.new(Err.TRUNCATED, v.err) elseif not parsed then return nil, Err.from(msg) end local L = parsed :: Layout local codec = CODECS[L.codec] if not codec then return nil, Err.new(Err.CORRUPT, "codec " .. L.codec) elseif codec == "ima" then return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM streams") end local ch = L.ch if ch < 1 or L.rate < 1 then return nil, Err.new(Err.CORRUPT, "bad channel count or sample rate") end local size = r.limit - r.base - L.data if L.data < 0 or size < 0 then return nil, Err.new(Err.TRUNCATED, "the data starts past the end") end local kind = if codec == "dsp" then "dsp" elseif codec == "pcm8" then "s8" elseif be then "s16be" else "s16le" local coefs: buffer? = nil local hist: { number }? = nil if codec == "dsp" then coefs = buffer.create(64 * ch) hist = {} for c = 0, ch - 1 do local adp = L.adp[c + 1] for k = 0, 15 do buffer.writei32(coefs :: buffer, c * 64 + k * 4, v.i16(adp + k * 2)) end hist[c * 2 + 1], hist[c * 2 + 2] = v.i16(adp + 36), v.i16(adp + 38) end if v.err then return nil, Err.new(Err.TRUNCATED, v.err) end end local histAt, entries = L.hist, L.histEntries local loop = if L.loop and L.loopStart < L.frames then { start = L.loopStart, stop = L.frames } else nil local dec: any = { sampleRate = L.rate, channels = ch, tags = {}, container = magic, codec = codec, loop = loop } local block = L.blockSize if block < 1 or (kind == "dsp" and block % 8 ~= 0) or (kind ~= "s8" and block % 2 ~= 0) then return nil, Err.new(Err.CORRUPT, "bad block size " .. block) end local d, err = Decoder.interleaved(dec, { kind = kind :: any, buf = r.buf, offset = r.base + L.data, size = size, interleave = block, lastInterleave = if L.lastPadded > 0 and L.lastPadded <= block then L.lastPadded else block, frames = L.frames, coefs = coefs, hist = hist, restore = if codec == "dsp" and histAt then function(row: number, st: buffer): boolean if row >= entries then return false end for c = 0, ch - 1 do local p = (histAt :: number) + (row * ch + c) * 4 buffer.writei32(st, c * 8, v.i16(p)) buffer.writei32(st, c * 8 + 4, v.i16(p + 2)) end return v.err == nil end else nil, }) if d then d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0 end return d, err end return Brstm end __FILES["audio/caf"] = function() -- audio/caf: Apple Core Audio Format (CAF 1.0 spec). Supports: linear PCM (8-32-bit integer, 32 / 64-bit float, either -- endian), ALAC, AAC-LC (kuki esds), mu-law, A-law, IMA4; pakt trimming, data size -1, info tags, seeking; encode PCM -- (16 / 24-bit BE, 32-bit float) and ALAC (16 / 20 / 24-bit). Not supported: other compressed formats. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Chunks = __include("containers/Chunks") local Pcm = __include("codecs/audio/Pcm") local Stream = __include("codecs/audio/Stream") local Aac = __include("codecs/audio/Aac") local Alac = __include("codecs/audio/Alac") local Adpcm = __include("codecs/audio/Adpcm/Decoder") -- ------------------------------------------------------------------------------------------------ contract local Caf = { name = "caf", category = "audio", extensions = { "caf", "caff" }, mime = { "audio/x-caf" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" }, caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { maxPackets: number?, -- default 2^24 } type EncodeOptions = { codec: ("pcm" | "alac")?, -- default "alac" bitDepth: number?, -- pcm: 16 (default), 24, 32 (float); alac: 16 (default), 20, 24 tags: Types.Tags?, -- default: the audio's tags } -- ------------------------------------------------------------------------------------------------ constants local INFO_TAGS: { [string]: string } = { title = "title", artist = "artist", album = "album", year = "date", genre = "genre", ["track number"] = "track", comments = "comment", composer = "composer", copyright = "copyright", lyricist = "lyricist", ["encoding application"] = "encoder", ["recorded date"] = "recorded", tempo = "bpm", } local TAG_INFO: { [string]: string } = {} for k, v in INFO_TAGS do TAG_INFO[v] = k end local ULAW, ALAW = table.create(256, 0), table.create(256, 0) for i = 0, 255 do local u = 255 - i local t = (bit32.band(u, 15) * 8 + 132) * 2 ^ bit32.band(bit32.rshift(u, 4), 7) ULAW[i + 1] = if bit32.band(u, 128) ~= 0 then 132 - t else t - 132 local a = bit32.bxor(i, 0x55) local seg = bit32.band(bit32.rshift(a, 4), 7) local m = bit32.band(a, 15) * 16 + 8 if seg > 0 then m = (m + 256) * 2 ^ (seg - 1) end ALAW[i + 1] = if bit32.band(a, 128) ~= 0 then m else -m end -- ------------------------------------------------------------------------------------------------ sniff function Caf.sniff(r: Bytes.Reader): number local h = r:peek(8) if #h == 8 and string.sub(h, 1, 4) == "caff" and string.byte(h, 5) == 0 and string.byte(h, 6) == 1 then return 1 end return 0 end -- ------------------------------------------------------------------------------------------------ decode type Desc = { rate: number, format: string, flags: number, bytesPerPacket: number, framesPerPacket: number, channels: number, bits: number } type Parsed = { desc: Desc, dataStart: number, -- absolute dataEnd: number, cookie: buffer?, packets: { number }?, -- sizes (pakt) packetFrames: { number }?, priming: number, remainder: number, validFrames: number?, tags: Types.Tags, } -- the esds payload in a kuki (version / flags, then the ES_Descriptor) -> the DecoderSpecificInfo local function esdsConfig(b: buffer): buffer? local r = Bytes.reader(b) if r:peekU8() ~= 3 then r:skip(4) -- the esds atom's version / flags end local function len(): number local n = 0 for _ = 1, 4 do local c = r:u8() n = n * 128 + bit32.band(c, 127) if c < 128 then break end end return n end while not r:eof() and not r.err do local tag = r:u8() local n = len() if tag == 3 then r:skip(2) local f = r:u8() if bit32.band(f, 0x80) ~= 0 then r:skip(2) end if bit32.band(f, 0x40) ~= 0 then r:skip(r:u8()) end if bit32.band(f, 0x20) ~= 0 then r:skip(2) end elseif tag == 4 then r:skip(13) elseif tag == 5 then if n > 0 and r:need(n) then return r:bytes(n) end return nil else r:skip(n) end end return nil end local function vlq(r: Bytes.Reader): number local v = 0 for _ = 1, 8 do local c = r:u8() v = v * 128 + bit32.band(c, 127) if c < 128 then return v end end r:fail(Err.CORRUPT, "bad packet table entry") return 0 end local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?) if Caf.sniff(r) == 0 then return nil, Err.new(Err.CORRUPT, "not a CAF file", r.base) end local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} } local haveData = false -- 64-bit big-endian chunk sizes; the data chunk may say -1 (= to the end) or run past a truncated file for _, ch in Chunks.walk(r.buf, r.base + 8, r.limit, { bigEndian = true, sizeBytes = 8, openEnded = { data = true } }) do local typ, start = ch.id, ch.offset if ch.truncated and typ ~= "data" then return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", ch.start) end local stop = start + ch.avail local c = Bytes.reader(r.buf, start, stop - start) if typ == "desc" then p.desc = { rate = c:f64be(), format = c:string(4), flags = c:u32be(), bytesPerPacket = c:u32be(), framesPerPacket = c:u32be(), channels = c:u32be(), bits = c:u32be(), } if c.err then return nil, c.err end elseif typ == "data" then p.dataStart = start + 4 -- edit count p.dataEnd = stop haveData = true elseif typ == "kuki" then p.cookie = c:bytes(stop - start) elseif typ == "pakt" then local n = c:i64be() p.validFrames = c:i64be() p.priming = c:i32be() p.remainder = c:i32be() if c.err then return nil, c.err end if n < 0 or n > (o.maxPackets or 2 ^ 24) or n > c:remaining() then return nil, Err.new(Err.LIMIT, "packet table of " .. n .. " entries", start) end local d = p.desc if not d then return nil, Err.new(Err.CORRUPT, "pakt before desc", start) end local sizes, frames = table.create(n, 0), nil if d.framesPerPacket == 0 then frames = table.create(n, 0) end for i = 1, n do sizes[i] = if d.bytesPerPacket == 0 then vlq(c) else d.bytesPerPacket if frames then frames[i] = vlq(c) end end if c.err then return nil, c.err end p.packets, p.packetFrames = sizes, frames elseif typ == "info" then local n = c:u32be() for _ = 1, math.min(n, 1000) do local k = c:cstring() local v = c:cstring() if c.err then break end p.tags[INFO_TAGS[string.lower(k)] or string.lower(k)] = v end end if typ == "data" and stop >= r.limit then break end end if not p.desc then return nil, Err.new(Err.CORRUPT, "no desc chunk", r.base) end if not haveData then return nil, Err.new(Err.CORRUPT, "no data chunk", r.base) end local d = p.desc if d.channels < 1 or d.channels > 64 or d.rate <= 0 or d.rate ~= d.rate or d.rate > 1e7 then return nil, Err.new(Err.CORRUPT, "bad stream description") end return p, nil end type Source = { channels: number, rate: number, packetCount: number, packetFrames: (number) -> number, decode: (number) -> (number?, Err.Err?), pcm: { number }, reset: () -> (), codec: string, bits: number?, } local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?) local d = p.desc local b = r.buf local ch = d.channels local fmt = d.format if fmt == "lpcm" or fmt == "ulaw" or fmt == "alaw" then local bits = if fmt == "lpcm" then d.bits else 8 local float = fmt == "lpcm" and bit32.band(d.flags, 1) ~= 0 local little = fmt == "lpcm" and bit32.band(d.flags, 2) ~= 0 local bpf = d.bytesPerPacket if bpf == 0 then bpf = ch * (bits // 8) end if not (bits == 8 or bits == 16 or bits == 24 or bits == 32 or (bits == 64 and float)) or (float and bits < 32) then return nil, Err.new(Err.UNSUPPORTED, "linear PCM with " .. bits .. " bits") end local bps = bits // 8 if bpf < ch * bps then return nil, Err.new(Err.CORRUPT, "bytes per packet smaller than a frame") end local total = (p.dataEnd - p.dataStart) // bpf local per = 1024 local pcm = table.create(per * ch, 0) local scale = 1 / 2 ^ (bits - 1) local readu8, readi8 = buffer.readu8, buffer.readi8 local src: Source = { channels = ch, rate = d.rate, packetCount = (total + per - 1) // per, packetFrames = function(i: number): number return math.min(per, total - (i - 1) * per) end, pcm = pcm, reset = function() end, codec = if fmt == "lpcm" then "pcm" else fmt, bits = bits, decode = function(i: number): (number?, Err.Err?) local f0 = (i - 1) * per local n = math.min(per, total - f0) local k = 1 for f = f0, f0 + n - 1 do local q = p.dataStart + f * bpf for _ = 1, ch do local v if fmt == "ulaw" then v = ULAW[readu8(b, q) + 1] / 32768 elseif fmt == "alaw" then v = ALAW[readu8(b, q) + 1] / 32768 elseif float then if bits == 32 then v = if little then buffer.readf32(b, q) else Bytes.reader(b, q, 4):f32be() else v = if little then buffer.readf64(b, q) else Bytes.reader(b, q, 8):f64be() end elseif bits == 8 then v = readi8(b, q) * scale elseif bits == 16 then v = if little then buffer.readi16(b, q) else readi8(b, q) * 256 + readu8(b, q + 1) v *= scale elseif bits == 24 then if little then v = readi8(b, q + 2) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q) else v = readi8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2) end v *= scale else if little then v = buffer.readi32(b, q) else v = readi8(b, q) * 16777216 + readu8(b, q + 1) * 65536 + readu8(b, q + 2) * 256 + readu8(b, q + 3) end v *= scale end pcm[k] = v k += 1 q += bps end end return n, nil end, } return src, nil end local sizes = p.packets if not sizes or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none if d.bytesPerPacket > 0 then local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket sizes = table.create(n, d.bytesPerPacket) else return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table") end end local offsets = table.create(#(sizes :: { number }), 0) local o = p.dataStart for i, s in sizes :: { number } do offsets[i] = o o += s if o > p.dataEnd then -- a truncated file: keep the whole packets offsets[i] = nil :: any sizes = table.move(sizes :: { number }, 1, i - 1, 1, {}) break end end local count = #(sizes :: { number }) local fpp = d.framesPerPacket local pf = p.packetFrames local function framesOf(i: number): number return if pf then pf[i] else fpp end local cookie = p.cookie if fmt == "alac" then if not cookie then return nil, Err.new(Err.CORRUPT, "ALAC without a magic cookie") end local cfg, err = Alac.config(cookie :: buffer) if not cfg then return nil, err end local dec = Alac.decoder(cfg) local pcm = table.create(cfg.frameLength * cfg.channels, 0) local scale = 1 / 2 ^ (cfg.bitDepth - 1) return { channels = cfg.channels, rate = d.rate, packetCount = count, packetFrames = framesOf, pcm = pcm, reset = function() end, codec = "alac", bits = cfg.bitDepth, decode = function(i: number): (number?, Err.Err?) local n, e = dec:decode(b, offsets[i], (sizes :: { number })[i]) if not n then return nil, e end local src = dec.pcm for k = 1, n * cfg.channels do pcm[k] = src[k] * scale end return n, nil end, }, nil elseif fmt == "aac " then local asc = if cookie then esdsConfig(cookie :: buffer) else nil if not asc then return nil, Err.new(Err.CORRUPT, "AAC without an esds magic cookie") end local dec, err = Aac.decoder(asc :: buffer) if not dec then return nil, err end local ad = dec :: Aac.Decoder return { channels = ad.channels, rate = d.rate, packetCount = count, packetFrames = framesOf, pcm = ad.pcm, reset = function() ad:reset() end, codec = "aac", decode = function(i: number): (number?, Err.Err?) return ad:decode(b, offsets[i], (sizes :: { number })[i]) end, }, nil end return nil, Err.new(Err.UNSUPPORTED, "CAF format '" .. fmt .. "'") end function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) local p, err = parse(r, opts or {}) if not p then return nil, err end local pp = p :: Parsed if pp.desc.format == "ima4" then -- Apple IMA ADPCM: 34-byte packets per channel, 64 frames; the predictor carries across packets local ch = pp.desc.channels local packets = (pp.dataEnd - pp.dataStart) // (34 * ch) local frames = packets * 64 if pp.validFrames and pp.validFrames >= 0 then frames = math.min(frames, pp.validFrames) end local dec: any = { sampleRate = pp.desc.rate, channels = ch, tags = pp.tags, codec = "ima4", bitsPerSample = 16 } local d, derr = Adpcm.blocks(dec, { kind = "ima_qt", buf = r.buf, offset = pp.dataStart, size = pp.dataEnd - pp.dataStart, frames = frames }) if d then d.bitrate = math.floor(pp.desc.rate * 34 * 8 * ch / 64) end return d, derr end local s, serr = source(r, pp) if not s then return nil, serr end local src = s :: Source local ch, rate = src.channels, src.rate local starts = table.create(src.packetCount + 1, 0) local total = 0 for i = 1, src.packetCount do starts[i] = total total += src.packetFrames(i) end starts[src.packetCount + 1] = total local skip = math.max(0, p.priming) local stopAt = total if p.validFrames and p.validFrames >= 0 then stopAt = math.min(total, skip + p.validFrames) elseif p.remainder > 0 then stopAt = math.max(skip, total - p.remainder) end local frames = math.max(0, stopAt - skip) local dec: any = { sampleRate = rate, channels = ch, frames = frames, duration = frames / rate, bitrate = if frames > 0 then math.floor((p.dataEnd - p.dataStart) * 8 * rate / frames) else 0, tags = p.tags, codec = src.codec, bitsPerSample = src.bits, } return Stream.packets(dec, { count = src.packetCount, start = function(i: number): number return starts[i] end, decode = src.decode, pcm = function(): { number } return src.pcm end, reset = src.reset, skip = skip, stop = stopAt, preroll = if src.codec == "aac" then 1 else 0, }) end function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = Caf.open(r, opts) if not dec then return nil, err end local d: any = dec return Pcm.drain(d, { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample }) end -- ------------------------------------------------------------------------------------------------ encode local function chunk(w: Bytes.Writer, typ: string, size: number) w:string(typ) w:i64be(size) end function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") end local codec = o.codec or "alac" if codec ~= "alac" and codec ~= "pcm" then return nil, Err.new(Err.ARG, "codec must be 'alac' or 'pcm'") end local sr, ch = value.sampleRate, value.channels local depth = o.bitDepth or 16 if codec == "pcm" and depth ~= 16 and depth ~= 24 and depth ~= 32 then return nil, Err.new(Err.ARG, "pcm bitDepth 16, 24 or 32 (float)") end if ch < 1 or ch > 64 or sr <= 0 then return nil, Err.new(Err.ARG, "bad sample rate / channels") end local isAudio = value.kind == "audio" and type(value.samples) == "buffer" if not isAudio and type(value.read) ~= "function" then return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") end if isAudio and buffer.len(value.samples) < value.frames * ch * 4 then return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") end local done = 0 local chunkBuf: buffer? = nil local function nextBlock(n: number): (buffer?, number, number) if isAudio then local k = math.min(n, value.frames - done) local base = done * ch * 4 done += k return value.samples, base, k end local b, got = value:read(n, chunkBuf) chunkBuf = b done += got return b, 0, got end local readf32 = buffer.readf32 local data = Bytes.writer(65536) local sizes: { number } = {} local enc: Alac.Encoder? = nil if codec == "alac" then local e, err = Alac.encoder({ sampleRate = math.floor(sr), channels = ch, bitDepth = depth }) if not e then return nil, err end enc = e local ints = table.create(4096 * ch, 0) local peak = 2 ^ (depth - 1) while true do local b, base, n = nextBlock(4096) if not b or n <= 0 then break end for i = 0, n * ch - 1 do local v = math.floor(readf32(b, base + i * 4) * peak + 0.5) ints[i + 1] = math.clamp(v, -peak, peak - 1) end local pkt, perr = (e :: Alac.Encoder):encode(ints, 1, n) if not pkt then return nil, perr end data:bytes(pkt) table.insert(sizes, buffer.len(pkt)) end else local peak = 2 ^ (depth - 1) while true do local b, base, n = nextBlock(4096) if not b or n <= 0 then break end for i = 0, n * ch - 1 do local f = readf32(b, base + i * 4) if depth == 32 then data:f32be(f) else local v = math.clamp(math.floor(f * peak + 0.5), -peak, peak - 1) if depth == 16 then data:u16be(v % 65536) else data:u24be(v % 16777216) end end end end end local frames = done local w = Bytes.writer(data:tell() + 1024) w:string("caff") w:u16be(1) w:u16be(0) chunk(w, "desc", 32) w:f64be(sr) if codec == "alac" then w:string("alac") w:u32be(({ [16] = 1, [20] = 2, [24] = 3, [32] = 4 })[depth] or 1) w:u32be(0) w:u32be(4096) w:u32be(ch) w:u32be(0) else w:string("lpcm") w:u32be(if depth == 32 then 1 else 0) -- float / big-endian integer w:u32be(ch * depth // 8) w:u32be(1) w:u32be(ch) w:u32be(depth) end local tags = o.tags or value.tags or {} local keys = {} for k, v in tags do if type(v) == "string" then table.insert(keys, k) end end table.sort(keys) if #keys > 0 then local info = Bytes.writer(256) info:u32be(#keys) for _, k in keys do info:cstring(TAG_INFO[k] or k) info:cstring(tags[k]) end chunk(w, "info", info:tell()) w:bytes(info.buf, 0, info:tell()) end if enc then local cookie = Alac.cookie(enc.config) chunk(w, "kuki", buffer.len(cookie)) w:bytes(cookie) local pk = Bytes.writer(64 + #sizes * 2) pk:i64be(#sizes) pk:i64be(frames) pk:u32be(0) pk:u32be(#sizes * 4096 - frames) for _, s in sizes do -- BER variable-length integer local bytes = { s % 128 } local v = s // 128 while v > 0 do table.insert(bytes, 1, 128 + v % 128) v //= 128 end for _, x in bytes do pk:u8(x) end end chunk(w, "pakt", pk:tell()) w:bytes(pk.buf, 0, pk:tell()) end chunk(w, "data", data:tell() + 4) w:u32be(0) -- edit count w:bytes(data.buf, 0, data:tell()) return w:finish(), nil end return Caf end __FILES["audio/flac"] = function() -- audio/flac: FLAC (RFC 9639), native and Ogg FLAC; absorbed from flac-luau 7083d0d (same author). Supports: every -- subframe type, Rice / Rice2, 4-32 bits, 1-8 channels, CRC-16 resync, seeking, an ID3v2 prefix, the main metadata -- blocks; encode levels 0-8 (libFLAC presets), 4-24 bits. Not supported: MD5 check on decode, chained Ogg, Ogg output. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Ogg = __include("containers/Ogg") local Stream = __include("audio/flac/Stream") local Encode = __include("codecs/audio/Flac/Encode") local Pcm = __include("codecs/audio/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Flac = { name = "flac", category = "audio", extensions = { "flac", "oga" }, mime = { "audio/flac", "audio/x-flac" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Flac/Frame", "codecs/audio/Flac/Encode" }, caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true }, } -- ------------------------------------------------------------------------------------------------ types type Decoder = Stream.Decoder type OpenOptions = { crc16: boolean?, -- default true; a bad frame is skipped by resyncing maxFrames: number?, -- default 2^28 } type EncodeOptions = { level: number?, -- 0..8 like libFLAC's -0 .. -8 (default 5) bits: number?, -- 4..24; default the source's bit depth if 4..24, else 16 blockSize: number?, -- 16..65535 (default: the level's, 1152 or 4096) seekInterval: number?, -- seconds between SEEKTABLE points when the length is known (default 10; 0 = none) padding: number?, -- bytes of PADDING after the metadata (default 0) } -- ------------------------------------------------------------------------------------------------ sniff function Flac.sniff(r: Bytes.Reader): number local head = r:peek(4) if head == "fLaC" then return 1 end if head == "OggS" then -- the first page's packet: 0x7F "FLAC" (the Ogg FLAC mapping) local nseg = r:peekU8(26) if nseg > 0 and r:peek(5, 27 + nseg) == "\127FLAC" then return 1 end return 0 end if string.sub(head, 1, 3) == "ID3" then -- an ID3v2 tag, then fLaC (mp3 files start with ID3 too) local sz = 0 for i = 6, 9 do local v = r:peekU8(i) if v < 0 then return 0 end sz = sz * 128 + bit32.band(v, 127) end local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 return if r:peek(4, 10 + sz + (if footer then 10 else 0)) == "fLaC" then 1 else 0 end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Flac.open(r, opts) if not dec then return nil, err end local d = dec :: any local limit = opts and opts.maxFrames or 2 ^ 28 if d.frames > limit or d.frames * d.channels > 2 ^ 28 then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) end return Pcm.drain(d, { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures, comments = d.comments }, limit) end -- ------------------------------------------------------------------------------------------------ encode function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then return nil, serr end local o: EncodeOptions = opts or {} local level = o.level or 5 if type(level) ~= "number" or level ~= math.floor(level) or level < 0 or level > 8 then return nil, Err.new(Err.ARG, "level must be 0..8") end local bits = o.bits if bits == nil then local v = value :: any local sb = (type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.bitDepth) or v.bitsPerSample bits = if type(sb) == "number" and sb >= 4 and sb <= 24 then sb else 16 end if type(bits) ~= "number" or bits ~= math.floor(bits) or bits < 4 or bits > 24 then return nil, Err.new(Err.ARG, "bits must be 4..24") end local bs = o.blockSize if bs ~= nil and (type(bs) ~= "number" or bs ~= math.floor(bs) or bs < 16 or bs > 65535) then return nil, Err.new(Err.ARG, "blockSize must be 16..65535") end if src.channels > 8 then return nil, Err.new(Err.ARG, "FLAC holds at most 8 channels") end if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 20 then return nil, Err.new(Err.ARG, "the sample rate must be an integer below 2^20") end local out, msg = Encode.encode(src :: any, { level = level, bits = bits :: number, blockSize = bs, seekInterval = math.max(0, o.seekInterval or 10), padding = math.clamp(math.floor(o.padding or 0), 0, 0xFFFFFF), vendor = "rosetta", }) if not out then return nil, Err.new(Err.CORRUPT, tostring(msg)) end return out, nil end -- ------------------------------------------------------------------------------------------------ open function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) if type(r) == "buffer" then r = Bytes.reader(r :: any) end if type(r) ~= "table" or type(r.buf) ~= "buffer" then return nil, Err.new(Err.ARG, "open: expected a Reader") end local dec, msg, code = Stream.open(r.buf, r.base, r.limit - r.base, opts) if not dec then return nil, Err.new(code or Err.CORRUPT, tostring(msg)) end return dec, nil end -- ------------------------------------------------------------------------------------------------ extras Flac.Stream = Stream Flac.Ogg = Ogg return Flac end __FILES["audio/flac/Meta"] = @native function() -- audio/flac/Meta: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE blocks; absorbed from flac-luau 7083d0d. local VorbisComment = __include("codecs/audio/VorbisComment") local readu8, readu32 = buffer.readu8, buffer.readu32 local Meta = {} @native local function be16(b: buffer, p: number): number return readu8(b, p) * 256 + readu8(b, p + 1) end @native local function be24(b: buffer, p: number): number return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) end @native local function be32(b: buffer, p: number): number return be16(b, p) * 65536 + be16(b, p + 2) end type StreamInfo = { minBlockSize: number, maxBlockSize: number, minFrameSize: number, -- 0 = unknown maxFrameSize: number, sampleRate: number, channels: number, bitsPerSample: number, totalSamples: number, -- 0 = unknown md5: string, -- 32 hex digits (all zero = not set) } type SeekPoint = { sample: number, offset: number, samples: number } type Picture = { type: number, mime: string, description: string, width: number, height: number, depth: number, colors: number, offset: number, -- the image bytes are buf[offset .. offset + size - 1] size: number, } type Info = { streamInfo: StreamInfo, seekTable: { SeekPoint }, vendor: string, tags: { [string]: string }, -- upper-case keys; repeated keys are joined with "; " comments: { { key: string, value: string } }, pictures: { Picture }, firstFrame: number, -- byte offset just after the last metadata block } @native local function streamInfo(b: buffer, p: number): StreamInfo local b12, b13 = readu8(b, p + 12), readu8(b, p + 13) local hex = table.create(16) for i = 0, 15 do hex[i + 1] = string.format("%02x", readu8(b, p + 18 + i)) end return { minBlockSize = be16(b, p), maxBlockSize = be16(b, p + 2), minFrameSize = be24(b, p + 4), maxFrameSize = be24(b, p + 7), sampleRate = readu8(b, p + 10) * 4096 + readu8(b, p + 11) * 16 + bit32.rshift(b12, 4), channels = bit32.band(bit32.rshift(b12, 1), 7) + 1, bitsPerSample = bit32.band(b12, 1) * 16 + bit32.rshift(b13, 4) + 1, totalSamples = bit32.band(b13, 15) * 4294967296 + be32(b, p + 14), md5 = table.concat(hex), } end @native local function vorbisComment(b: buffer, p: number, e: number, info: Info): boolean if p + 4 > e then return false end local vl = readu32(b, p) p += 4 if p + vl > e then return false end info.vendor = buffer.readstring(b, p, vl) p += vl if p + 4 > e then return false end local n = readu32(b, p) p += 4 for _ = 1, n do if p + 4 > e then return false end local l = readu32(b, p) p += 4 if p + l > e then return false end local s = buffer.readstring(b, p, l) p += l local eq = string.find(s, "=", 1, true) if eq then local name, value = string.sub(s, 1, eq - 1), string.sub(s, eq + 1) table.insert(info.comments, { key = string.upper(name), value = value }) local key = VorbisComment.tagKey(name) local old = info.tags[key] info.tags[key] = if old then old .. "; " .. value else value end end return true end @native local function picture(b: buffer, p: number, e: number): Picture? if p + 8 > e then return nil end local typ = be32(b, p) local ml = be32(b, p + 4) p += 8 if p + ml + 4 > e then return nil end local mime = buffer.readstring(b, p, ml) p += ml local dl = be32(b, p) p += 4 if p + dl + 20 > e then return nil end local desc = buffer.readstring(b, p, dl) p += dl local pic = { type = typ, mime = mime, description = desc, width = be32(b, p), height = be32(b, p + 4), depth = be32(b, p + 8), colors = be32(b, p + 12), offset = p + 20, size = be32(b, p + 16), } if pic.offset + pic.size > e then return nil end return pic end @native function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?) if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then return nil, "Flac: no fLaC marker" end local info: Info = { streamInfo = nil :: any, seekTable = {}, vendor = "", tags = {}, comments = {}, pictures = {}, firstFrame = 0, } local p = pos + 4 while true do if p + 4 > len then return nil, "Flac: truncated metadata" end local h = readu8(b, p) local last = h >= 128 local typ = bit32.band(h, 127) local size = be24(b, p + 1) p += 4 local e = p + size if e > len then return nil, "Flac: truncated metadata block" end if typ == 0 then if size < 34 then return nil, "Flac: bad STREAMINFO" end info.streamInfo = streamInfo(b, p) elseif typ == 3 then for q = p, e - 18, 18 do local hi = be32(b, q) if hi ~= 0xFFFFFFFF then -- placeholder points are all ones table.insert(info.seekTable, { sample = hi * 4294967296 + be32(b, q + 4), offset = be32(b, q + 8) * 4294967296 + be32(b, q + 12), samples = be16(b, q + 16), }) end end elseif typ == 4 then vorbisComment(b, p, e, info) elseif typ == 6 then local pic = picture(b, p, e) if pic then table.insert(info.pictures, pic) end elseif typ == 127 then return nil, "Flac: invalid metadata block type" end p = e if last then break end end if not info.streamInfo then return nil, "Flac: no STREAMINFO" end local si = info.streamInfo if si.sampleRate == 0 then return nil, "Flac: bad STREAMINFO values" end info.firstFrame = p return info, nil end return Meta end __FILES["audio/flac/Stream"] = @native function() -- audio/flac/Stream: streaming FLAC decoder (native and Ogg FLAC); absorbed from flac-luau 7083d0d (same author). local Bytes = __include("core/Bytes") local Ogg = __include("containers/Ogg") local Frame = __include("codecs/audio/Flac/Frame") local Meta = __include("audio/flac/Meta") local Stream = {} local writef32, writei32 = buffer.writef32, buffer.writei32 type Header = any -- Frame.Header local PAD = Frame.PAD type Decoder = { sampleRate: number, channels: number, bitsPerSample: number, frames: number, -- total sample frames (per channel); 0 if unknown and not found duration: number, -- seconds bitrate: number, -- average bits per second of the audio data tags: { [string]: string }, comments: { { key: string, value: string } }, vendor: string, md5: string, seekTable: { any }, pictures: { any }, container: string, -- "flac" | "ogg" read: (Decoder, number, buffer?) -> (buffer, number), readInt: (Decoder, number, buffer?) -> (buffer, number), seek: (Decoder, number) -> boolean, seekSample: (Decoder, number) -> boolean, position: (Decoder) -> (number, number), } local Dec = {} Dec.__index = Dec @native local function sampleOf(self: any, h: Header): number return if h.variable then h.number else h.number * self._nominal end @native local function plausible(self: any, h: Header): boolean if h.channels ~= self.channels or h.bps ~= self.bitsPerSample or h.blockSize > 65536 then return false end if self.frames > 0 and sampleOf(self, h) >= self.frames then return false end return true end @native local function findFrame(self: any, pos: number, limit: number): Header? local b, len, si = self._b, self._len, self._si while true do local h = Frame.find(b, pos, limit, len, si) if not h then return nil end if plausible(self, h) then return h end pos = h.offset + 1 end end @native local function ensure(self: any, n: number) if n > self._cap then for c = 1, self.channels do self._chans[c] = table.create(n, 0) end self._cap = n end end @native local function decodeAt(self: any, pos: number): boolean local b, len = self._b, self._len while true do local h = Frame.header(b, pos, len, self._si) if not h or not plausible(self, h) then h = findFrame(self, pos, len) if not h then self._pos = len return false end end ensure(self, h.blockSize) local nextPos = Frame.decode(b, len, h, self._chans, self._cf, self._crc) if nextPos then local s = sampleOf(self, h) local n = h.blockSize if self.frames > 0 and s + n > self.frames then n = math.max(0, self.frames - s) end self._pos = nextPos self._fs = s self._fn = n self._cur = 0 return true end pos = h.offset + 1 end end @native local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?): (buffer, number) local ch = self.channels local want = math.floor(tonumber(maxFrames) or 0) if not (want >= 0) then want = 0 end want = math.min(want, 2 ^ 26 // ch) -- keeps the output buffer under 256 MB local reuse = dst ~= nil and type(dst) == "buffer" and buffer.len(dst) >= want * ch * 4 local out = if reuse then dst :: buffer else buffer.create(want * ch * 4) local got = 0 local scale = 1 / 2 ^ (self.bitsPerSample - 1) local stride = ch * 4 while got < want do if self._cur >= self._fn then if self._pos >= self._len or not decodeAt(self, self._pos) then self._fs += self._cur self._cur, self._fn = 0, 0 break end end local take = math.min(want - got, self._fn - self._cur) local from = self._cur + 1 local to = self._cur + take for c = 1, ch do local s = self._chans[c] local o = (got * ch + c - 1) * 4 if asInt then for i = from, to do writei32(out, o, s[i]) o += stride end else for i = from, to do writef32(out, o, s[i] * scale) o += stride end end end self._cur += take got += take end if got < want and not reuse then local short = buffer.create(got * ch * 4) buffer.copy(short, 0, out, 0, got * ch * 4) out = short end return out, got end @native function Dec.read(self: any, maxFrames: number, out: buffer?): (buffer, number) return pull(self, maxFrames, false, out) end @native function Dec.readInt(self: any, maxFrames: number, out: buffer?): (buffer, number) return pull(self, maxFrames, true, out) end @native function Dec.position(self: any): (number, number) local s = self._fs + self._cur return s / self.sampleRate, s end @native function Dec.seekSample(self: any, t: number): boolean t = math.floor(tonumber(t) or 0) if not (t >= 0) then t = 0 end if self.frames > 0 and t >= self.frames then self._pos, self._fs, self._fn, self._cur = self._len, self.frames, 0, 0 return true end if self._fn > 0 and t >= self._fs and t < self._fs + self._fn then self._cur = t - self._fs return true end local first, len = self._first, self._len local lo, hi = first, len for _, sp in self.seekTable do local o = first + sp.offset if o < len then if sp.sample <= t then lo = math.max(lo, o) else hi = math.min(hi, o) break end end end local window = math.max(16384, 2 * self._si.maxFrameSize) while hi - lo > window do local mid = (lo + hi) // 2 local h = findFrame(self, mid, hi) if h and sampleOf(self, h) <= t then lo = h.offset else hi = mid end end local pos = lo while true do local h = findFrame(self, pos, len) if not h then self._pos, self._fs, self._fn, self._cur = len, math.max(t, self.frames), 0, 0 return false end local s = sampleOf(self, h) if s + h.blockSize > t then if decodeAt(self, h.offset) then if self._fs <= t and t < self._fs + self._fn then self._cur = t - self._fs return true elseif self._fs > t then return false end pos = self._pos else return false end else pos = h.offset + h.size end end end @native function Dec.seek(self: any, seconds: number): boolean return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)) end @native local function scanLength(self: any): number local len = self._len local step = math.max(65536, 2 * self._si.maxFrameSize) local from = len while from > self._first do local start = math.max(self._first, from - step) local best: Header? = nil local pos = start while true do local h = findFrame(self, pos, from) if not h then break end best = h pos = h.offset + 1 end if best then local s = sampleOf(self, best) -- the last frame may be shorter than its header claims only via STREAMINFO, which is unknown here return s + best.blockSize end from = start end return 0 end @native local function skipId3(b: buffer, base: number, len: number): number local p = 0 while p + 10 <= len and buffer.readstring(b, base + p, 3) == "ID3" do local sz = 0 for i = 6, 9 do sz = sz * 128 + bit32.band(buffer.readu8(b, base + p + i), 127) end local footer = bit32.band(buffer.readu8(b, base + p + 5), 0x10) ~= 0 p += 10 + sz + (if footer then 10 else 0) end return p end @native function Stream.open(buf: buffer, base: number, srcLen: number, opts: { crc16: boolean? }?): (Decoder?, string?, string?) local b, len, container if srcLen >= 4 and buffer.readstring(buf, base, 4) == "OggS" then local demux, err = Ogg.open(Bytes.reader(buf, base, srcLen)) if not demux then return nil, (err :: any).message, "CORRUPT" end local serial = demux:find("flac") if not serial then return nil, "no FLAC stream in the Ogg file", "CORRUPT" end -- rebuild a native stream: "fLaC" + metadata (from the header packets) + frames (one per packet) local packets, total = {}, 0 for p in demux:packets(serial) do local off, size = p.offset, p.size if #packets == 0 then if size < 13 then return nil, "bad Ogg FLAC header", "CORRUPT" end off += 9 size -= 9 end table.insert(packets, { p.data, off, size }) total += size end b = buffer.create(total + PAD) local o = 0 for _, p in packets do buffer.copy(b, o, p[1], p[2], p[3]) o += p[3] end len = total container = "ogg" else local start = skipId3(buf, base, srcLen) if start + 4 > srcLen or buffer.readstring(buf, base + start, 4) ~= "fLaC" then return nil, "not a FLAC file", "CORRUPT" end len = srcLen - start b = buffer.create(len + PAD) buffer.copy(b, 0, buf, base + start, len) container = "flac" end local info, err = Meta.parse(b, 0, len) if not info then return nil, err, "CORRUPT" end local si = info.streamInfo local self = setmetatable({ sampleRate = si.sampleRate, channels = si.channels, bitsPerSample = si.bitsPerSample, frames = si.totalSamples, duration = 0, bitrate = 0, tags = info.tags, comments = info.comments, vendor = info.vendor, md5 = si.md5, seekTable = info.seekTable, pictures = info.pictures, container = container, _b = b, _len = len, _si = si, _first = info.firstFrame, _pos = info.firstFrame, _chans = {}, _cap = 0, _cf = table.create(32, 0), _crc = not (opts and opts.crc16 == false), _fs = 0, _fn = 0, _cur = 0, _nominal = math.max(si.maxBlockSize, 1), }, Dec) ensure(self, math.max(si.maxBlockSize, 16)) local h = findFrame(self, info.firstFrame, len) if h then if not h.variable then self._nominal = h.blockSize end end if self.frames == 0 then self.frames = scanLength(self) end self.duration = self.frames / self.sampleRate if self.duration > 0 then self.bitrate = (len - info.firstFrame) * 8 / self.duration end return self :: any, nil end Stream.Dec = Dec return Stream end __FILES["audio/m4a"] = function() -- audio/m4a: MPEG-4 audio (M4A / M4B / MP4 / MOV audio tracks) via containers/IsoBmff. Supports: AAC-LC (HE-AAC plays -- its core), ALAC, edit-list gapless trimming, seeking, iTunes tags and cover art; encode ALAC (16 / 20 / 24-bit, 1-8 -- channels). Not supported: writing AAC, other codecs in MP4 (UNSUPPORTED), encrypted files. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") local Stream = __include("codecs/audio/Stream") local IsoBmff = __include("containers/IsoBmff") local Aac = __include("codecs/audio/Aac") local Alac = __include("codecs/audio/Alac") -- ------------------------------------------------------------------------------------------------ contract local M4a = { name = "m4a", category = "audio", extensions = { "m4a", "m4b", "m4r" }, mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream" }, caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { track: number?, -- the track id to play (default: the first AAC / ALAC track) gapless: boolean?, -- apply the edit list (default true) maxSamples: number?, -- default 2^25 } type EncodeOptions = { bitDepth: number?, -- 16 (default), 20 or 24 frameLength: number?, -- samples per packet, default 4096 tags: Types.Tags?, -- default: the audio's tags pictures: { { mime: string, data: buffer } }?, -- default: audio.meta.pictures } -- ------------------------------------------------------------------------------------------------ constants local AUDIO_BRANDS: { [string]: number } = { ["M4A "] = 1, ["M4B "] = 1, ["M4P "] = 1, ["M4V "] = 0.3 } -- ------------------------------------------------------------------------------------------------ sniff function M4a.sniff(r: Bytes.Reader): number local brand = IsoBmff.sniff(r) if brand == nil then return 0 end if AUDIO_BRANDS[brand] then return AUDIO_BRANDS[brand] end if brand == "avif" or brand == "avis" or brand == "heic" or brand == "heix" or brand == "mif1" or brand == "msf1" or brand == "crx " then return 0 end return 0.4 -- an MP4 / MOV that may hold audio; a video format claims it more strongly end -- ------------------------------------------------------------------------------------------------ decode type PacketDecoder = { channels: number, sampleRate: number, frameSize: number, pcm: { number }, decode: (buf: buffer, off: number, len: number) -> (number?, Err.Err?), reset: () -> (), } local function packetDecoder(t: IsoBmff.Track): (PacketDecoder?, Err.Err?) if not t.config then return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " (" .. t.codec .. ") has no codec configuration") end if t.codec == "alac" then local cfg, err = Alac.config(t.config :: buffer) if not cfg then return nil, err end local dec = Alac.decoder(cfg) local pcm = table.create(cfg.frameLength * cfg.channels, 0) local scale = 1 / 2 ^ (cfg.bitDepth - 1) local pd: PacketDecoder = { channels = cfg.channels, sampleRate = if cfg.sampleRate > 0 then cfg.sampleRate else (t.sampleRate or 44100), frameSize = cfg.frameLength, pcm = pcm, decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?) local n, e = dec:decode(buf, off, len) if not n then return nil, e end local src = dec.pcm for i = 1, n * cfg.channels do pcm[i] = src[i] * scale end return n, nil end, reset = function() end, } return pd, nil elseif t.codec == "aac" then local dec, err = Aac.decoder(t.config :: buffer) if not dec then return nil, err end local d = dec :: Aac.Decoder local pd: PacketDecoder = { channels = d.channels, sampleRate = d.sampleRate, frameSize = d.frameLength, pcm = d.pcm, decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?) return d:decode(buf, off, len) end, reset = function() d:reset() end, } return pd, nil end return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4") end function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) local o: DecodeOptions = opts or {} local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples }) if not movie then return nil, err end local track: IsoBmff.Track? = nil local other: IsoBmff.Track? = nil for _, t in movie.tracks do if t.kind == "audio" then if o.track and t.id ~= o.track then continue end if t.codec == "aac" or t.codec == "alac" then track = t break end other = other or t end end if not track then if other then return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. other.codec .. " in MP4") end return nil, Err.new(Err.CORRUPT, "no audio track") end local t = track :: IsoBmff.Track local pd, perr = packetDecoder(t) if not pd then return nil, perr end local p = pd :: PacketDecoder local channels, sr = p.channels, p.sampleRate local tickScale = sr / t.timescale local gapless = o.gapless ~= false local skip = if gapless then math.floor(t.skip * tickScale + 0.5) else 0 local total = 0 for i = 1, t.sampleCount do total += t.durations[i] end total = math.floor(total * tickScale + 0.5) if gapless and t.playDuration then total = math.min(total, skip + math.floor(t.playDuration * tickScale + 0.5)) end local tags, pictures = IsoBmff.tags(r, movie) -- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 ..." (hex) local smpb = tags.itunsmpb if gapless and not t.edits and smpb then local f: { number } = {} for w in string.gmatch(smpb, "%x+") do table.insert(f, tonumber(w, 16) :: number) end if #f >= 4 and f[2] and f[4] and f[4] > 0 and f[2] + f[4] <= total then skip = f[2] total = f[2] + f[4] end end local frames = math.max(0, total - skip) local buf = r.buf local dec: any = { sampleRate = sr, channels = channels, frames = frames, duration = frames / sr, bitrate = 0, tags = tags, pictures = pictures, codec = t.codec, track = t, movie = movie, } local bytes = 0 for i = 1, t.sampleCount do bytes += t.sizes[i] end dec.bitrate = if frames > 0 then math.floor(bytes * 8 * sr / frames) else (t.bitrate or 0) -- packet start frames (media ticks -> frames); one AAC packet of pre-roll for the overlap when seeking return Stream.packets(dec, { count = t.sampleCount, start = function(i: number): number return math.floor((t.dts[i] or (t.dts[t.sampleCount] or 0) + (t.durations[t.sampleCount] or 0)) * tickScale + 0.5) end, decode = function(i: number): (number?, Err.Err?) return p.decode(buf, t.offsets[i], t.sizes[i]) end, pcm = function(): { number } return p.pcm end, reset = p.reset, skip = skip, stop = total, preroll = if t.codec == "aac" then 1 else 0, cumulative = true, }) end function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = M4a.open(r, opts) if not dec then return nil, err end local d: any = dec local audio, derr = Pcm.drain(d, { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand }) if audio and #d.pictures > 0 then audio.meta.pictures = d.pictures end return audio, derr end -- ------------------------------------------------------------------------------------------------ encode function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") end local sr, ch = value.sampleRate, value.channels local enc, eerr = Alac.encoder({ sampleRate = sr, channels = ch, bitDepth = o.bitDepth or 16, frameLength = o.frameLength }) if not enc then return nil, eerr end local e = enc :: Alac.Encoder local depth = e.config.bitDepth local fl = e.config.frameLength local peak = 2 ^ (depth - 1) local packets: { buffer } = {} local durations: { number } = {} local ints = table.create(fl * ch, 0) local floor = math.floor local readf32 = buffer.readf32 local src: buffer, srcFrames = nil :: any, 0 local isAudio = value.kind == "audio" and type(value.samples) == "buffer" if isAudio then src, srcFrames = value.samples, value.frames if buffer.len(src) < srcFrames * ch * 4 then return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") end elseif type(value.read) ~= "function" then return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") end local done = 0 local chunk: buffer? = nil while true do local n, b, base if isAudio then n = math.min(fl, srcFrames - done) b, base = src, done * ch * 4 else local got b, got = value:read(fl, chunk) chunk = b n, base = got, 0 end if n <= 0 then break end for i = 0, n * ch - 1 do local v = floor(readf32(b, base + i * 4) * peak + 0.5) if v >= peak then v = peak - 1 elseif v < -peak then v = -peak end ints[i + 1] = v end local pkt, perr = e:encode(ints, 1, n) if not pkt then return nil, perr end table.insert(packets, pkt) table.insert(durations, n) done += n if isAudio and done >= srcFrames then break end end local tags = o.tags or value.tags or {} local pictures = o.pictures or (value.meta and value.meta.pictures) or nil local timescale = if sr < 65536 then sr else 0 local file, merr = IsoBmff.mux({ brand = "M4A ", minor = 0, compatible = { "M4A ", "mp42", "isom" }, timescale = 1000, tracks = { { kind = "audio", entry = "alac", timescale = if timescale > 0 then timescale else 48000, samples = packets, durations = if timescale > 0 then durations else (function() local d = {} for i, v in durations do d[i] = math.floor(v * 48000 / sr + 0.5) end return d end)(), sampleRate = sr, channels = ch, bitsPerSample = depth, config = Alac.cookie(e.config), }, }, tags = tags, pictures = pictures, }) if not file then return nil, merr end return file, nil end return M4a end __FILES["audio/mp3"] = function() -- audio/mp3: MPEG audio layers I-III (ISO/IEC 11172-3, 13818-3, MPEG-2.5); absorbed from mp3-luau c755bbf, a port of -- minimp3 by lieff (CC0: licenses/minimp3-CC0.txt). Supports: every mode, CBR / VBR / free format, Xing / LAME gapless, -- exact seeking, ID3v2 / ID3v1 tags; encode layers III / II (CBR). Not supported: MPEG-2 multichannel, CRC, VBR output. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Header = __include("codecs/audio/Mpa/Header") local Index = __include("audio/mp3/Index") local Tags = __include("audio/mp3/Tags") local Stream = __include("audio/mp3/Stream") local Encode3 = __include("codecs/audio/Mpa/Encode3") local Encode2 = __include("codecs/audio/Mpa/Encode2") local Pcm = __include("codecs/audio/Pcm") local Resample = __include("codecs/audio/Resample") -- ------------------------------------------------------------------------------------------------ contract local Mp3 = { name = "mp3", category = "audio", extensions = { "mp3", "mp2", "mp1", "mpga" }, mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/Mpa/Header", "codecs/audio/Mpa/Core", "codecs/audio/Mpa/Encode3", "codecs/audio/Mpa/Encode2" }, caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 }, } -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { maxFrames: number?, -- default 2^31 } type Decoder = Stream.Decoder type EncodeOptions = { layer: number?, -- 3 (MP3, default) or 2 (MP2) bitrate: number?, -- bits per second, constant: one of the layer's rates (default 128000 for layer III, 192000 for -- layer II; MPEG-2 / 2.5 rates: 64000 / 96000); values below 1000 are kbit/s (128 = 128000, the old unit) mode: ("stereo" | "joint" | "mono")?, -- default "joint" (mid / side) for stereo layer III, "stereo" for layer II, -- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo" id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags) sampleRate: number?, -- output rate (one the layer holds); default the input rate if possible, else the nearest -- higher one (input at other rates is resampled through codecs/audio/Resample) resampleQuality: ("low" | "medium" | "high")?, -- codecs/audio/Resample quality (default "medium") } -- ------------------------------------------------------------------------------------------------ constants local MAX_FRAMES = 2 ^ 31 -- ------------------------------------------------------------------------------------------------ sniff function Mp3.sniff(r: Bytes.Reader): number local b, p, lim = r.buf, r.pos, r.limit local id3 = false for _ = 1, 4 do -- (ffmpeg writes a tag even when the input had one: tags can follow each other) local n = if p + 3 <= lim and buffer.readstring(b, p, 3) == "ID3" then Tags.id3v2Size(b, p, lim) else 0 if n <= 0 then break end id3 = true p += n end if p + 4 > lim or not Header.valid(b, p) then return if id3 then 0.5 else 0 end local fb = Header.frameBytes(b, p, 0) if fb > 0 then fb += Header.padding(b, p) if p + fb + 4 <= lim and Header.compare(b, p, p + fb) then return 0.9 end if p + fb == lim then return 0.6 end end return if id3 then 0.7 else 0.25 end -- ------------------------------------------------------------------------------------------------ decode function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Mp3.open(r, opts) if not dec then return nil, err end local a, derr = Pcm.drain(dec, { format = "mp3", layer = dec.layer, version = dec.version, bitrate = dec.bitrate, vbr = dec.vbr }) if a and a.frames < dec.frames then return nil, Err.new(Err.CORRUPT, string.format("decoded %d of %d frames", a.frames, dec.frames)) end return a, derr end -- ------------------------------------------------------------------------------------------------ encode local ID3_FRAMES = { { "title", "TIT2" }, { "artist", "TPE1" }, { "album", "TALB" }, { "albumartist", "TPE2" }, { "year", "TDRC" }, { "date", "TDRC" }, { "track", "TRCK" }, { "genre", "TCON" }, { "composer", "TCOM" }, } local function id3Tag(tags: { [string]: any }): buffer? local w = Bytes.writer(256) local seen: { [string]: boolean } = {} local function syncsafe(v: number) w:u8((v // 2097152) % 128) w:u8((v // 16384) % 128) w:u8((v // 128) % 128) w:u8(v % 128) end for _, f in ID3_FRAMES do local v = tags[f[1]] if type(v) == "string" and #v > 0 and not seen[f[2]] then seen[f[2]] = true w:string(f[2]) syncsafe(#v + 1) w:u16be(0) w:u8(3) -- UTF-8 w:string(v) end end if type(tags.comment) == "string" and #tags.comment > 0 then local v = tags.comment w:string("COMM") syncsafe(#v + 5) w:u16be(0) w:u8(3) w:string("eng") w:u8(0) -- empty description w:string(v) end local body = w:finish() if buffer.len(body) == 0 then return nil end local out = Bytes.writer(buffer.len(body) + 10) out:string("ID3") out:u8(4) out:u8(0) out:u8(0) local n = buffer.len(body) out:u8((n // 2097152) % 128) out:u8((n // 16384) % 128) out:u8((n // 128) % 128) out:u8(n % 128) out:bytes(body) return out:finish() end function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then return nil, serr end local o: EncodeOptions = opts or {} local layer = o.layer or 3 if layer ~= 2 and layer ~= 3 then return nil, Err.new(Err.ARG, "layer must be 2 or 3") end local Enc = if layer == 3 then Encode3 else Encode2 local rate = o.sampleRate or src.sampleRate if o.sampleRate and not Enc.RATES[o.sampleRate] then return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz", layer, tostring(o.sampleRate))) end if not Enc.RATES[rate] then local best, top = nil, 0 for r in Enc.RATES do top = math.max(top, r) if r >= rate and (best == nil or r < best) then best = r end end rate = best or top end if rate ~= src.sampleRate then local rs, rerr = Resample.source(src, rate, { quality = o.resampleQuality }) if not rs then return nil, Err.new(Err.ARG, tostring(rerr)) end src = rs end local info = Enc.RATES[rate] local mpeg1 = info[1] == 3 local mode = o.mode or (if src.channels == 1 then "mono" elseif layer == 3 then "joint" else "stereo") if mode ~= "stereo" and mode ~= "joint" and mode ~= "mono" then return nil, Err.new(Err.ARG, "mode must be stereo, joint or mono") end if src.channels > 2 then return nil, Err.new(Err.ARG, "MPEG audio holds 1 or 2 channels") end if layer == 2 and mode == "joint" then mode = "stereo" end local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96)) if type(bitrate) == "number" and bitrate >= 1000 then bitrate /= 1000 end if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then return nil, Err.new(Err.ARG, string.format("%s bit/s is not a layer %d bit rate at %d Hz", tostring(if type(o.bitrate) == "number" and o.bitrate < 1000 then o.bitrate * 1000 else o.bitrate), layer, rate)) end if layer == 2 and mpeg1 then -- the standard's allowed bit rate / mode combinations if mode == "mono" and bitrate > 192 then return nil, Err.new(Err.ARG, "layer II mono is at most 192 kbps") elseif mode ~= "mono" and (bitrate == 32 or bitrate == 48 or bitrate == 56 or bitrate == 80) then return nil, Err.new(Err.ARG, "layer II stereo needs 64 kbps or more (and not 80)") end end local prefix = if o.id3 == false then nil else id3Tag(src.tags) local out, msg = Enc.encode(src :: any, { bitrate = bitrate, mode = mode, prefix = prefix }) if not out then return nil, Err.new(Err.ARG, tostring(msg)) end return out, nil end -- ------------------------------------------------------------------------------------------------ open local function stringTags(t: any): { [string]: string } local out: { [string]: string } = {} for k, v in t do if type(k) == "string" and type(v) == "string" and k ~= "id3v2" then out[k] = v end end return out end function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) local b = r.buf if r.base ~= 0 or r.limit ~= buffer.len(b) then b = buffer.create(r.limit - r.base) -- the core indexes from offset 0 buffer.copy(b, 0, r.buf, r.base, r.limit - r.base) end local okTags, tags, start, stop = pcall(Tags.parse, b) if not okTags then tags, start, stop = { raw = {} }, 0, buffer.len(b) end local idx = Index.build(b, start, stop) if not idx then return nil, Err.new(Err.CORRUPT, "no MPEG audio frames found") end local dec = Stream.new(b, idx, stringTags(tags), { raw = tags.raw, id3v2 = tags.id3v2, id3v1 = tags.id3v1 == true, ape = tags.ape == true, }) if dec.frames > (opts and opts.maxFrames or MAX_FRAMES) then return nil, Err.new(Err.LIMIT, string.format("%d sample frames is over the limit", dec.frames)) end return dec, nil end -- ------------------------------------------------------------------------------------------------ extras Mp3.Tags = Tags return Mp3 end __FILES["audio/mp3/Index"] = @native function() -- audio/mp3/Index: the frame index as minimp3_ex's mp3dec_load_buf walks it, simulating the layer III bit reservoir. local Header = __include("codecs/audio/Mpa/Header") local Core = __include("codecs/audio/Mpa/Core") local band, rshift = bit32.band, bit32.rshift local ru8 = buffer.readu8 local min, max = math.min, math.max local compare, frameBytes, padding, findFrame = Header.compare, Header.frameBytes, Header.padding, Header.findFrame local Index = {} Index.FLAG_RESET = 1 -- decoder state is zeroed before this frame (minimp3 re-synced here) Index.FLAG_OUTPUT = 2 -- this frame gives samples in a continuous decode type Index = { n: number, -- frames off: buffer, -- u32 byte offset per frame size: buffer, -- u16 byte size per frame (header and padding included) flags: buffer, -- u8 FLAG_* out: buffer, -- u32 first output sample (before the encoder delay is cut) per frame main: buffer, -- u16 layer III main data bytes per frame (0 for layers I / II) outTotal: number, -- samples (per channel) of a continuous decode, delay not cut bytes: number, -- audio bytes in indexed frames sampleRate: number, channels: number, -- the most channels of any frame layer: number, version: number, -- 1, 2 or 2.5 spf: number, -- samples per frame -- Xing / Info / LAME vbrTag: number, -- mp3dec_check_vbrtag result of the first frame (0 = none) tagFrames: number, delay: number, padding: number, skipped: number, -- frames with another sample rate or layer, left out } @native local function grow(b: buffer, n: number): buffer local nb = buffer.create(n) buffer.copy(nb, 0, b, 0, math.min(buffer.len(b), n)) return nb end @native function Index.build(b: buffer, start: number, stop: number): Index? local cap = 1024 local OFF, SIZE, FLAGS, OUT, MAIN = buffer.create(cap * 4), buffer.create(cap * 2), buffer.create(cap), buffer.create(cap * 4), buffer.create(cap * 2) local n = 0 local pos = start local prev = -1 -- offset of the last decoded header (dec->header), -1 = none local ffb = 0 -- free format bytes local reserv = 0 local outTotal = 0 local bytes = 0 local first = true local skipped = 0 local outCh = 0 -- the most channels of a frame that gives output local hz, nch, layer, spf, version = 0, 0, 0, 0, 0 local vbr, tagFrames, delay, pad = 0, 0, 0, 0 while true do local remaining = stop - pos if remaining <= 0 then break end local fs = 0 local reset = false if remaining > 4 and prev >= 0 and compare(b, prev, pos) then fs = frameBytes(b, pos, ffb) + padding(b, pos) if fs ~= remaining and (fs + 4 > remaining or not compare(b, pos, pos + fs)) then fs = 0 end end if fs == 0 then reset = true reserv = 0 local i i, fs, ffb = findFrame(b, pos, remaining, 0) if fs == 0 or i + fs > remaining then break end pos += i end if fs < 4 or fs > Core.MAX_FRAME then prev = -1 pos += max(fs, 1) continue end local h1, h2, h3 = ru8(b, pos + 1), ru8(b, pos + 2), ru8(b, pos + 3) local fLayer = 4 - band(rshift(h1, 1), 3) local fHz = Header.sampleRate(h1, h2) local fCh = if band(h3, 0xC0) == 0xC0 then 1 else 2 if first then first = false hz, nch, layer, spf = fHz, fCh, fLayer, Header.frameSamples(h1) :: number version = if band(h1, 8) ~= 0 then 1 elseif band(h1, 0x10) ~= 0 then 2 else 2.5 if fLayer == 3 then local ret, frames, d, p = Core.vbrTag(b, pos, fs) if ret ~= 0 then vbr, tagFrames, delay, pad = ret, frames, d, p if ret < 0 then delay, pad = 0, 0 end -- the tag frame is not audio; the next frame is found again from scratch prev = -1 pos += fs continue end end elseif fHz ~= hz or fLayer ~= layer then skipped += 1 prev = pos pos += fs continue end local output = true local mainBytes = 0 local nextPrev = pos if fLayer == 3 then local mdb, p23, mb = Core.probeL3(b, pos, fs) if mdb < 0 then output = false nextPrev = -1 -- mp3dec_init: the next frame re-syncs else mainBytes = mb local have = min(reserv, mdb) output = reserv >= mdb local remains = have + mb - (if output then (p23 + 7) // 8 else 0) reserv = max(0, min(remains, 511)) end else output = Core.probeL12(b, pos, fs) if not output then nextPrev = -1 end end if output and fCh > outCh then outCh = fCh -- mono / stereo switches: the stream is stereo, mono frames are duplicated end if n == cap then cap *= 2 OFF, SIZE, FLAGS, OUT, MAIN = grow(OFF, cap * 4), grow(SIZE, cap * 2), grow(FLAGS, cap), grow(OUT, cap * 4), grow(MAIN, cap * 2) :: buffer end buffer.writeu32(OFF, n * 4, pos) buffer.writeu16(SIZE, n * 2, fs) buffer.writeu8(FLAGS, n, (if reset then Index.FLAG_RESET else 0) + (if output then Index.FLAG_OUTPUT else 0)) buffer.writeu32(OUT, n * 4, outTotal) buffer.writeu16(MAIN, n * 2, min(mainBytes, 65535)) n += 1 bytes += fs if output then outTotal += spf end prev = nextPrev pos += fs end if first then return nil end return { n = n, off = OFF, size = SIZE, flags = FLAGS, out = OUT, main = MAIN, outTotal = outTotal, bytes = bytes, sampleRate = hz, channels = if outCh > 0 then outCh else nch, layer = layer, version = version, spf = spf, vbrTag = vbr, tagFrames = tagFrames, delay = delay, padding = pad, skipped = skipped, } end return Index end __FILES["audio/mp3/Stream"] = function() -- audio/mp3/Stream: streaming Decoder over the frame index (gapless, exact seeking); from mp3-luau (same author). local Core = __include("codecs/audio/Mpa/Core") local Index = __include("audio/mp3/Index") local FLAG_RESET, FLAG_OUTPUT = Index.FLAG_RESET, Index.FLAG_OUTPUT local ru8, ru16, ru32 = buffer.readu8, buffer.readu16, buffer.readu32 local band = bit32.band local min, max, floor = math.min, math.max, math.floor local Stream = {} local Decoder = {} Decoder.__index = Decoder type Decoder = typeof(setmetatable( {} :: { sampleRate: number, channels: number, frames: number, duration: number, bitrate: number, tags: { [string]: string }, id3: any, layer: number, version: number, vbr: boolean, delay: number, padding: number, mpegFrames: number, _buf: buffer, _idx: any, _st: any, _pcm: buffer, _cur: number, _pcmPos: number, _pcmEnd: number, _minAbs: number, _endAbs: number, _pos: number, }, Decoder )) function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): Decoder local spf, hz, nch = idx.spf, idx.sampleRate, idx.channels -- gapless: minimp3_ex cuts delay samples off the start and caps the length at the Xing / LAME count local delay = 0 local total = idx.outTotal if idx.vbrTag > 0 then delay = idx.delay total = max(0, total - delay) -- (a frame count of 0: written by an encoder that couldn't seek back to fill it in, e.g. ffmpeg writing to a -- pipe; ffmpeg ignores it too. The frames found in the file are the length.) if idx.tagFrames > 0 then local detected = spf * idx.tagFrames if detected >= delay then detected -= delay end if idx.padding > 0 and detected >= idx.padding then detected -= idx.padding end total = min(total, detected) end end delay = min(delay, idx.outTotal) local self = setmetatable({ sampleRate = hz, channels = nch, frames = total, duration = total / hz, bitrate = if idx.n > 0 then floor(idx.bytes * 8 * hz / (idx.n * spf) + 0.5) else 0, -- bit/s tags = tags, id3 = id3, layer = idx.layer, version = idx.version, vbr = idx.vbrTag ~= 0, delay = delay, padding = if idx.vbrTag > 0 then max(0, idx.padding) else 0, mpegFrames = idx.n, _buf = b, _idx = idx, _st = Core.newState(), _pcm = buffer.create(1152 * 2 * 4), _cur = 0, _pcmPos = 0, _pcmEnd = 0, _minAbs = delay, _endAbs = delay + total, _pos = 0, }, Decoder) return self end local function fill(self: Decoder): boolean local idx = self._idx local n = idx.n local spf = idx.spf local st = self._st while self._cur < n do local f = self._cur self._cur = f + 1 local flags = ru8(idx.flags, f) if band(flags, FLAG_RESET) ~= 0 then Core.reset(st) end local a = ru32(idx.out, f * 4) if a >= self._endAbs then self._cur = n return false end local got = Core.decodeFrame(st, self._buf, ru32(idx.off, f * 4), ru16(idx.size, f * 2), self._pcm) if got > 0 and band(flags, FLAG_OUTPUT) ~= 0 then if Core.lastChannels < self.channels then Core.upmix(self._pcm, got) end local lo = max(a, self._minAbs) local hi = min(a + spf, self._endAbs) if hi > lo then self._pcmPos = lo - a self._pcmEnd = hi - a return true end end end return false end function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, number) local ch = self.channels local want = tonumber(maxFrames) or 4096 if want ~= want then want = 0 end want = floor(max(0, min(want, self.frames - self._pos))) if out and buffer.len(out) < want * ch * 4 then out = nil end local dst = out or buffer.create(want * ch * 4) local got = 0 local pcm = self._pcm while got < want do if self._pcmPos >= self._pcmEnd then if not fill(self) then break end end local k = min(want - got, self._pcmEnd - self._pcmPos) buffer.copy(dst, got * ch * 4, pcm, self._pcmPos * ch * 4, k * ch * 4) got += k self._pcmPos += k end self._pos += got if not out and got < want then local r = buffer.create(got * ch * 4) buffer.copy(r, 0, dst, 0, got * ch * 4) dst = r end return dst, got end function Decoder.seek(self: Decoder, seconds: number) local hz = self.sampleRate local target = floor((tonumber(seconds) or 0) * hz + 0.5) target = max(0, min(target, self.frames)) self:seekFrame(target) end function Decoder.seekFrame(self: Decoder, target: number) target = tonumber(target) or 0 if target ~= target then target = 0 end target = max(0, min(floor(target), self.frames)) local idx = self._idx local abs = self.delay + target self._pos = target self._minAbs = abs self._pcmPos, self._pcmEnd = 0, 0 Core.reset(self._st) local n = idx.n if abs >= self._endAbs or n == 0 then self._cur = n return end local lo, hi = 0, n - 1 while lo < hi do local mid = (lo + hi + 1) // 2 if ru32(idx.out, mid * 4) <= abs then lo = mid else hi = mid - 1 end end local j = lo -- go back >= 2 frames (layer I needs 2 for the polyphase history), and for layer III until the main data -- before frame j - 1 covers the largest reservoir (511 bytes), stopping at a frame where the decoder resets local need = if idx.layer == 3 then 511 else 0 local s, back, acc = j, 0, 0 while s > 0 and band(ru8(idx.flags, s), FLAG_RESET) == 0 do if back >= 2 and acc >= need then break end s -= 1 back += 1 if back >= 2 then acc += ru16(idx.main, s * 2) end end self._cur = s end function Decoder.position(self: Decoder): (number, number) return self._pos / self.sampleRate, self._pos end function Decoder.readAll(self: Decoder): (buffer, number) return self:read(max(0, self.frames - self._pos)) end Stream.Decoder = Decoder return Stream end __FILES["audio/mp3/Tags"] = function() -- audio/mp3/Tags: ID3v2.2-2.4 and ID3v1 / 1.1 tags (APEv2 skipped); the audio range as minimp3_ex's mp3dec_skip_id3. local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift local ru8 = buffer.readu8 local Tags = {} -- ID3v1 genres 0..147 (the original 80 + the Winamp extensions) local GENRES = { [0] = "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska", "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "AlternRock", "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave", "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock", "National Folk", "Swing", "Fast Fusion", "Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock", "Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour", "Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus", "Porn Groove", "Satire", "Slow Jam", "Club", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul", "Freestyle", "Duet", "Punk Rock", "Drum Solo", "A capella", "Euro-House", "Dance Hall", "Goa", "Drum & Bass", "Club-House", "Hardcore", "Terror", "Indie", "BritPop", "Negerpunk", "Polsk Punk", "Beat", "Christian Gangsta Rap", "Heavy Metal", "Black Metal", "Crossover", "Contemporary Christian", "Christian Rock", "Merengue", "Salsa", "Thrash Metal", "Anime", "JPop", "Synthpop", } Tags.GENRES = GENRES -- frame id -> field name (v2.3/2.4 ids and their v2.2 equivalents) local FIELDS = { TIT2 = "title", TT2 = "title", TPE1 = "artist", TP1 = "artist", TALB = "album", TAL = "album", TPE2 = "albumartist", TP2 = "albumartist", TYER = "date", TYE = "date", TDRC = "date", TRCK = "track", TRK = "track", TPOS = "disc", TPA = "disc", TCON = "genre", TCO = "genre", TCOM = "composer", TCM = "composer", COMM = "comment", COM = "comment", } local function utf8char(cp: number): string if cp < 0 or cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then cp = 0xFFFD end return utf8.char(cp) end -- bytes [i, j) of b, decoded from ID3 text encoding enc (0 latin-1, 1 UTF-16 + BOM, 2 UTF-16BE, 3 UTF-8) local function decodeText(b: buffer, i: number, j: number, enc: number): string local out = {} if enc == 1 or enc == 2 then local le = false if enc == 1 and j - i >= 2 then local b0, b1 = ru8(b, i), ru8(b, i + 1) if b0 == 0xFF and b1 == 0xFE then le = true i += 2 elseif b0 == 0xFE and b1 == 0xFF then i += 2 else le = true -- no BOM: assume little-endian (what most taggers write) end end local pending = 0 while i + 1 < j do local u = if le then bor(ru8(b, i), lshift(ru8(b, i + 1), 8)) else bor(lshift(ru8(b, i), 8), ru8(b, i + 1)) i += 2 if u >= 0xD800 and u <= 0xDBFF then pending = u else if u >= 0xDC00 and u <= 0xDFFF and pending ~= 0 then u = 0x10000 + lshift(pending - 0xD800, 10) + (u - 0xDC00) end pending = 0 table.insert(out, if u == 0 then "\0" else utf8char(u)) end end elseif enc == 3 then local s = buffer.readstring(b, i, j - i) if utf8.len(s) then return s end enc = 0 -- invalid UTF-8: fall back to latin-1 end if enc == 0 then for k = i, j - 1 do local c = ru8(b, k) table.insert(out, if c < 0x80 then string.char(c) else utf8char(c)) end end return table.concat(out) end local function clean(s: string): string s = string.gsub(s, "[%z%s]+$", "") s = string.gsub(s, "%z+", " / ") return s end -- "(17)", "(17)Rock", "17" -> "Rock" local function genreName(s: string): string local n = tonumber(string.match(s, "^%((%d+)%)$") or string.match(s, "^(%d+)$")) if n and GENRES[n] then return GENRES[n] end local rest = string.match(s, "^%(%d+%)(.+)$") return rest or s end local function syncsafe(b: buffer, o: number): number return bor(lshift(band(ru8(b, o), 0x7F), 21), lshift(band(ru8(b, o + 1), 0x7F), 14), lshift(band(ru8(b, o + 2), 0x7F), 7), band(ru8(b, o + 3), 0x7F)) end local function be32(b: buffer, o: number): number return bor(lshift(ru8(b, o), 24), lshift(ru8(b, o + 1), 16), lshift(ru8(b, o + 2), 8), ru8(b, o + 3)) end -- undo unsynchronisation (FF 00 -> FF) of b[i, j) into a new buffer local function deunsync(b: buffer, i: number, j: number): buffer local out = buffer.create(math.max(0, j - i)) local n = 0 local k = i while k < j do local c = ru8(b, k) buffer.writeu8(out, n, c) n += 1 k += if c == 0xFF and k + 1 < j and ru8(b, k + 1) == 0 then 2 else 1 end local r = buffer.create(n) buffer.copy(r, 0, out, 0, n) return r end -- minimp3's ID3v2 detection: total tag size (header + body + footer) or 0 function Tags.id3v2Size(b: buffer, o: number, len: number): number if len - o < 10 or buffer.readstring(b, o, 3) ~= "ID3" then return 0 end if band(ru8(b, o + 5), 15) ~= 0 then return 0 end for k = 6, 9 do if band(ru8(b, o + k), 0x80) ~= 0 then return 0 end end local size = syncsafe(b, o + 6) + 10 if band(ru8(b, o + 5), 16) ~= 0 then size += 10 end return size end local function setField(tags: any, id: string, text: string) tags.raw[id] = text local f = FIELDS[id] if f and tags[f] == nil and text ~= "" then tags[f] = if f == "genre" then genreName(text) else text end end local function parseV2(b: buffer, o: number, size: number, tags: any) local ver = ru8(b, o + 3) local flags = ru8(b, o + 5) if ver < 2 or ver > 4 then return end tags.id3v2 = "2." .. ver local bodyEnd = math.min(o + 10 + syncsafe(b, o + 6), buffer.len(b)) local body = b local p, e = o + 10, bodyEnd if band(flags, 0x80) ~= 0 and ver < 4 then body = deunsync(b, p, e) p = 0 e = buffer.len(body) end if band(flags, 0x40) ~= 0 and ver >= 3 and p + 4 <= e then -- extended header: v2.3 size excludes its own 4 bytes, v2.4 includes them (syncsafe) p += if ver == 3 then be32(body, p) + 4 else syncsafe(body, p) end local hdr = if ver == 2 then 6 else 10 while p + hdr <= e do local c0 = ru8(body, p) if c0 == 0 then break -- padding end local id, fsize, fflags if ver == 2 then id = buffer.readstring(body, p, 3) fsize = bor(lshift(ru8(body, p + 3), 16), lshift(ru8(body, p + 4), 8), ru8(body, p + 5)) fflags = 0 else id = buffer.readstring(body, p, 4) fsize = if ver == 4 then syncsafe(body, p + 4) else be32(body, p + 4) fflags = bor(lshift(ru8(body, p + 8), 8), ru8(body, p + 9)) end if not string.match(id, "^[A-Z0-9]+$") or fsize <= 0 or p + hdr + fsize > e then break end local fs, fe = p + hdr, p + hdr + fsize local fb = body local skip = false if ver == 3 then skip = band(fflags, 0x00C0) ~= 0 -- compressed / encrypted elseif ver == 4 then skip = band(fflags, 0x000C) ~= 0 if not skip and band(fflags, 0x0001) ~= 0 then fs += 4 -- data length indicator end if not skip and band(fflags, 0x0002) ~= 0 and fs < fe then fb = deunsync(body, fs, fe) fs = 0 fe = buffer.len(fb) end end if not skip and fs < fe then local first = string.sub(id, 1, 1) local enc = ru8(fb, fs) if first == "T" and id ~= "TXXX" and id ~= "TXX" then setField(tags, id, clean(decodeText(fb, fs + 1, fe, enc))) elseif (id == "COMM" or id == "COM") and fe - fs >= 4 then -- encoding, language[3], short description (NUL-terminated in the encoding), text local q = fs + 4 local wide = enc == 1 or enc == 2 while q < fe do if wide then if q + 1 < fe and ru8(fb, q) == 0 and ru8(fb, q + 1) == 0 then q += 2 break end q += 2 else if ru8(fb, q) == 0 then q += 1 break end q += 1 end end if q <= fe then setField(tags, id, clean(decodeText(fb, q, fe, enc))) end end end p += hdr + fsize end end local function v1String(b: buffer, o: number, n: number): string return (string.gsub(decodeText(b, o, o + n, 0), "[%z%s]+$", "")) end function Tags.parse(b: buffer): (any, number, number) local len = buffer.len(b) local tags: any = { raw = {} } local start, stop = 0, len local v2 = Tags.id3v2Size(b, 0, len) if v2 > 0 then pcall(parseV2, b, 0, v2, tags) start = math.min(v2, len) end -- mp3dec_skip_id3v1 on what follows the ID3v2 tag local size = stop - start if size >= 128 and buffer.readstring(b, start + size - 128, 3) == "TAG" then local o = start + size - 128 tags.id3v1 = true local v1: { [string]: any } = { title = v1String(b, o + 3, 30), artist = v1String(b, o + 33, 30), album = v1String(b, o + 63, 30), date = v1String(b, o + 93, 4), } if ru8(b, o + 125) == 0 and ru8(b, o + 126) ~= 0 then v1.comment = v1String(b, o + 97, 28) v1.track = tostring(ru8(b, o + 126)) else v1.comment = v1String(b, o + 97, 30) end local g = ru8(b, o + 127) if GENRES[g] then v1.genre = GENRES[g] end for k, v in v1 do if tags[k] == nil and v ~= "" then tags[k] = v end end size -= 128 if size >= 227 and buffer.readstring(b, start + size - 227, 4) == "TAG+" then size -= 227 end end if size > 32 and buffer.readstring(b, start + size - 32, 8) == "APETAGEX" then size -= 32 local t = start + size + 12 local tagSize = bor(ru8(b, t), lshift(ru8(b, t + 1), 8), lshift(ru8(b, t + 2), 16), lshift(ru8(b, t + 3), 24)) if size >= tagSize then size -= tagSize end tags.ape = true end stop = start + size return tags, start, stop end return Tags end __FILES["audio/mpc"] = function() -- audio/mpc: Musepack (.mpc / .mp+ / .mpp) SV7 and SV8 via codecs/audio/Musepack (a libmpcdec port). Supports: mono / -- stereo, 32-48 kHz, gapless length, seeking (SV8 exact; SV7 with 32 frames of pre-roll, as libmpcdec), APEv2 tags, -- an ID3v2 prefix, ReplayGain in meta. Not supported: writing, SV4-SV6 (UNSUPPORTED), chapters. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") local Stream = __include("codecs/audio/Stream") local ApeTag = __include("codecs/audio/ApeTag") local Musepack = __include("codecs/audio/Musepack") -- ------------------------------------------------------------------------------------------------ contract local Mpc = { name = "mpc", category = "audio", extensions = { "mpc", "mp+", "mpp" }, mime = { "audio/x-musepack", "audio/musepack" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" }, caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { maxFrames: number?, -- default 2^31 } -- ------------------------------------------------------------------------------------------------ constants local function id3v2(b: buffer, p: number, limit: number): number if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then return 0 end local n = 10 for i = 6, 9 do n += bit32.band(buffer.readu8(b, p + i), 127) * 128 ^ (9 - i) end return n + (if bit32.band(buffer.readu8(b, p + 5), 0x10) ~= 0 then 10 else 0) end -- ------------------------------------------------------------------------------------------------ sniff function Mpc.sniff(r: Bytes.Reader): number local b, p, limit = r.buf, r.pos, r.limit p += id3v2(b, p, limit) local v = Musepack.magic(b, p, limit) if v == 8 then return 1 end return if v == 7 then 0.9 else 0 end -- ------------------------------------------------------------------------------------------------ decode function Mpc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) local o: DecodeOptions = opts or {} local b, base, limit = r.buf, r.base, r.limit local start = base + id3v2(b, base, limit) local tags, info = ApeTag.find(b, start, limit) local stop = if info and info.start > start then info.start else limit local s, err = Musepack.open(b, start, stop) if not s then return nil, err end if s.frames > (o.maxFrames or 2 ^ 31) then return nil, Err.new(Err.LIMIT, "more than " .. (o.maxFrames or 2 ^ 31) .. " frames") end local duration = s.frames / s.sampleRate local dec = { sampleRate = s.sampleRate, channels = s.channels, frames = s.frames, duration = duration, bitrate = if duration > 0 then math.floor(s.bytes * 8 / duration + 0.5) else 0, tags = tags or {}, codec = "musepack", version = s.version, profile = s.profile, gain = s.gain, } return Stream.packets(dec, s :: any) end function Mpc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = Mpc.open(r, opts) if not dec then return nil, err end local d: any = dec return Pcm.drain(d, { format = "mpc", codec = "musepack", version = d.version, profile = d.profile, gain = d.gain, bitrate = d.bitrate }) end return Mpc end __FILES["audio/opus"] = function() -- audio/opus: Ogg Opus (RFC 6716, RFC 7845); absorbed from opus-luau dd2b4e5, a port of the libopus 1.6 decoder (BSD: -- licenses/libopus-BSD.txt). Supports: every mode / bandwidth / frame size, mapping families 0 / 1 / 255, seeking, PLC; -- encode CELT only (20 ms, full band, CBR). Not supported: SILK / hybrid encoding, mapping family 3, chained streams. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Ogg = __include("containers/Ogg") local Decoder = __include("codecs/audio/Opus/Decoder") local Packet = __include("codecs/audio/Opus/Packet") local VorbisComment = __include("codecs/audio/VorbisComment") local Pcm = __include("codecs/audio/Pcm") local RangeDecoder = __include("codecs/entropy/RangeCoder/Decoder") local Celt = __include("codecs/audio/Opus/Celt") local Silk = __include("codecs/audio/Opus/Silk") local Encode = __include("audio/opus/Encode") -- ------------------------------------------------------------------------------------------------ contract local Opus = { name = "opus", category = "audio", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/entropy/RangeCoder/Decoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment", "codecs/audio/Opus/CeltEncoder", "codecs/audio/Opus/Decoder", "codecs/audio/Opus/Packet", "codecs/audio/Opus/Celt", "codecs/audio/Opus/Silk" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 }, } -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { verify: boolean?, -- check the Ogg page CRCs (default true; false decodes damaged files) stereo: boolean?, -- downmix more than 2 channels to stereo (default false; dec.channels is then 2) } -- ------------------------------------------------------------------------------------------------ constants local SAMPLE_RATE = 48000 -- stereo downmix weights for the Vorbis channel orders of mapping family 1 (3 to 8 channels), as in opusfile local DOWNMIX = { [3] = { 0.5858, 0, 0.4142, 0.4142, 0, 0.5858 }, [4] = { 0.4226, 0, 0, 0.4226, 0.366, 0.2114, 0.2114, 0.366 }, [5] = { 0.651, 0, 0.46, 0.46, 0, 0.651, 0.5636, 0.3254, 0.3254, 0.5636 }, [6] = { 0.529, 0, 0.3741, 0.3741, 0, 0.529, 0.4582, 0.2645, 0.2645, 0.4582, 0.3741, 0.3741 }, [7] = { 0.4553, 0, 0.322, 0.322, 0, 0.4553, 0.3943, 0.2277, 0.2277, 0.3943, 0.2788, 0.2788, 0.322, 0.322 }, [8] = { 0.3886, 0, 0.2748, 0.2748, 0, 0.3886, 0.3366, 0.1943, 0.1943, 0.3366, 0.3366, 0.1943, 0.1943, 0.3366, 0.2748, 0.2748 }, } local PREROLL = 3840 -- 80 ms, RFC 7845 section 4.6 local MAX_PACKET = 5760 -- 120 ms type Head = { version: number, channels: number, preSkip: number, inputSampleRate: number, outputGain: number, -- Q7.8 dB mappingFamily: number, streams: number, coupled: number, mapping: { number }, } -- OpusHead (RFC 7845 section 5.1) local function parseHead(b: buffer, off: number, size: number): (Head?, string?) if size < 19 or buffer.readstring(b, off, 8) ~= "OpusHead" then return nil, "not an OpusHead packet" end local version = buffer.readu8(b, off + 8) if bit32.rshift(version, 4) ~= 0 then return nil, "unsupported OpusHead version " .. version end local channels = buffer.readu8(b, off + 9) if channels < 1 then return nil, "OpusHead: zero channels" end local head: Head = { version = version, channels = channels, preSkip = buffer.readu16(b, off + 10), inputSampleRate = buffer.readu32(b, off + 12), outputGain = buffer.readi16(b, off + 16), mappingFamily = buffer.readu8(b, off + 18), streams = 1, coupled = channels - 1, mapping = {}, } if head.mappingFamily == 0 then if channels > 2 then return nil, "OpusHead: mapping family 0 with more than 2 channels" end head.mapping = if channels == 2 then { 0, 1 } else { 0 } else if head.mappingFamily == 3 then return nil, "unsupported channel mapping family 3 (projection)" end if size < 21 + channels then return nil, "OpusHead: truncated channel mapping table" end head.streams = buffer.readu8(b, off + 19) head.coupled = buffer.readu8(b, off + 20) if head.streams < 1 or head.coupled > head.streams or head.streams + head.coupled > 255 then return nil, "OpusHead: bad stream counts" end for c = 0, channels - 1 do local m = buffer.readu8(b, off + 21 + c) if m ~= 255 and m >= head.streams + head.coupled then return nil, "OpusHead: bad channel mapping" end head.mapping[c + 1] = m end end return head, nil end -- OpusTags (RFC 7845 section 5.2) local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }, { VorbisComment.Field }) if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then return "", {}, {} end local p = off + 8 local e = off + size local vlen = buffer.readu32(b, p) p += 4 if p + vlen > e then return "", {}, {} end local vendor = buffer.readstring(b, p, vlen) p += vlen local list = {} if p + 4 <= e then local n = buffer.readu32(b, p) p += 4 for _ = 1, n do if p + 4 > e then break end local l = buffer.readu32(b, p) p += 4 if p + l > e then break end table.insert(list, buffer.readstring(b, p, l)) p += l end end local tags, raw = VorbisComment.tags(list) return vendor, tags, raw end Opus.Decoder = Decoder Opus.Packet = Packet Opus.RangeDecoder = RangeDecoder Opus.Celt = Celt Opus.Silk = Silk Opus.parseHead = parseHead Opus.parseTags = parseTags Opus.SAMPLE_RATE = SAMPLE_RATE -- ------------------------------------------------------------------------------------------------ sniff function Opus.sniff(r: Bytes.Reader): number if r:peek(4) ~= "OggS" then return 0 end local nseg = r:peekU8(26) if nseg < 1 then return 0 end return if r:peek(8, 27 + nseg) == "OpusHead" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Opus.open(r, opts) if not dec then return nil, err end return Pcm.drain(dec, { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, comments = dec.comments, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate }) end -- ------------------------------------------------------------------------------------------------ encode function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?) return Encode.encode(value, opts) end -- ------------------------------------------------------------------------------------------------ open local Stream = {} Stream.__index = Stream local function decodeNext(self: any): boolean local p = self.demux:nextPacket(self.serial) if p == nil then return false end local n if p.size > 0 then n = Decoder.decodeMultistream(self.ms, p.data, p.offset, p.size, self.pend, 1, MAX_PACKET) else n = -1 end if n < 0 then -- corrupt or empty packet: conceal for its nominal duration local dur = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else -1 if dur <= 0 then dur = self.lastDuration end n = Decoder.decodeMultistream(self.ms, nil, 0, 0, self.pend, 1, dur) if n < 0 then n = dur for i = 1, n * self.channels do self.pend[i] = 0 end end end self.lastDuration = n self.pendStart = self.decoded self.pendLen = n self.pendPos = 0 self.decoded += n return true end function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, number) local ch = self.channels local mf = if type(maxFrames) == "number" and maxFrames == maxFrames then maxFrames else 0 local want = math.max(0, math.min(math.floor(mf), self.endSample - self.next)) local reuse = into ~= nil and buffer.len(into) >= want * ch * 4 local out = if reuse then into :: buffer else buffer.create(want * ch * 4) local got = 0 local gain = self.gain while got < want do if self.pendPos >= self.pendLen then if not decodeNext(self) then break end end local s = self.pendStart + self.pendPos if s < self.next then self.pendPos = math.min(self.pendLen, self.pendPos + (self.next - s)) continue end local n = math.min(self.pendLen - self.pendPos, want - got) if self.downmix then Decoder.writeDownmix(self.pend, self.pendPos * self.sourceChannels, n, self.sourceChannels, self.downmix, gain, out, got * 8) else Decoder.writeF32(self.pend, self.pendPos * ch, n * ch, gain, out, got * ch * 4) if self.order then Pcm.reorder(out, got * ch * 4, n, ch, self.order) end end self.pendPos += n got += n self.next += n end if got < want then if not reuse then local trimmed = buffer.create(got * ch * 4) buffer.copy(trimmed, 0, out, 0, got * ch * 4) out = trimmed end self.endSample = self.next end return out, got end function Stream.position(self: any): number return (self.next - self.preSkip) / SAMPLE_RATE end function Stream.seek(self: any, seconds: number) local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0 local p = math.floor(math.max(0, math.min(sec, 1e12)) * SAMPLE_RATE + 0.5) p = math.min(p, self.frames) local target = p + self.preSkip -- decoded-sample index of the wanted sample Decoder.resetMultistream(self.ms) self.pendLen, self.pendPos = 0, 0 local g = target - PREROLL + self.startGranule local start = -1 if g > self.startGranule then start = self.demux:seekGranule(self.serial, g) or -1 end if start < 0 then self.demux:rewind(self.serial) self.demux:nextPacket(self.serial) -- OpusHead self.demux:nextPacket(self.serial) -- OpusTags self.decoded = 0 else self.decoded = start - self.startGranule end self.pendStart = self.decoded self.next = target end function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?) local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil) if not demux then return nil, derr end local serial = demux:find("opus") if serial == nil then return nil, Err.new(Err.CORRUPT, "no Opus stream in the Ogg file") end local hp = demux:nextPacket(serial) if hp == nil then return nil, Err.new(Err.TRUNCATED, "missing OpusHead") end local head, herr = parseHead(hp.data, hp.offset, hp.size) if not head then return nil, Err.new(if string.find(herr or "", "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT, herr or "bad OpusHead") end local tp = demux:nextPacket(serial) if tp == nil then return nil, Err.new(Err.TRUNCATED, "missing OpusTags") end local vendor, tags, rawTags = parseTags(tp.data, tp.offset, tp.size) -- granule of the first audio sample: first page granule minus the packets that end on it local startGranule = 0 local sum = 0 while true do local p = demux:nextPacket(serial) if p == nil then break end local d = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else 0 sum += math.max(d, 0) if p.granule ~= -1 then startGranule = math.max(0, p.granule - sum) break end end demux:rewind(serial) demux:nextPacket(serial) demux:nextPacket(serial) local info = demux:stream(serial) local last = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else startGranule local frames = math.max(0, last - startGranule - head.preSkip) local downmix = nil if opts and opts.stereo and head.channels > 2 then downmix = DOWNMIX[head.channels] if downmix == nil or head.mappingFamily ~= 1 then -- unknown layout: every channel to both sides, equally downmix = table.create(head.channels * 2, 1 / head.channels) end end local self = setmetatable({ demux = demux, serial = serial, head = head, vendor = vendor, tags = tags, comments = rawTags, -- mapping family 1 is in Vorbis channel order; the output is WAVE order (codecs/audio/Pcm) order = if not downmix and head.mappingFamily == 1 and head.channels > 2 then Pcm.WAVE_FROM_VORBIS[head.channels] else nil, sampleRate = SAMPLE_RATE, channels = if downmix then 2 else head.channels, sourceChannels = head.channels, downmix = downmix, frames = frames, duration = frames / SAMPLE_RATE, bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / SAMPLE_RATE)) else 0, preSkip = head.preSkip, startGranule = startGranule, gain = 10 ^ (head.outputGain / (20 * 256)), ms = Decoder.newMultistream(head.channels, head.streams, head.coupled, head.mapping), pend = table.create(MAX_PACKET * head.channels, 0), pendStart = 0, pendLen = 0, pendPos = 0, decoded = 0, -- decoded-sample index of the next packet's first sample next = head.preSkip, -- decoded-sample index of the next sample read() returns endSample = head.preSkip + frames, lastDuration = 960, }, Stream) return self, nil end return Opus end __FILES["audio/opus/Encode"] = function() -- audio/opus/Encode: Ogg Opus writing (RFC 7845), CELT only (TOC config 31: full band, 20 ms, code 0), family 0. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Ogg = __include("containers/Ogg") local Pcm = __include("codecs/audio/Pcm") local Resample = __include("codecs/audio/Resample") local VorbisComment = __include("codecs/audio/VorbisComment") local CeltEncoder = __include("codecs/audio/Opus/CeltEncoder") local Encode = {} type Options = { bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant); values below 1000 -- are kbit/s (96 = 96000), as for every encoder's bitrate option tags: { [string]: string }?, -- default: the audio's tags vendor: string?, -- OpusTags vendor (default "rosetta") serial: number?, -- Ogg stream serial (default 0x4f707573) } local floor = math.floor function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) local o: Options = opts or {} local src, serr = Pcm.source(value) if not src then return nil, serr end local ch = src.channels if ch ~= 1 and ch ~= 2 then return nil, Err.new(Err.UNSUPPORTED, "the CELT encoder writes mono or stereo (got " .. ch .. " channels)") end local rate = src.sampleRate if rate < 1000 or rate > 768000 then return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate)) end local bitrate = o.bitrate or 64000 * ch if type(bitrate) == "number" and bitrate > 0 and bitrate < 1000 then bitrate *= 1000 end if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000") end if rate ~= 48000 then local rs, rerr = Resample.source(src, 48000) if not rs then return nil, Err.new(Err.ARG, tostring(rerr)) end src = rs end local all, aerr = Pcm.collect(src :: Pcm.Source) if not all then return nil, aerr end local n48 = all.frames local samples = all.samples local pcm: { number } = table.create(n48 * ch, 0) local readf32 = buffer.readf32 for i = 1, n48 * ch do pcm[i] = readf32(samples, (i - 1) * 4) end local FRAME = CeltEncoder.FRAME local preSkip = CeltEncoder.DELAY local packets = (n48 + preSkip + FRAME - 1) // FRAME for i = n48 * ch + 1, packets * FRAME * ch do pcm[i] = 0 end local bytes = math.clamp(floor(bitrate * FRAME / 48000 / 8), if ch == 2 then 40 else 20, 1275 - 1) local st = CeltEncoder.new(ch) local mux = Ogg.muxer({ pageSize = 4096 }) local s = mux:stream(o.serial or 0x4f707573) -- OpusHead local head = Bytes.writer(19) head:string("OpusHead") head:u8(1) head:u8(ch) head:u16le(preSkip) head:u32le(floor(rate)) head:u16le(0) head:u8(0) s:packet(head:finish(), 0, { flush = true }) -- OpusTags local tags = o.tags or src.tags or {} local tw = Bytes.writer(256) tw:string("OpusTags") local vendor = o.vendor or "rosetta" tw:u32le(#vendor) tw:string(vendor) local fields = VorbisComment.fields(tags) tw:u32le(#fields) for _, field in fields do tw:u32le(#field) tw:string(field) end s:packet(tw:finish(), 0, { flush = true }) local toc = 31 * 8 + (if ch == 2 then 4 else 0) for p = 0, packets - 1 do local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes) local pkt = buffer.create(bytes + 1) buffer.writeu8(pkt, 0, toc) buffer.copy(pkt, 1, frame, 0, bytes) local last = p == packets - 1 local granule = if last then preSkip + n48 else (p + 1) * FRAME s:packet(pkt, granule, { eos = last }) end return mux:finish(), nil end return Encode end __FILES["audio/qoa"] = function() -- audio/qoa: QOA "Quite OK Audio" via codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). Supports: static and -- streaming files, 1-255 channels, rates up to 16777215 Hz, frame-accurate seeking; encode byte-for-byte as qoa_encode, -- 1-8 channels. Not supported: channel count or rate changes mid-stream. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") local Stream = __include("codecs/audio/Stream") local Codec = __include("codecs/audio/Qoa") -- ------------------------------------------------------------------------------------------------ contract local Qoa = { name = "qoa", category = "audio", extensions = { "qoa" }, mime = { "audio/qoa" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" }, caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff function Qoa.sniff(r: Bytes.Reader): number return if r:peek(4) == "qoaf" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode function Qoa.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = Qoa.open(r) if not dec then return nil, err end local d = dec :: any local limit = opts and opts.maxFrames or 2 ^ 28 if d.frames > limit or d.frames * d.channels > 2 ^ 28 then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) end return Pcm.drain(d, { format = "qoa", streaming = d.streaming }, limit) end -- ------------------------------------------------------------------------------------------------ encode function Qoa.encode(value: any, _opts: any?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then return nil, serr end local ch, rate = src.channels, src.sampleRate if ch > 8 then return nil, Err.new(Err.ARG, "QOA (qoa.h) holds at most 8 channels") end if rate ~= math.floor(rate) or rate < 1 or rate > 0xFFFFFF then return nil, Err.new(Err.ARG, "the sample rate must be an integer in 1 .. 16777215") end local FL = Codec.FRAME_LEN local w = Bytes.writer(8 + (if src.frames > 0 then Codec.frameSize(ch, (src.frames + 19) // 20) + 24 * ch * (src.frames // FL + 1) else 65536)) w:string("qoaf") w:u32be(0) local lms = Codec.newLms(ch) local fb = buffer.create(FL * ch * 4) local tmp: buffer? = nil local total = 0 while true do -- one frame: 5120 sample frames (the last may be shorter), as qoa.h cuts them local have = 0 while have < FL do local b, n = src:read(FL - have, tmp) if n <= 0 then break end tmp = b buffer.copy(fb, have * ch * 4, b, 0, n * ch * 4) have += n end if have == 0 then break end local at = w:reserve(Codec.frameSize(ch, (have + 19) // 20)) w.pos = at + Codec.encodeFrame(fb, 0, have, ch, rate, lms, w.buf, at) total += have if have < FL then break end end if src.err then return nil, src.err end if total == 0 then return nil, Err.new(Err.ARG, "QOA needs at least one sample") end if total >= 2 ^ 32 then return nil, Err.new(Err.ARG, "too many samples for QOA") end local out = w:finish() buffer.writeu32(out, 4, bit32.byteswap(total)) return out, nil end -- ------------------------------------------------------------------------------------------------ open function Qoa.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) if type(r) ~= "table" or type(r.buf) ~= "buffer" then return nil, Err.new(Err.ARG, "open: expected a Reader") end local h = r:sub(0) if h:string(4) ~= "qoaf" then return nil, Err.new(Err.CORRUPT, "not a QOA file") end local declared = h:u32be() if h.err then return nil, h.err end local buf = r.buf local offs, starts = {}, {} local p, total = r.base + 8, 0 local ch, rate = 0, 0 while p < r.limit do local info, msg = Codec.frameInfo(buf, p, r.limit - p) if not info then if #offs == 0 then return nil, Err.from(msg, p - r.base) end break -- a cut or damaged tail: keep the whole frames end if #offs == 0 then ch, rate = info.channels, info.rate elseif info.channels ~= ch or info.rate ~= rate then return nil, Err.new(Err.UNSUPPORTED, "the channel count or rate changes mid-stream", p - r.base) end table.insert(offs, p) table.insert(starts, total) total += info.samples p += info.size if declared > 0 and total >= declared then break end end if #offs == 0 then return nil, Err.new(Err.TRUNCATED, "no frames") end local frames = if declared > 0 then math.min(declared, total) else total local pcm = buffer.create(Codec.FRAME_LEN * ch * 4) local dec: any = { sampleRate = rate, channels = ch, frames = frames, duration = frames / rate, bitrate = math.floor((p - r.base) * 8 / math.max(frames / rate, 1e-9)), tags = {}, streaming = declared == 0, } local limit = r.limit return Stream.packets(dec, { count = #offs, start = function(i: number): number return if i > #offs then total else starts[i] end, decode = function(i: number): (number?, Err.Err?) local n, msg = Codec.decodeFrame(buf, offs[i], limit - offs[i], pcm, 0) if not n then return nil, Err.from(msg, offs[i] - r.base) end return n, nil end, pcm = function(): buffer return pcm end, reset = function() end, stop = frames, }) end return Qoa end __FILES["audio/tta"] = function() -- audio/tta: True Audio (.tta, TTA1) via codecs/audio/Tta, from the TTA1 format description. Supports: 8 / 16 / 24 -- bits, any channel count, seeking by the seek table, APEv2 tags, an ID3v2 prefix. Not supported: password-protected -- files, TTA2, ID3v2 contents, encoding. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") local Stream = __include("codecs/audio/Stream") local ApeTag = __include("codecs/audio/ApeTag") local TtaCodec = __include("codecs/audio/Tta") -- ------------------------------------------------------------------------------------------------ contract local Tta = { name = "tta", category = "audio", extensions = { "tta" }, mime = { "audio/x-tta", "audio/tta" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" }, caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } }, } -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff local function id3Size(r: Bytes.Reader): number if r:peek(3) ~= "ID3" then return 0 end local sz = 0 for i = 6, 9 do local v = r:peekU8(i) if v < 0 then return 0 end sz = sz * 128 + bit32.band(v, 127) end local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 return 10 + sz + (if footer then 10 else 0) end function Tta.sniff(r: Bytes.Reader): number return if r:peek(4, id3Size(r)) == "TTA1" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Tta.open(r, opts) if not dec then return nil, err end local d = dec :: any local limit = opts and opts.maxFrames or 2 ^ 28 if d.frames > limit or d.frames * d.channels > 2 ^ 28 then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) end return Pcm.drain(d, d.source, limit) end -- ------------------------------------------------------------------------------------------------ open function Tta.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) if type(r) == "buffer" then r = Bytes.reader(r :: any) end if type(r) ~= "table" or type(r.buf) ~= "buffer" then return nil, Err.new(Err.ARG, "open: expected a Reader") end local buf, base, limit = r.buf, r.base, r.limit local at = base + id3Size(r) local tags, tagInfo = ApeTag.find(buf, at, limit) local stop = if tagInfo then tagInfo.start else limit local info, err = TtaCodec.info(buf, at, stop) if not info then return nil, err end if info.channels * info.frameLength > 2 ^ 24 then return nil, Err.new(Err.LIMIT, info.channels .. " channels of " .. info.frameLength .. "-sample frames") end local codec = TtaCodec.decoder(info, stop) local frames = info.samples local dec: any = { sampleRate = info.sampleRate, channels = info.channels, frames = frames, duration = frames / info.sampleRate, bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, tags = tags or {}, bitsPerSample = info.bitsPerSample, float = false, source = { format = "tta", bitDepth = info.bitsPerSample, tags = tagInfo and tagInfo.items }, } local fl, count = info.frameLength, info.frames return Stream.packets(dec, { count = count, start = function(i: number): number return if i > count then frames else (i - 1) * fl end, decode = function(i: number): (number?, Err.Err?) return codec:frame(buf, i) end, pcm = function(): { number } return codec.pcm end, reset = function() end, stop = frames, scale = 1 / 2 ^ (info.bitsPerSample - 1), ints = true, }) end return Tta end __FILES["audio/vag"] = function() -- audio/vag: Sony VAG (PS-ADPCM: VAGp mono, VAGi stereo) and KVAG (IMA); layouts follow vgmstream r2117 (ISC, -- licenses/vgmstream-LICENSE.txt), bit-exact, Sony's leading blank frame included. Supports: loop points; encode VAGp / -- VAGi. Not supported: HEVAG (0x00020001 / 0x00030000), game-specific variants (pGAV, VAG1 / VAG2, Jak, ...). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") local Adpcm = __include("codecs/audio/Adpcm") local Decoder = __include("codecs/audio/Adpcm/Decoder") -- ------------------------------------------------------------------------------------------------ contract local Vag = { name = "vag", category = "audio", extensions = { "vag" }, mime = { "audio/x-vag" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 }, } -- ------------------------------------------------------------------------------------------------ types type Loop = { start: number, stop: number } type DecodeOptions = { maxFrames: number?, -- default 2^28 } type EncodeOptions = { loop: Loop?, -- loop points in frames of the input (stop exclusive), rounded out to 28-sample frames; default: the -- source's meta.source.loop, else none name: string?, -- the 16-byte name field (default: tags.title) interleave: number?, -- stereo: bytes per channel block (default 2048, a multiple of 16) } -- ------------------------------------------------------------------------------------------------ constants local HEVAG = { [0x00020001] = true, [0x00030000] = true } -- ------------------------------------------------------------------------------------------------ sniff function Vag.sniff(r: Bytes.Reader): number local m = r:peek(4) return if m == "VAGp" or m == "VAGi" or m == "KVAG" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode function Vag.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local dec, err = Vag.open(r) if not dec then return nil, err end local d = dec :: any local limit = opts and opts.maxFrames or 2 ^ 28 if d.frames > limit or d.frames * d.channels > 2 ^ 28 then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) end return Pcm.drain(d, { format = "vag", variant = d.variant, codec = d.codec, loop = d.loop }, limit) end -- ------------------------------------------------------------------------------------------------ encode function Vag.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local src, serr = Pcm.source(value) if not src then return nil, serr end local ch, rate = src.channels, src.sampleRate if ch > 2 then return nil, Err.new(Err.ARG, "VAG holds mono or stereo") end if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 32 then return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") end local il = o.interleave or 2048 if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then return nil, Err.new(Err.ARG, "interleave must be a multiple of 16") end local loop = o.loop local v = value :: any if loop == nil and type(v.meta) == "table" and type(v.meta.source) == "table" and type(v.meta.source.loop) == "table" then loop = v.meta.source.loop end local a, cerr = Pcm.collect(src) if not a then return nil, cerr end local n = a.frames local nf = (n + 27) // 28 -- data frames (after the blank one) local ls, le = -1, -1 if loop then if type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop > n then return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio") end ls, le = loop.start // 28, (loop.stop + 27) // 28 - 1 if le <= ls then return nil, Err.new(Err.ARG, "the loop must span two 28-sample frames") end end local chBytes = (nf + 1) * 16 local stride = if ch == 1 then chBytes else (chBytes + il - 1) // il * il local start = if ch == 1 then 0x30 else 0x800 local out = buffer.create(start + stride * ch) local title = o.name or (a.tags and a.tags.title) or "" buffer.writestring(out, 0, if ch == 1 then "VAGp" else "VAGi") buffer.writeu32(out, 4, bit32.byteswap(0x20)) if ch == 2 then buffer.writeu32(out, 8, il) end buffer.writeu32(out, 0x0C, bit32.byteswap(if ch == 1 then chBytes else stride)) buffer.writeu32(out, 0x10, bit32.byteswap(rate)) buffer.writestring(out, 0x20, string.sub(title, 1, 16)) local st = buffer.create(8 * ch) local plane = buffer.create(chBytes) for c = 0, ch - 1 do buffer.fill(plane, 0, 0) Adpcm.psxEncode(a.samples, c, ch, n, st, c * 8, plane, 16, 16) for k = 0, nf - 1 do local flag = if k == ls then 6 elseif k == le then 3 elseif k > ls and k < le then 2 else 0 if not loop and k == nf - 1 then flag = 1 end buffer.writeu8(plane, 16 + k * 16 + 1, flag) end if ch == 1 then buffer.copy(out, start, plane, 0, chBytes) else for b = 0, stride // il - 1 do local take = math.clamp(chBytes - b * il, 0, il) if take > 0 then buffer.copy(out, start + (b * ch + c) * il, plane, b * il, take) end end end end return out, nil end -- ------------------------------------------------------------------------------------------------ open -- vgmstream's loop reading: channel 0's first start flag 6 and first end flag 3 local function findLoop(buf: buffer, p: number, frames: number, il: number, ch: number): Loop? local ls, le = -1, -1 for k = 0, frames - 1 do local off = p + (k * 16) // il * il * ch + (k * 16) % il local flag = bit32.band(buffer.readu8(buf, off + 1), 15) if flag == 6 and ls < 0 then ls = k * 28 elseif flag == 3 and le < 0 then le = k * 28 + 28 if ls >= 0 then break end end end return if ls >= 0 and le > ls then { start = ls, stop = le } else nil end function Vag.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) if type(r) ~= "table" or type(r.buf) ~= "buffer" then return nil, Err.new(Err.ARG, "open: expected a Reader") end local h = r:sub(0) local magic = h:string(4) local total = r.limit - r.base if magic == "KVAG" then local size, rate, stereo = h:u32le(), h:u32le(), h:u16le() if h.err then return nil, h.err end if rate < 1 or stereo > 1 then return nil, Err.new(Err.CORRUPT, "bad KVAG header") end local dec: any = { sampleRate = rate, channels = stereo + 1, tags = {}, variant = "KVAG", codec = "ima" } local d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base + 14, size = math.min(size, total - 14), hi = true }) if d then d.bitrate = rate * 4 * (stereo + 1) end return d, err end if magic ~= "VAGp" and magic ~= "VAGi" then return nil, Err.new(Err.CORRUPT, "not a VAG file") end local version, il = h:u32be(), h:u32le() local chSize, rate = h:u32be(), h:u32be() local name = r:sub(0x20, 16):cstring(16) if h.err then return nil, h.err end if HEVAG[version] then return nil, Err.new(Err.UNSUPPORTED, "HEVAG (Vita / PS4 VAG)") end if rate < 1 or rate >= 2 ^ 31 then return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) end local ch, start = 1, 0x30 if magic == "VAGi" then ch, start = 2, 0x800 if il < 16 or il % 16 ~= 0 then return nil, Err.new(Err.CORRUPT, "bad interleave " .. il) end else il = 16 end if total < start then return nil, Err.new(Err.TRUNCATED, "the header runs past the end") end local size = math.min(chSize * ch, total - start) local p = r.base + start local frames = math.min(chSize // 16, (size // (il * ch)) * (il // 16) + math.clamp(size % (il * ch) - (ch - 1) * il, 0, il) // 16) local loop = if magic == "VAGp" then findLoop(r.buf, p, frames, il, ch) else nil -- vgmstream: VAGi never loops local tags = {} if name ~= "" then tags.title = name end local dec: any = { sampleRate = rate, channels = ch, tags = tags, variant = magic, codec = "psx", loop = loop } local d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = p, size = size, interleave = il, frames = frames * 28 }) if d then d.bitrate = rate * 16 * 8 * ch // 28 end return d, err end return Vag end __FILES["audio/voc"] = function() -- audio/voc: Creative Voice File (.voc), from Creative's format description. Supports: block types 1, 2, 3, 5, 8, 9 -- (8 / 16-bit, A-law, mu-law); markers and repeats played once, as ffmpeg; truncated files; encode version 1.20 type 9 -- blocks. Not supported: Creative ADPCM, channel count changes mid-file (the first block's rate is used). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") -- ------------------------------------------------------------------------------------------------ contract local Voc = { name = "voc", category = "audio", extensions = { "voc" }, mime = { "audio/x-voc" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, } type DecodeOptions = { maxFrames: number?, -- default 2^28 } type EncodeOptions = { sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16" } -- ------------------------------------------------------------------------------------------------ constants local MAGIC = "Creative Voice File\26" local T9_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le", [6] = "alaw", [7] = "ulaw" } local T1_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le" } local WRITE = { u8 = { 0, "u8", 8 }, s16 = { 4, "s16le", 16 }, alaw = { 6, "alaw", 8 }, ulaw = { 7, "ulaw", 8 } } local MAX_BLOCK = 0xFFFFFF - 12 -- payload bytes of one type 9 block (a 24-bit size, 12 header bytes) local readu8 = buffer.readu8 local function u16(b: buffer, o: number): number return readu8(b, o) + readu8(b, o + 1) * 256 end local function u24(b: buffer, o: number): number return readu8(b, o) + readu8(b, o + 1) * 256 + readu8(b, o + 2) * 65536 end -- ------------------------------------------------------------------------------------------------ sniff function Voc.sniff(r: Bytes.Reader): number return if r:peek(20) == MAGIC then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode type Segment = { at: number, frames: number, fmt: string? } -- fmt nil: silence function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) local b, base, limit = r.buf, r.base, r.limit if limit - base < 26 or buffer.readstring(b, base, 20) ~= MAGIC then return nil, Err.new(Err.CORRUPT, "bad magic", base) end local hsize = u16(b, base + 20) local version = u16(b, base + 22) if hsize < 26 or hsize > limit - base then return nil, Err.new(Err.CORRUPT, "bad header size", base + 20) end local maxFrames = opts and opts.maxFrames or 2 ^ 28 local rate, channels = 0, 0 local extRate, extChannels = 0, 0 -- a type 8 block's settings for the next type 1 block local lastFmt: string? = nil local codec = -1 local segments: { Segment } = {} local total = 0 local truncated = false local tags: Types.Tags = {} local p = base + hsize local function add(at: number, bytes: number, fmt: string?, ch: number, sr: number): Err.Err? if channels == 0 then channels, rate = ch, sr elseif ch ~= channels then return Err.new(Err.UNSUPPORTED, "the channel count changes mid-file", at) end local frames = if fmt then bytes // (ch * Pcm.Convert.SIZE[fmt]) else bytes if frames > 0 then total += frames if total > maxFrames then return Err.new(Err.LIMIT, string.format("over the %d frame limit", maxFrames)) end table.insert(segments, { at = at, frames = frames, fmt = fmt }) end return nil end while p < limit do local t = readu8(b, p) if t == 0 then break end if p + 4 > limit then truncated = true break end local size = u24(b, p + 1) local d = p + 4 local avail = math.min(size, limit - d) if avail < size then truncated = true end local err: Err.Err? = nil if t == 1 then if avail < 2 then break end local div, c = readu8(b, d), readu8(b, d + 1) local fmt = T1_CODECS[c] if not fmt then return nil, Err.new(Err.UNSUPPORTED, "Creative ADPCM (codec " .. c .. ")", d + 1) end local ch, sr = 1, 1000000 // (256 - div) if extChannels > 0 then ch, sr = extChannels, extRate extChannels = 0 end lastFmt, codec = fmt, c err = add(d + 2, avail - 2, fmt, ch, sr) elseif t == 2 then if lastFmt == nil then return nil, Err.new(Err.CORRUPT, "continuation block before any sound data", p) end err = add(d, avail, lastFmt, channels, rate) elseif t == 3 then if avail < 3 then break end local len, div = u16(b, d) + 1, readu8(b, d + 2) err = add(d, len, nil, if channels > 0 then channels else 1, if rate > 0 then rate else 1000000 // (256 - div)) elseif t == 5 then local s = buffer.readstring(b, d, avail) local z = string.find(s, "\0", 1, true) if z then s = string.sub(s, 1, z - 1) end tags.comment = if tags.comment then tags.comment .. "\n" .. s else s elseif t == 8 then if avail < 4 then break end local tc, mode = u16(b, d), readu8(b, d + 3) extChannels = mode + 1 extRate = 256000000 // (extChannels * (65536 - tc)) elseif t == 9 then if avail < 12 then break end local sr = readu8(b, d) + readu8(b, d + 1) * 256 + readu8(b, d + 2) * 65536 + readu8(b, d + 3) * 16777216 local ch, c = readu8(b, d + 5), u16(b, d + 6) local fmt = T9_CODECS[c] if not fmt then return nil, Err.new(Err.UNSUPPORTED, "codec " .. c, d + 6) end if ch < 1 or sr < 1 then return nil, Err.new(Err.CORRUPT, "bad channels or sample rate", d) end lastFmt, codec = fmt, c err = add(d + 12, avail - 12, fmt, ch, sr) end if err then return nil, err end p = d + size end if channels == 0 then return nil, Err.new(if truncated then Err.TRUNCATED else Err.CORRUPT, "no sound data", p) end local a = Types.Audio.new(rate, channels, total) local o = 0 for _, s in segments do local n = s.frames * channels if s.fmt then Pcm.Convert.decode(b, s.at, s.fmt :: string, n, a.samples, o) end o += n * 4 end a.tags = tags a.meta.source = { format = "voc", version = string.format("%d.%02d", version // 256, version % 256), codec = codec, sampleFormat = lastFmt, bitDepth = if lastFmt == "s16le" then 16 else 8, truncated = truncated or nil, } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then return nil, serr end local o: EncodeOptions = opts or {} local spec = WRITE[o.sampleFormat or "s16"] if not spec then return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) end if src.channels > 255 then return nil, Err.new(Err.ARG, "at most 255 channels") end if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then return nil, Err.new(Err.ARG, "the sample rate must be an integer") end local w = Bytes.writer(65536) w:string(MAGIC) w:u16le(26) w:u16le(0x0114) w:u16le((0xFFFF - 0x0114 + 0x1234 + 1) % 65536) -- ~version + 0x1234 if type(src.tags.comment) == "string" and #src.tags.comment > 0 then local s = string.sub(src.tags.comment, 1, 0xFFFFFE) w:u8(5) w:u24le(#s + 1) w:string(s) w:u8(0) end local size = Pcm.Convert.SIZE[spec[2]] local frameBytes = size * src.channels local framesPerBlock = MAX_BLOCK // frameBytes local blockAt, blockFrames = -1, 0 local tmp: buffer? = nil while true do local bf, n = src:read(math.min(8192, framesPerBlock), tmp) if n <= 0 then break end tmp = bf local i = 0 while i < n do if blockAt < 0 or blockFrames == framesPerBlock then blockAt = w:tell() blockFrames = 0 w:u8(9) w:u24le(0) w:u32le(src.sampleRate) w:u8(spec[3]) w:u8(src.channels) w:u16le(spec[1]) w:u32le(0) end local take = math.min(n - i, framesPerBlock - blockFrames) local at = w:reserve(take * frameBytes) Pcm.Convert.encode(bf, i * src.channels * 4, take * src.channels, spec[2], w.buf, at) w.pos = at + take * frameBytes blockFrames += take i += take local len = blockFrames * frameBytes + 12 w:setU8(blockAt + 1, len % 256) w:setU8(blockAt + 2, (len // 256) % 256) w:setU8(blockAt + 3, len // 65536) end end if src.err then return nil, src.err end w:u8(0) -- terminator return w:finish(), nil end -- ------------------------------------------------------------------------------------------------ open function Voc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) local a, err = Voc.decode(r, opts) if not a then return nil, err end local dec = Pcm.audioDecoder(a) :: any dec.source = a.meta.source return dec, nil end return Voc end __FILES["audio/vorbis"] = function() -- audio/vorbis: Ogg Vorbis (Vorbis I spec; RFC 5215); the decoder is a port of stb_vorbis 1.22 (public domain / MIT, -- licenses/stb_vorbis-LICENSE.txt) with libvorbis' sample-exact trimming and seeking. Supports: 1-255 channels, -- floor 1, residues 0-2, packetDecoder for Matroska / MP4; an encoder. Not supported: floor 0, chained streams. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Ogg = __include("containers/Ogg") local Setup = __include("codecs/audio/Vorbis/Setup") local Packet = __include("codecs/audio/Vorbis/Packet") local Encode = __include("audio/vorbis/Encode") local Pcm = __include("codecs/audio/Pcm") local VorbisComment = __include("codecs/audio/VorbisComment") -- ------------------------------------------------------------------------------------------------ contract local Vorbis = { name = "vorbis", category = "audio", extensions = { "ogg", "oga" }, mime = { "audio/ogg", "audio/vorbis" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Vorbis/Tables", "codecs/audio/Vorbis/Setup", "codecs/audio/Vorbis/Packet" }, caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 }, } type OpenOptions = { verify: boolean?, -- check the Ogg page CRCs (default true) } type EncodeOptions = { quality: number?, -- -1 .. 10 (default 3): the floor sits 2 * quality - 1 dB under the band energies (8 dB -- less at the top of the spectrum), which sets the residue's quantization step serial: number?, -- the Ogg stream serial number (default 0x464C5541) } -- ------------------------------------------------------------------------------------------------ constants local function waveOrder(ch: number): { number } local m = Pcm.WAVE_FROM_VORBIS[ch] if m then return m end local id = table.create(ch, 0) for c = 1, ch do id[c] = c end return id end local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, { VorbisComment.Field }?, Err.Err?) local id, ierr = Setup.ident(h1.data, h1.offset, h1.size) if not id then return nil, nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header") end local vendor, comments = Setup.comment(h2.data, h2.offset, h2.size) if not vendor then return nil, nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header") end local setup, serr = Setup.setup(h3.data, h3.offset, h3.size, id) if not setup then local code = if serr == "floor 0" then Err.UNSUPPORTED else Err.CORRUPT return nil, nil, nil, nil, nil, Err.new(code, serr or "bad setup header") end local tags, raw = VorbisComment.tags(comments or {}) return id, setup, vendor, tags, raw, nil end -- ------------------------------------------------------------------------------------------------ sniff function Vorbis.sniff(r: Bytes.Reader): number if r:remaining() < 35 or r:peek(4) ~= "OggS" then return 0 end local b, p = r.buf, r.pos local nseg = buffer.readu8(b, p + 26) local d = p + 27 + nseg if d + 7 > r.limit then return 0 end return if buffer.readu8(b, d) == 1 and buffer.readstring(b, d + 1, 6) == "vorbis" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Vorbis.open(r, opts) if not dec then return nil, err end return Pcm.drain(dec) end -- ------------------------------------------------------------------------------------------------ encode function Vorbis.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local src, serr = Pcm.source(value) if not src then return nil, serr end local o: EncodeOptions = opts or {} local q = o.quality or 3 if type(q) ~= "number" or q ~= q or q < -1 or q > 10 then return nil, Err.new(Err.ARG, "quality must be -1 .. 10") end if src.channels > 255 then return nil, Err.new(Err.ARG, "at most 255 channels") end if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 32 then return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") end local serial = o.serial or 0x464C5541 if type(serial) ~= "number" or serial ~= math.floor(serial) or serial < 0 or serial >= 2 ^ 32 then return nil, Err.new(Err.ARG, "serial must be a 32-bit unsigned integer") end local out, msg = Encode.encode(src :: any, { quality = q, vendor = "rosetta Vorbis encoder", serial = serial }) if not out then return nil, Err.new(Err.CORRUPT, tostring(msg)) end return out, nil end -- ------------------------------------------------------------------------------------------------ open local Stream = {} Stream.__index = Stream local function push(self: any, arrays: { { number } }, g0: number, count: number, hi: number) local lo = math.max(g0, self.startG, self.skipTo) if hi > g0 + count then hi = g0 + count end if hi > lo then table.insert(self.queue, { arrays, lo - g0 + 1, hi - g0, lo }) end end local function copyOut(self: any, count: number): { { number } } local t = table.create(self.channels) for c = 1, self.channels do local src = self.st.out[c] local a = table.create(count, 0) table.move(src, 1, count, 1, a) t[c] = a end return t end local function decodeMore(self: any): boolean local reader, st = self.reader, self.st while not self.ended do local p = reader:nextPacket() if p == nil then self.ended = true break end if p.gap then Packet.reset(st) self.syncing, self.pend, self.pendCount = true, {}, 0 end local count = Packet.decode(st, p.data, p.offset, p.size) if count >= 0 then local endG = if p.eos and p.granule >= 0 then p.granule else math.huge if self.syncing then if count > 0 then table.insert(self.pend, { copyOut(self, count), count }) self.pendCount += count end if p.granule >= 0 then -- the position is known again: this packet's output ends at its granule local g = p.granule - self.pendCount if p.eos and self.pendCount > 0 then g = math.max(g, self.pos) -- an end-trimmed last page: keep the running position end for _, c in self.pend do push(self, c[1], g, c[2], endG) g += c[2] end self.pos = g self.syncing, self.pend, self.pendCount = false, {}, 0 end else local g0 = self.pos self.pos += count if count > 0 then push(self, st.out, g0, count, endG) end if p.granule >= 0 and not p.eos then self.pos = p.granule end end if p.eos then self.ended = true end if #self.queue > 0 then return true end end end return #self.queue > 0 end function Stream.read(self: any, n: number, out: buffer?): (buffer, number) local ch = self.channels n = math.max(0, math.floor(n)) local b = if out and buffer.len(out) >= n * ch * 4 then out else buffer.create(n * ch * 4) local got = 0 local writef32 = buffer.writef32 while got < n do local q = self.queue[1] if q == nil then if not decodeMore(self) then break end q = self.queue[1] end local arrays, first, last = q[1], q[2], q[3] local take = math.min(n - got, last - first + 1) local order = self.order for c = 1, ch do local a = arrays[order[c]] local o = got * ch * 4 + (c - 1) * 4 for i = first, first + take - 1 do writef32(b, o, a[i]) o += ch * 4 end end got += take self.next = q[4] + take if first + take > last then table.remove(self.queue, 1) else q[2] = first + take q[4] += take end end if got > 0 then self.skipTo = -math.huge end return b, got end function Stream.position(self: any): number return (self.next - self.startG) / self.sampleRate end local function restart(self: any) local r = self.reader r:rewind() for _ = 1, 3 do r:nextPacket() end Packet.reset(self.st) self.pos = self.base self.syncing, self.pend, self.pendCount = false, {}, 0 self.ended = false self.queue = {} end function Stream.seek(self: any, seconds: number) local target = self.startG + math.floor(math.max(0, seconds) * self.sampleRate + 0.5) if target ~= target then target = self.startG end if self.lastG >= 0 and target > self.lastG then target = self.lastG end self.skipTo = target self.next = target local r = self.reader local g = target - self.st.n1 for _ = 1, 16 do if g <= self.startG then break end local G = r:seekGranule(g) if G == nil or G < 0 then break end -- decode forward to the next page boundary to learn the exact position Packet.reset(self.st) self.queue = {} self.ended = false self.syncing, self.pend, self.pendCount = true, {}, 0 self.pos = G local ok = false while true do local p = r:nextPacket() if p == nil then break end local count = Packet.decode(self.st, p.data, p.offset, p.size) if count > 0 then table.insert(self.pend, { copyOut(self, count), count }) self.pendCount += count end if p.granule >= 0 then if not p.eos then local g0 = p.granule - self.pendCount for _, c in self.pend do push(self, c[1], g0, c[2], math.huge) g0 += c[2] end self.pos = p.granule self.syncing, self.pend, self.pendCount = false, {}, 0 ok = true end break end end if ok then return end g = G - 1 -- the last page: start one page earlier end restart(self) self.skipTo = target self.next = target end function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?) local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil) if not demux then return nil, derr end local serial = demux:find("vorbis") if serial == nil then return nil, Err.new(Err.CORRUPT, "no Vorbis stream in the Ogg file") end local reader = demux:reader(serial) local h1 = reader:nextPacket() if h1 == nil then return nil, Err.new(Err.TRUNCATED, "missing identification header") end local id0, ierr = Setup.ident(h1.data, h1.offset, h1.size) if not id0 then return nil, Err.new(Err.CORRUPT, ierr or "bad identification header") end local h2 = reader:nextPacket() if h2 == nil then return nil, Err.new(Err.TRUNCATED, "missing comment header") end local h2copy = { data = Ogg.copy(h2), offset = 0, size = h2.size } local h3 = reader:nextPacket() if h3 == nil then return nil, Err.new(Err.TRUNCATED, "missing setup header") end local id, setup, vendor, tags, raw, herr = headers(h1, h2copy, h3) if not id then return nil, herr end local st = Packet.new(id, setup) if not st then return nil, Err.new(Err.CORRUPT, "bad block sizes") end -- the granule of the first returned sample: the first granule page minus what its packets return local base = 0 do local prev, sum = 0, 0 while true do local p = reader:nextPacket() if p == nil then break end local bs = Packet.blocksize(st, p.data, p.offset, p.size) if bs > 0 then if prev > 0 then sum += prev // 4 + bs // 4 end prev = bs end if p.granule >= 0 then base = p.granule - sum if p.eos then base = 0 -- one page holds the whole stream: the spec trims its end, not its start end break end end end local info = demux:stream(serial) local lastG = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else -1 local startG = math.max(base, 0) local frames = if lastG >= 0 then math.max(0, lastG - startG) else 0 local rate = id.sampleRate local self = setmetatable({ sampleRate = rate, channels = id.channels, frames = frames, duration = frames / rate, bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / rate)) else id.bitrateNominal, tags = tags, vendor = vendor, ident = id, -- WAVE channel order out (codecs/audio/Pcm): output channel c is Vorbis channel order[c] order = waveOrder(id.channels), source = { format = "vorbis", codec = "vorbis", vendor = vendor, comments = raw, blocksizes = { id.blocksize0, id.blocksize1 }, nominalBitrate = id.bitrateNominal, }, demux = demux, reader = reader, st = st, base = base, startG = startG, lastG = lastG, pos = base, next = startG, skipTo = -math.huge, queue = {}, syncing = false, pend = {}, pendCount = 0, ended = false, }, Stream) restart(self) return self :: any, nil end -- ------------------------------------------------------------------------------------------------ extras -- raw Vorbis packets: Matroska / WebM / MP4 carry the three headers in their codec private data function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err?) local function pk(b: buffer): any return { data = b, offset = 0, size = buffer.len(b) } end local id, setup, vendor, tags, _, err = headers(pk(h1), pk(h2), pk(h3)) if not id then return nil, err end local st = Packet.new(id, setup) if not st then return nil, Err.new(Err.CORRUPT, "bad block sizes") end return { sampleRate = id.sampleRate, channels = id.channels, vendor = vendor, tags = tags, out = st.out, -- per Vorbis channel; WAVE-order channel c is out[order[c]] order = waveOrder(id.channels), decode = function(_self: any, b: buffer, offset: number, size: number): number if offset < 0 or size < 0 or offset + size > buffer.len(b) then return -1 end return Packet.decode(st, b, offset, size) end, reset = function(_self: any) Packet.reset(st) end, }, nil end return Vorbis end __FILES["audio/vorbis/Encode"] = @native function() -- audio/vorbis/Encode: Vorbis I encoder in Ogg, from the Vorbis I spec (no libvorbis code): long blocks only (2048), -- one floor 1 per channel (30 posts), square-polar coupling, residue type 2, a fixed codebook set with Laplacian lengths. local Mdct = __include("codecs/audio/Mdct") local Pcm = __include("codecs/audio/Pcm") local VorbisComment = __include("codecs/audio/VorbisComment") local Ogg = __include("containers/Ogg") local Tables = __include("codecs/audio/Vorbis/Tables") local Encode = {} local floor, log, exp, abs = math.floor, math.log, math.exp, math.abs local writeu8 = buffer.writeu8 local POW = table.create(40, 0) for i = 0, 39 do POW[i + 1] = 2 ^ i end local N = 2048 local N2 = 1024 local PSIZE_PER_CHANNEL = 16 -- residue partitions hold 16 values per channel (libvorbis needs a multiple of ch) local MULT = 2 -- floor1 multiplier (range 128) local RANGE = 128 local NCLASS = 6 -- ------------------------------------------------------------------------------------------------ LSB-first bit writer type W = { buf: buffer, pos: number, acc: number, cnt: number } @native local function newW(size: number): W return { buf = buffer.create(size), pos = 0, acc = 0, cnt = 0 } end @native local function put(w: W, v: number, n: number) if n == 0 then return end local acc = w.acc + v * POW[w.cnt + 1] local cnt = w.cnt + n local b, p = w.buf, w.pos if p + 8 > buffer.len(b) then local nb = buffer.create(buffer.len(b) * 2 + 64) buffer.copy(nb, 0, b, 0, p) b = nb w.buf = nb end while cnt >= 8 do local byte = acc % 256 writeu8(b, p, byte) p += 1 acc = (acc - byte) / 256 cnt -= 8 end w.acc, w.cnt, w.pos = acc, cnt, p end @native local function finish(w: W): buffer if w.cnt > 0 then put(w, 0, 8 - w.cnt) end local out = buffer.create(w.pos) buffer.copy(out, 0, w.buf, 0, w.pos) return out end @native local function putString(w: W, s: string) for i = 1, #s do put(w, string.byte(s, i), 8) end end @native local function ilog(x: number): number local n = 0 while x > 0 do n += 1 x = floor(x / 2) end return n end -- ------------------------------------------------------------------------------------------------ codebooks type Book = { dims: number, entries: number, lengths: { number }, codes: { number }, -- bit-reversed codewords (ready for the LSB-first writer) lookup: number, -- 0 or 1 minimum: number, delta: number, values: number, -- lookup1 values per dimension } @native local function huffmanLengths(w: { number }): { number } local n = #w local total = 0 for i = 1, n do total += w[i] end local lens = table.create(n, 0) if n == 1 then lens[1] = 1 return lens end local minw = total * 2 ^ -20 local order = table.create(n, 0) for i = 1, n do order[i] = i end local weight = table.create(2 * n, 0) local parent = table.create(2 * n, 0) for i = 1, n do weight[i] = math.max(w[i], minw) end table.sort(order, @native function(a: number, b: number): boolean if weight[a] ~= weight[b] then return weight[a] < weight[b] end return a < b end) local q1, h1 = order, 1 local q2, h2, t2 = table.create(n, 0), 1, 0 local nextId = n @native local function pop(): number local a = if h1 <= n then q1[h1] else nil local b = if h2 <= t2 then q2[h2] else nil if a and (not b or weight[a] <= weight[b]) then h1 += 1 return a end h2 += 1 return b :: number end for _ = 1, n - 1 do local a = pop() local b = pop() nextId += 1 weight[nextId] = weight[a] + weight[b] parent[a], parent[b] = nextId, nextId t2 += 1 q2[t2] = nextId end for i = 1, n do local d, x = 0, i while parent[x] ~= 0 do x = parent[x] d += 1 end lens[i] = d end return lens end -- the spec's codeword assignment (lowest free leaf, in entry order) @native local function assign(lens: { number }): { number } local codes = table.create(#lens, 0) local available = table.create(33, 0) local first = true for i, len in lens do if len > 0 then local code if first then first = false code = 0 for l = 1, len do available[l + 1] = POW[33 - l] + 1 end else local z = len while z > 0 and available[z + 1] == 0 do z -= 1 end code = available[z + 1] - 1 available[z + 1] = 0 for y = len, z + 1, -1 do available[y + 1] = code + POW[33 - y] + 1 end end -- the top len bits of the 32-bit left-aligned code, MSB first, reversed for the LSB-first writer local msb = floor(code / POW[33 - len]) local rev = 0 for _ = 1, len do rev = rev * 2 + msb % 2 msb = floor(msb / 2) end codes[i] = rev end end return codes end @native local function makeBook(dims: number, entries: number, weight: (number) -> number, lookup: number, minimum: number, delta: number, values: number): Book local w = table.create(entries, 0) for e = 0, entries - 1 do w[e + 1] = weight(e) end local lens = huffmanLengths(w) return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values } end @native local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book local values = 2 * h + 1 local entries = values ^ dims return makeBook(dims, entries, @native function(e: number): number local wt = 1 local x = e for _ = 1, dims do local v = x % values - h x = x // values wt *= exp(-abs(v) / s) * (if v == 0 then zeroBoost else 1) end return wt end, 1, -h * scale, scale, values) end local BOOK_FLOOR = makeBook(1, RANGE, @native function(e: number): number return exp(-e / 7) + 0.002 end, 0, 0, 0, 0) local CLASS_W = { 0.30, 0.30, 0.20, 0.12, 0.06, 0.02 } local BOOK_CLASS = makeBook(2, NCLASS * NCLASS, @native function(e: number): number return CLASS_W[e % NCLASS + 1] * CLASS_W[e // NCLASS + 1] end, 0, 0, 0, 0) local BOOK_A = vqBook(4, 1, 1, 0.6, 2.5) -- |v| <= 1, 4 at a time (mostly zeros) local BOOK_B = vqBook(2, 4, 1, 1.4, 1) -- |v| <= 4 local BOOK_C = vqBook(2, 15, 1, 4, 1) -- |v| <= 15 local BOOK_D = vqBook(2, 15, 16, 3, 1) -- multiples of 16 up to 240 local BOOK_E = vqBook(2, 15, 256, 3, 1) -- multiples of 256 up to 3840 local BOOKS = { BOOK_FLOOR, BOOK_CLASS, BOOK_A, BOOK_B, BOOK_C, BOOK_D, BOOK_E } local FLOOR_BOOK, CLASS_BOOK, A_BOOK, B_BOOK, C_BOOK, D_BOOK, E_BOOK = 0, 1, 2, 3, 4, 5, 6 -- the books of each residue class per pass (book numbers; -1 = none) local CLASS_BOOKS = { { -1, -1, -1 }, { A_BOOK, -1, -1 }, { B_BOOK, -1, -1 }, { C_BOOK, -1, -1 }, { D_BOOK, C_BOOK, -1 }, { E_BOOK, D_BOOK, C_BOOK }, } local CLASS_MAX = { 0, 1, 4, 15, 255, 4095 } -- float32_pack (spec 9.2.2) of an integer-valued x @native local function float32Pack(x: number): number local sign = if x < 0 then 2147483648 else 0 local m = abs(x) local e = 788 while m >= 2097152 do m /= 2 e += 1 end return sign + e * 2097152 + floor(m) end @native local function writeBook(w: W, b: Book) put(w, 0x564342, 24) put(w, b.dims, 16) put(w, b.entries, 24) put(w, 0, 1) -- not ordered put(w, 0, 1) -- not sparse for i = 1, b.entries do put(w, b.lengths[i] - 1, 5) end put(w, b.lookup, 4) if b.lookup == 1 then put(w, float32Pack(b.minimum), 32) put(w, float32Pack(b.delta), 32) local vb = ilog(b.values - 1) put(w, vb - 1, 4) put(w, 0, 1) -- sequence_p for j = 0, b.values - 1 do put(w, j, vb) end end end @native local function putEntry(w: W, b: Book, e: number) put(w, b.codes[e + 1], b.lengths[e + 1]) end -- ------------------------------------------------------------------------------------------------ floor posts -- x positions: 0, 1024, then 28 log-spaced points in bisection order (coarse first) so predictions are good local POSTS: { number } = { 0, N2 } do local xs = {} local seen = { [0] = true, [N2] = true } for j = 0, 27 do local x = floor(3 + 957 * (j / 27) ^ 2.2 + 0.5) -- 3 .. 960, denser at low frequencies while seen[x] do x += 1 end seen[x] = true table.insert(xs, x) end table.sort(xs) local queue = { { 1, #xs } } local qh = 1 while qh <= #queue do local r = queue[qh] qh += 1 if r[1] <= r[2] then local m = (r[1] + r[2]) // 2 table.insert(POSTS, xs[m]) table.insert(queue, { r[1], m - 1 }) table.insert(queue, { m + 1, r[2] }) end end end local NPOSTS = #POSTS -- 30 local FLOOR_PARTS = (NPOSTS - 2) // 4 -- 7 partitions of one class with 4 dimensions local SORTED: { number } = table.create(NPOSTS, 0) -- post indices (1-based) by increasing x for i = 1, NPOSTS do SORTED[i] = i end table.sort(SORTED, @native function(a: number, b: number): boolean return POSTS[a] < POSTS[b] end) local LOW, HIGH = table.create(NPOSTS, 0), table.create(NPOSTS, 0) for j = 3, NPOSTS do local lo, hi = -1, 65536 local x = POSTS[j] for k = 1, j - 1 do local xv = POSTS[k] if xv > lo and xv < x then LOW[j], lo = k, xv end if xv < hi and xv > x then HIGH[j], hi = k, xv end end end -- the floor value (0..127) closest to an amplitude, through the spec's inverse dB table local DB = table.create(RANGE, 0) for y = 0, RANGE - 1 do DB[y + 1] = 20 * math.log10(Tables[y * MULT + 1]) end @native local function yOf(db: number): number local y = floor((db - DB[1]) / (DB[RANGE] - DB[1]) * (RANGE - 1) + 0.5) return math.clamp(y, 0, RANGE - 1) end @native local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number local dy = y1 - y0 local adx = x1 - x0 local off = (abs(dy) * (x - x0)) // adx return if dy < 0 then y0 - off else y0 + off end -- render the decoder's floor curve for final Y values into F[1..N2] (only the posts the decoder marks used) @native local function renderFloor(Y: { number }, used: { boolean }, F: { number }) local lx, ly = 0, Y[1] * MULT for q = 2, NPOSTS do local j = SORTED[q] if not used[j] then continue end local hx, hy = POSTS[j], Y[j] * MULT -- draw_line(lx, ly, hx, hy) local dy = hy - ly local adx = hx - lx local ady = abs(dy) local base = if dy < 0 then -(ady // adx) else ady // adx local sy = if dy < 0 then base - 1 else base + 1 ady -= abs(base) * adx local x, y, err = lx, ly, 0 local x1 = math.min(hx, N2) if x < x1 then F[x + 1] = Tables[y % 256 + 1] x += 1 while x < x1 do err += ady if err >= adx then err -= adx y += sy else y += base end F[x + 1] = Tables[y % 256 + 1] x += 1 end end lx, ly = hx, hy end for x = lx + 1, N2 do F[x] = Tables[ly % 256 + 1] end end -- the coded value for target t at post j given the final values of its neighbours (spec 7.2.4 step 1, inverted) @native local function floorVal(Y: { number }, j: number): number local lo, hi = LOW[j], HIGH[j] local pred = predict(POSTS[j], POSTS[lo], POSTS[hi], Y[lo], Y[hi]) local t = Y[j] local d = t - pred if d == 0 then return 0 end local highroom = RANGE - pred local lowroom = pred local room = if highroom < lowroom then highroom * 2 else lowroom * 2 local cands = { if d > 0 then 2 * d else -2 * d - 1, d + lowroom, -d + highroom - 1 } for _, v in cands do if v > 0 and v < RANGE then local got if v >= room then got = if highroom > lowroom then v - lowroom + pred else pred - v + highroom - 1 elseif v % 2 == 1 then got = pred - (v + 1) // 2 else got = pred + v // 2 end if got == t then return v end end end return 0 end -- ------------------------------------------------------------------------------------------------ headers @native local function identHeader(ch: number, rate: number, nominal: number): buffer local w = newW(64) put(w, 1, 8) putString(w, "vorbis") put(w, 0, 32) put(w, ch, 8) put(w, rate, 32) put(w, 0, 32) put(w, nominal, 32) put(w, 0, 32) put(w, 8, 4) -- blocksize 0: 256 put(w, 11, 4) -- blocksize 1: 2048 put(w, 1, 1) return finish(w) end @native local function commentHeader(vendor: string, tags: { [string]: string }): buffer local w = newW(256) put(w, 3, 8) putString(w, "vorbis") put(w, #vendor, 32) putString(w, vendor) local fields = VorbisComment.fields(tags) put(w, #fields, 32) for _, s in fields do put(w, #s, 32) putString(w, s) end put(w, 1, 1) return finish(w) end @native local function setupHeader(ch: number): buffer local w = newW(8192) put(w, 5, 8) putString(w, "vorbis") -- codebooks put(w, #BOOKS - 1, 8) for _, b in BOOKS do writeBook(w, b) end -- time domain placeholders put(w, 0, 6) put(w, 0, 16) -- one floor 1 put(w, 0, 6) put(w, 1, 16) put(w, FLOOR_PARTS, 5) for _ = 1, FLOOR_PARTS do put(w, 0, 4) -- class 0 end put(w, 3, 3) -- class 0: 4 dimensions put(w, 0, 2) -- no subclasses put(w, FLOOR_BOOK + 1, 8) -- its one subclass book (+1) put(w, MULT - 1, 2) put(w, 10, 4) -- rangebits: x in 0 .. 1024 for j = 3, NPOSTS do put(w, POSTS[j], 10) end -- one residue 2 put(w, 0, 6) put(w, 2, 16) put(w, 0, 24) -- begin put(w, N2 * ch, 24) -- end put(w, PSIZE_PER_CHANNEL * ch - 1, 24) put(w, NCLASS - 1, 6) put(w, CLASS_BOOK, 8) for c = 1, NCLASS do local bits = 0 for pass = 1, 3 do if CLASS_BOOKS[c][pass] >= 0 then bits += POW[pass] end end put(w, bits % 8, 3) if bits >= 8 then put(w, 1, 1) put(w, bits // 8, 5) else put(w, 0, 1) end end for c = 1, NCLASS do for pass = 1, 3 do local b = CLASS_BOOKS[c][pass] if b >= 0 then put(w, b, 8) end end end -- one mapping put(w, 0, 6) put(w, 0, 16) put(w, 0, 1) -- one submap if ch == 2 then put(w, 1, 1) put(w, 0, 8) -- one coupling step put(w, 0, 1) -- magnitude: channel 0 put(w, 1, 1) -- angle: channel 1 else put(w, 0, 1) end put(w, 0, 2) put(w, 0, 8) -- submap 0: time (unused) put(w, 0, 8) -- floor 0 put(w, 0, 8) -- residue 0 -- one mode: long blocks put(w, 0, 6) put(w, 1, 1) put(w, 0, 16) put(w, 0, 16) put(w, 0, 8) put(w, 1, 1) -- framing return finish(w) end -- ------------------------------------------------------------------------------------------------ encoder type Source = { sampleRate: number, channels: number, frames: number, tags: { [string]: string }, read: (self: any, n: number, out: buffer?) -> (buffer, number), err: any, } type Options = { quality: number, -- -1 .. 10 vendor: string, serial: number, } @native local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number) local b = CLASS_BOOKS[c][pass] if b < 0 then return end local book = BOOKS[b + 1] local dims, h = book.dims, (book.values - 1) // 2 local scale = book.delta local values = book.values local i = 0 while i < psize do local e = 0 local m = 1 for k = 0, dims - 1 do local x = v[o + i + k + 1] -- the part of x this pass carries (coarse passes take the rounded multiple of their scale) local q if pass < 3 and CLASS_BOOKS[c][pass + 1] >= 0 then q = math.clamp(floor(x / scale + 0.5), -h, h) else q = math.clamp(x // scale, -h, h) end v[o + i + k + 1] = x - q * scale e += (q + h) * m m *= values end putEntry(w, book, e) i += dims end end @native function Encode.encode(src: Source, opts: Options): (buffer?, string?) local ch, rate = src.channels, src.sampleRate local q = math.clamp(opts.quality, -1, 10) local snrDb = 2 * q - 1 -- floor level below the band energy (at low frequencies; 8 dB less at the top) local mux = Ogg.muxer({ pageSize = 4096 }) local stream = mux:stream(opts.serial) local nominal = floor(math.clamp(rate * ch * (0.6 + 0.12 * q), 32000, 500000)) stream:packet(identHeader(ch, rate, nominal), 0, { flush = true }) stream:packet(commentHeader(opts.vendor, src.tags), 0) stream:packet(setupHeader(ch), 0, { flush = true }) local plan = Mdct.new(N) :: Mdct.Plan local win = Mdct.window("vorbis", N) :: { number } -- input ring: per channel the samples of the current frame [k*1024 - 1024, k*1024 + 1024) local frame: { { number } } = table.create(ch) :: any for c = 1, ch do frame[c] = table.create(N, 0) end -- the input is in WAVE channel order; input channel c goes to Vorbis channel order[c] local order = Pcm.WAVE_FROM_VORBIS[ch] or {} if #order ~= ch then order = table.create(ch, 0) for c = 1, ch do order[c] = c end end local blk = table.create(N, 0) local X: { { number } } = table.create(ch) :: any local R: { { number } } = table.create(ch) :: any for c = 1, ch do X[c] = table.create(N2, 0) R[c] = table.create(N2, 0) end local F = table.create(N2, 0) local Y = table.create(NPOSTS, 0) local vals = table.create(NPOSTS, 0) local used = table.create(NPOSTS, false) local inter = table.create(N2 * ch, 0) local psize = PSIZE_PER_CHANNEL * ch local npart = N2 * ch // psize local classes = table.create(npart + 2, 0) local total = 0 local srcDone = false local tmp: buffer? = nil local pending: buffer? = nil local pendN, pendOff = 0, 0 local k = 0 local lastWanted = -1 -- the last packet index needed (known once the input ends) while true do for c = 1, ch do local fr = frame[c] table.move(fr, N2 + 1, N, 1) end local got = 0 while got < N2 and not srcDone do if pendN == 0 then local b, n = src:read(4096, tmp) if n <= 0 then srcDone = true break end tmp = b pending, pendN, pendOff = b, n, 0 end local take = math.min(N2 - got, pendN) local pb = pending :: buffer for i = 0, take - 1 do local base = (pendOff + i) * ch * 4 for c = 1, ch do frame[order[c]][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4) end end got += take pendN -= take pendOff += take end for c = 1, ch do local fr = frame[c] for i = N2 + got + 1, N do fr[i] = 0 end end total += got if srcDone and lastWanted < 0 then lastWanted = (total + N2 - 1) // N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024)) end -- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024) local energy = 0 for c = 1, ch do local fr = frame[c] for i = 1, N do blk[i] = fr[i] * win[i] end Mdct.forward(plan, blk, 1, X[c], 1, 1, 4 / N) local xc = X[c] for i = 1, N2 do energy += xc[i] * xc[i] end end local w = newW(2048) put(w, 0, 1) -- audio packet -- (one mode: 0 bits) long block, previous and next long put(w, 1, 1) put(w, 1, 1) local silent = energy < 1e-18 if silent then for _ = 1, ch do put(w, 0, 1) -- no floor: the channel is zero end else -- the floor from the loudest channel's band energies at each post for j = 1, NPOSTS do local x = POSTS[j] -- the band around x: halfway to the neighbouring posts in x order local idx = table.find(SORTED, j) :: number local lo = if idx > 1 then (POSTS[SORTED[idx - 1]] + x) // 2 else 0 local hi = if idx < NPOSTS then (POSTS[SORTED[idx + 1]] + x) // 2 else N2 - 1 if hi < lo then hi = lo end local e = 0 for c = 1, ch do local xc = X[c] local s = 0 for i = lo + 1, math.min(hi + 1, N2) do s += xc[i] * xc[i] end s /= (hi - lo + 1) if s > e then e = s end end local db = if e > 0 then 10 * math.log10(e) - snrDb + 8 * x / N2 else -200 Y[j] = yOf(db) end -- the decoder's step 2 flags: a point is drawn when its value or a later neighbour's value is nonzero used[1], used[2] = true, true for j = 3, NPOSTS do local v = floorVal(Y, j) vals[j] = v used[j] = v ~= 0 if v ~= 0 then used[LOW[j]], used[HIGH[j]] = true, true end end renderFloor(Y, used, F) -- residues: X / F rounded, then coupling, then interleaving for c = 1, ch do local xc, rc = X[c], R[c] for i = 1, N2 do local v = floor(xc[i] / F[i] + 0.5) rc[i] = math.clamp(v, -4095, 4095) end end if ch == 2 then local l, r = R[1], R[2] for i = 1, N2 do local a, b = l[i], r[i] local m, an if abs(a) > abs(b) then m = a an = if a > 0 then a - b else b - a else m = b an = if b > 0 then a - b else b - a end -- keep the angle inside the books' range l[i], r[i] = m, math.clamp(an, -4095, 4095) end end for c = 1, ch do local rc = R[c] for i = 1, N2 do inter[(i - 1) * ch + c] = rc[i] end end -- floors for _ = 1, ch do put(w, 1, 1) put(w, Y[1], 7) put(w, Y[2], 7) for j = 3, NPOSTS do putEntry(w, BOOK_FLOOR, vals[j]) end end -- residue classes for p = 0, npart - 1 do local m = 0 for i = 1, psize do local a = abs(inter[p * psize + i]) if a > m then m = a end end local c = 1 while CLASS_MAX[c] < m do c += 1 end classes[p + 1] = c end classes[npart + 1] = 1 for pass = 1, 3 do for p = 0, npart - 1, 2 do if pass == 1 then putEntry(w, BOOK_CLASS, (classes[p + 1] - 1) * NCLASS + (classes[p + 2] - 1)) -- first partition: the high digit end writePartition(w, inter, p * psize, psize, classes[p + 1], pass) if p + 1 < npart then writePartition(w, inter, (p + 1) * psize, psize, classes[p + 2], pass) end end end end local pk = finish(w) local last = lastWanted >= 0 and k >= lastWanted local granule = if k == 0 then 0 else math.min(k * N2, if lastWanted >= 0 then total else math.huge) stream:packet(pk, granule, if last then { eos = true } else nil) if last then break end k += 1 end if src.err then return nil, tostring(src.err) end return mux:finish(), nil end Encode.BOOKS = BOOKS return Encode end __FILES["audio/wav"] = function() -- audio/wav: WAVE in RIFF / RIFX / RF64 / BW64; absorbed from wav-luau fd9a909 (same author). Supports: PCM 8-32 bit, -- float 32 / 64, A-law, mu-law, IMA / MS ADPCM, EXTENSIBLE, LIST/INFO tags, data size 0 / 0xFFFFFFFF (to the end); -- encode PCM and f32, EXTENSIBLE and RF64 as ffmpeg. Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") local Riff = __include("containers/Riff") local Codecs = __include("audio/wav/Codecs") local Adpcm = __include("codecs/audio/Adpcm") -- ------------------------------------------------------------------------------------------------ contract local Wav = { name = "wav", category = "audio", extensions = { "wav", "wave", "rf64", "bw64" }, mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" }, caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, } -- ------------------------------------------------------------------------------------------------ types type Tags = { [string]: string } type OpenOptions = { maxBytes: number?, } type EncodeOptions = { sampleFormat: ("u8" | "s16" | "s24" | "s32" | "f32")?, -- default "s16" rf64: (boolean | "auto")?, -- default "auto": RF64 only when the file passes 4 GiB extensible: boolean?, -- force (true) or forbid (false) WAVE_FORMAT_EXTENSIBLE; default as ffmpeg channelMask: number?, -- the EXTENSIBLE speaker mask (default: ffmpeg's default layout for the channel count) tags: Tags?, -- default: the Audio's tags rf64Threshold: number?, -- testing: the RIFF size past which "auto" switches to RF64 (default 0xFFFFFFFF) } -- ------------------------------------------------------------------------------------------------ constants Wav.FORMAT_PCM = 1 Wav.FORMAT_MS_ADPCM = 2 Wav.FORMAT_FLOAT = 3 Wav.FORMAT_ALAW = 6 Wav.FORMAT_MULAW = 7 Wav.FORMAT_IMA_ADPCM = 0x11 Wav.FORMAT_EXTENSIBLE = 0xFFFE local FORMAT_NAMES = { [1] = "pcm", [2] = "ms_adpcm", [3] = "float", [6] = "alaw", [7] = "mulaw", [0x11] = "ima_adpcm", } -- LIST/INFO ids -> tag names local INFO_TAGS = { INAM = "title", IART = "artist", IPRD = "album", ICMT = "comment", ICRD = "date", IGNR = "genre", ITRK = "track", IPRT = "track", ISFT = "encoder", ICOP = "copyright", IENG = "engineer", ISBJ = "subject", IKEY = "keywords", } -- A-law / mu-law -> f32 tables (G.711, as ffmpeg's alaw2linear / ulaw2linear) local ALAW, MULAW = buffer.create(1024), buffer.create(1024) do for i = 0, 255 do local a = bit32.bxor(i, 0x55) local t = bit32.band(a, 15) local seg = bit32.rshift(bit32.band(a, 0x70), 4) if seg > 0 then t = bit32.lshift(t * 2 + 1 + 32, seg + 2) else t = bit32.lshift(t * 2 + 1, 3) end if bit32.band(a, 0x80) == 0 then t = -t end buffer.writef32(ALAW, i * 4, t / 32768) local u = bit32.band(bit32.bnot(i), 255) local m = bit32.lshift(bit32.lshift(bit32.band(u, 15), 3) + 0x84, bit32.rshift(bit32.band(u, 0x70), 4)) local v = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84 buffer.writef32(MULAW, i * 4, v / 32768) end end local Decoder = {} Decoder.__index = Decoder type Decoder = typeof(setmetatable( {} :: { sampleRate: number, channels: number, frames: number, duration: number, bitrate: number, tags: Tags, format: string, formatTag: number, bitsPerSample: number, blockAlign: number, container: string, dataOffset: number, dataSize: number, truncated: boolean, channelMask: number?, validBits: number?, _buf: buffer, _pos: number, _be: boolean, _bytes: number, _kind: string, _spb: number, _cache: buffer?, _cacheBlock: number, _cacheFrames: number, _coefs: buffer?, _ncoef: number, _state: buffer?, _tmp: buffer, }, Decoder )) local function trimTag(s: string): string local e = #s while e > 0 do local c = string.byte(s, e) if c ~= 0 and c ~= 32 then break end e -= 1 end local z = string.find(s, "\0", 1, true) if z and z <= e then e = z - 1 end return string.sub(s, 1, e) end -- ------------------------------------------------------------------------------------------------ sniff function Wav.sniff(r: Bytes.Reader): number return if Riff.sniff(r) == "WAVE" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode function Wav.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = Wav.open(r, opts) if not dec then return nil, err end return Pcm.drain(dec, { format = "wav", codec = dec.format, bitDepth = dec.bitsPerSample, container = dec.container, channelMask = dec.channelMask, truncated = dec.truncated, }) end -- ------------------------------------------------------------------------------------------------ encode local SAMPLE_BYTES = { u8 = 1, s16 = 2, s24 = 3, s32 = 4, f32 = 4 } -- ffmpeg's default speaker masks per channel count (av_channel_layout_default) local MASKS = { [1] = 0x4, [2] = 0x3, [3] = 0xB, [4] = 0x107, [5] = 0x37, [6] = 0x3F, [7] = 0x70F, [8] = 0x63F } local GUID_TAIL = "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" -- KSDATAFORMAT_SUBTYPE_* after the 2-byte format tag -- tags -> LIST/INFO ids (the first id per name) local TAG_IDS = { title = "INAM", artist = "IART", album = "IPRD", comment = "ICMT", date = "ICRD", genre = "IGNR", track = "ITRK", encoder = "ISFT", copyright = "ICOP", engineer = "IENG", subject = "ISBJ", keywords = "IKEY" } local BLOCK = 65536 -- frames per data piece when streaming a Decoder local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean): (any, Err.Err?) if type(value) ~= "table" then return nil, Err.new(Err.ARG, "encode: needs an Audio or a Decoder") end local o: EncodeOptions = opts or {} local kind = o.sampleFormat or "s16" local bytes: number? = SAMPLE_BYTES[kind] if not bytes then return nil, Err.new(Err.ARG, "encode: sampleFormat must be u8, s16, s24, s32 or f32") end local rate: number, ch: number = value.sampleRate, value.channels if type(rate) ~= "number" or rate < 1 or rate > 4294967295 or rate % 1 ~= 0 then return nil, Err.new(Err.ARG, "encode: bad sample rate") end if type(ch) ~= "number" or ch < 1 or ch > 65535 or ch % 1 ~= 0 then return nil, Err.new(Err.ARG, "encode: bad channel count") end local isAudio = type(value.samples) == "buffer" if not isAudio and type(value.read) ~= "function" then return nil, Err.new(Err.ARG, "encode: needs an Audio (samples) or a Decoder (read)") end local frameBytes = bytes * ch local pieces: { buffer } = {} local frames: number = 0 if isAudio then frames = (value.frames :: number?) or (buffer.len(value.samples) // (ch * 4)) if type(frames) ~= "number" or frames < 0 or buffer.len(value.samples) < frames * ch * 4 then return nil, Err.new(Err.ARG, "encode: the samples buffer is shorter than frames * channels") end if not asParts and frames * frameBytes > 0x3FFFFF00 then return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)") end -- pieces of at most 256 MiB local per = math.max(1, 0x10000000 // frameBytes) local f0 = 0 while f0 < frames do local n = math.min(per, frames - f0) local b = buffer.create(n * frameBytes) Codecs.quantize(value.samples, f0 * ch, b, 0, n * ch, kind) table.insert(pieces, b) f0 += n end else local tmp = buffer.create(BLOCK * ch * 4) while true do local ok, out, n = pcall(value.read, value, BLOCK, tmp) if not ok then return nil, Err.new(Err.ARG, "encode: the decoder failed: " .. tostring(out)) end if type(n) ~= "number" or n <= 0 or type(out) ~= "buffer" then break end n = math.min(n, buffer.len(out) // (ch * 4)) local b = buffer.create(n * frameBytes) Codecs.quantize(out, 0, b, 0, n * ch, kind) table.insert(pieces, b) frames += n if not asParts and frames * frameBytes > 0x3FFFFF00 then return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)") end end end local dataSize = frames * frameBytes local bits = bytes * 8 local float = kind == "f32" local tag = if float then 3 else 1 local extensible = ch > 2 or rate > 48000 or (not float and bits > 16) if o.extensible ~= nil then extensible = o.extensible end local w = Riff.writer("WAVE", { rf64 = if o.rf64 ~= nil then o.rf64 else "auto", sampleCount = frames, rf64Threshold = o.rf64Threshold }) local fmt = Bytes.writer(40) fmt:u16le(if extensible then 0xFFFE else tag) fmt:u16le(ch) fmt:u32le(rate) fmt:u32le(rate * frameBytes) fmt:u16le(frameBytes) fmt:u16le(bits) if extensible then fmt:u16le(22) fmt:u16le(bits) fmt:u32le(o.channelMask or MASKS[ch] or 0) fmt:u16le(tag) fmt:string(GUID_TAIL) elseif float then fmt:u16le(0) -- cbSize end w:chunk("fmt ", fmt:finish()) if float then local fact = Bytes.writer(4) fact:u32le(if w.rf64 == true or frames > 0xFFFFFFFF then 0xFFFFFFFF else frames) -- RF64: in ds64 (as ffmpeg) w:chunk("fact", fact:finish()) end local tags = o.tags or value.tags if type(tags) == "table" then local items = {} local keys = {} for k in tags do if type(k) == "string" then table.insert(keys, k) end end table.sort(keys) for _, k in keys do local v = tags[k] -- other RIFF INFO ids come back as their lower-cased id ("ixyz") and are written as such local id = TAG_IDS[k] or (if string.match(string.lower(k), "^i[%l%d][%l%d][%l%d]$") then string.upper(k) else nil) if id and type(v) == "string" and v ~= "" then table.insert(items, { id, v }) end end if #items > 0 then w:list("INFO", items) end end w:chunk("data", pieces) local _ = dataSize return w:finish({ parts = asParts }) end function Wav.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) return encodeParts(value, opts, false) end function Wav.encodeParts(value: any, opts: EncodeOptions?): ({ buffer }?, Err.Err?) return encodeParts(value, opts, true) end -- ------------------------------------------------------------------------------------------------ open function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?) if type(r) == "buffer" or type(r) == "string" then r = Bytes.reader(if type(r) == "string" then buffer.fromstring(r) else r :: any) end local f, ferr = Riff.read(r, { openEnded = { data = true } }) if not f then return nil, ferr end if f.form ~= "WAVE" then return nil, Err.new(Err.CORRUPT, "not a WAVE file (" .. f.form .. ")", f.base + 8) end local buf = f.buf local magic = f.container local be = f.bigEndian local fmt: any = nil local tags: Tags = {} local dataOff, dataSize = -1, 0 local truncated = false local ds64Frames: number? = if f.ds64 and f.ds64.sampleCount > 0 then f.ds64.sampleCount else nil local factFrames: number? = nil local function u16(o: number): number return Riff.u16(f, o) end local function u32(o: number): number return Riff.u32(f, o) end local function i16(o: number): number local v = u16(o) return if v >= 32768 then v - 65536 else v end for _, c in f.chunks do local id, size, body, avail = c.id, c.size, c.offset, c.avail if id == "fmt " and avail >= 14 then fmt = { tag = u16(body), channels = u16(body + 2), rate = u32(body + 4), byteRate = u32(body + 8), blockAlign = u16(body + 12), bits = if avail >= 16 then u16(body + 14) else 8, body = body, avail = avail, } elseif id == "fact" and avail >= 4 then factFrames = u32(body) elseif id == "LIST" and Riff.listType(f, c) == "INFO" then for _, sc in Riff.list(f, c) do local name = INFO_TAGS[sc.id] if sc.avail > 0 then local v = trimTag(buffer.readstring(buf, sc.offset, sc.avail)) if v ~= "" then tags[name or string.lower(sc.id)] = v end end end elseif id == "data" and dataOff < 0 then dataOff = body dataSize = avail truncated = c.truncated end local _ = size end if not fmt then return nil, Err.new(Err.CORRUPT, "no fmt chunk") end if dataOff < 0 then return nil, Err.new(Err.CORRUPT, "no data chunk") end local tag, ch, rate, bits = fmt.tag, fmt.channels, fmt.rate, fmt.bits local channelMask: number? = nil local validBits: number? = nil if tag == 0xFFFE then if fmt.avail < 40 then return nil, Err.new(Err.CORRUPT, "WAVE_FORMAT_EXTENSIBLE without its extension") end local valid = u16(fmt.body + 18) channelMask = u32(fmt.body + 20) tag = u16(fmt.body + 24) -- the GUID's first two bytes are the format tag -- valid bits < container bits: the samples are left-justified, so decoding the container is right validBits = valid end if ch < 1 or ch > 255 then return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch) end if rate < 1 or rate > 4000000 then return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) end local name: string? = FORMAT_NAMES[tag] if not name then return nil, Err.new(Err.UNSUPPORTED, string.format("format 0x%04X", tag)) end local dec = setmetatable({}, Decoder) :: any dec.sampleRate = rate dec.channels = ch dec.tags = tags dec.format = name dec.formatTag = tag dec.bitsPerSample = bits dec.container = magic dec.dataOffset = dataOff dec.dataSize = dataSize dec.channelMask = channelMask dec._buf = buf dec._pos = 0 dec._be = be dec._tmp = buffer.create(8) dec._cacheBlock = -1 dec._cacheFrames = 0 dec._ncoef = 0 local blockAlign: number = fmt.blockAlign local frames: number if name == "pcm" or name == "float" or name == "alaw" or name == "mulaw" then local bytes if name == "alaw" or name == "mulaw" then bytes = 1 elseif name == "float" then if bits ~= 32 and bits ~= 64 then return nil, Err.new(Err.UNSUPPORTED, "float size " .. bits) end bytes = bits // 8 else if bits < 1 or bits > 32 then return nil, Err.new(Err.UNSUPPORTED, "PCM size " .. bits) end -- container: from blockAlign when it is consistent, else from the bit depth bytes = (bits + 7) // 8 if blockAlign >= ch and blockAlign % ch == 0 and blockAlign // ch >= bytes and blockAlign // ch <= 4 then bytes = blockAlign // ch end end blockAlign = bytes * ch dec._bytes = bytes dec._kind = name frames = dataSize // blockAlign dec._spb = 1 elseif name == "ima_adpcm" or name == "ms_adpcm" then if blockAlign < 1 then return nil, Err.new(Err.CORRUPT, "ADPCM with blockAlign 0") end local spb = if fmt.avail >= 20 then u16(fmt.body + 18) else 0 if name == "ima_adpcm" then if bits ~= 4 then return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM size " .. bits) end if blockAlign < 4 * ch then return nil, Err.new(Err.CORRUPT, "IMA ADPCM block too small") end local computed = (blockAlign - 4 * ch) * 2 // ch + 1 if spb < 1 or spb > computed then spb = computed end else if blockAlign < 7 * ch then return nil, Err.new(Err.CORRUPT, "MS ADPCM block too small") end local computed = (blockAlign - 7 * ch) * 2 // ch + 2 if spb < 2 or spb > computed then spb = computed end -- coefficients from the fmt extension, else the 7 standard pairs local c1, c2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 local ncoef = 7 if fmt.avail >= 22 then local k = u16(fmt.body + 20) if k >= 1 and k <= 256 and fmt.avail >= 22 + 4 * k then ncoef = k c1, c2 = {}, {} for i = 1, k do c1[i] = i16(fmt.body + 22 + (i - 1) * 4) c2[i] = i16(fmt.body + 24 + (i - 1) * 4) end end end local coefs = buffer.create(ncoef * 8) for i = 1, ncoef do buffer.writei32(coefs, (i - 1) * 8, c1[i]) buffer.writei32(coefs, (i - 1) * 8 + 4, c2[i]) end dec._coefs = coefs dec._ncoef = ncoef dec._state = buffer.create(20 * ch) end if spb * ch > 2 ^ 20 then return nil, Err.new(Err.LIMIT, "ADPCM block too large") end dec._kind = name dec._spb = spb dec._cache = buffer.create(spb * ch * 4) local full = dataSize // blockAlign frames = full * spb local rest = dataSize - full * blockAlign if rest > 0 then -- a partial last block: the frames it holds whole if name == "ima_adpcm" then if rest >= 4 * ch then frames += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8) end elseif rest >= 7 * ch then frames += math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) end end -- fact: the true length (the last block is padded) if factFrames and factFrames > 0 and factFrames < frames then frames = factFrames end else return nil, Err.new(Err.UNSUPPORTED, "format " .. name) end if ds64Frames and ds64Frames > 0 and ds64Frames < frames then frames = ds64Frames end dec.blockAlign = blockAlign dec.frames = frames dec.duration = frames / rate dec.truncated = truncated dec.validBits = validBits dec.bitrate = if fmt.byteRate > 0 then fmt.byteRate * 8 else math.floor(rate * blockAlign * 8 / dec._spb) return dec, nil end -- ------------------------------------------------------------------------------------------------ extras function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, number) local ch = self.channels local req = math.floor(tonumber(maxFrames) or 0) if req ~= req then -- NaN (math.min / max treat it differently on LuaJIT) req = 0 end local want = math.max(0, math.min(req, self.frames - self._pos)) local dst: buffer = if out and type(out) == "buffer" and buffer.len(out) >= want * ch * 4 then out else buffer.create(want * ch * 4) if want == 0 then return dst, 0 end local kind = self._kind if self._spb == 1 then local off = self.dataOffset + self._pos * self.blockAlign local count = want * ch if kind == "pcm" then Codecs.int(self._buf, off, dst, 0, count, self._bytes, self._be) elseif kind == "float" then Codecs.float(self._buf, off, dst, 0, count, self._bytes, self._be, self._tmp) elseif kind == "alaw" then Codecs.law(self._buf, off, dst, 0, count, ALAW) else Codecs.law(self._buf, off, dst, 0, count, MULAW) end self._pos += want return dst, want end local spb, ba = self._spb, self.blockAlign local cache = self._cache :: buffer local done = 0 while done < want do local block = self._pos // spb if block ~= self._cacheBlock then local off = self.dataOffset + block * ba local avail = math.min(ba, self.dataOffset + self.dataSize - off) local got if kind == "ima_adpcm" then got = Adpcm.imaWav(self._buf, off, avail, ch, spb, cache, 0) else got = Adpcm.msBlock(self._buf, off, avail, ch, spb, cache, 0, self._coefs :: buffer, self._ncoef, self._state :: buffer) end self._cacheBlock = block self._cacheFrames = got end local inBlock = self._pos - block * spb local k = math.min(want - done, self._cacheFrames - inBlock) if k <= 0 then break end Codecs.copy(cache, inBlock * ch, dst, done * ch, k * ch) done += k self._pos += k end return dst, done end function Decoder.seek(self: Decoder, seconds: number) local f = math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5) if f ~= f then f = 0 end self._pos = math.clamp(f, 0, self.frames) end function Decoder.seekFrame(self: Decoder, frame: number) local f = math.floor(tonumber(frame) or 0) if f ~= f then f = 0 end self._pos = math.clamp(f, 0, self.frames) end function Decoder.position(self: Decoder): number return self._pos / self.sampleRate end function Decoder.tell(self: Decoder): number return self._pos end return Wav end __FILES["audio/wav/Codecs"] = @native function() -- audio/wav/Codecs: PCM / float / G.711 sample loops into interleaved f32 and back; absorbed from wav-luau fd9a909. local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 local readf32, readf64, writef32, writeu32 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writeu32 local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writei16, buffer.writei32 local Codecs = {} -- integer PCM: 1 byte = unsigned, 2 / 3 / 4 bytes = signed @native function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean) local o = d * 4 if bytes == 1 then for i = 0, count - 1 do writef32(dst, o + i * 4, (readu8(src, off + i) - 128) / 128) end elseif bytes == 2 then if be then for i = 0, count - 1 do local s = off + i * 2 local v = readi8(src, s) * 256 + readu8(src, s + 1) writef32(dst, o + i * 4, v / 32768) end else for i = 0, count - 1 do writef32(dst, o + i * 4, readi16(src, off + i * 2) / 32768) end end elseif bytes == 3 then if be then for i = 0, count - 1 do local s = off + i * 3 local v = readi8(src, s) * 65536 + readu8(src, s + 1) * 256 + readu8(src, s + 2) writef32(dst, o + i * 4, v / 8388608) end else for i = 0, count - 1 do local s = off + i * 3 local v = readi8(src, s + 2) * 65536 + readu16(src, s) writef32(dst, o + i * 4, v / 8388608) end end else if be then for i = 0, count - 1 do local v = byteswap(readu32(src, off + i * 4)) if v >= 0x80000000 then v -= 0x100000000 end writef32(dst, o + i * 4, v / 2147483648) end else for i = 0, count - 1 do writef32(dst, o + i * 4, readi32(src, off + i * 4) / 2147483648) end end end end @native function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean, tmp: buffer) local o = d * 4 if bytes == 4 then if be then for i = 0, count - 1 do writeu32(tmp, 0, byteswap(readu32(src, off + i * 4))) writef32(dst, o + i * 4, readf32(tmp, 0)) end else for i = 0, count - 1 do writef32(dst, o + i * 4, readf32(src, off + i * 4)) end end else if be then for i = 0, count - 1 do local s = off + i * 8 writeu32(tmp, 0, byteswap(readu32(src, s + 4))) writeu32(tmp, 4, byteswap(readu32(src, s))) writef32(dst, o + i * 4, readf64(tmp, 0)) end else for i = 0, count - 1 do writef32(dst, o + i * 4, readf64(src, off + i * 8)) end end end end @native function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: number, tbl: buffer) local o = d * 4 for i = 0, count - 1 do writef32(dst, o + i * 4, readf32(tbl, readu8(src, off + i) * 4)) end end @native function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number) buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4) end @native function Codecs.quantize(src: buffer, s: number, dst: buffer, off: number, count: number, kind: string) local so = s * 4 if kind == "f32" then buffer.copy(dst, off, src, so, count * 4) elseif kind == "s16" then for i = 0, count - 1 do local v = math.floor(readf32(src, so + i * 4) * 32768 + 0.5) if v > 32767 then v = 32767 elseif v < -32768 then v = -32768 elseif v ~= v then v = 0 end writei16(dst, off + i * 2, v) end elseif kind == "s24" then for i = 0, count - 1 do local v = math.floor(readf32(src, so + i * 4) * 8388608 + 0.5) if v > 8388607 then v = 8388607 elseif v < -8388608 then v = -8388608 elseif v ~= v then v = 0 end if v < 0 then v += 16777216 end local o = off + i * 3 writeu16(dst, o, v % 65536) writeu8(dst, o + 2, v // 65536) end elseif kind == "s32" then for i = 0, count - 1 do local v = math.floor(readf32(src, so + i * 4) * 2147483648 + 0.5) if v > 2147483647 then v = 2147483647 elseif v < -2147483648 then v = -2147483648 elseif v ~= v then v = 0 end writei32(dst, off + i * 4, v) end else -- u8 for i = 0, count - 1 do local v = math.floor(readf32(src, so + i * 4) * 128 + 0.5) if v > 127 then v = 127 elseif v < -128 then v = -128 elseif v ~= v then v = 0 end writeu8(dst, off + i, v + 128) end end end return Codecs end __FILES["audio/wavpack"] = function() -- audio/wavpack: WavPack (.wv) via codecs/audio/WavPack, from the WavPack 5 file format document and WavPack 5.9.0's -- open_utils.c (BSD 3-clause, licenses/wavpack-LICENSE.txt). Supports: lossless and hybrid (lossy without the .wvc, as -- wvunpack), 8-32-bit integer and float, 1-4096 channels, seeking, APEv2. Not supported: DSD, WavPack 1-3, encoding. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Pcm = __include("codecs/audio/Pcm") local Stream = __include("codecs/audio/Stream") local ApeTag = __include("codecs/audio/ApeTag") local WavPackCodec = __include("codecs/audio/WavPack") -- ------------------------------------------------------------------------------------------------ contract local WavPack = { name = "wavpack", category = "audio", extensions = { "wv" }, mime = { "audio/x-wavpack", "audio/wavpack" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" }, caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } }, } -- ------------------------------------------------------------------------------------------------ types type OpenOptions = { correction: (buffer | string)?, -- the .wvc file of a hybrid file (default: opts.resolve(name .. "c") when given) resolve: ((uri: string) -> buffer?)?, name: string?, maxFrames: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff function WavPack.sniff(r: Bytes.Reader): number if r:peek(4) ~= "wvpk" then return 0 end local v = r:peekU8(9) return if v == 4 then 1 else 0.5 end -- ------------------------------------------------------------------------------------------------ decode function WavPack.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) local dec, err = WavPack.open(r, opts) if not dec then return nil, err end local d = dec :: any local limit = opts and opts.maxFrames or 2 ^ 28 if d.frames > limit or d.frames * d.channels > 2 ^ 28 then return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames)) end return Pcm.drain(d, d.source, limit) end -- ------------------------------------------------------------------------------------------------ open type Index = { offsets: { { number } }, starts: { number }, samples: { number }, total: number, first: number, md5: string? } local function index(buf: buffer, base: number, limit: number): (Index?, string?) local at = base local idx: Index = { offsets = {}, starts = {}, samples = {}, total = -1, first = -1 } local cur: { number }? = nil local initial = -1 local resyncs = 0 while at + 32 <= limit do local h = WavPackCodec.header(buf, at, limit) if not h then -- garbage (or a tag) between blocks: search the next header if resyncs > 64 then break end local s = buffer.readstring(buf, at + 1, math.min(limit - at - 1, 1048576)) local k = string.find(s, "wvpk", 1, true) if not k then break end at = at + k resyncs += 1 continue end if initial < 0 then initial = h.index idx.total = h.total end if h.samples > 0 then if bit32.band(h.flags, WavPackCodec.INITIAL) ~= 0 or not cur then cur = { at } table.insert(idx.offsets, cur) table.insert(idx.starts, h.index - initial) table.insert(idx.samples, h.samples) if idx.first < 0 then idx.first = at end else table.insert(cur, at) end if bit32.band(h.flags, WavPackCodec.FINAL) ~= 0 then cur = nil end else idx.md5 = idx.md5 or WavPackCodec.md5(buf, at, limit) end at += h.size end if idx.first < 0 then return nil, "no audio blocks" end return idx, nil end local function correctionFile(opts: OpenOptions?): buffer? if not opts then return nil end local c = opts.correction if type(c) == "string" then return buffer.fromstring(c) elseif type(c) == "buffer" then return c end if type(opts.resolve) == "function" and type(opts.name) == "string" then local base = string.match(opts.name, "([^/\\]+)$") if base then local ok, b = pcall(opts.resolve, base .. "c") if ok and type(b) == "buffer" then return b end end end return nil end function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) if type(r) == "buffer" then r = Bytes.reader(r :: any) end if type(r) ~= "table" or type(r.buf) ~= "buffer" then return nil, Err.new(Err.ARG, "open: expected a Reader") end local buf, base, limit = r.buf, r.base, r.limit local tags, tagInfo = ApeTag.find(buf, base, limit) local stop = if tagInfo then tagInfo.start else limit local idx, ierr = index(buf, base, stop) if not idx then return nil, Err.from(ierr, base) end local info, err = WavPackCodec.info(buf, idx.first, stop) if not info then return nil, err end if info.channels > 256 then return nil, Err.new(Err.LIMIT, info.channels .. " channels") end local count = #idx.offsets local last = idx.starts[count] + idx.samples[count] local frames = if idx.total >= 0 then math.min(idx.total, last) else last local cbuf = if info.hybrid then correctionFile(opts) else nil local cfor: { [number]: { number } } = {} if cbuf then local cidx = index(cbuf, 0, buffer.len(cbuf)) if cidx then for i, offs in cidx.offsets do cfor[cidx.starts[i]] = offs end else cbuf = nil end end local codec = WavPackCodec.decoder(info.channels) local dec: any = { sampleRate = info.sampleRate, channels = info.channels, frames = frames, duration = frames / info.sampleRate, bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, tags = tags or {}, bitsPerSample = info.bitsPerSample, float = info.float, hybrid = info.hybrid, lossless = not info.hybrid or cbuf ~= nil, channelMask = info.channelMask, md5 = idx.md5, source = { format = "wavpack", bitDepth = info.bitsPerSample, float = info.float, hybrid = info.hybrid, correction = cbuf ~= nil, version = info.version, tags = tagInfo and tagInfo.items }, } local starts, offsets = idx.starts, idx.offsets return Stream.packets(dec, { count = count, start = function(i: number): number return if i > count then last else starts[i] end, decode = function(i: number): (number?, Err.Err?) local co = if cbuf then cfor[starts[i]] else nil return codec:frame(buf, offsets[i], if co then cbuf else nil, co) end, pcm = function(): { number } return codec.pcm end, reset = function() end, stop = frames, scale = if info.float then 1 else 1 / 2 ^ (info.bytesPerSample * 8 - 1), ints = not info.float, }) end return WavPack end __FILES["cad/step"] = function() -- cad/step: STEP physical files (ISO 10303-21 eds 1-3; AP203 / AP214 / AP242 / any schema). Supports: header, DATA -- sections, simple and complex instances, every parameter kind, ANCHOR / REFERENCE / SIGNATURE kept raw; B-rep via the -- injected plug-in (cad/step/Brep). Not supported: STEP-XML (10303-28), .stpZ, ed. 3 value instances, \P?\ code pages. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Sniff = __include("core/Sniff") local Bytes = __include("core/Bytes") local Types = __include("Types") local Parse = __include("cad/step/Parse") local Write = __include("cad/step/Write") local Brep = __include("cad/step/Brep") -- ------------------------------------------------------------------------------------------------ contract local Step = { name = "step", category = "cad", extensions = { "step", "stp", "p21" }, mime = { "model/step", "application/step", "application/p21" }, deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { maxBytes: number?, -- default 2^30 maxEntities: number?, -- default 2^24 } type EncodeOptions = { schema: string?, -- overrides the header's FILE_SCHEMA name: string?, -- default: the header's, else "model" timestamp: string?, -- default "1970-01-01T00:00:00" crlf: boolean?, } type BrepOptions = { brep: any?, plugins: { [string]: any }?, chord: number?, -- millimetres (default 0.05) tess: { [string]: any }?, } -- ------------------------------------------------------------------------------------------------ constants Step.NULL = table.freeze({ null = true }) -- $ Step.DERIVED = table.freeze({ derived = true }) -- * local SCHEMAS = { AP203 = "CONFIG_CONTROL_DESIGN", AP214 = "AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }", AP242 = "AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }", } Step.SCHEMAS = SCHEMAS local function schemaOf(name: string): string local n = string.upper(string.match(name, "^%s*([^%s{]+)") or name) if n == "CONFIG_CONTROL_DESIGN" or string.find(n, "^AP203") then return "AP203" elseif n == "AUTOMOTIVE_DESIGN" or n == "AUTOMOTIVE_DESIGN_CC2" or string.find(n, "^AP214") then return "AP214" elseif string.find(n, "^AP242") then return "AP242" end return n end Step.schemaOf = schemaOf -- ------------------------------------------------------------------------------------------------ sniff function Step.sniff(r: Bytes.Reader): number local head = Sniff.text(r, 256) head = string.gsub(head, "^%s*/%*.-%*/", "") if string.find(head, "^%s*ISO%-10303%-21%s*;") then return 1 end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Step.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Cad?, Err.Err?) local size = r.limit - r.base if size > (opts and opts.maxBytes or 2 ^ 30) then return nil, Err.new(Err.LIMIT, "file over maxBytes") end local s = buffer.readstring(r.buf, r.base, size) local bom = 0 if string.sub(s, 1, 3) == "\239\187\191" then s = string.sub(s, 4) bom = 3 end local res, msg, at = Parse.parse(s, Step.NULL, Step.DERIVED, opts and opts.maxEntities or 2 ^ 24) if not res then local off = if at then r.base + bom + at - 1 else nil if msg == "LIMIT" then return nil, Err.new(Err.LIMIT, "more entity instances than maxEntities", off) end local m = msg or "parse error" if string.find(m, "^truncated") or string.find(m, "^unterminated") or (at and at > #s) then return nil, Err.new(Err.TRUNCATED, m, off) end return nil, Err.new(Err.CORRUPT, m, off) end local fs = res.header.FILE_SCHEMA local schemaName = if fs and type(fs[1]) == "table" and type(fs[1][1]) == "string" then fs[1][1] else "" local cad: Types.Cad = { kind = "cad", schema = if schemaName ~= "" then schemaOf(schemaName) else "unknown", header = res.header, entities = res.entities, meta = { count = res.count, headerOrder = res.headerOrder, source = { format = "step", schemaName = schemaName, sections = res.sections, extra = if #res.extra > 0 then res.extra else nil, duplicates = if res.duplicates > 0 then res.duplicates else nil, terminated = res.terminated, }, }, } return cad, nil end -- ------------------------------------------------------------------------------------------------ encode local function headerArgs(cad: Types.Cad, o: EncodeOptions): { [string]: { any } } local h = if type(cad.header) == "table" then cad.header else {} local out: { [string]: { any } } = {} for k, v in h do out[k] = v end if type(out.FILE_DESCRIPTION) ~= "table" then out.FILE_DESCRIPTION = { { "rosetta" }, "2;1" } end if type(out.FILE_NAME) ~= "table" then out.FILE_NAME = { o.name or "model", o.timestamp or "1970-01-01T00:00:00", { "" }, { "" }, "rosetta", "rosetta", "" } end local schema = o.schema or (if type(out.FILE_SCHEMA) ~= "table" then cad.schema else nil) if schema then out.FILE_SCHEMA = { { SCHEMAS[schema] or schema } } end return out end function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?) if type(cad) ~= "table" or cad.kind ~= "cad" or type(cad.entities) ~= "table" then return nil, Err.new(Err.ARG, "needs a Cad (kind = \"cad\", entities)") end local o: EncodeOptions = opts or {} local nl = if o.crlf then "\r\n" else "\n" local ctx: Write.Ctx = { out = {}, null = Step.NULL, derived = Step.DERIVED, err = nil } local out = ctx.out table.insert(out, "ISO-10303-21;" .. nl .. "HEADER;" .. nl) local header = headerArgs(cad, o) local order = { "FILE_DESCRIPTION", "FILE_NAME", "FILE_SCHEMA" } local seen = { FILE_DESCRIPTION = true, FILE_NAME = true, FILE_SCHEMA = true } local meta: any = if type(cad.meta) == "table" then cad.meta else {} local rest = {} for _, k in (if type(meta.headerOrder) == "table" then meta.headerOrder else {}) do if type(k) == "string" and header[k] and not seen[k] then seen[k] = true table.insert(order, k) end end for k in header do if type(k) == "string" and not seen[k] then table.insert(rest, k) end end table.sort(rest) for _, k in rest do table.insert(order, k) end for _, k in order do if not Write.record(ctx, k, header[k]) then return nil, Err.new(Err.ARG, "header " .. tostring(k) .. ": " .. tostring(ctx.err)) end table.insert(out, ";" .. nl) end table.insert(out, "ENDSEC;" .. nl) local source = if type(meta.source) == "table" then meta.source else {} if type(source.extra) == "table" then for _, x in source.extra do if type(x) == "table" and type(x.name) == "string" and type(x.text) == "string" then table.insert(out, x.name .. x.text .. "ENDSEC;" .. nl) end end end local ids = {} for id, e in cad.entities do if type(id) ~= "number" or id ~= math.floor(id) or id < 0 or type(e) ~= "table" then return nil, Err.new(Err.ARG, "entity ids must be non-negative integers (" .. tostring(id) .. ")") end table.insert(ids, id) end table.sort(ids) local sections = if type(source.sections) == "table" and #source.sections > 1 then source.sections else { {} } for si, sec in sections do if #sections > 1 then table.insert(out, "DATA") local params = {} if sec.name ~= nil then params[1] = sec.name params[2] = if sec.schema ~= nil then sec.schema else {} if not Write.list(ctx, params, 0) then return nil, Err.new(Err.ARG, "section " .. si .. ": " .. tostring(ctx.err)) end end table.insert(out, ";" .. nl) else table.insert(out, "DATA;" .. nl) end for _, id in ids do local e: any = cad.entities[id] local esec = if type(e.section) == "number" then e.section else 1 if #sections == 1 or esec == si or (si == 1 and (esec < 1 or esec > #sections)) then table.insert(out, string.format("#%.0f=", id)) if e.type == "COMPLEX" or type(e.parts) == "table" then if type(e.parts) ~= "table" or #e.parts == 0 then return nil, Err.new(Err.ARG, "#" .. id .. ": a complex instance without parts") end table.insert(out, "(") for _, p in e.parts do if type(p) ~= "table" or not Write.record(ctx, p.type, p.args) then return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err or "bad part")) end end table.insert(out, ")") elseif not Write.record(ctx, e.type, e.args) then return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err)) end table.insert(out, ";" .. nl) end end table.insert(out, "ENDSEC;" .. nl) end table.insert(out, "END-ISO-10303-21;" .. nl) return buffer.fromstring(table.concat(out)), nil end -- ------------------------------------------------------------------------------------------------ extras function Step.get(cad: Types.Cad, id: any): Types.StepEntity? if type(id) == "table" then id = id.ref end return cad.entities[id] end function Step.ids(cad: Types.Cad): { number } local out = {} for id in cad.entities do table.insert(out, id) end table.sort(out) return out end function Step.byType(cad: Types.Cad, name: string): { number } local n = string.upper(name) local out = {} for id, e in cad.entities do if e.type == n then table.insert(out, id) elseif e.parts then for _, p in e.parts do if p.type == n then table.insert(out, id) break end end end end table.sort(out) return out end function Step.part(e: Types.StepEntity?, name: string): { any }? if not e then return nil end if e.type == name then return e.args end if e.parts then for _, p in e.parts do if p.type == name then return p.args end end end return nil end function Step.add(cad: Types.Cad, type: string, args: { any }): number local top = 0 for id in cad.entities do if id > top then top = id end end local id = top + 1 cad.entities[id] = { id = id, type = string.upper(type), args = args } cad.meta.count = (cad.meta.count or 0) + 1 return id end function Step.real(t: { [any]: any }, key: any): { [any]: any } local mt: any = getmetatable(t) if not mt then mt = { __reals = {} } setmetatable(t, mt) end mt.__reals[key] = true return t end function Step.new(schema: string?): Types.Cad return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } } end Step.plugin = Brep.plugin local function textOf(cad: Types.Cad): (string?, Err.Err?) local buf, err = Step.encode(cad) if not buf then return nil, err end return buffer.tostring(buf), nil end function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any) local plug, perr = Brep.find(opts) if not plug then return nil, perr end local text, err = textOf(cad) if not text then return nil, err end local bodies, res, rerr = Brep.read(plug, text, opts) if not bodies then return nil, rerr end return bodies, res end function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err.Err?) if type(bodies) ~= "table" then return nil, Err.new(Err.ARG, "needs a list of bodies") end local plug, perr = Brep.find(opts) if not plug then return nil, perr end local text, err = Brep.write(plug, bodies, opts) if not text then return nil, err end return Step.decode(Bytes.reader(buffer.fromstring(text))) end function Step.tessellate(value: any, opts: BrepOptions?): (Types.Scene?, Err.Err?) local plug, perr = Brep.find(opts) if not plug then return nil, perr end local bodies = value if type(value) == "table" and value.kind == "cad" then local b, err = Step.toBodies(value, opts) if not b then return nil, err end bodies = b end if type(bodies) ~= "table" then return nil, Err.new(Err.ARG, "needs a Cad or a list of bodies") end return Brep.scene(plug, bodies, opts) end return Step end __FILES["cad/step/Brep"] = function() -- cad/step/Brep: the injected B-rep plug-in (Rosetta.plugins.brep; never required by rosetta), called under pcall. -- Interface (each may throw): read(text, opts) -> { bodies, stats? }; write(bodies, opts) -> text; -- tessellate(body, opts) -> { positions, normals?, indices (1-based triples), faceOf? }; or brep-luau's modules as-is. local Err = __include("core/Err") local Types = __include("Types") local Brep = {} type Plugin = { read: (text: string, opts: any) -> any, write: ((bodies: { any }, opts: any) -> string)?, tessellate: ((body: any, opts: any) -> any)?, } local function rgbOf(c: any): (number?, number?, number?) if c == nil then return nil, nil, nil end local ok, r, g, b = pcall(function(): (any, any, any) if type(c) == "table" then return c.r or c.R or c[1], c.g or c.G or c[2], c.b or c.B or c[3] end return (c :: any).R, (c :: any).G, (c :: any).B end) if ok and type(r) == "number" and type(g) == "number" and type(b) == "number" then return r, g, b end return nil, nil, nil end function Brep.plugin(p: any): (Plugin?, string?) if type(p) ~= "table" then return nil, "needs the B-rep plug-in (Rosetta.plugins.brep = { read, write, tessellate }, e.g. brep-luau's { Step, StepBrep, StepWrite, Tess })" end if type(p.read) == "function" then return { read = p.read, write = if type(p.write) == "function" then p.write else nil, tessellate = if type(p.tessellate) == "function" then p.tessellate else nil, }, nil end local S, SB, SW, Tess = p.Step, p.StepBrep, p.StepWrite, p.Tess if type(S) == "table" and type(SB) == "table" and type(S.parse) == "function" and type(SB.read) == "function" then return { read = function(text: string, opts: any): any return SB.read(S.parse(text), opts) end, write = if type(SW) == "table" and type(SW.write) == "function" then function(bodies: { any }, opts: any): string local o = if type(opts) == "table" then table.clone(opts) else {} if o.colors == nil then local colors = {} for i, b in bodies do local r, g, bl = rgbOf(type(b) == "table" and b.color or nil) if r then colors[i] = { r, g, bl } end end o.colors = colors end return SW.write(bodies, o) end else nil, tessellate = if type(Tess) == "table" and type(Tess.body) == "function" then function(body: any, opts: any): any return Tess.body(body, opts) end else nil, }, nil end return nil, "the B-rep plug-in has neither read() nor brep-luau's Step + StepBrep modules" end function Brep.find(opts: any): (Plugin?, Err.Err?) local p = nil if type(opts) == "table" then p = opts.brep if p == nil and type(opts.plugins) == "table" then p = opts.plugins.brep end end local plug, why = Brep.plugin(p) if not plug then return nil, Err.new(Err.UNSUPPORTED, why :: string) end return plug, nil end function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err.Err?) local ok, res = pcall(plug.read, text, opts) if not ok then return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to read: " .. tostring(res)) end if type(res) ~= "table" or type(res.bodies) ~= "table" then return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in's read returned no bodies") end return res.bodies, res, nil end function Brep.write(plug: Plugin, bodies: { any }, opts: any): (string?, Err.Err?) local w = plug.write if not w then return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no write()") end local ok, res = pcall(w, bodies, opts) if not ok then return nil, Err.new(Err.ARG, "the B-rep plug-in failed to write: " .. tostring(res)) end if type(res) ~= "string" then return nil, Err.new(Err.ARG, "the B-rep plug-in's write returned no text") end return res, nil end local function xyz(p: any): (number, number, number) if type(p) == "table" then return tonumber(p.x or p.X or p[1]) or 0, tonumber(p.y or p.Y or p[2]) or 0, tonumber(p.z or p.Z or p[3]) or 0 end return (p :: any).X, (p :: any).Y, (p :: any).Z end local function linear(c: number): number c = math.clamp(c, 0, 1) return if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4 end -- baseColor = the STEP colour converted from sRGB to linear; extras.color = the colour as written function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Err.Err?) local tess = plug.tessellate if not tess then return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no tessellate()") end local scene = Types.Scene.new() scene.meta.up = "z" scene.meta.unit = 0.001 local tessOpts = if type(opts) == "table" and type(opts.tess) == "table" then opts.tess else { chord = if type(opts) == "table" and type(opts.chord) == "number" then opts.chord else 0.05 } local matByKey: { [string]: number } = {} local function material(r: number?, g: number?, b: number?): number local key = if r then string.format("%.6f,%.6f,%.6f", r, g :: number, b :: number) else "default" local m = matByKey[key] if m then return m end local mat = Types.Scene.material(if r then "step_" .. #scene.materials + 1 else "default") if r then mat.baseColor = { linear(r), linear(g :: number), linear(b :: number), 1 } mat.extras = { color = { r, g, b } } else mat.baseColor = { 0.6, 0.6, 0.6, 1 } end mat.metallic, mat.roughness = 0, 0.5 table.insert(scene.materials, mat) matByKey[key] = #scene.materials return #scene.materials end for bi, body in bodies do local ok, mesh = pcall(tess, body, tessOpts) if not ok then return nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to tessellate body " .. bi .. ": " .. tostring(mesh)) end if type(mesh) ~= "table" or type(mesh.positions) ~= "table" or type(mesh.indices) ~= "table" then return nil, Err.new(Err.CORRUPT, "the B-rep plug-in's tessellate returned no mesh") end local cok, prims = pcall(function(): { Types.Primitive } local P, N, I = mesh.positions, mesh.normals, mesh.indices local nv = #P local pos = Types.Scene.accessor(nil, "f32", 3, nv) local nrm = if type(N) == "table" and #N == nv then Types.Scene.accessor(nil, "f32", 3, nv) else nil for i = 1, nv do local x, y, z = xyz(P[i]) buffer.writef32(pos.data, (i - 1) * 12, x) buffer.writef32(pos.data, (i - 1) * 12 + 4, y) buffer.writef32(pos.data, (i - 1) * 12 + 8, z) if nrm then local a, b, c = xyz(N[i]) buffer.writef32(nrm.data, (i - 1) * 12, a) buffer.writef32(nrm.data, (i - 1) * 12 + 4, b) buffer.writef32(nrm.data, (i - 1) * 12 + 8, c) end end local br, bg, bb = rgbOf(type(body) == "table" and body.color or nil) local groups: { { mat: number, tris: { number } } } = {} local byMat: { [number]: { mat: number, tris: { number } } } = {} local faceOf = if type(mesh.faceOf) == "table" then mesh.faceOf else {} local nt = #I // 3 for t = 1, nt do local f = faceOf[t] local r, g, b = rgbOf(type(f) == "table" and f.color or nil) if not r then r, g, b = br, bg, bb end local m = material(r, g, b) local grp = byMat[m] if not grp then grp = { mat = m, tris = {} } byMat[m] = grp table.insert(groups, grp) end table.insert(grp.tris, t) end local out: { Types.Primitive } = {} for _, grp in groups do local idx = Types.Scene.accessor(nil, "u32", 1, #grp.tris * 3) for k, t in grp.tris do for c = 0, 2 do local v = (tonumber(I[(t - 1) * 3 + c + 1]) or 1) - 1 buffer.writeu32(idx.data, ((k - 1) * 3 + c) * 4, math.clamp(v, 0, math.max(nv - 1, 0))) end end local attrs: { [string]: Types.Accessor } = { POSITION = pos } if nrm then attrs.NORMAL = nrm end table.insert(out, { attributes = attrs, indices = idx, mode = "triangles" :: any, material = grp.mat }) end return out end) if not cok then return nil, Err.new(Err.CORRUPT, "bad tessellation of body " .. bi .. ": " .. tostring(prims)) end local name = if type(body) == "table" and type(body.name) == "string" then body.name else "body_" .. bi table.insert(scene.meshes, { name = name, primitives = prims }) table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes }) table.insert(scene.roots, #scene.nodes) end scene.meta.source = { format = "step", tessellated = true, bodies = #bodies } return scene, nil end return Brep end __FILES["cad/step/Parse"] = @native function() -- cad/step/Parse: ISO 10303-21 text -> header + entity instances, one pass; never throws (nil, message, offset). -- An integral real (`0.`, `1.E2`) is marked in its holder's metatable (`__reals = { [index | "value"] = true }`). local Parse = {} local sbyte, ssub, sfind, schar, floor = string.byte, string.sub, string.find, string.char, math.floor local MAX_DEPTH = 100 type Ctx = { s: string, n: number, err: string?, errAt: number?, null: any, derived: any, } @native local function fail(ctx: Ctx, msg: string, at: number): nil if not ctx.err then ctx.err, ctx.errAt = msg, at end return nil end @native local function skip(ctx: Ctx, i: number): number local s, n = ctx.s, ctx.n while i <= n do local c = sbyte(s, i) if c == 32 or c == 10 or c == 13 or c == 9 or c == 12 then i += 1 elseif c == 47 and sbyte(s, i + 1) == 42 then local _, e = sfind(s, "*/", i + 2, true) if not e then fail(ctx, "unterminated comment", i) return n + 1 end i = e + 1 else return i end end return i end @native local function isAlpha(c: number): boolean return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 end @native local function isWord(c: number): boolean return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57) end @native local function keyword(ctx: Ctx, i: number): (string?, number) local s, n = ctx.s, ctx.n local j = i if j <= n and sbyte(s, j) == 33 then -- '!' user-defined j += 1 end if j > n or not isAlpha(sbyte(s, j) :: number) then return nil, i end j += 1 while j <= n and isWord(sbyte(s, j) :: number) do j += 1 end return string.upper(ssub(s, i, j - 1)), j end @native local function utf8char(cp: number): string if cp < 0x80 then return schar(cp) elseif cp < 0x800 then return schar(0xC0 + floor(cp / 64), 0x80 + cp % 64) elseif cp < 0x10000 then return schar(0xE0 + floor(cp / 4096), 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64) elseif cp < 0x110000 then return schar(0xF0 + floor(cp / 262144), 0x80 + floor(cp / 4096) % 64, 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64) end return "\239\191\189" end Parse.utf8char = utf8char @native local function hexAt(s: string, i: number, k: number): number? local h = ssub(s, i, i + k - 1) if #h ~= k or sfind(h, "[^%x]") then return nil end return tonumber(h, 16) end -- Part 21 escapes: '' \\ \S\c \X\hh \X2\..\X0\ \X4\..\X0\; \P?\ ignored (ISO 8859-1); raw bytes >= 0x80 pass through @native function Parse.unescape(raw: string): string if not sfind(raw, "[\\']") then return raw end local out = {} local i, n = 1, #raw local plain = 1 while i <= n do local c = sbyte(raw, i) if c == 39 then -- '' -> ' table.insert(out, ssub(raw, plain, i)) i += 2 plain = i elseif c == 92 then table.insert(out, ssub(raw, plain, i - 1)) local d = sbyte(raw, i + 1) if d == 92 then table.insert(out, "\\") i += 2 elseif d == 83 and sbyte(raw, i + 2) == 92 and i + 3 <= n then -- \S\c table.insert(out, utf8char(((sbyte(raw, i + 3) :: number) + 128) % 256)) i += 4 elseif d == 80 and sbyte(raw, i + 3) == 92 then -- \P?\ code page i += 4 elseif d == 88 and sbyte(raw, i + 2) == 92 then -- \X\hh local h = hexAt(raw, i + 3, 2) if h then table.insert(out, utf8char(h)) i += 5 else table.insert(out, "\\") i += 1 end elseif d == 88 and (sbyte(raw, i + 2) == 50 or sbyte(raw, i + 2) == 52) and sbyte(raw, i + 3) == 92 then local k = if sbyte(raw, i + 2) == 50 then 4 else 8 local j = i + 4 local hi: number? = nil while j <= n do if sbyte(raw, j) == 92 then break end local cp = hexAt(raw, j, k) if not cp then break end if k == 4 and cp >= 0xD800 and cp < 0xDC00 then hi = cp elseif k == 4 and hi and cp >= 0xDC00 and cp < 0xE000 then table.insert(out, utf8char(0x10000 + (hi - 0xD800) * 1024 + (cp - 0xDC00))) hi = nil else table.insert(out, utf8char(cp)) hi = nil end j += k end if ssub(raw, j, j + 3) == "\\X0\\" then j += 4 end i = j else table.insert(out, "\\") i += 1 end plain = i else i += 1 end end table.insert(out, ssub(raw, plain, n)) return table.concat(out) end @native local function markReal(t: { [any]: any }, key: any) local mt: any = getmetatable(t) if not mt then mt = { __reals = {} } setmetatable(t, mt) end mt.__reals[key] = true end local value: (ctx: Ctx, i: number, depth: number) -> (any, number, boolean) @native local function list(ctx: Ctx, i: number, depth: number): ({ any }?, number) local s = ctx.s local out = {} i = skip(ctx, i) if sbyte(s, i) == 41 then return out, i + 1 end local k = 0 while true do local v, j, intReal = value(ctx, i, depth + 1) if v == nil then return nil, j end k += 1 out[k] = v if intReal then markReal(out, k) end j = skip(ctx, j) local c = sbyte(s, j) if c == 44 then i = skip(ctx, j + 1) elseif c == 41 then return out, j + 1 elseif c == nil then return fail(ctx, "truncated list", j), j else return fail(ctx, "expected , or ) in a list", j), j end end end Parse.list = list value = @native function(ctx: Ctx, i: number, depth: number): (any, number, boolean) if depth > MAX_DEPTH then return fail(ctx, "lists nested too deeply", i), i, false end local s = ctx.s i = skip(ctx, i) local c = sbyte(s, i) if c == nil then return fail(ctx, "truncated parameter", i), i, false elseif c == 35 then -- #ref local _, e = sfind(s, "^%d+", i + 1) if not e then return fail(ctx, "bad entity reference", i), i, false end return { ref = tonumber(ssub(s, i + 1, e)) }, e + 1, false elseif c == 39 then -- 'string' local j = i + 1 while true do local q = sfind(s, "'", j, true) if not q then return fail(ctx, "unterminated string", i), i, false end if sbyte(s, q + 1) == 39 then j = q + 2 else return Parse.unescape(ssub(s, i + 1, q - 1)), q + 1, false end end elseif c == 36 then return ctx.null, i + 1, false elseif c == 42 then return ctx.derived, i + 1, false elseif c == 40 then local l, j = list(ctx, i + 1, depth) return l, j, false elseif c == 46 then -- .ENUM. local _, e = sfind(s, "^[%a_][%w_]*%.", i + 1) if not e then return fail(ctx, "bad enumeration", i), i, false end return { enum = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false elseif c == 34 then -- "binary" local _, e = sfind(s, "^[0-3]%x*\"", i + 1) if not e then return fail(ctx, "bad binary literal", i), i, false end return { binary = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false elseif (c >= 48 and c <= 57) or c == 45 or c == 43 then local _, e = sfind(s, "^[+-]?%d*%.?%d*[eE]?[+-]?%d*", i) local tok = ssub(s, i, e :: number) local num = tonumber(if c == 43 then ssub(tok, 2) else tok) if num == nil then -- "1.E" without digits and the like local core = string.match(tok, "^[+-]?%d*%.?%d*") num = core and tonumber(if c == 43 then ssub(core, 2) else core) if num == nil then return fail(ctx, "bad number", i), i, false end e = i + #(core :: string) - 1 end local real = sfind(tok, "[.eE]") ~= nil local nv = num :: number return nv, (e :: number) + 1, real and nv == floor(nv) and nv == nv elseif isAlpha(c) or c == 33 then -- typed parameter NAME(value) local word, j = keyword(ctx, i) j = skip(ctx, j) if word == nil or sbyte(s, j) ~= 40 then return fail(ctx, "expected a parameter", i), i, false end local v, k, intReal = value(ctx, j + 1, depth + 1) if v == nil then return nil, k, false end k = skip(ctx, k) if sbyte(s, k) ~= 41 then return fail(ctx, "expected ) after a typed parameter", k), k, false end local t = { typed = word, value = v } if intReal then markReal(t, "value") end return t, k + 1, false end return fail(ctx, "unexpected character " .. string.format("%q", schar(c)), i), i, false end Parse.value = value @native local function record(ctx: Ctx, i: number): (string?, { any }?, number) local word, j = keyword(ctx, i) if not word then return fail(ctx, "expected an entity name", i), nil, i end j = skip(ctx, j) if sbyte(ctx.s, j) ~= 40 then return fail(ctx, "expected ( after " .. word, j), nil, j end local args, k = list(ctx, j + 1, 0) if not args then return nil, nil, k end return word, args, k end @native local function expect(ctx: Ctx, i: number, ch: number, what: string): number? i = skip(ctx, i) if sbyte(ctx.s, i) ~= ch then if i > ctx.n then return fail(ctx, "truncated: expected " .. what, i) end return fail(ctx, "expected " .. what, i) end return i + 1 end @native local function at(s: string, i: number, word: string): boolean return ssub(s, i, i + #word - 1) == word end type Result = { header: { [string]: { any } }, headerOrder: { string }, entities: { [number]: any }, count: number, sections: { { name: any?, schema: any? } }, extra: { { name: string, text: string } }, duplicates: number, terminated: boolean, } @native function Parse.parse(s: string, null: any, derived: any, maxEntities: number): (Result?, string?, number?) local ctx: Ctx = { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived } local res: Result = { header = {}, headerOrder = {}, entities = {}, count = 0, sections = {}, extra = {}, duplicates = 0, terminated = false, } local i = skip(ctx, 1) if not at(s, i, "ISO-10303-21") then return nil, "no ISO-10303-21 magic", i end local ni = expect(ctx, i + 12, 59, ";") if not ni then return nil, ctx.err, ctx.errAt end i = ni local sawData = false while true do i = skip(ctx, i) if ctx.err then return nil, ctx.err, ctx.errAt end if i > ctx.n then if not sawData then return nil, "truncated: no DATA section", i end break end if at(s, i, "END-ISO-10303-21") then res.terminated = true local e = expect(ctx, i + 16, 59, ";") if not e then return nil, ctx.err, ctx.errAt end break end local word, j = keyword(ctx, i) if word == "HEADER" then local e = expect(ctx, j, 59, ";") if not e then return nil, ctx.err, ctx.errAt end i = e while true do i = skip(ctx, i) if at(s, i, "ENDSEC") then local e2 = expect(ctx, i + 6, 59, ";") if not e2 then return nil, ctx.err, ctx.errAt end i = e2 break end if i > ctx.n then return nil, "truncated header", i end local t, args, k = record(ctx, i) if not t then return nil, ctx.err, ctx.errAt end local e2 = expect(ctx, k, 59, ";") if not e2 then return nil, ctx.err, ctx.errAt end if res.header[t] == nil then table.insert(res.headerOrder, t) end res.header[t] = args :: { any } i = e2 end elseif word == "DATA" then sawData = true local sec: { name: any?, schema: any? } = {} j = skip(ctx, j) if sbyte(s, j) == 40 then local params, k = list(ctx, j + 1, 0) if not params then return nil, ctx.err, ctx.errAt end sec.name, sec.schema = params[1], params[2] j = k end table.insert(res.sections, sec) local secIndex = #res.sections local e = expect(ctx, j, 59, ";") if not e then return nil, ctx.err, ctx.errAt end i = e while true do i = skip(ctx, i) if ctx.err then return nil, ctx.err, ctx.errAt end local c = sbyte(s, i) if c == nil then return nil, "truncated: the DATA section has no ENDSEC", i end if c ~= 35 then if at(s, i, "ENDSEC") then local e2 = expect(ctx, i + 6, 59, ";") if not e2 then return nil, ctx.err, ctx.errAt end i = e2 break end return nil, "expected an entity instance (#id = ...)", i end local _, idEnd = sfind(s, "^%d+", i + 1) if not idEnd then return nil, "bad entity instance name", i end local id = tonumber(ssub(s, i + 1, idEnd)) :: number local k = expect(ctx, idEnd + 1, 61, "=") if not k then return nil, ctx.err, ctx.errAt end k = skip(ctx, k) local ent: any if sbyte(s, k) == 40 then -- complex instance (A(..) B(..)) local parts = {} k = skip(ctx, k + 1) while sbyte(s, k) ~= 41 do if k > ctx.n then return nil, "truncated complex instance", k end local t, args, k2 = record(ctx, k) if not t then return nil, ctx.err, ctx.errAt end table.insert(parts, { type = t, args = args }) k = skip(ctx, k2) end if #parts == 0 then return nil, "empty complex instance", k end ent = { id = id, type = "COMPLEX", args = {}, parts = parts } k += 1 else local t, args, k2 = record(ctx, k) if not t then return nil, ctx.err, ctx.errAt end ent = { id = id, type = t, args = args } k = k2 end local e2 = expect(ctx, k, 59, ";") if not e2 then return nil, ctx.err, ctx.errAt end if secIndex > 1 then ent.section = secIndex end if res.entities[id] then res.duplicates += 1 else res.count += 1 if res.count > maxEntities then return nil, "LIMIT", i end end res.entities[id] = ent i = e2 end elseif word == "ANCHOR" or word == "REFERENCE" or word == "SIGNATURE" then -- kept as raw text (to the ENDSEC outside strings) local k = j local stop: number? = nil while k <= ctx.n do local c = sbyte(s, k) if c == 39 then local q = k + 1 while true do local p = sfind(s, "'", q, true) if not p then return nil, "unterminated string", k end if sbyte(s, p + 1) == 39 then q = p + 2 else k = p + 1 break end end elseif c == 69 and at(s, k, "ENDSEC") then stop = k break else k += 1 end end if not stop then return nil, "truncated " .. word .. " section", i end table.insert(res.extra, { name = word, text = ssub(s, j, stop - 1) }) local e2 = expect(ctx, stop + 6, 59, ";") if not e2 then return nil, ctx.err, ctx.errAt end i = e2 else return nil, "unknown section " .. tostring(word), i end end if not sawData then return nil, "no DATA section", i end return res, nil, nil end return Parse end __FILES["cad/step/Write"] = @native function() -- cad/step/Write: header + entity instances -> ISO 10303-21 text (escaped strings, shortest round-trip reals). local Write = {} local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, string.sub, string.find, math.floor, math.huge local MAX_DEPTH = 100 -- Part 21 real: a '.' always, upper-case E @native function Write.real(v: number): string? if v ~= v or v == huge or v == -huge then return nil end local s = sformat("%.15g", v) if tonumber(s) ~= v then s = sformat("%.16g", v) if tonumber(s) ~= v then s = sformat("%.17g", v) end end s = string.upper(s) local e = sfind(s, "E", 1, true) if not sfind(s, ".", 1, true) then if e then s = ssub(s, 1, e - 1) .. "." .. ssub(s, e) else s ..= "." end end return s end local HEX = "0123456789ABCDEF" @native local function hex(v: number, k: number): string local out = table.create(k) for i = k, 1, -1 do local d = v % 16 out[i] = ssub(HEX, d + 1, d + 1) v = floor(v / 16) end return table.concat(out) end @native function Write.str(s: string): string if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \ return "'" .. s .. "'" end local out = { "'" } local i, n = 1, #s local wide: number? = nil -- 4 (\X2\) or 8 (\X4\) while in an extended run @native local function close() if wide then table.insert(out, "\\X0\\") wide = nil end end while i <= n do local c = sbyte(s, i) :: number if c >= 32 and c < 127 then close() if c == 39 then table.insert(out, "''") elseif c == 92 then table.insert(out, "\\\\") else table.insert(out, string.char(c)) end i += 1 else local cp: number? = nil local len = 1 if c >= 0xC2 and c < 0xE0 then local c2 = sbyte(s, i + 1) if c2 and c2 >= 0x80 and c2 < 0xC0 then cp, len = (c - 0xC0) * 64 + (c2 - 0x80), 2 end elseif c >= 0xE0 and c < 0xF0 then local c2, c3 = sbyte(s, i + 1, i + 2) if c2 and c3 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 then local v = (c - 0xE0) * 4096 + (c2 - 0x80) * 64 + (c3 - 0x80) if v >= 0x800 and (v < 0xD800 or v >= 0xE000) then cp, len = v, 3 end end elseif c >= 0xF0 and c < 0xF5 then local c2, c3, c4 = sbyte(s, i + 1, i + 3) if c2 and c3 and c4 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 and c4 >= 0x80 and c4 < 0xC0 then local v = (c - 0xF0) * 262144 + (c2 - 0x80) * 4096 + (c3 - 0x80) * 64 + (c4 - 0x80) if v >= 0x10000 and v < 0x110000 then cp, len = v, 4 end end end if cp == nil then close() table.insert(out, "\\X\\" .. hex(c, 2)) i += 1 else local k = if cp >= 0x10000 then 8 else 4 if wide ~= k then close() table.insert(out, if k == 4 then "\\X2\\" else "\\X4\\") wide = k end table.insert(out, hex(cp, k)) i += len end end end close() table.insert(out, "'") return table.concat(out) end @native local function isName(s: any): boolean return type(s) == "string" and sfind(s, "^!?[%a_][%w_]*$") ~= nil end Write.isName = isName type Ctx = { out: { string }, null: any, derived: any, err: string? } local value: (ctx: Ctx, v: any, real: boolean, depth: number) -> boolean @native local function reals(t: any): { [any]: boolean }? local mt = getmetatable(t) return if type(mt) == "table" and type(mt.__reals) == "table" then mt.__reals else nil end @native local function list(ctx: Ctx, t: { any }, depth: number): boolean local out = ctx.out table.insert(out, "(") local marks = reals(t) local n = #t for i = 1, n do if i > 1 then table.insert(out, ",") end if not value(ctx, t[i], marks ~= nil and marks[i] == true, depth + 1) then return false end end table.insert(out, ")") return true end Write.list = list value = @native function(ctx: Ctx, v: any, real: boolean, depth: number): boolean local out = ctx.out if depth > MAX_DEPTH then ctx.err = "values nested too deeply (or a cycle)" return false end local tv = type(v) if tv == "number" then if not real and v == floor(v) and v > -2 ^ 53 and v < 2 ^ 53 then table.insert(out, sformat("%.0f", v)) return true end local r = Write.real(v) if not r then ctx.err = "a number that STEP cannot hold (nan / inf)" return false end table.insert(out, r) return true elseif tv == "string" then table.insert(out, Write.str(v)) return true elseif tv == "boolean" then table.insert(out, if v then ".T." else ".F.") return true elseif tv == "table" then if v == ctx.null then table.insert(out, "$") return true elseif v == ctx.derived then table.insert(out, "*") return true end local ref = v.ref if ref ~= nil then if type(ref) ~= "number" or ref ~= floor(ref) or ref < 0 then ctx.err = "bad entity reference " .. tostring(ref) return false end table.insert(out, sformat("#%.0f", ref)) return true end local enum = v.enum if enum ~= nil then if type(enum) ~= "string" or not sfind(enum, "^[%a_][%w_]*$") then ctx.err = "bad enumeration " .. tostring(enum) return false end table.insert(out, "." .. string.upper(enum) .. ".") return true end local bin = v.binary if bin ~= nil then if type(bin) ~= "string" or not sfind(bin, "^[0-3]%x*$") then ctx.err = "bad binary literal" return false end table.insert(out, "\"" .. string.upper(bin) .. "\"") return true end local typed = v.typed if typed ~= nil then if not isName(typed) then ctx.err = "bad typed parameter name " .. tostring(typed) return false end if v.value == nil then ctx.err = "typed parameter " .. typed .. " without a value" return false end local marks = reals(v) table.insert(out, string.upper(typed) .. "(") if not value(ctx, v.value, marks ~= nil and marks.value == true, depth + 1) then return false end table.insert(out, ")") return true end return list(ctx, v, depth) end ctx.err = "cannot write a " .. tv .. " value" return false end Write.value = value @native function Write.record(ctx: Ctx, t: any, args: any): boolean if not isName(t) then ctx.err = "bad entity type " .. tostring(t) return false end if type(args) ~= "table" then ctx.err = "entity " .. t .. " without an args list" return false end table.insert(ctx.out, string.upper(t)) return list(ctx, args, 0) end return Write end __FILES["codecs/audio/Aac"] = function() -- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): AudioSpecificConfig, ADTS, raw_data_block. -- Written from the standard; no third-party code. HE-AAC decodes its AAC-LC core at the core rate. Not supported: Main -- prediction, LTP, SSR, coupling channels, 960-sample frames, ER / USAC (UNSUPPORTED). local Err = __include("core/Err") local Bits = __include("core/Bits") local Decode = __include("codecs/audio/Aac/Decode") local Aac = {} Aac.RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } local CONFIG_CHANNELS = { 1, 2, 3, 4, 5, 6, 8 } -- element order (AAC: C, L, R, ...) -> WAV order (L, R, C, LFE, ...) for channel configurations 3 .. 7 local CONFIG_MAP: { [number]: { number } } = { [3] = { 3, 1, 2 }, [4] = { 3, 1, 2, 4 }, [5] = { 3, 1, 2, 4, 5 }, [6] = { 3, 1, 2, 5, 6, 4 }, [7] = { 3, 7, 8, 1, 2, 5, 6, 4 }, } type Config = { objectType: number, -- 2 = AAC-LC (the core object type when SBR / PS is signalled) sfIndex: number, sampleRate: number, channelConfig: number, channels: number, sbr: boolean, ps: boolean, extensionRate: number?, frameLength: number, } local function rateIndex(rate: number): number -- the nearest standard rate (ISO 14496-3 table 4.82 mapping for explicit frequencies) local best, bi = math.huge, 4 for i, r in Aac.RATES do if math.abs(r - rate) < best then best, bi = math.abs(r - rate), i - 1 end end return bi end local function objectType(br: Bits.BitReader): number local t = br:read(5) if t == 31 then t = 32 + br:read(6) end return t end local function frequency(br: Bits.BitReader): (number, number) local i = br:read(4) if i == 15 then local f = br:read(24) return rateIndex(f), f end return i, Aac.RATES[i + 1] or 0 end -- program_config_element local function pce(br: Bits.BitReader): number br:read(4 + 2 + 4) local front, side, back = br:read(4), br:read(4), br:read(4) local lfe, assoc, cc = br:read(2), br:read(3), br:read(4) if br:read(1) == 1 then br:read(4) end if br:read(1) == 1 then br:read(4) end if br:read(1) == 1 then br:read(3) end local channels = 0 for _ = 1, front + side + back do channels += if br:read(1) == 1 then 2 else 1 br:read(4) end channels += lfe br:skip(lfe * 4 + assoc * 4 + cc * 5) br:align() br:skip(br:read(8) * 8) return channels end function Aac.config(asc: buffer): (Config?, Err.Err?) if type(asc) ~= "buffer" or buffer.len(asc) < 2 then return nil, Err.new(Err.TRUNCATED, "AudioSpecificConfig is shorter than 2 bytes") end local br = Bits.msbReader(asc) local aot = objectType(br) local sfi, rate = frequency(br) local chcfg = br:read(4) local sbr, ps = false, false local extRate: number? = nil if aot == 5 or aot == 29 then sbr = true ps = aot == 29 local _, er = frequency(br) extRate = er aot = objectType(br) if aot == 22 then br:read(4) end end if aot ~= 2 and aot ~= 1 and aot ~= 4 then if aot == 0 or br.err then return nil, Err.new(Err.CORRUPT, "bad AudioSpecificConfig") end return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. aot .. " (only AAC-LC)") end if aot ~= 2 then return nil, Err.new(Err.UNSUPPORTED, if aot == 1 then "AAC Main" else "AAC LTP") end -- GASpecificConfig local frameLengthFlag = br:read(1) if br:read(1) == 1 then br:read(14) end local ext = br:read(1) local channels = CONFIG_CHANNELS[chcfg] or 0 if chcfg == 0 then channels = pce(br) elseif chcfg > 7 then return nil, Err.new(Err.UNSUPPORTED, "channel configuration " .. chcfg) end if ext == 1 then br:read(1) -- extensionFlag3 end -- backward-compatible SBR signalling if not sbr and br:bitsLeft() >= 16 then if br:read(11) == 0x2b7 then local et = objectType(br) if et == 5 and br:read(1) == 1 then sbr = true local _, er = frequency(br) extRate = er if br:bitsLeft() >= 12 and br:read(11) == 0x548 then ps = br:read(1) == 1 end end end end if br.err and channels == 0 then return nil, br.err end if sfi > 12 or rate <= 0 then return nil, Err.new(Err.CORRUPT, "bad sampling frequency index " .. sfi) end if frameLengthFlag == 1 then return nil, Err.new(Err.UNSUPPORTED, "960-sample AAC frames") end if channels < 1 or channels > 8 then return nil, Err.new(Err.UNSUPPORTED, channels .. " channels") end return { objectType = aot, sfIndex = sfi, sampleRate = rate, channelConfig = chcfg, channels = channels, sbr = sbr, ps = ps, extensionRate = extRate, frameLength = 1024, }, nil end function Aac.asc(aot: number, sfIndex: number, channelConfig: number): buffer local b = buffer.create(2) local v = aot * 2048 + sfIndex * 128 + channelConfig * 8 buffer.writeu8(b, 0, bit32.rshift(v, 8)) buffer.writeu8(b, 1, bit32.band(v, 255)) return b end type Adts = { headerSize: number, -- 7, or 9 with a CRC frameSize: number, objectType: number, sfIndex: number, sampleRate: number, channelConfig: number, blocks: number, -- raw_data_blocks in the frame (1 .. 4) protected: boolean, } function Aac.adts(b: buffer, o: number, limit: number): Adts? if o < 0 or o + 7 > limit or o + 7 > buffer.len(b) then return nil end local b0, b1, b2, b3, b4, b5, b6 = buffer.readu8(b, o), buffer.readu8(b, o + 1), buffer.readu8(b, o + 2), buffer.readu8(b, o + 3), buffer.readu8(b, o + 4), buffer.readu8(b, o + 5), buffer.readu8(b, o + 6) if b0 ~= 0xFF or bit32.band(b1, 0xF6) ~= 0xF0 then -- sync, layer 0 return nil end local protected = bit32.band(b1, 1) == 0 local profile = bit32.rshift(b2, 6) local sfi = bit32.band(bit32.rshift(b2, 2), 15) local ch = bit32.band(b2, 1) * 4 + bit32.rshift(b3, 6) local size = bit32.band(b3, 3) * 2048 + b4 * 8 + bit32.rshift(b5, 5) local blocks = bit32.band(b6, 3) + 1 local hs = if protected then 9 else 7 if sfi > 12 or size < hs then return nil end return { headerSize = hs, frameSize = size, objectType = profile + 1, sfIndex = sfi, sampleRate = Aac.RATES[sfi + 1], channelConfig = ch, blocks = blocks, protected = protected, } end type Decoder = { config: Config, channels: number, sampleRate: number, frameLength: number, pcm: { number }, sbr: boolean, onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?, decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), reset: (self: Decoder) -> (), state: Decode.State, } local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) local o = offset or 0 local n = length or (buffer.len(buf) - o) if type(buf) ~= "buffer" or o < 0 or n < 0 or o + n > buffer.len(buf) then return nil, Err.new(Err.ARG, "packet range out of the buffer") end local st = self.state st.onExtension = self.onExtension local chans, msg = Decode.frame(st, buf, o, n) if not chans then return nil, Err.new(Err.CORRUPT, msg or "bad frame", o) end if st.sbr then self.sbr = true end if chans == 0 then for i = 1, 1024 * self.channels do st.pcm[i] = 0 end return 1024, nil end if chans ~= self.channels then return nil, Err.new(Err.CORRUPT, string.format("frame has %d channels, the configuration %d", chans, self.channels), o) end return 1024, nil end local function reset(self: Decoder) for _, c in self.state.ch do for i = 1, 1024 do c.overlap[i] = 0 end c.prevShape = 0 end end function Aac.decoder(asc: any): (Decoder?, Err.Err?) local cfg: Config if type(asc) == "buffer" then local c, err = Aac.config(asc) if not c then return nil, err end cfg = c elseif type(asc) == "table" and type(asc.sfIndex) == "number" and type(asc.channels) == "number" then local sfi = asc.sfIndex if sfi < 0 or sfi > 12 or asc.channels < 1 or asc.channels > 8 then return nil, Err.new(Err.ARG, "bad sampling index / channels") end if (asc.objectType or 2) ~= 2 then return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. asc.objectType .. " (only AAC-LC)") end cfg = { objectType = 2, sfIndex = sfi, sampleRate = Aac.RATES[sfi + 1], channelConfig = asc.channelConfig or asc.channels, channels = asc.channels, sbr = false, ps = false, frameLength = 1024, } :: Config else return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer") end local st = Decode.state(cfg.sfIndex) st.channels = cfg.channels if cfg.channelConfig >= 3 then st.map = CONFIG_MAP[cfg.channelConfig] end return { config = cfg, channels = cfg.channels, sampleRate = cfg.sampleRate, frameLength = 1024, pcm = st.pcm, sbr = cfg.sbr, onExtension = nil, decode = decode, reset = reset, state = st, }, nil end return Aac end __FILES["codecs/audio/Aac/Decode"] = @native function() -- codecs/audio/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4). -- Written from the standard; no third-party code. PNS uses FFmpeg's LCG so the noise matches it. local Mdct = __include("codecs/audio/Mdct") local Tables = __include("codecs/audio/Aac/Tables") local readu32, byteswap, lshift, rshift, band = buffer.readu32, bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band local floor, sqrt, abs = math.floor, math.sqrt, math.abs local Decode = {} local ONLY_LONG, LONG_START, EIGHT_SHORT, LONG_STOP = 0, 1, 2, 3 local ZERO_HCB, ESC_HCB, NOISE_HCB, INTENSITY_HCB2, INTENSITY_HCB = 0, 11, 13, 14, 15 -- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields) local B: buffer = buffer.create(16) local BP = 0 local BL = 0 local OVER = false @native local function getBits(n: number): number local p = BP BP = p + n if p > BL then OVER = true return 0 end return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) end @native local function peekBits(n: number): number local p = BP if p > BL then return 0 end return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) end @native local function getLong(n: number): number if n > 24 then local hi = getBits(n - 16) return hi * 65536 + getBits(16) end return getBits(n) end local PEEK = 10 type Book = { tab: { number }, map: { [number]: number }, maxLen: number } @native local function book(codes: { number }, bits: { number }): Book local tab = table.create(2 ^ PEEK, 0) local map = {} local maxLen = 0 for s = 1, #codes do local c, l = codes[s], bits[s] maxLen = math.max(maxLen, l) if l <= PEEK then local shift = 2 ^ (PEEK - l) for k = 0, shift - 1 do tab[c * shift + k + 1] = (s - 1) * 32 + l end else map[l * 2 ^ 20 + c] = s - 1 end end return { tab = tab, map = map, maxLen = maxLen } end local SF_BOOK = book(Tables.SF_CODES, Tables.SF_BITS) local SPEC_BOOK: { Book } = {} for i = 1, 11 do SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i]) end @native local function huff(bk: Book): number local e = bk.tab[peekBits(PEEK) + 1] if e > 0 then BP += band(e, 31) return rshift(e, 5) end local code = getBits(PEEK) local map = bk.map for l = PEEK + 1, bk.maxLen do code = code * 2 + getBits(1) local s = map[l * 1048576 + code] if s then return s end end return -1 end local DIM = { 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2 } local UNSIGNED = { false, false, true, true, false, false, true, true, true, true, true } local MOD = { 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17 } local OFF = { 1, 1, 0, 0, 4, 4, 0, 0, 0, 0, 0 } -- |q|^(4/3) local POW43 = table.create(8192, 0) for i = 0, 8191 do POW43[i + 1] = i ^ (4 / 3) end local SINE_LONG = Mdct.window("sine", 2048) :: { number } local KBD_LONG = Mdct.window("kbd", 2048, 4) :: { number } local SINE_SHORT = Mdct.window("sine", 256) :: { number } local KBD_SHORT = Mdct.window("kbd", 256, 6) :: { number } local PLAN_LONG = Mdct.new(2048) :: Mdct.Plan local PLAN_SHORT = Mdct.new(256) :: Mdct.Plan type Channel = { spec: { number }, overlap: { number }, prevShape: number, windowSequence: number, windowShape: number, maxSfb: number, numGroups: number, groupLen: { number }, bandType: { number }, sf: { number }, tnsFilters: { { { number } } }, } type State = { sfIndex: number, channels: number, frameLength: number, ch: { Channel }, pcm: { number }, random: number, time: { number }, frame: { number }, short: { number }, onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?, extensions: number, sbr: boolean, map: { number }?, } @native local function newChannel(): Channel return { spec = table.create(1024, 0), overlap = table.create(1024, 0), prevShape = 0, windowSequence = 0, windowShape = 0, maxSfb = 0, numGroups = 1, groupLen = { 1, 0, 0, 0, 0, 0, 0, 0 }, bandType = table.create(8 * 64, 0), sf = table.create(8 * 64, 0), tnsFilters = {}, } end Decode.newChannel = newChannel @native local function icsInfo(st: State, c: Channel): string? if getBits(1) ~= 0 then return "reserved ics bit set" end c.windowSequence = getBits(2) c.windowShape = getBits(1) if c.windowSequence == EIGHT_SHORT then c.maxSfb = getBits(4) local grouping = getBits(7) local ng = 1 local gl = c.groupLen gl[1] = 1 for w = 1, 7 do if band(grouping, 2 ^ (6 - (w - 1))) ~= 0 then gl[ng] += 1 else ng += 1 gl[ng] = 1 end end c.numGroups = ng if c.maxSfb > Tables.NUM_SWB_SHORT[st.sfIndex + 1] then return "max_sfb over the short band count" end else c.maxSfb = getBits(6) c.numGroups = 1 c.groupLen[1] = 1 if getBits(1) ~= 0 then return "prediction (AAC Main / LTP) is not supported" end if c.maxSfb > Tables.NUM_SWB_LONG[st.sfIndex + 1] then return "max_sfb over the long band count" end end return nil end @native local function sectionData(c: Channel): string? local long = c.windowSequence ~= EIGHT_SHORT local bits = if long then 5 else 3 local esc = 2 ^ bits - 1 local maxSfb = c.maxSfb local bt = c.bandType for g = 0, c.numGroups - 1 do local k = 0 while k < maxSfb do local cb = getBits(4) if cb == 12 then return "reserved codebook 12" end local len = 0 while true do local inc = getBits(bits) len += inc if inc ~= esc then break end if OVER then return "section data runs past the end" end end if k + len > maxSfb then return "section runs past max_sfb" end for s = k, k + len - 1 do bt[g * maxSfb + s + 1] = cb end k += len if OVER then return "section data runs past the end" end end end return nil end @native local function scaleFactors(c: Channel, globalGain: number): string? local sfv = globalGain local noise = globalGain - 90 local is = 0 local firstNoise = true local maxSfb = c.maxSfb local bt, sf = c.bandType, c.sf for g = 0, c.numGroups - 1 do for s = 0, maxSfb - 1 do local i = g * maxSfb + s + 1 local cb = bt[i] if cb == ZERO_HCB then sf[i] = 0 elseif cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then local d = huff(SF_BOOK) if d < 0 then return "bad scalefactor code" end is += d - 60 sf[i] = math.clamp(is, -155, 100) elseif cb == NOISE_HCB then if firstNoise then noise += getBits(9) - 256 firstNoise = false else local d = huff(SF_BOOK) if d < 0 then return "bad scalefactor code" end noise += d - 60 end sf[i] = math.clamp(noise, -100, 155) else local d = huff(SF_BOOK) if d < 0 then return "bad scalefactor code" end sfv += d - 60 if sfv < 0 or sfv > 255 then return "scalefactor out of range" end sf[i] = sfv end end end return nil end @native local function tnsData(st: State, c: Channel): string? local short = c.windowSequence == EIGHT_SHORT local nw = if short then 8 else 1 local filters = {} for w = 1, nw do local list = {} local nFilt = getBits(if short then 1 else 2) if nFilt > 0 then local coefRes = getBits(1) for _ = 1, nFilt do local length = getBits(if short then 4 else 6) local order = getBits(if short then 3 else 5) local f = { length, order, 0 } if order > (if short then 7 else 12) then return "TNS order too high" end if order > 0 then f[3] = getBits(1) local compress = getBits(1) local resBits = coefRes + 3 local nb = resBits - compress local iq = ((2 ^ (resBits - 1)) - 0.5) / (math.pi / 2) local iqm = ((2 ^ (resBits - 1)) + 0.5) / (math.pi / 2) local tmp = table.create(order, 0) for k = 1, order do local v = getBits(nb) if v >= 2 ^ (nb - 1) then v -= 2 ^ nb end tmp[k] = math.sin(v / (if v >= 0 then iq else iqm)) end -- parcor -> LPC local a = table.create(order + 1, 0) local b = table.create(order + 1, 0) a[1] = 1 for m = 1, order do for i = 1, m - 1 do b[i + 1] = a[i + 1] + tmp[m] * a[m - i + 1] end for i = 1, m - 1 do a[i + 1] = b[i + 1] end a[m + 1] = tmp[m] end for k = 1, order do f[3 + k] = a[k + 1] end end table.insert(list, f) end end filters[w] = list end c.tnsFilters = filters local _ = st return nil end @native local function applyTns(st: State, c: Channel) local short = c.windowSequence == EIGHT_SHORT local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] local numSwb = if short then Tables.NUM_SWB_SHORT[st.sfIndex + 1] else Tables.NUM_SWB_LONG[st.sfIndex + 1] local maxBands = if short then Tables.TNS_MAX_BANDS_SHORT[st.sfIndex + 1] else Tables.TNS_MAX_BANDS_LONG[st.sfIndex + 1] local mmm = math.min(maxBands, c.maxSfb) if mmm == 0 then return end local spec = c.spec for w, list in c.tnsFilters do local bottom = numSwb for _, f in list do local top = bottom bottom = math.max(0, top - f[1]) local order = f[2] if order > 0 then local start = swb[math.min(bottom, mmm) + 1] local stop = swb[math.min(top, mmm) + 1] local size = stop - start if size > 0 then local inc = 1 local p = (w - 1) * 128 + start + 1 if f[3] == 1 then inc = -1 p = (w - 1) * 128 + stop end for m = 0, size - 1 do local y = spec[p] local lim = if m < order then m else order for i = 1, lim do y -= spec[p - i * inc] * f[3 + i] end spec[p] = y p += inc end end end end end end @native local function spectralData(st: State, c: Channel, pulses: { number }?): string? local short = c.windowSequence == EIGHT_SHORT local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] local spec = c.spec for i = 1, 1024 do spec[i] = 0 end local maxSfb = c.maxSfb local bt, sf = c.bandType, c.sf local win = 0 for g = 0, c.numGroups - 1 do local glen = c.groupLen[g + 1] for s = 0, maxSfb - 1 do local idx = g * maxSfb + s + 1 local cb = bt[idx] local lo, hi = swb[s + 1], swb[s + 2] local width = hi - lo if cb == ZERO_HCB or cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then -- zeros (intensity bands are filled from the other channel later) continue elseif cb == NOISE_HCB then local scale = 2 ^ (0.25 * sf[idx]) for w = 0, glen - 1 do local base = (win + w) * 128 + lo local energy = 0 local r = st.random for k = 1, width do r = (r * 1664525 + 1013904223) % 4294967296 local v = if r >= 2147483648 then r - 4294967296 else r spec[base + k] = v energy += v * v end st.random = r local m = if energy > 0 then scale / sqrt(energy) else 0 for k = 1, width do spec[base + k] *= m end end continue end local bk = SPEC_BOOK[cb] local dim, uns, mod, off = DIM[cb], UNSIGNED[cb], MOD[cb], OFF[cb] local gain = 2 ^ (0.25 * (sf[idx] - 100)) for w = 0, glen - 1 do local base = (win + w) * 128 + lo local k = 0 while k < width do local sym = huff(bk) if sym < 0 then return "bad spectral code" end -- unpack the symbol into dim values (first value most significant) local vals1: number, vals2: number, vals3: number, vals4: number if dim == 4 then vals4 = sym % mod - off sym = (sym - (sym % mod)) / mod vals3 = sym % mod - off sym = (sym - (sym % mod)) / mod vals2 = sym % mod - off sym = (sym - (sym % mod)) / mod vals1 = sym % mod - off else vals2 = sym % mod - off vals1 = (sym - (sym % mod)) / mod - off end if uns then if vals1 ~= 0 and getBits(1) == 1 then vals1 = -vals1 end if vals2 ~= 0 and getBits(1) == 1 then vals2 = -vals2 end if dim == 4 then if vals3 ~= 0 and getBits(1) == 1 then vals3 = -vals3 end if vals4 ~= 0 and getBits(1) == 1 then vals4 = -vals4 end end if cb == ESC_HCB then for e = 1, 2 do local v = if e == 1 then vals1 else vals2 if v == 16 or v == -16 then local n = 0 while getBits(1) == 1 do n += 1 if n > 8 or OVER then return "bad escape" end end local esc = 2 ^ (n + 4) + getBits(n + 4) if v < 0 then esc = -esc end if e == 1 then vals1 = esc else vals2 = esc end end end end end local p = base + k + 1 spec[p] = vals1 spec[p + 1] = vals2 if dim == 4 then spec[p + 2] = vals3 spec[p + 3] = vals4 end k += dim end if OVER then return "spectral data runs past the end" end end -- dequantise (pulses are added to the quantised values first: long windows only, applied below) if not pulses then for w = 0, glen - 1 do local base = (win + w) * 128 + lo for k = 1, width do local q = spec[base + k] if q ~= 0 then local aq = if q < 0 then -q else q local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain spec[base + k] = if q < 0 then -v else v end end end end end win += glen end if pulses then for i = 1, #pulses, 2 do local pos = pulses[i] + 1 if pos <= 1024 then local q = spec[pos] spec[pos] = if q > 0 then q + pulses[i + 1] else q - pulses[i + 1] end end for s = 0, maxSfb - 1 do local idx = s + 1 local cb = bt[idx] if cb ~= ZERO_HCB and cb < NOISE_HCB then local gain = 2 ^ (0.25 * (sf[idx] - 100)) for k = swb[s + 1] + 1, swb[s + 2] do local q = spec[k] if q ~= 0 then local aq = if q < 0 then -q else q local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain spec[k] = if q < 0 then -v else v end end end end end return nil end -- individual_channel_stream @native local function ics(st: State, c: Channel, commonWindow: boolean): string? local globalGain = getBits(8) if not commonWindow then local e = icsInfo(st, c) if e then return e end end local e = sectionData(c) if e then return e end e = scaleFactors(c, globalGain) if e then return e end local pulses: { number }? = nil if getBits(1) == 1 then if c.windowSequence == EIGHT_SHORT then return "pulse data in a short window" end local n = getBits(2) + 1 local startSfb = getBits(6) if startSfb >= Tables.NUM_SWB_LONG[st.sfIndex + 1] then return "bad pulse start band" end local pos = Tables.SWB_LONG[st.sfIndex + 1][startSfb + 1] local list = {} for _ = 1, n do pos += getBits(5) table.insert(list, pos) table.insert(list, getBits(4)) end pulses = list end c.tnsFilters = {} if getBits(1) == 1 then e = tnsData(st, c) if e then return e end end if getBits(1) == 1 then return "gain control (AAC SSR) is not supported" end if OVER then return "channel stream runs past the end" end return spectralData(st, c, pulses) end @native local function msStereo(st: State, l: Channel, r: Channel, mask: { number }) local short = l.windowSequence == EIGHT_SHORT local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] local maxSfb = l.maxSfb local a, b = l.spec, r.spec local win = 0 for g = 0, l.numGroups - 1 do local glen = l.groupLen[g + 1] for s = 0, maxSfb - 1 do local idx = g * maxSfb + s + 1 if mask[idx] == 1 and l.bandType[idx] < NOISE_HCB and r.bandType[idx] < NOISE_HCB then for w = 0, glen - 1 do local base = (win + w) * 128 for k = base + swb[s + 1] + 1, base + swb[s + 2] do local m, sd = a[k], b[k] a[k], b[k] = m + sd, m - sd end end end end win += glen end end @native local function intensity(st: State, l: Channel, r: Channel, mask: { number }, msPresent: number) local short = r.windowSequence == EIGHT_SHORT local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] local maxSfb = r.maxSfb local a, b = l.spec, r.spec local win = 0 for g = 0, r.numGroups - 1 do local glen = r.groupLen[g + 1] for s = 0, maxSfb - 1 do local idx = g * maxSfb + s + 1 local cb = r.bandType[idx] if cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then local sign = if cb == INTENSITY_HCB then 1 else -1 if msPresent ~= 0 and mask[idx] == 1 then sign = -sign end local scale = sign * 0.5 ^ (0.25 * r.sf[idx]) for w = 0, glen - 1 do local base = (win + w) * 128 for k = base + swb[s + 1] + 1, base + swb[s + 2] do b[k] = a[k] * scale end end end end win += glen end end @native local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number) local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape local spec, overlap = c.spec, c.overlap local frame = st.frame local scale = 1 / 32768 if seq == EIGHT_SHORT then for i = 1, 2048 do frame[i] = 0 end local tmp = st.short local rise0 = if prev == 1 then KBD_SHORT else SINE_SHORT local wcur = if shape == 1 then KBD_SHORT else SINE_SHORT for w = 0, 7 do Mdct.inverse(PLAN_SHORT, spec, w * 128 + 1, 1, tmp, 1, 2 / 256) local rise = if w == 0 then rise0 else wcur local base = 448 + w * 128 for n = 1, 128 do frame[base + n] += tmp[n] * rise[n] frame[base + 128 + n] += tmp[128 + n] * wcur[128 + n] end end else local t = st.time Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048) if seq == LONG_STOP then local rise = if prev == 1 then KBD_SHORT else SINE_SHORT for n = 1, 448 do frame[n] = 0 end for n = 1, 128 do frame[448 + n] = t[448 + n] * rise[n] end for n = 577, 1024 do frame[n] = t[n] end else local rise = if prev == 1 then KBD_LONG else SINE_LONG for n = 1, 1024 do frame[n] = t[n] * rise[n] end end if seq == LONG_START then local fall = if shape == 1 then KBD_SHORT else SINE_SHORT for n = 1025, 1472 do frame[n] = t[n] end for n = 1, 128 do frame[1472 + n] = t[1472 + n] * fall[128 + n] end for n = 1601, 2048 do frame[n] = 0 end else local fall = if shape == 1 then KBD_LONG else SINE_LONG for n = 1025, 2048 do frame[n] = t[n] * fall[n] end end end local p = offset for n = 1, 1024 do out[p] = (frame[n] + overlap[n]) * scale overlap[n] = frame[1024 + n] p += stride end c.prevShape = shape end @native function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) if buffer.len(B) < len + 16 then B = buffer.create(len + 256) end buffer.copy(B, 0, buf, off, len) buffer.fill(B, len, 0, 16) BP, BL, OVER = 0, len * 8, false local chans = st.ch local nextCh = 1 local order: { Channel } = {} local lastElement = -1 while true do if BP + 3 > BL then break -- tolerate a missing END end local id = getBits(3) if id == 7 then break end if id == 0 or id == 3 then -- SCE / LFE getBits(4) local c = chans[nextCh] if not c then c = newChannel() chans[nextCh] = c end local e = ics(st, c, false) if e then return nil, e end applyTns(st, c) table.insert(order, c) nextCh += 1 lastElement = id elseif id == 1 then -- CPE getBits(4) local l, r = chans[nextCh], chans[nextCh + 1] if not l then l = newChannel() chans[nextCh] = l end if not r then r = newChannel() chans[nextCh + 1] = r end local common = getBits(1) == 1 local msPresent = 0 local mask = table.create(8 * 64, 0) if common then local e = icsInfo(st, l) if e then return nil, e end r.windowSequence, r.windowShape, r.maxSfb, r.numGroups = l.windowSequence, l.windowShape, l.maxSfb, l.numGroups for i = 1, 8 do r.groupLen[i] = l.groupLen[i] end msPresent = getBits(2) if msPresent == 1 then for i = 1, l.numGroups * l.maxSfb do mask[i] = getBits(1) end elseif msPresent == 2 then for i = 1, l.numGroups * l.maxSfb do mask[i] = 1 end elseif msPresent == 3 then return nil, "reserved ms_mask_present" end end local e = ics(st, l, common) if e then return nil, e end e = ics(st, r, common) if e then return nil, e end if common and msPresent ~= 0 then msStereo(st, l, r, mask) end if common then intensity(st, l, r, mask, msPresent) end applyTns(st, l) applyTns(st, r) table.insert(order, l) table.insert(order, r) nextCh += 2 lastElement = id elseif id == 2 then return nil, "coupling channel elements are not supported" elseif id == 4 then -- DSE getBits(4) local align = getBits(1) local count = getBits(8) if count == 255 then count += getBits(8) end if align == 1 then BP = (BP + 7) // 8 * 8 end BP += count * 8 elseif id == 5 then -- PCE: skipped here (parsed from the configuration) return nil, "program config element inside the stream is not supported" elseif id == 6 then -- FIL local count = getBits(4) if count == 15 then count += getBits(8) - 1 end if count > 0 then local start = BP local kind = getBits(4) if kind == 13 or kind == 14 then -- EXT_SBR_DATA / EXT_SBR_DATA_CRC st.sbr = true end st.extensions += 1 local hook = st.onExtension if hook then hook(kind, lastElement, B, start, count * 8) end BP = start + count * 8 end end if OVER or BP > BL then return nil, "frame runs past the end" end if nextCh > 9 then return nil, "more than 8 channels" end end local n = #order if n == 0 then return 0, nil end local pcm = st.pcm local map = st.map for i, c in order do local o = if map and map[i] then map[i] else i filterbank(st, c, pcm, n, o) end return n, nil end @native function Decode.state(sfIndex: number): State return { sfIndex = sfIndex, channels = 0, frameLength = 1024, ch = {}, pcm = table.create(1024 * 8, 0), random = 0x1f2e3d4c, time = table.create(2048, 0), frame = table.create(2048, 0), short = table.create(256, 0), onExtension = nil, extensions = 0, sbr = false, map = nil, } end local _ = abs local _2 = floor return Decode end __FILES["codecs/audio/Aac/Tables"] = function() -- codecs/audio/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): Huffman codebooks, scalefactor -- band offsets, TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code; see -- licenses/NOTICE.md). Generated; do not edit. local Tables = {} Tables.SF_CODES = { 262120, 262118, 262119, 262117, 524277, 524273, 524269, 524278, 524270, 524271, 524272, 524284, 524285, 524287, 524286, 524279, 524280, 524283, 524281, 262116, 524282, 262115, 131055, 131056, 65525, 131054, 65522, 65523, 65524, 65521, 32758, 32759, 16377, 16373, 16375, 16371, 16374, 16370, 8183, 8181, 4089, 4087, 4086, 2041, 4084, 2040, 1017, 1015, 1013, 504, 503, 250, 248, 246, 121, 58, 56, 26, 11, 4, 0, 10, 12, 27, 57, 59, 120, 122, 247, 249, 502, 505, 1012, 1014, 1016, 2037, 2036, 2038, 2039, 4085, 4088, 8180, 8182, 8184, 16376, 16372, 65520, 32756, 65526, 32757, 262114, 524249, 524250, 524251, 524252, 524253, 524254, 524248, 524242, 524243, 524244, 524245, 524246, 524274, 524255, 524263, 524264, 524265, 524266, 524267, 524262, 524256, 524257, 524258, 524259, 524260, 524261, 524247, 524268, 524276, 524275, } Tables.SF_BITS = { 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16, 15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3, 1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, } Tables.SPEC_CODES = { { 2040, 497, 2045, 1013, 104, 1008, 2039, 492, 2037, 1009, 114, 1012, 116, 17, 118, 491, 108, 1014, 2044, 481, 2033, 496, 97, 502, 2034, 490, 2043, 498, 105, 493, 119, 23, 111, 486, 100, 485, 103, 21, 98, 18, 0, 20, 101, 22, 109, 489, 99, 484, 107, 19, 113, 483, 112, 499, 2046, 487, 2035, 495, 96, 494, 2032, 482, 2042, 1011, 106, 488, 117, 16, 115, 500, 110, 1015, 2038, 480, 2041, 1010, 102, 501, 2047, 503, 2036, }, { 499, 111, 509, 235, 35, 234, 503, 232, 506, 242, 45, 112, 32, 6, 43, 110, 40, 233, 505, 102, 248, 231, 27, 241, 500, 107, 501, 236, 42, 108, 44, 10, 39, 103, 26, 245, 36, 8, 31, 9, 0, 7, 29, 11, 48, 239, 28, 100, 30, 12, 41, 243, 47, 240, 508, 113, 498, 244, 33, 230, 247, 104, 504, 238, 34, 101, 49, 2, 38, 237, 37, 106, 507, 114, 510, 105, 46, 246, 511, 109, 502, }, { 0, 9, 239, 11, 25, 240, 491, 486, 1010, 10, 53, 495, 52, 55, 489, 493, 487, 1011, 494, 1005, 8186, 492, 498, 2041, 2040, 1016, 4088, 8, 56, 1014, 54, 117, 1009, 1003, 1004, 4084, 24, 118, 2036, 57, 116, 1007, 499, 500, 2038, 488, 1002, 8188, 242, 497, 4091, 1013, 2035, 4092, 238, 1015, 32766, 496, 2037, 32765, 8187, 16378, 65535, 241, 1008, 16380, 490, 1006, 16379, 4086, 4090, 32764, 2034, 4085, 65534, 1012, 2039, 32763, 4087, 4089, 32762, }, { 7, 22, 246, 24, 8, 239, 495, 243, 2040, 25, 23, 237, 21, 1, 226, 240, 112, 1008, 494, 241, 2042, 238, 228, 1010, 2038, 1007, 2045, 5, 20, 242, 9, 4, 229, 244, 232, 1012, 6, 2, 231, 3, 0, 107, 227, 105, 499, 235, 230, 1014, 110, 106, 500, 1004, 496, 1017, 245, 236, 2043, 234, 111, 1015, 2041, 1011, 4095, 233, 109, 1016, 108, 104, 501, 1006, 498, 2036, 2039, 1009, 4094, 1005, 497, 2037, 2046, 1013, 2044, }, { 8191, 4087, 2036, 2024, 1009, 2030, 2041, 4088, 8189, 4093, 2033, 1000, 488, 240, 492, 1006, 2034, 4090, 4084, 1007, 498, 232, 112, 236, 496, 1002, 2035, 2027, 491, 234, 26, 8, 25, 238, 495, 2029, 1008, 242, 115, 11, 0, 10, 113, 243, 2025, 2031, 494, 239, 24, 9, 27, 235, 489, 2028, 2038, 1003, 499, 237, 114, 233, 497, 1005, 2039, 4086, 2032, 1001, 493, 241, 490, 1004, 2040, 4089, 8188, 4092, 4085, 2026, 1011, 1010, 2037, 4091, 8190, }, { 2046, 1021, 497, 491, 500, 490, 496, 1020, 2045, 1014, 485, 234, 108, 113, 104, 240, 486, 1015, 499, 239, 50, 39, 40, 38, 49, 235, 503, 488, 111, 46, 8, 4, 6, 41, 107, 494, 495, 114, 45, 2, 0, 3, 47, 115, 506, 487, 110, 43, 7, 1, 5, 44, 109, 492, 505, 238, 48, 36, 42, 37, 51, 236, 498, 1016, 484, 237, 106, 112, 105, 116, 241, 1018, 2047, 1017, 502, 493, 504, 489, 501, 1019, 2044, }, { 0, 5, 55, 116, 242, 491, 1005, 2039, 4, 12, 53, 113, 236, 238, 494, 501, 54, 52, 114, 234, 241, 489, 499, 1013, 115, 112, 235, 240, 497, 496, 1004, 1018, 243, 237, 488, 495, 1007, 1009, 1017, 2043, 493, 239, 490, 498, 1011, 1016, 2041, 2044, 1006, 492, 500, 1012, 1015, 2040, 4093, 4094, 2038, 1008, 1010, 1014, 2042, 2045, 4092, 4095, }, { 14, 5, 16, 48, 111, 241, 506, 1022, 3, 0, 4, 18, 44, 106, 117, 248, 15, 2, 6, 20, 46, 105, 114, 245, 47, 17, 19, 42, 50, 108, 236, 250, 113, 43, 45, 49, 109, 112, 242, 505, 239, 104, 51, 107, 110, 238, 249, 1020, 504, 116, 115, 237, 240, 246, 502, 509, 1021, 243, 244, 247, 503, 507, 508, 1023, }, { 0, 5, 55, 231, 478, 974, 985, 1992, 1997, 4040, 4061, 8164, 8172, 4, 12, 53, 114, 234, 237, 482, 977, 979, 992, 2008, 4047, 4053, 54, 52, 113, 232, 236, 481, 975, 989, 987, 2000, 4039, 4052, 4068, 230, 112, 233, 477, 483, 978, 988, 1996, 1994, 2014, 4056, 4074, 8155, 479, 235, 476, 486, 981, 990, 1995, 2013, 2012, 4045, 4066, 4071, 8161, 976, 480, 484, 982, 1989, 2001, 2011, 4050, 2016, 4057, 4075, 8163, 8169, 1988, 485, 983, 1990, 1999, 2010, 4043, 4058, 4067, 4073, 8166, 8179, 8183, 2003, 984, 993, 2004, 2009, 4051, 4062, 8157, 8153, 8162, 8170, 8177, 8182, 2002, 980, 986, 1991, 2007, 2018, 4046, 4059, 8152, 8174, 16368, 8180, 16370, 2017, 991, 1993, 2006, 4042, 4048, 4069, 4070, 8171, 8175, 16371, 16372, 16373, 4064, 1998, 2005, 4038, 4049, 4065, 8160, 8168, 8176, 16369, 16376, 16374, 32764, 4072, 2015, 4041, 4055, 4060, 8156, 8159, 8173, 8181, 16377, 16379, 32765, 32766, 8167, 4044, 4054, 4063, 8158, 8154, 8165, 8178, 16378, 16375, 16380, 16381, 32767, }, { 34, 8, 29, 38, 95, 211, 463, 976, 983, 1005, 2032, 2038, 4093, 7, 0, 1, 9, 32, 84, 96, 213, 220, 468, 973, 990, 2023, 28, 2, 6, 12, 30, 40, 91, 205, 217, 462, 476, 985, 1009, 37, 11, 10, 13, 36, 87, 97, 204, 221, 460, 478, 979, 999, 93, 33, 31, 35, 39, 89, 100, 216, 223, 466, 482, 989, 1006, 209, 85, 41, 86, 88, 98, 206, 224, 226, 474, 980, 995, 2027, 457, 94, 90, 92, 99, 202, 218, 455, 458, 480, 987, 1000, 2028, 483, 210, 203, 208, 215, 219, 454, 469, 472, 970, 986, 2026, 2033, 481, 212, 207, 214, 222, 225, 464, 470, 977, 981, 1010, 2030, 2043, 1001, 461, 456, 459, 465, 471, 479, 975, 992, 1007, 2022, 2040, 4090, 1003, 477, 467, 473, 475, 978, 972, 988, 1002, 2029, 2035, 2041, 4089, 2034, 974, 484, 971, 984, 982, 994, 997, 2024, 2036, 2037, 2039, 4091, 2042, 1004, 991, 993, 996, 998, 1008, 2025, 2031, 4088, 4094, 4092, 4095, }, { 0, 6, 25, 61, 156, 198, 423, 912, 962, 991, 2022, 2035, 4091, 2028, 4090, 4094, 910, 5, 1, 8, 20, 55, 66, 146, 175, 401, 421, 437, 926, 960, 930, 973, 2006, 174, 23, 7, 9, 24, 57, 64, 142, 163, 184, 409, 428, 449, 945, 918, 958, 970, 157, 60, 21, 22, 26, 59, 68, 145, 165, 190, 406, 430, 441, 929, 913, 933, 981, 148, 154, 54, 56, 58, 65, 140, 155, 176, 195, 414, 427, 444, 927, 911, 937, 975, 147, 191, 62, 63, 67, 69, 158, 167, 185, 404, 418, 442, 451, 934, 935, 955, 980, 159, 416, 143, 141, 144, 152, 166, 182, 196, 415, 431, 447, 921, 959, 948, 969, 999, 168, 438, 171, 164, 170, 178, 194, 197, 408, 420, 440, 908, 932, 964, 966, 989, 1000, 173, 943, 402, 189, 188, 398, 407, 410, 419, 433, 909, 920, 951, 979, 977, 987, 2013, 180, 990, 425, 411, 412, 417, 426, 429, 435, 907, 946, 952, 974, 993, 992, 2002, 2021, 183, 2019, 443, 424, 422, 432, 434, 439, 923, 922, 954, 949, 982, 2007, 996, 2008, 2026, 186, 2024, 928, 445, 436, 906, 452, 914, 938, 944, 956, 983, 2004, 2012, 2011, 2005, 2032, 193, 2043, 968, 931, 917, 925, 940, 942, 965, 984, 994, 998, 2020, 2023, 2016, 2025, 2039, 400, 2034, 915, 446, 448, 916, 919, 941, 963, 961, 978, 2010, 2009, 2015, 2027, 2036, 2042, 405, 2040, 957, 924, 939, 936, 947, 953, 976, 995, 997, 2018, 2014, 2029, 2033, 2041, 2044, 403, 4093, 988, 950, 967, 972, 971, 985, 986, 2003, 2017, 2030, 2031, 2037, 2038, 4092, 4095, 413, 450, 181, 161, 150, 151, 149, 153, 160, 162, 172, 169, 177, 179, 187, 192, 399, 4, }, } Tables.SPEC_BITS = { { 11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9, 7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9, 11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11, }, { 9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8, 8, 7, 9, 8, 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9, }, { 1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10, 6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15, 13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, 15, }, { 4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8, 4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10, 11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11, }, { 13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8, 9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13, }, { 11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6, 6, 8, 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11, }, { 1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9, 10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10, 11, 11, 12, 12, }, { 5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7, 8, 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8, 9, 9, 9, 10, }, { 1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11, 11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, }, { 6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, 10, 11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, 10, 9, 9, 9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12, 12, 12, }, { 4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10, 10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, 12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5, }, } Tables.SWB_LONG = { { 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960, 1024, }, { 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960, 1024, }, { 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100, 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704, 744, 784, 824, 864, 904, 944, 984, 1024, }, { 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, }, { 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, }, { 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024, }, { 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, 600, 652, 704, 768, 832, 896, 960, 1024, }, { 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, 600, 652, 704, 768, 832, 896, 960, 1024, }, { 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, 832, 896, 960, 1024, }, { 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, 832, 896, 960, 1024, }, { 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, 832, 896, 960, 1024, }, { 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, 1024, }, { 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, 1024, }, } Tables.SWB_SHORT = { { 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, }, { 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, }, { 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, }, { 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, }, { 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, }, { 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, }, { 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, }, { 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, }, { 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, }, { 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, }, { 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, }, { 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, }, { 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, }, } Tables.NUM_SWB_LONG = { 41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40, 40, } Tables.NUM_SWB_SHORT = { 12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, } Tables.TNS_MAX_BANDS_LONG = { 31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39, } Tables.TNS_MAX_BANDS_SHORT = { 9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, } return Tables end __FILES["codecs/audio/Ac3"] = function() -- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: syncinfo / BSI, CRC check and decoder. -- Written from ATSC A/52:2018; no third-party code. E-AC-3 (bsid 11 .. 16) and bsid 9 / 10 are UNSUPPORTED. local Err = __include("core/Err") local T = __include("codecs/audio/Ac3/Tables") local Decode = __include("codecs/audio/Ac3/Decode") local Ac3 = {} local readu8 = buffer.readu8 local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } type Header = { sampleRate: number, frameSize: number, bitrate: number, channels: number, acmod: number, lfeon: boolean, bsid: number, } function Ac3.header(b: buffer, o: number, limit: number): Header? if o < 0 or o + 8 > limit or o + 8 > buffer.len(b) then return nil end if readu8(b, o) ~= 0x0B or readu8(b, o + 1) ~= 0x77 then return nil end local bsid = bit32.rshift(readu8(b, o + 5), 3) if bsid > 10 then if bsid > 16 then return nil end -- E-AC-3: strmtyp(2) substreamid(3) frmsiz(11) fscod(2) ... local words = bit32.band(readu8(b, o + 2), 7) * 256 + readu8(b, o + 3) + 1 local fs = bit32.rshift(readu8(b, o + 4), 6) return { sampleRate = if fs < 3 then T.RATES[fs + 1] else 0, frameSize = words * 2, bitrate = 0, channels = 0, acmod = bit32.band(bit32.rshift(readu8(b, o + 4), 1), 7), lfeon = false, bsid = bsid, } end local b4 = readu8(b, o + 4) local fscod, frmsizecod = bit32.rshift(b4, 6), bit32.band(b4, 63) local words = T.frameWords(fscod, frmsizecod) if words == 0 then return nil end local acmod = bit32.rshift(readu8(b, o + 6), 5) -- lfeon: after acmod and the optional cmixlev / surmixlev / dsurmod fields local skip = 0 if bit32.band(acmod, 1) == 1 and acmod ~= 1 then skip += 2 end if bit32.band(acmod, 4) ~= 0 then skip += 2 end if acmod == 2 then skip += 2 end local w = readu8(b, o + 6) * 256 + readu8(b, o + 7) local lfeon = bit32.extract(w, 12 - skip, 1) == 1 local shift = if bsid > 8 then bsid - 8 else 0 return { sampleRate = T.RATES[fscod + 1] // 2 ^ shift, frameSize = words * 2, bitrate = T.BITRATES[frmsizecod // 2 + 1] * 1000 // 2 ^ shift, channels = NFCHANS[acmod] + (if lfeon then 1 else 0), acmod = acmod, lfeon = lfeon, bsid = bsid, } end -- CRC-16 of A/52 section 7.10.1 (x^16 + x^15 + x^2 + 1, MSB first, zero start): 0 over everything after the sync word local CRC = table.create(256, 0) for i = 0, 255 do local c = i * 256 for _ = 1, 8 do c = if c >= 0x8000 then bit32.bxor(bit32.band(c * 2, 0xFFFF), 0x8005) else c * 2 end CRC[i + 1] = c end function Ac3.crc(b: buffer, o: number, n: number): number local c = 0 for i = o, o + n - 1 do c = bit32.bxor(bit32.band(c * 256, 0xFFFF), CRC[bit32.bxor(bit32.rshift(c, 8), readu8(b, i)) + 1]) end return c end type Options = { drc: number?, -- 0 = off (default, as ffmpeg -drc_scale 0), 1 = as the stream says crc: boolean?, } type Decoder = { pcm: { number }, channels: number, sampleRate: number, blocks: { number }, decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), reset: (self: Decoder) -> (), } function Ac3.decoder(opts: Options?): Decoder local o: Options = opts or {} local drc = math.max(0, o.drc or 0) local checkCrc = o.crc ~= false local st = Decode.state() local scratch = buffer.create(3840 + Decode.PAD) local dec: Decoder dec = { pcm = st.pcm, channels = 0, sampleRate = 0, blocks = st.blocks, decode = function(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) local off = offset or 0 if type(buf) ~= "buffer" or off < 0 or off >= buffer.len(buf) then return nil, Err.new(Err.ARG, "frame range out of the buffer") end local h = Ac3.header(buf, off, buffer.len(buf)) if not h then return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", off) end local n = h.frameSize if length and length < n or off + n > buffer.len(buf) then return nil, Err.new(Err.TRUNCATED, "truncated syncframe", off) end if checkCrc and Ac3.crc(buf, off + 2, n - 2) ~= 0 then return nil, Err.new(Err.CHECKSUM, "syncframe CRC", off) end buffer.copy(scratch, 0, buf, off, n) local frames, msg = Decode.frame(st, scratch, n, drc) if not frames then return nil, Err.from(msg, off) end self.pcm = st.pcm self.channels = st.channels self.sampleRate = h.sampleRate return frames, nil end, reset = function(_self: Decoder) Decode.reset(st) end, } return dec end return Ac3 end __FILES["codecs/audio/Ac3/Decode"] = @native function() -- codecs/audio/Ac3/Decode: one AC-3 syncframe (6 audio blocks of 256 samples) -> PCM. -- Written from ATSC A/52:2018 (5.3 syntax, 7.1 exponents, 7.2 bit allocation, 7.3 mantissas, 7.4 coupling, 7.5 -- rematrixing, 7.7.1 dynamic range, 7.9 transforms); no third-party code. The caller pads the frame by PAD bytes. local T = __include("codecs/audio/Ac3/Tables") local Mdct = __include("codecs/audio/Mdct") local readu32, bswap, extract, band, rshift = buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.rshift local max, min = math.max, math.min local Decode = {} Decode.PAD = 2048 local CPL, LFE = 7, 6 -- channel slots: 1 .. 5 full bandwidth, 6 LFE, 7 the coupling channel local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } local SLOWDEC, FASTDEC, SLOWGAIN, DBPBTAB, FLOORTAB, FASTGAIN = T.SLOWDEC, T.FASTDEC, T.SLOWGAIN, T.DBPBTAB, T.FLOORTAB, T.FASTGAIN local BNDTAB, BNDSZ, MASKTAB, LATAB, HTH, BAPTAB = T.BNDTAB, T.BNDSZ, T.MASKTAB, T.LATAB, T.HTH, T.BAPTAB local POW2 = table.create(32, 0) for e = 0, 31 do POW2[e + 1] = 2 ^ -e end -- symmetric quantiser values (Tables 7.19 - 7.23): Q1[code + 1] etc. @native local function levels(n: number): { number } local t = {} for c = 0, n - 1 do t[c + 1] = (2 * c - (n - 1)) / n end return t end local Q1, Q2, Q3, Q4, Q5 = levels(3), levels(5), levels(7), levels(11), levels(15) -- bits of the asymmetric quantisers (bap 6 .. 15) local QBITS = { [6] = 5, [7] = 6, [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 14, [15] = 16 } local WINDOW = Mdct.window("kbd", 512, 5) :: { number } local PLAN512 = Mdct.new(512) :: Mdct.Plan local PLAN256 = Mdct.new(256) :: Mdct.Plan local B: buffer = buffer.create(0) local P = 0 @native local function bits(n: number): number if n <= 0 then return 0 end if n > 24 then local hi = bits(n - 16) return hi * 65536 + bits(16) end local w = bswap(readu32(B, rshift(P, 3))) local v = extract(w, 32 - band(P, 7) - n, n) P += n return v end type State = { fscod: number, acmod: number, lfeon: boolean, nfchans: number, channels: number, map: { number }, drc: number, exp: { { number } }, bap: { { number } }, coef: { { number } }, delay: { { number } }, endmant: { number }, chexpstr: { number }, blksw: { boolean }, dithflag: { boolean }, fsnroffst: { number }, fgaincod: { number }, dbaOn: { boolean }, dbaOffst: { { number } }, dbaLen: { { number } }, dbaBa: { { number } }, cplinu: boolean, chincpl: { boolean }, phsflginu: boolean, cplbegf: number, cplendf: number, cplbndstrc: { boolean }, -- [sbnd + 1], sbnd = 0 .. 17 (absolute sub-band) cplco: { { number } }, phsflg: { boolean }, cplfleak: number, cplsleak: number, rematflg: { boolean }, sdcycod: number, fdcycod: number, sgaincod: number, dbpbcod: number, floorcod: number, csnroffst: number, dynrng: { number }, -- gain for Ch1 / Ch2 seed: number, psd: { number }, bndpsd: { number }, excite: { number }, mask: { number }, y: { number }, pcm: { number }, blocks: { number }, } @native local function arrays(n: number, size: number, v: any): { any } local t = {} for i = 1, n do t[i] = table.create(size, v) end return t end @native function Decode.state(): State return { fscod = 0, acmod = 2, lfeon = false, nfchans = 2, channels = 2, map = { 1, 2, 3, 4, 5, 6 }, drc = 0, exp = arrays(7, 264, 0), bap = arrays(7, 264, 0), coef = arrays(7, 256, 0), delay = arrays(6, 256, 0), endmant = table.create(7, 0), chexpstr = table.create(7, 0), blksw = table.create(7, false), dithflag = table.create(7, false), fsnroffst = table.create(7, 0), fgaincod = table.create(7, 0), dbaOn = table.create(7, false), dbaOffst = arrays(7, 8, 0), dbaLen = arrays(7, 8, 0), dbaBa = arrays(7, 8, 0), cplinu = false, chincpl = table.create(7, false), phsflginu = false, cplbegf = 0, cplendf = 0, cplbndstrc = table.create(18, false), cplco = arrays(5, 18, 0), phsflg = table.create(18, false), cplfleak = 0, cplsleak = 0, rematflg = table.create(4, false), sdcycod = 0, fdcycod = 0, sgaincod = 0, dbpbcod = 0, floorcod = 0, csnroffst = 0, dynrng = { 1, 1 }, seed = 1, psd = table.create(256, 0), bndpsd = table.create(50, 0), excite = table.create(50, 0), mask = table.create(50, 0), y = table.create(512, 0), pcm = table.create(1536 * 2, 0), blocks = table.create(6, 0), } end @native function Decode.reset(st: State) for _, d in st.delay do for i = 1, 256 do d[i] = 0 end end end -- grouped exponents: 7 bits = 3 deltas each after absexp, grpsize bins per delta; each exponent stays in 0 .. 24 @native local function exponents(e: { number }, absexp: number, ngrps: number, grpsize: number, first: number): boolean local prev = absexp local k = first + 1 for _ = 1, ngrps do local g = bits(7) if g >= 125 then return false end local d1 = g // 25 local d2 = (g % 25) // 5 local d3 = g % 5 for m = 1, 3 do local d = if m == 1 then d1 elseif m == 2 then d2 else d3 prev += d - 2 if prev < 0 or prev > 24 then return false end for _ = 1, grpsize do e[k] = prev k += 1 end end end return true end @native local function logadd(a: number, b: number): number local c = a - b local adr = min(rshift(if c >= 0 then c else -c, 1), 255) return if c >= 0 then a + LATAB[adr + 1] else b + LATAB[adr + 1] end @native local function lowcomp(a: number, b0: number, b1: number, bin: number): number if bin < 7 then if b0 + 256 == b1 then a = 384 elseif b0 > b1 then a = max(0, a - 64) end elseif bin < 20 then if b0 + 256 == b1 then a = 320 elseif b0 > b1 then a = max(0, a - 64) end else a = max(0, a - 128) end return a end -- section 7.2.2: the bap of bins [start, stop) of channel slot ch @native local function allocate(st: State, ch: number, start: number, stop: number, fgain: number, snroffset: number, isLfe: boolean) local e, bap = st.exp[ch], st.bap[ch] local psd, bndpsd, excite, mask = st.psd, st.bndpsd, st.excite, st.mask local sdecay, fdecay = SLOWDEC[st.sdcycod + 1], FASTDEC[st.fdcycod + 1] local sgain, dbknee, floor = SLOWGAIN[st.sgaincod + 1], DBPBTAB[st.dbpbcod + 1], FLOORTAB[st.floorcod + 1] if floor >= 0x8000 then floor -= 0x10000 -- 0xf800: a negative 16-bit value end for bin = start, stop - 1 do psd[bin + 1] = 3072 - e[bin + 1] * 128 end -- PSD integration local j = start local k = MASKTAB[start + 1] local lastbin repeat lastbin = min(BNDTAB[k + 1] + BNDSZ[k + 1], stop) local v = psd[j + 1] j += 1 while j < lastbin do v = logadd(v, psd[j + 1]) j += 1 end bndpsd[k + 1] = v k += 1 until stop <= lastbin -- excitation local bndstrt = MASKTAB[start + 1] local bndend = MASKTAB[stop] + 1 local fastleak, slowleak = 0, 0 local begin if bndstrt == 0 then local lc = 0 lc = lowcomp(lc, bndpsd[1], bndpsd[2], 0) excite[1] = bndpsd[1] - fgain - lc lc = lowcomp(lc, bndpsd[2], bndpsd[3], 1) excite[2] = bndpsd[2] - fgain - lc begin = 7 for bin = 2, 6 do local last = isLfe and bin == 6 if not last then lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) end fastleak = bndpsd[bin + 1] - fgain slowleak = bndpsd[bin + 1] - sgain excite[bin + 1] = fastleak - lc if not last and bndpsd[bin + 1] <= bndpsd[bin + 2] then begin = bin + 1 break end end for bin = begin, min(bndend, 22) - 1 do if not (isLfe and bin == 6) then lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) end fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) excite[bin + 1] = max(fastleak - lc, slowleak) end begin = 22 else begin = bndstrt fastleak = st.cplfleak * 256 + 768 slowleak = st.cplsleak * 256 + 768 end for bin = begin, bndend - 1 do fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) excite[bin + 1] = max(fastleak, slowleak) end -- masking curve local hth = HTH[st.fscod + 1] for bin = bndstrt, bndend - 1 do local x = excite[bin + 1] local p = bndpsd[bin + 1] if p < dbknee then x += (dbknee - p) // 4 end mask[bin + 1] = max(x, hth[bin + 1]) end -- delta bit allocation if st.dbaOn[ch] then local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] local b = 0 for seg = 1, #offs do b += offs[seg] local ba = bas[seg] local delta = if ba >= 4 then (ba - 3) * 128 else (ba - 4) * 128 for _ = 1, lens[seg] do if b < 50 then mask[b + 1] += delta end b += 1 end end end -- bit allocation pointers local i = start j = MASKTAB[start + 1] repeat lastbin = min(BNDTAB[j + 1] + BNDSZ[j + 1], stop) local m = mask[j + 1] - snroffset - floor if m < 0 then m = 0 end m = band(m, 0x1fe0) + floor while i < lastbin do local adr = (psd[i + 1] - m) // 32 bap[i + 1] = BAPTAB[min(63, max(0, adr)) + 1] i += 1 end j += 1 until stop <= lastbin end -- grouped mantissa state (bap 1, 2, 4 share groups across channels within a block) local G1, G2, G4 = table.create(3, 0), table.create(3, 0), table.create(2, 0) local n1, n2, n4 = 0, 0, 0 @native local function dither(st: State): number local s = (st.seed * 1664525 + 1013904223) % 4294967296 st.seed = s return (s / 2147483648 - 1) * 0.707 end @native local function mantissas(st: State, ch: number, start: number, stop: number, out: { number }, dith: boolean) local e, bap = st.exp[ch], st.bap[ch] for bin = start, stop - 1 do local b = bap[bin + 1] local v if b == 0 then v = if dith then dither(st) else 0 elseif b == 1 then if n1 == 0 then local g = bits(5) if g > 26 then g = 26 end G1[1], G1[2], G1[3] = Q1[g // 9 + 1], Q1[(g % 9) // 3 + 1], Q1[g % 3 + 1] n1 = 3 end v = G1[4 - n1] n1 -= 1 elseif b == 2 then if n2 == 0 then local g = bits(7) if g > 124 then g = 124 end G2[1], G2[2], G2[3] = Q2[g // 25 + 1], Q2[(g % 25) // 5 + 1], Q2[g % 5 + 1] n2 = 3 end v = G2[4 - n2] n2 -= 1 elseif b == 3 then v = Q3[min(bits(3), 6) + 1] elseif b == 4 then if n4 == 0 then local g = bits(7) if g > 120 then g = 120 end G4[1], G4[2] = Q4[g // 11 + 1], Q4[g % 11 + 1] n4 = 2 end v = G4[3 - n4] n4 -= 1 elseif b == 5 then v = Q5[min(bits(4), 14) + 1] else local nb = QBITS[b] local m = bits(nb) local half = 2 ^ (nb - 1) if m >= half then m -= 2 * half end v = m / half end out[bin + 1] = v * POW2[e[bin + 1] + 1] end end @native local function readDba(st: State, ch: number) local nseg = bits(3) + 1 local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] table.clear(offs) table.clear(lens) table.clear(bas) for seg = 1, nseg do offs[seg] = bits(5) lens[seg] = bits(4) bas[seg] = bits(3) end end local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D25 / D45) @native local function audblk(st: State, blk: number, limit: number): (boolean?, string?) local nf, acmod = st.nfchans, st.acmod for ch = 1, nf do st.blksw[ch] = bits(1) == 1 end for ch = 1, nf do st.dithflag[ch] = bits(1) == 1 end for i = 1, if acmod == 0 then 2 else 1 do if bits(1) == 1 then local v = bits(8) local x = rshift(v, 5) if x >= 4 then x -= 8 end local g = 2 ^ (x + 1) * (32 + band(v, 31)) / 64 st.dynrng[i] = if st.drc == 1 then g else g ^ st.drc elseif blk == 0 then st.dynrng[i] = 1 end end if bits(1) == 1 then st.cplinu = bits(1) == 1 if st.cplinu then if acmod < 2 then return nil, "coupling in a mono / dual mono stream" end for ch = 1, nf do st.chincpl[ch] = bits(1) == 1 end st.phsflginu = if acmod == 2 then bits(1) == 1 else false st.cplbegf = bits(4) st.cplendf = bits(4) if st.cplendf + 3 <= st.cplbegf then return nil, "bad coupling range" end st.cplbndstrc[st.cplbegf + 1] = false for sbnd = st.cplbegf + 1, st.cplendf + 2 do st.cplbndstrc[sbnd + 1] = bits(1) == 1 end else for ch = 1, nf do st.chincpl[ch] = false end st.phsflginu = false end elseif blk == 0 then return nil, "no coupling strategy in block 0" end local cplinu = st.cplinu local cplbegf, cplendf = st.cplbegf, st.cplendf local cplstrt = 37 + 12 * cplbegf local cplend = 37 + 12 * (cplendf + 3) -- coupling coordinates (per sub-band, duplicated over each coupling band) if cplinu then local anyNew = false for ch = 1, nf do if st.chincpl[ch] then if bits(1) == 1 then anyNew = true local mstr = bits(2) * 3 local co = st.cplco[ch] local v = 0 for sbnd = cplbegf, cplendf + 2 do if not st.cplbndstrc[sbnd + 1] then local ex, mant = bits(4), bits(4) local m = if ex == 15 then mant / 16 else (mant + 16) / 32 v = m * 2 ^ -(ex + mstr) end co[sbnd + 1] = v end end end end if acmod == 2 and st.phsflginu and anyNew then local f = false for sbnd = cplbegf, cplendf + 2 do if not st.cplbndstrc[sbnd + 1] then f = bits(1) == 1 end st.phsflg[sbnd + 1] = f end end end if acmod == 2 then if bits(1) == 1 then local n = if not cplinu or cplbegf > 2 then 4 elseif cplbegf > 0 then 3 else 2 for r = 1, 4 do st.rematflg[r] = if r <= n then bits(1) == 1 else false end elseif blk == 0 then for r = 1, 4 do st.rematflg[r] = false end end end local chexpstr = st.chexpstr chexpstr[CPL] = if cplinu then bits(2) else 0 for ch = 1, nf do chexpstr[ch] = bits(2) end chexpstr[LFE] = if st.lfeon then bits(1) else 0 if blk == 0 then for ch = 1, nf do if chexpstr[ch] == 0 then return nil, "exponent reuse in block 0" end end if (cplinu and chexpstr[CPL] == 0) or (st.lfeon and chexpstr[LFE] == 0) then return nil, "exponent reuse in block 0" end end local endmant = st.endmant for ch = 1, nf do if chexpstr[ch] ~= 0 then if st.chincpl[ch] then endmant[ch] = cplstrt else local bw = bits(6) if bw > 60 then return nil, "bad channel bandwidth code" end endmant[ch] = 37 + 3 * (bw + 12) end end end endmant[LFE] = 7 if cplinu and chexpstr[CPL] ~= 0 then local abs = bits(4) * 2 local grp = EXPGRP[chexpstr[CPL]] if not exponents(st.exp[CPL], abs, (cplend - cplstrt) // grp, grp // 3, cplstrt) then return nil, "bad coupling exponents" end end for ch = 1, nf do local s = chexpstr[ch] if s ~= 0 then local grp = EXPGRP[s] local ngrps if s == 1 then ngrps = (endmant[ch] - 1) // 3 elseif s == 2 then ngrps = (endmant[ch] - 1 + 3) // 6 else ngrps = (endmant[ch] - 1 + 9) // 12 end local e = st.exp[ch] e[1] = bits(4) if not exponents(e, e[1], ngrps, grp // 3, 1) then return nil, "bad exponents" end bits(2) -- gainrng end end if st.lfeon and chexpstr[LFE] ~= 0 then local e = st.exp[LFE] e[1] = bits(4) if not exponents(e, e[1], 2, 1, 1) then return nil, "bad LFE exponents" end end if P > limit then return nil, "truncated block" end if bits(1) == 1 then st.sdcycod, st.fdcycod, st.sgaincod, st.dbpbcod, st.floorcod = bits(2), bits(2), bits(2), bits(2), bits(3) elseif blk == 0 then return nil, "no bit allocation parameters in block 0" end if bits(1) == 1 then st.csnroffst = bits(6) if cplinu then st.fsnroffst[CPL], st.fgaincod[CPL] = bits(4), bits(3) end for ch = 1, nf do st.fsnroffst[ch], st.fgaincod[ch] = bits(4), bits(3) end if st.lfeon then st.fsnroffst[LFE], st.fgaincod[LFE] = bits(4), bits(3) end elseif blk == 0 then return nil, "no SNR offsets in block 0" end if cplinu then if bits(1) == 1 then st.cplfleak, st.cplsleak = bits(3), bits(3) end end if bits(1) == 1 then local modes = table.create(7, 0) if cplinu then modes[CPL] = bits(2) end for ch = 1, nf do modes[ch] = bits(2) end if cplinu and modes[CPL] == 1 then readDba(st, CPL) end for ch = 1, nf do if modes[ch] == 1 then readDba(st, ch) end end for _, ch in { 1, 2, 3, 4, 5, CPL } do if modes[ch] == 1 then st.dbaOn[ch] = true elseif modes[ch] == 2 or modes[ch] == 3 then st.dbaOn[ch] = false end end elseif blk == 0 then for ch = 1, 7 do st.dbaOn[ch] = false end end if bits(1) == 1 then P += bits(9) * 8 end if P > limit then return nil, "truncated block" end local zero = st.csnroffst == 0 if zero then for ch = 1, nf do if st.fsnroffst[ch] ~= 0 then zero = false end end if (cplinu and st.fsnroffst[CPL] ~= 0) or (st.lfeon and st.fsnroffst[LFE] ~= 0) then zero = false end end @native local function alloc(ch: number, start: number, stop: number, isLfe: boolean) if zero then for i = start + 1, stop do st.bap[ch][i] = 0 end else local snr = ((st.csnroffst - 15) * 16 + st.fsnroffst[ch]) * 4 allocate(st, ch, start, stop, FASTGAIN[st.fgaincod[ch] + 1], snr, isLfe) end end if cplinu then alloc(CPL, cplstrt, cplend, false) end for ch = 1, nf do alloc(ch, 0, endmant[ch], false) end if st.lfeon then alloc(LFE, 0, 7, true) end n1, n2, n4 = 0, 0, 0 local gotCpl = false local coef = st.coef for ch = 1, nf do local c = coef[ch] mantissas(st, ch, 0, endmant[ch], c, st.dithflag[ch]) for i = endmant[ch] + 1, 256 do c[i] = 0 end if cplinu and st.chincpl[ch] and not gotCpl then mantissas(st, CPL, cplstrt, cplend, coef[CPL], false) gotCpl = true end if P > limit then return nil, "truncated block" end end if st.lfeon then local c = coef[LFE] mantissas(st, LFE, 0, 7, c, false) for i = 8, 256 do c[i] = 0 end end if P > limit then return nil, "truncated block" end -- decoupling (section 7.4): dither the coupling channel's zero-bit mantissas per channel if cplinu then local cc, cbap, cexp = coef[CPL], st.bap[CPL], st.exp[CPL] for ch = 1, nf do if st.chincpl[ch] then local c, co = coef[ch], st.cplco[ch] local dith = st.dithflag[ch] local flip = acmod == 2 and ch == 2 and st.phsflginu for sbnd = cplbegf, cplendf + 2 do local f = co[sbnd + 1] * 8 if flip and st.phsflg[sbnd + 1] then f = -f end for k = 37 + 12 * sbnd + 1, 37 + 12 * sbnd + 12 do local v = cc[k] if cbap[k] == 0 then v = if dith then dither(st) * POW2[cexp[k] + 1] else 0 end c[k] = v * f end end for k = cplend + 1, 256 do c[k] = 0 end end end end -- rematrixing (section 7.5) if acmod == 2 then local stop = if cplinu then cplstrt else min(endmant[1], endmant[2]) local l, r = coef[1], coef[2] local edges = { 13, 25, 37, 61, 253 } for rb = 1, 4 do if st.rematflg[rb] then for k = edges[rb] + 1, min(edges[rb + 1], stop) do local a, b = l[k], r[k] l[k], r[k] = a + b, a - b end end end end return true, nil end @native local function synth(st: State, ch: number, short: boolean, gain: number, out: { number }, base: number, step: number) local x, y, d, w = st.coef[ch], st.y, st.delay[ch], WINDOW if short then -- two 256-point transforms of the interleaved coefficients, phases alpha = -1 (n0 = 0) and +1 (n0 = N / 2) local z = st.psd Mdct.inverse(PLAN256, x, 1, 2, z, 1, -2 * gain) for n = 0, 63 do y[n + 1] = -z[n + 193] end for n = 64, 255 do y[n + 1] = z[n - 63] end Mdct.inverse(PLAN256, x, 2, 2, z, 1, -2 * gain) for n = 0, 191 do y[257 + n] = z[n + 65] end for n = 192, 255 do y[257 + n] = -z[n - 191] end else Mdct.inverse(PLAN512, x, 1, 1, y, 1, -2 * gain) end local p = base for n = 1, 256 do out[p] = y[n] * w[n] + d[n] d[n] = y[n + 256] * w[n + 256] p += step end end -- the output index of each slot (1 .. 5 full bandwidth, 6 LFE) in WAVE order: L R C LFE surrounds local ORDER: { [number]: { number } } = { [0] = { 1, 2 }, { 1 }, { 1, 2 }, { 1, 3, 2 }, { 1, 2, 3 }, { 1, 3, 2, 4 }, { 1, 2, 3, 4 }, { 1, 3, 2, 4, 5 }, } local HAS_C = { [0] = false, true, false, true, false, true, false, true } @native function Decode.frame(st: State, buf: buffer, len: number, drc: number): (number?, string?) if len < 8 or buffer.len(buf) < len + Decode.PAD then return nil, "truncated frame" end B, P = buf, 32 local fscod = bits(2) bits(6) local bsid = bits(5) if bsid > 8 then B = buffer.create(0) return nil, "unsupported: bsid " .. bsid .. (if bsid > 10 then " (E-AC-3)" else " (reduced sample rate)") end if fscod == 3 then B = buffer.create(0) return nil, "bad sample rate code" end bits(3) -- bsmod local acmod = bits(3) if band(acmod, 1) == 1 and acmod ~= 1 then bits(2) end if band(acmod, 4) ~= 0 then bits(2) end if acmod == 2 then bits(2) end local lfeon = bits(1) == 1 for _ = 1, if acmod == 0 then 2 else 1 do bits(5) if bits(1) == 1 then bits(8) end if bits(1) == 1 then bits(8) end if bits(1) == 1 then bits(7) end end bits(2) if bits(1) == 1 then bits(14) end if bits(1) == 1 then bits(14) end if bits(1) == 1 then P += (bits(6) + 1) * 8 end local nf = NFCHANS[acmod] local channels = nf + (if lfeon then 1 else 0) if st.acmod ~= acmod or st.lfeon ~= lfeon then local order = ORDER[acmod] local map = table.create(6, 0) local nfront = if HAS_C[acmod] then 3 elseif acmod == 1 then 1 else 2 for ch = 1, nf do local o = order[ch] map[ch] = if lfeon and o > nfront then o + 1 else o end if lfeon then map[LFE] = nfront + 1 end st.map = map st.pcm = table.create(1536 * channels, 0) Decode.reset(st) end st.fscod, st.acmod, st.lfeon, st.nfchans, st.channels, st.drc = fscod, acmod, lfeon, nf, channels, drc local pcm = st.pcm local limit = len * 8 - 16 -- crc2 for blk = 0, 5 do st.blocks[blk + 1] = P local ok, err = audblk(st, blk, limit) if not ok then B = buffer.create(0) return nil, err end local base = blk * 256 * channels for ch = 1, nf do local g = st.dynrng[if acmod == 0 and ch == 2 then 2 else 1] synth(st, ch, st.blksw[ch], g, pcm, base + st.map[ch], channels) end if lfeon then synth(st, LFE, false, st.dynrng[1], pcm, base + st.map[LFE], channels) end end B = buffer.create(0) return 1536, nil end return Decode end __FILES["codecs/audio/Ac3/Tables"] = function() -- codecs/audio/Ac3/Tables: transcribed from ATSC A/52:2018 section 7.2.3 (bit allocation tables) and section 5.4 (frame -- sizes); masktab is derived from bndtab / bndsz. No third-party code. local T = {} T.SLOWDEC = { 0x0f, 0x11, 0x13, 0x15 } T.FASTDEC = { 0x3f, 0x53, 0x67, 0x7b } T.SLOWGAIN = { 0x540, 0x4d8, 0x478, 0x410 } T.DBPBTAB = { 0x000, 0x700, 0x900, 0xb00 } T.FLOORTAB = { 0x2f0, 0x2b0, 0x270, 0x230, 0x1f0, 0x170, 0x0f0, 0xf800 } T.FASTGAIN = { 0x080, 0x100, 0x180, 0x200, 0x280, 0x300, 0x380, 0x400 } -- bit allocation bands: first bin and width (Table 7.12) T.BNDTAB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 31, 34, 37, 40, 43, 46, 49, 55, 61, 67, 73, 79, 85, 97, 109, 121, 133, 157, 181, 205, 229, } T.BNDSZ = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 12, 12, 12, 12, 24, 24, 24, 24, 24, } -- masktab (Table 7.13; bins 253 .. 255 map to 0) T.MASKTAB = table.create(256, 0) for b = 1, 50 do for k = T.BNDTAB[b], T.BNDTAB[b] + T.BNDSZ[b] - 1 do T.MASKTAB[k + 1] = b - 1 end end -- log-addition table (Table 7.14) T.LATAB = { 0x0040, 0x003f, 0x003e, 0x003d, 0x003c, 0x003b, 0x003a, 0x0039, 0x0038, 0x0037, 0x0036, 0x0035, 0x0034, 0x0034, 0x0033, 0x0032, 0x0031, 0x0030, 0x002f, 0x002f, 0x002e, 0x002d, 0x002c, 0x002c, 0x002b, 0x002a, 0x0029, 0x0029, 0x0028, 0x0027, 0x0026, 0x0026, 0x0025, 0x0024, 0x0024, 0x0023, 0x0023, 0x0022, 0x0021, 0x0021, 0x0020, 0x0020, 0x001f, 0x001e, 0x001e, 0x001d, 0x001d, 0x001c, 0x001c, 0x001b, 0x001b, 0x001a, 0x001a, 0x0019, 0x0019, 0x0018, 0x0018, 0x0017, 0x0017, 0x0016, 0x0016, 0x0015, 0x0015, 0x0015, 0x0014, 0x0014, 0x0013, 0x0013, 0x0013, 0x0012, 0x0012, 0x0012, 0x0011, 0x0011, 0x0011, 0x0010, 0x0010, 0x0010, 0x000f, 0x000f, 0x000f, 0x000e, 0x000e, 0x000e, 0x000d, 0x000d, 0x000d, 0x000d, 0x000c, 0x000c, 0x000c, 0x000c, 0x000b, 0x000b, 0x000b, 0x000b, 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x0009, 0x0009, 0x0009, 0x0009, 0x0009, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, } -- hearing threshold (Table 7.15): HTH[fscod + 1][band + 1] T.HTH = { { 0x04d0, 0x04d0, 0x0440, 0x0400, 0x03e0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0370, 0x0370, 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, 0x0340, 0x0390, 0x03e0, 0x0420, 0x0460, 0x0490, 0x04a0, 0x0460, 0x0440, 0x0440, 0x0520, 0x0800, 0x0840, 0x0840, }, { 0x04f0, 0x04f0, 0x0460, 0x0410, 0x03e0, 0x03d0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, 0x0370, 0x0370, 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0320, 0x0310, 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0320, 0x0350, 0x0390, 0x03e0, 0x0420, 0x0450, 0x04a0, 0x0490, 0x0460, 0x0440, 0x0480, 0x0630, 0x0840, 0x0840, }, { 0x0580, 0x0580, 0x04b0, 0x0450, 0x0420, 0x03f0, 0x03e0, 0x03d0, 0x03c0, 0x03b0, 0x03b0, 0x03b0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, 0x0370, 0x0360, 0x0350, 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, 0x0330, 0x0350, 0x03c0, 0x0410, 0x0470, 0x04a0, 0x0460, 0x0440, 0x0450, 0x04e0, }, } -- bit allocation pointers (Table 7.16) T.BAPTAB = { 0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, } -- words per syncframe (Table 5.18) for frmsizecod // 2 (the nominal bit rate in kbps) and fscod: 48 kHz = 2 x rate, -- 32 kHz = 3 x rate, 44.1 kHz = floor(rate x 1536000 / 705600) + (frmsizecod & 1) T.BITRATES = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640 } T.RATES = { 48000, 44100, 32000 } function T.frameWords(fscod: number, frmsizecod: number): number local kbps = T.BITRATES[frmsizecod // 2 + 1] if not kbps or fscod > 2 then return 0 end if fscod == 0 then return 2 * kbps elseif fscod == 2 then return 3 * kbps end return kbps * 1536000 // 705600 + frmsizecod % 2 end return T end __FILES["codecs/audio/Adpcm"] = @native function() -- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). -- ADX, PS-ADPCM and Nintendo DSP decoding follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt) bit-exactly: the -- ADX scale + 1 and version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024 rounding. local readu8, readi16, readu16, readi32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readi32 local writef32, readf32, writei32, writeu8, writeu16 = buffer.writef32, buffer.readf32, buffer.writei32, buffer.writeu8, buffer.writeu16 local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift local floor = math.floor local Adpcm = {} local IMA_STEP = { 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767, } local IMA_ADJ = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 } -- IMA_DIFF[index * 8 + (nibble & 7) + 1]: the shift-and-add difference (step/8 + bits of step/4, step/2, step), as -- the IMA reference computes it (not (2n + 1) * step / 8, which rounds differently) local IMA_DIFF = table.create(89 * 8, 0) -- IMA_NEXT[index * 16 + nibble + 1]: the next step index local IMA_NEXT = table.create(89 * 16, 0) for i = 0, 88 do local step = IMA_STEP[i + 1] for n = 0, 7 do local d = rshift(step, 3) if band(n, 1) ~= 0 then d += rshift(step, 2) end if band(n, 2) ~= 0 then d += rshift(step, 1) end if band(n, 4) ~= 0 then d += step end IMA_DIFF[i * 8 + n + 1] = d end for n = 0, 15 do IMA_NEXT[i * 16 + n + 1] = math.clamp(i + IMA_ADJ[n + 1], 0, 88) end end Adpcm.IMA_STEP = IMA_STEP -- IMA nibble q is in byte p + q // 2, the low half first unless hi @native function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number, hi: boolean, st: buffer, so: number, dst: buffer, d: number, ds: number) local pred = readi32(st, so) local index = math.clamp(readi32(st, so + 4), 0, 88) local q = q0 local o = d * 4 local os = ds * 4 for _ = 1, count do local b = readu8(src, p + rshift(q, 1)) local nib if (band(q, 1) == 0) == hi then nib = rshift(b, 4) else nib = band(b, 15) end local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] if nib >= 8 then pred -= diff if pred < -32768 then pred = -32768 end else pred += diff if pred > 32767 then pred = 32767 end end index = IMA_NEXT[index * 16 + nib + 1] writef32(dst, o, pred / 32768) o += os q += qs end writei32(st, so, pred) writei32(st, so + 4, index) end -- Apple ima4: 34 bytes: a big-endian header (the predictor's top 9 bits, 7-bit step index), 64 nibbles low first; -- Apple's decoders keep the full-precision predictor while the header agrees (same step index, within 127) @native function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer, d: number, ds: number) local h = readu8(src, p) * 256 + readu8(src, p + 1) local pred = band(h, 0xFF80) if pred >= 32768 then pred -= 65536 end local index = band(h, 0x7F) if index ~= readi32(st, so + 4) or math.abs(pred - readi32(st, so)) > 0x7F then writei32(st, so, pred) writei32(st, so + 4, index) end Adpcm.ima(src, p + 2, 0, 1, 64, false, st, so, dst, d, ds) end -- Microsoft IMA block: per channel s16 predictor (= the first sample), u8 step index, pad; then 4-byte groups -- (8 nibbles, low first) per channel in turn @native function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number): number if avail < 4 * ch then return 0 end local groups = (avail - 4 * ch) // (4 * ch) local frames = math.min(spb, 1 + groups * 8) local o = d * 4 for c = 0, ch - 1 do local pred = readi16(src, off + c * 4) local index = math.min(readu8(src, off + c * 4 + 2), 88) writef32(dst, o + c * 4, pred / 32768) local f = 1 local g = 0 while f < frames do local p = off + 4 * ch + (g * ch + c) * 4 local k = 0 while k < 8 and f < frames do local b = readu8(src, p + rshift(k, 1)) local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4) local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] if nib >= 8 then pred -= diff if pred < -32768 then pred = -32768 end else pred += diff if pred > 32767 then pred = 32767 end end index = IMA_NEXT[index * 16 + nib + 1] writef32(dst, o + (f * ch + c) * 4, pred / 32768) f += 1 k += 1 end g += 1 end end return frames end local MS_ADAPT = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 } Adpcm.MS_COEF1 = { 256, 512, 0, 192, 240, 460, 392 } Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 } -- MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for every channel -- in turn), then nibbles high first, channels interleaved per nibble; coefficients 256 = 1.0 @native function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number, coefs: buffer, ncoef: number, state: buffer): number local hdr = 7 * ch if avail < hdr or ncoef < 1 then return 0 end local frames = math.min(spb, 2 + ((avail - hdr) * 2) // ch) local o = d * 4 for c = 0, ch - 1 do local pi = math.min(readu8(src, off + c), ncoef - 1) local idelta = readi16(src, off + ch + c * 2) local s1 = readi16(src, off + 3 * ch + c * 2) local s2 = readi16(src, off + 5 * ch + c * 2) local so = c * 20 writei32(state, so, readi32(coefs, pi * 8)) writei32(state, so + 4, readi32(coefs, pi * 8 + 4)) writei32(state, so + 8, idelta) writei32(state, so + 12, s1) writei32(state, so + 16, s2) writef32(dst, o + c * 4, s2 / 32768) if frames > 1 then writef32(dst, o + (ch + c) * 4, s1 / 32768) end end local total = (frames - 2) * ch for k = 0, total - 1 do local b = readu8(src, off + hdr + rshift(k, 1)) local nib = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) local so = (k % ch) * 20 local c1, c2 = readi32(state, so), readi32(state, so + 4) local idelta = readi32(state, so + 8) local s1, s2 = readi32(state, so + 12), readi32(state, so + 16) local p = s1 * c1 + s2 * c2 p = if p >= 0 then p // 256 else -((-p) // 256) p += (if nib >= 8 then nib - 16 else nib) * idelta if p > 32767 then p = 32767 elseif p < -32768 then p = -32768 end idelta = (MS_ADAPT[nib + 1] * idelta) // 256 if idelta < 16 then idelta = 16 elseif idelta > 2796202 then -- INT_MAX / 768 idelta = 2796202 end writei32(state, so + 8, idelta) writei32(state, so + 12, p) writei32(state, so + 16, s1) writef32(dst, o + (2 * ch + k) * 4, p / 32768) end return frames end local F32 = buffer.create(4) @native local function f32(x: number): number writef32(F32, 0, x) return readf32(F32, 0) end -- coef1, coef2 (12 fractional bits): the 2-pole high-pass predictor from the header's cutoff, in single precision as -- CRI's decoders (and vgmstream) compute it @native function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number) if rate <= 0 then return 0, 0 end local z = f32(math.cos(f32(2 * math.pi * cutoff / rate))) local a = f32(math.sqrt(2) - z) local b = f32(math.sqrt(2) - 1) local c = f32(f32(a - f32(math.sqrt(f32(f32(a + b) * f32(a - b))))) / b) local c1 = c * 8192 local c2 = f32(c * c) * -4096 c1 = if c1 >= 0 then floor(c1) else -floor(-c1) c2 = if c2 >= 0 then floor(c2) else -floor(-c2) return c1, c2 end -- ADX frame: s16 big-endian scale, 32 nibbles high first. v3 shifts each product on its own; scale 0x8001 (CRI's end -- marker) decodes as silence @native function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1: number, c2: number, v3: boolean, st: buffer, so: number, dst: buffer, d: number, ds: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) local o = d * 4 local os = ds * 4 for f = 0, nframes - 1 do local fp = p + f * pstride local scale = readu8(src, fp) * 256 + readu8(src, fp + 1) if scale == 0x8001 then scale = 0 elseif scale >= 32768 then scale -= 65535 -- the signed value + 1 else scale += 1 end for k = 0, 31 do local b = readu8(src, fp + 2 + rshift(k, 1)) local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) if n >= 8 then n -= 16 end local s if v3 then s = n * scale + (c1 * h1) // 4096 + (c2 * h2) // 4096 else s = n * scale + (c1 * h1 + c2 * h2) // 4096 end if s > 32767 then s = 32767 elseif s < -32768 then s = -32768 end h2 = h1 h1 = s writef32(dst, o, s / 32768) o += os end end writei32(st, so, h1) writei32(st, so + 4, h2) end local PSX1 = { 0, 60, 115, 98, 122 } local PSX2 = { 0, 0, -52, -55, -60 } -- the filter term (c1 * h1 + c2 * h2) / 64 * 256 truncated, as vgmstream's single-precision float code computes it: -- exact in integers while the products fit a float's 24 bits @native local function psxPred(f: number, h1: number, h2: number): number local x = PSX1[f] * h1 + PSX2[f] * h2 if h1 > -65536 and h1 < 65536 and h2 > -65536 and h2 < 65536 then return 4 * x end local v = f32(f32(f32(PSX1[f] / 64) * h1) + f32(f32(PSX2[f] / 64) * h2)) * 256 return if v >= 0 then floor(v) else -floor(-v) end -- PS-ADPCM frame: filter << 4 | shift, flags, 28 nibbles low first. Filters past 4 decode as 0 and shifts past 12 as 9 -- (as vgmstream); flags 7 is silence; the history keeps the unclipped value @native function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st: buffer, so: number, dst: buffer, d: number, ds: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) local o = d * 4 local os = ds * 4 for f = 0, nframes - 1 do local fp = p + f * pstride local head = readu8(src, fp) local filter = rshift(head, 4) local shift = band(head, 15) if filter > 4 then filter = 0 end if shift > 12 then shift = 9 end local mul = 2 ^ (20 - shift) local fi = filter + 1 local silent = band(readu8(src, fp + 1), 15) == 7 for k = 0, 27 do local s = 0 if not silent then local b = readu8(src, fp + 2 + rshift(k, 1)) local n = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4) if n >= 8 then n -= 16 end s = (n * mul + psxPred(fi, h1, h2)) // 256 end h2 = h1 h1 = s if s > 32767 then s = 32767 elseif s < -32768 then s = -32768 end writef32(dst, o, s / 32768) o += os end end writei32(st, so, h1) writei32(st, so + 4, h2) end -- DSP frame: predictor << 4 | scale shift, 14 nibbles high first; coefs 8 pairs, 11 fractional bits; a predictor -- index past 7 uses pair 7 @native function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: number, st: buffer, so: number, dst: buffer, d: number, ds: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) local o = d * 4 local os = ds * 4 local done = 0 local fp = p while done < count do local head = readu8(src, fp) local pi = math.min(rshift(head, 4), 7) local scale = 2 ^ band(head, 15) * 2048 local c1, c2 = readi32(coefs, co + pi * 8), readi32(coefs, co + pi * 8 + 4) local n14 = math.min(14, count - done) for k = 0, n14 - 1 do local b = readu8(src, fp + 1 + rshift(k, 1)) local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) if n >= 8 then n -= 16 end local s = (n * scale + 1024 + c1 * h1 + c2 * h2) // 2048 if s > 32767 then s = 32767 elseif s < -32768 then s = -32768 end h2 = h1 h1 = s writef32(dst, o, s / 32768) o += os end done += n14 fp += 8 end writei32(st, so, h1) writei32(st, so + 4, h2) end @native local function toS16(x: number): number local v = floor(x * 32768 + 0.5) if v ~= v then return 0 elseif v > 32767 then return 32767 elseif v < -32768 then return -32768 end return v end Adpcm.toS16 = toS16 @native local function imaNibble(x: number, pred: number, index: number): number local base = index * 8 + 1 local best, bestErr = 0, math.huge for m = 0, 7 do local diff = IMA_DIFF[base + m] local up = math.min(pred + diff, 32767) local e = math.abs(x - up) if e < bestErr then best, bestErr = m, e end local down = math.max(pred - diff, -32768) e = math.abs(x - down) if e < bestErr then best, bestErr = m + 8, e end end return best end @native function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, p: number, q0: number, qs: number, hi: boolean) local pred = readi32(st, so) local index = math.clamp(readi32(st, so + 4), 0, 88) local q = q0 for i = 0, count - 1 do local v = toS16(readf32(x, (xi + i * xs) * 4)) local nib = imaNibble(v, pred, index) local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767) index = IMA_NEXT[index * 16 + nib + 1] local bp = p + rshift(q, 1) local b = readu8(out, bp) if (band(q, 1) == 0) == hi then b = bor(band(b, 0x0F), lshift(nib, 4)) else b = bor(band(b, 0xF0), nib) end writeu8(out, bp, b) q += qs end writei32(st, so, pred) writei32(st, so + 4, index) end -- Microsoft IMA block: spb = 1 + 8k frames, 4 * ch + (spb - 1) / 2 * ch bytes @native function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: number, st: buffer, out: buffer, off: number) local groups = (spb - 1) // 8 for c = 0, ch - 1 do local so = c * 8 local first = if n > 0 then toS16(readf32(x, (xf * ch + c) * 4)) else 0 writei32(st, so, first) local index = math.clamp(readi32(st, so + 4), 0, 88) writei32(st, so + 4, index) buffer.writei16(out, off + c * 4, first) writeu8(out, off + c * 4 + 2, index) writeu8(out, off + c * 4 + 3, 0) local pred = first for g = 0, groups - 1 do local gp = off + 4 * ch + (g * ch + c) * 4 for k = 0, 7 do local f = 1 + g * 8 + k local v = if f < n then toS16(readf32(x, ((xf + f) * ch + c) * 4)) else pred local nib = imaNibble(v, pred, index) local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767) index = IMA_NEXT[index * 16 + nib + 1] local bp = gp + rshift(k, 1) if band(k, 1) == 0 then writeu8(out, bp, nib) else writeu8(out, bp, bor(readu8(out, bp), lshift(nib, 4))) end end end writei32(st, so + 4, index) end end @native local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0: number, nibs: { number }?): number local s1, s2 = xs[2], xs[1] local idelta = delta0 local err = 0 for i = 3, n do local p = s1 * c1 + s2 * c2 p = if p >= 0 then p // 256 else -((-p) // 256) local e = xs[i] - p local nib = if e >= 0 then (e + idelta // 2) // idelta else -((-e + idelta // 2) // idelta) nib = math.clamp(nib, -8, 7) local v = math.clamp(p + nib * idelta, -32768, 32767) err += (xs[i] - v) * (xs[i] - v) if nibs then nibs[i] = band(nib, 15) end idelta = math.clamp((MS_ADAPT[band(nib, 15) + 1] * idelta) // 256, 16, 2796202) s2 = s1 s1 = v end return err end -- MS ADPCM block (standard 7 coefficient pairs): 7 * ch + (spb - 2) * ch / 2 bytes @native function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: number, out: buffer, off: number) local C1, C2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 local xs = table.create(spb, 0) local nibs = table.create(spb, 0) local all = table.create(spb * ch, 0) for c = 0, ch - 1 do for i = 1, spb do xs[i] = if i <= n then toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) else 0 end local sum = 0 for i = 3, math.min(spb, 10) do sum += math.abs(xs[i] - xs[i - 1]) end local delta0 = math.clamp(sum // 16, 16, 32767) local best, bestErr = 1, math.huge for k = 1, 7 do local e = msTrial(xs, spb, C1[k], C2[k], delta0, nil) if e < bestErr then best, bestErr = k, e end end msTrial(xs, spb, C1[best], C2[best], delta0, nibs) writeu8(out, off + c, best - 1) writeu16(out, off + ch + c * 2, delta0) buffer.writei16(out, off + 3 * ch + c * 2, xs[2] or 0) buffer.writei16(out, off + 5 * ch + c * 2, xs[1]) for i = 3, spb do all[(i - 3) * ch + c + 1] = nibs[i] end end local total = (spb - 2) * ch for k = 0, total - 1, 2 do writeu8(out, off + 7 * ch + k // 2, all[k + 1] * 16 + (all[k + 2] or 0)) end end @native local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h1: number, h2: number, nibs: { number }?): (number, number, number) local err = 0 for k = 1, 32 do local pred = (c1 * h1 + c2 * h2) // 4096 local e = xs[k] - pred local n = if e >= 0 then (e + scale // 2) // scale else -((-e + scale // 2) // scale) n = math.clamp(n, -8, 7) local s = math.clamp(n * scale + pred, -32768, 32767) err += (xs[k] - s) * (xs[k] - s) if nibs then nibs[k] = band(n, 15) end h2 = h1 h1 = s end return err, h1, h2 end -- ADX v4 rounding; the scale is stored minus one as CRI's decoders add it back -- (v4 rounding, the scale stored minus one as CRI's decoders add it back) at out[p], pstride bytes apart; the frame @native function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: number, c2: number, st: buffer, so: number, out: buffer, p: number, pstride: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) local v = table.create(32, 0) local nibs = table.create(32, 0) for f = 0, (count + 31) // 32 - 1 do local peak = 0 local a, b = h1, h2 for k = 1, 32 do local i = f * 32 + k - 1 local s = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0 v[k] = s peak = math.max(peak, math.abs(s - (c1 * a + c2 * b) // 4096)) b = a a = s end local base = math.max(1, (peak + 6) // 7) local best, bestErr = base, math.huge for _, m in { 1, 0.75, 1.25, 0.5, 1.6 } do local sc = math.clamp(floor(base * m + 0.5), 1, 0x7FFF) local e = adxTrial(v, sc, c1, c2, h1, h2, nil) if e < bestErr then best, bestErr = sc, e end end local _, n1, n2 = adxTrial(v, best, c1, c2, h1, h2, nibs) h1, h2 = n1, n2 local fp = p + f * pstride writeu8(out, fp, rshift(best - 1, 8)) writeu8(out, fp + 1, band(best - 1, 255)) for k = 0, 15 do writeu8(out, fp + 2 + k, nibs[k * 2 + 1] * 16 + nibs[k * 2 + 2]) end end writei32(st, so, h1) writei32(st, so + 4, h2) end @native function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, p: number, pstride: number) local h1, h2 = readi32(st, so), readi32(st, so + 4) local v = table.create(28, 0) local nibs = table.create(28, 0) for f = 0, (count + 27) // 28 - 1 do for k = 1, 28 do local i = f * 28 + k - 1 v[k] = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0 end local bestErr, bestHead = math.huge, 0 for fi = 1, 5 do for shift = 0, 12 do local mul = 2 ^ (20 - shift) local a, b = h1, h2 local err = 0 for k = 1, 28 do local pred = psxPred(fi, a, b) local n = floor((v[k] * 256 - pred) / mul + 0.5) n = if n > 7 then 7 elseif n < -8 then -8 else n local s = (n * mul + pred) // 256 local c = if s > 32767 then 32767 elseif s < -32768 then -32768 else s err += (v[k] - c) * (v[k] - c) if err >= bestErr then break end b = a a = s end if err < bestErr then bestErr, bestHead = err, (fi - 1) * 16 + shift end end end local fi, shift = rshift(bestHead, 4) + 1, band(bestHead, 15) local mul = 2 ^ (20 - shift) for k = 1, 28 do local pred = psxPred(fi, h1, h2) local n = math.clamp(floor((v[k] * 256 - pred) / mul + 0.5), -8, 7) nibs[k] = band(n, 15) h2 = h1 h1 = (n * mul + pred) // 256 end local fp = p + f * pstride writeu8(out, fp, bestHead) writeu8(out, fp + 1, 0) for k = 0, 13 do writeu8(out, fp + 2 + k, nibs[k * 2 + 1] + nibs[k * 2 + 2] * 16) end end writei32(st, so, h1) writei32(st, so + 4, h2) end -- ModPlug / OpenMPT ADPCM (sample data marked 0xAD): 16 signed byte deltas, then nibbles low first, each adding its -- delta to a wrapping signed byte; value / 128 @native function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: number) local tab = table.create(16, 0) for k = 0, 15 do tab[k + 1] = buffer.readi8(src, p + k) end local v = 0 for i = 0, count - 1 do local b = readu8(src, p + 16 + rshift(i, 1)) local nib = if band(i, 1) == 0 then band(b, 15) else rshift(b, 4) v = (v + tab[nib + 1] + 128) % 256 - 128 writef32(dst, (d + i) * 4, v / 128) end end -- The SWF / FLV ADPCM (SoundFormat 1, Adobe's SWF specification, "ADPCM compression"): an MSB-first bit stream of -- 2 bits (code size - 2), then blocks of 4096 frames: per channel a signed 16-bit first sample and a 6-bit step -- index, then 4095 frames of `bits`-bit codes, channels interleaved. A code is IMA generalised to 2..5 bits: sign in -- the top bit, the magnitude bits adding step, step/2, ... and the final step/2^(bits-1) (as ffmpeg's adpcm_swf and -- the spec's reference decoder do); the step index moves by SWF_INDEX[bits]. The last block may be short. local SWF_INDEX: { { number } } = { { -1, 2 }, { -1, -1, 2, 4 }, { -1, -1, -1, -1, 2, 4, 6, 8 }, { -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 }, } @native function Adpcm.swfFrames(src: buffer, p: number, n: number, ch: number): number if n < 1 or ch < 1 then return 0 end local bits = rshift(readu8(src, p), 6) + 2 local total = n * 8 - 2 local hdr = 22 * ch local block = hdr + bits * ch * 4095 local blocks = total // block local left = total - blocks * block local frames = blocks * 4096 if left >= hdr then frames += 1 + (left - hdr) // (bits * ch) end return frames end @native local function msb(src: buffer, p: number, e: number, pos: number, k: number): number local q = p + rshift(pos, 3) local v = readu8(src, q) * 65536 if q + 1 < e then v += readu8(src, q + 1) * 256 end if q + 2 < e then v += readu8(src, q + 2) end return band(rshift(v, 24 - band(pos, 7) - k), lshift(1, k) - 1) end @native function Adpcm.swf(src: buffer, p: number, n: number, ch: number, dst: buffer, d: number): number local frames = Adpcm.swfFrames(src, p, n, ch) if frames == 0 then return 0 end local e = p + n local bits = rshift(readu8(src, p), 6) + 2 local tab = SWF_INDEX[bits - 1] local k0 = lshift(1, bits - 2) local sign = lshift(1, bits - 1) local mask = sign - 1 local pred = table.create(ch, 0) local index = table.create(ch, 0) local pos = 2 local o = d * 4 local done = 0 while done < frames do for c = 1, ch do local v = msb(src, p, e, pos, 16) if v >= 32768 then v -= 65536 end pred[c] = v index[c] = msb(src, p, e, pos + 16, 6) pos += 22 writef32(dst, o, v / 32768) o += 4 end done += 1 local m = math.min(4095, frames - done) for _ = 1, m do for c = 1, ch do local code = msb(src, p, e, pos, bits) pos += bits local step = IMA_STEP[math.clamp(index[c], 0, 88) + 1] local diff = 0 local k = k0 while k > 0 do if band(code, k) ~= 0 then diff += step end step = rshift(step, 1) k = rshift(k, 1) end diff += step local v = pred[c] if band(code, sign) ~= 0 then v -= diff else v += diff end v = math.clamp(v, -32768, 32767) pred[c] = v index[c] = math.clamp(index[c] + tab[band(code, mask) + 1], 0, 88) writef32(dst, o, v / 32768) o += 4 end end done += m end return frames end return Adpcm end __FILES["codecs/audio/Adpcm/Decoder"] = function() -- codecs/audio/Adpcm/Decoder: the streaming Types.Decoder over packetised ADPCM (ADX, VAG, BRSTM, raw IMA) with exact seeking. -- New in rosetta. local Err = __include("core/Err") local Stream = __include("codecs/audio/Stream") local Adpcm = __include("codecs/audio/Adpcm") local Decoder = {} type Spec = { count: number, packetFrames: number, frames: number, state: buffer, decode: (i: number, out: buffer) -> (number?, Err.Err?), restore: ((i: number) -> boolean)?, } function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?) local ch = dec.channels local pf = spec.packetFrames local st = spec.state local out = buffer.create(pf * ch * 4) local decodeP = spec.decode local restore = spec.restore local snaps: { [number]: buffer } = {} local nextPacket = 1 local function snap(i: number) if not snaps[i] then local b = buffer.create(buffer.len(st)) buffer.copy(b, 0, st) snaps[i] = b end end snap(1) local function decode(i: number): (number?, Err.Err?) if i ~= nextPacket then if snaps[i] then buffer.copy(st, 0, snaps[i]) elseif restore and restore(i) then else local j = i - 1 while j > 1 and not snaps[j] do j -= 1 end buffer.copy(st, 0, snaps[j]) for k = j, i - 1 do local n, e = decodeP(k, out) if not n then return nil, e end snap(k + 1) end end end local n, e = decodeP(i, out) if n then nextPacket = i + 1 snap(i + 1) end return n, e end return Stream.packets(dec, { count = spec.count, start = function(i: number): number return (i - 1) * pf end, decode = decode, pcm = function(): buffer return out end, reset = function() end, stop = spec.frames, }) end local FRAME: { [string]: number } = { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame local SPF: { [string]: number } = { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer, d: number, ds: number) if kind == "s8" then for k = 0, n - 1 do buffer.writef32(dst, (d + k * ds) * 4, buffer.readi8(src, p + k) / 128) end elseif kind == "s16le" then for k = 0, n - 1 do buffer.writef32(dst, (d + k * ds) * 4, buffer.readi16(src, p + k * 2) / 32768) end else for k = 0, n - 1 do local v = buffer.readu8(src, p + k * 2) * 256 + buffer.readu8(src, p + k * 2 + 1) buffer.writef32(dst, (d + k * ds) * 4, (if v >= 32768 then v - 65536 else v) / 32768) end end end type InterleavedSpec = { kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", buf: buffer, offset: number, size: number, interleave: number, lastInterleave: number?, -- bytes per channel in the last row (BRSTM's padded last block), default interleave frames: number?, c1: number?, c2: number?, v3: boolean?, coefs: buffer?, -- dsp: 16 i32 per channel hist: { number }?, restore: ((row: number, st: buffer) -> boolean)?, -- the exact history at the start of a row (BRSTM ADPC) } function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?) local ch = dec.channels local kind = spec.kind local fsize, spf = FRAME[kind], SPF[kind] local il = spec.interleave local last = spec.lastInterleave or il if not fsize or ch < 1 or il < fsize or il % fsize ~= 0 or last < 0 or last > il then return nil, Err.new(Err.CORRUPT, "bad interleave " .. tostring(il)) end local buf, base, size = spec.buf, spec.offset, spec.size local rowBytes = il * ch local rows = math.max(1, math.ceil(size / rowBytes)) local function rowFrames(r: number): number local width = if r == rows - 1 then last else il -- channel c sits at c * width in the row: the last channel is the one a cut file shortens local per = math.clamp(size - r * rowBytes - (ch - 1) * width, 0, width) return (per // fsize) * spf end local fullFrames = (il // fsize) * spf local total = (rows - 1) * fullFrames + rowFrames(rows - 1) local frames = math.min(spec.frames or total, total) local st = buffer.create(8 * ch) if spec.hist then for c = 0, ch - 1 do buffer.writei32(st, c * 8, spec.hist[c * 2 + 1] or 0) buffer.writei32(st, c * 8 + 4, spec.hist[c * 2 + 2] or 0) end end local rowsPer = if spec.restore then 1 else math.max(1, 4096 // fullFrames) local pf = rowsPer * fullFrames local c1, c2, v3, coefs = spec.c1 or 0, spec.c2 or 0, spec.v3 == true, spec.coefs local restore = spec.restore dec.frames = frames dec.duration = frames / dec.sampleRate return Decoder.packets(dec, { count = math.max(1, math.ceil(frames / pf)), packetFrames = pf, frames = frames, state = st, restore = if restore then function(i: number): boolean return restore(i - 1, st) end else nil, decode = function(i: number, out: buffer): (number?, Err.Err?) local got = 0 for r = (i - 1) * rowsPer, math.min(i * rowsPer, rows) - 1 do local n = math.min(rowFrames(r), frames - r * fullFrames) if n <= 0 then break end local nf = math.ceil(n / spf) local width = if r == rows - 1 then last else il for c = 0, ch - 1 do local p = base + r * rowBytes + c * width local d = got * ch + c if kind == "psx" then Adpcm.psx(buf, p, fsize, nf, st, c * 8, out, d, ch) elseif kind == "adx" then Adpcm.adx(buf, p, fsize, nf, c1, c2, v3, st, c * 8, out, d, ch) elseif kind == "dsp" then Adpcm.dsp(buf, p, n, coefs :: buffer, c * 64, st, c * 8, out, d, ch) else pcm(kind, buf, p, n, out, d, ch) end end got += n end return got, nil end, }) end type NibbleSpec = { buf: buffer, offset: number, size: number, hi: boolean?, -- the high nibble first (DVI / KVAG); default low first frames: number?, } -- IMA from predictor 0, step index 0; channel c in nibbles c, c + ch, ... function Decoder.nibbles(dec: any, spec: NibbleSpec): (any, Err.Err?) local ch = dec.channels local buf, base = spec.buf, spec.offset local frames = math.min(spec.frames or math.huge, (spec.size * 2) // ch) local st = buffer.create(8 * ch) local hi = spec.hi == true dec.frames = frames dec.duration = frames / dec.sampleRate return Decoder.packets(dec, { count = math.max(1, math.ceil(frames / 4096)), packetFrames = 4096, frames = frames, state = st, decode = function(i: number, out: buffer): (number?, Err.Err?) local f0 = (i - 1) * 4096 local n = math.min(4096, frames - f0) for c = 0, ch - 1 do Adpcm.ima(buf, base, f0 * ch + c, ch, n, hi, st, c * 8, out, c, ch) end return n, nil end, }) end type BlockSpec = { kind: "ms" | "ima_wav" | "ima_qt", buf: buffer, offset: number, size: number, blockAlign: number?, frames: number?, coefs: { number }?, -- ms: coefficient pairs, flat (default the 7 standard pairs) } function Decoder.blockFrames(kind: string, ba: number, ch: number): number? if kind == "ima_qt" then return 64 elseif kind == "ms" then return if ba >= 7 * ch then (ba - 7 * ch) * 2 // ch + 2 else nil end return if ba >= 4 * ch then (ba - 4 * ch) * 2 // ch + 1 else nil end function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?) local ch = dec.channels local kind = spec.kind local ba = if kind == "ima_qt" then 34 * ch else spec.blockAlign or 0 local spb = Decoder.blockFrames(kind, ba, ch) if not spb then return nil, Err.new(Err.CORRUPT, "block of " .. ba .. " bytes is too small") end if spb * ch > 2 ^ 20 then return nil, Err.new(Err.LIMIT, "ADPCM block too large") end local buf, base, size = spec.buf, spec.offset, spec.size local full = size // ba local rest = size - full * ba local total = full * spb if kind ~= "ima_qt" and rest > 0 then if kind == "ms" then total += if rest >= 7 * ch then math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) else 0 elseif rest >= 4 * ch then total += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8) end end local frames = math.min(spec.frames or total, total) local ncoef = 7 local cf = spec.coefs if cf and #cf >= 2 then ncoef = math.min(256, #cf // 2) end local coefs = buffer.create(ncoef * 8) for k = 0, ncoef - 1 do buffer.writei32(coefs, k * 8, if cf and #cf >= 2 then cf[k * 2 + 1] else Adpcm.MS_COEF1[k + 1]) buffer.writei32(coefs, k * 8 + 4, if cf and #cf >= 2 then cf[k * 2 + 2] else Adpcm.MS_COEF2[k + 1]) end local scratch = buffer.create(20 * ch) dec.frames = frames dec.duration = frames / dec.sampleRate dec.blockAlign = ba dec.samplesPerBlock = spb return Decoder.packets(dec, { count = math.max(1, math.ceil(frames / spb)), packetFrames = spb, frames = frames, state = scratch, decode = function(i: number, out: buffer): (number?, Err.Err?) local off = base + (i - 1) * ba local avail = math.min(ba, base + size - off) if kind == "ms" then return Adpcm.msBlock(buf, off, avail, ch, spb, out, 0, coefs, ncoef, scratch), nil elseif kind == "ima_wav" then return Adpcm.imaWav(buf, off, avail, ch, spb, out, 0), nil end if avail < ba then return 0, nil end for c = 0, ch - 1 do Adpcm.imaQt(buf, off + c * 34, scratch, c * 8, out, c, ch) end return 64, nil end, }) end return Decoder end __FILES["codecs/audio/Alac"] = function() -- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder. -- Written from the ALAC format as Apple published it; no third-party code. ALAC stores C L R ... for 3+ channels; the -- API uses WAV order. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Decode = __include("codecs/audio/Alac/Decode") local Encode = __include("codecs/audio/Alac/Encode") local Alac = {} type Config = { frameLength: number, compatibleVersion: number, bitDepth: number, pb: number, mb: number, kb: number, channels: number, maxRun: number, maxFrameBytes: number, avgBitRate: number, sampleRate: number, } local TO_WAV: { { number } } = { { 1 }, { 1, 2 }, { 3, 1, 2 }, { 3, 1, 2, 4 }, { 3, 1, 2, 4, 5 }, { 3, 1, 2, 5, 6, 4 }, { 3, 1, 2, 5, 6, 7, 4 }, { 3, 7, 8, 1, 2, 5, 6, 4 }, } local ELEMENTS: { { number } } = { { 1 }, { 2 }, { 1, 2 }, { 1, 2, 1 }, { 1, 2, 2 }, { 1, 2, 2, 1 }, { 1, 2, 2, 1, 1 }, { 1, 2, 2, 2, 1 }, } Alac.TO_WAV = TO_WAV function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, Err.Err?) local r = Bytes.reader(buf, offset, length) -- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie for _ = 1, 2 do local typ = r:peek(4, 4) if typ == "frma" then r:skip(12) elseif typ == "alac" then r:skip(12) end end if r:remaining() < 24 then return nil, Err.new(Err.TRUNCATED, "ALAC configuration is shorter than 24 bytes") end local c: Config = { frameLength = r:u32be(), compatibleVersion = r:u8(), bitDepth = r:u8(), pb = r:u8(), mb = r:u8(), kb = r:u8(), channels = r:u8(), maxRun = r:u16be(), maxFrameBytes = r:u32be(), avgBitRate = r:u32be(), sampleRate = r:u32be(), } if c.compatibleVersion ~= 0 then return nil, Err.new(Err.UNSUPPORTED, "ALAC version " .. c.compatibleVersion) end if c.frameLength < 1 or c.frameLength > 65536 then return nil, Err.new(Err.CORRUPT, "bad ALAC frame length " .. c.frameLength) end if c.bitDepth ~= 16 and c.bitDepth ~= 20 and c.bitDepth ~= 24 and c.bitDepth ~= 32 then return nil, Err.new(Err.UNSUPPORTED, "ALAC bit depth " .. c.bitDepth) end if c.channels < 1 or c.channels > 8 then return nil, Err.new(Err.UNSUPPORTED, "ALAC with " .. c.channels .. " channels") end if c.kb < 1 or c.kb > 24 then return nil, Err.new(Err.CORRUPT, "bad ALAC rice limit " .. c.kb) end return c, nil end function Alac.cookie(c: Config): buffer local w = Bytes.writer(24) w:u32be(c.frameLength) w:u8(0) w:u8(c.bitDepth) w:u8(c.pb) w:u8(c.mb) w:u8(c.kb) w:u8(c.channels) w:u16be(c.maxRun) w:u32be(c.maxFrameBytes) w:u32be(c.avgBitRate) w:u32be(c.sampleRate) return w:finish() end type Decoder = { config: Config, pcm: { number }, decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), state: Decode.State, } local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) local o = offset or 0 local n = length or (buffer.len(buf) - o) if o < 0 or n < 0 or o + n > buffer.len(buf) then return nil, Err.new(Err.ARG, "packet range out of the buffer") end local frames, msg = Decode.frame(self.state, buf, o, n) if not frames then return nil, Err.new(Err.CORRUPT, msg or "bad packet", o) end local ch = self.config.channels local src, dst = self.state.out, self.pcm if ch <= 2 then for i = 1, frames * ch do dst[i] = src[i] end else local map = TO_WAV[ch] for f = 0, frames - 1 do local base = f * ch for k = 1, ch do dst[base + map[k]] = src[base + k] end end end return frames, nil end function Alac.decoder(cfg: Config): Decoder return { config = cfg, pcm = table.create(cfg.frameLength * cfg.channels, 0), decode = decode, state = Decode.state(cfg), } end type Encoder = { config: Config, encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?), state: Encode.State, bytes: number, frames: number, } local function encode(self: Encoder, samples: { number }, first: number, frames: number): (buffer?, Err.Err?) local cfg = self.config if type(samples) ~= "table" or frames < 1 or frames > cfg.frameLength or frames % 1 ~= 0 then return nil, Err.new(Err.ARG, "encode: 1 .. " .. cfg.frameLength .. " frames of interleaved integer samples") end if first < 1 or first + frames * cfg.channels - 1 > #samples then return nil, Err.new(Err.ARG, "encode: the samples end early") end local ch = cfg.channels local pkt = Encode.frame(self.state, samples, first, frames, TO_WAV[ch], ELEMENTS[ch]) local n = buffer.len(pkt) self.bytes += n self.frames += frames if n > cfg.maxFrameBytes then cfg.maxFrameBytes = n end if self.frames > 0 then cfg.avgBitRate = math.floor(self.bytes * 8 * cfg.sampleRate / self.frames) end return pkt, nil end type EncoderOptions = { sampleRate: number, channels: number, bitDepth: number?, frameLength: number?, } function Alac.encoder(opts: EncoderOptions): (Encoder?, Err.Err?) if type(opts) ~= "table" then return nil, Err.new(Err.ARG, "encoder: expected options") end local depth = opts.bitDepth or 16 local ch = opts.channels if depth ~= 16 and depth ~= 20 and depth ~= 24 then return nil, Err.new(Err.ARG, "encoder: bitDepth 16, 20 or 24") end if type(ch) ~= "number" or ch < 1 or ch > 8 or ch % 1 ~= 0 then return nil, Err.new(Err.ARG, "encoder: 1 .. 8 channels") end local sr = opts.sampleRate if type(sr) ~= "number" or sr < 1 or sr % 1 ~= 0 then return nil, Err.new(Err.ARG, "encoder: bad sampleRate") end local fl = opts.frameLength or 4096 if fl < 16 or fl > 16384 or fl % 1 ~= 0 then return nil, Err.new(Err.ARG, "encoder: frameLength 16 .. 16384") end local cfg: Config = { frameLength = fl, compatibleVersion = 0, bitDepth = depth, pb = 40, mb = 10, kb = 14, channels = ch, maxRun = 255, maxFrameBytes = 0, avgBitRate = 0, sampleRate = sr, } return { config = cfg, encode = encode, state = Encode.state(cfg), bytes = 0, frames = 0, }, nil end return Alac end __FILES["codecs/audio/Alac/Decode"] = @native function() -- codecs/audio/Alac/Decode: the ALAC frame decoder (SCE / CPE / LFE / DSE / FIL / END elements). -- Written from the ALAC format as published by Apple (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). local readu32, readu8 = buffer.readu32, buffer.readu8 local byteswap, lshift, rshift, band, countlz, bnot = bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band, bit32.countlz, bit32.bnot local floor = math.floor local Decode = {} type State = { frameLength: number, bitDepth: number, pb: number, mb: number, kb: number, channels: number, maxRun: number, scratch: buffer, -- the packet + 16 zero bytes (reads past the end are safe; the overrun is checked) pred: { { number } }, mix: { { number } }, shift: { number }, out: { number }, } local POW = table.create(64, 0) for i = 0, 63 do POW[i + 1] = 2 ^ i end @native local function bitsAt(b: buffer, pos: number, n: number): number local w = byteswap(readu32(b, rshift(pos, 3))) return rshift(lshift(w, band(pos, 7)), 32 - n) end @native local function signExtend(v: number, bits: number): number local m = POW[bits + 1] v = v % m if v >= m / 2 then v -= m end return v end -- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits @native local function scalar(b: buffer, pos: number, k: number, m: number, bps: number): (number, number) local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7)) local pre = countlz(bnot(w)) if pre >= 9 then pos += 9 local v if bps > 25 then v = bitsAt(b, pos, bps - 16) * 65536 + bitsAt(b, pos + bps - 16, 16) else v = bitsAt(b, pos, bps) end return v, pos + bps end pos += pre + 1 if k == 1 then return pre, pos end local v = bitsAt(b, pos, k) local x = pre * m if v > 1 then return x + v - 1, pos + k end return x, pos + k - 1 end @native local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number local history = st.mb local kb = st.kb local signMod = 0 local i = 1 while i <= n do if pos > limit then return -1 -- each value reads at most 41 bits past here: inside the 16 padding bytes end local k = 31 - countlz(floor(history / 512) + 3) if k > kb then k = kb end local x x, pos = scalar(b, pos, k, POW[k + 1] - 1, bps) x += signMod signMod = 0 out[i] = if x % 2 == 0 then x / 2 else -(x + 1) / 2 if x > 0xFFFF then history = 0xFFFF else history += x * mult - floor(history * mult / 512) end if history < 128 and i < n then if pos > limit then return -1 end local lg = if history > 0 then 31 - countlz(history) else 0 k = 7 - lg + floor((history + 16) / 64) if k > kb then k = kb end local run run, pos = scalar(b, pos, k, POW[k + 1] - 1, 16) if run > 0 then if run > n - i then return -1 end for j = i + 1, i + run do out[j] = 0 end i += run end if run < 0xFFFF then signMod = 1 -- the next value is not 0 (unless the run hit its maximum) end history = 0 end i += 1 end return pos end @native local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) out[1] = err[1] if n <= 1 then return end if order == 0 then if out ~= err then for i = 2, n do out[i] = err[i] end end return end if order == 31 then for i = 2, n do out[i] = signExtend(out[i - 1] + err[i], bps) end return end local i = 2 while i <= order + 1 and i <= n do out[i] = signExtend(out[i - 1] + err[i], bps) i += 1 end local half = if quant > 0 then POW[quant] else 0 local qd = POW[quant + 1] -- coefs[1] multiplies the most recent sample while i <= n do local d = out[i - order - 1] local val = 0 for j = 1, order do val += (out[i - j] - d) * coefs[j] end val = floor((val + half) / qd) local e = err[i] out[i] = signExtend(val + d + e, bps) if e ~= 0 then local es = if e > 0 then 1 else -1 -- adapt from the oldest sample to the newest while the error keeps its sign for j = order, 1, -1 do if e * es <= 0 then break end local v = d - out[i - j] local sgn = if v > 0 then es elseif v < 0 then -es else 0 coefs[j] -= sgn e -= floor(v * sgn / qd) * (order - j + 1) end end i += 1 end end @native function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) if len <= 0 then return nil, "empty packet" end local b = st.scratch if buffer.len(b) < len + 16 then b = buffer.create(len + 64) st.scratch = b end buffer.copy(b, 0, buf, off, len) buffer.fill(b, len, 0, 16) local limit = len * 8 local pos = 0 local channels = st.channels local ch = 0 local frames = -1 local out = st.out while true do if pos + 3 > limit then return nil, "frame runs past the end" end local tag = bitsAt(b, pos, 3) pos += 3 if tag == 7 then -- END break elseif tag == 0 or tag == 1 or tag == 3 then -- SCE / CPE / LFE local nch = if tag == 1 then 2 else 1 if ch + nch > channels then return nil, "more channels than the configuration" end pos += 4 -- element instance tag if bitsAt(b, pos, 12) ~= 0 then return nil, "bad element header" end pos += 12 local h = bitsAt(b, pos, 4) pos += 4 local partial = rshift(h, 3) local shiftBytes = band(rshift(h, 1), 3) local escape = band(h, 1) if shiftBytes == 3 then return nil, "bad shift" end local n = st.frameLength if partial == 1 then n = bitsAt(b, pos, 16) * 65536 + bitsAt(b, pos + 16, 16) pos += 32 end if n < 1 or n > st.frameLength then return nil, "bad frame length " .. n end if frames >= 0 and n ~= frames then return nil, "elements of different lengths" end frames = n if #out < n * channels then for k = #out + 1, n * channels do out[k] = 0 end end local shift = shiftBytes * 8 local bps = st.bitDepth - shift + nch - 1 if bps > 32 or bps < 1 then return nil, "bad sample size" end if pos > limit then return nil, "frame runs past the end" end local mixBits, mixRes = 0, 0 local p0, p1 = st.pred[1], st.pred[2] local m0, m1 = st.mix[1], st.mix[2] local shiftBuf = st.shift if escape == 0 then mixBits = bitsAt(b, pos, 8) mixRes = bitsAt(b, pos + 8, 8) pos += 16 if mixRes >= 128 then mixRes -= 256 end local mode, denShift, pbFactor, order = {}, {}, {}, {} local coefs = { {}, {} } for c = 1, nch do local x = bitsAt(b, pos, 8) local y = bitsAt(b, pos + 8, 8) pos += 16 mode[c], denShift[c] = rshift(x, 4), band(x, 15) :: number pbFactor[c], order[c] = rshift(y, 5), band(y, 31) :: number if pos + order[c] * 16 > limit then return nil, "frame runs past the end" end for j = 1, order[c] do local v = bitsAt(b, pos, 16) pos += 16 coefs[c][j] = if v >= 32768 then v - 65536 else v end end if pos > limit then return nil, "frame runs past the end" end local shiftPos = pos if shift > 0 then pos += shift * n * nch end for c = 1, nch do local p = if c == 1 then p0 else p1 local mb = if c == 1 then m0 else m1 pos = rice(b, pos, limit, p, n, bps, floor(st.pb * pbFactor[c] / 4), st) if pos < 0 or pos > limit then return nil, "bad residuals" end if mode[c] == 15 then predict(p, p, n, bps, {}, 31, 0) elseif mode[c] ~= 0 then return nil, "unknown prediction mode " .. mode[c] end predict(p, mb, n, bps, coefs[c], order[c], denShift[c]) end if shift > 0 then local sp = shiftPos for i = 1, n * nch do shiftBuf[i] = bitsAt(b, sp, shift) sp += shift end end else -- uncompressed: interleaved samples of bitDepth bits local bits = st.bitDepth if pos + n * nch * bits > limit then return nil, "frame runs past the end" end for i = 1, n do for c = 1, nch do local v if bits > 25 then v = bitsAt(b, pos, bits - 16) * 65536 + bitsAt(b, pos + bits - 16, 16) else v = bitsAt(b, pos, bits) end pos += bits v = signExtend(v, bits) if c == 1 then m0[i] = v else m1[i] = v end end end shift = 0 end local sm = POW[shift + 1] if nch == 2 then local den = POW[mixBits + 1] for i = 1, n do local u, v = m0[i], m1[i] local l, r if mixRes ~= 0 then l = u + v - floor(mixRes * v / den) r = l - v else l, r = u, v end if shift > 0 then l = l * sm + shiftBuf[2 * i - 1] r = r * sm + shiftBuf[2 * i] end local o = (i - 1) * channels + ch + 1 out[o] = l out[o + 1] = r end else for i = 1, n do local v = m0[i] if shift > 0 then v = v * sm + shiftBuf[i] end out[(i - 1) * channels + ch + 1] = v end end ch += nch elseif tag == 4 then -- DSE pos += 4 local align = bitsAt(b, pos, 1) local count = bitsAt(b, pos + 1, 8) pos += 9 if count == 255 then count += bitsAt(b, pos, 8) pos += 8 end if align == 1 then pos = (pos + 7) // 8 * 8 end pos += count * 8 elseif tag == 6 then -- FIL local count = bitsAt(b, pos, 4) pos += 4 if count == 15 then count += bitsAt(b, pos, 8) - 1 pos += 8 end pos += count * 8 else return nil, "unsupported element " .. tag end if pos > limit then return nil, "frame runs past the end" end end if frames < 0 then return 0, nil end if ch < channels then for i = 1, frames do for c = ch + 1, channels do out[(i - 1) * channels + c] = 0 end end end return frames, nil end @native function Decode.state(cfg: any): State local n = cfg.frameLength return { frameLength = n, bitDepth = cfg.bitDepth, pb = cfg.pb, mb = cfg.mb, kb = cfg.kb, channels = cfg.channels, maxRun = cfg.maxRun, scratch = buffer.create(math.max(64, cfg.maxFrameBytes or 0) + 64), pred = { table.create(n, 0), table.create(n, 0) }, mix = { table.create(n, 0), table.create(n, 0) }, shift = table.create(n * 2, 0), out = table.create(n * cfg.channels, 0), } end local _ = readu8 return Decode end __FILES["codecs/audio/Alac/Encode"] = @native function() -- codecs/audio/Alac/Encode: an ALAC frame encoder (mixBits 2, LPC orders 4 / 8 with denShift 9, escape frames). -- Written from the ALAC format; no third-party code. local band, rshift, bor, lshift, countlz = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.countlz local readu8, writeu8 = buffer.readu8, buffer.writeu8 local floor, abs = math.floor, math.abs local Encode = {} local POW = table.create(64, 0) for i = 0, 63 do POW[i + 1] = 2 ^ i end local DENSHIFT = 9 local PB_FACTOR = 4 type State = { frameLength: number, bitDepth: number, pb: number, mb: number, kb: number, channels: number, out: buffer, pos: number, cap: number, u: { number }, v: { number }, err: { number }, work: { number }, } @native local function put(st: State, v: number, n: number) local pos = st.pos if pos + n > st.cap then st.pos = st.cap + 1 -- overflow: the caller falls back to an uncompressed frame return end local b = st.out while n > 0 do local byte = rshift(pos, 3) local free = 8 - band(pos, 7) local take = if n < free then n else free local bits = band(rshift(v, n - take), POW[take + 1] - 1) writeu8(b, byte, bor(readu8(b, byte), lshift(bits, free - take))) pos += take n -= take end st.pos = pos end @native local function putBig(st: State, v: number, n: number) if n > 24 then local lo = v % 65536 put(st, (v - lo) / 65536, n - 16) put(st, lo, 16) else put(st, v, n) end end @native local function signExtend(v: number, bits: number): number local m = POW[bits + 1] v = v % m if v >= m / 2 then v -= m end return v end @native local function scalarBits(x: number, k: number, m: number, bps: number): number local pre = if k == 1 then x else floor(x / m) if pre >= 9 then return 9 + bps end if k == 1 then return pre + 1 end local r = x - pre * m return pre + 1 + (if r == 0 then k - 1 else k) end @native local function scalar(st: State, x: number, k: number, m: number, bps: number) local pre = if k == 1 then x else floor(x / m) if pre >= 9 then put(st, 511, 9) putBig(st, x, bps) return end put(st, POW[pre + 2] - 2, pre + 1) if k ~= 1 then local r = x - pre * m if r == 0 then put(st, 0, k - 1) else put(st, r + 1, k) end end end @native local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number local history = st.mb local kb = st.kb local signMod = 0 local bits = 0 local i = 1 while i <= n do local k = 31 - countlz(floor(history / 512) + 3) if k > kb then k = kb end local v = e[i] local zz = if v >= 0 then 2 * v else -2 * v - 1 local x = zz - signMod signMod = 0 local m = POW[k + 1] - 1 if write then scalar(st, x, k, m, bps) else bits += scalarBits(x, k, m, bps) end if zz > 0xFFFF then -- the decoder adapts on the value with its sign modifier added back history = 0xFFFF else history += zz * mult - floor(history * mult / 512) end if history < 128 and i < n then local lg = if history > 0 then 31 - countlz(history) else 0 k = 7 - lg + floor((history + 16) / 64) if k > kb then k = kb end local run = 0 while i + run < n and e[i + run + 1] == 0 and run < 0xFFFF do run += 1 end m = POW[k + 1] - 1 if write then scalar(st, run, k, m, 16) else bits += scalarBits(run, k, m, 16) end i += run if run < 0xFFFF then signMod = 1 end history = 0 end i += 1 end return bits end -- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder) @native local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) e[1] = x[1] if n <= 1 then return end local i = 2 while i <= order + 1 and i <= n do e[i] = signExtend(x[i] - x[i - 1], bps) i += 1 end local half = POW[quant] local qd = POW[quant + 1] while i <= n do local d = x[i - order - 1] local val = 0 for j = 1, order do val += (x[i - j] - d) * coefs[j] end val = floor((val + half) / qd) local r = signExtend(x[i] - val - d, bps) e[i] = r if r ~= 0 then local es = if r > 0 then 1 else -1 for j = order, 1, -1 do if r * es <= 0 then break end local v = d - x[i - j] local sgn = if v > 0 then es elseif v < 0 then -es else 0 coefs[j] -= sgn r -= floor(v * sgn / qd) * (order - j + 1) end end i += 1 end end @native local function lpc(x: { number }, n: number, order: number, work: { number }): { number } local ac = table.create(order + 1, 0) for i = 1, n do local t = (2 * (i - 1) - (n - 1)) / (n + 1) work[i] = x[i] * (1 - t * t) end for lag = 0, order do local s = 0 for i = lag + 1, n do s += work[i] * work[i - lag] end ac[lag + 1] = s end local coefs = table.create(order, 0) if ac[1] <= 0 then return coefs end ac[1] *= 1.0001 -- a little white noise: keeps the recursion stable local a = table.create(order + 1, 0) local tmp = table.create(order + 1, 0) local errv = ac[1] for i = 1, order do local acc = ac[i + 1] for j = 1, i - 1 do acc -= a[j] * ac[i - j + 1] end local kc = acc / errv for j = 1, i - 1 do tmp[j] = a[j] - kc * a[i - j] end for j = 1, i - 1 do a[j] = tmp[j] end a[i] = kc errv *= (1 - kc * kc) if errv <= 0 then break end end local scale = POW[DENSHIFT + 1] for j = 1, order do coefs[j] = math.clamp(floor(a[j] * scale + 0.5), -32768, 32767) end return coefs end @native local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number) local mult = floor(st.pb * PB_FACTOR / 4) local bestOrder, bestCoefs, bestBits = 0, {}, math.huge for _, order in { 4, 8 } do if order >= n then continue end local coefs = lpc(x, n, order, st.work) local trial = table.clone(coefs) residuals(x, st.err, n, bps, trial, order, DENSHIFT) local bits = rice(st, st.err, n, bps, mult, false) + order * 16 if bits < bestBits then bestOrder, bestCoefs, bestBits = order, coefs, bits end end if bestBits == math.huge then -- tiny frames: first-order prediction (order 31 is only a decoder mode; order 0 = no prediction) for i = 1, n do st.err[i] = x[i] end return 0, {}, rice(st, st.err, n, bps, mult, false) end return bestOrder, bestCoefs, bestBits end @native function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer local channels, depth = st.channels, st.bitDepth local n = frames local partial = n ~= st.frameLength local rawBits = n * channels * depth local need = rawBits + 64 * #elements + 64 if st.cap < need + 8 * 32 * 2 * #elements * 16 then local bytes = (need + 8 * 32 * 2 * #elements * 16) // 8 + 16 st.out = buffer.create(bytes) st.cap = bytes * 8 end buffer.fill(st.out, 0, 0) st.pos = 0 local u, v = st.u, st.v local mult = floor(st.pb * PB_FACTOR / 4) local compressed = true local ch = 1 for _, nch in elements do local a, b = map[ch], map[ch + 1] local bps = depth + nch - 1 local mixRes = 0 if nch == 2 then local best = math.huge for res = 0, 4 do local cost = 0 local pu, pv = 0, 0 for i = 0, n - 1 do local l = samples[first + i * channels + a - 1] local r = samples[first + i * channels + b - 1] local uu, vv if res == 0 then uu, vv = l, r else uu, vv = floor((res * l + (4 - res) * r) / 4), l - r end cost += abs(uu - pu) + abs(vv - pv) pu, pv = uu, vv end if cost < best then best, mixRes = cost, res end end for i = 1, n do local l = samples[first + (i - 1) * channels + a - 1] local r = samples[first + (i - 1) * channels + b - 1] if mixRes == 0 then u[i], v[i] = l, r else u[i], v[i] = floor((mixRes * l + (4 - mixRes) * r) / 4), l - r end end else for i = 1, n do u[i] = samples[first + (i - 1) * channels + a - 1] end end put(st, if nch == 2 then 1 else 0, 3) put(st, 0, 4) put(st, 0, 12) put(st, if partial then 1 else 0, 1) put(st, 0, 2) put(st, 0, 1) if partial then putBig(st, n, 32) end put(st, if mixRes == 0 then 0 else 2, 8) put(st, mixRes, 8) local orders, coefsList = {}, {} for c = 1, nch do local x = if c == 1 then u else v local order, coefs = analyse(st, x, n, bps) orders[c], coefsList[c] = order, coefs put(st, 0 * 16 + DENSHIFT, 8) -- mode 0, denShift put(st, PB_FACTOR * 32 + order, 8) for j = 1, order do put(st, coefs[j] % 65536, 16) end end for c = 1, nch do local x = if c == 1 then u else v local order = orders[c] if order == 0 then for i = 1, n do st.err[i] = x[i] end else residuals(x, st.err, n, bps, table.clone(coefsList[c]), order, DENSHIFT) end rice(st, st.err, n, bps, mult, true) end ch += nch if st.pos > rawBits + 64 * #elements then compressed = false break end end if not compressed then buffer.fill(st.out, 0, 0) st.pos = 0 ch = 1 for _, nch in elements do put(st, if nch == 2 then 1 else 0, 3) put(st, 0, 4) put(st, 0, 12) put(st, if partial then 1 else 0, 1) put(st, 0, 2) put(st, 1, 1) if partial then putBig(st, n, 32) end for i = 0, n - 1 do for c = 0, nch - 1 do putBig(st, samples[first + i * channels + map[ch + c] - 1] % POW[depth + 1], depth) end end ch += nch end end put(st, 7, 3) -- END local bytes = (st.pos + 7) // 8 local pkt = buffer.create(bytes) buffer.copy(pkt, 0, st.out, 0, bytes) return pkt end @native function Encode.state(cfg: any): State local n = cfg.frameLength return { frameLength = n, bitDepth = cfg.bitDepth, pb = cfg.pb, mb = cfg.mb, kb = cfg.kb, channels = cfg.channels, out = buffer.create(16), pos = 0, cap = 0, u = table.create(n, 0), v = table.create(n, 0), err = table.create(n, 0), work = table.create(n, 0), } end return Encode end __FILES["codecs/audio/Ape"] = function() -- codecs/audio/Ape: the Monkey's Audio codec (.ape), file versions 3.95 and later. -- Ported from the Monkey's Audio SDK 13.28 (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt): -- APEHeader.cpp, APEInfo / APEDecompress.cpp. Not supported: pre-3.95 (UNSUPPORTED), the pre-8.50 "interim" 24-bit re-decode. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Decode = __include("codecs/audio/Ape/Decode") local Ape = {} type Info = { version: number, -- file version * 1000 (3990) programVersion: number, level: number, -- 1000 (fast) .. 5000 (insane) flags: number, channels: number, sampleRate: number, bitsPerSample: number, float: boolean, blocksPerFrame: number, finalFrameBlocks: number, totalFrames: number, totalBlocks: number, frameStart: { number }, firstFrame: number, -- byte offset of frame 1 (the word alignment origin) dataEnd: number, limit: number, md5: string?, } local FLAG_8, FLAG_24, FLAG_PEAK, FLAG_SEEKN, FLAG_WAVHDR, FLAG_FLOAT = 1, 8, 4, 16, 32, 4096 function Ape.find(buf: buffer, base: number, limit: number): number? local at = base if limit - at >= 10 and buffer.readstring(buf, at, 3) == "ID3" then local size = 0 for i = 6, 9 do size = size * 128 + bit32.band(buffer.readu8(buf, at + i), 127) end local footer = bit32.band(buffer.readu8(buf, at + 5), 16) ~= 0 at += size + (if footer then 20 else 10) if not footer then while at < limit and buffer.readu8(buf, at) == 0 do at += 1 end end end if at + 4 > limit then return nil end local id = buffer.readstring(buf, at, 4) if id == "MAC " or id == "MACF" then return at end local s = buffer.readstring(buf, at, math.min(limit - at, 1048576)) local k = string.find(s, "MAC ", 1, true) return if k then at + k - 1 else nil end function Ape.info(buf: buffer, base: number, limit: number): (Info?, Err.Err?) local at = Ape.find(buf, base, limit) if not at then return nil, Err.new(Err.CORRUPT, "no Monkey's Audio header") end local junk = at - base -- seek offsets count from the start of the APE data (after any junk / ID3v2) local r = Bytes.reader(buf, at, limit - at) r:skip(4) local version = r:u16le() if r.err then return nil, r.err end if version < 3950 then return nil, Err.new(Err.UNSUPPORTED, "Monkey's Audio file version " .. version .. " (3950 and later are supported)") end local info: any = { version = version, programVersion = 0 } local seekCount, seekAt if version >= 3980 then info.programVersion = r:u16le() local descBytes, headBytes, seekBytes, hdrDataBytes = r:u32le(), r:u32le(), r:u32le(), r:u32le() local dataLo, dataHi, termBytes = r:u32le(), r:u32le(), r:u32le() local md5 = r:string(16) r:seek(descBytes) info.level = r:u16le() info.flags = r:u16le() info.blocksPerFrame = r:u32le() info.finalFrameBlocks = r:u32le() info.totalFrames = r:u32le() info.bitsPerSample = r:u16le() info.channels = r:u16le() info.sampleRate = r:u32le() if r.err then return nil, r.err end seekAt = at + descBytes + headBytes seekCount = seekBytes // 4 info.dataEnd = seekAt + seekBytes + hdrDataBytes + dataLo + dataHi * 4294967296 local _ = termBytes local hex = table.create(16, "") local any = false for k = 1, 16 do local b = string.byte(md5, k) any = any or b ~= 0 hex[k] = string.format("%02x", b) end info.md5 = if any then table.concat(hex) else nil else info.level = r:u16le() info.flags = r:u16le() info.channels = r:u16le() info.sampleRate = r:u32le() local headerBytes = r:u32le() r:u32le() -- terminating bytes info.totalFrames = r:u32le() info.finalFrameBlocks = r:u32le() if bit32.band(info.flags, FLAG_PEAK) ~= 0 then r:skip(4) end seekCount = info.totalFrames if bit32.band(info.flags, FLAG_SEEKN) ~= 0 then seekCount = r:u32le() end if bit32.band(info.flags, FLAG_WAVHDR) == 0 then r:skip(headerBytes) end if r.err then return nil, r.err end info.blocksPerFrame = 73728 * 4 info.bitsPerSample = if bit32.band(info.flags, FLAG_8) ~= 0 then 8 elseif bit32.band(info.flags, FLAG_24) ~= 0 then 24 else 16 seekAt = r:tell() info.dataEnd = limit end local C, bits = info.channels, info.bitsPerSample if C < 1 or C > 32 then return nil, Err.new(Err.CORRUPT, "bad channel count " .. C) end if bits ~= 8 and bits ~= 16 and bits ~= 24 and bits ~= 32 then return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit samples") end if info.sampleRate < 1 or info.blocksPerFrame < 1 or info.blocksPerFrame > 10000000 or info.finalFrameBlocks > info.blocksPerFrame then return nil, Err.new(Err.CORRUPT, "bad header") end if info.totalFrames < 1 then return nil, Err.new(Err.CORRUPT, "no frames") end info.float = bit32.band(info.flags, FLAG_FLOAT) ~= 0 and bits == 32 info.totalBlocks = (info.totalFrames - 1) * info.blocksPerFrame + info.finalFrameBlocks if seekCount < info.totalFrames or seekAt + seekCount * 4 > limit then return nil, Err.new(Err.TRUNCATED, "the seek table is incomplete") end local starts = table.create(info.totalFrames, 0) local add, prev = 0, 0 for i = 1, info.totalFrames do local v = buffer.readu32(buf, seekAt + (i - 1) * 4) if v < prev then add += 4294967296 end prev = v starts[i] = base + junk + add + v end for i = 1, info.totalFrames do if starts[i] < base or (i > 1 and starts[i] < starts[i - 1]) then return nil, Err.new(Err.CORRUPT, "bad seek table entry " .. i) end end info.frameStart = starts info.firstFrame = starts[1] info.dataEnd = math.min(math.max(info.dataEnd, starts[info.totalFrames]), limit) info.limit = limit return info :: Info, nil end type Decoder = { info: Info, pcm: { number }, frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?), state: Decode.State, } local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) local info = self.info if i < 1 or i > info.totalFrames then return nil, Err.new(Err.ARG, "no frame " .. i) end local start = info.frameStart[i] local rem = (start - info.firstFrame) % 4 local want = (if i < info.totalFrames then info.frameStart[i + 1] else info.dataEnd) + 4 local stop = math.min(want, info.limit, buffer.len(buf)) if start + 8 > stop then return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " is past the end of the data", start) end local n = if i < info.totalFrames then info.blocksPerFrame else info.finalFrameBlocks local n2, msg = Decode.frame(self.state, buf, start - rem, rem, stop, n, self.pcm, info.float, stop < want - 4) if not n2 then return nil, Err.from(msg, start) end return n2, nil end function Ape.decoder(info: Info): (Decoder?, Err.Err?) local st, msg = Decode.state(info.version, info.level, info.bitsPerSample, info.channels) if not st then return nil, Err.from(msg) end return { info = info, pcm = table.create(math.min(info.blocksPerFrame, 1048576) * info.channels, 0), frame = frame, state = st, }, nil end return Ape end __FILES["codecs/audio/Ape/Decode"] = @native function() -- codecs/audio/Ape/Decode: one Monkey's Audio frame -> samples. -- Ported from the Monkey's Audio SDK 13.28 (Matthew T. Ashland, BSD 3-clause, licenses/monkeys-audio-LICENSE.txt): -- UnBitArray.cpp, Old/UnBitArrayOld.cpp, NNFilter.h, NewPredictor.cpp, Prepare.cpp, APEDecompressCore.cpp, FloatTransform.cpp. local Crc32 = __include("core/Crc32") local readu8, readu32, writeu32, byteswap = buffer.readu8, buffer.readu32, buffer.writeu32, bit32.byteswap local writeu8, writei16, writeu16, writei32, readf32 = buffer.writeu8, buffer.writei16, buffer.writeu16, buffer.writei32, buffer.readf32 local readi16, readi32 = buffer.readi16, buffer.readi32 local band, bor, bnot, rshift, lshift, bxor = bit32.band, bit32.bor, bit32.bnot, bit32.rshift, bit32.lshift, bit32.bxor local sign = math.sign local Decode = {} local TWO31, TWO32 = 2147483648, 4294967296 local PAD = 64 -- the range coder's symbol models (UnBitArrayBase.h) local RT1 = { 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926, 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419, 65450, 65469, 65480, 65487, 65491, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 } local RT2 = { 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435, 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482, 65485, 65488, 65490, 65491, 65492, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 } local KMIN = { 0, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 0, 0, 0, 0, 0 } -- symbol(total) lookup buffers (RangeOverflowTable), built on first use local OVT: { [number]: buffer } = {} @native local function overflowTable(rt: { number }): buffer local t = OVT[rt[2]] if t then return t end t = buffer.create(65536) local o = 0 for z = 0, 65535 do if z >= rt[o + 2] then o += 1 end writeu8(t, z, o) end OVT[rt[2]] = t return t end @native local function wrap32(v: number): number if v >= TWO31 or v < -TWO31 then return (v + TWO31) % TWO32 - TWO31 end return v end -- C integer division by 2 (toward zero) @native local function half(v: number): number return if v >= 0 then v // 2 else -((-v) // 2) end type Filter = { order: number, shift: number, M: buffer, I: buffer, D: buffer } type State = { version: number, bits: number, channels: number, filters: { Filter }, -- per level, applied last to first on decode (as m_spNNFilter2, 1, 0) V: { { number } }, S: buffer, crcbuf: buffer, scratch: buffer, lastX: number, rc: Rc, } local FILTERS: { [number]: { number } } = { -- level -> { order, shift, ... } in m_spNNFilter, 1, 2 order [1000] = {}, [2000] = { 16, 11 }, [3000] = { 64, 11 }, [4000] = { 256, 13, 32, 10 }, [5000] = { 1280, 15, 256, 13, 16, 11 }, } @native function Decode.state(version: number, level: number, bits: number, channels: number): (State?, string?) local spec = FILTERS[level] if not spec then return nil, "unsupported: compression level " .. level end local filters: { Filter } = {} for k = 1, #spec, 2 do local order = spec[k] local es = if bits >= 32 then 4 else 2 table.insert(filters, { order = order, shift = spec[k + 1], M = buffer.create(order * es), I = buffer.create((512 + order + 1) * es), D = buffer.create((512 + order + 1) * es), }) end local V = {} for c = 1, channels do V[c] = {} end return { version = version, bits = bits, channels = channels, filters = filters, V = V, S = buffer.create(1024), crcbuf = buffer.create(1024), scratch = buffer.create(4), lastX = 0, rc = { q = 0, low = 0, range = 0, prev = 0 }, }, nil end -- the range coder as a record (the 3.95 - 3.98 model's RangeDecodeFastWithUpdate) type Rc = { q: number, low: number, range: number, prev: number } @native local function rcBits(rc: Rc, S: buffer, nb: number): number local q, low, range, prev = rc.q, rc.low, rc.range, rc.prev while range <= 8388608 do local byte = readu8(S, q) q += 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range *= 256 end range = range // 2 ^ nb local r = 0 if range > 0 then r = low // range low %= range end rc.q, rc.low, rc.range, rc.prev = q, low, range, prev return r end @native local function values(st: State, q: number, lim: number, n: number, order: { number }, old: boolean): (number?, string?) local S = st.S local V = st.V local version = st.version -- FlushBitArray: a dummy byte, then the first byte local prev = readu8(S, q + 1) q += 2 local low = rshift(prev, 1) local range = 128 local nch = #order local ksum = table.create(nch, 16384) local kk = table.create(nch, 10) local ovt = overflowTable(if old then RT1 else RT2) local RT = if old then RT1 else RT2 for b = 1, n do for ci = 1, nch do if q > lim then return nil, "overrun" end local ks = ksum[ci] local value -- the overflow symbol (RangeDecodeFast(16) + the model) while range <= 8388608 do local byte = readu8(S, q) q += 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range *= 256 end range = range // 65536 local total = low // range if total >= 65536 then return nil, "bad range code" end local ov = readu8(ovt, total) low -= range * RT[ov + 1] range *= RT[ov + 2] - RT[ov + 1] if not old then local pivot = math.max(ks // 32, 1) while ov == 63 do -- escape: 32 bits of overflow (two 16-bit range decodes); 1 = the overflow signal local r = 0 for _ = 1, 2 do while range <= 8388608 do local byte = readu8(S, q) q += 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range *= 256 end range = range // 65536 if range == 0 then return nil, "bad range code" end r = r * 65536 + low // range low %= range end ov = r if ov == 1 then pivot = 32768 while range <= 8388608 do local byte = readu8(S, q) q += 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range *= 256 end range = range // 65536 total = low // range if total >= 65536 then return nil, "bad range code" end ov = readu8(ovt, total) low -= range * RT[ov + 1] range *= RT[ov + 2] - RT[ov + 1] else break end end local base if pivot >= 65536 then local pbits = 0 while pivot // 2 ^ pbits > 0 do pbits += 1 end local split = 2 ^ (if pbits >= 16 then pbits - 16 else 0) local pa = pivot // split + 1 while range <= 8388608 do local byte = readu8(S, q) q += 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range *= 256 end range = range // pa local ba = low // range low %= range while range <= 8388608 do local byte = readu8(S, q) q += 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range *= 256 end range = range // split local bb = low // range low %= range base = ba * split + bb else while range <= 8388608 do local byte = readu8(S, q) q += 1 low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) prev = byte range *= 256 end range = range // pivot base = low // range low %= range end value = base + ov * pivot else -- 3.95 - 3.98: k bits (escape: k in 5 bits) local rc = st.rc rc.q, rc.low, rc.range, rc.prev = q, low, range, prev local k if ov == 63 then k = rcBits(rc, S, 5) ov = 0 else k = math.max(kk[ci] - 1, 0) end if k <= 16 or version < 3910 then value = rcBits(rc, S, k) else local x1 = rcBits(rc, S, 16) value = x1 + rcBits(rc, S, k - 16) * 65536 end value += ov * 2 ^ k q = rc.q low = rc.low range = rc.range prev = rc.prev end ks = (ks + (value + 1) // 2 - (ks + 16) // 32) % TWO32 ksum[ci] = ks if old then local k = kk[ci] if ks < KMIN[k + 1] then kk[ci] = k - 1 elseif KMIN[k + 2] ~= 0 and ks >= KMIN[k + 2] then kk[ci] = k + 1 end end V[order[ci]][b] = if value % 2 == 1 then (value - 1) // 2 + 1 else -(value // 2) end end return q, nil end -- ((v >> s) & m) ~= 0 for an int64 v (s given as 2^s) @native local function negBit(v: number, p2: number, m: number): boolean return band((v // p2) % TWO32, m) ~= 0 end @native local function dot16(M: buffer, I: buffer, b: number, span: number): number local dot = 0 for k = 0, span - 16, 16 do local bb = b + k dot += readi16(I, bb) * readi16(M, k) + readi16(I, bb + 2) * readi16(M, k + 2) + readi16(I, bb + 4) * readi16(M, k + 4) + readi16(I, bb + 6) * readi16(M, k + 6) + readi16(I, bb + 8) * readi16(M, k + 8) + readi16(I, bb + 10) * readi16(M, k + 10) + readi16(I, bb + 12) * readi16(M, k + 12) + readi16(I, bb + 14) * readi16(M, k + 14) end return dot end -- the same, adapting each weight after its use: M += D * dm (int16, wrapping) @native local function dotAdapt16(M: buffer, I: buffer, D: buffer, b: number, span: number, dm: number): number local dot = 0 for k = 0, span - 8, 8 do local bb = b + k local m0, m1, m2, m3 = readi16(M, k), readi16(M, k + 2), readi16(M, k + 4), readi16(M, k + 6) dot += readi16(I, bb) * m0 + readi16(I, bb + 2) * m1 + readi16(I, bb + 4) * m2 + readi16(I, bb + 6) * m3 writei16(M, k, m0 + readi16(D, bb) * dm) writei16(M, k + 2, m1 + readi16(D, bb + 2) * dm) writei16(M, k + 4, m2 + readi16(D, bb + 4) * dm) writei16(M, k + 6, m3 + readi16(D, bb + 6) * dm) end return dot end -- one CNNFilter (DecompressGeneric); weights in the C types (int16 up to 24-bit files, int32 for 32-bit) wrap as C does @native local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean, wide: boolean) local order, M, I, D = f.order, f.M, f.I, f.D local es = if wide then 4 else 2 local shift = 2 ^ f.shift local round = shift // 2 buffer.fill(M, 0, 0, order * es) buffer.fill(I, 0, 0, (order + 1) * es) buffer.fill(D, 0, 0, (order + 1) * es) local p = order local total = 512 + order local avg = 0 local span = order * 2 for t = 1, n do local x = v[t] local dm = -sign(x) -- the weights move by +delta when x < 0, -delta when x > 0 local dot = 0 if wide then local b = (p - order) * 4 for k = 0, order * 4 - 4, 4 do local m = readi32(M, k) local pr = readi32(I, b + k) * m if pr >= TWO31 or pr < -TWO31 then pr = (pr + TWO31) % TWO32 - TWO31 end dot += pr if dm ~= 0 then writei32(M, k, m + readi32(D, b + k) * dm) end end else local b = (p - order) * 2 dot = if dm == 0 then dot16(M, I, b, span) else dotAdapt16(M, I, D, b, span, dm) dot = wrap32(dot) end local o = x + (dot + round) // shift if not wide then o = wrap32(o) end local d = 0 local a = if o < 0 then -o else o if newDelta then if a > avg * 3 then d = if (if wide then negBit(o, 33554432, 64) else o < 0) then 32 else -32 elseif a > (avg * 4) // 3 then d = if (if wide then negBit(o, 67108864, 32) else o < 0) then 16 else -16 elseif a > 0 then d = if (if wide then negBit(o, 134217728, 16) else o < 0) then 8 else -8 end local dd = a - avg avg += if dd >= 0 then dd // 16 else -((-dd) // 16) else d = if o == 0 then 0 elseif o < 0 then 4 else -4 end local sat = if o > 32767 then 32767 elseif o < -32768 then -32768 else o if wide then local q = p * 4 writei32(D, q, d) if newDelta then writei32(D, q - 4, readi32(D, q - 4) // 2) writei32(D, q - 8, readi32(D, q - 8) // 2) else writei32(D, q - 16, readi32(D, q - 16) // 2) end writei32(D, q - 32, readi32(D, q - 32) // 2) writei32(I, q, sat) else local q = p * 2 writei16(D, q, d) if newDelta then writei16(D, q - 2, readi16(D, q - 2) // 2) writei16(D, q - 4, readi16(D, q - 4) // 2) else writei16(D, q - 8, readi16(D, q - 8) // 2) end writei16(D, q - 16, readi16(D, q - 16) // 2) writei16(I, q, sat) end v[t] = o p += 1 if p == total then buffer.copy(I, 0, I, (p - order) * es, order * es) buffer.copy(D, 0, D, (p - order) * es, order * es) p = order end end end -- the adapt sign of a 32-bit file's int64 prediction value: ((v >> 30) & 2) - 1, or 0 @native local function adaptWide(v: number): number if v == 0 then return 0 end return if (v // 1073741824) % 4 >= 2 then 1 else -1 end -- CPredictorDecompress3950toCurrent, single-channel form @native local function predictOne(st: State, v: { number }, n: number) local wide = st.bits >= 32 local lastA, prevA0, A1, A2, A3 = 0, 0, 0, 0, 0 local MA0, MA1, MA2, MA3 = 360, 317, -109, 98 local stage = 0 for t = 1, n do local nA = v[t] local A0 = lastA A3 = A2 A2 = A1 A1 = A0 - prevA0 prevA0 = A0 local predA = A0 * MA0 + A1 * MA1 + A2 * MA2 + A3 * MA3 local cur if wide then cur = nA + predA // 1024 else cur = wrap32(nA + wrap32(predA) // 1024) end local s = sign(nA) if s ~= 0 then if wide then s = -s MA0 += adaptWide(A0) * s MA1 += adaptWide(A1) * s MA2 += adaptWide(A2) * s MA3 += adaptWide(A3) * s else MA0 += sign(A0) * s MA1 += sign(A1) * s MA2 += sign(A2) * s MA3 += sign(A3) * s end end stage = wrap32(cur + (stage * 31) // 32) lastA = cur v[t] = stage end end -- the stereo predictors: Y = P1(nY, last X), X = P0(nX, Y); X into V[1], Y into V[2] @native local function predictStereo(st: State, X: { number }, Y: { number }, n: number) local wide = st.bits >= 32 -- predictor 1 (Y) local yLast, yPrev, yA1, yA2, yA3 = 0, 0, 0, 0, 0 local yBin, yBprev, yB1, yB2, yB3, yB4 = 0, 0, 0, 0, 0, 0 local yMA0, yMA1, yMA2, yMA3 = 360, 317, -109, 98 local yMB0, yMB1, yMB2, yMB3, yMB4 = 0, 0, 0, 0, 0 local yStage = 0 -- predictor 0 (X) local xLast, xPrev, xA1, xA2, xA3 = 0, 0, 0, 0, 0 local xBin, xBprev, xB1, xB2, xB3, xB4 = 0, 0, 0, 0, 0, 0 local xMA0, xMA1, xMA2, xMA3 = 360, 317, -109, 98 local xMB0, xMB1, xMB2, xMB3, xMB4 = 0, 0, 0, 0, 0 local xStage = 0 local lastX = 0 for t = 1, n do local nA = Y[t] local A0 = yLast yA3 = yA2 yA2 = yA1 yA1 = A0 - yPrev yPrev = A0 local B0 = lastX - (yBin * 31) // 32 yBin = lastX yB4 = yB3 yB3 = yB2 yB2 = yB1 yB1 = B0 - yBprev yBprev = B0 local predA = A0 * yMA0 + yA1 * yMA1 + yA2 * yMA2 + yA3 * yMA3 local predB = B0 * yMB0 + yB1 * yMB1 + yB2 * yMB2 + yB3 * yMB3 + yB4 * yMB4 local cur if wide then cur = nA + (predA + predB // 2) // 1024 else cur = wrap32(nA + wrap32(wrap32(predA) + wrap32(predB) // 2) // 1024) end local s = sign(nA) if s ~= 0 then if wide then s = -s yMA0 += adaptWide(A0) * s yMA1 += adaptWide(yA1) * s yMA2 += adaptWide(yA2) * s yMA3 += adaptWide(yA3) * s yMB0 += adaptWide(B0) * s yMB1 += adaptWide(yB1) * s yMB2 += adaptWide(yB2) * s yMB3 += adaptWide(yB3) * s yMB4 += adaptWide(yB4) * s else yMA0 += sign(A0) * s yMA1 += sign(yA1) * s yMA2 += sign(yA2) * s yMA3 += sign(yA3) * s yMB0 += sign(B0) * s yMB1 += sign(yB1) * s yMB2 += sign(yB2) * s yMB3 += sign(yB3) * s yMB4 += sign(yB4) * s end end yStage = wrap32(cur + (yStage * 31) // 32) yLast = cur local yv = yStage nA = X[t] A0 = xLast xA3 = xA2 xA2 = xA1 xA1 = A0 - xPrev xPrev = A0 B0 = yv - (xBin * 31) // 32 xBin = yv xB4 = xB3 xB3 = xB2 xB2 = xB1 xB1 = B0 - xBprev xBprev = B0 predA = A0 * xMA0 + xA1 * xMA1 + xA2 * xMA2 + xA3 * xMA3 predB = B0 * xMB0 + xB1 * xMB1 + xB2 * xMB2 + xB3 * xMB3 + xB4 * xMB4 if wide then cur = nA + (predA + predB // 2) // 1024 else cur = wrap32(nA + wrap32(wrap32(predA) + wrap32(predB) // 2) // 1024) end s = sign(nA) if s ~= 0 then if wide then s = -s xMA0 += adaptWide(A0) * s xMA1 += adaptWide(xA1) * s xMA2 += adaptWide(xA2) * s xMA3 += adaptWide(xA3) * s xMB0 += adaptWide(B0) * s xMB1 += adaptWide(xB1) * s xMB2 += adaptWide(xB2) * s xMB3 += adaptWide(xB3) * s xMB4 += adaptWide(xB4) * s else xMA0 += sign(A0) * s xMA1 += sign(xA1) * s xMA2 += sign(xA2) * s xMA3 += sign(xA3) * s xMB0 += sign(B0) * s xMB1 += sign(xB1) * s xMB2 += sign(xB2) * s xMB3 += sign(xB3) * s xMB4 += sign(xB4) * s end end xStage = wrap32(cur + (xStage * 31) // 32) xLast = cur lastX = xStage X[t], Y[t] = xStage, yv end end @native function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: number, n: number, P: { number }, float: boolean, cut: boolean): (number?, string?) local C, bits = st.channels, st.bits local len = math.max(0, stop - at) local words = (len + 3) // 4 local S = st.S if buffer.len(S) < words * 4 + PAD then S = buffer.create(words * 4 + PAD + 4096) st.S = S end buffer.fill(S, 0, 0, words * 4 + PAD) -- the bit array: 32-bit little-endian words read MSB first for w = 0, words - 1 do local o = at + w * 4 if o + 4 <= stop then writeu32(S, w * 4, byteswap(readu32(buf, o))) else for k = 0, 3 do if o + k < stop then writeu8(S, w * 4 + 3 - k, readu8(buf, o + k)) end end end end @native local function u32be(q: number): number return readu8(S, q) * 16777216 + readu8(S, q + 1) * 65536 + readu8(S, q + 2) * 256 + readu8(S, q + 3) end local q = rem if q + 16 > words * 4 + PAD then return nil, "truncated frame" end local stored = u32be(q) q += 4 local special = 0 if st.version > 3820 then if stored >= TWO31 then special = u32be(q) q += 4 end stored %= TWO31 end local V = st.V local order: { number } local mode if C == 1 then if band(special, 1) ~= 0 then mode = "silence" order = {} else mode = "mono" order = { 1 } end elseif C == 2 then if band(special, 3) == 3 then mode = "silence" order = {} elseif band(special, 4) ~= 0 then mode = "pseudo" order = { 1 } else mode, order = "stereo", { 2, 1 } end else mode = "multi" order = {} for c = 1, C do order[c] = c end end local lim = words * 4 + PAD - 40 if #order > 0 then local qe = values(st, q, lim, n, order, st.version < 3990) if not qe or qe > words * 4 + 8 then return nil, if cut then "truncated frame" else "bad frame: the values run over its data" end -- the NN filters (last level first), then the predictors local newDelta = st.version >= 3980 local filters = st.filters for _, c in order do for f = #filters, 1, -1 do nnFilter(filters[f], V[c], n, newDelta, bits >= 32) end end if mode == "stereo" then predictStereo(st, V[1], V[2], n) else for _, c in order do predictOne(st, V[c], n) end end end -- Unprepare: values -> channels, the CRC over the output bytes as the WAV holds them local bps = bits // 8 local cb = st.crcbuf if buffer.len(cb) < n * C * bps then cb = buffer.create(n * C * bps + 1024) st.crcbuf = cb end local paired: { [number]: boolean } = {} if C == 2 and mode == "stereo" then paired[0] = true elseif C == 4 and (bits == 16 or bits == 24) then paired[0], paired[2] = true, true elseif C >= 6 and (bits == 16 or bits == 24) then paired[0], paired[4] = true, true if C >= 8 then paired[6] = true end end local o = 0 local mono = mode == "mono" or mode == "pseudo" local X = V[1] for t = 1, n do local base = (t - 1) * C local c = 0 while c < C do local a: number, b2: number = 0, 0 local pair = paired[c] if mode == "silence" then a = 0 b2 = 0 elseif mono then a = X[t] b2 = a elseif pair then local x, y = V[c + 1][t], V[c + 2][t] a = x - half(y) b2 = a + y else a = V[c + 1][t] end local width = if pair or (C == 2) then 2 else 1 for k = 0, width - 1 do local s: number = if k == 0 then a else b2 if bits == 16 then if s < -32768 or s > 32767 then return nil, "sample out of range" end writei16(cb, o, s) o += 2 elseif bits == 8 then s = (s + 128) % 256 - 128 writeu8(cb, o, s + 128) o += 1 elseif bits == 24 then s = (s + 8388608) % 16777216 - 8388608 local u = s % 16777216 writeu16(cb, o, u % 65536) writeu8(cb, o + 2, u // 65536) o += 3 else s = wrap32(s) writei32(cb, o, s) o += 4 end P[base + c + k + 1] = s end c += width end end local crc = Crc32.of(cb, 0, o) if crc // 2 ~= stored then return nil, "checksum: frame CRC mismatch" end if float then local sc = st.scratch for k = 1, n * C do local u = P[k] % TWO32 local out = bor(band(u, 0xC3FFFFFF), bxor(bnot(band(u, 0x3C000000)), 0xC3FFFFFF)) if out >= TWO31 then out = bor(bnot(out), 0x80000000) end writeu32(sc, 0, out) P[k] = readf32(sc, 0) end end return n, nil end return Decode end __FILES["codecs/audio/ApeTag"] = function() -- codecs/audio/ApeTag: APEv1 / APEv2 tags -> Types.Tags. -- From the APEv2 specification (wiki.hydrogenaud.io); no third-party code. Items + a 32-byte "APETAGEX" footer, optional -- 32-byte header (APEv2), before an optional ID3v1 tag. local ApeTag = {} type Item = { key: string, value: string, kind: string } type Info = { start: number, stop: number, version: number, items: { Item } } local TO_TAG: { [string]: string } = { year = "date", ["album artist"] = "albumartist", albumartist = "albumartist", tracknumber = "track", discnumber = "disc", description = "comment", } local KINDS = { [0] = "text", "binary", "link", "text" } function ApeTag.tagKey(key: string): string local k = string.lower(key) return TO_TAG[k] or k end function ApeTag.parse(buf: buffer, footer: number, start: number?): ({ [string]: string }?, Info?) local lo = start or 0 local n = buffer.len(buf) if footer < lo or footer + 32 > n or buffer.readstring(buf, footer, 8) ~= "APETAGEX" then return nil, nil end local version = buffer.readu32(buf, footer + 8) local size = buffer.readu32(buf, footer + 12) -- items + footer local count = buffer.readu32(buf, footer + 16) local flags = buffer.readu32(buf, footer + 20) if size < 32 or footer + 32 - size < lo then return nil, nil end local p = footer + 32 - size local first = p if version >= 2000 and bit32.band(flags, 0x80000000) ~= 0 and p - 32 >= lo and buffer.readstring(buf, p - 32, 8) == "APETAGEX" then first = p - 32 end local stop = footer local tags: { [string]: string } = {} local items: { Item } = {} for _ = 1, math.min(count, 65536) do if p + 9 > stop then break end local len = buffer.readu32(buf, p) local iflags = buffer.readu32(buf, p + 4) local k = p + 8 while k < stop and buffer.readu8(buf, k) ~= 0 do k += 1 end if k >= stop then break end local key = buffer.readstring(buf, p + 8, k - p - 8) local v0 = k + 1 if len > stop - v0 then break end local value = buffer.readstring(buf, v0, len) local kind = if version >= 2000 then KINDS[bit32.band(bit32.rshift(iflags, 1), 3)] else "text" table.insert(items, { key = key, value = value, kind = kind }) if kind == "text" and key ~= "" then local tk = ApeTag.tagKey(key) local s = (string.gsub(value, "%z+$", "")) s = (string.gsub(s, "%z", "; ")) local old = tags[tk] tags[tk] = if old then old .. "; " .. s else s end p = v0 + len end return tags, { start = first, stop = footer + 32, version = version, items = items } end function ApeTag.find(buf: buffer, start: number, limit: number): ({ [string]: string }?, Info?) if limit > buffer.len(buf) then limit = buffer.len(buf) end if limit - start >= 32 then local tags, info = ApeTag.parse(buf, limit - 32, start) if tags then return tags, info end end if limit - start >= 160 and buffer.readstring(buf, limit - 128, 3) == "TAG" then return ApeTag.parse(buf, limit - 160, start) end return nil, nil end return ApeTag end __FILES["codecs/audio/Flac"] = function() -- codecs/audio/Flac: FLAC frames without the container (frame header, subframes, CRC-8 / CRC-16) and the frame encoder. -- Absorbed from flac-luau 7083d0d; the encoder is new. local Flac = { Frame = __include("codecs/audio/Flac/Frame"), Encode = __include("codecs/audio/Flac/Encode"), } return Flac end __FILES["codecs/audio/Flac/Encode"] = @native function() -- codecs/audio/Flac/Encode: the FLAC encoder (RFC 9639), written from the RFC. -- The presets mirror libFLAC's -0 .. -8; QLP precision follows libFLAC's table. local Bits = __include("core/Bits") local Md5 = __include("core/Md5") local VorbisComment = __include("codecs/audio/VorbisComment") local Frame = __include("codecs/audio/Flac/Frame") local Encode = {} local floor, abs, log = math.floor, math.abs, math.log local readf32, writeu8 = buffer.readf32, buffer.writeu8 local POW = table.create(64, 0) for i = 0, 63 do POW[i + 1] = 2 ^ i end @native local function crc8(b: buffer, o: number, n: number): number return Frame.crc8(b, o, o + n) end @native local function crc16(b: buffer, o: number, n: number): number return Frame.crc16(b, o, o + n) end Encode.crc8, Encode.crc16 = crc8, crc16 type W = Bits.RawWriter @native local function ensure(w: W, n: number) local need = w.pos + n + 16 local cap = buffer.len(w.buf) if need > cap then local nb = buffer.create(math.max(cap * 2, need)) buffer.copy(nb, 0, w.buf, 0, w.pos) w.buf = nb end end local put = Bits.msbPut @native local function putSigned(w: W, v: number, n: number) put(w, if v < 0 then v + POW[n + 1] else v, n) end @native local function alignByte(w: W) if w.cnt > 0 then put(w, 0, 8 - w.cnt) end end @native local function putUtf8(w: W, v: number) if v < 0x80 then put(w, v, 8) return end local n = if v < 0x800 then 2 elseif v < 0x10000 then 3 elseif v < 0x200000 then 4 elseif v < 0x4000000 then 5 elseif v < 0x80000000 then 6 else 7 local first = if n == 7 then 0xFE else (0xFF00 // POW[n + 1]) % 256 -- n leading ones local shift = 6 * (n - 1) put(w, first + floor(v / POW[shift + 1]), 8) for k = n - 2, 0, -1 do put(w, 0x80 + floor(v / POW[6 * k + 1]) % 64, 8) end end type Config = { blockSize: number, maxLpcOrder: number, maxPartitionOrder: number, stereo: string, exhaustiveOrder: boolean, } local PRESETS: { Config } = { { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "independent", exhaustiveOrder = false }, { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "adaptive", exhaustiveOrder = false }, { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "exhaustive", exhaustiveOrder = false }, { blockSize = 4096, maxLpcOrder = 6, maxPartitionOrder = 4, stereo = "independent", exhaustiveOrder = false }, { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 4, stereo = "adaptive", exhaustiveOrder = false }, { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 5, stereo = "exhaustive", exhaustiveOrder = false }, { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = true }, } Encode.PRESETS = PRESETS type Plan = { kind: number, bits: number, order: number, wasted: number, bps: number, res: { number }, porder: number, params: { number }, method: number, -- 0 Rice (4-bit params), 1 Rice2 (5-bit) qlp: { number }, shift: number, precision: number, x: { number }, } @native local function newPlan(n: number): Plan return { kind = 1, bits = 0, order = 0, wasted = 0, bps = 16, res = table.create(n, 0), porder = 0, params = table.create(64, 0), method = 0, qlp = table.create(32, 0), shift = 0, precision = 0, x = table.create(n, 0), } end type Scratch = { sums: { number }, counts: { number }, ks: { number }, bestKs: { number }, tmpRes: { number }, win: { number }, winN: number, wx: { number }, autoc: { number }, lpc: { { number } }, err: { number }, qlp: { number }, } @native local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP: number): (number, number, number) local p = maxP while p > 0 and (n % POW[p + 1] ~= 0 or n // POW[p + 1] <= order) do p -= 1 end local sums, counts = sc.sums, sc.counts local parts = POW[p + 1] local ps = n // parts for j = 0, parts - 1 do local s = 0 local a = if j == 0 then order + 1 else j * ps + 1 local e = (j + 1) * ps for i = a, e do local r = res[i] s += if r >= 0 then 2 * r else -2 * r - 1 end sums[j + 1] = s counts[j + 1] = e - a + 1 end local bestBits, bestP, bestMethod = math.huge, 0, 0 local ks, bestKs = sc.ks, sc.bestKs local q = p while true do local np = POW[q + 1] local total = 0 local maxk = 0 for j = 1, np do local s, c = sums[j], counts[j] local k = 0 local cost = s + c -- k = 0: unary s, plus one stop bit per sample if c > 0 and s > c then local k0 = floor(log(s / c) / 0.6931471805599453) for kk = math.max(0, k0 - 1), math.min(30, k0 + 1) do local cc = c * (kk + 1) + floor(s / POW[kk + 1]) if cc < cost then cost, k = cc, kk end end end ks[j] = k if k > maxk then maxk = k end total += cost end local method = if maxk > 14 then 1 else 0 total += np * (if method == 1 then 5 else 4) + 2 + 4 if total < bestBits then bestBits, bestP, bestMethod = total, q, method for j = 1, np do bestKs[j] = ks[j] end end if q == 0 then break end for j = 1, np // 2 do sums[j] = sums[2 * j - 1] + sums[2 * j] counts[j] = counts[2 * j - 1] + counts[2 * j] end q -= 1 end return bestBits, bestP, bestMethod end @native local function keepRice(sc: Scratch, plan: Plan, porder: number, method: number) plan.porder, plan.method = porder, method local params = plan.params for j = 1, POW[porder + 1] do params[j] = sc.bestKs[j] end end @native local function fixedResidual(x: { number }, n: number, order: number, res: { number }) for i = 1, order do res[i] = 0 end if order == 0 then for i = 1, n do res[i] = x[i] end elseif order == 1 then for i = 2, n do res[i] = x[i] - x[i - 1] end elseif order == 2 then for i = 3, n do res[i] = x[i] - 2 * x[i - 1] + x[i - 2] end elseif order == 3 then for i = 4, n do res[i] = x[i] - 3 * x[i - 1] + 3 * x[i - 2] - x[i - 3] end else for i = 5, n do res[i] = x[i] - 4 * x[i - 1] + 6 * x[i - 2] - 4 * x[i - 3] + x[i - 4] end end end -- the fixed order with the smallest residual magnitude (libFLAC's estimate) @native local function bestFixedOrder(x: { number }, n: number): (number, number) if n <= 4 then return 0, 0 end local s0, s1, s2, s3, s4 = 0, 0, 0, 0, 0 local a, b, c, d = x[4], x[4] - x[3], x[4] - 2 * x[3] + x[2], x[4] - 3 * x[3] + 3 * x[2] - x[1] for i = 5, n do local e0 = x[i] local e1 = e0 - a local e2 = e1 - b local e3 = e2 - c local e4 = e3 - d s0 += abs(e0) s1 += abs(e1) s2 += abs(e2) s3 += abs(e3) s4 += abs(e4) a, b, c, d = e0, e1, e2, e3 end local best, bs = 0, s0 if s1 < bs then best, bs = 1, s1 end if s2 < bs then best, bs = 2, s2 end if s3 < bs then best, bs = 3, s3 end if s4 < bs then best, bs = 4, s4 end return best, bs end Encode.bestFixedOrder = bestFixedOrder -- libFLAC's default QLP coefficient precision for a block size @native local function qlpPrecision(bps: number, n: number): number if bps > 16 then return 15 end if n <= 192 then return 7 elseif n <= 384 then return 8 elseif n <= 576 then return 9 elseif n <= 1152 then return 10 elseif n <= 2304 then return 11 elseif n <= 4608 then return 12 end return 13 end @native local function quantize(lp: { number }, order: number, precision: number, qlp: { number }): number? local cmax = 0 for i = 1, order do local a = abs(lp[i]) if a > cmax then cmax = a end end if cmax <= 0 or cmax ~= cmax or cmax == math.huge then return nil end local log2cmax = 0 while cmax >= 1 do cmax /= 2 log2cmax += 1 end while cmax < 0.5 do cmax *= 2 log2cmax -= 1 end -- frexp: cmax = m * 2^log2cmax with m in [0.5, 1) log2cmax -= 1 local p = precision - 1 local qmax = POW[p + 1] - 1 local qmin = -POW[p + 1] local shift = p - log2cmax - 1 if shift > 15 then shift = 15 elseif shift < 0 then return nil end local err = 0 local scale = POW[shift + 1] for i = 1, order do err += lp[i] * scale local q = floor(err + 0.5) if q > qmax then q = qmax elseif q < qmin then q = qmin end err -= q qlp[i] = q end return shift end @native local function lpcResidual(x: { number }, n: number, order: number, qlp: { number }, shift: number, res: { number }) local d = POW[shift + 1] for i = 1, order do res[i] = 0 end for i = order + 1, n do local s = 0 for j = 1, order do s += qlp[j] * x[i - j] end res[i] = x[i] - floor(s / d) end end @native local function levinson(sc: Scratch, maxOrder: number): number local r = sc.autoc local e = r[1] if e <= 0 then return 0 end local a = table.create(maxOrder + 1, 0) local tmp = table.create(maxOrder + 1, 0) for o = 1, maxOrder do local acc = r[o + 1] for j = 1, o - 1 do acc -= a[j] * r[o - j + 1] end local k = acc / e for j = 1, o - 1 do tmp[j] = a[j] - k * a[o - j] end for j = 1, o - 1 do a[j] = tmp[j] end a[o] = k e *= (1 - k * k) local row = sc.lpc[o] for j = 1, o do row[j] = a[j] end sc.err[o] = e if e <= 0 then return o end end return maxOrder end @native local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps: number, plan: Plan) local x = plan.x local first = src[1] local constant = true for i = 1, n do local v = src[i] if v ~= first then constant = false end end if constant then plan.kind, plan.bits, plan.wasted, plan.bps = 0, 8 + bps, 0, bps plan.res[1] = first return end local wasted = 0 do local w = 0 while w < bps - 1 do local m = POW[w + 2] local all = true for i = 1, n do if src[i] % m ~= 0 then all = false break end end if not all then break end w += 1 end wasted = w end local d = POW[wasted + 1] for i = 1, n do x[i] = src[i] / d end local b = bps - wasted local hdr = 8 + wasted plan.wasted, plan.bps = wasted, b plan.kind, plan.bits = 1, hdr + n * b local fo = bestFixedOrder(x, n) if n > fo then local tmp = sc.tmpRes fixedResidual(x, n, fo, tmp) local rb, po, me = rice(sc, tmp, n, fo, cfg.maxPartitionOrder) local bits = hdr + fo * b + rb if bits < plan.bits then plan.kind, plan.bits, plan.order = 2, bits, fo sc.tmpRes, plan.res = plan.res, tmp keepRice(sc, plan, po, me) end end local maxOrder = math.min(cfg.maxLpcOrder, n - 1, 32) if maxOrder > 0 then local win = sc.win if sc.winN ~= n then -- tukey(0.5) local np = floor(0.25 * n) for i = 1, n do win[i] = 1 end if np > 0 then for i = 0, np - 1 do local v = 0.5 - 0.5 * math.cos(math.pi * i / np) win[i + 1] = v win[n - i] = v end end sc.winN = n end local wx = sc.wx for i = 1, n do wx[i] = x[i] * win[i] end local ac = sc.autoc for lag = 0, maxOrder do local s = 0 for i = lag + 1, n do s += wx[i] * wx[i - lag] end ac[lag + 1] = s end local top = levinson(sc, maxOrder) if top > 0 then local precision = qlpPrecision(b, n) local orders = {} if cfg.exhaustiveOrder then for o = 1, top do table.insert(orders, o) end else -- estimated bits: (n - o) * 0.5 * log2(err_o / n) + o * precision local bestO, bestE = 1, math.huge for o = 1, top do local e = sc.err[o] local est = if e > 0 then (n - o) * 0.5 * log(e / n) / 0.6931471805599453 + o * (precision + b) else -math.huge if est < bestE then bestO, bestE = o, est end end orders[1] = bestO end local qlp = sc.qlp for _, o in orders do local prec = precision local shift = quantize(sc.lpc[o], o, prec, qlp) if shift then local tmp = sc.tmpRes lpcResidual(x, n, o, qlp, shift, tmp) local rb, po, me = rice(sc, tmp, n, o, cfg.maxPartitionOrder) local bits = hdr + o * b + 4 + 5 + o * prec + rb if bits < plan.bits then plan.kind, plan.bits, plan.order = 3, bits, o plan.shift, plan.precision = shift, prec for j = 1, o do plan.qlp[j] = qlp[j] end sc.tmpRes, plan.res = plan.res, tmp keepRice(sc, plan, po, me) end end end end end end @native local function writeResidual(w: W, plan: Plan, n: number) local method = plan.method put(w, method, 2) local porder = plan.porder put(w, porder, 4) local parts = POW[porder + 1] local ps = n // parts local res = plan.res local pbits = if method == 1 then 5 else 4 for j = 0, parts - 1 do local k = plan.params[j + 1] put(w, k, pbits) local a = if j == 0 then plan.order + 1 else j * ps + 1 local e = (j + 1) * ps local mk = POW[k + 1] for i = a, e do local r = res[i] local u = if r >= 0 then 2 * r else -2 * r - 1 local hi = floor(u / mk) local lo = u - hi * mk if hi + 1 + k <= 32 then put(w, mk + lo, hi + 1 + k) else local q = hi while q > 24 do put(w, 0, 24) q -= 24 end put(w, 1, q + 1) put(w, lo, k) end end end end @native local function writeSubframe(w: W, plan: Plan, n: number) local kind = plan.kind local typ = if kind == 0 then 0 elseif kind == 1 then 1 elseif kind == 2 then 8 + plan.order else 32 + plan.order - 1 put(w, 0, 1) put(w, typ, 6) if kind ~= 0 and plan.wasted > 0 then put(w, 1, 1) put(w, 1, plan.wasted) -- k - 1 zeros, then a one else put(w, 0, 1) end local b = plan.bps if kind == 0 then putSigned(w, plan.res[1], b) return end local x = plan.x if kind == 1 then for i = 1, n do putSigned(w, x[i], b) end return end for i = 1, plan.order do putSigned(w, x[i], b) end if kind == 3 then put(w, plan.precision - 1, 4) put(w, plan.shift, 5) for j = 1, plan.order do putSigned(w, plan.qlp[j], plan.precision) end end writeResidual(w, plan, n) end local RATE_CODES: { [number]: number } = { [88200] = 1, [176400] = 2, [192000] = 3, [8000] = 4, [16000] = 5, [22050] = 6, [24000] = 7, [32000] = 8, [44100] = 9, [48000] = 10, [96000] = 11, } local SIZE_CODES: { [number]: number } = { [8] = 1, [12] = 2, [16] = 4, [20] = 5, [24] = 6, [32] = 7 } @native local function blockCode(n: number): (number, number) -- code, extra bits (0, 8, 16) if n == 192 then return 1, 0 end for k = 2, 5 do if n == 576 * POW[k - 1] then return k, 0 end end for k = 8, 15 do if n == 256 * POW[k - 7] then return k, 0 end end if n <= 256 then return 6, 8 end return 7, 16 end type Source = { sampleRate: number, channels: number, frames: number, tags: { [string]: string }, read: (self: any, n: number, out: buffer?) -> (buffer, number), err: any, } type Options = { level: number, bits: number, blockSize: number?, seekInterval: number, padding: number, vendor: string, } @native function Encode.encode(src: Source, opts: Options): (buffer?, string?) local cfg = PRESETS[opts.level + 1] local ch, rate, bps = src.channels, src.sampleRate, opts.bits local bs = opts.blockSize or cfg.blockSize local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } put(w, 0x664C6143, 32) -- "fLaC" put(w, 0, 1) put(w, 0, 7) put(w, 34, 24) local siData = w.pos for _ = 1, 34 do put(w, 0, 8) end local seekPoints = 0 local seekAt = 0 local interval = floor(opts.seekInterval * rate) if interval > 0 and src.frames > 0 then seekPoints = (src.frames - 1) // interval + 1 if seekPoints > 65535 // 18 * 18 then seekPoints = 0 end end local comments = VorbisComment.fields(src.tags) local vendor = opts.vendor local vcLen = 4 + #vendor + 4 for _, c in comments do vcLen += 4 + #c end if seekPoints > 0 then put(w, 0, 1) put(w, 3, 7) put(w, seekPoints * 18, 24) seekAt = w.pos ensure(w, seekPoints * 18) for _ = 1, seekPoints do put(w, 0xFFFFFFFF, 32) -- sample number: a placeholder until a frame fills it put(w, 0xFFFFFFFF, 32) put(w, 0, 32) -- byte offset put(w, 0, 32) put(w, 0, 16) -- frame samples end end -- VORBIS_COMMENT (little-endian lengths) @native local function le32(v: number) put(w, v % 256, 8) put(w, (v // 256) % 256, 8) put(w, (v // 65536) % 256, 8) put(w, v // 16777216, 8) end ensure(w, vcLen + 8) put(w, if opts.padding > 0 then 0 else 1, 1) -- the last metadata block unless PADDING follows put(w, 4, 7) put(w, vcLen, 24) le32(#vendor) for i = 1, #vendor do put(w, string.byte(vendor, i), 8) end le32(#comments) for _, c in comments do ensure(w, #c + 8) le32(#c) for i = 1, #c do put(w, string.byte(c, i), 8) end end if opts.padding > 0 then ensure(w, opts.padding + 8) put(w, 1, 1) put(w, 1, 7) put(w, opts.padding, 24) for _ = 1, opts.padding do put(w, 0, 8) end end local audioStart = w.pos local md5 = Md5.new() local mbytes = (bps + 7) // 8 local mbuf = buffer.create(bs * ch * mbytes) local scale = POW[bps] local maxv, minv = scale - 1, -scale local X: { { number } } = table.create(ch) :: any for c = 1, ch do X[c] = table.create(bs, 0) end local side = table.create(bs, 0) local mid = table.create(bs, 0) local plans = {} for i = 1, 4 do plans[i] = newPlan(bs) end for c = 1, ch do plans[4 + c] = newPlan(bs) end local lpcRows = {} for o = 1, 32 do lpcRows[o] = table.create(o, 0) end local sc: Scratch = { sums = table.create(64, 0), counts = table.create(64, 0), ks = table.create(64, 0), bestKs = table.create(64, 0), tmpRes = table.create(bs, 0), win = table.create(bs, 0), winN = 0, wx = table.create(bs, 0), autoc = table.create(33, 0), lpc = lpcRows, err = table.create(32, 0), qlp = table.create(32, 0), } local frameNo = 0 local total = 0 local minFrame, maxFrame = math.huge, 0 local seekNext = 0 local seekIdx = 0 local rateCode = RATE_CODES[rate] or 0 local sizeCode = SIZE_CODES[bps] or 0 local tmp: buffer? = nil local pendingBuf: buffer? = nil local pendingN, pendingOff = 0, 0 @native local function readBlock(): (buffer?, number) local out = buffer.create(bs * ch * 4) local got = 0 while got < bs do if pendingN == 0 then local b, n = src:read(math.max(bs, 4096), tmp) if n <= 0 then break end tmp = b pendingBuf, pendingN, pendingOff = b, n, 0 end local take = math.min(bs - got, pendingN) buffer.copy(out, got * ch * 4, pendingBuf :: buffer, pendingOff * ch * 4, take * ch * 4) got += take pendingN -= take pendingOff += take end return out, got end while true do local fb, n = readBlock() if n <= 0 or fb == nil then break end -- to integers (+ the MD5 bytes, signed little endian) local mo = 0 for i = 0, n - 1 do for c = 1, ch do local v = floor(readf32(fb, (i * ch + c - 1) * 4) * scale + 0.5) if v ~= v then v = 0 elseif v > maxv then v = maxv elseif v < minv then v = minv end X[c][i + 1] = v local u = if v < 0 then v + 4294967296 else v for k = 0, mbytes - 1 do writeu8(mbuf, mo, floor(u / POW[8 * k + 1]) % 256) mo += 1 end end end md5:update(mbuf, 0, mo) local assign = ch - 1 local chosen: { Plan } = {} if ch == 2 and cfg.stereo ~= "independent" then local L, R = X[1], X[2] for i = 1, n do local l, r = L[i], R[i] side[i] = l - r mid[i] = floor((l + r) / 2) end local pl, pr, pm, ps = plans[1], plans[2], plans[3], plans[4] if cfg.stereo == "adaptive" then local _, el = bestFixedOrder(L, n) local _, er = bestFixedOrder(R, n) local _, em = bestFixedOrder(mid, n) local _, es = bestFixedOrder(side, n) -- the estimate picks one decorrelated pair; it is kept only if it beats left / right for real local best = math.min(el + es, er + es, em + es) analyze(sc, cfg, L, n, bps, pl) analyze(sc, cfg, R, n, bps, pr) chosen, assign = { pl, pr }, 1 if best < el + er then analyze(sc, cfg, side, n, bps + 1, ps) if best == em + es then analyze(sc, cfg, mid, n, bps, pm) if pm.bits + ps.bits < pl.bits + pr.bits then chosen, assign = { pm, ps }, 10 end elseif best == el + es then if pl.bits + ps.bits < pl.bits + pr.bits then chosen, assign = { pl, ps }, 8 end elseif ps.bits + pr.bits < pl.bits + pr.bits then chosen, assign = { ps, pr }, 9 end end else analyze(sc, cfg, L, n, bps, pl) analyze(sc, cfg, R, n, bps, pr) analyze(sc, cfg, mid, n, bps, pm) analyze(sc, cfg, side, n, bps + 1, ps) local lr, ls, rs, msb = pl.bits + pr.bits, pl.bits + ps.bits, ps.bits + pr.bits, pm.bits + ps.bits local best = math.min(lr, ls, rs, msb) if best == lr then chosen, assign = { pl, pr }, 1 elseif best == msb then chosen, assign = { pm, ps }, 10 elseif best == ls then chosen, assign = { pl, ps }, 8 else chosen, assign = { ps, pr }, 9 end end else for c = 1, ch do analyze(sc, cfg, X[c], n, bps, plans[4 + c]) chosen[c] = plans[4 + c] end end local need = n * ch * 4 + 64 for _, p in chosen do need += (p.bits // 8) + 8 end ensure(w, need) local start = w.pos while seekIdx < seekPoints and total >= seekNext do local at = seekAt + seekIdx * 18 local sn, off = total, start - audioStart local tb = w.buf for k = 0, 7 do writeu8(tb, at + k, floor(sn / POW[8 * (7 - k) + 1]) % 256) writeu8(tb, at + 8 + k, floor(off / POW[8 * (7 - k) + 1]) % 256) end writeu8(tb, at + 16, n // 256) writeu8(tb, at + 17, n % 256) seekIdx += 1 seekNext = seekIdx * interval end put(w, 0x3FFE, 14) put(w, 0, 1) put(w, 0, 1) -- fixed block size local bcode, bextra = blockCode(n) put(w, bcode, 4) put(w, rateCode, 4) put(w, assign, 4) put(w, sizeCode, 3) put(w, 0, 1) putUtf8(w, frameNo) if bextra > 0 then put(w, n - 1, bextra) end put(w, crc8(w.buf, start, w.pos - start), 8) for _, p in chosen do writeSubframe(w, p, n) end alignByte(w) local c16 = crc16(w.buf, start, w.pos - start) put(w, c16, 16) local fsize = w.pos - start if fsize < minFrame then minFrame = fsize end if fsize > maxFrame then maxFrame = fsize end frameNo += 1 total += n if n < bs then break end end if src.err then return nil, tostring(src.err) end local out = buffer.create(w.pos) buffer.copy(out, 0, w.buf, 0, w.pos) local si = Encode.streaminfo(bs, if frameNo > 0 then minFrame else 0, maxFrame, rate, ch, bps, total, md5:digest()) buffer.copy(out, siData, si, 0, 34) return out, nil end -- STREAMINFO: 34 bytes @native function Encode.streaminfo(bs: number, minFrame: number, maxFrame: number, rate: number, ch: number, bps: number, total: number, md5: string): buffer local w: W = { buf = buffer.create(64), pos = 0, acc = 0, cnt = 0 } put(w, bs, 16) put(w, bs, 16) put(w, minFrame, 24) put(w, maxFrame, 24) put(w, rate, 20) put(w, ch - 1, 3) put(w, bps - 1, 5) put(w, floor(total / 2 ^ 32), 4) put(w, total % 2 ^ 32, 32) for i = 1, 16 do put(w, string.byte(md5, i), 8) end local out = buffer.create(34) buffer.copy(out, 0, w.buf, 0, 34) return out end return Encode end __FILES["codecs/audio/Flac/Frame"] = @native function() -- codecs/audio/Flac/Frame: FLAC frames: header (CRC-8), sync search, subframes, residuals, decorrelation, CRC-16. -- Absorbed from flac-luau 7083d0d (no third-party code). The input needs PAD zero bytes after `len`: the bit reader -- reads 32-bit words unchecked and compares its position with the data end once per sample. local readu8, readu32 = buffer.readu8, buffer.readu32 local band, bxor, lshift, rshift, countlz, byteswap = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift, bit32.countlz, bit32.byteswap local floor = math.floor local Frame = {} Frame.PAD = 32 -- CRC-8 (poly 0x07) and CRC-16 (poly 0x8005), MSB first, init 0 local CRC8 = table.create(256, 0) local CRC16 = table.create(256, 0) for i = 0, 255 do local c = i for _ = 1, 8 do c = if band(c, 0x80) ~= 0 then band(bxor(lshift(c, 1), 0x07), 0xFF) else band(lshift(c, 1), 0xFF) end CRC8[i + 1] = c local d = lshift(i, 8) for _ = 1, 8 do d = if band(d, 0x8000) ~= 0 then band(bxor(lshift(d, 1), 0x8005), 0xFFFF) else band(lshift(d, 1), 0xFFFF) end CRC16[i + 1] = d end @native local function crc16(b: buffer, from: number, to: number): number local c = 0 for i = from, to - 1 do c = bxor(band(lshift(c, 8), 0xFFFF), CRC16[bxor(rshift(c, 8), readu8(b, i)) + 1]) end return c end Frame.crc16 = crc16 @native local function crc8(b: buffer, from: number, to: number): number local c = 0 for i = from, to - 1 do c = CRC8[bxor(c, readu8(b, i)) + 1] end return c end Frame.crc8 = crc8 local POW2 = table.create(64, 0) for i = 0, 63 do POW2[i + 1] = 2 ^ i end local BLOCK = { [1] = 192, [2] = 576, [3] = 1152, [4] = 2304, [5] = 4608, [8] = 256, [9] = 512, [10] = 1024, [11] = 2048, [12] = 4096, [13] = 8192, [14] = 16384, [15] = 32768 } local RATE = { [1] = 88200, [2] = 176400, [3] = 192000, [4] = 8000, [5] = 16000, [6] = 22050, [7] = 24000, [8] = 32000, [9] = 44100, [10] = 48000, [11] = 96000 } local BITS = { [1] = 8, [2] = 12, [4] = 16, [5] = 20, [6] = 24, [7] = 32 } type Header = { offset: number, size: number, -- header bytes, CRC-8 included blockSize: number, sampleRate: number, channels: number, assignment: number, -- 0..7 independent, 8 left/side, 9 side/right, 10 mid/side bps: number, variable: boolean, -- variable block size: number is a sample number, else a frame number number: number, } @native function Frame.header(b: buffer, pos: number, len: number, si: any): Header? if pos < 0 or pos + 6 > len then return nil end if readu8(b, pos) ~= 0xFF then return nil end local b1 = readu8(b, pos + 1) if band(b1, 0xFE) ~= 0xF8 then return nil end local b2 = readu8(b, pos + 2) local b3 = readu8(b, pos + 3) local bsCode, rCode = rshift(b2, 4), band(b2, 15) local chCode, sCode = rshift(b3, 4), band(rshift(b3, 1), 7) if bsCode == 0 or rCode == 15 or chCode > 10 or sCode == 3 or band(b3, 1) ~= 0 then return nil end -- UTF-8-like coded number local p = pos + 4 local x = readu8(b, p) p += 1 local num, more if x < 0x80 then num, more = x, 0 elseif x >= 0xC0 and x < 0xE0 then num, more = band(x, 0x1F), 1 elseif x >= 0xE0 and x < 0xF0 then num, more = band(x, 0x0F), 2 elseif x >= 0xF0 and x < 0xF8 then num, more = band(x, 0x07), 3 elseif x >= 0xF8 and x < 0xFC then num, more = band(x, 0x03), 4 elseif x >= 0xFC and x < 0xFE then num, more = band(x, 0x01), 5 elseif x == 0xFE then num, more = 0, 6 else return nil end for _ = 1, more do local c = readu8(b, p) p += 1 if band(c, 0xC0) ~= 0x80 then return nil end num = num * 64 + band(c, 0x3F) end local variable = band(b1, 1) == 1 if not variable and more > 5 then return nil end local bs = BLOCK[bsCode] if bsCode == 6 then bs = readu8(b, p) + 1 p += 1 elseif bsCode == 7 then bs = readu8(b, p) * 256 + readu8(b, p + 1) + 1 p += 2 end local rate = RATE[rCode] if rCode == 0 then rate = si and si.sampleRate or 0 elseif rCode == 12 then rate = readu8(b, p) * 1000 p += 1 elseif rCode == 13 then rate = readu8(b, p) * 256 + readu8(b, p + 1) p += 2 elseif rCode == 14 then rate = (readu8(b, p) * 256 + readu8(b, p + 1)) * 10 p += 2 end local bps = BITS[sCode] if sCode == 0 then bps = si and si.bitsPerSample or 0 end if not bs or not bps or bps < 4 or bps > 32 or p + 1 > len then return nil end if crc8(b, pos, p) ~= readu8(b, p) then return nil end return { offset = pos, size = p + 1 - pos, blockSize = bs, sampleRate = rate or 0, channels = if chCode < 8 then chCode + 1 else 2, assignment = chCode, bps = bps, variable = variable, number = num, } end @native function Frame.find(b: buffer, pos: number, limit: number, len: number, si: any): Header? local lim = math.min(limit, len - 6) if pos < 0 then pos = 0 end while pos < lim do if readu8(b, pos) == 0xFF then local b1 = readu8(b, pos + 1) if b1 == 0xF8 or b1 == 0xF9 then local h = Frame.header(b, pos, len, si) if h then return h end end end pos += 1 end return nil end @native local function bits(b: buffer, p: number, n: number): number if n == 0 then return 0 elseif n <= 24 then return rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - n) end local hi = rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - (n - 16)) local q = p + n - 16 return hi * 65536 + rshift(lshift(byteswap(readu32(b, rshift(q, 3))), band(q, 7)), 16) end @native local function sbits(b: buffer, p: number, n: number): number local v = bits(b, p, n) if n > 0 and v >= POW2[n] then v -= POW2[n + 1] end return v end @native local function residual(b: buffer, p: number, lim: number, s: { number }, n: number, order: number): number local method = bits(b, p, 2) if method > 1 then return -1 end local porder = bits(b, p + 2, 4) p += 6 local pbits = if method == 0 then 4 else 5 local escape = if method == 0 then 15 else 31 local parts = POW2[porder + 1] local psize = rshift(n, porder) if psize * parts ~= n or psize < order then return -1 end local i = order + 1 for part = 0, parts - 1 do if p > lim then return -1 end local k = bits(b, p, pbits) p += pbits local stop = (part + 1) * psize if k == escape then local nb = bits(b, p, 5) p += 5 if nb == 0 then for j = i, stop do s[j] = 0 end else local half, full = POW2[nb], POW2[nb + 1] for j = i, stop do if p > lim then return -1 end local v = bits(b, p, nb) p += nb if v >= half then v -= full end s[j] = v end end elseif k <= 24 then local pk = POW2[k + 1] local rk = 32 - k for j = i, stop do if p > lim then return -1 end local sh = band(p, 7) local w = lshift(byteswap(readu32(b, rshift(p, 3))), sh) local q, r if w ~= 0 then q = countlz(w) local used = q + 1 + k if used <= 32 - sh then r = if k == 0 then 0 else rshift(lshift(w, q + 1), rk) p += used else p += q + 1 r = if k == 0 then 0 else rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) p += k end else q = 32 - sh p += q while true do if p > lim then return -1 end local w2 = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)) if w2 ~= 0 then local z = countlz(w2) q += z p += z + 1 break end local adv = 32 - band(p, 7) q += adv p += adv end r = if k == 0 then 0 else rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) p += k end local u = q * pk + r local h = floor(u * 0.5) s[j] = if h + h == u then h else -h - 1 end else -- k = 25..30 (Rice2): the remainder takes two reads local pk = POW2[k + 1] for j = i, stop do if p > lim then return -1 end local q = 0 while true do if p > lim then return -1 end local w = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)) if w ~= 0 then local z = countlz(w) q += z p += z + 1 break end local adv = 32 - band(p, 7) q += adv p += adv end local r = bits(b, p, k) p += k local u = q * pk + r local h = floor(u * 0.5) s[j] = if h + h == u then h else -h - 1 end end i = stop + 1 end return p end @native local function fixed(s: { number }, n: number, order: number) if order == 1 then local a = s[1] for i = 2, n do a += s[i] s[i] = a end elseif order == 2 then local a, c = s[2], s[1] for i = 3, n do local v = s[i] + 2 * a - c s[i] = v c = a a = v end elseif order == 3 then local a, c, d = s[3], s[2], s[1] for i = 4, n do local v = s[i] + 3 * a - 3 * c + d s[i] = v d = c c = a a = v end elseif order == 4 then local a, c, d, e = s[4], s[3], s[2], s[1] for i = 5, n do local v = s[i] + 4 * a - 6 * c + 4 * d - e s[i] = v e = d d = c c = a a = v end end end -- LPC restoration: s[i] += floor(sum(coef[j] * s[i - j]) / 2^shift); unrolled for orders up to 12 @native local function lpc(s: { number }, n: number, cf: { number }, order: number, shift: number) local div = POW2[shift + 1] local inv = 1 / div if order <= 4 then local c1, c2, c3, c4 = cf[1], cf[2] or 0, cf[3] or 0, cf[4] or 0 local s1, s2, s3, s4 = s[order], s[order - 1] or 0, s[order - 2] or 0, s[order - 3] or 0 for i = order + 1, n do local v = s[i] + floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4) * inv) s[i] = v s4 = s3 s3 = s2 s2 = s1 s1 = v end elseif order <= 8 then local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6] or 0, cf[7] or 0, cf[8] or 0 local s1, s2, s3, s4, s5 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4] local s6, s7, s8 = s[order - 5] or 0, s[order - 6] or 0, s[order - 7] or 0 for i = order + 1, n do local v = s[i] + floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6 + c7 * s7 + c8 * s8) * inv) s[i] = v s8 = s7 s7 = s6 s6 = s5 s5 = s4 s4 = s3 s3 = s2 s2 = s1 s1 = v end elseif order <= 12 then local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6], cf[7], cf[8] local c9, c10, c11, c12 = cf[9], cf[10] or 0, cf[11] or 0, cf[12] or 0 local s1, s2, s3, s4, s5, s6 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4], s[order - 5] local s7, s8, s9 = s[order - 6], s[order - 7], s[order - 8] local s10, s11, s12 = s[order - 9] or 0, s[order - 10] or 0, s[order - 11] or 0 for i = order + 1, n do local v = s[i] + floor( ( c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6 + c7 * s7 + c8 * s8 + c9 * s9 + c10 * s10 + c11 * s11 + c12 * s12 ) * inv ) s[i] = v s12 = s11 s11 = s10 s10 = s9 s9 = s8 s8 = s7 s7 = s6 s6 = s5 s5 = s4 s4 = s3 s3 = s2 s2 = s1 s1 = v end else for i = order + 1, n do local sum = 0 for j = 1, order do sum += cf[j] * s[i - j] end s[i] += floor(sum * inv) end end end @native local function subframe(b: buffer, p: number, lim: number, s: { number }, n: number, bps: number, cf: { number }): number if p > lim then return -1 end local hdr = bits(b, p, 8) p += 8 if hdr >= 128 then return -1 end local typ = rshift(hdr, 1) local wasted = 0 if band(hdr, 1) == 1 then -- unary count of wasted bits (minus one) while true do if p > lim or wasted > 32 then return -1 end local bit = bits(b, p, 1) p += 1 wasted += 1 if bit == 1 then break end end bps -= wasted if bps < 1 then return -1 end end if typ == 0 then local v = sbits(b, p, bps) p += bps for i = 1, n do s[i] = v end elseif typ == 1 then for i = 1, n do if p > lim then return -1 end s[i] = sbits(b, p, bps) p += bps end elseif typ >= 8 and typ <= 12 then local order = typ - 8 if order > n then return -1 end for i = 1, order do if p > lim then return -1 end s[i] = sbits(b, p, bps) p += bps end p = residual(b, p, lim, s, n, order) if p < 0 then return -1 end fixed(s, n, order) elseif typ >= 32 then local order = typ - 31 if order > n then return -1 end for i = 1, order do if p > lim then return -1 end s[i] = sbits(b, p, bps) p += bps end local prec = bits(b, p, 4) + 1 p += 4 if prec == 16 then return -1 end local shift = sbits(b, p, 5) p += 5 if shift < 0 then return -1 end for j = 1, order do if p > lim then return -1 end cf[j] = sbits(b, p, prec) p += prec end for j = order + 1, 12 do cf[j] = 0 -- the unrolled filters read up to 12 coefficients end p = residual(b, p, lim, s, n, order) if p < 0 then return -1 end lpc(s, n, cf, order, shift) else return -1 end if wasted > 0 then local m = POW2[wasted + 1] for i = 1, n do s[i] *= m end end return p end @native function Frame.decode(b: buffer, len: number, h: Header, chans: { { number } }, cf: { number }, checkCrc: boolean): (number?, string?) local n = h.blockSize local lim = len * 8 local p = (h.offset + h.size) * 8 local asg = h.assignment for c = 1, h.channels do local bps = h.bps if (asg == 8 and c == 2) or (asg == 9 and c == 1) or (asg == 10 and c == 2) then bps += 1 -- the side channel end p = subframe(b, p, lim, chans[c], n, bps, cf) if p < 0 then return nil, "bad subframe" end end local e = rshift(p + 7, 3) if e + 2 > len then return nil, "truncated frame" end if checkCrc then local want = readu8(b, e) * 256 + readu8(b, e + 1) if crc16(b, h.offset, e) ~= want then return nil, "crc16 mismatch" end end if asg >= 8 then local l, r = chans[1], chans[2] if asg == 8 then for i = 1, n do r[i] = l[i] - r[i] end elseif asg == 9 then for i = 1, n do l[i] += r[i] end else for i = 1, n do local side = r[i] local m = l[i] * 2 + (side % 2) l[i] = (m + side) * 0.5 r[i] = (m - side) * 0.5 end end end return e + 2, nil end return Frame end __FILES["codecs/audio/Hively"] = function() -- codecs/audio/Hively: the AHX / HivelyTracker engine (loader, replayer, waveform tables, render glue). -- A port of hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt); at -- hvl2wav's settings the output equals its 16-bit samples / 32768. hvl2wav pads a 44.1 kHz speed-multiplier-4 frame to -- 882 samples with stale data; this renders 880. local Err = __include("core/Err") local Types = __include("Types") local Load = __include("codecs/audio/Hively/Load") local Player = __include("codecs/audio/Hively/Player") local Pcm = __include("codecs/audio/Pcm") local Hively = {} type Tune = Load.Tune type RenderOptions = { sampleRate: number?, subsong: number?, stereo: number?, -- AHX stereo separation 0..4 (4 = 100 % Amiga L R R L); default 0 as hvl2wav loop: boolean?, maxDuration: number?, -- seconds, default 600 (hvl2wav's 10 minute limit) } function Hively.parse(b: buffer, base: number?, limit: number?): (Tune?, Err.Err?) local tune, msg, kind = Load.parse(b, base or 0, limit or buffer.len(b)) if not tune then return nil, Err.from(msg or "corrupt", nil, kind) end return tune, nil end local function settings(tune: Tune, opts: RenderOptions?): (number?, number, number, Err.Err?) local o: RenderOptions = opts or {} local rate = o.sampleRate or 44100 if type(rate) ~= "number" or rate < 8000 or rate > 192000 or rate % 1 ~= 0 then return nil, 0, 0, Err.new(Err.ARG, "render: sampleRate must be an integer 8000..192000") end local sub = o.subsong or 0 if type(sub) ~= "number" or sub < 0 or sub > #tune.subsongs or sub % 1 ~= 0 then return nil, 0, 0, Err.new(Err.ARG, string.format("render: subsong must be 0..%d", #tune.subsongs)) end return rate, sub, tonumber(o.stereo) or 0, nil end function Hively.frameCount(tune: Tune, opts: RenderOptions?): number local rate, sub, stereo = settings(tune, opts) local st = rate and Player.new(tune, rate :: number, stereo, sub) if not st then return 0 end local maxFrames = math.floor(((opts and opts.maxDuration) or 600) * 50) local n = 0 while n < maxFrames and not st.songEndReached do for _ = 1, tune.speedMultiplier do Player.irq(st, false) end n += 1 end return n end function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err.Err?) local rate, sub, stereo, err = settings(tune, opts) if not rate then return nil, err end local sr = rate :: number local mult = tune.speedMultiplier local perIrq = sr // 50 // mult local perFrame = perIrq * mult local nframes = Hively.frameCount(tune, opts) local frames = nframes * perFrame local loop = opts ~= nil and opts.loop == true local st = Player.new(tune, sr, stereo, sub) :: Player.State local fbuf = buffer.create(perFrame * 8) local fpos, ffill = 0, 0 local pos = 0 local function nextFrame() for k = 0, mult - 1 do Player.irq(st, true) Player.mix(st, fbuf, k * perIrq, perIrq) end fpos, ffill = 0, perFrame end local dec = { sampleRate = sr, channels = 2, frames = frames, duration = frames / sr, bitrate = 0, tags = { title = if tune.title ~= "" then tune.title else nil } :: Types.Tags, } local function read(_self: any, n: number, out: buffer?): (buffer, number) n = math.max(0, math.floor(n)) if not loop then n = math.min(n, frames - pos) end local b = out if not b or buffer.len(b) < n * 8 then b = buffer.create(math.max(n, 1) * 8) end local ob = b :: buffer local done = 0 while done < n do if fpos >= ffill then nextFrame() end local k = math.min(n - done, ffill - fpos) buffer.copy(ob, done * 8, fbuf, fpos * 8, k * 8) fpos += k done += k end pos += n return ob, n end dec.read = read :: any local scratch = buffer.create(4096 * 8) dec.seek = function(_self: any, seconds: number) local target = math.max(0, math.floor((tonumber(seconds) or 0) * sr)) if not loop then target = math.min(target, frames) end if target < pos then st = Player.new(tune, sr, stereo, sub) :: Player.State pos, fpos, ffill = 0, 0, 0 end while pos < target do read(nil, math.min(4096, target - pos), scratch) end end :: any dec.position = function(_self: any): number return pos / sr end :: any return (dec :: any) :: Types.Decoder, nil end function Hively.module(tune: Tune): Types.Module local patterns = {} for t = 0, tune.trackNr do local data = buffer.create(tune.trackLength * 6) buffer.copy(data, 0, tune.tracks, t * 64 * 6, tune.trackLength * 6) patterns[t + 1] = { rows = tune.trackLength, data = data } end local order, positions = {}, {} for i = 0, tune.positionNr - 1 do order[i + 1] = i local tr, tp = {}, {} for c = 0, tune.channels - 1 do tr[c + 1] = buffer.readu8(tune.positions, (i * 16 + c) * 2) tp[c + 1] = buffer.readi8(tune.positions, (i * 16 + c) * 2 + 1) end positions[i + 1] = { tracks = tr, transpose = tp } end local m: any = { kind = "music", format = tune.format, title = tune.title, channels = tune.channels, speed = 6, tempo = 125 * tune.speedMultiplier, -- 50 Hz player calls per speed multiplier (a tick lasts 2.5 / tempo s) patterns = patterns, order = order, positions = positions, restart = tune.restart, subsongs = table.clone(tune.subsongs), instruments = tune.instruments, samples = {}, meta = { source = { format = tune.format, version = tune.version, speedMultiplier = tune.speedMultiplier, trackLength = tune.trackLength, tracks = tune.trackNr + 1, mixgain = if tune.format == "hvl" then tune.mixgain else nil, stereo = if tune.format == "hvl" then tune.stereo else nil, }, }, tune = tune, } m.render = function(self: any, opts: RenderOptions?): Types.Decoder local dec, derr = Hively.decoder(self.tune, opts) if dec then return dec end local empty: any = Pcm.audioDecoder(Types.Audio.new(44100, 2, 0)) empty.err = derr return empty end return m :: Types.Module end return Hively end __FILES["codecs/audio/Hively/Load"] = function() -- codecs/audio/Hively/Load: AHX ("THX\0".."THX\2") and HivelyTracker ("HVL\0", "HVL\1") module files -> Tune. -- Ported from hvl2wav replay.c 1.9 (hvl_load_ahx / hvl_reset; BSD-3-Clause, (c) 2006-2018 Pete Gordon; -- licenses/hivelytracker-LICENSE.txt), with bounds checks the C code does not have. local Load = {} local readu8, readi8 = buffer.readu8, buffer.readi8 type PlistEntry = { note: number, waveform: number, fixed: number, fx: { number }, param: { number } } type Instrument = { name: string, volume: number, waveLength: number, filterLower: number, filterUpper: number, filterSpeed: number, squareLower: number, squareUpper: number, squareSpeed: number, vibratoDelay: number, vibratoSpeed: number, vibratoDepth: number, hardCutRelease: number, hardCutReleaseFrames: number, envelope: { aFrames: number, aVolume: number, dFrames: number, dVolume: number, sFrames: number, rFrames: number, rVolume: number }, plist: { speed: number, length: number, entries: { PlistEntry } }, } type Tune = { format: string, version: number, title: string, channels: number, positionNr: number, restart: number, speedMultiplier: number, trackLength: number, trackNr: number, instrumentNr: number, subsongs: { number }, positions: buffer, -- positionNr * 16 * 2 bytes: per channel track (u8), transpose (i8) tracks: buffer, -- 257 * 64 * 6 bytes: per track row note, instrument, fx, param, fxb, paramb instruments: { Instrument }, mixgain: number, -- (percent * 256) / 100, HVL only (AHX: set by the stereo separation at render time) stereo: number, emptyTrack0: boolean, } local function cstring(b: buffer, p: number, limit: number, max: number): (string, number) local e = p while e < limit and e - p < max and readu8(b, e) ~= 0 do e += 1 end return buffer.readstring(b, p, e - p), e end function Load.parse(b: buffer, base: number, limit: number): (Tune?, string?, string?) local size = limit - base if size < 14 then return nil, "truncated header", "truncated" end local function u8(o: number): number return readu8(b, base + o) end local magic = buffer.readstring(b, base, 3) local ahx = magic == "THX" and u8(3) < 3 if not ahx and not (magic == "HVL" and u8(3) <= 1) then return nil, "not an AHX / HVL module", nil end if not ahx and size < 16 then return nil, "truncated header", "truncated" end local posn = bit32.band(u8(6), 0x0f) * 256 + u8(7) local insn, ssn, trkl, trkn = u8(12), u8(13), u8(10), u8(11) local chnn = if ahx then 4 else bit32.rshift(u8(8), 2) + 4 local tune: Tune = { format = if ahx then "ahx" else "hvl", version = u8(3), title = "", channels = chnn, positionNr = posn, restart = if ahx then u8(8) * 256 + u8(9) else bit32.band(u8(8), 3) * 256 + u8(9), speedMultiplier = bit32.band(bit32.rshift(u8(6), 5), 3) + 1, trackLength = trkl, trackNr = trkn, instrumentNr = insn, subsongs = {}, positions = buffer.create(math.max(posn, 1) * 32), tracks = buffer.create(257 * 64 * 6), instruments = {}, mixgain = if ahx then 256 else (u8(14) * 256) // 100, stereo = if ahx then 0 else math.min(u8(15), 4), emptyTrack0 = bit32.band(u8(6), 0x80) ~= 0, } if posn == 0 or posn > 1000 or trkl > 64 or trkl == 0 or insn > 64 then return nil, string.format("bad header (positions %d, track length %d, instruments %d)", posn, trkl, insn), nil end if chnn > 16 then return nil, "unsupported: more than 16 channels", "unsupported" end if tune.restart >= posn then tune.restart = posn - 1 end local nameAt = u8(4) * 256 + u8(5) local nptr = limit if nameAt < size then local title, e = cstring(b, base + nameAt, limit, 128) tune.title = title nptr = e + 1 end local p = base + (if ahx then 14 else 16) local function need(n: number): boolean return p + n <= limit end if not need(ssn * 2 + posn * chnn * 2) then return nil, "truncated position list", "truncated" end for i = 1, ssn do local s = readu8(b, p) * 256 + readu8(b, p + 1) if s >= posn then s = 0 end tune.subsongs[i] = s p += 2 end for i = 0, posn - 1 do for j = 0, chnn - 1 do buffer.writeu8(tune.positions, (i * 16 + j) * 2, readu8(b, p)) buffer.writei8(tune.positions, (i * 16 + j) * 2 + 1, readi8(b, p + 1)) p += 2 end end local tracks = tune.tracks for i = 0, trkn do if not (tune.emptyTrack0 and i == 0) then for j = 0, trkl - 1 do local o = (i * 64 + j) * 6 if ahx then if not need(3) then return nil, "truncated track data", "truncated" end local b0, b1 = readu8(b, p), readu8(b, p + 1) buffer.writeu8(tracks, o, bit32.band(bit32.rshift(b0, 2), 0x3f)) buffer.writeu8(tracks, o + 1, bit32.band(b0, 3) * 16 + bit32.rshift(b1, 4)) buffer.writeu8(tracks, o + 2, bit32.band(b1, 0xf)) buffer.writeu8(tracks, o + 3, readu8(b, p + 2)) p += 3 else if not need(1) then return nil, "truncated track data", "truncated" end if readu8(b, p) == 0x3f then p += 1 else if not need(5) then return nil, "truncated track data", "truncated" end local fx = readu8(b, p + 2) buffer.writeu8(tracks, o, readu8(b, p)) buffer.writeu8(tracks, o + 1, readu8(b, p + 1)) buffer.writeu8(tracks, o + 2, bit32.rshift(fx, 4)) buffer.writeu8(tracks, o + 3, readu8(b, p + 3)) buffer.writeu8(tracks, o + 4, bit32.band(fx, 0xf)) buffer.writeu8(tracks, o + 5, readu8(b, p + 4)) p += 5 end end end end end local plSize = if ahx then 4 else 5 for i = 1, insn do if not need(22) then return nil, "truncated instrument", "truncated" end local function at(k: number): number return readu8(b, p + k) end local name = "" if nptr < limit then local e name, e = cstring(b, nptr, limit, 128) nptr = e + 1 end local plen = at(21) local ins: Instrument = { name = name, volume = at(0), filterSpeed = bit32.bor(bit32.band(bit32.rshift(at(1), 3), 0x1f), bit32.band(bit32.rshift(at(12), 2), 0x20)), waveLength = bit32.band(at(1), 7), envelope = { aFrames = at(2), aVolume = at(3), dFrames = at(4), dVolume = at(5), sFrames = at(6), rFrames = at(7), rVolume = at(8) }, filterLower = bit32.band(at(12), 0x7f), vibratoDelay = at(13), hardCutReleaseFrames = bit32.band(bit32.rshift(at(14), 4), 7), hardCutRelease = if bit32.band(at(14), 0x80) ~= 0 then 1 else 0, vibratoDepth = bit32.band(at(14), 0x0f), vibratoSpeed = at(15), squareLower = at(16), squareUpper = at(17), squareSpeed = at(18), filterUpper = bit32.band(at(19), 0x3f), plist = { speed = at(20), length = plen, entries = {} }, } p += 22 if not need(plen * plSize) then return nil, "truncated instrument play list", "truncated" end for j = 1, plen do local e: PlistEntry local b0, b1, b2, b3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) if ahx then local k = bit32.band(bit32.rshift(b0, 5), 7) k = if k == 6 then 12 elseif k == 7 then 15 else k local l = bit32.band(bit32.rshift(b0, 2), 7) l = if l == 6 then 12 elseif l == 7 then 15 else l e = { fx = { l, k }, waveform = bit32.band(b0 * 2, 6) + bit32.rshift(b1, 7), fixed = bit32.band(bit32.rshift(b1, 6), 1), note = bit32.band(b1, 0x3f), param = { b2, b3 }, } -- 1.6: version 0 modules (before filters) drop the "toggle filter" half of command 4 if tune.version == 0 and l == 4 and bit32.band(b2, 0xf0) ~= 0 then e.param[1] = bit32.band(b2, 0x0f) end if tune.version == 0 and k == 4 and bit32.band(b3, 0xf0) ~= 0 then e.param[2] = bit32.band(b3, 0x0f) end else e = { fx = { bit32.band(b0, 0xf), bit32.band(bit32.rshift(b1, 3), 0xf) }, waveform = bit32.band(b1, 7), fixed = bit32.band(bit32.rshift(b2, 6), 1), note = bit32.band(b2, 0x3f), param = { b3, readu8(b, p + 4) }, } end ins.plist.entries[j] = e p += plSize end tune.instruments[i] = ins end return tune, nil, nil end return Load end __FILES["codecs/audio/Hively/Player"] = @native function() -- codecs/audio/Hively/Player: the AHX / HivelyTracker replayer and integer mixer, as hvl2wav's replay.c 1.9 computes them. -- Ported from HivelyTracker (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt). Where the C -- code reads outside its arrays on bad data this port clamps instead. local Tables = __include("codecs/audio/Hively/Tables") local Load = __include("codecs/audio/Hively/Load") local Player = {} local readu8, readi8, writei8, writef32 = buffer.readu8, buffer.readi8, buffer.writei8, buffer.writef32 local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift local FILTER_SET = Tables.FILTER_SET local WO_TRIANGLE_04, WO_SAWTOOTH_04 = Tables.WO_TRIANGLE_04, Tables.WO_SAWTOOTH_04 local WO_SQUARES, WO_WHITENOISE = Tables.WO_SQUARES, Tables.WO_WHITENOISE local OFFSETS, VIB, PERIOD = Tables.OFFSETS, Tables.VIB, Tables.PERIOD local WAVEFORM_AT = { [0] = WO_TRIANGLE_04, WO_SAWTOOTH_04, 0, WO_WHITENOISE } local WRAP = 0x280 * 65536 local TWO32 = 4294967296 local f32scratch = buffer.create(4) @native local function s16(v: number): number return (v + 32768) % 65536 - 32768 end @native local function tdiv(a: number, b: number): number -- C integer division (truncates) local q = a / b return if q >= 0 then math.floor(q) else -math.floor(-q) end @native local function period(i: number): number return PERIOD[i] or 0 end -- (3546897.f * 65536.f) / period as a float, then / mix rate as a double, truncated @native local function deltaOf(p: number, freq: number): number if p == 0 then return 1 end writef32(f32scratch, 0, 232449441792 / p) -- 3546897 * 65536 = 232449441792 (exact in a float) local d = math.floor(buffer.readf32(f32scratch, 0) / freq) if d < 0 then d = 0 end if d > WRAP then d -= WRAP end if d == 0 then d = 1 end return d end type Voice = { [string]: any } type State = { tune: Load.Tune, freq: number, version: number, channels: number, voices: { Voice }, tempo: number, posNr: number, posJump: number, posJumpNote: number, noteNr: number, stepWaitFrames: number, getNewPosition: boolean, patternBreak: boolean, songEndReached: boolean, playingTime: number, mixgain: number, waves: buffer, panL: { number }, panR: { number }, } @native local function newVoice(i: number): Voice return { track = 0, nextTrack = 0, transpose = 0, nextTranspose = 0, overrideTranspose = 1000, adsrVolume = 0, aFrames = 0, aVolume = 0, dFrames = 0, dVolume = 0, sFrames = 0, rFrames = 0, rVolume = 0, instrument = false :: any, samplePos = 0, delta = 1, instrPeriod = 0, trackPeriod = 0, vibratoPeriod = 0, waveLength = 0, noteMaxVolume = 0, perfSubVolume = 0, newWaveform = false, waveform = 0, plantPeriod = false, voiceVolume = 0, plantSquare = false, ignoreSquare = 0, fixedNote = 0, volumeSlideUp = 0, volumeSlideDown = 0, hardCut = 0, hardCutRelease = 0, hardCutReleaseF = 0, periodSlideOn = false, periodSlideSpeed = 0, periodSlidePeriod = 0, periodSlideLimit = 0, periodSlideWithLimit = false, periodPerfSlideSpeed = 0, periodPerfSlidePeriod = 0, periodPerfSlideOn = false, vibratoDelay = 0, vibratoSpeed = 0, vibratoCurrent = 0, vibratoDepth = 0, squareOn = 0, squareInit = 0, squareWait = 0, squareLowerLimit = 0, squareUpperLimit = 0, squarePos = 0, squareSign = 0, squareSlidingIn = false, squareReverse = false, filterOn = 0, filterInit = 0, filterWait = 0, filterSpeed = 0, filterUpperLimit = 0, filterLowerLimit = 0, filterPos = 0, filterSign = 0, filterSlidingIn = false, ignoreFilter = 0, perfCurrent = 0, perfSpeed = 0, perfWait = 0, perfList = false :: any, audioSrc = false :: any, audioOff = 0, noteDelayOn = false, noteCutOn = false, noteDelayWait = 0, noteCutWait = 0, audioPeriod = 0, audioVolume = 0, wnHi = 0, wnLo = 0x280, squareBuf = buffer.create(0x80), voiceBuf = buffer.create(0x284), voiceNum = i, trackMasterVolume = 0x40, pan = 0, setPan = 0, panMultLeft = 0, panMultRight = 0, ringSamplePos = 0, ringDelta = 0, ringMix = false, ringPlantPeriod = false, ringBasePeriod = 0, ringAudioPeriod = 0, ringAudioOff = -1, ringNewWaveform = false, ringWaveform = 0, ringFixedPeriod = 0, ringBuf = buffer.create(0x284), } end @native function Player.new(tune: Load.Tune, freq: number, stereo: number, subsong: number): State? if subsong < 0 or subsong > #tune.subsongs then return nil end local t = Tables.get() local defstereo = if tune.format == "ahx" then math.clamp(math.floor(stereo), 0, 4) else tune.stereo local mixgain = tune.mixgain if tune.format == "ahx" then local defgain = { [0] = 71, 72, 76, 85, 100 } mixgain = (defgain[defstereo] * 256) // 100 end local st: State = { tune = tune, freq = freq, version = if tune.format == "hvl" then tune.version else 0, channels = tune.channels, voices = {}, tempo = 6, posNr = if subsong > 0 then tune.subsongs[subsong] else 0, posJump = 0, posJumpNote = 0, noteNr = 0, stepWaitFrames = 0, getNewPosition = true, patternBreak = false, songEndReached = false, playingTime = 0, mixgain = mixgain, waves = t.waves, panL = t.panL, panR = t.panR, } local left, right = Tables.STEREO_LEFT[defstereo], Tables.STEREO_RIGHT[defstereo] for i = 0, 15 do local v = newVoice(i) local p = if i % 4 == 0 or i % 4 == 3 then left else right v.pan, v.setPan, v.panMultLeft, v.panMultRight = p, p, t.panL[p], t.panR[p] st.voices[i + 1] = v end return st end @native local function setPan(st: State, v: Voice, p: number) v.pan = p v.panMultLeft, v.panMultRight = st.panL[p], st.panR[p] end @native local function stepfx1(st: State, v: Voice, fx: number, param: number) if fx == 0x0 then local lo = band(param, 0x0f) if lo > 0 and lo <= 9 then st.posJump = lo end elseif fx == 0x5 or fx == 0xa then v.volumeSlideDown = band(param, 0x0f) v.volumeSlideUp = rshift(param, 4) elseif fx == 0x7 then if param > 127 then param -= 256 end setPan(st, v, param + 128) v.setPan = param + 128 elseif fx == 0xb then st.posJump = (st.posJump * 100 + band(param, 0x0f) + rshift(param, 4) * 10) % 65536 st.patternBreak = true if st.posJump <= st.posNr then st.songEndReached = true end elseif fx == 0xd then st.posJump = st.posNr + 1 st.posJumpNote = band(param, 0x0f) + rshift(param, 4) * 10 st.patternBreak = true if st.posJumpNote > st.tune.trackLength then st.posJumpNote = 0 end elseif fx == 0xe then if rshift(param, 4) == 0xc and band(param, 0x0f) < st.tempo then v.noteCutWait = band(param, 0x0f) if v.noteCutWait ~= 0 then v.noteCutOn = true v.hardCutRelease = 0 end end elseif fx == 0xf then st.tempo = param if param == 0 then st.songEndReached = true end end end @native local function stepfx2(v: Voice, fx: number, param: number, note: number): number if fx == 0x9 then v.squarePos = rshift(param, 5 - v.waveLength) v.ignoreSquare = 1 elseif fx == 0x3 or fx == 0x5 then if fx == 0x3 and param ~= 0 then v.periodSlideSpeed = param end if note ~= 0 then local new = period(note) local diff = period(v.trackPeriod) - new new = diff + v.periodSlidePeriod if new ~= 0 then v.periodSlideLimit = s16(-diff) end end v.periodSlideOn = true v.periodSlideWithLimit = true note = 0 end return note end @native local function stepfx3(st: State, v: Voice, fx: number, param: number) if fx == 0x01 then v.periodSlideSpeed = -param v.periodSlideOn = true v.periodSlideWithLimit = false elseif fx == 0x02 then v.periodSlideSpeed = param v.periodSlideOn = true v.periodSlideWithLimit = false elseif fx == 0x04 then if param == 0 or param == 0x40 then return end if param < 0x40 then v.ignoreFilter = param return end if param > 0x7f then return end v.filterPos = param - 0x40 elseif fx == 0x0c then if param <= 0x40 then v.noteMaxVolume = param return end param -= 0x50 if param < 0 then return end if param <= 0x40 then for i = 1, st.channels do st.voices[i].trackMasterVolume = param end return end param -= 0xa0 - 0x50 if param < 0 then return end if param <= 0x40 then v.trackMasterVolume = param end elseif fx == 0xe then local sub, lo = rshift(param, 4), band(param, 0x0f) if sub == 0x1 then v.periodSlidePeriod = s16(v.periodSlidePeriod - lo) v.plantPeriod = true elseif sub == 0x2 then v.periodSlidePeriod = s16(v.periodSlidePeriod + lo) v.plantPeriod = true elseif sub == 0x4 then v.vibratoDepth = lo elseif sub == 0xa then v.noteMaxVolume = math.min(v.noteMaxVolume + lo, 0x40) elseif sub == 0xb then v.noteMaxVolume = math.max(v.noteMaxVolume - lo, 0) elseif sub == 0xf then if st.version >= 1 and lo == 1 then v.overrideTranspose = v.transpose end end end end @native local function processStep(st: State, v: Voice) v.volumeSlideUp, v.volumeSlideDown = 0, 0 local tune = st.tune local track = readu8(tune.positions, (st.posNr * 16 + v.voiceNum) * 2) local so = (track * 64 + st.noteNr) * 6 local tracks = tune.tracks local note, instr = readu8(tracks, so), readu8(tracks, so + 1) local fx, fxp, fxb, fxbp = band(readu8(tracks, so + 2), 0xf), readu8(tracks, so + 3), band(readu8(tracks, so + 4), 0xf), readu8(tracks, so + 5) local doneNoteDel = false if fx == 0xe and band(fxp, 0xf0) == 0xd0 then if v.noteDelayOn then v.noteDelayOn = false doneNoteDel = true elseif band(fxp, 0x0f) < st.tempo then v.noteDelayWait = band(fxp, 0x0f) if v.noteDelayWait ~= 0 then v.noteDelayOn = true return end end end if not doneNoteDel and fxb == 0xe and band(fxbp, 0xf0) == 0xd0 then if v.noteDelayOn then v.noteDelayOn = false elseif band(fxbp, 0x0f) < st.tempo then v.noteDelayWait = band(fxbp, 0x0f) if v.noteDelayWait ~= 0 then v.noteDelayOn = true return end end end if note ~= 0 then v.overrideTranspose = 1000 end stepfx1(st, v, fx, fxp) stepfx1(st, v, fxb, fxbp) if instr ~= 0 and instr <= tune.instrumentNr then local ins = tune.instruments[instr] setPan(st, v, v.setPan) v.periodSlideSpeed, v.periodSlidePeriod, v.periodSlideLimit = 0, 0, 0 v.perfSubVolume = 0x40 v.adsrVolume = 0 v.instrument = ins v.samplePos = 0 local env = ins.envelope v.aFrames = env.aFrames v.aVolume = s16(if v.aFrames ~= 0 then tdiv(env.aVolume * 256, v.aFrames) else env.aVolume * 256) v.dFrames = env.dFrames v.dVolume = s16(if v.dFrames ~= 0 then tdiv((env.dVolume - env.aVolume) * 256, v.dFrames) else env.dVolume * 256) v.sFrames = env.sFrames v.rFrames = env.rFrames v.rVolume = s16(if v.rFrames ~= 0 then tdiv((env.rVolume - env.dVolume) * 256, v.rFrames) else env.rVolume * 256) v.waveLength = math.min(ins.waveLength, 5) v.noteMaxVolume = ins.volume v.vibratoCurrent = 0 v.vibratoDelay = ins.vibratoDelay v.vibratoDepth = ins.vibratoDepth v.vibratoSpeed = ins.vibratoSpeed v.vibratoPeriod = 0 v.hardCutRelease = ins.hardCutRelease v.hardCut = ins.hardCutReleaseFrames v.ignoreSquare, v.squareSlidingIn = 0, false v.squareWait, v.squareOn = 0, 0 local lower = rshift(ins.squareLower, 5 - v.waveLength) local upper = rshift(ins.squareUpper, 5 - v.waveLength) if upper < lower then lower, upper = upper, lower end v.squareUpperLimit, v.squareLowerLimit = upper, lower v.ignoreFilter, v.filterWait, v.filterOn = 0, 0, 0 v.filterSlidingIn = false local d6, d3, d4 = ins.filterSpeed, ins.filterLower, ins.filterUpper v.filterSpeed = d6 if d3 > d4 then d3, d4 = d4, d3 end v.filterUpperLimit, v.filterLowerLimit = d4, d3 v.filterPos = 32 v.perfWait, v.perfCurrent = 0, 0 v.perfSpeed = ins.plist.speed v.perfList = ins.plist v.ringMix = false v.ringSamplePos = 0 v.ringPlantPeriod = false v.ringNewWaveform = false end v.periodSlideOn = false note = stepfx2(v, fx, fxp, note) note = stepfx2(v, fxb, fxbp, note) if note ~= 0 then v.trackPeriod = note v.plantPeriod = true end stepfx3(st, v, fx, fxp) stepfx3(st, v, fxb, fxbp) end @native local function plistCommand(st: State, v: Voice, fx: number, param: number) if fx == 0 then if param > 0 and param < 0x40 then if v.ignoreFilter ~= 0 then v.filterPos = v.ignoreFilter v.ignoreFilter = 0 else v.filterPos = param end v.newWaveform = true end elseif fx == 1 then v.periodPerfSlideSpeed = param v.periodPerfSlideOn = true elseif fx == 2 then v.periodPerfSlideSpeed = -param v.periodPerfSlideOn = true elseif fx == 3 then if v.ignoreSquare == 0 then v.squarePos = rshift(param, 5 - v.waveLength) else v.ignoreSquare = 0 end elseif fx == 4 then if param == 0 then v.squareOn = 1 - v.squareOn v.squareInit = v.squareOn v.squareSign = 1 else if band(param, 0x0f) ~= 0 then v.squareOn = 1 - v.squareOn v.squareInit = v.squareOn v.squareSign = if band(param, 0x0f) == 0x0f then -1 else 1 end if band(param, 0xf0) ~= 0 then v.filterOn = 1 - v.filterOn v.filterInit = v.filterOn v.filterSign = if band(param, 0xf0) == 0xf0 then -1 else 1 end end elseif fx == 5 then v.perfCurrent = param elseif fx == 7 or fx == 8 then if param >= 1 and param <= 0x3c then v.ringBasePeriod = param v.ringFixedPeriod = 1 elseif param >= 0x81 and param <= 0xbc then v.ringBasePeriod = param - 0x80 v.ringFixedPeriod = 0 else v.ringBasePeriod = 0 v.ringFixedPeriod = 0 v.ringNewWaveform = false v.ringAudioOff = -1 v.ringMix = false return end v.ringWaveform = fx - 7 v.ringNewWaveform = true v.ringPlantPeriod = true elseif fx == 9 then if param > 127 then param -= 256 end setPan(st, v, param + 128) elseif fx == 12 then if param <= 0x40 then v.noteMaxVolume = param return end param -= 0x50 if param < 0 then return end if param <= 0x40 then v.perfSubVolume = param return end param -= 0xa0 - 0x50 if param < 0 then return end if param <= 0x40 then v.trackMasterVolume = param end elseif fx == 15 then v.perfSpeed = param v.perfWait = param end end -- the noise offset generator (vc_WNRandom, a 64-bit `long` in hvl2wav): W += 2239384; -- W = ((((W >> 8) | (W << 24)) + 782323) ^ 75) - 6735 @native local function wnStep(v: Voice) local hi, lo = v.wnHi, v.wnLo + 2239384 if lo >= TWO32 then lo -= TWO32 hi = (hi + 1) % TWO32 end local shi = rshift(hi, 8) if hi >= 0x80000000 then shi = bor(shi, 0xff000000) end local nlo = bor(rshift(lo, 8), lshift(band(hi, 0xff), 24), lshift(lo, 24)) local nhi = bor(shi, lshift(hi, 24), rshift(lo, 8)) nlo += 782323 if nlo >= TWO32 then nlo -= TWO32 nhi = (nhi + 1) % TWO32 end nlo = bit32.bxor(nlo, 75) nlo -= 6735 if nlo < 0 then nlo += TWO32 nhi = (nhi + TWO32 - 1) % TWO32 end v.wnHi, v.wnLo = nhi, nlo end @native local function processFrame(st: State, v: Voice) local tune = st.tune if v.noteDelayOn then if v.noteDelayWait <= 0 then processStep(st, v) else v.noteDelayWait -= 1 end end if v.hardCut ~= 0 then local row = st.noteNr + 1 local nextinst if row < tune.trackLength then nextinst = readu8(tune.tracks, ((v.track * 64) + row) * 6 + 1) else nextinst = readu8(tune.tracks, (v.nextTrack * 64) * 6 + 1) end if nextinst ~= 0 then local d1 = math.max(st.tempo - v.hardCut, 0) if not v.noteCutOn then v.noteCutOn = true v.noteCutWait = d1 v.hardCutReleaseF = -(d1 - st.tempo) else v.hardCut = 0 end end end if v.noteCutOn then if v.noteCutWait <= 0 then v.noteCutOn = false if v.hardCutRelease ~= 0 then local ins = v.instrument local f = v.hardCutReleaseF v.rVolume = if f ~= 0 then s16(tdiv(-(v.adsrVolume - ins.envelope.rVolume * 256), f)) else 0 v.rFrames = f v.aFrames, v.dFrames, v.sFrames = 0, 0, 0 else v.noteMaxVolume = 0 end else v.noteCutWait -= 1 end end if v.aFrames ~= 0 then v.adsrVolume += v.aVolume v.aFrames -= 1 if v.aFrames <= 0 then v.adsrVolume = v.instrument.envelope.aVolume * 256 end elseif v.dFrames ~= 0 then v.adsrVolume += v.dVolume v.dFrames -= 1 if v.dFrames <= 0 then v.adsrVolume = v.instrument.envelope.dVolume * 256 end elseif v.sFrames ~= 0 then v.sFrames -= 1 elseif v.rFrames ~= 0 then v.adsrVolume += v.rVolume v.rFrames -= 1 if v.rFrames <= 0 then v.adsrVolume = v.instrument.envelope.rVolume * 256 end end v.noteMaxVolume = math.clamp(v.noteMaxVolume + v.volumeSlideUp - v.volumeSlideDown, 0, 0x40) if v.periodSlideOn then if v.periodSlideWithLimit then local d0 = v.periodSlidePeriod - v.periodSlideLimit local d2 = v.periodSlideSpeed if d0 > 0 then d2 = -d2 end if d0 ~= 0 then local sum = d0 + d2 -- (d0 + d2) ^ d0 >= 0: the same sign (or zero) if (sum >= 0) == (d0 >= 0) then d0 = v.periodSlidePeriod + d2 else d0 = v.periodSlideLimit end v.periodSlidePeriod = s16(d0) v.plantPeriod = true end else v.periodSlidePeriod = s16(v.periodSlidePeriod + v.periodSlideSpeed) v.plantPeriod = true end end if v.vibratoDepth ~= 0 then if v.vibratoDelay <= 0 then v.vibratoPeriod = (VIB[v.vibratoCurrent] * v.vibratoDepth) // 128 v.plantPeriod = true v.vibratoCurrent = band(v.vibratoCurrent + v.vibratoSpeed, 0x3f) else v.vibratoDelay -= 1 end end local pl = v.perfList if pl then if v.instrument and v.perfCurrent < v.instrument.plist.length then local overflow = v.perfWait == 128 v.perfWait = s16(v.perfWait - 1) local w8 = (v.perfWait + 128) % 256 - 128 if overflow or w8 <= 0 then local cur = v.perfCurrent v.perfCurrent += 1 v.perfWait = v.perfSpeed local e = pl.entries[cur + 1] if e then if e.waveform ~= 0 then v.waveform = e.waveform - 1 v.newWaveform = true v.periodPerfSlideSpeed, v.periodPerfSlidePeriod = 0, 0 end v.periodPerfSlideOn = false plistCommand(st, v, e.fx[1], e.param[1]) plistCommand(st, v, e.fx[2], e.param[2]) if e.note ~= 0 then v.instrPeriod = e.note v.plantPeriod = true v.fixedNote = e.fixed end end end else if v.perfWait ~= 0 then v.perfWait -= 1 else v.periodPerfSlideSpeed = 0 end end end if v.periodPerfSlideOn then v.periodPerfSlidePeriod = s16(v.periodPerfSlidePeriod - v.periodPerfSlideSpeed) if v.periodPerfSlidePeriod ~= 0 then v.plantPeriod = true end end if v.waveform == 2 and v.squareOn ~= 0 then v.squareWait -= 1 if v.squareWait <= 0 then local d1, d2, d3 = v.squareLowerLimit, v.squareUpperLimit, v.squarePos if v.squareInit ~= 0 then v.squareInit = 0 if d3 <= d1 then v.squareSlidingIn = true v.squareSign = 1 elseif d3 >= d2 then v.squareSlidingIn = true v.squareSign = -1 end end if d1 == d3 or d2 == d3 then if v.squareSlidingIn then v.squareSlidingIn = false else v.squareSign = -v.squareSign end end d3 += v.squareSign v.squarePos = s16(d3) v.plantSquare = true local ins: any = v.instrument v.squareWait = if ins then ins.squareSpeed else 0 end end if v.filterOn ~= 0 then v.filterWait -= 1 if v.filterWait <= 0 then local d1, d2, d3 = v.filterLowerLimit, v.filterUpperLimit, v.filterPos if v.filterInit ~= 0 then v.filterInit = 0 if d3 <= d1 then v.filterSlidingIn = true v.filterSign = 1 elseif d3 >= d2 then v.filterSlidingIn = true v.filterSign = -1 end end local fmax = if v.filterSpeed < 4 then 5 - v.filterSpeed else 1 for _ = 1, fmax do if d1 == d3 or d2 == d3 then if v.filterSlidingIn then v.filterSlidingIn = false else v.filterSign = -v.filterSign end end d3 += v.filterSign end v.filterPos = math.clamp(d3, 1, 63) v.newWaveform = true v.filterWait = math.max(v.filterSpeed - 3, 1) end end local waves = st.waves local fpos = math.clamp(v.filterPos, 1, 63) if v.waveform == 2 or v.plantSquare then -- CalcSquare local sp = WO_SQUARES + (fpos - 0x20) * FILTER_SET local x = v.squarePos * 2 ^ (5 - v.waveLength) if x > 0x20 then x = 0x40 - x v.squareReverse = true end if x > 0 then sp += (x - 1) * 128 end local delta = 32 // 2 ^ v.waveLength local sb = v.squareBuf for i = 0, 4 * 2 ^ v.waveLength - 1 do writei8(sb, i, readi8(waves, sp)) sp += delta end v.newWaveform = true v.waveform = 2 v.plantSquare = false end if v.waveform == 3 then v.newWaveform = true end if v.ringNewWaveform then if v.ringWaveform > 1 then v.ringWaveform = 1 end v.ringAudioOff = WAVEFORM_AT[v.ringWaveform] + OFFSETS[v.waveLength] end if v.newWaveform and v.waveform <= 3 then if v.waveform == 2 then v.audioSrc, v.audioOff = v.squareBuf, 0 else local off = WAVEFORM_AT[v.waveform] + (fpos - 0x20) * FILTER_SET if v.waveform < 2 then off += OFFSETS[v.waveLength] else off += band(band(v.wnLo, 2 * 0x280 - 1), 0xfffffffe) wnStep(v) end v.audioSrc, v.audioOff = waves, off end end if v.ringAudioOff >= 0 then local rp = v.ringBasePeriod if v.ringFixedPeriod == 0 then if v.overrideTranspose ~= 1000 then rp += v.overrideTranspose + v.trackPeriod - 1 else rp += v.transpose + v.trackPeriod - 1 end end rp = period(math.clamp(s16(rp), 0, 60)) if v.ringFixedPeriod == 0 then rp += v.periodSlidePeriod end rp = s16(rp + v.periodPerfSlidePeriod + v.vibratoPeriod) v.ringAudioPeriod = math.clamp(rp, 0x71, 0xd60) end local ap = v.instrPeriod if v.fixedNote == 0 then if v.overrideTranspose ~= 1000 then ap += v.overrideTranspose + v.trackPeriod - 1 else ap += v.transpose + v.trackPeriod - 1 end end ap = period(math.clamp(s16(ap), 0, 60)) if v.fixedNote == 0 then ap += v.periodSlidePeriod end ap = s16(ap + v.periodPerfSlidePeriod + v.vibratoPeriod) v.audioPeriod = math.clamp(ap, 0x71, 0xd60) local vol = (v.adsrVolume // 256 * v.noteMaxVolume) // 64 vol = (vol * v.perfSubVolume) // 64 vol = (vol * v.trackMasterVolume) // 64 v.audioVolume = s16(vol) end @native local function fillCycles(dst: buffer, src: buffer, off: number, len: number) if off < 0 or off + len > buffer.len(src) then buffer.fill(dst, 0, 0, 0x281) return end buffer.copy(dst, 0, src, off, len) local filled = len while filled < 0x280 do local k = math.min(filled, 0x280 - filled) buffer.copy(dst, filled, dst, 0, k) filled += k end writei8(dst, 0x280, readi8(dst, 0)) end @native local function setAudio(st: State, v: Voice) v.voiceVolume = v.audioVolume % 256 if v.plantPeriod then v.plantPeriod = false v.delta = deltaOf(v.audioPeriod, st.freq) end local src: buffer? = v.audioSrc or nil if v.newWaveform and src then fillCycles(v.voiceBuf, src, v.audioOff, if v.waveform == 3 then 0x280 else 4 * 2 ^ v.waveLength) end if v.ringPlantPeriod then v.ringPlantPeriod = false v.ringDelta = deltaOf(v.ringAudioPeriod, st.freq) end if v.ringNewWaveform and v.ringAudioOff >= 0 then fillCycles(v.ringBuf, st.waves, v.ringAudioOff, 4 * 2 ^ v.waveLength) v.ringMix = true end end -- hvl_play_irq (audio = false skips the audio side) @native function Player.irq(st: State, audio: boolean) local tune = st.tune local nch = st.channels local voices = st.voices if st.stepWaitFrames == 0 then if st.getNewPosition then local nextpos = if st.posNr + 1 == tune.positionNr then 0 else st.posNr + 1 local P = tune.positions for i = 0, nch - 1 do local v = voices[i + 1] v.track = readu8(P, (st.posNr * 16 + i) * 2) v.transpose = readi8(P, (st.posNr * 16 + i) * 2 + 1) v.nextTrack = readu8(P, (nextpos * 16 + i) * 2) v.nextTranspose = readi8(P, (nextpos * 16 + i) * 2 + 1) end st.getNewPosition = false end for i = 1, nch do processStep(st, voices[i]) end st.stepWaitFrames = st.tempo end for i = 1, nch do processFrame(st, voices[i]) end st.playingTime += 1 st.stepWaitFrames = s16(st.stepWaitFrames - 1) if st.stepWaitFrames == 0 then if not st.patternBreak then st.noteNr += 1 if st.noteNr >= tune.trackLength then st.posJump = st.posNr + 1 st.posJumpNote = 0 st.patternBreak = true end end if st.patternBreak then st.patternBreak = false st.posNr = st.posJump st.noteNr = st.posJumpNote if st.posNr >= tune.positionNr then -- (past the end is bad data: the C code reads outside its position list) st.songEndReached = true st.posNr = tune.restart end st.posJumpNote = 0 st.posJump = 0 st.getNewPosition = true end end if audio then for i = 1, nch do setAudio(st, voices[i]) end end end -- hvl_mixchunk: integer mixing, s16 clipping, / 32768 @native function Player.mix(st: State, out: buffer, at: number, n: number) local nch = st.channels local voices = st.voices local src, rsrc, delta, rdelta, vol, pos, rpos, panl, panr = {}, {}, {}, {}, {}, {}, {}, {}, {} for i = 1, nch do local v = voices[i] delta[i] = math.max(v.delta, 1) vol[i] = v.voiceVolume pos[i] = v.samplePos src[i] = v.voiceBuf panl[i] = v.panMultLeft panr[i] = v.panMultRight rdelta[i] = math.max(v.ringDelta, 1) rpos[i] = v.ringSamplePos rsrc[i] = if v.ringMix then v.ringBuf else false end local gain = st.mixgain local o = at * 8 local samples = n while samples > 0 do local loops = samples for i = 1, nch do if pos[i] >= WRAP then pos[i] -= WRAP end local cnt = (WRAP - pos[i] - 1) // delta[i] + 1 if cnt < loops then loops = cnt end if rsrc[i] then if rpos[i] >= WRAP then rpos[i] -= WRAP end cnt = (WRAP - rpos[i] - 1) // rdelta[i] + 1 if cnt < loops then loops = cnt end end end samples -= loops for _ = 1, loops do local a, b = 0, 0 for i = 1, nch do local j local r = rsrc[i] if r then j = ((readi8(src[i], pos[i] // 65536) * readi8(r, rpos[i] // 65536)) // 128) * vol[i] rpos[i] += rdelta[i] else j = readi8(src[i], pos[i] // 65536) * vol[i] end a += (j * panl[i]) // 128 b += (j * panr[i]) // 128 pos[i] += delta[i] end a = (a * gain) // 256 b = (b * gain) // 256 if a < -32768 then a = -32768 elseif a > 32767 then a = 32767 end if b < -32768 then b = -32768 elseif b > 32767 then b = 32767 end writef32(out, o, a / 32768) writef32(out, o + 4, b / 32768) o += 8 end end for i = 1, nch do voices[i].samplePos = pos[i] voices[i].ringSamplePos = rpos[i] end end return Player end __FILES["codecs/audio/Hively/Tables"] = @native function() -- codecs/audio/Hively/Tables: the AHX / HivelyTracker replayer's waveform, panning, vibrato and period tables. -- Ported from hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt) as -- built on 64-bit Linux (`long` is 64-bit: the noise generator's shifts do not wrap at 32 bits). local Tables = {} local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local FILTER_SET = 0xfc + 0xfc + 0x80 * 0x1f + 0x80 + 3 * 0x280 -- 6520: one filtered copy of every waveform local WHITENOISELEN = 0x280 * 3 local WO_LOWPASSES = 0 local WO_TRIANGLE_04 = WO_LOWPASSES + FILTER_SET * 31 local WO_SAWTOOTH_04 = WO_TRIANGLE_04 + 0xfc local WO_SQUARES = WO_SAWTOOTH_04 + 0xfc local WO_WHITENOISE = WO_SQUARES + 0x80 * 0x20 local WO_HIGHPASSES = WO_WHITENOISE + WHITENOISELEN local WAVES_SIZE = WO_HIGHPASSES + FILTER_SET * 31 Tables.FILTER_SET = FILTER_SET Tables.WO_TRIANGLE_04 = WO_TRIANGLE_04 Tables.WO_SAWTOOTH_04 = WO_SAWTOOTH_04 Tables.WO_SQUARES = WO_SQUARES Tables.WO_WHITENOISE = WO_WHITENOISE Tables.WAVES_SIZE = WAVES_SIZE -- offset of the waveform of length 4 << n inside the triangle / sawtooth runs Tables.OFFSETS = { [0] = 0x00, 0x04, 0x04 + 0x08, 0x04 + 0x08 + 0x10, 0x04 + 0x08 + 0x10 + 0x20, 0x04 + 0x08 + 0x10 + 0x20 + 0x40 } Tables.VIB = { [0] = 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24, 0, -24, -49, -74, -97, -120, -141, -161, -180, -197, -212, -224, -235, -244, -250, -253, -255, -253, -250, -244, -235, -224, -212, -197, -180, -161, -141, -120, -97, -74, -49, -24, } Tables.PERIOD = { [0] = 0x0000, 0x0D60, 0x0CA0, 0x0BE8, 0x0B40, 0x0A98, 0x0A00, 0x0970, 0x08E8, 0x0868, 0x07F0, 0x0780, 0x0714, 0x06B0, 0x0650, 0x05F4, 0x05A0, 0x054C, 0x0500, 0x04B8, 0x0474, 0x0434, 0x03F8, 0x03C0, 0x038A, 0x0358, 0x0328, 0x02FA, 0x02D0, 0x02A6, 0x0280, 0x025C, 0x023A, 0x021A, 0x01FC, 0x01E0, 0x01C5, 0x01AC, 0x0194, 0x017D, 0x0168, 0x0153, 0x0140, 0x012E, 0x011D, 0x010D, 0x00FE, 0x00F0, 0x00E2, 0x00D6, 0x00CA, 0x00BE, 0x00B4, 0x00AA, 0x00A0, 0x0097, 0x008F, 0x0087, 0x007F, 0x0078, 0x0071, } Tables.STEREO_LEFT = { [0] = 128, 96, 64, 32, 0 } Tables.STEREO_RIGHT = { [0] = 128, 160, 193, 225, 255 } @native local function i8(v: number): number v = v % 256 return if v >= 128 then v - 256 else v end @native local function genSawtooth(w: buffer, at: number, len: number) local add = 256 // (len - 1) local val = -128 for i = 0, len - 1 do buffer.writei8(w, at + i, i8(val)) val += add end end @native local function genTriangle(w: buffer, at: number, len: number) local d5 = len // 4 local d1 = 128 // d5 local d4 = -(len // 2) local p = at local val = 0 for _ = 1, d5 do buffer.writei8(w, p, i8(val)) p += 1 val += d1 end buffer.writei8(w, p, 0x7f) p += 1 if d5 ~= 1 then val = 128 for _ = 1, d5 - 1 do val -= d1 buffer.writei8(w, p, i8(val)) p += 1 end end local q = p + d4 for _ = 1, d5 * 2 do local c = buffer.readi8(w, q) q += 1 buffer.writei8(w, p, if c == 0x7f then -128 else i8(-c)) p += 1 end end @native local function genSquare(w: buffer, at: number) local p = at for i = 1, 0x20 do for _ = 1, (0x40 - i) * 2 do buffer.writei8(w, p, -128) p += 1 end for _ = 1, i * 2 do buffer.writei8(w, p, 0x7f) p += 1 end end end -- hvl_GenWhiteNoise with `unsigned long` = 64 bits: (hi, lo) halves @native local function genWhiteNoise(w: buffer, at: number, len: number) local hi, lo = 0, 0x41595321 for i = 0, len - 1 do local s = i8(band(lo, 0xff)) if band(lo, 0x100) ~= 0 then s = 0x7f -- (int32)(ays & 0xffff) >= 0 always holds end buffer.writei8(w, at + i, s) -- ays = (ays >> 5) | (ays << 27) local nlo = bor(rshift(lo, 5), lshift(band(hi, 31), 27), lshift(lo, 27)) -- (the high half is masked off next: ays & 0xffffff00 zero-extends) lo = bor(band(nlo, 0xffffff00), bxor(band(nlo, 0xff), 0x9a)) local bx = band(lo, 0xffff) -- ays = (ays << 2) | (ays >> 30) lo = bor(lshift(lo, 2), rshift(lo, 30)) local ax = band(lo, 0xffff) bx = band(bx + ax, 0xffff) ax = bxor(ax, bx) lo = bor(band(lo, 0xffff0000), ax) -- ays = (ays >> 3) | (ays << 29) hi = rshift(lo, 3) lo = bor(rshift(lo, 3), lshift(lo, 29)) end end local LENTAB = { 3, 7, 0xf, 0x1f, 0x3f, 0x7f, 3, 7, 0xf, 0x1f, 0x3f, 0x7f } for _ = 1, 32 do table.insert(LENTAB, 0x7f) end table.insert(LENTAB, 0x280 * 3 - 1) @native local function clip(x: number): number if x > 127 then return 127 elseif x < -128 then return -128 end return x end @native local function trunc8(x: number): number return if x >= 0 then math.floor(x) else -math.floor(-x) end @native local function genFilterWaves(w: buffer) local low, high = WO_LOWPASSES, WO_HIGHPASSES local freq = 8 for _ = 0, 30 do local a0 = WO_TRIANGLE_04 local fre = freq * 1.25 / 100.0 for wv = 1, 45 do local n = LENTAB[wv] local mid, lo = 0, 0 for i = 0, n do local h = clip(buffer.readi8(w, a0 + i) - mid - lo) mid = clip(mid + h * fre) lo = clip(lo + mid * fre) end for i = 0, n do local h = clip(buffer.readi8(w, a0 + i) - mid - lo) mid = clip(mid + h * fre) lo = clip(lo + mid * fre) buffer.writei8(w, low, trunc8(lo)) buffer.writei8(w, high, trunc8(h)) low += 1 high += 1 end a0 += n + 1 end freq += 3 end end local cache: { waves: buffer, panL: { number }, panR: { number } }? = nil @native function Tables.get(): { waves: buffer, panL: { number }, panR: { number } } if cache then return cache end local w = buffer.create(WAVES_SIZE) local n = 4 for k = 0, 5 do genSawtooth(w, WO_SAWTOOTH_04 + Tables.OFFSETS[k], n) genTriangle(w, WO_TRIANGLE_04 + Tables.OFFSETS[k], n) n *= 2 end genSquare(w, WO_SQUARES) genWhiteNoise(w, WO_WHITENOISE, WHITENOISELEN) genFilterWaves(w) -- sine panning: the start angle is a float expression in the C source ((3.14159265f * 2.0f) / 4.0f) local f = buffer.create(4) buffer.writef32(f, 0, 3.14159265) local aa = buffer.readf32(f, 0) * 2 / 4 local ab = 0.0 local step = (3.14159265 * 2.0 / 4.0) / 256.0 local pl: { number }, pr: { number } = {}, {} for i = 0, 255 do pl[i] = math.floor(math.sin(aa) * 255.0) pr[i] = math.floor(math.sin(ab) * 255.0) aa += step ab += step end pl[255] = 0 pr[0] = 0 cache = { waves = w, panL = pl, panR = pr } return cache :: any end return Tables end __FILES["codecs/audio/Mdct"] = @native function() -- codecs/audio/Mdct: MDCT / IMDCT for any N divisible by 4, DCT-IV, and the sine / KBD / Vorbis windows. -- Through an N / 4-point complex FFT; written from the textbook definitions, no third-party code. -- -- X[k] = sum_{j=0}^{N-1} x[j] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) forward, k = 0 .. N/2 - 1 -- y[j] = sum_{k=0}^{N/2-1} X[k] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) inverse, j = 0 .. N - 1 -- -- Unnormalised: forward + inverse + overlap-add with a Princen-Bradley window gives the input times N / 4 (the AAC spec -- IMDCT is inverse(..., 2 / N)). local Fft = __include("codecs/audio/Mdct/Fft") local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt local Mdct = {} Mdct.Fft = Fft type Plan = { n: number, m: number, fft: Fft.Plan, twc: { number }, -- cos / sin (pi (p + 1/8) / M), p = 0 .. N/4 - 1 tws: { number }, re: { number }, im: { number }, c: { number }, } @native function Mdct.new(n: number): Plan? if type(n) ~= "number" or n < 4 or n % 4 ~= 0 or n > 2 ^ 24 then return nil end local m = n // 2 local q = n // 4 local fft = Fft.new(q) if not fft then return nil end local twc, tws = table.create(q, 0), table.create(q, 0) for p = 0, q - 1 do local a = pi * (p + 0.125) / m twc[p + 1], tws[p + 1] = cos(a), sin(a) end return { n = n, m = m, fft = fft, twc = twc, tws = tws, re = table.create(q, 0), im = table.create(q, 0), c = table.create(m, 0), } end @native local function dct4Post(plan: Plan, out: { number }, oi: number, os: number, scale: number) local q, m = plan.n // 4, plan.m local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws Fft.forward(plan.fft, re, im) for k = 0, q - 1 do local c, s = twc[k + 1], tws[k + 1] local tr, ti = re[k + 1], im[k + 1] out[oi + 2 * k * os] = (tr * c + ti * s) * scale out[oi + (m - 1 - 2 * k) * os] = -(ti * c - tr * s) * scale end end -- C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)), M = N / 2 (its own inverse up to 2 / M) @native function Mdct.dct4(plan: Plan, u: { number }, ui: number, us: number, out: { number }, oi: number, os: number, scale: number?) local q, m = plan.n // 4, plan.m local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws for p = 0, q - 1 do local a, b = u[ui + 2 * p * us], u[ui + (m - 1 - 2 * p) * us] local c, s = twc[p + 1], tws[p + 1] re[p + 1] = a * c + b * s im[p + 1] = b * c - a * s end dct4Post(plan, out, oi, os, scale or 1) end @native function Mdct.forward(plan: Plan, x: { number }, xi: number, out: { number }, oi: number, os: number?, scale: number?) local q, m = plan.n // 4, plan.m local h = m // 2 local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws -- fold: u[j] = -x[3M/2 - 1 - j] - x[3M/2 + j] (j < M/2), x[j - M/2] - x[3M/2 - 1 - j] (j >= M/2) local b3 = xi + 3 * h for p = 0, q - 1 do local j = 2 * p local a if j < h then a = -x[b3 - 1 - j] - x[b3 + j] else a = x[xi + j - h] - x[b3 - 1 - j] end j = m - 1 - 2 * p local b if j < h then b = -x[b3 - 1 - j] - x[b3 + j] else b = x[xi + j - h] - x[b3 - 1 - j] end local c, s = twc[p + 1], tws[p + 1] re[p + 1] = a * c + b * s im[p + 1] = b * c - a * s end dct4Post(plan, out, oi, os or 1, scale or 1) end @native function Mdct.inverse(plan: Plan, inp: { number }, ii: number, is: number?, y: { number }, yi: number, scale: number?) local m = plan.m local h = m // 2 local c = plan.c Mdct.dct4(plan, inp, ii, is or 1, c, 1, 1, scale) -- unfold: y = (C2, -C2 reversed, -C1 reversed, -C1) for j = 0, h - 1 do y[yi + j] = c[h + j + 1] y[yi + h + j] = -c[m - j] y[yi + m + j] = -c[h - j] y[yi + 3 * h + j] = -c[j + 1] end end @native local function besselI0(x: number): number local sum, term = 1, 1 local k = 1 while k < 200 do term *= (x / (2 * k)) ^ 2 sum += term if term < sum * 1e-17 then break end k += 1 end return sum end Mdct.besselI0 = besselI0 -- "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (AAC: alpha 4 long, 6 short); "vorbis" -- sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1. @native function Mdct.window(kind: string, n: number, alpha: number?): { number }? if type(n) ~= "number" or n < 2 or n % 2 ~= 0 then return nil end local w = table.create(n, 0) if kind == "sine" then for i = 0, n - 1 do w[i + 1] = sin(pi * (i + 0.5) / n) end elseif kind == "vorbis" then for i = 0, n - 1 do local s = sin(pi * (i + 0.5) / n) w[i + 1] = sin(pi / 2 * s * s) end elseif kind == "kbd" then local half = n // 2 local a = alpha or 4 local kais = table.create(half + 1, 0) local total = 0 for i = 0, half do local r = 2 * i / half - 1 kais[i + 1] = besselI0(pi * a * sqrt(math.max(0, 1 - r * r))) total += kais[i + 1] end local acc = 0 for i = 0, half - 1 do acc += kais[i + 1] local v = sqrt(acc / total) w[i + 1] = v w[n - i] = v end else return nil end return w end @native function Mdct.fft(n: number): Fft.Plan? return Fft.new(n) end return Mdct end __FILES["codecs/audio/Mdct/Fft"] = @native function() -- codecs/audio/Mdct/Fft: mixed-radix complex FFT (radix 4, 2, 3, 5, generic odd), self-sorting Stockham passes (the -- FFTPACK / pocketfft pass structure, written from the textbook derivation; no third-party code). local Fft = {} type Plan = { n: number, factors: { number }, -- per pass: twiddles exp(-2 pi i u i l1 / n) for u = 1 .. p - 1, i = 0 .. ido - 1 at [(u - 1) * ido + i + 1] twr: { { number } }, twi: { { number } }, -- per pass, generic odd radix: exp(-2 pi i k / p) for k = 0 .. p - 1 rr: { { number } }, ri: { { number } }, sre: { number }, sim: { number }, } local cos, sin, pi = math.cos, math.sin, math.pi @native function Fft.new(n: number): Plan? if type(n) ~= "number" or n < 1 or n % 1 ~= 0 or n > 2 ^ 24 then return nil end local factors = {} local m = n while m % 4 == 0 do table.insert(factors, 4) m //= 4 end while m % 2 == 0 do table.insert(factors, 2) m //= 2 end local f = 3 while m > 1 do while m % f == 0 do table.insert(factors, f) m //= f end f += 2 if f * f > m and m > 1 then table.insert(factors, m) m = 1 end end local twr, twi, rr, ri = {}, {}, {}, {} local l1 = 1 for k, p in factors do local ido = n // (l1 * p) local tr, ti = table.create((p - 1) * ido, 0), table.create((p - 1) * ido, 0) for u = 1, p - 1 do for i = 0, ido - 1 do local a = -2 * pi * u * i * l1 / n tr[(u - 1) * ido + i + 1] = cos(a) ti[(u - 1) * ido + i + 1] = sin(a) end end twr[k], twi[k] = tr, ti local cr, ci = table.create(p, 0), table.create(p, 0) for j = 0, p - 1 do cr[j + 1] = cos(-2 * pi * j / p) ci[j + 1] = sin(-2 * pi * j / p) end rr[k], ri[k] = cr, ci l1 *= p end return { n = n, factors = factors, twr = twr, twi = twi, rr = rr, ri = ri, sre = table.create(n, 0), sim = table.create(n, 0), } end -- one pass of radix p: cc (i, v, k) = src[1 + i + ido * (v + p * k)] -> ch (i, k, u) = dst[1 + i + ido * (k + l1 * u)] @native local function pass(p: number, ido: number, l1: number, ar: { number }, ai: { number }, br: { number }, bi: { number }, tr: { number }, ti: { number }, cr: { number }, ci: { number }) local lp = ido * l1 if p == 4 then for k = 0, l1 - 1 do for i = 0, ido - 1 do local s = 1 + i + ido * 4 * k local a0r, a0i = ar[s], ai[s] local a1r, a1i = ar[s + ido], ai[s + ido] local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido] local a3r, a3i = ar[s + 3 * ido], ai[s + 3 * ido] local t0r, t0i = a0r + a2r, a0i + a2i local t1r, t1i = a0r - a2r, a0i - a2i local t2r, t2i = a1r + a3r, a1i + a3i local t3r, t3i = a1r - a3r, a1i - a3i local d = 1 + i + ido * k br[d], bi[d] = t0r + t2r, t0i + t2i local y1r, y1i = t1r + t3i, t1i - t3r local y2r, y2i = t0r - t2r, t0i - t2i local y3r, y3i = t1r - t3i, t1i + t3r if i == 0 then br[d + lp], bi[d + lp] = y1r, y1i br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i br[d + 3 * lp], bi[d + 3 * lp] = y3r, y3i else local w1r, w1i = tr[i + 1], ti[i + 1] local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1] local w3r, w3i = tr[2 * ido + i + 1], ti[2 * ido + i + 1] br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r br[d + 3 * lp], bi[d + 3 * lp] = y3r * w3r - y3i * w3i, y3r * w3i + y3i * w3r end end end elseif p == 2 then for k = 0, l1 - 1 do for i = 0, ido - 1 do local s = 1 + i + ido * 2 * k local a0r, a0i = ar[s], ai[s] local a1r, a1i = ar[s + ido], ai[s + ido] local d = 1 + i + ido * k br[d], bi[d] = a0r + a1r, a0i + a1i local yr, yi = a0r - a1r, a0i - a1i if i == 0 then br[d + lp], bi[d + lp] = yr, yi else local wr, wi = tr[i + 1], ti[i + 1] br[d + lp], bi[d + lp] = yr * wr - yi * wi, yr * wi + yi * wr end end end elseif p == 3 then local c = 0.86602540378443864676 -- sin(pi / 3) for k = 0, l1 - 1 do for i = 0, ido - 1 do local s = 1 + i + ido * 3 * k local a0r, a0i = ar[s], ai[s] local a1r, a1i = ar[s + ido], ai[s + ido] local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido] local tr_, ti_ = a1r + a2r, a1i + a2i local sr, si = a1r - a2r, a1i - a2i local d = 1 + i + ido * k br[d], bi[d] = a0r + tr_, a0i + ti_ local mr, mi = a0r - 0.5 * tr_, a0i - 0.5 * ti_ local y1r, y1i = mr + c * si, mi - c * sr local y2r, y2i = mr - c * si, mi + c * sr if i == 0 then br[d + lp], bi[d + lp] = y1r, y1i br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i else local w1r, w1i = tr[i + 1], ti[i + 1] local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1] br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r end end end else -- generic radix: y_u = sum_v a_v exp(-2 pi i u v / p), then the twiddle for k = 0, l1 - 1 do for i = 0, ido - 1 do local s = 1 + i + ido * p * k local d = 1 + i + ido * k for u = 0, p - 1 do local yr, yi = 0, 0 local j = 0 for v = 0, p - 1 do local xr, xi = ar[s + v * ido], ai[s + v * ido] local wr, wi = cr[j + 1], ci[j + 1] yr += xr * wr - xi * wi yi += xr * wi + xi * wr j += u if j >= p then j -= p end end if u > 0 and i > 0 then local wr, wi = tr[(u - 1) * ido + i + 1], ti[(u - 1) * ido + i + 1] yr, yi = yr * wr - yi * wi, yr * wi + yi * wr end br[d + u * lp], bi[d + u * lp] = yr, yi end end end end end -- X[k] = sum x[j] exp(-2 pi i j k / n), in place; the inverse (without 1 / n) is forward(plan, im, re) @native function Fft.forward(plan: Plan, re: { number }, im: { number }) local n = plan.n local ar, ai, br, bi = re, im, plan.sre, plan.sim local l1 = 1 for k, p in plan.factors do local ido = n // (l1 * p) pass(p, ido, l1, ar, ai, br, bi, plan.twr[k], plan.twi[k], plan.rr[k], plan.ri[k]) ar, ai, br, bi = br, bi, ar, ai l1 *= p end if ar ~= re then for j = 1, n do re[j], im[j] = ar[j], ai[j] end end end return Fft end __FILES["codecs/audio/MidiRender"] = function() -- codecs/audio/MidiRender: the MIDI tempo map, event timeline and the Decoder that plays a Midi through SoundFont. -- Lengths as python mido computes them. Format 0 / 1: one tempo map from every track, tracks merged (ties keep track -- order); format 2: each track is its own song, played one after another. local Err = __include("core/Err") local Types = __include("Types") local SoundFont = __include("codecs/audio/SoundFont") local Synth = SoundFont.Synth local Render = {} type TempoMap = { ticks: { number }, secs: { number }, us: { number }, division: number } local STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } local function tempoOf(ev: any): number? if ev.type == "meta" and ev.meta == 0x51 and type(ev.data) == "table" and #ev.data >= 3 then return ev.data[1] * 65536 + ev.data[2] * 256 + ev.data[3] end return nil end function Render.tempoMap(midi: Types.Midi, track: number?): TempoMap local changes: { { number } } = {} for ti, t in midi.tracks do if track == nil or track == ti then for i, ev in t.events do local us = tempoOf(ev) if us then table.insert(changes, { ev.tick, ti, i, us }) end end end end table.sort(changes, function(a: { number }, b: { number }): boolean if a[1] ~= b[1] then return a[1] < b[1] end if a[2] ~= b[2] then return a[2] < b[2] end return a[3] < b[3] end) local map: TempoMap = { ticks = { 0 }, secs = { 0 }, us = { 500000 }, division = midi.division } local div = midi.division for _, c in changes do local n = #map.ticks local tick = c[1] local sec = map.secs[n] + (tick - map.ticks[n]) * map.us[n] * 1e-6 / div if tick == map.ticks[n] then map.us[n] = c[4] else table.insert(map.ticks, tick) table.insert(map.secs, sec) table.insert(map.us, c[4]) end end return map end function Render.seconds(map: TempoMap, tick: number): number local div = map.division if div < 0 then local fps = -(div // 256) local tpf = div % 256 if tpf == 0 then return 0 end return tick / ((if fps == 29 then 29.97 else fps) * tpf) end local ticks = map.ticks local lo, hi = 1, #ticks while lo < hi do local mid = (lo + hi + 1) // 2 if ticks[mid] <= tick then lo = mid else hi = mid - 1 end end return map.secs[lo] + (tick - ticks[lo]) * map.us[lo] * 1e-6 / div end function Render.length(midi: Types.Midi): number if #midi.tracks == 0 then return 0 end if midi.format == 2 then local total = 0 for ti, t in midi.tracks do local map = Render.tempoMap(midi, ti) local last = 0 for _, ev in t.events do last = math.max(last, ev.tick) end total += Render.seconds(map, last) end return total end local map = Render.tempoMap(midi) local last = 0 for _, t in midi.tracks do for _, ev in t.events do last = math.max(last, ev.tick) end end return Render.seconds(map, last) end type Timeline = { time: { number }, status: { number }, d1: { number }, d2: { number }, length: number } function Render.timeline(midi: Types.Midi): Timeline local items: { { any } } = {} local offset = 0 local function add(map: TempoMap, ti: number, t: any, base: number) for i, ev in t.events do local st = STATUS[ev.type] if st and type(ev.data) == "table" then local ch = ev.channel or 0 table.insert(items, { base + Render.seconds(map, ev.tick), ti, i, st + ch % 16, ev.data[1] or 0, ev.data[2] or 0 }) end end end if midi.format == 2 then for ti, t in midi.tracks do local map = Render.tempoMap(midi, ti) add(map, ti, t, offset) local last = 0 for _, ev in t.events do last = math.max(last, ev.tick) end offset += Render.seconds(map, last) end else local map = Render.tempoMap(midi) for ti, t in midi.tracks do add(map, ti, t, 0) end end table.sort(items, function(a: { any }, b: { any }): boolean if a[1] ~= b[1] then return a[1] < b[1] end if a[2] ~= b[2] then return a[2] < b[2] end return a[3] < b[3] end) local tl: Timeline = { time = table.create(#items) :: { number }, status = table.create(#items) :: { number }, d1 = table.create(#items) :: { number }, d2 = table.create(#items) :: { number }, length = Render.length(midi) } for i, it in items do tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] = it[1], it[4], it[5] % 128, it[6] % 128 end return tl end type RenderOptions = { sampleRate: number?, soundfont: any?, gain: number?, tail: number?, maxVoices: number?, } function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?) if type(midi) ~= "table" or type(midi.tracks) ~= "table" or type(midi.division) ~= "number" or midi.division == 0 then return nil, Err.new(Err.ARG, "render: needs a Midi value") end local o: RenderOptions = opts or {} local rate = o.sampleRate or 44100 if type(rate) ~= "number" or rate < 1000 or rate > 384000 then return nil, Err.new(Err.ARG, "render: sampleRate must be 1000..384000") end local sf = o.soundfont if sf == nil then sf = SoundFont.fallback() elseif not SoundFont.isSoundFont(sf) then local parsed, err = SoundFont.parse(sf) if not parsed then return nil, err end sf = parsed end local tl = Render.timeline(midi) local tail = o.tail or 1 local frames = math.max(0, math.ceil((tl.length + tail) * rate)) local nev = #tl.time local evFrame: { number } = table.create(nev) :: { number } for i = 1, nev do evFrame[i] = math.floor(tl.time[i] * rate + 0.5) end local gain, maxVoices = o.gain, o.maxVoices local state = Synth.new(sf, rate, gain, maxVoices) local pos, nextEv = 0, 1 local dec = { sampleRate = rate, channels = 2, frames = frames, duration = frames / rate, bitrate = 0, tags = {} :: Types.Tags, } local mtags = type(midi.meta) == "table" and midi.meta.tags if type(mtags) == "table" then for k, v in mtags do if type(k) == "string" and type(v) == "string" then dec.tags[k] = v end end end for _, t in midi.tracks do if t.name and not dec.tags.title then dec.tags.title = t.name end end local function read(_self: any, n: number, out: buffer?): (buffer, number) n = math.max(0, math.min(math.floor(n), frames - pos)) local buf = out if not buf or buffer.len(buf) < n * 8 then buf = buffer.create(math.max(n, 1) * 8) end local b = buf :: buffer buffer.fill(b, 0, 0, n * 8) local i = 0 while i < n do while nextEv <= nev and evFrame[nextEv] <= pos + i do Synth.midi(state, tl.status[nextEv], tl.d1[nextEv], tl.d2[nextEv]) nextEv += 1 end local stop = n if nextEv <= nev then stop = math.min(n, evFrame[nextEv] - pos) end if stop > i then Synth.render(state, b, i, stop - i) i = stop end end pos += n return b, n end dec.read = read :: any local scratch = buffer.create(4096 * 8) dec.seek = function(_self: any, seconds: number) local target = math.clamp(math.floor((tonumber(seconds) or 0) * rate), 0, frames) if target < pos then Synth.reset(state) pos, nextEv = 0, 1 end while pos < target do read(nil, math.min(4096, target - pos), scratch) end end :: any dec.position = function(_self: any): number return pos / rate end :: any return (dec :: any) :: Types.Decoder, nil end -- tempo meta making each tick last 1 / ticksPerSecond s at that division (MUS, XMIDI, HMP / HMI) function Render.tempoBytes(division: number, ticksPerSecond: number): { number } local us = math.clamp(math.floor(division * 1e6 / ticksPerSecond + 0.5), 1, 0xFFFFFF) return { us // 65536, (us // 256) % 256, us % 256 } end type PendingOff = { tick: number, onTick: number, ev: Types.MidiEvent } -- XMIDI / HMI note durations: at equal ticks an off whose note started earlier goes before the file's events, -- an off of a zero-length note after them function Render.merge(events: { Types.MidiEvent }, offs: { PendingOff }): { Types.MidiEvent } for i, o in offs do (o :: any).seq = i end table.sort(offs, function(a: any, b: any): boolean if a.tick ~= b.tick then return a.tick < b.tick end return a.seq < b.seq end) local out: { Types.MidiEvent } = table.create(#events + #offs) :: { Types.MidiEvent } local k = 1 for _, ev in events do while k <= #offs and (offs[k].tick < ev.tick or (offs[k].tick == ev.tick and offs[k].onTick < ev.tick)) do table.insert(out, offs[k].ev) k += 1 end table.insert(out, ev) end for j = k, #offs do table.insert(out, offs[j].ev) end return out end local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder local dec, err = Render.decoder(self, opts) if not dec then local empty: any = { sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err, read = function(_self: any, _n: number, out: buffer?): (buffer, number) return out or buffer.create(0), 0 end, seek = function() end, position = function(): number return 0 end, } return empty end return dec end function Render.summarize(midi: Types.Midi) local tempos, sigs, keys = {}, {}, {} local map = Render.tempoMap(midi) for ti, t in midi.tracks do for _, ev in t.events do if ev.type == "meta" then local d = ev.data :: { number } if ev.meta == 0x51 and #d >= 3 then table.insert(tempos, { tick = ev.tick, track = ti, usPerQuarter = d[1] * 65536 + d[2] * 256 + d[3], bpm = 60000000 / math.max(1, d[1] * 65536 + d[2] * 256 + d[3]), seconds = Render.seconds(map, ev.tick) }) elseif ev.meta == 0x58 and #d >= 4 then table.insert(sigs, { tick = ev.tick, track = ti, numerator = d[1], denominator = 2 ^ math.min(d[2], 31), clocksPerClick = d[3], notated32ndsPerBeat = d[4] }) elseif ev.meta == 0x59 and #d >= 2 then table.insert(keys, { tick = ev.tick, track = ti, sharps = if d[1] >= 128 then d[1] - 256 else d[1], minor = d[2] == 1 }) end end end end midi.meta.tempos = tempos midi.meta.timeSignatures = sigs midi.meta.keySignatures = keys midi.meta.length = Render.length(midi) end function Render.attach(midi: Types.Midi, source: { [string]: any }) Render.summarize(midi) midi.meta.source = source midi.render = render end return Render end __FILES["codecs/audio/Mpa"] = function() -- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it. -- Core is a port of minimp3 by lieff (CC0, licenses/minimp3-CC0.txt), absorbed from mp3-luau c755bbf; the layer II / III -- encoders are new. local Mpa = { Header = __include("codecs/audio/Mpa/Header"), Core = __include("codecs/audio/Mpa/Core"), Encode3 = __include("codecs/audio/Mpa/Encode3"), Encode2 = __include("codecs/audio/Mpa/Encode2"), } return Mpa end __FILES["codecs/audio/Mpa/Analysis"] = @native function() -- codecs/audio/Mpa/Analysis: the polyphase analysis filterbank (ISO/IEC 11172-3 C.1.3, figure C.4): window C = D / 32, -- matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). local E = __include("codecs/audio/Mpa/EncTables") local Analysis = {} local C = table.create(512, 0) for i = 1, 512 do C[i] = E.D[i] / 32 end local M = table.create(32 * 64, 0) for k = 0, 31 do for i = 0, 63 do M[k * 64 + i + 1] = math.cos((2 * k + 1) * (i - 16) * math.pi / 64) end end type State = { x: { number }, off: number, y: { number } } @native function Analysis.new(): State return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) } end @native function Analysis.run(st: State, s: { number }, si: number, out: { number }, oi: number) -- the window X is kept twice (x[p] and x[p + 512]) so X[i] = x[off + i + 1] without a modulo local x = st.x local off = (st.off - 32) % 512 st.off = off for j = 0, 31 do local v = s[si + j] local p = (off + 31 - j) % 512 + 1 -- X[31 - j]: the first new sample goes to X[31], the newest to X[0] x[p] = v x[p + 512] = v end local y = st.y for i = 0, 63 do local acc = 0 local b = off + i + 1 for j = 0, 7 do acc += C[i + 64 * j + 1] * x[b + 64 * j] end y[i + 1] = acc end for k = 0, 31 do local acc = 0 local mb = k * 64 for i = 1, 64 do acc += M[mb + i] * y[i] end out[oi + k] = acc end end return Analysis end __FILES["codecs/audio/Mpa/Core"] = @native function() -- codecs/audio/Mpa/Core: a line-by-line port of minimp3's mp3dec_decode_frame (https://github.com/lieff/minimp3, CC0) -- for layers I, II and III, using its scalar (non-SIMD) code paths and float output. local T = __include("codecs/audio/Mpa/Tables") local band, bor, lshift, rshift, arshift, bswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.arshift, bit32.byteswap local ru8, wu8, ru32, ri16 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.readi16 local rf, wf = buffer.readf32, buffer.writef32 local bcopy, bfill, bcreate = buffer.copy, buffer.fill, buffer.create local min, max = math.min, math.max local MAX_BITRESERVOIR_BYTES = 511 local MAX_FRAME = 2304 + 8 -- largest frame (free format) incl. padding, rounded up local SCALE = 1 / 32768 -- tables (floats rounded to f32 like the C arrays) local F32 = bcreate(4) @native local function f32(x: number): number wf(F32, 0, x) return rf(F32, 0) end @native local function fbuf(list: { [number]: number }, n: number): buffer local b = bcreate(n * 4) for i = 0, n - 1 do wf(b, i * 4, list[i]) end return b end -- scalefactor band widths: long (8 x 23) | short (8 x 40) | mixed (8 x 40), one u8 buffer local SFB_LONG, SFB_SHORT, SFB_MIXED = 0, 184, 504 local SFB = bcreate(824 + 8) for i = 0, 183 do wu8(SFB, SFB_LONG + i, T.g_scf_long[i]) end for i = 0, 319 do wu8(SFB, SFB_SHORT + i, T.g_scf_short[i]) wu8(SFB, SFB_MIXED + i, T.g_scf_mixed[i]) end local TABS = bcreate(2164 * 2) for i = 0, 2163 do buffer.writei16(TABS, i * 2, T.tabs[i]) end local TAB32, TAB33 = T.tab32, T.tab33 local TABINDEX, LINBITS = T.tabindex, T.g_linbits local SCF_PARTITIONS, SCFC_DECODE, GMOD, PREAMP = T.g_scf_partitions, T.g_scfc_decode, T.g_mod, T.g_preamp local EXPFRAC = { [0] = f32(T.g_expfrac[0]), f32(T.g_expfrac[1]), f32(T.g_expfrac[2]), f32(T.g_expfrac[3]) } local PAN = {} for i = 0, 13 do PAN[i] = f32(T.g_pan[i]) end local BITALLOC_CODE = T.g_bitalloc_code_tab local HALFRATE = T.halfrate -- L3_pow_43 for every value a Huffman pair can give (15 + 8191 linbits), evaluated in f32 like the C code local POW43 = bcreate(8207 * 4) do local g = {} for i = 0, 144 do g[i] = f32(T.g_pow43[i]) end local c43, c29 = f32(4 / 3), f32(2 / 9) for x0 = 0, 8206 do local v if x0 < 129 then v = g[16 + x0] else local x, mult = x0, 256 if x < 1024 then mult = 16 x *= 8 end local sign = band(2 * x, 64) local frac = f32((band(x, 63) - sign) / (band(x, bit32.bnot(63)) + sign)) v = f32(f32(g[16 + rshift(x + sign, 6)] * f32(1 + f32(frac * f32(c43 + f32(frac * c29))))) * mult) end wf(POW43, x0 * 4, v) end end -- L12 dequantizer: 9.53674316e-07f / x (and two more steps of 2^(-1/3)) for 3, 7, ..., 65535, 3, 5, 9 local DEQ_L12 = {} do local div = { 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 3, 5, 9 } local base = { f32(9.53674316e-07), f32(7.56931807e-07), f32(6.00777173e-07) } for i = 0, 17 do for j = 0, 2 do DEQ_L12[i * 3 + j] = f32(base[j + 1] / div[i + 1]) end end end local AA = fbuf(T.g_aa, 16) local TWID3 = fbuf(T.g_twid3, 6) local MDCT_WIN0, MDCT_WIN1 = table.create(18, 0), table.create(18, 0) -- g_mdct_window[2][18], 1-based for i = 0, 17 do MDCT_WIN0[i + 1] = f32(T.g_mdct_window[i]) MDCT_WIN1[i + 1] = f32(T.g_mdct_window[18 + i]) end local WINT = table.create(240, 0) -- g_win as a 1-based Luau array (f32 values) for i = 0, 239 do WINT[i + 1] = f32(T.g_win[i]) end local FRAME = bcreate(MAX_FRAME + 64) -- the current frame, copied (bit reader reads up to 4 bytes ahead) local MAIN = bcreate(MAX_BITRESERVOIR_BYTES + MAX_FRAME + 4096) local GRBUF = bcreate(576 * 2 * 4) -- [ch][576] f32 local SCF = bcreate(40 * 4) local SYN = bcreate((18 + 15) * 64 * 4) local IST = bcreate(2 * 39 + 8) -- ist_pos[2][39], u8 local ISCF = bcreate(48) local TMP = bcreate(18 * 4 * 2) -- imdct scratch: co[9] si[9] / short block copy[18] local L12SCF = bcreate(192 * 4) -- L12 scalefactors [band*2 + ch][3], f32 local BA = bcreate(64) local SCFCOD = bcreate(64) -- layer III side info, per granule x channel (0..3) local GR_P23, GR_BV, GR_SFC, GR_GAIN, GR_BT, GR_MIXED = {}, {}, {}, {}, {}, {} local GR_NLONG, GR_NSHORT, GR_SFB, GR_PRE, GR_SCALE, GR_C1, GR_SCFSI = {}, {}, {}, {}, {}, {}, {} local GR_TS, GR_RC, GR_SBG = {}, {}, {} -- [gr * 3 + k] for i = 0, 3 do GR_P23[i], GR_BV[i], GR_SFC[i], GR_GAIN[i], GR_BT[i], GR_MIXED[i] = 0, 0, 0, 0, 0, 0 GR_NLONG[i], GR_NSHORT[i], GR_SFB[i], GR_PRE[i], GR_SCALE[i], GR_C1[i], GR_SCFSI[i] = 0, 0, 0, 0, 0, 0, 0 for k = 0, 2 do GR_TS[i * 3 + k], GR_RC[i * 3 + k], GR_SBG[i * 3 + k] = 0, 0, 0 end end local MAXB = { [0] = -1, -1, -1 } local SCFSIZE = { [0] = 0, 0, 0, 0 } local OVL: buffer = bcreate(4) -- mdct_overlap[2][9*32] local QMF: buffer = bcreate(4) -- qmf_state[15*2*32] local PCM: buffer = bcreate(4) -- bit reader (bs_t) local bsBuf: buffer = FRAME local bsPos = 0 local bsLimit = 0 @native local function getBits(n: number): number local pos = bsPos bsPos = pos + n if pos + n > bsLimit then return 0 end local w = lshift(bswap(ru32(bsBuf, rshift(pos, 3))), band(pos, 7)) return rshift(w, 32 - n) end -- layer III side info (L3_read_side_info): fills GR_*, returns main_data_begin or -1 @native local function readSideInfo(h1: number, h2: number, h3: number): number local mono = band(h3, 0xC0) == 0xC0 local mpeg1 = band(h1, 8) ~= 0 local srIdx = band(rshift(h2, 2), 3) + (band(rshift(h1, 3), 1) + band(rshift(h1, 4), 1)) * 3 if srIdx ~= 0 then srIdx -= 1 end local grCount = if mono then 1 else 2 local scfsi = 0 local mdb if mpeg1 then grCount *= 2 mdb = getBits(9) scfsi = getBits(7 + grCount) else mdb = rshift(getBits(8 + grCount), grCount) end local part23sum = 0 for gr = 0, grCount - 1 do if mono then scfsi = lshift(scfsi, 4) end local p23 = getBits(12) GR_P23[gr] = p23 part23sum += p23 local bv = getBits(9) if bv > 288 then return -1 end GR_BV[gr] = bv GR_GAIN[gr] = getBits(8) local sfc = getBits(if mpeg1 then 4 else 9) GR_SFC[gr] = sfc GR_SFB[gr] = SFB_LONG + srIdx * 23 GR_NLONG[gr] = 22 GR_NSHORT[gr] = 0 local tables local g3 = gr * 3 if getBits(1) ~= 0 then local bt = getBits(2) if bt == 0 then return -1 end GR_BT[gr] = bt local mixed = getBits(1) GR_MIXED[gr] = mixed GR_RC[g3] = 7 GR_RC[g3 + 1] = 255 if bt == 2 then scfsi = band(scfsi, 0x0F0F) if mixed == 0 then GR_RC[g3] = 8 GR_SFB[gr] = SFB_SHORT + srIdx * 40 GR_NLONG[gr] = 0 GR_NSHORT[gr] = 39 else GR_SFB[gr] = SFB_MIXED + srIdx * 40 GR_NLONG[gr] = if mpeg1 then 8 else 6 GR_NSHORT[gr] = 30 end end tables = lshift(getBits(10), 5) GR_SBG[g3] = getBits(3) GR_SBG[g3 + 1] = getBits(3) GR_SBG[g3 + 2] = getBits(3) else GR_BT[gr] = 0 GR_MIXED[gr] = 0 tables = getBits(15) GR_RC[g3] = getBits(4) GR_RC[g3 + 1] = getBits(3) GR_RC[g3 + 2] = 255 end GR_TS[g3] = rshift(tables, 10) GR_TS[g3 + 1] = band(rshift(tables, 5), 31) GR_TS[g3 + 2] = band(tables, 31) GR_PRE[gr] = if mpeg1 then getBits(1) elseif sfc >= 500 then 1 else 0 GR_SCALE[gr] = getBits(1) GR_C1[gr] = getBits(1) GR_SCFSI[gr] = band(rshift(scfsi, 12), 15) scfsi = lshift(scfsi, 4) end if part23sum + bsPos > bsLimit + mdb * 8 then return -1 end return mdb end @native local function ldexpQ2(y: number, e: number): number repeat local s = if e < 120 then e else 120 y = f32(y * EXPFRAC[band(s, 3)] * lshift(1, 30 - arshift(s, 2))) e -= s until e <= 0 return y end -- L3_read_scalefactors + L3_decode_scalefactors -> SCF[0 .. nLong + nShort) @native local function decodeScalefactors(h1: number, h3: number, istOff: number, gr: number, ch: number) local mpeg1 = band(h1, 8) ~= 0 local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr] local part = ((if nShort ~= 0 then 1 else 0) + (if nLong == 0 then 1 else 0)) * 28 local scfShift = GR_SCALE[gr] + 1 local scfsi = GR_SCFSI[gr] if mpeg1 then local p = SCFC_DECODE[GR_SFC[gr]] local hi, lo = rshift(p, 2), band(p, 3) SCFSIZE[0], SCFSIZE[1], SCFSIZE[2], SCFSIZE[3] = hi, hi, lo, lo else local ist = if band(h3, 0x10) ~= 0 and ch ~= 0 then 1 else 0 local sfc = rshift(GR_SFC[gr], ist) local k = ist * 12 while sfc >= 0 do local modprod = 1 for i = 3, 0, -1 do SCFSIZE[i] = (sfc // modprod) % GMOD[k + i] modprod *= GMOD[k + i] end sfc -= modprod k += 4 end part += k end -- L3_read_scalefactors local sp, ip = 0, istOff for i = 0, 3 do local cnt = SCF_PARTITIONS[part + i] if cnt == 0 then break end if mpeg1 and band(scfsi, 8) ~= 0 then bcopy(ISCF, sp, IST, ip, cnt) else local bits = SCFSIZE[i] if bits == 0 then bfill(ISCF, sp, 0, cnt) bfill(IST, ip, 0, cnt) else local maxScf = if mpeg1 then -1 else lshift(1, bits) - 1 for k = 0, cnt - 1 do local s = getBits(bits) wu8(IST, ip + k, if s == maxScf then 255 else s) wu8(ISCF, sp + k, s) end end end sp += cnt ip += cnt scfsi *= 2 end wu8(ISCF, sp, 0) wu8(ISCF, sp + 1, 0) wu8(ISCF, sp + 2, 0) if nShort ~= 0 then local sh = 3 - scfShift local g3 = gr * 3 local s0, s1, s2 = lshift(GR_SBG[g3], sh), lshift(GR_SBG[g3 + 1], sh), lshift(GR_SBG[g3 + 2], sh) for i = 0, nShort - 1, 3 do local o = nLong + i wu8(ISCF, o, band(ru8(ISCF, o) + s0, 255)) wu8(ISCF, o + 1, band(ru8(ISCF, o + 1) + s1, 255)) wu8(ISCF, o + 2, band(ru8(ISCF, o + 2) + s2, 255)) end elseif GR_PRE[gr] ~= 0 then for i = 0, 9 do wu8(ISCF, 11 + i, band(ru8(ISCF, 11 + i) + PREAMP[i], 255)) end end local gainExp = GR_GAIN[gr] - 4 - 210 - (if band(h3, 0xE0) == 0x60 then 2 else 0) local gain = ldexpQ2(2048, 44 - gainExp) for i = 0, nLong + nShort - 1 do wf(SCF, i * 4, ldexpQ2(gain, lshift(ru8(ISCF, i), scfShift))) end end -- layer III Huffman decoding (L3_huffman) into GRBUF[dst ..], reads MAIN through a 32-bit cache @native local function huffman(dst: number, gr: number, limit: number) local b = bsBuf local one = 0.0 local ireg = 0 local bigValCnt = GR_BV[gr] local sfb = GR_SFB[gr] local scf = 0 local pos = bsPos local nextPtr = rshift(pos, 3) local cache = lshift(bswap(ru32(b, nextPtr)), band(pos, 7)) local sh = band(pos, 7) - 8 nextPtr += 4 local g3 = gr * 3 local d = dst * 4 while bigValCnt > 0 do if ireg > 2 then break end local tabNum = GR_TS[g3 + ireg] local sfbCnt = GR_RC[g3 + ireg] ireg += 1 local cb = TABINDEX[tabNum] local linbits = LINBITS[tabNum] repeat local np = rshift(ru8(SFB, sfb), 1) sfb += 1 if np == 0 then bigValCnt = 0 break end local pairs = if bigValCnt < np then bigValCnt else np one = rf(SCF, scf) scf += 4 for _ = 1, pairs do local w = 5 local leaf = ri16(TABS, (cb + rshift(cache, 27)) * 2) while leaf < 0 do cache = lshift(cache, w) sh += w w = band(leaf, 7) leaf = ri16(TABS, (cb + rshift(cache, 32 - w) - leaf // 8) * 2) end local l = rshift(leaf, 8) cache = lshift(cache, l) sh += l for _ = 1, 2 do local lsb = band(leaf, 15) if lsb == 15 and linbits ~= 0 then lsb += rshift(cache, 32 - linbits) cache = lshift(cache, linbits) sh += linbits while sh >= 0 do cache = bor(cache, lshift(ru8(b, nextPtr), sh)) nextPtr += 1 sh -= 8 end end local v = rf(POW43, lsb * 4) * one if lsb ~= 0 then if cache >= 0x80000000 then v = -v end cache = lshift(cache, 1) sh += 1 end wf(GRBUF, d, v) d += 4 leaf = rshift(leaf, 4) end while sh >= 0 do cache = bor(cache, lshift(ru8(b, nextPtr), sh)) nextPtr += 1 sh -= 8 end end bigValCnt -= np sfbCnt -= 1 until not (bigValCnt > 0 and sfbCnt >= 0) end -- count1 quadruples local np = 1 - bigValCnt local cb1 = if GR_C1[gr] ~= 0 then TAB33 else TAB32 local dend = 576 * 4 * 2 while true do local leaf = cb1[rshift(cache, 28)] if band(leaf, 8) == 0 then leaf = cb1[rshift(leaf, 3) + rshift(lshift(cache, 4), 32 - band(leaf, 3))] end local l = band(leaf, 7) cache = lshift(cache, l) sh += l if nextPtr * 8 - 24 + sh > limit or d + 16 > dend then break end np -= 1 if np == 0 then np = rshift(ru8(SFB, sfb), 1) sfb += 1 if np == 0 then break end one = rf(SCF, scf) scf += 4 end if band(leaf, 128) ~= 0 then wf(GRBUF, d, if cache >= 0x80000000 then -one else one) cache = lshift(cache, 1) sh += 1 end if band(leaf, 64) ~= 0 then wf(GRBUF, d + 4, if cache >= 0x80000000 then -one else one) cache = lshift(cache, 1) sh += 1 end np -= 1 if np == 0 then np = rshift(ru8(SFB, sfb), 1) sfb += 1 if np == 0 then break end one = rf(SCF, scf) scf += 4 end if band(leaf, 32) ~= 0 then wf(GRBUF, d + 8, if cache >= 0x80000000 then -one else one) cache = lshift(cache, 1) sh += 1 end if band(leaf, 16) ~= 0 then wf(GRBUF, d + 12, if cache >= 0x80000000 then -one else one) cache = lshift(cache, 1) sh += 1 end while sh >= 0 do cache = bor(cache, lshift(ru8(b, nextPtr), sh)) nextPtr += 1 sh -= 8 end d += 16 end bsPos = limit end -- L3_midside_stereo on GRBUF[left .. left + n) and its right channel at + 576 @native local function midside(left: number, n: number) for i = left * 4, (left + n - 1) * 4, 4 do local a, c = rf(GRBUF, i), rf(GRBUF, i + 2304) wf(GRBUF, i, a + c) wf(GRBUF, i + 2304, a - c) end end @native local function intensityStereo(h1: number, h3: number, gr: number) local mpeg1 = band(h1, 8) ~= 0 local ms = band(h3, 0x20) ~= 0 local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr] local nSfb = nLong + nShort local maxBlocks = if nShort ~= 0 then 3 else 1 local sfb0 = GR_SFB[gr] -- L3_stereo_top_band on the right channel MAXB[0], MAXB[1], MAXB[2] = -1, -1, -1 local right = 576 for i = 0, nSfb - 1 do local n = ru8(SFB, sfb0 + i) for k = right, right + n - 1, 2 do if rf(GRBUF, k * 4) ~= 0 or rf(GRBUF, k * 4 + 4) ~= 0 then MAXB[i % 3] = i break end end right += n end if nLong ~= 0 then local m = max(MAXB[0], MAXB[1], MAXB[2]) MAXB[0], MAXB[1], MAXB[2] = m, m, m end for i = 0, maxBlocks - 1 do local defaultPos = if mpeg1 then 3 else 0 local itop = nSfb - maxBlocks + i local prev = itop - maxBlocks wu8(IST, 39 + itop, if MAXB[i] >= prev then defaultPos else ru8(IST, 39 + prev)) end -- L3_stereo_process local mpeg2sh = band(GR_SFC[gr + 1], 1) local maxPos = if mpeg1 then 7 else 64 local s = if ms then f32(1.41421356) else 1 local left = 0 local i = 0 while true do local n = ru8(SFB, sfb0 + i) if n == 0 then break end local ipos = ru8(IST, 39 + i) if i > MAXB[i % 3] and ipos < maxPos then local kl, kr if mpeg1 then kl, kr = PAN[2 * ipos], PAN[2 * ipos + 1] else kl = 1 kr = ldexpQ2(1, lshift(rshift(ipos + 1, 1), mpeg2sh)) if band(ipos, 1) ~= 0 then kl = kr kr = 1 end end kl = f32(kl * s) kr = f32(kr * s) for k = left * 4, (left + n - 1) * 4, 4 do local v = rf(GRBUF, k) wf(GRBUF, k + 2304, v * kr) wf(GRBUF, k, v * kl) end elseif ms then midside(left, n) end left += n i += 1 end end @native local function reorder(g: number, sfb: number) local src, dst = g, 0 while true do local len = ru8(SFB, sfb) if len == 0 then break end for i = 0, len - 1 do local s = (src + i) * 4 wf(SYN, dst, rf(GRBUF, s)) wf(SYN, dst + 4, rf(GRBUF, s + len * 4)) wf(SYN, dst + 8, rf(GRBUF, s + len * 8)) dst += 12 end src += 3 * len sfb += 3 end bcopy(GRBUF, g * 4, SYN, 0, dst) end local AA0 = table.create(8, 0) local AA1 = table.create(8, 0) for i = 0, 7 do AA0[i + 1] = rf(AA, i * 4) AA1[i + 1] = rf(AA, 32 + i * 4) end @native local function antialias(g: number, nbands: number) local o = g * 4 for _ = 1, nbands do for i = 0, 7 do local ui, di = o + (18 + i) * 4, o + (17 - i) * 4 local u, d = rf(GRBUF, ui), rf(GRBUF, di) local c0, c1 = AA0[i + 1], AA1[i + 1] wf(GRBUF, ui, u * c0 - d * c1) wf(GRBUF, di, u * c1 + d * c0) end o += 72 end end -- BEGIN generated by tools/gen_dsp.py -- L3_dct3_9 on 9 values @native local function dct3_9(s0: number, s1: number, s2: number, s3: number, s4: number, s5: number, s6: number, s7: number, s8: number) local t0 = s0 + s6 * 0.5 s0 -= s6 local t4 = (s4 + s2) * 0.939692616 local t2 = (s8 + s2) * 0.766044438 s6 = (s4 - s8) * 0.173648179 s4 += s8 - s2 s2 = s0 - s4 * 0.5 local y4 = s4 + s0 s8 = t0 - t2 + s6 s0 = t0 - t4 + t2 s4 = t0 + t4 - s6 s3 *= 0.866025388 t0 = (s5 + s1) * 0.98480773 t4 = (s5 - s7) * 0.342020154 t2 = (s1 + s7) * 0.642787635 s1 = (s1 - s5 - s7) * 0.866025388 s5 = t0 - s3 - t2 s7 = t4 - s3 - t0 s3 = t4 + s3 - t2 return s4 - s7, s2 + s1, s0 - s3, s8 + s5, y4, s8 - s5, s0 + s3, s2 - s1, s4 + s7 end -- L3_imdct36: GRBUF[g ..], OVL[ov ..] (float indices), window W (1-based, 18 values) @native local function imdct36(g: number, ov: number, W: { number }, nbands: number) local w0 = W[1] local w1 = W[2] local w2 = W[3] local w3 = W[4] local w4 = W[5] local w5 = W[6] local w6 = W[7] local w7 = W[8] local w8 = W[9] local w9 = W[10] local w10 = W[11] local w11 = W[12] local w12 = W[13] local w13 = W[14] local w14 = W[15] local w15 = W[16] local w16 = W[17] local w17 = W[18] for _ = 1, nbands do local gb = g * 4 local g0 = rf(GRBUF, gb + 0) local g1 = rf(GRBUF, gb + 4) local g2 = rf(GRBUF, gb + 8) local g3 = rf(GRBUF, gb + 12) local g4 = rf(GRBUF, gb + 16) local g5 = rf(GRBUF, gb + 20) local g6 = rf(GRBUF, gb + 24) local g7 = rf(GRBUF, gb + 28) local g8 = rf(GRBUF, gb + 32) local g9 = rf(GRBUF, gb + 36) local g10 = rf(GRBUF, gb + 40) local g11 = rf(GRBUF, gb + 44) local g12 = rf(GRBUF, gb + 48) local g13 = rf(GRBUF, gb + 52) local g14 = rf(GRBUF, gb + 56) local g15 = rf(GRBUF, gb + 60) local g16 = rf(GRBUF, gb + 64) local g17 = rf(GRBUF, gb + 68) local c0, c1, c2, c3, c4, c5, c6, c7, c8 = dct3_9(-g0, g1 + g2, -(g3 + g4), g5 + g6, -(g7 + g8), g9 + g10, -(g11 + g12), g13 + g14, -(g15 + g16)) local s0, s1, s2, s3, s4, s5, s6, s7, s8 = dct3_9(g17, g16 - g15, g13 - g14, g12 - g11, g9 - g10, g8 - g7, g5 - g6, g4 - g3, g1 - g2) s1, s3, s5, s7 = -s1, -s3, -s5, -s7 local ob = ov * 4 do local ovl = rf(OVL, ob + 0) local sum = c0 * 0.675590217 + s0 * 0.737277329 wf(OVL, ob + 0, c0 * 0.737277329 - s0 * 0.675590217) wf(GRBUF, gb + 0, ovl * w0 - sum * w9) wf(GRBUF, gb + 68, ovl * w9 + sum * w0) end do local ovl = rf(OVL, ob + 4) local sum = c1 * 0.60876143 + s1 * 0.793353319 wf(OVL, ob + 4, c1 * 0.793353319 - s1 * 0.60876143) wf(GRBUF, gb + 4, ovl * w1 - sum * w10) wf(GRBUF, gb + 64, ovl * w10 + sum * w1) end do local ovl = rf(OVL, ob + 8) local sum = c2 * 0.537299633 + s2 * 0.843391478 wf(OVL, ob + 8, c2 * 0.843391478 - s2 * 0.537299633) wf(GRBUF, gb + 8, ovl * w2 - sum * w11) wf(GRBUF, gb + 60, ovl * w11 + sum * w2) end do local ovl = rf(OVL, ob + 12) local sum = c3 * 0.4617486 + s3 * 0.887010813 wf(OVL, ob + 12, c3 * 0.887010813 - s3 * 0.4617486) wf(GRBUF, gb + 12, ovl * w3 - sum * w12) wf(GRBUF, gb + 56, ovl * w12 + sum * w3) end do local ovl = rf(OVL, ob + 16) local sum = c4 * 0.382683426 + s4 * 0.923879504 wf(OVL, ob + 16, c4 * 0.923879504 - s4 * 0.382683426) wf(GRBUF, gb + 16, ovl * w4 - sum * w13) wf(GRBUF, gb + 52, ovl * w13 + sum * w4) end do local ovl = rf(OVL, ob + 20) local sum = c5 * 0.300705791 + s5 * 0.953716934 wf(OVL, ob + 20, c5 * 0.953716934 - s5 * 0.300705791) wf(GRBUF, gb + 20, ovl * w5 - sum * w14) wf(GRBUF, gb + 48, ovl * w14 + sum * w5) end do local ovl = rf(OVL, ob + 24) local sum = c6 * 0.216439605 + s6 * 0.976296008 wf(OVL, ob + 24, c6 * 0.976296008 - s6 * 0.216439605) wf(GRBUF, gb + 24, ovl * w6 - sum * w15) wf(GRBUF, gb + 44, ovl * w15 + sum * w6) end do local ovl = rf(OVL, ob + 28) local sum = c7 * 0.130526185 + s7 * 0.991444886 wf(OVL, ob + 28, c7 * 0.991444886 - s7 * 0.130526185) wf(GRBUF, gb + 28, ovl * w7 - sum * w16) wf(GRBUF, gb + 40, ovl * w16 + sum * w7) end do local ovl = rf(OVL, ob + 32) local sum = c8 * 0.0436193794 + s8 * 0.999048233 wf(OVL, ob + 32, c8 * 0.999048233 - s8 * 0.0436193794) wf(GRBUF, gb + 32, ovl * w8 - sum * w17) wf(GRBUF, gb + 36, ovl * w17 + sum * w8) end g += 18 ov += 9 end end -- mp3d_DCT_II (scalar path) over the n time slots of a channel at GRBUF[g ..]: t[4][8] in locals @native local function dctII(g: number, n: number) for k = 0, n - 1 do local y = (g + k) * 4 local t0_0, t1_0, t2_0, t3_0 do local x0, x1, x2, x3 = rf(GRBUF, y + 0), rf(GRBUF, y + 1080), rf(GRBUF, y + 1152), rf(GRBUF, y + 2232) local a, b = x0 + x3, x1 + x2 local c, d = (x1 - x2) * 10.1900082, (x0 - x3) * 0.50060302 t0_0 = a + b t1_0 = (a - b) * 0.502419293 t2_0 = d + c t3_0 = (d - c) * 0.502419293 end local t0_1, t1_1, t2_1, t3_1 do local x0, x1, x2, x3 = rf(GRBUF, y + 72), rf(GRBUF, y + 1008), rf(GRBUF, y + 1224), rf(GRBUF, y + 2160) local a, b = x0 + x3, x1 + x2 local c, d = (x1 - x2) * 3.40760851, (x0 - x3) * 0.505470932 t0_1 = a + b t1_1 = (a - b) * 0.522498608 t2_1 = d + c t3_1 = (d - c) * 0.522498608 end local t0_2, t1_2, t2_2, t3_2 do local x0, x1, x2, x3 = rf(GRBUF, y + 144), rf(GRBUF, y + 936), rf(GRBUF, y + 1296), rf(GRBUF, y + 2088) local a, b = x0 + x3, x1 + x2 local c, d = (x1 - x2) * 2.05778098, (x0 - x3) * 0.515447319 t0_2 = a + b t1_2 = (a - b) * 0.566944063 t2_2 = d + c t3_2 = (d - c) * 0.566944063 end local t0_3, t1_3, t2_3, t3_3 do local x0, x1, x2, x3 = rf(GRBUF, y + 216), rf(GRBUF, y + 864), rf(GRBUF, y + 1368), rf(GRBUF, y + 2016) local a, b = x0 + x3, x1 + x2 local c, d = (x1 - x2) * 1.4841646, (x0 - x3) * 0.531042576 t0_3 = a + b t1_3 = (a - b) * 0.646821797 t2_3 = d + c t3_3 = (d - c) * 0.646821797 end local t0_4, t1_4, t2_4, t3_4 do local x0, x1, x2, x3 = rf(GRBUF, y + 288), rf(GRBUF, y + 792), rf(GRBUF, y + 1440), rf(GRBUF, y + 1944) local a, b = x0 + x3, x1 + x2 local c, d = (x1 - x2) * 1.16943991, (x0 - x3) * 0.553103924 t0_4 = a + b t1_4 = (a - b) * 0.788154602 t2_4 = d + c t3_4 = (d - c) * 0.788154602 end local t0_5, t1_5, t2_5, t3_5 do local x0, x1, x2, x3 = rf(GRBUF, y + 360), rf(GRBUF, y + 720), rf(GRBUF, y + 1512), rf(GRBUF, y + 1872) local a, b = x0 + x3, x1 + x2 local c, d = (x1 - x2) * 0.972568214, (x0 - x3) * 0.582934976 t0_5 = a + b t1_5 = (a - b) * 1.06067765 t2_5 = d + c t3_5 = (d - c) * 1.06067765 end local t0_6, t1_6, t2_6, t3_6 do local x0, x1, x2, x3 = rf(GRBUF, y + 432), rf(GRBUF, y + 648), rf(GRBUF, y + 1584), rf(GRBUF, y + 1800) local a, b = x0 + x3, x1 + x2 local c, d = (x1 - x2) * 0.839349627, (x0 - x3) * 0.622504115 t0_6 = a + b t1_6 = (a - b) * 1.72244716 t2_6 = d + c t3_6 = (d - c) * 1.72244716 end local t0_7, t1_7, t2_7, t3_7 do local x0, x1, x2, x3 = rf(GRBUF, y + 504), rf(GRBUF, y + 576), rf(GRBUF, y + 1656), rf(GRBUF, y + 1728) local a, b = x0 + x3, x1 + x2 local c, d = (x1 - x2) * 0.744536281, (x0 - x3) * 0.674808323 t0_7 = a + b t1_7 = (a - b) * 5.10114861 t2_7 = d + c t3_7 = (d - c) * 5.10114861 end do local x0, x1, x2, x3, x4, x5, x6, x7 = t0_0, t0_1, t0_2, t0_3, t0_4, t0_5, t0_6, t0_7 local xt = x0 - x7 x0 += x7 x7 = x1 - x6 x1 += x6 x6 = x2 - x5 x2 += x5 x5 = x3 - x4 x3 += x4 x4 = x0 - x3 x0 += x3 x3 = x1 - x2 x1 += x2 t0_0 = x0 + x1 t0_4 = (x0 - x1) * 0.707106769 x5 += x6 x6 = (x6 + x7) * 0.707106769 x7 += xt x3 = (x3 + x4) * 0.707106769 x5 -= x7 * 0.198912367 x7 += x5 * 0.382683426 x5 -= x7 * 0.198912367 x0 = xt - x6 xt += x6 t0_1 = (xt + x7) * 0.509795606 t0_2 = (x4 + x3) * 0.541196108 t0_3 = (x0 - x5) * 0.601344883 t0_5 = (x0 + x5) * 0.899976194 t0_6 = (x4 - x3) * 1.30656302 t0_7 = (xt - x7) * 2.56291556 end do local x0, x1, x2, x3, x4, x5, x6, x7 = t1_0, t1_1, t1_2, t1_3, t1_4, t1_5, t1_6, t1_7 local xt = x0 - x7 x0 += x7 x7 = x1 - x6 x1 += x6 x6 = x2 - x5 x2 += x5 x5 = x3 - x4 x3 += x4 x4 = x0 - x3 x0 += x3 x3 = x1 - x2 x1 += x2 t1_0 = x0 + x1 t1_4 = (x0 - x1) * 0.707106769 x5 += x6 x6 = (x6 + x7) * 0.707106769 x7 += xt x3 = (x3 + x4) * 0.707106769 x5 -= x7 * 0.198912367 x7 += x5 * 0.382683426 x5 -= x7 * 0.198912367 x0 = xt - x6 xt += x6 t1_1 = (xt + x7) * 0.509795606 t1_2 = (x4 + x3) * 0.541196108 t1_3 = (x0 - x5) * 0.601344883 t1_5 = (x0 + x5) * 0.899976194 t1_6 = (x4 - x3) * 1.30656302 t1_7 = (xt - x7) * 2.56291556 end do local x0, x1, x2, x3, x4, x5, x6, x7 = t2_0, t2_1, t2_2, t2_3, t2_4, t2_5, t2_6, t2_7 local xt = x0 - x7 x0 += x7 x7 = x1 - x6 x1 += x6 x6 = x2 - x5 x2 += x5 x5 = x3 - x4 x3 += x4 x4 = x0 - x3 x0 += x3 x3 = x1 - x2 x1 += x2 t2_0 = x0 + x1 t2_4 = (x0 - x1) * 0.707106769 x5 += x6 x6 = (x6 + x7) * 0.707106769 x7 += xt x3 = (x3 + x4) * 0.707106769 x5 -= x7 * 0.198912367 x7 += x5 * 0.382683426 x5 -= x7 * 0.198912367 x0 = xt - x6 xt += x6 t2_1 = (xt + x7) * 0.509795606 t2_2 = (x4 + x3) * 0.541196108 t2_3 = (x0 - x5) * 0.601344883 t2_5 = (x0 + x5) * 0.899976194 t2_6 = (x4 - x3) * 1.30656302 t2_7 = (xt - x7) * 2.56291556 end do local x0, x1, x2, x3, x4, x5, x6, x7 = t3_0, t3_1, t3_2, t3_3, t3_4, t3_5, t3_6, t3_7 local xt = x0 - x7 x0 += x7 x7 = x1 - x6 x1 += x6 x6 = x2 - x5 x2 += x5 x5 = x3 - x4 x3 += x4 x4 = x0 - x3 x0 += x3 x3 = x1 - x2 x1 += x2 t3_0 = x0 + x1 t3_4 = (x0 - x1) * 0.707106769 x5 += x6 x6 = (x6 + x7) * 0.707106769 x7 += xt x3 = (x3 + x4) * 0.707106769 x5 -= x7 * 0.198912367 x7 += x5 * 0.382683426 x5 -= x7 * 0.198912367 x0 = xt - x6 xt += x6 t3_1 = (xt + x7) * 0.509795606 t3_2 = (x4 + x3) * 0.541196108 t3_3 = (x0 - x5) * 0.601344883 t3_5 = (x0 + x5) * 0.899976194 t3_6 = (x4 - x3) * 1.30656302 t3_7 = (xt - x7) * 2.56291556 end wf(GRBUF, y + 0, t0_0) wf(GRBUF, y + 72, t2_0 + t3_0 + t3_1) wf(GRBUF, y + 144, t1_0 + t1_1) wf(GRBUF, y + 216, t2_1 + t3_0 + t3_1) wf(GRBUF, y + 288, t0_1) wf(GRBUF, y + 360, t2_1 + t3_1 + t3_2) wf(GRBUF, y + 432, t1_1 + t1_2) wf(GRBUF, y + 504, t2_2 + t3_1 + t3_2) wf(GRBUF, y + 576, t0_2) wf(GRBUF, y + 648, t2_2 + t3_2 + t3_3) wf(GRBUF, y + 720, t1_2 + t1_3) wf(GRBUF, y + 792, t2_3 + t3_2 + t3_3) wf(GRBUF, y + 864, t0_3) wf(GRBUF, y + 936, t2_3 + t3_3 + t3_4) wf(GRBUF, y + 1008, t1_3 + t1_4) wf(GRBUF, y + 1080, t2_4 + t3_3 + t3_4) wf(GRBUF, y + 1152, t0_4) wf(GRBUF, y + 1224, t2_4 + t3_4 + t3_5) wf(GRBUF, y + 1296, t1_4 + t1_5) wf(GRBUF, y + 1368, t2_5 + t3_4 + t3_5) wf(GRBUF, y + 1440, t0_5) wf(GRBUF, y + 1512, t2_5 + t3_5 + t3_6) wf(GRBUF, y + 1584, t1_5 + t1_6) wf(GRBUF, y + 1656, t2_6 + t3_5 + t3_6) wf(GRBUF, y + 1728, t0_6) wf(GRBUF, y + 1800, t2_6 + t3_6 + t3_7) wf(GRBUF, y + 1872, t1_6 + t1_7) wf(GRBUF, y + 1944, t2_7 + t3_6 + t3_7) wf(GRBUF, y + 2016, t0_7) wf(GRBUF, y + 2088, t2_7 + t3_7) wf(GRBUF, y + 2160, t1_7) wf(GRBUF, y + 2232, t3_7) end end -- END generated -- L3_imdct12: x = TMP f32 index (stride 3), dst buffer + float index, ov = OVL float index @native local function imdct12(x: number, dst: buffer, d: number, ov: number) local xb = x * 4 local x0, x3, x6, x9, x12, x15 = rf(TMP, xb), rf(TMP, xb + 12), rf(TMP, xb + 24), rf(TMP, xb + 36), rf(TMP, xb + 48), rf(TMP, xb + 60) -- L3_idct3(-x0, x6 + x3, x12 + x9) -> co local c0, c1, c2 = -x0, (x6 + x3), (x12 + x9) local m1 = (c1 * 0.86602540) local a1 = (c0 - c2 * 0.5) local co1 = c0 + c2 local co0, co2 = a1 + m1, a1 - m1 -- L3_idct3(x15, x12 - x9, x6 - x3) -> si c0, c1, c2 = x15, (x12 - x9), (x6 - x3) m1 = (c1 * 0.86602540) a1 = (c0 - c2 * 0.5) local si1 = -(c0 + c2) local si0, si2 = a1 + m1, a1 - m1 local ob, db = ov * 4, d * 4 for i = 0, 2 do local co = if i == 0 then co0 elseif i == 1 then co1 else co2 local si = if i == 0 then si0 elseif i == 1 then si1 else si2 local ovl = rf(OVL, ob + i * 4) local sum = (co * rf(TWID3, (3 + i) * 4) + si * rf(TWID3, i * 4)) wf(OVL, ob + i * 4, co * rf(TWID3, i * 4) - si * rf(TWID3, (3 + i) * 4)) wf(dst, db + i * 4, ovl * rf(TWID3, (2 - i) * 4) - sum * rf(TWID3, (5 - i) * 4)) wf(dst, db + (5 - i) * 4, ovl * rf(TWID3, (5 - i) * 4) + sum * rf(TWID3, (2 - i) * 4)) end end @native local function imdctShort(g: number, ov: number, nbands: number) for _ = 1, nbands do bcopy(TMP, 0, GRBUF, g * 4, 72) bcopy(GRBUF, g * 4, OVL, ov * 4, 24) imdct12(0, GRBUF, g + 6, ov + 6) imdct12(1, GRBUF, g + 12, ov + 6) imdct12(2, OVL, ov, ov + 6) g += 18 ov += 9 end end @native local function changeSign(g: number) local o = (g + 18) * 4 for _ = 0, 15 do for i = 1, 17, 2 do wf(GRBUF, o + i * 4, -rf(GRBUF, o + i * 4)) end o += 144 end end @native local function imdctGr(g: number, ov: number, bt: number, nLongBands: number) if nLongBands ~= 0 then imdct36(g, ov, MDCT_WIN0, nLongBands) g += 18 * nLongBands ov += 9 * nLongBands end if bt == 2 then imdctShort(g, ov, 32 - nLongBands) else imdct36(g, ov, if bt == 3 then MDCT_WIN1 else MDCT_WIN0, 32 - nLongBands) end end -- L3_decode: one granule, side info at gr = grBase + ch @native local function l3Decode(h1: number, h2: number, h3: number, grBase: number, nch: number) for ch = 0, nch - 1 do local gr = grBase + ch local limit = bsPos + GR_P23[gr] decodeScalefactors(h1, h3, ch * 39, gr, ch) huffman(ch * 576, gr, limit) end if band(h3, 0x10) ~= 0 then intensityStereo(h1, h3, grBase) elseif band(h3, 0xE0) == 0x60 then midside(0, 576) end local mySr = band(rshift(h2, 2), 3) + (band(rshift(h1, 3), 1) + band(rshift(h1, 4), 1)) * 3 for ch = 0, nch - 1 do local gr = grBase + ch local aaBands = 31 local nLongBands = if GR_MIXED[gr] ~= 0 then (if mySr == 2 then 4 else 2) else 0 local g = ch * 576 if GR_NSHORT[gr] ~= 0 then aaBands = nLongBands - 1 reorder(g + nLongBands * 18, GR_SFB[gr] + GR_NLONG[gr]) end antialias(g, aaBands) imdctGr(g, ch * 288, GR_BT[gr], nLongBands) changeSign(g) end end -- polyphase synthesis (mp3d_DCT_II, mp3d_synth, mp3d_synth_granule) -- mp3d_synth_pair: z = SYN float index, dst = PCM float index @native local function synthPair(dst: number, nch: number, z: number) local zb = z * 4 local a = (rf(SYN, zb + 14 * 256) - rf(SYN, zb)) * 29 a += (rf(SYN, zb + 1 * 256) + rf(SYN, zb + 13 * 256)) * 213 a += (rf(SYN, zb + 12 * 256) - rf(SYN, zb + 2 * 256)) * 459 a += (rf(SYN, zb + 3 * 256) + rf(SYN, zb + 11 * 256)) * 2037 a += (rf(SYN, zb + 10 * 256) - rf(SYN, zb + 4 * 256)) * 5153 a += (rf(SYN, zb + 5 * 256) + rf(SYN, zb + 9 * 256)) * 6574 a += (rf(SYN, zb + 8 * 256) - rf(SYN, zb + 6 * 256)) * 37489 a += rf(SYN, zb + 7 * 256) * 75038 wf(PCM, dst * 4, a * SCALE) zb += 8 a = rf(SYN, zb + 14 * 256) * 104 a += rf(SYN, zb + 12 * 256) * 1567 a += rf(SYN, zb + 10 * 256) * 9727 a += rf(SYN, zb + 8 * 256) * 64019 a += rf(SYN, zb + 6 * 256) * -9975 a += rf(SYN, zb + 4 * 256) * -45 a += rf(SYN, zb + 2 * 256) * 146 a += rf(SYN, zb) * -5 wf(PCM, (dst + 16 * nch) * 4, a * SCALE) end -- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel @native local function synth(xl: number, dstl: number, nch: number, lins: number) local xr = xl + 576 * (nch - 1) local dstr = dstl + (nch - 1) local zlin = lins + 15 * 64 local zb = zlin * 4 local xlb, xrb = xl * 4, xr * 4 wf(SYN, zb + 60 * 4, rf(GRBUF, xlb + 288 * 4)) wf(SYN, zb + 61 * 4, rf(GRBUF, xrb + 288 * 4)) wf(SYN, zb + 62 * 4, rf(GRBUF, xlb)) wf(SYN, zb + 63 * 4, rf(GRBUF, xrb)) wf(SYN, zb + 124 * 4, rf(GRBUF, xlb + 289 * 4)) wf(SYN, zb + 125 * 4, rf(GRBUF, xrb + 289 * 4)) wf(SYN, zb + 126 * 4, rf(GRBUF, xlb + 4)) wf(SYN, zb + 127 * 4, rf(GRBUF, xrb + 4)) if nch == 2 then synthPair(dstr, nch, lins + 4 * 15 + 1) synthPair(dstr + 32 * nch, nch, lins + 4 * 15 + 64 + 1) end synthPair(dstl, nch, lins + 4 * 15) synthPair(dstl + 32 * nch, nch, lins + 4 * 15 + 64) local w = 1 for i = 14, 0, -1 do local zi = zb + 16 * i local s1 = (18 * (31 - i)) * 4 local s2 = (18 * (1 + i)) * 4 wf(SYN, zi, rf(GRBUF, xlb + s1)) wf(SYN, zi + 4, rf(GRBUF, xrb + s1)) wf(SYN, zi + 8, rf(GRBUF, xlb + s1 + 4)) wf(SYN, zi + 12, rf(GRBUF, xrb + s1 + 4)) wf(SYN, zi + 256, rf(GRBUF, xlb + s2 + 4)) wf(SYN, zi + 260, rf(GRBUF, xrb + s2 + 4)) wf(SYN, zi - 248, rf(GRBUF, xlb + s2)) wf(SYN, zi - 244, rf(GRBUF, xrb + s2)) -- the 8 window steps, even k (a += z w0 - y w1) and odd k (a += y w1 - z w0) in pairs; mono needs lanes 0, 2 local a0, a1, a2, a3, b0, b1, b2, b3 = 0, 0, 0, 0, 0, 0, 0, 0 local vz, vy = zi, zi - 15 * 256 if nch == 2 then for _ = 0, 3 do local w0, w1, w2, w3 = WINT[w], WINT[w + 1], WINT[w + 2], WINT[w + 3] w += 4 local z0, z1, z2, z3 = rf(SYN, vz), rf(SYN, vz + 4), rf(SYN, vz + 8), rf(SYN, vz + 12) local y0, y1, y2, y3 = rf(SYN, vy), rf(SYN, vy + 4), rf(SYN, vy + 8), rf(SYN, vy + 12) b0 += z0 * w1 + y0 * w0 b1 += z1 * w1 + y1 * w0 b2 += z2 * w1 + y2 * w0 b3 += z3 * w1 + y3 * w0 a0 += z0 * w0 - y0 * w1 a1 += z1 * w0 - y1 * w1 a2 += z2 * w0 - y2 * w1 a3 += z3 * w0 - y3 * w1 vz -= 256 vy += 256 z0 = rf(SYN, vz) z1 = rf(SYN, vz + 4) z2 = rf(SYN, vz + 8) z3 = rf(SYN, vz + 12) y0 = rf(SYN, vy) y1 = rf(SYN, vy + 4) y2 = rf(SYN, vy + 8) y3 = rf(SYN, vy + 12) b0 += z0 * w3 + y0 * w2 b1 += z1 * w3 + y1 * w2 b2 += z2 * w3 + y2 * w2 b3 += z3 * w3 + y3 * w2 a0 += y0 * w3 - z0 * w2 a1 += y1 * w3 - z1 * w2 a2 += y2 * w3 - z2 * w2 a3 += y3 * w3 - z3 * w2 vz -= 256 vy += 256 end wf(PCM, (dstr + (15 - i) * 2) * 4, a1 * SCALE) wf(PCM, (dstr + (17 + i) * 2) * 4, b1 * SCALE) wf(PCM, (dstr + (47 - i) * 2) * 4, a3 * SCALE) wf(PCM, (dstr + (49 + i) * 2) * 4, b3 * SCALE) else for _ = 0, 3 do local w0, w1, w2, w3 = WINT[w], WINT[w + 1], WINT[w + 2], WINT[w + 3] w += 4 local z0, z2 = rf(SYN, vz), rf(SYN, vz + 8) local y0, y2 = rf(SYN, vy), rf(SYN, vy + 8) b0 += z0 * w1 + y0 * w0 b2 += z2 * w1 + y2 * w0 a0 += z0 * w0 - y0 * w1 a2 += z2 * w0 - y2 * w1 vz -= 256 vy += 256 z0 = rf(SYN, vz) z2 = rf(SYN, vz + 8) y0 = rf(SYN, vy) y2 = rf(SYN, vy + 8) b0 += z0 * w3 + y0 * w2 b2 += z2 * w3 + y2 * w2 a0 += y0 * w3 - z0 * w2 a2 += y2 * w3 - z2 * w2 vz -= 256 vy += 256 end end wf(PCM, (dstl + (15 - i) * nch) * 4, a0 * SCALE) wf(PCM, (dstl + (17 + i) * nch) * 4, b0 * SCALE) wf(PCM, (dstl + (47 - i) * nch) * 4, a2 * SCALE) wf(PCM, (dstl + (49 + i) * nch) * 4, b2 * SCALE) end end @native local function synthGranule(nbands: number, nch: number, pcm: number) for ch = 0, nch - 1 do dctII(576 * ch, nbands) end bcopy(SYN, 0, QMF, 0, 15 * 64 * 4) for i = 0, nbands - 1, 2 do synth(i, pcm + 32 * nch * i, nch, i * 64) end if nch == 1 then local src = nbands * 64 * 4 for i = 0, 15 * 64 * 4 - 8, 8 do wf(QMF, i, rf(SYN, src + i)) end else bcopy(QMF, 0, SYN, nbands * 64 * 4, 15 * 64 * 4) end end local ALLOC_L1 = { 76, 4, 32 } local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } local totalBands, stereoBands = 0, 0 @native local function l12ReadScaleInfo(h1: number, h2: number, h3: number, kbpsHdr: number) local mode = rshift(h3, 6) local sb = if mode == 3 then 0 elseif mode == 1 then band(rshift(h3, 4), 3) * 4 + 4 else 32 local layer1 = band(h1, 6) == 6 local alloc, nbands if layer1 then alloc, nbands = ALLOC_L1, 32 elseif band(h1, 8) == 0 then alloc, nbands = ALLOC_L2M2, 30 else local srIdx = band(rshift(h2, 2), 3) local kbps = if mode ~= 3 then rshift(kbpsHdr, 1) else kbpsHdr if kbps == 0 then kbps = 192 end alloc, nbands = ALLOC_L2M1, 27 if kbps < 56 then alloc, nbands = ALLOC_L2M1_LOW, if srIdx == 2 then 12 else 8 elseif kbps >= 96 and srIdx ~= 1 then nbands = 30 end end totalBands = nbands stereoBands = min(sb, nbands) local k, baBits, codeOff, ai = 0, 0, 0, 1 for i = 0, nbands - 1 do if i == k then codeOff, baBits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2] ai += 3 end local ba = BITALLOC_CODE[codeOff + getBits(baBits)] wu8(BA, 2 * i, ba) if i < stereoBands then ba = BITALLOC_CODE[codeOff + getBits(baBits)] end wu8(BA, 2 * i + 1, if stereoBands ~= 0 then ba else 0) end for i = 0, 2 * nbands - 1 do wu8(SCFCOD, i, if ru8(BA, i) ~= 0 then (if layer1 then 2 else getBits(2)) else 6) end -- L12_read_scalefactors local so = 0 for i = 0, 2 * nbands - 1 do local s = 0 local ba = ru8(BA, i) local mask = if ba ~= 0 then 4 + band(rshift(19, ru8(SCFCOD, i)), 3) else 0 local m = 4 while m ~= 0 do if band(mask, m) ~= 0 then local b = getBits(6) s = f32(DEQ_L12[ba * 3 - 6 + b % 3] * rshift(lshift(1, 21), b // 3)) end wf(L12SCF, so, s) so += 4 m = rshift(m, 1) end end for i = stereoBands, nbands - 1 do wu8(BA, 2 * i + 1, 0) end end @native local function l12Dequantize(g: number, groupSize: number): number local choff = 576 for j = 0, 3 do local dst = g + groupSize * j for i = 0, 2 * totalBands - 1 do local ba = ru8(BA, i) if ba ~= 0 then if ba < 17 then local half = lshift(1, ba - 1) - 1 for k = 0, groupSize - 1 do wf(GRBUF, (dst + k) * 4, getBits(ba) - half) end else local mod = lshift(2, ba - 17) + 1 local code = getBits(mod + 2 - rshift(mod, 3)) for k = 0, groupSize - 1 do wf(GRBUF, (dst + k) * 4, code % mod - mod // 2) code //= mod end end end dst += choff choff = 18 - choff end end return groupSize * 4 end @native local function l12ApplyScf(scfOff: number) local sb, tb = stereoBands, totalBands bcopy(GRBUF, (576 + sb * 18) * 4, GRBUF, sb * 18 * 4, (tb - sb) * 18 * 4) for i = 0, tb - 1 do local d = i * 72 local s0 = rf(L12SCF, (scfOff + i * 6) * 4) local s1 = rf(L12SCF, (scfOff + i * 6 + 3) * 4) for k = 0, 11 do local p = d + k * 4 wf(GRBUF, p, rf(GRBUF, p) * s0) wf(GRBUF, p + 2304, rf(GRBUF, p + 2304) * s1) end end end local Core = {} Core.MAX_FRAME = MAX_FRAME type State = { overlap: buffer, qmf: buffer, reserv: buffer, reservLen: number, needReset: boolean, } @native function Core.newState(): State return { overlap = bcreate(2 * 9 * 32 * 4), qmf = bcreate(15 * 2 * 32 * 4), reserv = bcreate(MAX_BITRESERVOIR_BYTES + 8), reservLen = 0, needReset = false, } end -- memset(dec, 0): what minimp3 does whenever it has to re-sync @native function Core.reset(st: State) bfill(st.overlap, 0, 0) bfill(st.qmf, 0, 0) st.reservLen = 0 st.needReset = false end Core.lastChannels = 0 @native function Core.upmix(pcm: buffer, n: number) if buffer.len(pcm) < n * 8 then return end for i = n - 1, 0, -1 do local v = rf(pcm, i * 4) wf(pcm, i * 8, v) wf(pcm, i * 8 + 4, v) end end @native function Core.decodeFrame(st: State, b: buffer, off: number, size: number, pcm: buffer): number if size < 4 or size > MAX_FRAME or off < 0 or off + size > buffer.len(b) then st.needReset = true return 0 end if st.needReset then Core.reset(st) end bcopy(FRAME, 0, b, off, size) bfill(FRAME, size, 0, 8) OVL, QMF, PCM = st.overlap, st.qmf, pcm local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) local nch = if band(h3, 0xC0) == 0xC0 then 1 else 2 Core.lastChannels = nch local layer = 4 - band(rshift(h1, 1), 3) local spf = if band(h1, 6) == 6 then 384 elseif band(h1, 14) == 2 then 576 else 1152 if buffer.len(pcm) < spf * nch * 4 then return 0 end bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 if band(h1, 1) == 0 then getBits(16) -- CRC end if layer == 3 then local mdb = readSideInfo(h1, h2, h3) if mdb < 0 or bsPos > bsLimit then st.needReset = true return 0 end -- L3_restore_reservoir local frameBytes = (bsLimit - bsPos) // 8 local reserv = st.reservLen local have = min(reserv, mdb) if have > 0 then bcopy(MAIN, 0, st.reserv, max(0, reserv - mdb), have) end bcopy(MAIN, have, FRAME, bsPos // 8, frameBytes) bfill(MAIN, have + frameBytes, 0, 8) local success = reserv >= mdb bsBuf, bsPos, bsLimit = MAIN, 0, (have + frameBytes) * 8 if success then local ngr = if band(h1, 8) ~= 0 then 2 else 1 local p = 0 for igr = 0, ngr - 1 do bfill(GRBUF, 0, 0) l3Decode(h1, h2, h3, igr * nch, nch) synthGranule(18, nch, p) p += 576 * nch end end -- L3_save_reservoir local pos = (bsPos + 7) // 8 local remains = bsLimit // 8 - pos if remains > MAX_BITRESERVOIR_BYTES then pos += remains - MAX_BITRESERVOIR_BYTES remains = MAX_BITRESERVOIR_BYTES end if remains > 0 and pos >= 0 then bcopy(st.reserv, 0, MAIN, pos, remains) end st.reservLen = max(0, remains) bsBuf = FRAME return if success then spf else 0 end local kbps = 2 * HALFRATE[(if band(h1, 8) ~= 0 then 45 else 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)] l12ReadScaleInfo(h1, h2, h3, kbps) bfill(GRBUF, 0, 0) local i = 0 local p = 0 local group = bor(layer, 1) for igr = 0, 2 do i += l12Dequantize(i, group) if i == 12 then i = 0 l12ApplyScf(igr) synthGranule(12, nch, p) bfill(GRBUF, 0, 0) p += 384 * nch end if bsPos > bsLimit then st.needReset = true return 0 end end return spf end @native function Core.probeL3(b: buffer, off: number, size: number): (number, number, number) local n = min(size, 64) if size < 4 or off + n > buffer.len(b) then return -1, 0, 0 end bcopy(FRAME, 0, b, off, n) local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 if band(h1, 1) == 0 then getBits(16) end local mdb = readSideInfo(h1, h2, h3) if mdb < 0 or bsPos > bsLimit then return -1, 0, 0 end local ngr = (if band(h3, 0xC0) == 0xC0 then 1 else 2) * (if band(h1, 8) ~= 0 then 2 else 1) local sum = 0 for gr = 0, ngr - 1 do sum += GR_P23[gr] end return mdb, sum, (bsLimit - bsPos) // 8 end -- Layer I / II: minimp3 drops a frame that needs more bits than it has @native function Core.probeL12(b: buffer, off: number, size: number): boolean if size < 4 or size > MAX_FRAME or off + size > buffer.len(b) then return false end bcopy(FRAME, 0, b, off, size) bfill(FRAME, size, 0, 8) local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 if band(h1, 1) == 0 then getBits(16) end local layer = 4 - band(rshift(h1, 1), 3) local kbps = 2 * HALFRATE[(if band(h1, 8) ~= 0 then 45 else 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)] l12ReadScaleInfo(h1, h2, h3, kbps) -- the samples: 3 calls of l12Dequantize, each 4 groups of (layer | 1) samples per allocated band local group = bor(layer, 1) local bits = 0 for i = 0, 2 * totalBands - 1 do local ba = ru8(BA, i) if ba ~= 0 then if ba < 17 then bits += ba * group else local mod = lshift(2, ba - 17) + 1 bits += mod + 2 - rshift(mod, 3) end end end return bsPos + 12 * bits <= bsLimit end -- mp3dec_check_vbrtag on the frame b[off, off + size): 0 = no tag, -1 = a Xing / Info tag without a frame -- count, 1 = tag; then frames, encoder delay + 529, padding - 529 (both 0 without a LAME extension) @native function Core.vbrTag(b: buffer, off: number, size: number): (number, number, number, number) if size < 12 or size > MAX_FRAME or off + size > buffer.len(b) then return 0, 0, 0, 0 end bcopy(FRAME, 0, b, off, size) bfill(FRAME, size, 0, 8) local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 if band(h1, 1) == 0 then getBits(16) end if readSideInfo(h1, h2, h3) < 0 then return 0, 0, 0, 0 end local t = bsPos // 8 if t > size or size - t < 8 then return 0, 0, 0, 0 end local tag = buffer.readstring(FRAME, t, 4) if tag ~= "Xing" and tag ~= "Info" then return 0, 0, 0, 0 end local flags = ru8(FRAME, t + 7) if band(flags, 1) == 0 then return -1, 0, 0, 0 end t += 8 if size - t < 4 then return 0, 0, 0, 0 end local frames = bswap(ru32(FRAME, t)) t += 4 if band(flags, 2) ~= 0 then if size - t < 4 then return 0, 0, 0, 0 end t += 4 end if band(flags, 4) ~= 0 then if size - t < 100 then return 0, 0, 0, 0 end t += 100 end if band(flags, 8) ~= 0 then if size - t < 4 then return 0, 0, 0, 0 end t += 4 end if size - t < 1 then return 0, 0, 0, 0 end local delay, padding = 0, 0 if ru8(FRAME, t) ~= 0 then if size - t <= 35 then return 0, 0, 0, 0 end t += 21 local t0, t1, t2 = ru8(FRAME, t), ru8(FRAME, t + 1), ru8(FRAME, t + 2) delay = bor(lshift(t0, 4), rshift(t1, 4)) + 529 padding = bor(lshift(band(t1, 15), 8), t2) - 529 end return 1, frames, delay, padding end return Core end __FILES["codecs/audio/Mpa/EncTables"] = function() -- codecs/audio/Mpa/EncTables: the synthesis window D and the layer III Huffman trees of ISO/IEC 11172-3, from PDMP3 -- (public domain / unlicense, Krister Lagerstrom and contributors: licenses/PDMP3-UNLICENSE.txt). Tree entries with a -- high byte are nodes (high byte: left offset, low byte: right offset), else leaves (x << 4 | y; count1: v w x y bits). local E = {} E.D = { 0.000000000, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000030518, -0.000030518, -0.000030518, -0.000030518, -0.000045776, -0.000045776, -0.000061035, -0.000061035, -0.000076294, -0.000076294, -0.000091553, -0.000106812, -0.000106812, -0.000122070, -0.000137329, -0.000152588, -0.000167847, -0.000198364, -0.000213623, -0.000244141, -0.000259399, -0.000289917, -0.000320435, -0.000366211, -0.000396729, -0.000442505, -0.000473022, -0.000534058, -0.000579834, -0.000625610, -0.000686646, -0.000747681, -0.000808716, -0.000885010, -0.000961304, -0.001037598, -0.001113892, -0.001205444, -0.001296997, -0.001388550, -0.001480103, -0.001586914, -0.001693726, -0.001785278, -0.001907349, -0.002014160, -0.002120972, -0.002243042, -0.002349854, -0.002456665, -0.002578735, -0.002685547, -0.002792358, -0.002899170, -0.002990723, -0.003082275, -0.003173828, 0.003250122, 0.003326416, 0.003387451, 0.003433228, 0.003463745, 0.003479004, 0.003479004, 0.003463745, 0.003417969, 0.003372192, 0.003280640, 0.003173828, 0.003051758, 0.002883911, 0.002700806, 0.002487183, 0.002227783, 0.001937866, 0.001617432, 0.001266479, 0.000869751, 0.000442505, -0.000030518, -0.000549316, -0.001098633, -0.001693726, -0.002334595, -0.003005981, -0.003723145, -0.004486084, -0.005294800, -0.006118774, -0.007003784, -0.007919312, -0.008865356, -0.009841919, -0.010848999, -0.011886597, -0.012939453, -0.014022827, -0.015121460, -0.016235352, -0.017349243, -0.018463135, -0.019577026, -0.020690918, -0.021789551, -0.022857666, -0.023910522, -0.024932861, -0.025909424, -0.026840210, -0.027725220, -0.028533936, -0.029281616, -0.029937744, -0.030532837, -0.031005859, -0.031387329, -0.031661987, -0.031814575, -0.031845093, -0.031738281, -0.031478882, 0.031082153, 0.030517578, 0.029785156, 0.028884888, 0.027801514, 0.026535034, 0.025085449, 0.023422241, 0.021575928, 0.019531250, 0.017257690, 0.014801025, 0.012115479, 0.009231567, 0.006134033, 0.002822876, -0.000686646, -0.004394531, -0.008316040, -0.012420654, -0.016708374, -0.021179199, -0.025817871, -0.030609131, -0.035552979, -0.040634155, -0.045837402, -0.051132202, -0.056533813, -0.061996460, -0.067520142, -0.073059082, -0.078628540, -0.084182739, -0.089706421, -0.095169067, -0.100540161, -0.105819702, -0.110946655, -0.115921021, -0.120697021, -0.125259399, -0.129562378, -0.133590698, -0.137298584, -0.140670776, -0.143676758, -0.146255493, -0.148422241, -0.150115967, -0.151306152, -0.151962280, -0.152069092, -0.151596069, -0.150497437, -0.148773193, -0.146362305, -0.143264771, -0.139450073, -0.134887695, -0.129577637, -0.123474121, -0.116577148, -0.108856201, 0.100311279, 0.090927124, 0.080688477, 0.069595337, 0.057617188, 0.044784546, 0.031082153, 0.016510010, 0.001068115, -0.015228271, -0.032379150, -0.050354004, -0.069168091, -0.088775635, -0.109161377, -0.130310059, -0.152206421, -0.174789429, -0.198059082, -0.221984863, -0.246505737, -0.271591187, -0.297210693, -0.323318481, -0.349868774, -0.376800537, -0.404083252, -0.431655884, -0.459472656, -0.487472534, -0.515609741, -0.543823242, -0.572036743, -0.600219727, -0.628295898, -0.656219482, -0.683914185, -0.711318970, -0.738372803, -0.765029907, -0.791213989, -0.816864014, -0.841949463, -0.866363525, -0.890090942, -0.913055420, -0.935195923, -0.956481934, -0.976852417, -0.996246338, -1.014617920, -1.031936646, -1.048156738, -1.063217163, -1.077117920, -1.089782715, -1.101211548, -1.111373901, -1.120223999, -1.127746582, -1.133926392, -1.138763428, -1.142211914, -1.144287109, 1.144989014, 1.144287109, 1.142211914, 1.138763428, 1.133926392, 1.127746582, 1.120223999, 1.111373901, 1.101211548, 1.089782715, 1.077117920, 1.063217163, 1.048156738, 1.031936646, 1.014617920, 0.996246338, 0.976852417, 0.956481934, 0.935195923, 0.913055420, 0.890090942, 0.866363525, 0.841949463, 0.816864014, 0.791213989, 0.765029907, 0.738372803, 0.711318970, 0.683914185, 0.656219482, 0.628295898, 0.600219727, 0.572036743, 0.543823242, 0.515609741, 0.487472534, 0.459472656, 0.431655884, 0.404083252, 0.376800537, 0.349868774, 0.323318481, 0.297210693, 0.271591187, 0.246505737, 0.221984863, 0.198059082, 0.174789429, 0.152206421, 0.130310059, 0.109161377, 0.088775635, 0.069168091, 0.050354004, 0.032379150, 0.015228271, -0.001068115, -0.016510010, -0.031082153, -0.044784546, -0.057617188, -0.069595337, -0.080688477, -0.090927124, 0.100311279, 0.108856201, 0.116577148, 0.123474121, 0.129577637, 0.134887695, 0.139450073, 0.143264771, 0.146362305, 0.148773193, 0.150497437, 0.151596069, 0.152069092, 0.151962280, 0.151306152, 0.150115967, 0.148422241, 0.146255493, 0.143676758, 0.140670776, 0.137298584, 0.133590698, 0.129562378, 0.125259399, 0.120697021, 0.115921021, 0.110946655, 0.105819702, 0.100540161, 0.095169067, 0.089706421, 0.084182739, 0.078628540, 0.073059082, 0.067520142, 0.061996460, 0.056533813, 0.051132202, 0.045837402, 0.040634155, 0.035552979, 0.030609131, 0.025817871, 0.021179199, 0.016708374, 0.012420654, 0.008316040, 0.004394531, 0.000686646, -0.002822876, -0.006134033, -0.009231567, -0.012115479, -0.014801025, -0.017257690, -0.019531250, -0.021575928, -0.023422241, -0.025085449, -0.026535034, -0.027801514, -0.028884888, -0.029785156, -0.030517578, 0.031082153, 0.031478882, 0.031738281, 0.031845093, 0.031814575, 0.031661987, 0.031387329, 0.031005859, 0.030532837, 0.029937744, 0.029281616, 0.028533936, 0.027725220, 0.026840210, 0.025909424, 0.024932861, 0.023910522, 0.022857666, 0.021789551, 0.020690918, 0.019577026, 0.018463135, 0.017349243, 0.016235352, 0.015121460, 0.014022827, 0.012939453, 0.011886597, 0.010848999, 0.009841919, 0.008865356, 0.007919312, 0.007003784, 0.006118774, 0.005294800, 0.004486084, 0.003723145, 0.003005981, 0.002334595, 0.001693726, 0.001098633, 0.000549316, 0.000030518, -0.000442505, -0.000869751, -0.001266479, -0.001617432, -0.001937866, -0.002227783, -0.002487183, -0.002700806, -0.002883911, -0.003051758, -0.003173828, -0.003280640, -0.003372192, -0.003417969, -0.003463745, -0.003479004, -0.003479004, -0.003463745, -0.003433228, -0.003387451, -0.003326416, 0.003250122, 0.003173828, 0.003082275, 0.002990723, 0.002899170, 0.002792358, 0.002685547, 0.002578735, 0.002456665, 0.002349854, 0.002243042, 0.002120972, 0.002014160, 0.001907349, 0.001785278, 0.001693726, 0.001586914, 0.001480103, 0.001388550, 0.001296997, 0.001205444, 0.001113892, 0.001037598, 0.000961304, 0.000885010, 0.000808716, 0.000747681, 0.000686646, 0.000625610, 0.000579834, 0.000534058, 0.000473022, 0.000442505, 0.000396729, 0.000366211, 0.000320435, 0.000289917, 0.000259399, 0.000244141, 0.000213623, 0.000198364, 0.000167847, 0.000152588, 0.000137329, 0.000122070, 0.000106812, 0.000106812, 0.000091553, 0.000076294, 0.000076294, 0.000061035, 0.000061035, 0.000045776, 0.000045776, 0.000030518, 0.000030518, 0.000030518, 0.000030518, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, } E.LINBITS = { [0] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, 5, 6, 7, 8, 9, 11, 13, 0, 0 } -- trees by table number (tables 16..23 share 16's tree, 24..31 share 24's) E.TREES = { [1] = { 0x0201, 0x0000, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, }, [2] = { 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, 0x0022, }, [3] = { 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0011, 0x0201, 0x0010, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, 0x0022, }, [5] = { 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0013, 0x0201, 0x0031, 0x0201, 0x0032, 0x0201, 0x0023, 0x0033, }, [6] = { 0x0601, 0x0401, 0x0201, 0x0000, 0x0010, 0x0011, 0x0601, 0x0201, 0x0001, 0x0201, 0x0020, 0x0021, 0x0601, 0x0201, 0x0012, 0x0201, 0x0002, 0x0022, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0030, 0x0032, 0x0201, 0x0023, 0x0201, 0x0003, 0x0033, }, [7] = { 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, 0x1201, 0x0601, 0x0201, 0x0012, 0x0201, 0x0022, 0x0030, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, 0x0004, 0x0a01, 0x0401, 0x0201, 0x0040, 0x0041, 0x0201, 0x0014, 0x0201, 0x0042, 0x0024, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0033, 0x0043, 0x0050, 0x0401, 0x0201, 0x0034, 0x0005, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, 0x0035, 0x0401, 0x0201, 0x0053, 0x0054, 0x0201, 0x0045, 0x0055, }, [8] = { 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0021, 0x0012, 0x0e01, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0022, 0x0401, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0032, 0x0023, 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0201, 0x0014, 0x0042, 0x0c01, 0x0601, 0x0201, 0x0024, 0x0201, 0x0033, 0x0050, 0x0401, 0x0201, 0x0043, 0x0034, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0005, 0x0052, 0x0601, 0x0201, 0x0025, 0x0201, 0x0044, 0x0035, 0x0201, 0x0053, 0x0201, 0x0045, 0x0201, 0x0054, 0x0055, }, [9] = { 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0a01, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, 0x0022, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0030, 0x0003, 0x0031, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0c01, 0x0401, 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0040, 0x0033, 0x0201, 0x0042, 0x0024, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0050, 0x0043, 0x0201, 0x0034, 0x0051, 0x0801, 0x0401, 0x0201, 0x0015, 0x0052, 0x0201, 0x0025, 0x0044, 0x0601, 0x0401, 0x0201, 0x0005, 0x0054, 0x0053, 0x0201, 0x0035, 0x0201, 0x0045, 0x0055, }, [10] = { 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0a01, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, 0x1c01, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0031, 0x0013, 0x0801, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, 0x0040, 0x0401, 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0004, 0x0033, 0x0201, 0x0042, 0x0024, 0x1c01, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0050, 0x0005, 0x0060, 0x0201, 0x0061, 0x0016, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0043, 0x0034, 0x0051, 0x0201, 0x0015, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0026, 0x0036, 0x0071, 0x1401, 0x0801, 0x0201, 0x0017, 0x0401, 0x0201, 0x0044, 0x0053, 0x0006, 0x0601, 0x0401, 0x0201, 0x0035, 0x0045, 0x0062, 0x0201, 0x0070, 0x0201, 0x0007, 0x0064, 0x0e01, 0x0401, 0x0201, 0x0072, 0x0027, 0x0601, 0x0201, 0x0063, 0x0201, 0x0054, 0x0055, 0x0201, 0x0046, 0x0073, 0x0801, 0x0401, 0x0201, 0x0037, 0x0065, 0x0201, 0x0056, 0x0074, 0x0601, 0x0201, 0x0047, 0x0201, 0x0066, 0x0075, 0x0401, 0x0201, 0x0057, 0x0076, 0x0201, 0x0067, 0x0077, }, [11] = { 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0012, 0x1801, 0x0801, 0x0201, 0x0021, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, 0x0401, 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0014, 0x1e01, 0x1001, 0x0a01, 0x0401, 0x0201, 0x0042, 0x0024, 0x0401, 0x0201, 0x0033, 0x0043, 0x0050, 0x0401, 0x0201, 0x0034, 0x0051, 0x0061, 0x0601, 0x0201, 0x0016, 0x0201, 0x0006, 0x0026, 0x0201, 0x0062, 0x0201, 0x0015, 0x0201, 0x0005, 0x0052, 0x1001, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0025, 0x0044, 0x0060, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0070, 0x0017, 0x0071, 0x1001, 0x0601, 0x0401, 0x0201, 0x0007, 0x0064, 0x0072, 0x0201, 0x0027, 0x0401, 0x0201, 0x0053, 0x0035, 0x0201, 0x0054, 0x0045, 0x0a01, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, 0x0201, 0x0065, 0x0056, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0055, 0x0057, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0076, 0x0201, 0x0067, 0x0077, }, [12] = { 0x0c01, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0201, 0x0000, 0x0201, 0x0020, 0x0002, 0x1001, 0x0401, 0x0201, 0x0021, 0x0012, 0x0401, 0x0201, 0x0022, 0x0031, 0x0201, 0x0013, 0x0201, 0x0030, 0x0201, 0x0003, 0x0040, 0x1a01, 0x0801, 0x0401, 0x0201, 0x0032, 0x0023, 0x0201, 0x0041, 0x0033, 0x0a01, 0x0401, 0x0201, 0x0014, 0x0042, 0x0201, 0x0024, 0x0201, 0x0004, 0x0050, 0x0401, 0x0201, 0x0043, 0x0034, 0x0201, 0x0051, 0x0015, 0x1c01, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0052, 0x0025, 0x0201, 0x0053, 0x0035, 0x0401, 0x0201, 0x0060, 0x0016, 0x0061, 0x0401, 0x0201, 0x0062, 0x0026, 0x0601, 0x0401, 0x0201, 0x0005, 0x0006, 0x0044, 0x0201, 0x0054, 0x0045, 0x1201, 0x0a01, 0x0401, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0070, 0x0007, 0x0071, 0x0401, 0x0201, 0x0017, 0x0064, 0x0201, 0x0046, 0x0072, 0x0a01, 0x0601, 0x0201, 0x0027, 0x0201, 0x0055, 0x0073, 0x0201, 0x0037, 0x0056, 0x0801, 0x0401, 0x0201, 0x0065, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0076, 0x0201, 0x0067, 0x0077, }, [13] = { 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x1c01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x4601, 0x1c01, 0x0e01, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, 0x0050, 0x0201, 0x0043, 0x0034, 0x0401, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0005, 0x0052, 0x0201, 0x0025, 0x0201, 0x0044, 0x0053, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0060, 0x0006, 0x0201, 0x0061, 0x0016, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x1001, 0x0801, 0x0401, 0x0201, 0x0035, 0x0062, 0x0201, 0x0026, 0x0054, 0x0401, 0x0201, 0x0045, 0x0063, 0x0201, 0x0036, 0x0070, 0x0601, 0x0401, 0x0201, 0x0007, 0x0055, 0x0071, 0x0201, 0x0017, 0x0201, 0x0027, 0x0037, 0x4801, 0x1801, 0x0c01, 0x0401, 0x0201, 0x0018, 0x0082, 0x0201, 0x0028, 0x0401, 0x0201, 0x0064, 0x0046, 0x0072, 0x0801, 0x0401, 0x0201, 0x0084, 0x0048, 0x0201, 0x0090, 0x0009, 0x0201, 0x0091, 0x0019, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0073, 0x0065, 0x0201, 0x0056, 0x0074, 0x0401, 0x0201, 0x0047, 0x0066, 0x0083, 0x0601, 0x0201, 0x0038, 0x0201, 0x0075, 0x0057, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0067, 0x0085, 0x0201, 0x0058, 0x0039, 0x0201, 0x0093, 0x0201, 0x0049, 0x0086, 0x0601, 0x0201, 0x00a0, 0x0201, 0x0068, 0x000a, 0x0201, 0x00a1, 0x001a, 0x4401, 0x1801, 0x0c01, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0401, 0x0201, 0x0095, 0x0059, 0x0201, 0x00a3, 0x003a, 0x0801, 0x0401, 0x0201, 0x004a, 0x0096, 0x0201, 0x00b0, 0x000b, 0x0201, 0x00b1, 0x001b, 0x1401, 0x0801, 0x0201, 0x00b2, 0x0401, 0x0201, 0x0076, 0x0077, 0x0094, 0x0601, 0x0401, 0x0201, 0x0087, 0x0078, 0x00a4, 0x0401, 0x0201, 0x0069, 0x00a5, 0x002b, 0x0c01, 0x0601, 0x0401, 0x0201, 0x005a, 0x0088, 0x00b3, 0x0201, 0x003b, 0x0201, 0x0079, 0x00a6, 0x0601, 0x0401, 0x0201, 0x006a, 0x00b4, 0x00c0, 0x0401, 0x0201, 0x000c, 0x0098, 0x00c1, 0x3c01, 0x1601, 0x0a01, 0x0601, 0x0201, 0x001c, 0x0201, 0x0089, 0x00b5, 0x0201, 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x003c, 0x0401, 0x0201, 0x00b6, 0x006b, 0x0201, 0x00c4, 0x004c, 0x1001, 0x0801, 0x0401, 0x0201, 0x00a8, 0x008a, 0x0201, 0x00d0, 0x000d, 0x0201, 0x00d1, 0x0201, 0x004b, 0x0201, 0x0097, 0x00a7, 0x0c01, 0x0601, 0x0201, 0x00c3, 0x0201, 0x007a, 0x0099, 0x0401, 0x0201, 0x00c5, 0x005c, 0x00b7, 0x0401, 0x0201, 0x001d, 0x00d2, 0x0201, 0x002d, 0x0201, 0x007b, 0x00d3, 0x3401, 0x1c01, 0x0c01, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e0, 0x0a01, 0x0401, 0x0201, 0x00e1, 0x001e, 0x0401, 0x0201, 0x000e, 0x002e, 0x00e2, 0x0801, 0x0401, 0x0201, 0x00e3, 0x006d, 0x0201, 0x008c, 0x00e4, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x00f0, 0x2601, 0x1001, 0x0401, 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00aa, 0x009b, 0x00b9, 0x0201, 0x003e, 0x0201, 0x00d6, 0x00c8, 0x0c01, 0x0601, 0x0201, 0x004e, 0x0201, 0x00d7, 0x007d, 0x0201, 0x00ab, 0x0201, 0x005e, 0x00c9, 0x0601, 0x0201, 0x000f, 0x0201, 0x009c, 0x006e, 0x0201, 0x00f2, 0x002f, 0x2001, 0x1001, 0x0601, 0x0401, 0x0201, 0x00d8, 0x008d, 0x003f, 0x0601, 0x0201, 0x00f3, 0x0201, 0x00e6, 0x00ca, 0x0201, 0x00f4, 0x004f, 0x0801, 0x0401, 0x0201, 0x00bb, 0x00ac, 0x0201, 0x00e7, 0x00f5, 0x0401, 0x0201, 0x00d9, 0x009d, 0x0201, 0x005f, 0x00e8, 0x1e01, 0x0c01, 0x0601, 0x0201, 0x006f, 0x0201, 0x00f6, 0x00cb, 0x0401, 0x0201, 0x00bc, 0x00ad, 0x00da, 0x0801, 0x0201, 0x00f7, 0x0401, 0x0201, 0x007e, 0x007f, 0x008e, 0x0601, 0x0401, 0x0201, 0x009e, 0x00ae, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00db, 0x00bd, 0x0201, 0x00ea, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00eb, 0x0201, 0x00be, 0x0201, 0x00cd, 0x00fa, 0x0e01, 0x0401, 0x0201, 0x00dd, 0x00ec, 0x0601, 0x0401, 0x0201, 0x00e9, 0x00af, 0x00dc, 0x0201, 0x00ce, 0x00fb, 0x0801, 0x0401, 0x0201, 0x00bf, 0x00de, 0x0201, 0x00cf, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00ef, 0x0201, 0x00ff, 0x0201, 0x00ed, 0x0201, 0x00fd, 0x0201, 0x00fc, 0x00fe, }, [15] = { 0x1001, 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, 0x3201, 0x1001, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0003, 0x0040, 0x0201, 0x0032, 0x0023, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0014, 0x0041, 0x0401, 0x0201, 0x0033, 0x0042, 0x0201, 0x0024, 0x0043, 0x0a01, 0x0601, 0x0201, 0x0034, 0x0201, 0x0050, 0x0005, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, 0x0053, 0x0061, 0x5a01, 0x2401, 0x1201, 0x0a01, 0x0601, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0201, 0x0016, 0x0062, 0x0401, 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0a01, 0x0601, 0x0201, 0x0036, 0x0201, 0x0070, 0x0007, 0x0201, 0x0071, 0x0055, 0x0401, 0x0201, 0x0017, 0x0064, 0x0201, 0x0072, 0x0027, 0x1801, 0x1001, 0x0801, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, 0x0065, 0x0401, 0x0201, 0x0056, 0x0080, 0x0201, 0x0008, 0x0074, 0x0401, 0x0201, 0x0081, 0x0018, 0x0201, 0x0082, 0x0028, 0x1001, 0x0801, 0x0401, 0x0201, 0x0047, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, 0x0601, 0x0401, 0x0201, 0x0090, 0x0019, 0x0091, 0x0401, 0x0201, 0x0092, 0x0076, 0x0201, 0x0067, 0x0029, 0x5c01, 0x2401, 0x1201, 0x0a01, 0x0401, 0x0201, 0x0085, 0x0058, 0x0401, 0x0201, 0x0009, 0x0077, 0x0093, 0x0401, 0x0201, 0x0039, 0x0094, 0x0201, 0x0049, 0x0086, 0x0a01, 0x0601, 0x0201, 0x0068, 0x0201, 0x00a0, 0x000a, 0x0201, 0x00a1, 0x001a, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, 0x0059, 0x1a01, 0x0e01, 0x0601, 0x0201, 0x00a3, 0x0201, 0x003a, 0x0087, 0x0401, 0x0201, 0x0078, 0x00a4, 0x0201, 0x004a, 0x0096, 0x0601, 0x0401, 0x0201, 0x0069, 0x00b0, 0x00b1, 0x0401, 0x0201, 0x001b, 0x00a5, 0x00b2, 0x0e01, 0x0801, 0x0401, 0x0201, 0x005a, 0x002b, 0x0201, 0x0088, 0x0097, 0x0201, 0x00b3, 0x0201, 0x0079, 0x003b, 0x0801, 0x0401, 0x0201, 0x006a, 0x00b4, 0x0201, 0x004b, 0x00c1, 0x0401, 0x0201, 0x0098, 0x0089, 0x0201, 0x001c, 0x00b5, 0x5001, 0x2201, 0x1001, 0x0601, 0x0401, 0x0201, 0x005b, 0x002c, 0x00c2, 0x0601, 0x0401, 0x0201, 0x000b, 0x00c0, 0x00a6, 0x0201, 0x00a7, 0x007a, 0x0a01, 0x0401, 0x0201, 0x00c3, 0x003c, 0x0401, 0x0201, 0x000c, 0x0099, 0x00b6, 0x0401, 0x0201, 0x006b, 0x00c4, 0x0201, 0x004c, 0x00a8, 0x1401, 0x0a01, 0x0401, 0x0201, 0x008a, 0x00c5, 0x0401, 0x0201, 0x00d0, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x0201, 0x000d, 0x002d, 0x0c01, 0x0401, 0x0201, 0x00d2, 0x00d3, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x00a9, 0x0601, 0x0401, 0x0201, 0x009a, 0x00b8, 0x00d4, 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x4401, 0x2201, 0x1201, 0x0a01, 0x0401, 0x0201, 0x00d5, 0x005d, 0x0401, 0x0201, 0x00e0, 0x000e, 0x00e1, 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x002e, 0x0801, 0x0401, 0x0201, 0x00b9, 0x009b, 0x0201, 0x00e3, 0x00d6, 0x0401, 0x0201, 0x006d, 0x003e, 0x0201, 0x00c8, 0x008c, 0x1001, 0x0801, 0x0401, 0x0201, 0x00e4, 0x004e, 0x0201, 0x00d7, 0x007d, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x0201, 0x00ab, 0x005e, 0x0801, 0x0401, 0x0201, 0x00c9, 0x009c, 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00f0, 0x006e, 0x00f2, 0x0201, 0x002f, 0x00e6, 0x2601, 0x1201, 0x0801, 0x0401, 0x0201, 0x00d8, 0x00f3, 0x0201, 0x003f, 0x00f4, 0x0601, 0x0201, 0x004f, 0x0201, 0x008d, 0x00d9, 0x0201, 0x00bb, 0x00ca, 0x0801, 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00f5, 0x0801, 0x0401, 0x0201, 0x009d, 0x005f, 0x0201, 0x00e8, 0x008e, 0x0201, 0x00f6, 0x00cb, 0x2201, 0x1201, 0x0a01, 0x0601, 0x0401, 0x0201, 0x000f, 0x00ae, 0x006f, 0x0201, 0x00bc, 0x00da, 0x0401, 0x0201, 0x00ad, 0x00f7, 0x0201, 0x007f, 0x00e9, 0x0801, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x0401, 0x0201, 0x00db, 0x00bd, 0x0201, 0x00ea, 0x00f9, 0x1001, 0x0801, 0x0401, 0x0201, 0x009f, 0x00dc, 0x0201, 0x00cd, 0x00eb, 0x0401, 0x0201, 0x00be, 0x00fa, 0x0201, 0x00af, 0x00dd, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00ec, 0x00ce, 0x00fb, 0x0401, 0x0201, 0x00bf, 0x00ed, 0x0201, 0x00de, 0x00fc, 0x0601, 0x0401, 0x0201, 0x00cf, 0x00fd, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00fe, 0x0201, 0x00ef, 0x00ff, }, [16] = { 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x2a01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, 0x0a01, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0a01, 0x0401, 0x0201, 0x0032, 0x0023, 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, 0x0050, 0x0201, 0x0043, 0x0034, 0x8a01, 0x2801, 0x1001, 0x0601, 0x0401, 0x0201, 0x0005, 0x0015, 0x0051, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, 0x0035, 0x0053, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0060, 0x0006, 0x0061, 0x0201, 0x0016, 0x0062, 0x0801, 0x0401, 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0401, 0x0201, 0x0036, 0x0070, 0x0071, 0x2801, 0x1201, 0x0801, 0x0201, 0x0017, 0x0201, 0x0007, 0x0201, 0x0055, 0x0064, 0x0401, 0x0201, 0x0072, 0x0027, 0x0401, 0x0201, 0x0046, 0x0065, 0x0073, 0x0a01, 0x0601, 0x0201, 0x0037, 0x0201, 0x0056, 0x0008, 0x0201, 0x0080, 0x0081, 0x0601, 0x0201, 0x0018, 0x0201, 0x0074, 0x0047, 0x0201, 0x0082, 0x0201, 0x0028, 0x0066, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0083, 0x0038, 0x0201, 0x0075, 0x0084, 0x0401, 0x0201, 0x0048, 0x0090, 0x0091, 0x0601, 0x0201, 0x0019, 0x0201, 0x0009, 0x0076, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0085, 0x0058, 0x0201, 0x0093, 0x0039, 0x0401, 0x0201, 0x00a0, 0x000a, 0x001a, 0x0801, 0x0201, 0x00a2, 0x0201, 0x0067, 0x0201, 0x0057, 0x0049, 0x0601, 0x0201, 0x0094, 0x0201, 0x0077, 0x0086, 0x0201, 0x00a1, 0x0201, 0x0068, 0x0095, 0xdc01, 0x7e01, 0x3201, 0x1a01, 0x0c01, 0x0601, 0x0201, 0x002a, 0x0201, 0x0059, 0x003a, 0x0201, 0x00a3, 0x0201, 0x0087, 0x0078, 0x0801, 0x0401, 0x0201, 0x00a4, 0x004a, 0x0201, 0x0096, 0x0069, 0x0401, 0x0201, 0x00b0, 0x000b, 0x00b1, 0x0a01, 0x0401, 0x0201, 0x001b, 0x00b2, 0x0201, 0x002b, 0x0201, 0x00a5, 0x005a, 0x0601, 0x0201, 0x00b3, 0x0201, 0x00a6, 0x006a, 0x0401, 0x0201, 0x00b4, 0x004b, 0x0201, 0x000c, 0x00c1, 0x1e01, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00b5, 0x00c2, 0x002c, 0x0401, 0x0201, 0x00a7, 0x00c3, 0x0201, 0x006b, 0x00c4, 0x0801, 0x0201, 0x001d, 0x0401, 0x0201, 0x0088, 0x0097, 0x003b, 0x0401, 0x0201, 0x00d1, 0x00d2, 0x0201, 0x002d, 0x00d3, 0x1201, 0x0601, 0x0401, 0x0201, 0x001e, 0x002e, 0x00e2, 0x0601, 0x0401, 0x0201, 0x0079, 0x0098, 0x00c0, 0x0201, 0x001c, 0x0201, 0x0089, 0x005b, 0x0e01, 0x0601, 0x0201, 0x003c, 0x0201, 0x007a, 0x00b6, 0x0401, 0x0201, 0x004c, 0x0099, 0x0201, 0x00a8, 0x008a, 0x0601, 0x0201, 0x000d, 0x0201, 0x00c5, 0x005c, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x009a, 0x5801, 0x5601, 0x2401, 0x1001, 0x0801, 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x0401, 0x0201, 0x00d5, 0x005d, 0x0201, 0x00e0, 0x000e, 0x0801, 0x0201, 0x00e3, 0x0401, 0x0201, 0x00d0, 0x00b7, 0x007b, 0x0601, 0x0401, 0x0201, 0x00a9, 0x00b8, 0x00d4, 0x0201, 0x00e1, 0x0201, 0x00aa, 0x00b9, 0x1801, 0x0a01, 0x0601, 0x0401, 0x0201, 0x009b, 0x00d6, 0x006d, 0x0201, 0x003e, 0x00c8, 0x0601, 0x0401, 0x0201, 0x008c, 0x00e4, 0x004e, 0x0401, 0x0201, 0x00d7, 0x00e5, 0x0201, 0x00ba, 0x00ab, 0x0c01, 0x0401, 0x0201, 0x009c, 0x00e6, 0x0401, 0x0201, 0x006e, 0x00d8, 0x0201, 0x008d, 0x00bb, 0x0801, 0x0401, 0x0201, 0x00e7, 0x009d, 0x0201, 0x00e8, 0x008e, 0x0401, 0x0201, 0x00cb, 0x00bc, 0x009e, 0x00f1, 0x0201, 0x001f, 0x0201, 0x000f, 0x002f, 0x4201, 0x3801, 0x0201, 0x00f2, 0x3401, 0x3201, 0x1401, 0x0801, 0x0201, 0x00bd, 0x0201, 0x005e, 0x0201, 0x007d, 0x00c9, 0x0601, 0x0201, 0x00ca, 0x0201, 0x00ac, 0x007e, 0x0401, 0x0201, 0x00da, 0x00ad, 0x00cc, 0x0a01, 0x0601, 0x0201, 0x00ae, 0x0201, 0x00db, 0x00dc, 0x0201, 0x00cd, 0x00be, 0x0601, 0x0401, 0x0201, 0x00eb, 0x00ed, 0x00ee, 0x0601, 0x0401, 0x0201, 0x00d9, 0x00ea, 0x00e9, 0x0201, 0x00de, 0x0401, 0x0201, 0x00dd, 0x00ec, 0x00ce, 0x003f, 0x00f0, 0x0401, 0x0201, 0x00f3, 0x00f4, 0x0201, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0a01, 0x0201, 0x00ff, 0x0401, 0x0201, 0x00f6, 0x006f, 0x0201, 0x00f7, 0x007f, 0x0c01, 0x0601, 0x0201, 0x008f, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00fa, 0x00af, 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, }, [24] = { 0x3c01, 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, 0x0201, 0x0012, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0e01, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0801, 0x0401, 0x0201, 0x0014, 0x0033, 0x0201, 0x0042, 0x0024, 0x0601, 0x0401, 0x0201, 0x0043, 0x0034, 0x0051, 0x0601, 0x0401, 0x0201, 0x0050, 0x0005, 0x0015, 0x0201, 0x0052, 0x0025, 0xfa01, 0x6201, 0x2201, 0x1201, 0x0a01, 0x0401, 0x0201, 0x0044, 0x0053, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0401, 0x0201, 0x0061, 0x0016, 0x0201, 0x0062, 0x0026, 0x0801, 0x0401, 0x0201, 0x0054, 0x0045, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0071, 0x0055, 0x0201, 0x0064, 0x0046, 0x2001, 0x0e01, 0x0601, 0x0201, 0x0072, 0x0201, 0x0027, 0x0037, 0x0201, 0x0073, 0x0401, 0x0201, 0x0070, 0x0007, 0x0017, 0x0a01, 0x0401, 0x0201, 0x0065, 0x0056, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x0401, 0x0201, 0x0074, 0x0047, 0x0201, 0x0018, 0x0082, 0x1001, 0x0801, 0x0401, 0x0201, 0x0028, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, 0x0801, 0x0401, 0x0201, 0x0091, 0x0019, 0x0201, 0x0092, 0x0076, 0x0401, 0x0201, 0x0067, 0x0029, 0x0201, 0x0085, 0x0058, 0x5c01, 0x2201, 0x1001, 0x0801, 0x0401, 0x0201, 0x0093, 0x0039, 0x0201, 0x0094, 0x0049, 0x0401, 0x0201, 0x0077, 0x0086, 0x0201, 0x0068, 0x00a1, 0x0801, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, 0x0059, 0x0401, 0x0201, 0x00a3, 0x003a, 0x0201, 0x0087, 0x0201, 0x0078, 0x004a, 0x1601, 0x0c01, 0x0401, 0x0201, 0x00a4, 0x0096, 0x0401, 0x0201, 0x0069, 0x00b1, 0x0201, 0x001b, 0x00a5, 0x0601, 0x0201, 0x00b2, 0x0201, 0x005a, 0x002b, 0x0201, 0x0088, 0x00b3, 0x1001, 0x0a01, 0x0601, 0x0201, 0x0090, 0x0201, 0x0009, 0x00a0, 0x0201, 0x0097, 0x0079, 0x0401, 0x0201, 0x00a6, 0x006a, 0x00b4, 0x0c01, 0x0601, 0x0201, 0x001a, 0x0201, 0x000a, 0x00b0, 0x0201, 0x003b, 0x0201, 0x000b, 0x00c0, 0x0401, 0x0201, 0x004b, 0x00c1, 0x0201, 0x0098, 0x0089, 0x4301, 0x2201, 0x1001, 0x0801, 0x0401, 0x0201, 0x001c, 0x00b5, 0x0201, 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x00a7, 0x0201, 0x007a, 0x00c3, 0x0a01, 0x0601, 0x0201, 0x003c, 0x0201, 0x000c, 0x00d0, 0x0201, 0x00b6, 0x006b, 0x0401, 0x0201, 0x00c4, 0x004c, 0x0201, 0x0099, 0x00a8, 0x1001, 0x0801, 0x0401, 0x0201, 0x008a, 0x00c5, 0x0201, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x00d2, 0x0901, 0x0401, 0x0201, 0x002d, 0x00d3, 0x0201, 0x003d, 0x00c6, 0x55fa, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, 0x2001, 0x1001, 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e1, 0x0801, 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x00b9, 0x0401, 0x0201, 0x009b, 0x00e3, 0x0201, 0x00d6, 0x006d, 0x1401, 0x0a01, 0x0601, 0x0201, 0x003e, 0x0201, 0x002e, 0x004e, 0x0201, 0x00c8, 0x008c, 0x0401, 0x0201, 0x00e4, 0x00d7, 0x0401, 0x0201, 0x007d, 0x00ab, 0x00e5, 0x0a01, 0x0401, 0x0201, 0x00ba, 0x005e, 0x0201, 0x00c9, 0x0201, 0x009c, 0x006e, 0x0801, 0x0201, 0x00e6, 0x0201, 0x000d, 0x0201, 0x00e0, 0x000e, 0x0401, 0x0201, 0x00d8, 0x008d, 0x0201, 0x00bb, 0x00ca, 0x4a01, 0x0201, 0x00ff, 0x4001, 0x3a01, 0x2001, 0x1001, 0x0801, 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00d9, 0x0401, 0x0201, 0x009d, 0x00e8, 0x0201, 0x008e, 0x00cb, 0x0801, 0x0401, 0x0201, 0x00bc, 0x00da, 0x0201, 0x00ad, 0x00e9, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00db, 0x00bd, 0x1001, 0x0801, 0x0401, 0x0201, 0x00ea, 0x00ae, 0x0201, 0x00dc, 0x00cd, 0x0401, 0x0201, 0x00eb, 0x00be, 0x0201, 0x00dd, 0x00ec, 0x0801, 0x0401, 0x0201, 0x00ce, 0x00ed, 0x0201, 0x00de, 0x00ee, 0x000f, 0x0401, 0x0201, 0x00f0, 0x001f, 0x00f1, 0x0401, 0x0201, 0x00f2, 0x002f, 0x0201, 0x00f3, 0x003f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00f4, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0401, 0x0201, 0x00f6, 0x006f, 0x0201, 0x00f7, 0x0201, 0x007f, 0x008f, 0x0a01, 0x0401, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00af, 0x00fa, 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, }, [32] = { 0x0201, 0x0000, 0x0801, 0x0401, 0x0201, 0x0008, 0x0004, 0x0201, 0x0001, 0x0002, 0x0801, 0x0401, 0x0201, 0x000c, 0x000a, 0x0201, 0x0003, 0x0006, 0x0601, 0x0201, 0x0009, 0x0201, 0x0005, 0x0007, 0x0401, 0x0201, 0x000e, 0x000d, 0x0201, 0x000f, 0x000b, }, [33] = { 0x1001, 0x0801, 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0002, 0x0003, 0x0401, 0x0201, 0x0004, 0x0005, 0x0201, 0x0006, 0x0007, 0x0801, 0x0401, 0x0201, 0x0008, 0x0009, 0x0201, 0x000a, 0x000b, 0x0401, 0x0201, 0x000c, 0x000d, 0x0201, 0x000e, 0x000f, }, } return E end __FILES["codecs/audio/Mpa/Encode2"] = @native function() -- codecs/audio/Mpa/Encode2: an MPEG audio layer II CBR encoder, written from ISO/IEC 11172-3 (2.4.2.3, C.1.5.2). -- Bit allocation tables in minimp3's compact form (CC0, licenses/minimp3-CC0.txt); greedy allocation by noise (signal -- level minus the quantizer's SNR), no psychoacoustic model. local Bits = __include("core/Bits") local T = __include("codecs/audio/Mpa/Tables") local Analysis = __include("codecs/audio/Mpa/Analysis") local Encode2 = {} local floor, log = math.floor, math.log local writeu8 = buffer.writeu8 local POW = table.create(40, 0) for i = 0, 39 do POW[i + 1] = 2 ^ i end -- the allocation tables: { bit-allocation-code offset into g_bitalloc_code_tab, bits, band count } runs (minimp3) local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } local CODE = T.g_bitalloc_code_tab -- quantizer classes (minimp3's ba): 1..16 -> 2^ba - 1 levels in ba bits; 17 / 18 / 19 -> 3 / 5 / 9 levels grouped @native local function levels(ba: number): number if ba >= 17 then return if ba == 17 then 3 elseif ba == 18 then 5 else 9 end return POW[ba + 1] - 1 end @native local function tripleBits(ba: number): number if ba >= 17 then return if ba == 17 then 5 elseif ba == 18 then 7 else 10 end return 3 * ba end -- the quantizer's signal-to-noise ratio in dB (ISO 11172-3 table C.5) local SNR: { [number]: number } = {} do local byLevels = { [3] = 7.00, [5] = 11.00, [7] = 16.00, [9] = 20.84, [15] = 25.28, [31] = 31.59, [63] = 37.75, [127] = 43.84, [255] = 49.89, [511] = 55.93, [1023] = 61.96, [2047] = 67.98, [4095] = 74.01, [8191] = 80.03, [16383] = 86.05, [32767] = 92.01, [65535] = 98.01, } for ba = 1, 19 do SNR[ba] = byLevels[levels(ba)] or (6.02 * ba) end end -- scalefactors 2^(1 - i/3), i = 0 .. 62 local SCF = table.create(63, 0) for i = 0, 62 do SCF[i + 1] = 2 ^ (1 - i / 3) end local RATES = { [44100] = { 3, 0 }, [48000] = { 3, 1 }, [32000] = { 3, 2 }, [22050] = { 2, 0 }, [24000] = { 2, 1 }, [16000] = { 2, 2 }, } Encode2.RATES = RATES local BITRATES_V1 = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 } local BITRATES_V2 = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 } Encode2.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } type W = Bits.RawWriter local put = Bits.msbPut type Source = { sampleRate: number, channels: number, frames: number, read: (self: any, n: number, out: buffer?) -> (buffer, number), err: any, } type Options = { bitrate: number, mode: string, prefix: buffer? } @native function Encode2.encode(src: Source, opts: Options): (buffer?, string?) local rate = src.sampleRate local info = RATES[rate] if not info then return nil, "unsupported sample rate" end local version, srIndex = info[1], info[2] local mpeg1 = version == 3 local inCh = src.channels local nch = if opts.mode == "mono" then 1 else 2 local kbps = opts.bitrate local list = if mpeg1 then BITRATES_V1 else BITRATES_V2 local brIndex = table.find(list, kbps) if not brIndex then return nil, "unsupported bit rate" end local alloc, nbands if not mpeg1 then alloc, nbands = ALLOC_L2M2, 30 else local perCh = if nch == 2 then kbps // 2 else kbps alloc, nbands = ALLOC_L2M1, 27 if perCh < 56 then alloc, nbands = ALLOC_L2M1_LOW, if srIndex == 2 then 12 else 8 elseif perCh >= 96 and srIndex ~= 1 then nbands = 30 end end local bandOff, bandBits = table.create(nbands, 0), table.create(nbands, 0) do local k, ai = 0, 1 local off, bits = 0, 0 for i = 0, nbands - 1 do if i == k then off, bits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2] ai += 3 end bandOff[i + 1], bandBits[i + 1] = off, bits end end -- per band: the classes it can take, in increasing order (index into the code table = the value written) local steps: { { { number } } } = {} for i = 1, nbands do local s = {} for v = 1, POW[bandBits[i] + 1] - 1 do local ba = CODE[bandOff[i] + v] if ba and ba > 0 then table.insert(s, { v, ba }) end end steps[i] = s end local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } if opts.prefix then local pf = opts.prefix :: buffer if buffer.len(pf) > buffer.len(w.buf) - 16 then w.buf = buffer.create(buffer.len(pf) + 65536) end buffer.copy(w.buf, 0, pf, 0, buffer.len(pf)) w.pos = buffer.len(pf) end local ana = { Analysis.new(), Analysis.new() } local pcm = { table.create(1152, 0), table.create(1152, 0) } -- subband samples: sb[c][band * 36 + t + 1], t = 0 .. 35 local sbs = { table.create(32 * 36, 0), table.create(32 * 36, 0) } local sub = table.create(32, 0) local scf = { table.create(32 * 3, 0), table.create(32 * 3, 0) } local bal = { table.create(32, 0), table.create(32, 0) } local slot = 144000 * kbps local rest = 0 local tmp: buffer? = nil local pending: buffer? = nil local pendN, pendOff = 0, 0 local srcDone, flushed = false, false while true do local got = 0 while got < 1152 and not srcDone do if pendN == 0 then local b, n = src:read(4096, tmp) if n <= 0 then srcDone = true break end tmp = b pending, pendN, pendOff = b, n, 0 end local take = math.min(1152 - got, pendN) local pb = pending :: buffer for i = 0, take - 1 do local base = (pendOff + i) * inCh * 4 local l = buffer.readf32(pb, base) local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l if nch == 1 then pcm[1][got + i + 1] = if inCh > 1 then (l + r) * 0.5 else l else pcm[1][got + i + 1] = l pcm[2][got + i + 1] = r end end got += take pendN -= take pendOff += take end if got == 0 then if flushed then break end flushed = true end for c = 1, nch do local s = pcm[c] for i = got + 1, 1152 do s[i] = 0 end local sb = sbs[c] for t = 0, 35 do Analysis.run(ana[c], s, t * 32 + 1, sub, 1) for b = 0, 31 do sb[b * 36 + t + 1] = sub[b + 1] end end -- scalefactors: the smallest scalefactor (largest index) still >= the part's peak local sc = scf[c] for b = 0, nbands - 1 do for part = 0, 2 do local m = 0 local o = b * 36 + part * 12 for t = 1, 12 do local v = math.abs(sb[o + t]) if v > m then m = v end end local idx = 62 if m > 0 then idx = math.clamp(floor(3 * (1 - log(m) / log(2))), 0, 62) while idx > 0 and SCF[idx + 1] < m do idx -= 1 end while idx < 62 and SCF[idx + 2] >= m do idx += 1 end end sc[b * 3 + part + 1] = idx end end end local frameBytes = slot // rate rest += slot % rate local padding = 0 if rest >= rate then rest -= rate padding = 1 frameBytes += 1 end local avail = frameBytes * 8 - 32 for b = 1, nbands do avail -= bandBits[b] * nch end local level = { table.create(nbands, 0), table.create(nbands, 0) } for c = 1, nch do local sc = scf[c] for b = 1, nbands do local best = math.min(sc[(b - 1) * 3 + 1], sc[(b - 1) * 3 + 2], sc[(b - 1) * 3 + 3]) level[c][b] = 20 * math.log10(SCF[best + 1]) bal[c][b] = 0 end end while true do local bestC, bestB, bestNoise, bestCost = 0, 0, -math.huge, 0 for c = 1, nch do for b = 1, nbands do local st = bal[c][b] local s = steps[b] if st < #s and level[c][b] > -110 then local cur = if st == 0 then 0 else s[st][2] local nxt = s[st + 1][2] local noise = level[c][b] - (if st == 0 then 0 else SNR[cur]) local cost = 12 * tripleBits(nxt) - (if st == 0 then 0 else 12 * tripleBits(cur)) if st == 0 then cost += 2 + 18 -- scfsi + three scalefactors end if cost <= avail and noise > bestNoise then bestC, bestB, bestNoise, bestCost = c, b, noise, cost end end end end if bestC == 0 then break end bal[bestC][bestB] += 1 avail -= bestCost end if w.pos + frameBytes + 64 > buffer.len(w.buf) then local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) buffer.copy(nb, 0, w.buf, 0, w.pos) w.buf = nb end local start = w.pos put(w, 0x7FF, 11) put(w, version, 2) put(w, 2, 2) -- layer II put(w, 1, 1) -- no CRC put(w, brIndex, 4) put(w, srIndex, 2) put(w, padding, 1) put(w, 0, 1) put(w, if nch == 1 then 3 else 0, 2) put(w, 0, 2) put(w, 0, 1) put(w, 1, 1) put(w, 0, 2) for b = 1, nbands do for c = 1, nch do local st = bal[c][b] put(w, if st == 0 then 0 else steps[b][st][1], bandBits[b]) end end -- scfsi (0: three scalefactors) and the scalefactors for b = 1, nbands do for c = 1, nch do if bal[c][b] > 0 then put(w, 0, 2) end end end for b = 1, nbands do for c = 1, nch do if bal[c][b] > 0 then for part = 1, 3 do put(w, scf[c][(b - 1) * 3 + part], 6) end end end end -- samples: 12 granules of 3, band by band, channel by channel for gr = 0, 11 do local part = gr // 4 for b = 1, nbands do for c = 1, nch do local st = bal[c][b] if st > 0 then local ba = steps[b][st][2] local L = levels(ba) local inv = 1 / SCF[scf[c][(b - 1) * 3 + part + 1] + 1] local o = (b - 1) * 36 + gr * 3 local sb = sbs[c] local q0, q1, q2 do @native local function quant(x: number): number local q = floor((x * inv + 1) * L / 2) return if q < 0 then 0 elseif q > L - 1 then L - 1 else q end q0 = quant(sb[o + 1]) q1 = quant(sb[o + 2]) q2 = quant(sb[o + 3]) end if ba >= 17 then put(w, q0 + L * (q1 + L * q2), tripleBits(ba)) else put(w, q0, ba) put(w, q1, ba) put(w, q2, ba) end end end end end if w.cnt > 0 then put(w, 0, 8 - w.cnt) end while w.pos < start + frameBytes do writeu8(w.buf, w.pos, 0) w.pos += 1 end end if src.err then return nil, tostring(src.err) end local out = buffer.create(w.pos) buffer.copy(out, 0, w.buf, 0, w.pos) return out, nil end return Encode2 end __FILES["codecs/audio/Mpa/Encode3"] = @native function() -- codecs/audio/Mpa/Encode3: an MPEG audio layer III CBR encoder in the spirit of shine (long blocks, global-gain rate -- control, no bit reservoir). Written from ISO/IEC 11172-3 / 13818-3 (no shine / LAME code); Huffman codes derived -- from the standard's decoder trees (codecs/audio/Mpa/EncTables, from PDMP3, public domain). local Bits = __include("core/Bits") local E = __include("codecs/audio/Mpa/EncTables") local T = __include("codecs/audio/Mpa/Tables") local Analysis = __include("codecs/audio/Mpa/Analysis") local Encode3 = {} local floor, sqrt, cos, pi = math.floor, math.sqrt, math.cos, math.pi local writeu8 = buffer.writeu8 local POW = table.create(40, 0) for i = 0, 39 do POW[i + 1] = 2 ^ i end -- CODE[t][x * 16 + y + 1], LEN[t][...] for the pair tables 1..31 (16..23 and 24..31 share a tree); count1 tables A -- (32) and B (33) indexed by v * 8 + w * 4 + x * 2 + y + 1 local CODE: { [number]: { number } } = {} local LEN: { [number]: { number } } = {} local XLEN: { [number]: number } = {} @native local function walk(tree: { number }, codes: { number }, lens: { number }, p: number, code: number, len: number) local v = tree[p + 1] if bit32.band(v, 0xFF00) == 0 then local idx = bit32.band(v, 0xFF) + 1 if lens[idx] == 0 then codes[idx], lens[idx] = code, len end return end -- left (bit 0): offsets of 250+ chain local q = p while bit32.rshift(tree[q + 1], 8) >= 250 do q += bit32.rshift(tree[q + 1], 8) end q += bit32.rshift(tree[q + 1], 8) walk(tree, codes, lens, q, code * 2, len + 1) q = p while bit32.band(tree[q + 1], 0xFF) >= 250 do q += bit32.band(tree[q + 1], 0xFF) end q += bit32.band(tree[q + 1], 0xFF) walk(tree, codes, lens, q, code * 2 + 1, len + 1) end for t = 1, 33 do local src = if t >= 16 and t <= 23 then 16 elseif t >= 24 and t <= 31 then 24 else t local tree = E.TREES[src] if tree then local codes, lens = table.create(256, 0), table.create(256, 0) walk(tree, codes, lens, 0, 0, 0) -- the leaf value of pair tables is x << 4 | y: index x * 16 + y + 1 (count1: the 4-bit vwxy) CODE[t], LEN[t] = codes, lens local xl = 0 for idx = 1, 256 do if lens[idx] > 0 then local x = (idx - 1) // 16 if x + 1 > xl then xl = x + 1 end end end XLEN[t] = xl end end local LINBITS = E.LINBITS local SMALL: { [number]: { number } } = {} for m = 0, 15 do local list = {} for _, t in { 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15 } do if XLEN[t] and XLEN[t] - 1 >= m then table.insert(list, t) end end SMALL[m] = list end type W = Bits.RawWriter local put = Bits.msbPut Encode3.put = put local RATES = { -- rate -> version bits (3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5), sample rate index, scalefactor band group (g_scf_long) [44100] = { 3, 0, 5 }, [48000] = { 3, 1, 6 }, [32000] = { 3, 2, 7 }, [22050] = { 2, 0, 2 }, [24000] = { 2, 1, 3 }, [16000] = { 2, 2, 4 }, [11025] = { 0, 0, 0 }, [12000] = { 0, 1, 0 }, [8000] = { 0, 2, 1 }, } Encode3.RATES = RATES local BITRATES_V1 = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 } local BITRATES_V2 = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 } Encode3.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } -- the 36-point MDCT (long blocks): X[k] = 1/9 sum_i w_i z_i cos(pi/72 (2i + 19)(2k + 1)), w_i = sin(pi/36 (i + 1/2)) local MDCT = table.create(18 * 36, 0) for k = 0, 17 do for i = 0, 35 do MDCT[k * 36 + i + 1] = math.sin(pi / 36 * (i + 0.5)) * cos(pi / 72 * (2 * i + 19) * (2 * k + 1)) / 9 end end local CI = { -0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037 } local CS, CA = table.create(8, 0), table.create(8, 0) for i = 1, 8 do local s = sqrt(1 + CI[i] * CI[i]) CS[i], CA[i] = 1 / s, CI[i] / s end type Plan = { bits: number, bigValues: number, count1: number, tables: { number }, region0: number, region1: number, c1table: number, -- 0 = A (table 32), 1 = B (33) addr1: number, addr2: number, } @native local function newPlan(): Plan return { bits = 0, bigValues = 0, count1 = 0, tables = { 0, 0, 0 }, region0 = 0, region1 = 0, c1table = 0, addr1 = 0, addr2 = 0 } end @native local function pairBits(ix: { number }, a: number, b: number, t: number): number if t == 0 then return 0 end local lens = LEN[t] local lb = LINBITS[t] local bits = 0 for i = a, b - 1, 2 do local x, y = ix[i + 1], ix[i + 2] local extra = 0 if x > 14 then x = 15 extra += lb end if y > 14 then y = 15 extra += lb end bits += lens[x * 16 + y + 1] + extra if x ~= 0 then bits += 1 end if y ~= 0 then bits += 1 end end return bits end @native local function chooseTable(ix: { number }, a: number, b: number): (number, number) if b <= a then return 0, 0 end local m = 0 for i = a + 1, b do local v = ix[i] if v > m then m = v end end if m == 0 then return 0, 0 end if m <= 15 then local best, bestBits = 0, math.huge for _, t in SMALL[m] do local bits = pairBits(ix, a, b, t) if bits < bestBits then best, bestBits = t, bits end end return best, bestBits end local need = m - 15 local best, bestBits = 0, math.huge for _, group in { 16, 24 } do for t = group, group + 7 do if POW[LINBITS[t] + 1] - 1 >= need then local bits = pairBits(ix, a, b, t) if bits < bestBits then best, bestBits = t, bits end break end end end return best, bestBits end @native local function plan(ix: { number }, bounds: { number }, p: Plan) local i = 576 while i > 1 and ix[i] == 0 and ix[i - 1] == 0 do i -= 2 end -- count1 region: quadruples of values <= 1 local c1 = 0 while i > 3 and ix[i] <= 1 and ix[i - 1] <= 1 and ix[i - 2] <= 1 and ix[i - 3] <= 1 do i -= 4 c1 += 1 end local bv = i -- big_values * 2 coefficients p.bigValues, p.count1 = bv // 2, c1 local ba, bb = 0, 0 local lensA = LEN[32] for q = 0, c1 - 1 do local o = bv + q * 4 local v, w, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] local s = v + w + x + y ba += lensA[v * 8 + w * 4 + x * 2 + y + 1] + s bb += 4 + s end p.c1table = if bb < ba then 1 else 0 local bits = if bb < ba then bb else ba -- regions: region 0 / 1 / 2 split at scalefactor band boundaries local j = 0 while j + 1 < #bounds and bounds[j + 2] <= bv do j += 1 end local r0 = math.clamp(floor((j + 1) / 3), 0, 15) local r1 = math.clamp(floor((j + 1) / 3), 0, 7) if r0 + r1 + 2 > 22 then r1 = 22 - r0 - 2 end local a1 = math.min(bounds[r0 + 2] or 576, bv) local a2 = math.min(bounds[r0 + r1 + 3] or 576, bv) p.region0, p.region1, p.addr1, p.addr2 = r0, r1, a1, a2 local t1, b1 = chooseTable(ix, 0, a1) local t2, b2 = chooseTable(ix, a1, a2) local t3, b3 = chooseTable(ix, a2, bv) p.tables[1], p.tables[2], p.tables[3] = t1, t2, t3 p.bits = bits + b1 + b2 + b3 end @native local function writePairs(w: W, ix: { number }, sign: { boolean }, a: number, b: number, t: number) if t == 0 then return end local codes, lens = CODE[t], LEN[t] local lb = LINBITS[t] for i = a, b - 1, 2 do local x, y = ix[i + 1], ix[i + 2] local cx, cy = if x > 14 then 15 else x, if y > 14 then 15 else y local idx = cx * 16 + cy + 1 put(w, codes[idx], lens[idx]) if cx == 15 then put(w, x - 15, lb) end if x ~= 0 then put(w, if sign[i + 1] then 1 else 0, 1) end if cy == 15 then put(w, y - 15, lb) end if y ~= 0 then put(w, if sign[i + 2] then 1 else 0, 1) end end end @native local function writeHuffman(w: W, ix: { number }, sign: { boolean }, p: Plan) local bv = p.bigValues * 2 writePairs(w, ix, sign, 0, p.addr1, p.tables[1]) writePairs(w, ix, sign, p.addr1, p.addr2, p.tables[2]) writePairs(w, ix, sign, p.addr2, bv, p.tables[3]) local codesA, lensA = CODE[32], LEN[32] for q = 0, p.count1 - 1 do local o = bv + q * 4 local v, ww, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] local idx = v * 8 + ww * 4 + x * 2 + y if p.c1table == 1 then put(w, 15 - idx, 4) -- table B: the 4 bits inverted else put(w, codesA[idx + 1], lensA[idx + 1]) end for k = 1, 4 do if ix[o + k] ~= 0 then put(w, if sign[o + k] then 1 else 0, 1) end end end end type Unit = { xr: { number }, xa: { number }, -- |xr|^(3/4) ix: { number }, sign: { boolean }, plan: Plan, gain: number, } @native local function newUnit(): Unit return { xr = table.create(576, 0), xa = table.create(576, 0), ix = table.create(576, 0), sign = table.create(576, false), plan = newPlan(), gain = 210, } end -- quantize with global gain g: false when a value overflows 8206 @native local function quantize(u: Unit, g: number): boolean local step = 2 ^ (-(g - 210) * 3 / 16) local xa, ix = u.xa, u.ix for i = 1, 576 do local v = floor(xa[i] * step + 0.4054) if v > 8206 then return false end ix[i] = v end return true end @native local function rateLoop(u: Unit, budget: number, bounds: { number }) local xr, xa, sign = u.xr, u.xa, u.sign local maxa = 0 for i = 1, 576 do local v = xr[i] sign[i] = v < 0 local a = math.abs(v) ^ 0.75 xa[i] = a if a > maxa then maxa = a end end local p = u.plan if maxa < 1e-12 then for i = 1, 576 do u.ix[i] = 0 end plan(u.ix, bounds, p) u.gain = 0 return end local lo, hi = 0, 255 local best = -1 while lo <= hi do local mid = (lo + hi) // 2 if quantize(u, mid) then plan(u.ix, bounds, p) if p.bits <= budget then best = mid hi = mid - 1 else lo = mid + 1 end else lo = mid + 1 end end if best < 0 then best = 255 end quantize(u, best) plan(u.ix, bounds, p) if p.bits > budget then -- give up on this granule: silence fits any budget for i = 1, 576 do u.ix[i] = 0 end plan(u.ix, bounds, p) end u.gain = best end type Source = { sampleRate: number, channels: number, frames: number, read: (self: any, n: number, out: buffer?) -> (buffer, number), err: any, } type Options = { bitrate: number, mode: string, prefix: buffer?, } @native function Encode3.encode(src: Source, opts: Options): (buffer?, string?) local rate = src.sampleRate local info = RATES[rate] if not info then return nil, "unsupported sample rate" end local version, srIndex, group = info[1], info[2], info[3] local mpeg1 = version == 3 local granules = if mpeg1 then 2 else 1 local spf = 576 * granules local inCh = src.channels local mode = opts.mode local nch = if mode == "mono" then 1 else 2 local kbps = opts.bitrate local list = if mpeg1 then BITRATES_V1 else BITRATES_V2 local brIndex = table.find(list, kbps) if not brIndex then return nil, "unsupported bit rate" end local sideBytes = if mpeg1 then (if nch == 1 then 17 else 32) else (if nch == 1 then 9 else 17) local slotNum = (if mpeg1 then 144000 else 72000) * kbps -- frame bytes * rate local bounds = { 0 } do local acc = 0 for k = 0, 21 do acc += T.g_scf_long[group * 23 + k] table.insert(bounds, acc) end end local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } if opts.prefix then local pf = opts.prefix :: buffer local need = buffer.len(pf) if need > buffer.len(w.buf) - 16 then w.buf = buffer.create(need + 65536) end buffer.copy(w.buf, 0, pf, 0, need) w.pos = need end local ana = { Analysis.new(), Analysis.new() } local prev = { table.create(576, 0), table.create(576, 0) } local cur = { table.create(576, 0), table.create(576, 0) } local units = {} for g = 1, 2 do units[g] = { newUnit(), newUnit() } end local pcm = { table.create(spf, 0), table.create(spf, 0) } local sub = table.create(32, 0) local z = table.create(36, 0) local rest = 0 local tmp: buffer? = nil local pending: buffer? = nil local pendN, pendOff = 0, 0 local srcDone = false local flushed = false while true do local got = 0 while got < spf and not srcDone do if pendN == 0 then local b, n = src:read(4096, tmp) if n <= 0 then srcDone = true break end tmp = b pending, pendN, pendOff = b, n, 0 end local take = math.min(spf - got, pendN) local pb = pending :: buffer for i = 0, take - 1 do local base = (pendOff + i) * inCh * 4 local l = buffer.readf32(pb, base) local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l if nch == 1 then if inCh > 1 then l = (l + r) * 0.5 end pcm[1][got + i + 1] = l else pcm[1][got + i + 1] = l pcm[2][got + i + 1] = r end end got += take pendN -= take pendOff += take end if got == 0 then if flushed then break end flushed = true -- one silent frame after the input pushes its tail through the filterbank delay end for c = 1, nch do local s = pcm[c] for i = got + 1, spf do s[i] = 0 end end for g = 1, granules do for c = 1, nch do local cu, pv = cur[c], prev[c] local s = pcm[c] for k = 0, 17 do Analysis.run(ana[c], s, (g - 1) * 576 + k * 32 + 1, sub, 1) for sb = 0, 31 do local v = sub[sb + 1] if sb % 2 == 1 and k % 2 == 1 then v = -v -- frequency inversion of the odd subbands end cu[sb * 18 + k + 1] = v end end local xr = units[g][c].xr for sb = 0, 31 do local o = sb * 18 for i = 1, 18 do z[i] = pv[o + i] z[i + 18] = cu[o + i] end for k = 0, 17 do local acc = 0 local mb = k * 36 for i = 1, 36 do acc += MDCT[mb + i] * z[i] end xr[o + k + 1] = acc end end -- alias reduction butterflies (the inverse of the decoder's) for sb = 1, 31 do local o = sb * 18 for i = 0, 7 do local a, b = xr[o - i], xr[o + i + 1] xr[o - i] = a * CS[i + 1] + b * CA[i + 1] xr[o + i + 1] = b * CS[i + 1] - a * CA[i + 1] end end prev[c], cur[c] = cu, pv end if mode == "joint" then local x0, x1 = units[g][1].xr, units[g][2].xr local r2 = sqrt(0.5) for i = 1, 576 do local l, r = x0[i], x1[i] x0[i], x1[i] = (l + r) * r2, (l - r) * r2 end end end local frameBytes = slotNum // rate rest += slotNum % rate local padding = 0 if rest >= rate then rest -= rate padding = 1 frameBytes += 1 end local avail = (frameBytes - 4 - sideBytes) * 8 local left = avail local nUnits = granules * nch local done = 0 for g = 1, granules do for c = 1, nch do local budget = math.min(4095, left // (nUnits - done)) local u = units[g][c] rateLoop(u, budget, bounds) left -= u.plan.bits done += 1 end end if w.pos + frameBytes + 64 > buffer.len(w.buf) then local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) buffer.copy(nb, 0, w.buf, 0, w.pos) w.buf = nb end local start = w.pos put(w, 0x7FF, 11) put(w, version, 2) put(w, 1, 2) -- layer III put(w, 1, 1) -- no CRC put(w, brIndex, 4) put(w, srIndex, 2) put(w, padding, 1) put(w, 0, 1) put(w, if mode == "mono" then 3 elseif mode == "joint" then 1 else 0, 2) put(w, if mode == "joint" then 2 else 0, 2) -- mode extension: mid / side on, intensity off put(w, 0, 1) put(w, 1, 1) -- original put(w, 0, 2) if mpeg1 then put(w, 0, 9) -- main_data_begin put(w, 0, if nch == 1 then 5 else 3) for _ = 1, nch do put(w, 0, 4) -- scfsi end else put(w, 0, 8) put(w, 0, if nch == 1 then 1 else 2) end for g = 1, granules do for c = 1, nch do local u = units[g][c] local p = u.plan put(w, p.bits, 12) -- part2_3_length (no scalefactor bits) put(w, p.bigValues, 9) put(w, u.gain, 8) put(w, 0, if mpeg1 then 4 else 9) -- scalefac_compress put(w, 0, 1) -- window switching off put(w, p.tables[1], 5) put(w, p.tables[2], 5) put(w, p.tables[3], 5) put(w, p.region0, 4) put(w, p.region1, 3) if mpeg1 then put(w, 0, 1) -- preflag end put(w, 0, 1) -- scalefac_scale put(w, p.c1table, 1) end end for g = 1, granules do for c = 1, nch do local u = units[g][c] writeHuffman(w, u.ix, u.sign, u.plan) end end if w.cnt > 0 then put(w, 0, 8 - w.cnt) end -- ancillary padding to the frame size while w.pos < start + frameBytes do writeu8(w.buf, w.pos, 0) w.pos += 1 end end if src.err then return nil, tostring(src.err) end local out = buffer.create(w.pos) buffer.copy(out, 0, w.buf, 0, w.pos) return out, nil end return Encode3 end __FILES["codecs/audio/Mpa/Header"] = @native function() -- codecs/audio/Mpa/Header: MPEG audio frame headers and frame sync, after minimp3's hdr_* and mp3d_find_frame / -- mp3d_match_frame (CC0, licenses/minimp3-CC0.txt). local T = __include("codecs/audio/Mpa/Tables") local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift local ru8 = buffer.readu8 local HALFRATE = T.halfrate local HZ = { [0] = 44100, 48000, 32000 } local H = {} H.MAX_FREE_FORMAT_FRAME_SIZE = 2304 H.MAX_FRAME_SYNC_MATCHES = 10 -- hdr_valid @native function H.valid(b: buffer, o: number): boolean if ru8(b, o) ~= 0xFF then return false end local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) return (band(h1, 0xF0) == 0xF0 or band(h1, 0xFE) == 0xE2) and band(rshift(h1, 1), 3) ~= 0 and rshift(h2, 4) ~= 15 and band(rshift(h2, 2), 3) ~= 3 end local valid = H.valid -- hdr_compare @native function H.compare(b: buffer, o1: number, o2: number): boolean if not valid(b, o2) then return false end local a1, a2 = ru8(b, o1 + 1), ru8(b, o1 + 2) local c1, c2 = ru8(b, o2 + 1), ru8(b, o2 + 2) return band(bxor(a1, c1), 0xFE) == 0 and band(bxor(a2, c2), 0x0C) == 0 and (band(a2, 0xF0) == 0) == (band(c2, 0xF0) == 0) end local compare = H.compare -- from the header bytes h1 = byte 1, h2 = byte 2 @native function H.bitrateKbps(h1: number, h2: number): number local mpeg1 = if band(h1, 8) ~= 0 then 1 else 0 local layer = band(rshift(h1, 1), 3) return 2 * HALFRATE[mpeg1 * 45 + (layer - 1) * 15 + rshift(h2, 4)] end local bitrateKbps = H.bitrateKbps @native function H.sampleRate(h1: number, h2: number): number local hz = HZ[band(rshift(h2, 2), 3)] if band(h1, 8) == 0 then hz //= 2 end if band(h1, 0x10) == 0 then hz //= 2 end return hz end local sampleRate = H.sampleRate @native function H.frameSamples(h1: number): number if band(h1, 6) == 6 then return 384 elseif band(h1, 14) == 2 then return 576 end return 1152 end local frameSamples = H.frameSamples -- hdr_frame_bytes (without padding) @native function H.frameBytes(b: buffer, o: number, freeSize: number): number local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) local hz = sampleRate(h1, h2) local fb = frameSamples(h1) * bitrateKbps(h1, h2) * 125 // hz if band(h1, 6) == 6 then fb = band(fb, 0xFFFFFFFC) end return if fb ~= 0 then fb else freeSize end local frameBytes = H.frameBytes @native function H.padding(b: buffer, o: number): number if band(ru8(b, o + 2), 2) == 0 then return 0 end return if band(ru8(b, o + 1), 6) == 6 then 4 else 1 end local padding = H.padding -- mp3d_match_frame: the frames chained after o (n bytes left) keep comparing equal @native local function matchFrame(b: buffer, o: number, n: number, fb: number): boolean local i = 0 for nmatch = 0, H.MAX_FRAME_SYNC_MATCHES - 1 do i += frameBytes(b, o + i, fb) + padding(b, o + i) if i + 4 > n then return nmatch > 0 end if not compare(b, o, o + i) then return false end end return true end -- mp3d_find_frame @native function H.findFrame(b: buffer, base: number, n: number, ffb: number): (number, number, number) for i = 0, n - 5 do local o = base + i if valid(b, o) then local fb = frameBytes(b, o, ffb) local fap = fb + padding(b, o) local k = 4 while fb == 0 and k < H.MAX_FREE_FORMAT_FRAME_SIZE and i + 2 * k < n - 4 do if compare(b, o, o + k) then local f = k - padding(b, o) local nextfb = f + padding(b, o + k) if not (i + k + nextfb + 4 > n or not compare(b, o, o + k + nextfb)) then fap = k fb = f ffb = f end end k += 1 end if (fb ~= 0 and i + fap <= n and matchFrame(b, o, n - i, fb)) or (i == 0 and fap == n) then return i, fap, ffb end ffb = 0 end end return n, 0, ffb end return H end __FILES["codecs/audio/Mpa/Tables"] = function() -- codecs/audio/Mpa/Tables: constant tables of minimp3 (https://github.com/lieff/minimp3, CC0), generated by tools/gen_tables.py. -- Every list is flattened row-major and 0-based (t[0] is the first element), like the C arrays. local T = {} T.halfrate = { [0] = 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 72, 80, 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 72, 80, 0, 16, 24, 28, 32, 40, 48, 56, 64, 72, 80, 88, 96, 112, 128, 0, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 0, 16, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, } T.g_bitalloc_code_tab = { [0] = 0, 17, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0, 17, 18, 3, 19, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 0, 17, 18, 3, 19, 4, 5, 16, 0, 17, 18, 16, 0, 17, 18, 19, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 17, 18, 3, 19, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, } T.g_scf_long = { [0] = 6, 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 12, 12, 12, 12, 12, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 76, 90, 2, 2, 2, 2, 2, 0, 6, 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 6, 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 18, 22, 26, 32, 38, 46, 54, 62, 70, 76, 36, 0, 6, 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 4, 4, 4, 4, 4, 4, 6, 6, 8, 8, 10, 12, 16, 20, 24, 28, 34, 42, 50, 54, 76, 158, 0, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 10, 12, 16, 18, 22, 28, 34, 40, 46, 54, 54, 192, 0, 4, 4, 4, 4, 4, 4, 6, 6, 8, 10, 12, 16, 20, 24, 30, 38, 46, 56, 68, 84, 102, 26, 0, } T.g_scf_short = { [0] = 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2, 2, 2, 2, 26, 26, 26, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14, 14, 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, 42, 42, 42, 12, 12, 12, 0, } T.g_scf_mixed = { [0] = 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 0, 0, 0, 12, 12, 12, 4, 4, 4, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2, 2, 2, 2, 26, 26, 26, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14, 14, 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, 42, 42, 42, 12, 12, 12, 0, 0, } T.g_expfrac = { [0] = 9.31322575e-10, 7.83145814e-10, 6.58544508e-10, 5.53767716e-10, } T.g_scf_partitions = { [0] = 6, 5, 5, 5, 6, 5, 5, 5, 6, 5, 7, 3, 11, 10, 0, 0, 7, 7, 7, 0, 6, 6, 6, 3, 8, 8, 5, 0, 8, 9, 6, 12, 6, 9, 9, 9, 6, 9, 12, 6, 15, 18, 0, 0, 6, 15, 12, 0, 6, 12, 9, 6, 6, 18, 9, 0, 9, 9, 6, 12, 9, 9, 9, 9, 9, 9, 12, 6, 18, 18, 0, 0, 12, 12, 12, 0, 12, 9, 9, 6, 15, 12, 9, 0, } T.g_scfc_decode = { [0] = 0, 1, 2, 3, 12, 5, 6, 7, 9, 10, 11, 13, 14, 15, 18, 19, } T.g_mod = { [0] = 5, 5, 4, 4, 5, 5, 4, 1, 4, 3, 1, 1, 5, 6, 6, 1, 4, 4, 4, 1, 4, 3, 1, 1, } T.g_preamp = { [0] = 1, 1, 1, 1, 2, 2, 3, 3, 3, 2, } T.g_pow43 = { [0] = 0, -1, -2.519842, -4.326749, -6.349604, -8.549880, -10.902724, -13.390518, -16.000000, -18.720754, -21.544347, -24.463781, -27.473142, -30.567351, -33.741992, -36.993181, 0, 1, 2.519842, 4.326749, 6.349604, 8.549880, 10.902724, 13.390518, 16.000000, 18.720754, 21.544347, 24.463781, 27.473142, 30.567351, 33.741992, 36.993181, 40.317474, 43.711787, 47.173345, 50.699631, 54.288352, 57.937408, 61.644865, 65.408941, 69.227979, 73.100443, 77.024898, 81.000000, 85.024491, 89.097188, 93.216975, 97.382800, 101.593667, 105.848633, 110.146801, 114.487321, 118.869381, 123.292209, 127.755065, 132.257246, 136.798076, 141.376907, 145.993119, 150.646117, 155.335327, 160.060199, 164.820202, 169.614826, 174.443577, 179.305980, 184.201575, 189.129918, 194.090580, 199.083145, 204.107210, 209.162385, 214.248292, 219.364564, 224.510845, 229.686789, 234.892058, 240.126328, 245.389280, 250.680604, 256.000000, 261.347174, 266.721841, 272.123723, 277.552547, 283.008049, 288.489971, 293.998060, 299.532071, 305.091761, 310.676898, 316.287249, 321.922592, 327.582707, 333.267377, 338.976394, 344.709550, 350.466646, 356.247482, 362.051866, 367.879608, 373.730522, 379.604427, 385.501143, 391.420496, 397.362314, 403.326427, 409.312672, 415.320884, 421.350905, 427.402579, 433.475750, 439.570269, 445.685987, 451.822757, 457.980436, 464.158883, 470.357960, 476.577530, 482.817459, 489.077615, 495.357868, 501.658090, 507.978156, 514.317941, 520.677324, 527.056184, 533.454404, 539.871867, 546.308458, 552.764065, 559.238575, 565.731879, 572.243870, 578.774440, 585.323483, 591.890898, 598.476581, 605.080431, 611.702349, 618.342238, 625.000000, 631.675540, 638.368763, 645.079578, } T.tabs = { [0] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 785, 785, 785, 785, 784, 784, 784, 784, 513, 513, 513, 513, 513, 513, 513, 513, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -255, 1313, 1298, 1282, 785, 785, 785, 785, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 290, 288, -255, 1313, 1298, 1282, 769, 769, 769, 769, 529, 529, 529, 529, 529, 529, 529, 529, 528, 528, 528, 528, 528, 528, 528, 528, 512, 512, 512, 512, 512, 512, 512, 512, 290, 288, -253, -318, -351, -367, 785, 785, 785, 785, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 819, 818, 547, 547, 275, 275, 275, 275, 561, 560, 515, 546, 289, 274, 288, 258, -254, -287, 1329, 1299, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 784, 784, 784, 784, 529, 529, 529, 529, 529, 529, 529, 529, 769, 769, 769, 769, 768, 768, 768, 768, 563, 560, 306, 306, 291, 259, -252, -413, -477, -542, 1298, -575, 1041, 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -383, -399, 1107, 1092, 1106, 1061, 849, 849, 789, 789, 1104, 1091, 773, 773, 1076, 1075, 341, 340, 325, 309, 834, 804, 577, 577, 532, 532, 516, 516, 832, 818, 803, 816, 561, 561, 531, 531, 515, 546, 289, 289, 288, 258, -252, -429, -493, -559, 1057, 1057, 1042, 1042, 529, 529, 529, 529, 529, 529, 529, 529, 784, 784, 784, 784, 769, 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, -382, 1077, -415, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, 1075, 834, 834, 597, 581, 340, 340, 339, 324, 804, 833, 532, 532, 832, 772, 818, 803, 817, 787, 816, 771, 290, 290, 290, 290, 288, 258, -253, -349, -414, -447, -463, 1329, 1299, -479, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 785, 785, 785, 785, 784, 784, 784, 784, 769, 769, 769, 769, 768, 768, 768, 768, -319, 851, 821, -335, 836, 850, 805, 849, 341, 340, 325, 336, 533, 533, 579, 579, 564, 564, 773, 832, 578, 548, 563, 516, 321, 276, 306, 291, 304, 259, -251, -572, -733, -830, -863, -879, 1041, 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -511, -527, -543, 1396, 1351, 1381, 1366, 1395, 1335, 1380, -559, 1334, 1138, 1138, 1063, 1063, 1350, 1392, 1031, 1031, 1062, 1062, 1364, 1363, 1120, 1120, 1333, 1348, 881, 881, 881, 881, 375, 374, 359, 373, 343, 358, 341, 325, 791, 791, 1123, 1122, -703, 1105, 1045, -719, 865, 865, 790, 790, 774, 774, 1104, 1029, 338, 293, 323, 308, -799, -815, 833, 788, 772, 818, 803, 816, 322, 292, 307, 320, 561, 531, 515, 546, 289, 274, 288, 258, -251, -525, -605, -685, -765, -831, -846, 1298, 1057, 1057, 1312, 1282, 785, 785, 785, 785, 784, 784, 784, 784, 769, 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, 1399, 1398, 1383, 1367, 1382, 1396, 1351, -511, 1381, 1366, 1139, 1139, 1079, 1079, 1124, 1124, 1364, 1349, 1363, 1333, 882, 882, 882, 882, 807, 807, 807, 807, 1094, 1094, 1136, 1136, 373, 341, 535, 535, 881, 775, 867, 822, 774, -591, 324, 338, -671, 849, 550, 550, 866, 864, 609, 609, 293, 336, 534, 534, 789, 835, 773, -751, 834, 804, 308, 307, 833, 788, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290, 290, -252, -397, -477, -557, -622, -653, -719, -735, -750, 1329, 1299, 1314, 1057, 1057, 1042, 1042, 1312, 1282, 1024, 1024, 785, 785, 785, 785, 784, 784, 784, 784, 769, 769, 769, 769, -383, 1127, 1141, 1111, 1126, 1140, 1095, 1110, 869, 869, 883, 883, 1079, 1109, 882, 882, 375, 374, 807, 868, 838, 881, 791, -463, 867, 822, 368, 263, 852, 837, 836, -543, 610, 610, 550, 550, 352, 336, 534, 534, 865, 774, 851, 821, 850, 805, 593, 533, 579, 564, 773, 832, 578, 578, 548, 548, 577, 577, 307, 276, 306, 291, 516, 560, 259, 259, -250, -2107, -2507, -2764, -2909, -2974, -3007, -3023, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -767, -1052, -1213, -1277, -1358, -1405, -1469, -1535, -1550, -1582, -1614, -1647, -1662, -1694, -1726, -1759, -1774, -1807, -1822, -1854, -1886, 1565, -1919, -1935, -1951, -1967, 1731, 1730, 1580, 1717, -1983, 1729, 1564, -1999, 1548, -2015, -2031, 1715, 1595, -2047, 1714, -2063, 1610, -2079, 1609, -2095, 1323, 1323, 1457, 1457, 1307, 1307, 1712, 1547, 1641, 1700, 1699, 1594, 1685, 1625, 1442, 1442, 1322, 1322, -780, -973, -910, 1279, 1278, 1277, 1262, 1276, 1261, 1275, 1215, 1260, 1229, -959, 974, 974, 989, 989, -943, 735, 478, 478, 495, 463, 506, 414, -1039, 1003, 958, 1017, 927, 942, 987, 957, 431, 476, 1272, 1167, 1228, -1183, 1256, -1199, 895, 895, 941, 941, 1242, 1227, 1212, 1135, 1014, 1014, 490, 489, 503, 487, 910, 1013, 985, 925, 863, 894, 970, 955, 1012, 847, -1343, 831, 755, 755, 984, 909, 428, 366, 754, 559, -1391, 752, 486, 457, 924, 997, 698, 698, 983, 893, 740, 740, 908, 877, 739, 739, 667, 667, 953, 938, 497, 287, 271, 271, 683, 606, 590, 712, 726, 574, 302, 302, 738, 736, 481, 286, 526, 725, 605, 711, 636, 724, 696, 651, 589, 681, 666, 710, 364, 467, 573, 695, 466, 466, 301, 465, 379, 379, 709, 604, 665, 679, 316, 316, 634, 633, 436, 436, 464, 269, 424, 394, 452, 332, 438, 363, 347, 408, 393, 448, 331, 422, 362, 407, 392, 421, 346, 406, 391, 376, 375, 359, 1441, 1306, -2367, 1290, -2383, 1337, -2399, -2415, 1426, 1321, -2431, 1411, 1336, -2447, -2463, -2479, 1169, 1169, 1049, 1049, 1424, 1289, 1412, 1352, 1319, -2495, 1154, 1154, 1064, 1064, 1153, 1153, 416, 390, 360, 404, 403, 389, 344, 374, 373, 343, 358, 372, 327, 357, 342, 311, 356, 326, 1395, 1394, 1137, 1137, 1047, 1047, 1365, 1392, 1287, 1379, 1334, 1364, 1349, 1378, 1318, 1363, 792, 792, 792, 792, 1152, 1152, 1032, 1032, 1121, 1121, 1046, 1046, 1120, 1120, 1030, 1030, -2895, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, 1090, 1060, 1075, 833, 833, 309, 324, 532, 532, 832, 772, 818, 803, 561, 561, 531, 560, 515, 546, 289, 274, 288, 258, -250, -1179, -1579, -1836, -1996, -2124, -2253, -2333, -2413, -2477, -2542, -2574, -2607, -2622, -2655, 1314, 1313, 1298, 1312, 1282, 785, 785, 785, 785, 1040, 1040, 1025, 1025, 768, 768, 768, 768, -766, -798, -830, -862, -895, -911, -927, -943, -959, -975, -991, -1007, -1023, -1039, -1055, -1070, 1724, 1647, -1103, -1119, 1631, 1767, 1662, 1738, 1708, 1723, -1135, 1780, 1615, 1779, 1599, 1677, 1646, 1778, 1583, -1151, 1777, 1567, 1737, 1692, 1765, 1722, 1707, 1630, 1751, 1661, 1764, 1614, 1736, 1676, 1763, 1750, 1645, 1598, 1721, 1691, 1762, 1706, 1582, 1761, 1566, -1167, 1749, 1629, 767, 766, 751, 765, 494, 494, 735, 764, 719, 749, 734, 763, 447, 447, 748, 718, 477, 506, 431, 491, 446, 476, 461, 505, 415, 430, 475, 445, 504, 399, 460, 489, 414, 503, 383, 474, 429, 459, 502, 502, 746, 752, 488, 398, 501, 473, 413, 472, 486, 271, 480, 270, -1439, -1455, 1357, -1471, -1487, -1503, 1341, 1325, -1519, 1489, 1463, 1403, 1309, -1535, 1372, 1448, 1418, 1476, 1356, 1462, 1387, -1551, 1475, 1340, 1447, 1402, 1386, -1567, 1068, 1068, 1474, 1461, 455, 380, 468, 440, 395, 425, 410, 454, 364, 467, 466, 464, 453, 269, 409, 448, 268, 432, 1371, 1473, 1432, 1417, 1308, 1460, 1355, 1446, 1459, 1431, 1083, 1083, 1401, 1416, 1458, 1445, 1067, 1067, 1370, 1457, 1051, 1051, 1291, 1430, 1385, 1444, 1354, 1415, 1400, 1443, 1082, 1082, 1173, 1113, 1186, 1066, 1185, 1050, -1967, 1158, 1128, 1172, 1097, 1171, 1081, -1983, 1157, 1112, 416, 266, 375, 400, 1170, 1142, 1127, 1065, 793, 793, 1169, 1033, 1156, 1096, 1141, 1111, 1155, 1080, 1126, 1140, 898, 898, 808, 808, 897, 897, 792, 792, 1095, 1152, 1032, 1125, 1110, 1139, 1079, 1124, 882, 807, 838, 881, 853, 791, -2319, 867, 368, 263, 822, 852, 837, 866, 806, 865, -2399, 851, 352, 262, 534, 534, 821, 836, 594, 594, 549, 549, 593, 593, 533, 533, 848, 773, 579, 579, 564, 578, 548, 563, 276, 276, 577, 576, 306, 291, 516, 560, 305, 305, 275, 259, -251, -892, -2058, -2620, -2828, -2957, -3023, -3039, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -511, -527, -543, -559, 1530, -575, -591, 1528, 1527, 1407, 1526, 1391, 1023, 1023, 1023, 1023, 1525, 1375, 1268, 1268, 1103, 1103, 1087, 1087, 1039, 1039, 1523, -604, 815, 815, 815, 815, 510, 495, 509, 479, 508, 463, 507, 447, 431, 505, 415, 399, -734, -782, 1262, -815, 1259, 1244, -831, 1258, 1228, -847, -863, 1196, -879, 1253, 987, 987, 748, -767, 493, 493, 462, 477, 414, 414, 686, 669, 478, 446, 461, 445, 474, 429, 487, 458, 412, 471, 1266, 1264, 1009, 1009, 799, 799, -1019, -1276, -1452, -1581, -1677, -1757, -1821, -1886, -1933, -1997, 1257, 1257, 1483, 1468, 1512, 1422, 1497, 1406, 1467, 1496, 1421, 1510, 1134, 1134, 1225, 1225, 1466, 1451, 1374, 1405, 1252, 1252, 1358, 1480, 1164, 1164, 1251, 1251, 1238, 1238, 1389, 1465, -1407, 1054, 1101, -1423, 1207, -1439, 830, 830, 1248, 1038, 1237, 1117, 1223, 1148, 1236, 1208, 411, 426, 395, 410, 379, 269, 1193, 1222, 1132, 1235, 1221, 1116, 976, 976, 1192, 1162, 1177, 1220, 1131, 1191, 963, 963, -1647, 961, 780, -1663, 558, 558, 994, 993, 437, 408, 393, 407, 829, 978, 813, 797, 947, -1743, 721, 721, 377, 392, 844, 950, 828, 890, 706, 706, 812, 859, 796, 960, 948, 843, 934, 874, 571, 571, -1919, 690, 555, 689, 421, 346, 539, 539, 944, 779, 918, 873, 932, 842, 903, 888, 570, 570, 931, 917, 674, 674, -2575, 1562, -2591, 1609, -2607, 1654, 1322, 1322, 1441, 1441, 1696, 1546, 1683, 1593, 1669, 1624, 1426, 1426, 1321, 1321, 1639, 1680, 1425, 1425, 1305, 1305, 1545, 1668, 1608, 1623, 1667, 1592, 1638, 1666, 1320, 1320, 1652, 1607, 1409, 1409, 1304, 1304, 1288, 1288, 1664, 1637, 1395, 1395, 1335, 1335, 1622, 1636, 1394, 1394, 1319, 1319, 1606, 1621, 1392, 1392, 1137, 1137, 1137, 1137, 345, 390, 360, 375, 404, 373, 1047, -2751, -2767, -2783, 1062, 1121, 1046, -2799, 1077, -2815, 1106, 1061, 789, 789, 1105, 1104, 263, 355, 310, 340, 325, 354, 352, 262, 339, 324, 1091, 1076, 1029, 1090, 1060, 1075, 833, 833, 788, 788, 1088, 1028, 818, 818, 803, 803, 561, 561, 531, 531, 816, 771, 546, 546, 289, 274, 288, 258, -253, -317, -381, -446, -478, -509, 1279, 1279, -811, -1179, -1451, -1756, -1900, -2028, -2189, -2253, -2333, -2414, -2445, -2511, -2526, 1313, 1298, -2559, 1041, 1041, 1040, 1040, 1025, 1025, 1024, 1024, 1022, 1007, 1021, 991, 1020, 975, 1019, 959, 687, 687, 1018, 1017, 671, 671, 655, 655, 1016, 1015, 639, 639, 758, 758, 623, 623, 757, 607, 756, 591, 755, 575, 754, 559, 543, 543, 1009, 783, -575, -621, -685, -749, 496, -590, 750, 749, 734, 748, 974, 989, 1003, 958, 988, 973, 1002, 942, 987, 957, 972, 1001, 926, 986, 941, 971, 956, 1000, 910, 985, 925, 999, 894, 970, -1071, -1087, -1102, 1390, -1135, 1436, 1509, 1451, 1374, -1151, 1405, 1358, 1480, 1420, -1167, 1507, 1494, 1389, 1342, 1465, 1435, 1450, 1326, 1505, 1310, 1493, 1373, 1479, 1404, 1492, 1464, 1419, 428, 443, 472, 397, 736, 526, 464, 464, 486, 457, 442, 471, 484, 482, 1357, 1449, 1434, 1478, 1388, 1491, 1341, 1490, 1325, 1489, 1463, 1403, 1309, 1477, 1372, 1448, 1418, 1433, 1476, 1356, 1462, 1387, -1439, 1475, 1340, 1447, 1402, 1474, 1324, 1461, 1371, 1473, 269, 448, 1432, 1417, 1308, 1460, -1711, 1459, -1727, 1441, 1099, 1099, 1446, 1386, 1431, 1401, -1743, 1289, 1083, 1083, 1160, 1160, 1458, 1445, 1067, 1067, 1370, 1457, 1307, 1430, 1129, 1129, 1098, 1098, 268, 432, 267, 416, 266, 400, -1887, 1144, 1187, 1082, 1173, 1113, 1186, 1066, 1050, 1158, 1128, 1143, 1172, 1097, 1171, 1081, 420, 391, 1157, 1112, 1170, 1142, 1127, 1065, 1169, 1049, 1156, 1096, 1141, 1111, 1155, 1080, 1126, 1154, 1064, 1153, 1140, 1095, 1048, -2159, 1125, 1110, 1137, -2175, 823, 823, 1139, 1138, 807, 807, 384, 264, 368, 263, 868, 838, 853, 791, 867, 822, 852, 837, 866, 806, 865, 790, -2319, 851, 821, 836, 352, 262, 850, 805, 849, -2399, 533, 533, 835, 820, 336, 261, 578, 548, 563, 577, 532, 532, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290, 290, 288, 258, } T.tab32 = { [0] = 130, 162, 193, 209, 44, 28, 76, 140, 9, 9, 9, 9, 9, 9, 9, 9, 190, 254, 222, 238, 126, 94, 157, 157, 109, 61, 173, 205, } T.tab33 = { [0] = 252, 236, 220, 204, 188, 172, 156, 140, 124, 108, 92, 76, 60, 44, 28, 12, } T.tabindex = { [0] = 0, 32, 64, 98, 0, 132, 180, 218, 292, 364, 426, 538, 648, 746, 0, 1126, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1842, 1842, 1842, 1842, 1842, 1842, 1842, 1842, } T.g_linbits = { [0] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, 5, 6, 7, 8, 9, 11, 13, } T.g_pan = { [0] = 0, 1, 0.21132487, 0.78867513, 0.36602540, 0.63397460, 0.5, 0.5, 0.63397460, 0.36602540, 0.78867513, 0.21132487, 1, 0, } T.g_aa = { [0] = 0.85749293, 0.88174200, 0.94962865, 0.98331459, 0.99551782, 0.99916056, 0.99989920, 0.99999316, 0.51449576, 0.47173197, 0.31337745, 0.18191320, 0.09457419, 0.04096558, 0.01419856, 0.00369997, } T.g_twid9 = { [0] = 0.73727734, 0.79335334, 0.84339145, 0.88701083, 0.92387953, 0.95371695, 0.97629601, 0.99144486, 0.99904822, 0.67559021, 0.60876143, 0.53729961, 0.46174861, 0.38268343, 0.30070580, 0.21643961, 0.13052619, 0.04361938, } T.g_twid3 = { [0] = 0.79335334, 0.92387953, 0.99144486, 0.60876143, 0.38268343, 0.13052619, } T.g_mdct_window = { [0] = 0.99904822, 0.99144486, 0.97629601, 0.95371695, 0.92387953, 0.88701083, 0.84339145, 0.79335334, 0.73727734, 0.04361938, 0.13052619, 0.21643961, 0.30070580, 0.38268343, 0.46174861, 0.53729961, 0.60876143, 0.67559021, 1, 1, 1, 1, 1, 1, 0.99144486, 0.92387953, 0.79335334, 0, 0, 0, 0, 0, 0, 0.13052619, 0.38268343, 0.60876143, } T.g_sec = { [0] = 10.19000816, 0.50060302, 0.50241929, 3.40760851, 0.50547093, 0.52249861, 2.05778098, 0.51544732, 0.56694406, 1.48416460, 0.53104258, 0.64682180, 1.16943991, 0.55310392, 0.78815460, 0.97256821, 0.58293498, 1.06067765, 0.83934963, 0.62250412, 1.72244716, 0.74453628, 0.67480832, 5.10114861, } T.g_win = { [0] = -1, 26, -31, 208, 218, 401, -519, 2063, 2000, 4788, -5517, 7134, 5959, 35640, -39336, 74992, -1, 24, -35, 202, 222, 347, -581, 2080, 1952, 4425, -5879, 7640, 5288, 33791, -41176, 74856, -1, 21, -38, 196, 225, 294, -645, 2087, 1893, 4063, -6237, 8092, 4561, 31947, -43006, 74630, -1, 19, -41, 190, 227, 244, -711, 2085, 1822, 3705, -6589, 8492, 3776, 30112, -44821, 74313, -1, 17, -45, 183, 228, 197, -779, 2075, 1739, 3351, -6935, 8840, 2935, 28289, -46617, 73908, -1, 16, -49, 176, 228, 153, -848, 2057, 1644, 3004, -7271, 9139, 2037, 26482, -48390, 73415, -2, 14, -53, 169, 227, 111, -919, 2032, 1535, 2663, -7597, 9389, 1082, 24694, -50137, 72835, -2, 13, -58, 161, 224, 72, -991, 2001, 1414, 2330, -7910, 9592, 70, 22929, -51853, 72169, -2, 11, -63, 154, 221, 36, -1064, 1962, 1280, 2006, -8209, 9750, -998, 21189, -53534, 71420, -2, 10, -68, 147, 215, 2, -1137, 1919, 1131, 1692, -8491, 9863, -2122, 19478, -55178, 70590, -3, 9, -73, 139, 208, -29, -1210, 1870, 970, 1388, -8755, 9935, -3300, 17799, -56778, 69679, -3, 8, -79, 132, 200, -57, -1283, 1817, 794, 1095, -8998, 9966, -4533, 16155, -58333, 68692, -4, 7, -85, 125, 189, -83, -1356, 1759, 605, 814, -9219, 9959, -5818, 14548, -59838, 67629, -4, 7, -91, 117, 177, -106, -1428, 1698, 402, 545, -9416, 9916, -7154, 12980, -61289, 66494, -5, 6, -97, 111, 163, -127, -1498, 1634, 185, 288, -9585, 9838, -8540, 11455, -62684, 65290, } return T end __FILES["codecs/audio/Musepack"] = function() -- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8. -- A port of libmpcdec (musepack_src_r475: mpc_demux.c, streaminfo.c, mpc_decoder.c; BSD-3-Clause, (c) The Musepack -- Development Team, licenses/libmpcdec-BSD.txt), gapless like libmpcdec. SV4 - SV6 are UNSUPPORTED. local Err = __include("core/Err") local Crc32 = __include("core/Crc32") local Decode = __include("codecs/audio/Musepack/Decode") local Musepack = {} local RATES = { 44100, 48000, 37800, 32000 } local FRAME, DELAY, PAD = Decode.FRAME, Decode.DELAY, Decode.PAD local readu8 = buffer.readu8 type Stream = { version: number, sampleRate: number, channels: number, frames: number, maxBand: number, ms: boolean, profile: number, -- SV7: the profile index (7 telephone .. 13 braindead); SV8: the quality (0 .. 15.875) encoder: number, -- encoder version (SV7: one byte; SV8: major * 2^24 + minor * 2^16 + build * 2^8) gapless: boolean, pns: boolean?, gain: { titleGain: number, titlePeak: number, albumGain: number, albumPeak: number }?, blockFrames: number, -- frames per packet (SV7: 1; SV8: 2^block_pwr) bytes: number, count: number, start: (i: number) -> number, decode: (i: number) -> (number?, Err.Err?), pcm: () -> { number }, reset: () -> (), skip: number, stop: number, preroll: number, } -- SV7 reads the stream as little-endian 32-bit words, most significant bit first: swap them into a padded copy local function swapped(buf: buffer, p: number, limit: number): buffer local n = limit - p local words = (n + 3) // 4 local out = buffer.create(words * 4 + PAD) buffer.copy(out, 0, buf, p, n) for i = 0, words - 1 do buffer.writeu32(out, i * 4, bit32.byteswap(buffer.readu32(out, i * 4))) end return out end local function sv7(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) if limit - start < 32 then return nil, Err.new(Err.TRUNCATED, "SV7 header", start) end local ver = bit32.band(readu8(buf, start + 3), 15) if ver ~= 7 then return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. ver .. " (SV7 and SV8 only)", start) end local s = swapped(buf, start + 4, limit) local totalBits = (limit - start - 4) * 8 local at = Decode.bitsAt local frames = at(s, 0, 16) * 65536 + at(s, 16, 16) local ms = at(s, 33, 1) == 1 local maxBand = at(s, 34, 6) local profile = at(s, 40, 4) local rate = RATES[at(s, 46, 2) + 1] local gainTitle, peakTitle = at(s, 64, 16), at(s, 80, 16) local gainAlbum, peakAlbum = at(s, 96, 16), at(s, 112, 16) local gapless = at(s, 128, 1) == 1 local last = at(s, 129, 11) local encoder = at(s, 160, 8) if maxBand == 0 or maxBand >= 32 then return nil, Err.new(Err.CORRUPT, "bad band count " .. maxBand, start) end if last == 0 then last = FRAME elseif last > FRAME then return nil, Err.new(Err.CORRUPT, "bad last frame length", start) end if frames == 0 then return nil, Err.new(Err.CORRUPT, "no frames", start) end if frames > 2 ^ 24 then return nil, Err.new(Err.LIMIT, "more than 2^24 frames", start) end local samples = frames * FRAME - (if gapless then FRAME - last else DELAY) -- the frame index: a 20-bit size in front of each frame (the last one has 11 more bits: its length) local offs: { number }, sizes: { number } = {}, {} local pos = 168 for i = 1, frames do if pos + 20 > totalBits then break end local size = at(s, pos, 20) local stop = pos + 20 + size + (if i == frames then 11 else 0) if stop > totalBits then break end offs[i], sizes[i] = pos + 20, size pos = stop end local have = #offs if have == 0 then return nil, Err.new(Err.TRUNCATED, "no complete frame", start) end -- frames past the stream (a truncated file, or the synthesis tail of a gapless stream) decode as silence local need = math.min((samples + DELAY + FRAME - 1) // FRAME, have + 1) local stopAt = math.min(samples + DELAY, have * FRAME + (if have < frames then 0 else FRAME)) local st = Decode.state(7, maxBand, ms, 2) local pcm = table.create(FRAME * 2, 0) local prev = 0 local out: Stream = { version = 7, sampleRate = rate, channels = 2, frames = math.max(0, stopAt - DELAY), maxBand = maxBand, ms = ms, profile = profile, encoder = encoder, gapless = gapless, gain = { titleGain = gainTitle, titlePeak = peakTitle, albumGain = gainAlbum, albumPeak = peakAlbum }, blockFrames = 1, bytes = limit - start, count = need, start = function(i: number): number return (i - 1) * FRAME end, decode = function(i: number): (number?, Err.Err?) if i ~= prev + 1 then Decode.reset(st, if i == 1 then 0 else 0x01010101) end prev = i local o: number? = offs[i] if o == nil then Decode.frame(st, s, -1, 0, false, pcm, 1) return FRAME, nil end local e, msg = Decode.frame(st, s, o, o + sizes[i], false, pcm, 1) if not e then return nil, Err.from(msg, start + 4 + o // 8) end if e ~= o + sizes[i] then return nil, Err.new(Err.CORRUPT, "frame " .. i .. " has the wrong size", start + 4 + o // 8) end return FRAME, nil end, pcm = function(): { number } return pcm end, reset = function() prev = -1 end, skip = DELAY, stop = stopAt, preroll = 32, } return out, nil end -- a packet size: 7 bits per byte, most significant first, bit 7 = more local function varint(buf: buffer, p: number, limit: number): (number, number) local v = 0 for k = 0, 7 do if p + k >= limit then return -1, p end local b = readu8(buf, p + k) v = v * 128 + bit32.band(b, 127) if b < 128 then return v, p + k + 1 end end return -1, p end local function sv8(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) local p = start + 4 local sh: { [string]: any }? = nil local gain, pns, profile, encoder = nil, nil, 0, 0 local apOff: { number }, apSize: { number } = {}, {} while p + 2 < limit do local k1, k2 = readu8(buf, p), readu8(buf, p + 1) if k1 < 65 or k1 > 90 or k2 < 65 or k2 > 90 then return nil, Err.new(Err.CORRUPT, "bad packet key", p) end local key = buffer.readstring(buf, p, 2) local size, body = varint(buf, p + 2, limit) if size < 0 or size < body - p then return nil, Err.new(Err.CORRUPT, "bad packet size", p) end local stop = p + size if stop > limit then if key == "AP" then break end return nil, Err.new(Err.TRUNCATED, key .. " packet", p) end if key == "SH" then if stop - body < 6 then return nil, Err.new(Err.CORRUPT, "short stream header", p) end local crc = buffer.readu32(buf, body) crc = bit32.byteswap(crc) if Crc32.of(buf, body + 4, stop - body - 4) ~= crc then return nil, Err.new(Err.CHECKSUM, "stream header CRC", p) end if readu8(buf, body + 4) ~= 8 then return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. readu8(buf, body + 4), p) end local samples, q = varint(buf, body + 5, stop) local silence, q2 = varint(buf, q, stop) if samples < 0 or silence < 0 or q2 + 2 > stop then return nil, Err.new(Err.CORRUPT, "bad stream header", p) end local b0, b1 = readu8(buf, q2), readu8(buf, q2 + 1) sh = { samples = samples, silence = silence, rate = RATES[bit32.rshift(b0, 5) + 1], maxBand = bit32.band(b0, 31) + 1, channels = bit32.rshift(b1, 4) + 1, ms = bit32.band(b1, 8) ~= 0, blockPwr = bit32.band(b1, 7) * 2, } elseif key == "RG" and stop - body >= 9 and readu8(buf, body) == 1 then local function u16(o: number): number return readu8(buf, body + o) * 256 + readu8(buf, body + o + 1) end gain = { titleGain = u16(1), titlePeak = u16(3), albumGain = u16(5), albumPeak = u16(7) } elseif key == "EI" and stop - body >= 4 then local b = readu8(buf, body) profile = bit32.rshift(b, 1) / 8 pns = bit32.band(b, 1) == 1 encoder = readu8(buf, body + 1) * 2 ^ 24 + readu8(buf, body + 2) * 2 ^ 16 + readu8(buf, body + 3) * 2 ^ 8 elseif key == "AP" then table.insert(apOff, body) table.insert(apSize, stop - body) elseif key == "SE" then break end p = stop end if not sh then return nil, Err.new(Err.CORRUPT, "no stream header", start) end local h = sh :: { [string]: any } local samples, silence, maxBand, channels = h.samples, h.silence, h.maxBand, h.channels if maxBand >= 32 or channels > 2 or silence > samples then return nil, Err.new(Err.UNSUPPORTED, string.format("%d bands, %d channels", maxBand, channels), start) end if samples > 2 ^ 34 then return nil, Err.new(Err.LIMIT, "too many samples", start) end if #apOff == 0 then return nil, Err.new(Err.CORRUPT, "no audio packet", start) end local per = 2 ^ h.blockPwr if per * FRAME * channels > 2 ^ 22 then return nil, Err.new(Err.LIMIT, per .. " frames per audio packet", start) end local needFrames = (samples + DELAY + FRAME - 1) // FRAME local count = math.min(#apOff, (needFrames + per - 1) // per) local stopAt = math.min(samples + DELAY, count * per * FRAME) local st = Decode.state(8, maxBand, h.ms, channels) local pcm = table.create(per * FRAME * channels, 0) local scratch = buffer.create(0) local out: Stream = { version = 8, sampleRate = h.rate, channels = channels, frames = math.max(0, stopAt - DELAY - silence), maxBand = maxBand, ms = h.ms, profile = profile, encoder = encoder, gapless = true, pns = pns, gain = gain, blockFrames = per, bytes = limit - start, count = count, start = function(i: number): number return (i - 1) * per * FRAME end, decode = function(i: number): (number?, Err.Err?) local o: number, size: number = apOff[i], apSize[i] if buffer.len(scratch) < size + PAD then scratch = buffer.create(size + PAD) end buffer.copy(scratch, 0, buf, o, size) local nf = math.min(per, needFrames - (i - 1) * per) local pos = 0 for f = 1, nf do local e, msg = Decode.frame(st, scratch, pos, size * 8, f == 1, pcm, (f - 1) * FRAME * channels + 1) if not e then return nil, Err.from(msg, o) end pos = e end if nf == per and size * 8 - pos > 7 then return nil, Err.new(Err.CORRUPT, "audio packet " .. i .. " has unused data", o) end return nf * FRAME, nil end, pcm = function(): { number } return pcm end, reset = function() Decode.reset(st, 0) end, skip = DELAY + silence, stop = stopAt, preroll = 1, } return out, nil end function Musepack.magic(buf: buffer, p: number, limit: number): number if p + 4 > limit then return 0 end local m = buffer.readstring(buf, p, 4) if m == "MPCK" then return 8 end if string.sub(m, 1, 3) == "MP+" then return 7 end return 0 end function Musepack.open(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) local v = Musepack.magic(buf, start, limit) if v == 8 then return sv8(buf, start, limit) elseif v == 7 then return sv7(buf, start, limit) end return nil, Err.new(Err.CORRUPT, "not a Musepack stream", start) end return Musepack end __FILES["codecs/audio/Musepack/Decode"] = @native function() -- codecs/audio/Musepack/Decode: one Musepack SV7 / SV8 frame (1152 samples per channel). -- A line-by-line port of libmpcdec's mpc_decoder.c, requant.c and synth_filter.c (musepack_src_r475, BSD-3-Clause, (c) The -- Musepack Development Team, licenses/libmpcdec-BSD.txt). The caller pads the buffer by PAD bytes past `limit`. local T = __include("codecs/audio/Musepack/Tables") local readu32, bswap, extract, band, bor, rshift, lshift, bnot, bxor = buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.bnot, bit32.bxor local abs = math.abs local Decode = {} Decode.PAD = 8192 Decode.DELAY = 481 -- MPC_DECODER_SYNTH_DELAY Decode.FRAME = 1152 local L = T.lut local HDR, SCFI7, DSCF7 = L(T.HuffHdr), L(T.HuffSCFI), L(T.HuffDSCF) local Q7: { { T.Lut } } = { { L(T.HuffQ1_0), L(T.HuffQ1_1) }, { L(T.HuffQ2_0), L(T.HuffQ2_1) }, { L(T.HuffQ3_0), L(T.HuffQ3_1) }, { L(T.HuffQ4_0), L(T.HuffQ4_1) }, { L(T.HuffQ5_0), L(T.HuffQ5_1) }, { L(T.HuffQ6_0), L(T.HuffQ6_1) }, { L(T.HuffQ7_0), L(T.HuffQ7_1) }, } local BANDS8 = L(T.H_Bands, T.S_Bands) local SCFI8 = { L(T.H_SCFI_1, T.S_SCFI_1), L(T.H_SCFI_2, T.S_SCFI_2) } local DSCF8 = { L(T.H_DSCF_1, T.S_DSCF_1), L(T.H_DSCF_2, T.S_DSCF_2) } local RES8 = { L(T.H_Res_1, T.S_Res_1), L(T.H_Res_2, T.S_Res_2) } local Q1_8 = L(T.H_Q1, T.S_Q1) local Q9UP = L(T.H_Q9up, T.S_Q9up) -- mpc_can_Q[res - 2][0 / 1] for res 2 and 5 .. 8; res 3 / 4 use Q34[res - 2] local Q8: { [number]: { T.Lut } } = { [2] = { L(T.H_Q2_1, T.S_Q2_1), L(T.H_Q2_2, T.S_Q2_2) }, [5] = { L(T.H_Q5_1, T.S_Q5_1), L(T.H_Q5_2, T.S_Q5_2) }, [6] = { L(T.H_Q6_1, T.S_Q6_1), L(T.H_Q6_2, T.S_Q6_2) }, [7] = { L(T.H_Q7_1, T.S_Q7_1), L(T.H_Q7_2, T.S_Q7_2) }, [8] = { L(T.H_Q8_1, T.S_Q8_1), L(T.H_Q8_2, T.S_Q8_2) }, } local Q34 = { L(T.H_Q3, T.S_Q3), L(T.H_Q4, T.S_Q4) } local THRES = { [2] = 3, [5] = 1, [6] = 3, [7] = 4, [8] = 8 } local CC, DC, RES_BIT = T.CC, T.DC, T.RES_BIT local CNK, CNK_LEN, CNK_LOST, LOG2, LOG2_LOST = T.CNK, T.CNK_LEN, T.CNK_LOST, T.LOG2, T.LOG2_LOST -- the f32 rounding of the C tables (libmpcdec decodes in single precision) local F32 = buffer.create(4) @native local function f32(x: number): number buffer.writef32(F32, 0, x) return buffer.readf32(F32, 0) end for i, v in CC do CC[i] = f32(v) end -- SCF[i]: the scalefactor of index i (0 .. 255, the index's low byte): 2^-15 * 0.83298...^(s - 1), s = i as int8 -- (libmpcdec's mpc_decoder_scale_output in float mode: 1 dB steps, the table filled outwards from index 1) local SCF = table.create(256, 0) do local f1 = 1 / 32768 local f2 = f1 SCF[2] = f32(f1) f1 *= 0.83298066476582673961 f2 *= 1 / 0.83298066476582673961 for n = 1, 128 do SCF[band(1 + n, 255) + 1] = f32(f1) SCF[band(1 - n, 255) + 1] = f32(f2) f1 *= 0.83298066476582673961 f2 *= 1 / 0.83298066476582673961 end end -- the synthesis window D (Di_opt / 65536), 32 x 16, row-major local DW = table.create(512, 0) for i, v in T.DI do DW[i] = f32(v / 65536) end local B: buffer = buffer.create(0) local P = 0 @native local function bits(n: number): number if n <= 0 then return 0 end if n > 24 then local hi = bits(n - 16) return hi * 65536 + bits(16) end local w = bswap(readu32(B, rshift(P, 3))) local v = extract(w, 32 - band(P, 7) - n, n) P += n return v end @native local function peek16(): number local w = bswap(readu32(B, rshift(P, 3))) return extract(w, 16 - band(P, 7), 16) end @native local function huff(t: T.Lut): number local code = peek16() local k = rshift(code, 8) + 1 local n = t.len[k] if n > 0 then P += n return t.val[k] end local j = t.val[k] local codes = t.codes while code < codes[j] do j += 1 end n = t.lens[j] P += n local sym = t.sym if sym then return sym[band(t.vals[j] - rshift(code, 16 - n), 255) + 1] or 0 end return t.vals[j] end -- mpc_bits_log_dec: 0 .. max @native local function logDec(max: number): number if max <= 0 then return 0 end local v = 0 local len, lost = LOG2[max], LOG2_LOST[max] if len > 1 then v = bits(len - 1) end if v >= lost then v = v * 2 + bits(1) - lost end return v end -- mpc_bits_enum_dec: an n-bit word with k bits set @native local function enumDec(k: number, n: number): number local out = 0 local code = bits(CNK_LEN[k][n] - 1) local lost = CNK_LOST[k][n] if code >= lost then code = code * 2 + bits(1) - lost end repeat n -= 1 local c = CNK[k][n + 1] if code >= c then out = bor(out, lshift(1, n)) code -= c k -= 1 end until k <= 0 or n <= 0 return out end -- mpc_random_int: two polynomial counters, XORed local PARITY = table.create(256, 0) for i = 0, 255 do local p, v = 0, i while v > 0 do p = bxor(p, band(v, 1)) v = rshift(v, 1) end PARITY[i + 1] = p end -- mpc_compute_new_V: 32 subband samples Y[y .. y + 31] -> 64 V values at V[o .. o + 63] (the ISO 11172-3 matrixing -- through Byeong Gi Lee's fast DCT) @native local function newV(Y: { number }, y: number, V: { number }, o: number) local A00 = Y[y] + Y[y + 31] local A01 = Y[y + 1] + Y[y + 30] local A02 = Y[y + 2] + Y[y + 29] local A03 = Y[y + 3] + Y[y + 28] local A04 = Y[y + 4] + Y[y + 27] local A05 = Y[y + 5] + Y[y + 26] local A06 = Y[y + 6] + Y[y + 25] local A07 = Y[y + 7] + Y[y + 24] local A08 = Y[y + 8] + Y[y + 23] local A09 = Y[y + 9] + Y[y + 22] local A10 = Y[y + 10] + Y[y + 21] local A11 = Y[y + 11] + Y[y + 20] local A12 = Y[y + 12] + Y[y + 19] local A13 = Y[y + 13] + Y[y + 18] local A14 = Y[y + 14] + Y[y + 17] local A15 = Y[y + 15] + Y[y + 16] local B00 = A00 + A15 local B01 = A01 + A14 local B02 = A02 + A13 local B03 = A03 + A12 local B04 = A04 + A11 local B05 = A05 + A10 local B06 = A06 + A09 local B07 = A07 + A08 local B08 = (A00 - A15) * 0.5024192929 local B09 = (A01 - A14) * 0.5224986076 local B10 = (A02 - A13) * 0.5669440627 local B11 = (A03 - A12) * 0.6468217969 local B12 = (A04 - A11) * 0.7881546021 local B13 = (A05 - A10) * 1.0606776476 local B14 = (A06 - A09) * 1.7224471569 local B15 = (A07 - A08) * 5.1011486053 A00 = B00 + B07 A01 = B01 + B06 A02 = B02 + B05 A03 = B03 + B04 A04 = (B00 - B07) * 0.5097956061 A05 = (B01 - B06) * 0.6013448834 A06 = (B02 - B05) * 0.8999761939 A07 = (B03 - B04) * 2.5629155636 A08 = B08 + B15 A09 = B09 + B14 A10 = B10 + B13 A11 = B11 + B12 A12 = (B08 - B15) * 0.5097956061 A13 = (B09 - B14) * 0.6013448834 A14 = (B10 - B13) * 0.8999761939 A15 = (B11 - B12) * 2.5629155636 B00 = A00 + A03 B01 = A01 + A02 B02 = (A00 - A03) * 0.5411961079 B03 = (A01 - A02) * 1.3065630198 B04 = A04 + A07 B05 = A05 + A06 B06 = (A04 - A07) * 0.5411961079 B07 = (A05 - A06) * 1.3065630198 B08 = A08 + A11 B09 = A09 + A10 B10 = (A08 - A11) * 0.5411961079 B11 = (A09 - A10) * 1.3065630198 B12 = A12 + A15 B13 = A13 + A14 B14 = (A12 - A15) * 0.5411961079 B15 = (A13 - A14) * 1.3065630198 A00 = B00 + B01 A01 = (B00 - B01) * 0.7071067691 A02 = B02 + B03 A03 = (B02 - B03) * 0.7071067691 A04 = B04 + B05 A05 = (B04 - B05) * 0.7071067691 A06 = B06 + B07 A07 = (B06 - B07) * 0.7071067691 A08 = B08 + B09 A09 = (B08 - B09) * 0.7071067691 A10 = B10 + B11 A11 = (B10 - B11) * 0.7071067691 A12 = B12 + B13 A13 = (B12 - B13) * 0.7071067691 A14 = B14 + B15 A15 = (B14 - B15) * 0.7071067691 V[o + 48] = -A00 V[o] = A01 V[o + 8] = A03 V[o + 40] = -A02 - A03 V[o + 12] = A07 local t = A05 + A07 V[o + 4] = t V[o + 36] = -(t + A06) V[o + 44] = -A04 - A06 - A07 V[o + 14] = A15 t = A11 + A15 V[o + 10] = t V[o + 6] = t + A13 t = A09 + A13 + A15 V[o + 2] = t t = -t - A14 V[o + 34] = t V[o + 38] = t + A09 - A10 - A11 t = -(A12 + A14 + A15) V[o + 46] = t - A08 V[o + 42] = t - A10 - A11 A00 = (Y[y] - Y[y + 31]) * 0.5006030202 A01 = (Y[y + 1] - Y[y + 30]) * 0.5054709315 A02 = (Y[y + 2] - Y[y + 29]) * 0.5154473186 A03 = (Y[y + 3] - Y[y + 28]) * 0.5310425758 A04 = (Y[y + 4] - Y[y + 27]) * 0.5531039238 A05 = (Y[y + 5] - Y[y + 26]) * 0.5829349756 A06 = (Y[y + 6] - Y[y + 25]) * 0.6225041151 A07 = (Y[y + 7] - Y[y + 24]) * 0.6748083234 A08 = (Y[y + 8] - Y[y + 23]) * 0.7445362806 A09 = (Y[y + 9] - Y[y + 22]) * 0.8393496275 A10 = (Y[y + 10] - Y[y + 21]) * 0.9725682139 A11 = (Y[y + 11] - Y[y + 20]) * 1.1694399118 A12 = (Y[y + 12] - Y[y + 19]) * 1.4841645956 A13 = (Y[y + 13] - Y[y + 18]) * 2.0577809811 A14 = (Y[y + 14] - Y[y + 17]) * 3.4076085091 A15 = (Y[y + 15] - Y[y + 16]) * 10.1900081635 B00 = A00 + A15 B01 = A01 + A14 B02 = A02 + A13 B03 = A03 + A12 B04 = A04 + A11 B05 = A05 + A10 B06 = A06 + A09 B07 = A07 + A08 B08 = (A00 - A15) * 0.5024192929 B09 = (A01 - A14) * 0.5224986076 B10 = (A02 - A13) * 0.5669440627 B11 = (A03 - A12) * 0.6468217969 B12 = (A04 - A11) * 0.7881546021 B13 = (A05 - A10) * 1.0606776476 B14 = (A06 - A09) * 1.7224471569 B15 = (A07 - A08) * 5.1011486053 A00 = B00 + B07 A01 = B01 + B06 A02 = B02 + B05 A03 = B03 + B04 A04 = (B00 - B07) * 0.5097956061 A05 = (B01 - B06) * 0.6013448834 A06 = (B02 - B05) * 0.8999761939 A07 = (B03 - B04) * 2.5629155636 A08 = B08 + B15 A09 = B09 + B14 A10 = B10 + B13 A11 = B11 + B12 A12 = (B08 - B15) * 0.5097956061 A13 = (B09 - B14) * 0.6013448834 A14 = (B10 - B13) * 0.8999761939 A15 = (B11 - B12) * 2.5629155636 B00 = A00 + A03 B01 = A01 + A02 B02 = (A00 - A03) * 0.5411961079 B03 = (A01 - A02) * 1.3065630198 B04 = A04 + A07 B05 = A05 + A06 B06 = (A04 - A07) * 0.5411961079 B07 = (A05 - A06) * 1.3065630198 B08 = A08 + A11 B09 = A09 + A10 B10 = (A08 - A11) * 0.5411961079 B11 = (A09 - A10) * 1.3065630198 B12 = A12 + A15 B13 = A13 + A14 B14 = (A12 - A15) * 0.5411961079 B15 = (A13 - A14) * 1.3065630198 A00 = (B00 + B01) A01 = (B00 - B01) * 0.7071067691 A02 = (B02 + B03) A03 = (B02 - B03) * 0.7071067691 A04 = (B04 + B05) A05 = (B04 - B05) * 0.7071067691 A06 = (B06 + B07) A07 = (B06 - B07) * 0.7071067691 A08 = (B08 + B09) A09 = (B08 - B09) * 0.7071067691 A10 = (B10 + B11) A11 = (B10 - B11) * 0.7071067691 A12 = (B12 + B13) A13 = (B12 - B13) * 0.7071067691 A14 = (B14 + B15) A15 = (B14 - B15) * 0.7071067691 V[o + 15] = A15 t = A07 + A15 V[o + 13] = t t += A11 V[o + 11] = t V[o + 5] = t + A05 + A13 t = A03 + A11 + A15 V[o + 9] = t V[o + 7] = t + A13 t = A01 + A09 + A13 + A15 V[o + 1] = t V[o + 33] = -t - A14 t = A05 + A07 + A09 + A13 + A15 V[o + 3] = t V[o + 35] = -t - A06 - A14 t = -(A10 + A11 + A13 + A14 + A15) V[o + 37] = t - A05 - A06 - A07 V[o + 39] = t - A02 - A03 t += A13 - A12 V[o + 41] = t - A02 - A03 V[o + 43] = t - A04 - A06 - A07 t = -(A08 + A12 + A14 + A15) V[o + 47] = t - A00 V[o + 45] = t - A04 - A06 - A07 for i = 0, 15 do V[o + 32 - i] = -V[o + i] end for i = 33, 47 do V[o + 96 - i] = V[o + i] end end type State = { version: number, maxBand: number, ms: boolean, channels: number, resL: { number }, resR: { number }, scfL: { number }, scfR: { number }, scfiL: { number }, scfiR: { number }, dscfL: { boolean }, dscfR: { boolean }, msf: { boolean }, qL: { number }, qR: { number }, yL: { number }, yR: { number }, vL: { number }, vR: { number }, r1: number, r2: number, lastMaxBand: number, } @native function Decode.state(version: number, maxBand: number, ms: boolean, channels: number): State local st: State = { version = version, maxBand = maxBand, ms = ms, channels = channels, resL = table.create(33, 0), resR = table.create(33, 0), scfL = table.create(99, 0), scfR = table.create(99, 0), scfiL = table.create(33, 0), scfiR = table.create(33, 0), dscfL = table.create(33, false), dscfR = table.create(33, false), msf = table.create(33, false), qL = table.create(32 * 36, 0), qR = table.create(32 * 36, 0), yL = table.create(36 * 32, 0), yR = table.create(36 * 32, 0), vL = table.create(2304 + 960, 0), vR = table.create(2304 + 960, 0), r1 = 1, r2 = 1, lastMaxBand = 0, } return st end -- libmpcdec assumes scf 0 at the stream start, 0x01010101 mid-SV7; the noise generator restarts, as in a fresh stream @native function Decode.reset(st: State, scf: number) for i = 1, 99 do st.scfL[i] = scf st.scfR[i] = scf end for i = 1, 33 do st.resL[i], st.resR[i] = 0, 0 st.dscfL[i], st.dscfR[i] = false, false st.msf[i] = false end for i = 1, 2304 + 960 do st.vL[i], st.vR[i] = 0, 0 end st.lastMaxBand = 0 st.r1, st.r2 = 1, 1 end @native local function noise(st: State, q: { number }, o: number) local r1, r2 = st.r1, st.r2 for k = 0, 35 do local t1 = PARITY[band(r1, 0xF5) + 1] local t2 = PARITY[band(rshift(r2, 25), 0x63) + 1] r1 = bor(rshift(r1, 1), lshift(t1, 31)) r2 = bor(band(lshift(r2, 1), 0xFFFFFFFF), t2) local t = bxor(r1, r2) q[o + k] = band(rshift(t, 24), 255) + band(rshift(t, 16), 255) + band(rshift(t, 8), 255) + band(t, 255) - 510 end st.r1, st.r2 = r1, r2 end -- mpc_decoder_read_bitstream_sv7 @native local function readSv7(st: State, limit: number): (boolean?, string?) local resL, resR, msf = st.resL, st.resR, st.msf local maxUsed = 0 local ms = st.ms resL[1] = bits(4) resR[1] = bits(4) if resL[1] ~= 0 or resR[1] ~= 0 then if ms then msf[1] = bits(1) == 1 end maxUsed = 1 end for n = 1, st.maxBand do local idx = huff(HDR) resL[n + 1] = if idx ~= 4 then resL[n] + idx else bits(4) idx = huff(HDR) resR[n + 1] = if idx ~= 4 then resR[n] + idx else bits(4) local l, r = resL[n + 1], resR[n + 1] if l < -1 or l > 17 or r < -1 or r > 17 then return nil, "bad band resolution" end if l ~= 0 or r ~= 0 then if ms then msf[n + 1] = bits(1) == 1 end maxUsed = n + 1 end end if resL[1] > 17 or resR[1] > 17 then return nil, "bad band resolution" end -- SCFI local scfiL, scfiR = st.scfiL, st.scfiR for n = 1, maxUsed do if resL[n] ~= 0 then scfiL[n] = huff(SCFI7) end if resR[n] ~= 0 then scfiR[n] = huff(SCFI7) end end if P > limit then return nil, "truncated frame" end -- SCF / DSCF for n = 1, maxUsed do for c = 1, 2 do local res = if c == 1 then resL[n] else resR[n] if res ~= 0 then local scf = if c == 1 then st.scfL else st.scfR local scfi = if c == 1 then scfiL[n] else scfiR[n] local o = (n - 1) * 3 local idx = huff(DSCF7) local s0 = if idx ~= 8 then scf[o + 3] + idx else bits(6) local s1, s2 if scfi == 1 then idx = huff(DSCF7) s1 = if idx ~= 8 then s0 + idx else bits(6) s2 = s1 elseif scfi == 3 then s1, s2 = s0, s0 elseif scfi == 2 then s1 = s0 idx = huff(DSCF7) s2 = if idx ~= 8 then s1 + idx else bits(6) else idx = huff(DSCF7) s1 = if idx ~= 8 then s0 + idx else bits(6) idx = huff(DSCF7) s2 = if idx ~= 8 then s1 + idx else bits(6) end scf[o + 1] = if s0 > 1024 then 0x8080 else s0 scf[o + 2] = if s1 > 1024 then 0x8080 else s1 scf[o + 3] = if s2 > 1024 then 0x8080 else s2 end end end if P > limit then return nil, "truncated frame" end -- samples for n = 1, maxUsed do for c = 1, 2 do local res = if c == 1 then resL[n] else resR[n] local q = if c == 1 then st.qL else st.qR local o = (n - 1) * 36 + 1 if res == -1 then noise(st, q, o) elseif res == 1 then local tab = Q7[1][bits(1) + 1] for k = 0, 35, 3 do local idx = huff(tab) q[o + k] = idx % 3 - 1 q[o + k + 1] = (idx // 3) % 3 - 1 q[o + k + 2] = idx // 9 - 1 end elseif res == 2 then local tab = Q7[2][bits(1) + 1] for k = 0, 35, 2 do local idx = huff(tab) q[o + k] = idx % 5 - 2 q[o + k + 1] = idx // 5 - 2 end elseif res >= 3 and res <= 7 then local tab = Q7[res][bits(1) + 1] for k = 0, 35 do q[o + k] = huff(tab) end elseif res >= 8 then local nb, dc = RES_BIT[res], DC[res + 2] for k = 0, 35 do q[o + k] = bits(nb) - dc end end if P > limit then return nil, "truncated frame" end end end -- bands above maxUsed: silent for n = maxUsed + 1, st.maxBand + 1 do resL[n], resR[n] = 0, 0 end return true, nil end @native local function readSv8(st: State, key: boolean, limit: number): (boolean?, string?) local resL, resR, msf = st.resL, st.resR, st.msf local maxBand = st.maxBand local maxUsed if key then maxUsed = logDec(maxBand + 1) else maxUsed = st.lastMaxBand + huff(BANDS8) if maxUsed > 32 then maxUsed -= 33 end end if maxUsed > maxBand + 1 then return nil, "bad band count" end st.lastMaxBand = maxUsed if maxUsed > 0 then local l, r = huff(RES8[1]), huff(RES8[1]) resL[maxUsed] = if l > 15 then l - 17 else l resR[maxUsed] = if r > 15 then r - 17 else r for n = maxUsed - 1, 1, -1 do l = huff(RES8[if resL[n + 1] > 2 then 2 else 1]) + resL[n + 1] resL[n] = if l > 15 then l - 17 else l r = huff(RES8[if resR[n + 1] > 2 then 2 else 1]) + resR[n + 1] resR[n] = if r > 15 then r - 17 else r end if st.ms then local tot = 0 for n = 1, maxUsed do if resL[n] ~= 0 or resR[n] ~= 0 then tot += 1 end end local cnt = logDec(tot) local tmp = 0 if cnt ~= 0 and cnt ~= tot then tmp = enumDec(math.min(cnt, tot - cnt), tot) end if cnt * 2 > tot then tmp = bnot(tmp) end for n = maxUsed, 1, -1 do if resL[n] ~= 0 or resR[n] ~= 0 then msf[n] = band(tmp, 1) == 1 tmp = rshift(tmp, 1) end end end end for n = maxUsed + 1, maxBand + 1 do resL[n], resR[n] = 0, 0 end -- SCFI local dscfL, dscfR = st.dscfL, st.dscfR if key then for n = 1, 32 do dscfL[n], dscfR[n] = true, true end end local scfiL, scfiR = st.scfiL, st.scfiR for n = 1, maxUsed do local cnt = -1 if resL[n] ~= 0 then cnt += 1 end if resR[n] ~= 0 then cnt += 1 end if cnt >= 0 then local tmp = huff(SCFI8[cnt + 1]) if resL[n] ~= 0 then scfiL[n] = rshift(tmp, 2 * cnt) end if resR[n] ~= 0 then scfiR[n] = band(tmp, 3) end end end if P > limit then return nil, "truncated frame" end -- SCF / DSCF for n = 1, maxUsed do for c = 1, 2 do local res = if c == 1 then resL[n] else resR[n] if res ~= 0 then local scf = if c == 1 then st.scfL else st.scfR local scfi = if c == 1 then scfiL[n] else scfiR[n] local dscf = if c == 1 then dscfL else dscfR local o = (n - 1) * 3 if dscf[n] then scf[o + 1] = bits(7) - 6 dscf[n] = false else local tmp = huff(DSCF8[2]) if tmp == 64 then tmp += bits(6) end scf[o + 1] = band(scf[o + 3] - 25 + tmp, 127) - 6 end for m = 0, 1 do if band(lshift(scfi, m), 2) == 0 then local tmp = huff(DSCF8[1]) if tmp == 31 then tmp = 64 + bits(6) end scf[o + m + 2] = band(scf[o + m + 1] - 25 + tmp, 127) - 6 else scf[o + m + 2] = scf[o + m + 1] end end end end end if P > limit then return nil, "truncated frame" end -- samples for n = 1, maxUsed do for c = 1, 2 do local res = if c == 1 then resL[n] else resR[n] local q = if c == 1 then st.qL else st.qR local o = (n - 1) * 36 + 1 if res == 2 then local tabs = Q8[2] local thres = 3 local idx = 6 for k = 0, 35, 3 do local tmp = huff(tabs[if idx > thres then 2 else 1]) local a, b, cc = tmp % 5 - 2, (tmp // 5) % 5 - 2, tmp // 25 - 2 q[o + k], q[o + k + 1], q[o + k + 2] = a, b, cc idx = rshift(idx, 1) + abs(a) + abs(b) + abs(cc) end elseif res == 1 then local k = 0 while k < 36 do local kmax = k + 18 local cnt = huff(Q1_8) local idx = 0 if cnt > 0 and cnt < 18 then idx = enumDec(if cnt <= 9 then cnt else 18 - cnt, 18) end if cnt > 9 then idx = bnot(idx) end while k < kmax do q[o + k] = 0 if band(idx, 0x20000) ~= 0 then q[o + k] = bits(1) * 2 - 1 end idx = lshift(idx, 1) k += 1 end end elseif res == -1 then noise(st, q, o) elseif res == 3 or res == 4 then local tab = Q34[res - 2] for k = 0, 35, 2 do local s = band(huff(tab), 255) local s1, s2 = band(s, 15), rshift(s, 4) q[o + k] = if s1 >= 8 then s1 - 16 else s1 q[o + k + 1] = if s2 >= 8 then s2 - 16 else s2 end elseif res >= 5 and res <= 8 then local tabs = Q8[res] local thres = THRES[res] local idx = 2 * thres for k = 0, 35 do local v = huff(tabs[if idx > thres then 2 else 1]) q[o + k] = v idx = rshift(idx, 1) + abs(v) end elseif res >= 9 then local sh = res - 9 local dc = DC[res + 2] for k = 0, 35 do local v = band(huff(Q9UP), 255) if sh > 0 then v = v * 2 ^ sh + bits(sh) end q[o + k] = v - dc end elseif res < -1 then return nil, "bad band resolution" end if P > limit then return nil, "truncated frame" end end end return true, nil end @native local function requant(st: State) local resL, resR, msf = st.resL, st.resR, st.msf local scfL, scfR, qL, qR, yL, yR = st.scfL, st.scfR, st.qL, st.qR, st.yL, st.yR for b = 1, st.maxBand + 1 do local rl, rr = resL[b], resR[b] local ccl, ccr = CC[rl + 2] or 0, CC[rr + 2] or 0 local ms = msf[b] local o = (b - 1) * 36 + 1 for part = 0, 2 do local fl = if rl ~= 0 then f32(ccl * SCF[band(scfL[(b - 1) * 3 + part + 1], 255) + 1]) else 0 local fr = if rr ~= 0 then f32(ccr * SCF[band(scfR[(b - 1) * 3 + part + 1], 255) + 1]) else 0 local y = part * 12 * 32 + b local qo = o + part * 12 if ms then for k = 0, 11 do local l, r = fl * qL[qo + k], fr * qR[qo + k] yL[y], yR[y] = l + r, l - r y += 32 end else for k = 0, 11 do yL[y], yR[y] = fl * qL[qo + k], fr * qR[qo + k] y += 32 end end end end end -- mpc_synthese_filter_float @native local function synth(V: { number }, Y: { number }, out: { number }, base: number, step: number) table.move(V, 1, 960, 2305) local o = 2304 + 1 local dw = DW local p = base for n = 0, 35 do o -= 64 newV(Y, n * 32 + 1, V, o) for k = 0, 31 do local v = o + k local d = k * 16 + 1 out[p] = V[v] * dw[d] + V[v + 96] * dw[d + 1] + V[v + 128] * dw[d + 2] + V[v + 224] * dw[d + 3] + V[v + 256] * dw[d + 4] + V[v + 352] * dw[d + 5] + V[v + 384] * dw[d + 6] + V[v + 480] * dw[d + 7] + V[v + 512] * dw[d + 8] + V[v + 608] * dw[d + 9] + V[v + 640] * dw[d + 10] + V[v + 736] * dw[d + 11] + V[v + 768] * dw[d + 12] + V[v + 864] * dw[d + 13] + V[v + 896] * dw[d + 14] + V[v + 992] * dw[d + 15] p += step end end end @native function Decode.frame(st: State, buf: buffer, bitPos: number, limitBits: number, key: boolean, out: { number }, base: number): (number?, string?) if bitPos >= 0 then if rshift(limitBits, 3) + Decode.PAD > buffer.len(buf) or bitPos > limitBits then return nil, "truncated frame" end B, P = buf, bitPos local ok, err if st.version == 8 then ok, err = readSv8(st, key, limitBits) else ok, err = readSv7(st, limitBits) end B = buffer.create(0) if not ok then return nil, err end else for b = 1, st.maxBand + 1 do st.resL[b], st.resR[b] = 0, 0 end end local pos = P requant(st) local ch = st.channels synth(st.vL, st.yL, out, base, ch) if ch > 1 then synth(st.vR, st.yR, out, base + 1, ch) end return if bitPos >= 0 then pos else bitPos, nil end @native function Decode.bitsAt(buf: buffer, bitPos: number, n: number): number local w = bswap(readu32(buf, rshift(bitPos, 3))) return extract(w, 32 - band(bitPos, 7) - n, n) end return Decode end __FILES["codecs/audio/Musepack/Tables"] = function() -- codecs/audio/Musepack/Tables: the Musepack SV7 / SV8 Huffman tables, synthesis window and requantisation constants. -- Ported from libmpcdec (musepack_src_r475: huffman.c, synth_filter.c, requant.c, mpc_bits_reader.c; BSD-3-Clause, -- (c) The Musepack Development Team, licenses/libmpcdec-BSD.txt). Huffman tables: flat { code, length, value, ... } -- sorted by descending left-aligned 16-bit code; canonical (SV8) tables map value - (code >> (16 - length)). local T = {} T.HuffHdr = { 32768, 1, 0, 24576, 3, 1, 24064, 7, -4, 23936, 9, 3, 23808, 9, 4, 23552, 8, -5, 22528, 6, 2, 20480, 5, -3, 16384, 4, -2, 0, 2, -1, } T.HuffSCFI = { 32768, 1, 1, 24576, 3, 2, 16384, 3, 0, 0, 2, 3, } T.HuffDSCF = { 63488, 5, 5, 61440, 5, -4, 57344, 4, 3, 53248, 4, -3, 49152, 4, 8, 40960, 3, 1, 36864, 4, 0, 34816, 5, -5, 33792, 6, 7, 32768, 6, -7, 24576, 3, -1, 16384, 3, 2, 12288, 4, 4, 10240, 5, 6, 8192, 5, -6, 0, 3, -2, } T.HuffQ1_0 = { 57344, 3, 13, 56320, 6, 26, 55296, 6, 0, 54272, 6, 20, 53248, 6, 6, 49152, 4, 14, 45056, 4, 12, 40960, 4, 4, 36864, 4, 22, 35840, 6, 8, 34816, 6, 18, 33792, 6, 24, 32768, 6, 2, 28672, 4, 16, 24576, 4, 10, 22528, 5, 17, 20480, 5, 9, 18432, 5, 1, 16384, 5, 25, 14336, 5, 5, 12288, 5, 21, 10240, 5, 3, 8192, 5, 11, 6144, 5, 15, 4096, 5, 23, 2048, 5, 19, 0, 5, 7, } T.HuffQ1_1 = { 32768, 1, 13, 32256, 7, 15, 31744, 7, 1, 31232, 7, 11, 30720, 7, 7, 30208, 7, 17, 29696, 7, 25, 29184, 7, 19, 29056, 9, 8, 28928, 9, 18, 28800, 9, 2, 28672, 9, 24, 28160, 7, 3, 27648, 7, 23, 27136, 7, 21, 26624, 7, 5, 26368, 8, 0, 26112, 8, 26, 25856, 8, 6, 25600, 8, 20, 24576, 6, 9, 20480, 4, 14, 16384, 4, 12, 12288, 4, 4, 8192, 4, 22, 4096, 4, 16, 0, 4, 10, } T.HuffQ2_0 = { 61440, 4, 13, 57344, 4, 17, 53248, 4, 7, 49152, 4, 11, 48128, 6, 1, 47104, 6, 23, 46592, 7, 4, 46080, 7, 20, 45568, 7, 0, 45056, 7, 24, 43008, 5, 22, 40960, 5, 10, 32768, 3, 12, 30720, 5, 2, 28672, 5, 14, 24576, 4, 6, 20480, 4, 18, 16384, 4, 8, 12288, 4, 16, 10240, 5, 9, 8192, 5, 5, 6144, 5, 15, 4096, 5, 21, 2048, 5, 19, 0, 5, 3, } T.HuffQ2_1 = { 63488, 5, 18, 61440, 5, 6, 59392, 5, 8, 59136, 8, 3, 59072, 10, 24, 59008, 10, 4, 58944, 10, 0, 58880, 10, 20, 58368, 7, 23, 57856, 7, 1, 57344, 7, 19, 55296, 5, 16, 54784, 7, 15, 54272, 7, 21, 53760, 7, 9, 53248, 7, 5, 52224, 6, 2, 51200, 6, 10, 50176, 6, 14, 49152, 6, 22, 32768, 2, 12, 24576, 3, 13, 16384, 3, 17, 8192, 3, 11, 0, 3, 7, } T.HuffQ3_0 = { 57344, 3, 1, 53248, 4, 3, 49152, 4, -3, 40960, 3, 2, 32768, 3, -2, 16384, 2, 0, 0, 2, -1, } T.HuffQ3_1 = { 49152, 2, 0, 32768, 2, -1, 16384, 2, 1, 12288, 4, -2, 10240, 5, 3, 8192, 5, -3, 0, 3, 2, } T.HuffQ4_0 = { 57344, 3, 0, 49152, 3, -1, 40960, 3, 1, 32768, 3, -2, 24576, 3, 2, 20480, 4, -4, 16384, 4, 4, 8192, 3, 3, 0, 3, -3, } T.HuffQ4_1 = { 57344, 3, 1, 53248, 4, 2, 49152, 4, -3, 32768, 2, 0, 24576, 3, -2, 20480, 4, 3, 18432, 5, -4, 16384, 5, 4, 0, 2, -1, } T.HuffQ5_0 = { 61440, 4, 2, 59392, 5, 5, 58368, 6, -7, 57344, 6, 7, 53248, 4, -3, 49152, 4, 3, 47104, 5, -6, 45056, 5, 6, 40960, 4, -4, 36864, 4, 4, 32768, 4, -5, 24576, 3, 0, 16384, 3, -1, 8192, 3, 1, 0, 3, -2, } T.HuffQ5_1 = { 61440, 4, 3, 59392, 5, 4, 58880, 7, 6, 58624, 8, -7, 58368, 8, 7, 57344, 6, -6, 49152, 3, 0, 40960, 3, -1, 32768, 3, 1, 24576, 3, -2, 16384, 3, 2, 14336, 5, -5, 12288, 5, 5, 8192, 4, -4, 0, 3, -3, } T.HuffQ6_0 = { 63488, 5, 3, 61440, 5, -4, 60416, 6, -11, 59392, 6, 12, 57344, 5, 4, 55296, 5, 6, 53248, 5, -5, 51200, 5, 5, 49152, 5, 7, 47104, 5, -7, 46080, 6, -12, 45056, 6, -13, 43008, 5, -6, 40960, 5, 8, 38912, 5, -8, 36864, 5, 9, 34816, 5, -9, 33792, 6, 13, 33280, 7, -15, 32768, 7, 15, 28672, 4, 0, 26624, 5, -10, 24576, 5, 10, 20480, 4, -1, 16384, 4, 2, 12288, 4, 1, 8192, 4, -2, 7168, 6, 14, 6144, 6, -14, 4096, 5, 11, 0, 4, -3, } T.HuffQ6_1 = { 63488, 5, -6, 61440, 5, 6, 57344, 4, 1, 53248, 4, -1, 52736, 7, 10, 52224, 7, -10, 51968, 8, -11, 51840, 9, -12, 51808, 11, 13, 51800, 13, 15, 51792, 13, -14, 51784, 13, 14, 51776, 13, -15, 51712, 10, -13, 51456, 8, 11, 51200, 8, 12, 50176, 6, -9, 49152, 6, 9, 45056, 4, -2, 40960, 4, 2, 36864, 4, 3, 32768, 4, -3, 30720, 5, -7, 28672, 5, 7, 24576, 4, -4, 20480, 4, 4, 18432, 5, -8, 16384, 5, 8, 12288, 4, 5, 8192, 4, -5, 0, 3, 0, } T.HuffQ7_0 = { 64512, 6, 7, 63488, 6, 8, 62464, 6, 9, 61440, 6, -8, 60416, 6, 11, 59904, 7, 21, 59648, 8, -28, 59392, 8, 28, 58368, 6, -9, 57856, 7, -22, 57344, 7, -21, 56320, 6, -10, 55296, 6, -11, 54272, 6, 10, 53248, 6, 12, 52224, 6, -13, 51712, 7, 22, 51200, 7, 23, 50176, 6, -12, 49152, 6, 13, 48128, 6, 14, 47104, 6, -14, 46592, 7, -23, 46336, 8, -29, 46080, 8, 29, 45056, 6, -15, 44032, 6, 15, 43008, 6, 16, 41984, 6, -16, 41472, 7, -24, 40960, 7, 24, 39936, 6, 17, 39424, 7, -25, 39168, 8, -30, 38912, 8, 30, 37888, 6, -17, 36864, 6, 18, 35840, 6, -18, 35328, 7, 25, 34816, 7, 26, 33792, 6, 19, 33280, 7, -26, 32768, 7, -27, 30720, 5, 2, 29696, 6, -19, 28672, 6, 20, 26624, 5, -1, 26368, 8, -31, 26112, 8, 31, 25600, 7, 27, 24576, 6, -20, 22528, 5, 1, 20480, 5, -5, 18432, 5, -3, 16384, 5, 3, 14336, 5, 0, 12288, 5, -2, 10240, 5, -4, 8192, 5, 4, 6144, 5, 5, 4096, 5, -6, 2048, 5, 6, 0, 5, -7, } T.HuffQ7_1 = { 63488, 5, -1, 61440, 5, 2, 59392, 5, -2, 57344, 5, 3, 57088, 8, -20, 57024, 10, 24, 57020, 14, 28, 57016, 14, -28, 57012, 14, -30, 57008, 14, 30, 56992, 12, -27, 56988, 14, 29, 56984, 14, -29, 56980, 14, 31, 56976, 14, -31, 56960, 12, 27, 56832, 9, -22, 56320, 7, -17, 55296, 6, -11, 53248, 5, -3, 51200, 5, 4, 49152, 5, -4, 48640, 7, 17, 48384, 8, 20, 48256, 9, 22, 48192, 10, -25, 48128, 10, -26, 47104, 6, 12, 45056, 5, 5, 43008, 5, -5, 40960, 5, 6, 38912, 5, -6, 37888, 6, -12, 37376, 7, -18, 36864, 7, 18, 35840, 6, 13, 34816, 6, -13, 32768, 5, -7, 31744, 6, 14, 31488, 8, 21, 31232, 8, -21, 30720, 7, -19, 28672, 5, 7, 26624, 5, 8, 25600, 6, -14, 24576, 6, -15, 22528, 5, -8, 21504, 6, 15, 20992, 7, 19, 20928, 10, 25, 20864, 10, 26, 20736, 9, -23, 20608, 9, 23, 20480, 9, -24, 18432, 5, -9, 16384, 5, 9, 15360, 6, 16, 14336, 6, -16, 12288, 5, 10, 8192, 4, 0, 6144, 5, -10, 4096, 5, 11, 0, 4, 1, } T.H_SCFI_1 = { 32768, 1, 1, 16384, 2, 2, 0, 3, 3, } T.H_SCFI_2 = { 32768, 2, 3, 16384, 3, 5, 6144, 5, 11, 1024, 6, 14, 0, 7, 15, } T.H_DSCF_1 = { 40960, 3, 7, 16384, 4, 12, 10240, 5, 16, 6144, 6, 21, 3584, 7, 27, 1792, 8, 34, 896, 9, 41, 320, 10, 48, 128, 11, 53, 48, 12, 57, 24, 13, 60, 0, 14, 63, } T.H_DSCF_2 = { 24576, 3, 7, 12288, 4, 10, 6144, 5, 13, 4096, 6, 16, 2560, 7, 20, 1536, 8, 25, 896, 9, 31, 448, 10, 38, 224, 11, 45, 80, 12, 52, 32, 13, 57, 12, 14, 61, 0, 15, 64, } T.H_Bands = { 32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 5, 6, 2048, 6, 8, 1536, 7, 10, 768, 8, 13, 512, 9, 16, 320, 10, 20, 192, 11, 25, 16, 12, 31, 0, 13, 32, } T.H_Res_1 = { 32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 4, 4, 2048, 5, 5, 1024, 6, 6, 512, 7, 7, 256, 8, 8, 128, 9, 9, 64, 10, 10, 32, 11, 11, 16, 12, 12, 8, 13, 13, 4, 14, 14, 2, 15, 15, 0, 16, 16, } T.H_Res_2 = { 16384, 2, 3, 8192, 3, 4, 4096, 4, 5, 2048, 5, 6, 1024, 6, 7, 512, 7, 8, 256, 8, 9, 128, 9, 10, 64, 10, 11, 32, 11, 12, 16, 12, 13, 0, 14, 16, } T.H_Q1 = { 24576, 3, 7, 4096, 4, 10, 2048, 5, 11, 1024, 6, 12, 512, 7, 13, 256, 8, 14, 128, 9, 15, 64, 10, 16, 32, 11, 17, 0, 12, 18, } T.H_Q2_1 = { 57344, 3, 7, 32768, 4, 14, 15360, 6, 38, 10752, 7, 53, 4608, 8, 74, 1536, 9, 92, 960, 10, 104, 96, 11, 119, 32, 12, 122, 0, 13, 124, } T.H_Q2_2 = { 61440, 4, 15, 28672, 5, 30, 18432, 6, 44, 15360, 7, 62, 3072, 8, 92, 1920, 9, 104, 192, 10, 119, 64, 11, 122, 0, 12, 124, } T.H_Q3 = { 57344, 3, 7, 32768, 4, 14, 20480, 5, 22, 9216, 6, 32, 2560, 7, 41, 512, 8, 46, 0, 9, 48, } T.H_Q4 = { 61440, 4, 15, 36864, 5, 30, 13312, 6, 48, 6144, 7, 61, 1280, 8, 73, 256, 9, 78, 0, 10, 80, 0, 0, 90, } T.H_Q5_1 = { 49152, 2, 3, 16384, 3, 6, 8192, 4, 8, 4096, 5, 10, 2048, 6, 12, 0, 7, 14, } T.H_Q5_2 = { 24576, 3, 7, 8192, 4, 10, 4096, 5, 12, 0, 6, 14, } T.H_Q6_1 = { 49152, 2, 3, 32768, 3, 6, 16384, 4, 10, 10240, 5, 14, 3072, 6, 19, 2048, 7, 22, 1024, 8, 26, 0, 9, 30, } T.H_Q6_2 = { 20480, 4, 15, 8192, 5, 20, 4096, 6, 24, 1024, 7, 28, 0, 8, 30, } T.H_Q7_1 = { 49152, 2, 3, 32768, 3, 6, 24576, 4, 10, 16384, 5, 16, 10240, 6, 24, 5120, 7, 34, 2560, 8, 44, 1024, 9, 54, 0, 10, 62, } T.H_Q7_2 = { 24576, 5, 31, 9216, 6, 43, 4096, 7, 52, 512, 8, 60, 0, 9, 62, } T.H_Q8_1 = { 49152, 2, 3, 32768, 3, 6, 28672, 4, 10, 22528, 5, 17, 14336, 6, 28, 10240, 7, 42, 6400, 8, 62, 3328, 9, 87, 640, 10, 113, 96, 11, 123, 0, 12, 126, } T.H_Q8_2 = { 38912, 6, 63, 10752, 7, 101, 1024, 8, 122, 0, 9, 126, } T.H_Q9up = { 63488, 6, 63, 44032, 7, 125, 9728, 8, -45, 640, 9, -7, 64, 10, -2, 0, 11, -1, } T.S_SCFI_1 = { 2, 3, 1, 0, } T.S_SCFI_2 = { 15, 10, 14, 11, 13, 9, 7, 6, 5, 12, 8, 3, 2, 0, 4, 1, } T.S_DSCF_1 = { 35, 34, 33, 36, 32, 30, 29, 27, 26, 37, 28, 25, 39, 38, 24, 23, 40, 22, 21, 20, 19, 43, 42, 41, 18, 17, 16, 15, 46, 45, 44, 14, 13, 12, 11, 49, 48, 47, 31, 10, 9, 8, 7, 6, 52, 51, 50, 5, 4, 3, 54, 53, 2, 1, 0, 57, 56, 55, 63, 62, 61, 60, 59, 58, } T.S_DSCF_2 = { 33, 32, 31, 30, 29, 34, 28, 27, 36, 35, 26, 37, 25, 38, 24, 23, 40, 39, 22, 21, 42, 41, 20, 19, 18, 45, 44, 43, 17, 16, 15, 14, 48, 47, 46, 13, 12, 11, 10, 64, 52, 51, 50, 49, 9, 8, 7, 6, 55, 54, 53, 5, 4, 3, 58, 57, 56, 2, 1, 63, 62, 61, 60, 59, 0, } T.S_Bands = { 0, 32, 1, 31, 2, 30, 3, 4, 29, 6, 5, 28, 7, 27, 26, 8, 25, 24, 23, 9, 22, 21, 20, 18, 17, 16, 15, 14, 12, 11, 10, 19, 13, } T.S_Res_1 = { 0, 1, 16, 2, 3, 4, 5, 15, 6, 7, 8, 9, 10, 11, 12, 14, 13, } T.S_Res_2 = { 16, 1, 0, 2, 15, 3, 14, 4, 5, 13, 6, 12, 7, 11, 10, 9, 8, } T.S_Q1 = { 7, 6, 5, 4, 3, 10, 9, 8, 2, 1, 11, 0, 12, 13, 14, 15, 16, 18, 17, } T.S_Q2_1 = { 62, 87, 67, 63, 61, 57, 37, 93, 92, 88, 86, 83, 82, 81, 68, 66, 58, 56, 42, 41, 38, 36, 32, 31, 112, 91, 72, 64, 60, 52, 43, 33, 12, 117, 113, 111, 107, 97, 89, 85, 77, 73, 71, 69, 65, 59, 55, 53, 51, 47, 39, 35, 27, 17, 13, 11, 7, 118, 116, 108, 106, 98, 96, 94, 90, 84, 80, 78, 76, 48, 46, 44, 40, 34, 30, 28, 26, 18, 16, 8, 6, 122, 110, 102, 74, 70, 54, 50, 22, 2, 123, 121, 119, 115, 114, 109, 105, 103, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 14, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4, } T.S_Q2_2 = { 62, 92, 87, 86, 82, 68, 67, 66, 63, 61, 58, 57, 56, 42, 38, 37, 32, 93, 91, 88, 83, 81, 43, 41, 36, 33, 31, 112, 72, 64, 60, 52, 12, 118, 117, 116, 113, 111, 108, 107, 106, 98, 97, 96, 94, 90, 89, 85, 84, 80, 78, 77, 76, 73, 71, 69, 65, 59, 55, 53, 51, 48, 47, 46, 44, 40, 39, 35, 34, 30, 28, 27, 26, 18, 17, 16, 13, 11, 8, 7, 6, 122, 110, 74, 70, 54, 50, 22, 14, 2, 123, 121, 119, 115, 114, 109, 105, 103, 102, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4, } T.S_Q3 = { 0, 17, 16, 1, 15, -16, -1, 32, 31, 2, 14, -15, -32, 34, 33, 47, 46, 18, 30, -14, -2, -31, -17, -18, 49, 48, 63, 19, 29, 3, 13, -13, -3, -30, -47, -48, -33, 50, 62, 35, 45, -29, -19, -46, -34, 51, 61, -45, -35, } T.S_Q4 = { 0, 32, 17, 16, 31, 2, 1, 15, 14, -15, -16, -1, -32, 49, 48, 34, 33, 47, 46, 19, 18, 30, 29, 3, 13, -13, -14, -2, -3, -30, -31, -17, -18, -47, -48, -33, 64, 50, 63, 62, 35, 45, 4, 12, -29, -19, -46, -34, -64, -49, 66, 65, 79, 78, 51, 61, 36, 44, 20, 28, -12, -4, -28, -20, -45, -35, -62, -63, -50, 67, 77, 52, 60, -44, -36, -61, -51, 68, 76, -60, -52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, } T.S_Q5_1 = { 0, 2, 1, -1, -2, 3, -3, 4, -4, 5, -5, 7, 6, -6, -7, } T.S_Q5_2 = { 2, 1, 0, -1, -2, 4, 3, -3, -4, 5, -5, 7, 6, -6, -7, } T.S_Q6_1 = { 0, 1, -1, 3, 2, -2, -3, 4, -4, -5, 8, 7, 6, 5, -6, -7, -8, 9, -9, 11, 10, -10, -11, 15, 14, 13, 12, -12, -13, -14, -15, } T.S_Q6_2 = { 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, 8, 7, 6, -6, -7, -8, 10, 9, -9, -10, 13, 12, 11, -11, -12, -13, 15, 14, -14, -15, } T.S_Q7_1 = { 0, 1, -1, 2, -2, 4, 3, -3, -4, 7, 6, 5, -5, -6, -7, 13, 11, 10, 9, 8, -8, -9, -10, -11, -12, 17, 16, 15, 14, 12, -13, -14, -15, -16, -17, 28, 27, 21, 20, 19, 18, -18, -19, -20, -21, -27, -28, 31, 30, 29, 26, 25, 24, 23, 22, -22, -23, -24, -25, -26, -29, -30, -31, } T.S_Q7_2 = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, 17, 16, 15, 14, 13, 12, 11, -10, -11, -12, -13, -14, -15, -16, -17, 22, 21, 20, 19, 18, -18, -19, -20, -21, -22, 29, 28, 27, 26, 25, 24, 23, -23, -24, -25, -26, -27, -28, -29, 31, 30, -30, -31, } T.S_Q8_1 = { 0, 1, -1, -2, 3, 2, -3, 7, 6, 5, 4, -4, -5, -6, -7, 11, 10, 9, 8, -8, -9, -10, -11, 19, 18, 17, 16, 15, 14, 13, 12, -12, -13, -14, -15, -16, -17, -19, 56, 55, 31, 28, 27, 26, 25, 24, 23, 22, 21, 20, -18, -20, -21, -22, -23, -24, -25, -26, -27, -33, -54, -56, 63, 62, 61, 60, 59, 58, 57, 54, 53, 43, 40, 39, 38, 37, 36, 35, 34, 33, 32, 30, 29, -28, -29, -30, -31, -32, -34, -35, -36, -37, -38, -39, -40, -41, -43, -53, -55, -57, -58, -59, -60, -61, 49, 47, 46, 45, 44, 42, 41, -42, -44, -45, -46, -47, -48, -49, -50, -62, -63, 52, 51, 50, 48, -51, -52, } T.S_Q8_2 = { 13, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 12, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, -42, -43, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, 63, 62, 61, 60, -60, -61, -62, -63, } T.S_Q9up = { -128, 127, -108, -110, -111, -112, -113, -114, -115, -116, -117, -118, -119, -120, -121, -122, -123, -124, -125, -126, -127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112, 111, 110, 109, 108, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, -60, -61, -62, -63, -64, -65, -66, -67, -68, -69, -70, -71, -72, -73, -74, -75, -76, -77, -78, -79, -80, -81, -82, -83, -84, -85, -86, -87, -88, -89, -90, -91, -92, -93, -94, -95, -96, -97, -98, -99, -100, -101, -102, -103, -104, -105, -106, -107, -109, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 40, 20, 19, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, -42, -43, 41, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, -3, -4, -5, -6, 4, 3, 2, 1, 0, -1, -2, } -- Di_opt[32][16] (times 65536) T.DI = { 0, -29, 213, -459, 2037, -5153, 6574, -37489, 75038, 37489, 6574, 5153, 2037, 459, 213, 29, -1, -31, 218, -519, 2000, -5517, 5959, -39336, 74992, 35640, 7134, 4788, 2063, 401, 208, 26, -1, -35, 222, -581, 1952, -5879, 5288, -41176, 74856, 33791, 7640, 4425, 2080, 347, 202, 24, -1, -38, 225, -645, 1893, -6237, 4561, -43006, 74630, 31947, 8092, 4063, 2087, 294, 196, 21, -1, -41, 227, -711, 1822, -6589, 3776, -44821, 74313, 30112, 8492, 3705, 2085, 244, 190, 19, -1, -45, 228, -779, 1739, -6935, 2935, -46617, 73908, 28289, 8840, 3351, 2075, 197, 183, 17, -1, -49, 228, -848, 1644, -7271, 2037, -48390, 73415, 26482, 9139, 3004, 2057, 153, 176, 16, -2, -53, 227, -919, 1535, -7597, 1082, -50137, 72835, 24694, 9389, 2663, 2032, 111, 169, 14, -2, -58, 224, -991, 1414, -7910, 70, -51853, 72169, 22929, 9592, 2330, 2001, 72, 161, 13, -2, -63, 221, -1064, 1280, -8209, -998, -53534, 71420, 21189, 9750, 2006, 1962, 36, 154, 11, -2, -68, 215, -1137, 1131, -8491, -2122, -55178, 70590, 19478, 9863, 1692, 1919, 2, 147, 10, -3, -73, 208, -1210, 970, -8755, -3300, -56778, 69679, 17799, 9935, 1388, 1870, -29, 139, 9, -3, -79, 200, -1283, 794, -8998, -4533, -58333, 68692, 16155, 9966, 1095, 1817, -57, 132, 8, -4, -85, 189, -1356, 605, -9219, -5818, -59838, 67629, 14548, 9959, 814, 1759, -83, 125, 7, -4, -91, 177, -1428, 402, -9416, -7154, -61289, 66494, 12980, 9916, 545, 1698, -106, 117, 7, -5, -97, 163, -1498, 185, -9585, -8540, -62684, 65290, 11455, 9838, 288, 1634, -127, 111, 6, -5, -104, 146, -1567, -45, -9727, -9975, -64019, 64019, 9975, 9727, 45, 1567, -146, 104, 5, -6, -111, 127, -1634, -288, -9838, -11455, -65290, 62684, 8540, 9585, -185, 1498, -163, 97, 5, -7, -117, 106, -1698, -545, -9916, -12980, -66494, 61289, 7154, 9416, -402, 1428, -177, 91, 4, -7, -125, 83, -1759, -814, -9959, -14548, -67629, 59838, 5818, 9219, -605, 1356, -189, 85, 4, -8, -132, 57, -1817, -1095, -9966, -16155, -68692, 58333, 4533, 8998, -794, 1283, -200, 79, 3, -9, -139, 29, -1870, -1388, -9935, -17799, -69679, 56778, 3300, 8755, -970, 1210, -208, 73, 3, -10, -147, -2, -1919, -1692, -9863, -19478, -70590, 55178, 2122, 8491, -1131, 1137, -215, 68, 2, -11, -154, -36, -1962, -2006, -9750, -21189, -71420, 53534, 998, 8209, -1280, 1064, -221, 63, 2, -13, -161, -72, -2001, -2330, -9592, -22929, -72169, 51853, -70, 7910, -1414, 991, -224, 58, 2, -14, -169, -111, -2032, -2663, -9389, -24694, -72835, 50137, -1082, 7597, -1535, 919, -227, 53, 2, -16, -176, -153, -2057, -3004, -9139, -26482, -73415, 48390, -2037, 7271, -1644, 848, -228, 49, 1, -17, -183, -197, -2075, -3351, -8840, -28289, -73908, 46617, -2935, 6935, -1739, 779, -228, 45, 1, -19, -190, -244, -2085, -3705, -8492, -30112, -74313, 44821, -3776, 6589, -1822, 711, -227, 41, 1, -21, -196, -294, -2087, -4063, -8092, -31947, -74630, 43006, -4561, 6237, -1893, 645, -225, 38, 1, -24, -202, -347, -2080, -4425, -7640, -33791, -74856, 41176, -5288, 5879, -1952, 581, -222, 35, 1, -26, -208, -401, -2063, -4788, -7134, -35640, -74992, 39336, -5959, 5517, -2000, 519, -218, 31, 1, } -- requantisation: Cc[res] = 65536 / steps (res -1 .. 17, stored at res + 2), Dc[res] = (steps - 1) / 2, bits per -- sample of the plain quantisers (res 8 .. 17) T.CC = { 111.285962475327, 65536.000000000000, 21845.333333333332, 13107.200000000001, 9362.285714285713, 7281.777777777777, 4369.066666666666, 2114.064516129032, 1040.253968253968, 516.031496062992, 257.003921568627, 128.250489236790, 64.062561094819, 32.015632633121, 16.003907203907, 8.000976681723, 4.000244155527, 2.000061037018, 1.000015259021, } T.DC = { 2, 0, 1, 2, 3, 4, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767 } T.RES_BIT = { [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 13, [15] = 14, [16] = 15, [17] = 16 } -- log_dec(max): ceil(log2(max + 2)) bits and the unused codes (index max + 1, max = 0 .. 31) T.LOG2 = { 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6 } T.LOG2_LOST = { 0, 1, 0, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 31 } -- enum_dec: CNK[k][n + 1] = C(n, k) (k = 1 .. 16, n = 0 .. 31), the code length ceil(log2 C(n, k)) and the unused -- codes 2^len - C(n, k) (computed: libmpcdec's tables, whose last entry is 0) T.CNK, T.CNK_LEN, T.CNK_LOST = {}, {}, {} do for k = 1, 16 do local c, l, lost = table.create(32, 0), table.create(32, 0), table.create(32, 0) for n = 0, 32 do local v = 0 if n >= k then v = 1 for i = 1, k do v = v * (n - k + i) / i end v = math.floor(v + 0.5) end if n <= 31 then c[n + 1] = v end if n >= 1 then local bits = 0 while 2 ^ bits < v do bits += 1 end l[n] = bits lost[n] = if v > 0 then 2 ^ bits - v else 0 end end T.CNK[k], T.CNK_LEN[k], T.CNK_LOST[k] = c, l, lost end T.CNK_LOST[16][32] = 0 end type Lut = { len: { number }, val: { number }, codes: { number }, lens: { number }, vals: { number }, sym: { number }?, } function T.lut(tab: { number }, sym: { number }?): Lut local codes, lens, vals = {}, {}, {} for i = 1, #tab, 3 do table.insert(codes, tab[i]) table.insert(lens, tab[i + 1]) table.insert(vals, tab[i + 2]) end local function find(code: number): number local j = 1 while code < codes[j] do j += 1 end return j end local function symbol(j: number, code: number): number if sym then local idx = bit32.band(vals[j] - bit32.rshift(code, 16 - lens[j]), 255) return sym[idx + 1] or 0 end return vals[j] end local len, val = table.create(256, 0), table.create(256, 0) for p = 0, 255 do local lo, hi = find(p * 256), find(p * 256 + 255) if lo == hi and lens[lo] <= 8 then len[p + 1] = lens[lo] val[p + 1] = symbol(lo, p * 256) else len[p + 1] = 0 val[p + 1] = hi end end return { len = len, val = val, codes = codes, lens = lens, vals = vals, sym = sym } end return T end __FILES["codecs/audio/Opus"] = function() -- codecs/audio/Opus: the Opus codec (RFC 6716) without its container. -- A port of the libopus 1.6 decoder (BSD, licenses/libopus-BSD.txt), absorbed from opus-luau dd2b4e5; the CELT encoder is new. local Opus = { Packet = __include("codecs/audio/Opus/Packet"), Decoder = __include("codecs/audio/Opus/Decoder"), Celt = __include("codecs/audio/Opus/Celt"), Silk = __include("codecs/audio/Opus/Silk"), CeltEncoder = __include("codecs/audio/Opus/CeltEncoder"), } return Opus end __FILES["codecs/audio/Opus/Celt"] = @native function() -- codecs/audio/Opus/Celt: CELT decoder (RFC 6716 section 4.3), 48 kHz / 960-sample mode, noise-based PLC only. -- A port of the libopus float decoder (celt_decoder.c, bands.c, vq.c, cwrs.c, rate.c, quant_bands.c, laplace.c, celt.c; -- BSD, licenses/libopus-BSD.txt). The C code's band pointers are 0-based offsets into one table W. local RD = __include("codecs/entropy/RangeCoder/Decoder") local Mdct = __include("codecs/audio/Opus/Mdct") local T = __include("codecs/audio/Opus/CeltTables") local Celt = {} local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift local min, max, sqrt, floor, exp, cos = math.min, math.max, math.sqrt, math.floor, math.exp, math.cos local decBitLogp, decIcdf, decBits, decUint = RD.bitLogp, RD.icdf, RD.bits, RD.uint local decDecode, decDecodeBin, decUpdate = RD.decode, RD.decodeBin, RD.update local tell, tellFrac = RD.tell, RD.tellFrac local NB_EBANDS = 21 local EFF_EBANDS = 21 local OVERLAP = 120 local SHORT_MDCT = 120 local MAX_LM = 3 local DECODE_BUFFER_SIZE = 2048 local BITRES = 3 local MAX_FINE_BITS = 8 local FINE_OFFSET = 21 local QTHETA_OFFSET = 4 local QTHETA_OFFSET_TWOPHASE = 16 local SPREAD_AGGRESSIVE = 3 local PREEMPH = 0.85000610 local COMBFILTER_MINPERIOD = 15 local FRAME_NONE, FRAME_NORMAL, FRAME_PLC_NOISE = 0, 1, 2 -- eBands (1-based: EB[i + 1] is eBands[i]) local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 } local ALLOC = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104, } local NB_ALLOC_VECTORS = 11 local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 } local LOGN = T.logN400 local CACHE_INDEX = T.cache_index50 local CACHE_BITS = T.cache_bits50 local CACHE_CAPS = T.cache_caps50 local E_PROB = T.e_prob_model local E_MEANS = { 6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500, 4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500, 3.750000, 3.750000, 3.750000, 3.750000, 3.750000, } local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 } local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 } local BETA_INTRA = 4915 / 32768 local TF_SELECT = { -- [LM][4 * isTransient + 2 * tf_select + flag] { 0, -1, 0, -1, 0, -1, 0, -1 }, { 0, -1, 0, -2, 1, 0, 1, -1 }, { 0, -2, 0, -3, 2, 0, 1, -1 }, { 0, -2, 0, -3, 3, 0, 1, -1 }, } local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } local SPREAD_ICDF = { 25, 23, 2, 0 } local TAPSET_ICDF = { 2, 1, 0 } local SMALL_ENERGY_ICDF = { 2, 1, 0 } local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } local ORDERY = { 1, 0, 3, 0, 2, 1, 7, 0, 4, 3, 6, 1, 5, 2, 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5 } local BIT_INTERLEAVE = { 0, 1, 1, 1, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3 } local BIT_DEINTERLEAVE = { 0x00, 0x03, 0x0C, 0x0F, 0x30, 0x33, 0x3C, 0x3F, 0xC0, 0xC3, 0xCC, 0xCF, 0xF0, 0xF3, 0xFC, 0xFF } local COMB_GAINS = { { 0.3066406250, 0.2170410156, 0.1296386719 }, { 0.4638671875, 0.2680664062, 0.0 }, { 0.7998046875, 0.1000976562, 0.0 }, } local WINDOW = table.create(OVERLAP, 0) for i = 0, OVERLAP - 1 do local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s) end Celt.window = WINDOW -- PVQ codebook sizes U(n, k) (cwrs.c), flat: U[n * UK + k + 1], n, k in 0 .. 176 local UK = 177 local U = table.create(UK * UK, 0) U[1] = 1 for n = 1, UK - 1 do for k = 1, UK - 1 do U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k] end end local NORM_BASE = 1920 local W = table.create(4096, 0) local TMP = table.create(256, 0) local IY = table.create(256, 0) local FREQ = table.create(960, 0) local FREQ2 = table.create(960, 0) local COLLAPSE = table.create(42, 0) local TF_RES = table.create(21, 0) local CAP = table.create(21, 0) local OFFSETS = table.create(21, 0) local FINE_QUANT = table.create(21, 0) local PULSES = table.create(21, 0) local FINE_PRIORITY = table.create(21, 0) local BITS1 = table.create(21, 0) local BITS2 = table.create(21, 0) local THRESH = table.create(21, 0) local TRIM_OFFSET = table.create(21, 0) @native local function imin(a: number, b: number): number return if a < b then a else b end @native local function imax(a: number, b: number): number return if a > b then a else b end -- C integer division (truncates toward zero) @native local function tdiv(a: number, b: number): number local q = a / b return if q >= 0 then floor(q) else -floor(-q) end @native local function exp2(x: number): number return exp(0.6931471805599453094 * x) end @native local function lcg(seed: number): number return (1664525 * seed + 1013904223) % 4294967296 end @native local function signed32(x: number): number return if x >= 2147483648 then x - 4294967296 else x end @native local function fracMul16(a: number, b: number): number return (16384 + a * b) // 32768 end @native local function bitexactCos(x: number): number local tmp = (4096 + x * x) // 8192 local x2 = tmp x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) return 1 + x2 end @native local function bitexactLog2tan(isin: number, icos: number): number local lc = RD.ilog(icos) local ls = RD.ilog(isin) icos = icos * 2 ^ (15 - lc) isin = isin * 2 ^ (15 - ls) return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) end -- energy (quant_bands.c, laplace.c) @native local function laplaceDecode(dec: RD.Dec, fs: number, decay: number): number local val = 0 local fm = decDecodeBin(dec, 15) local fl = 0 if fm >= fs then val += 1 fl = fs fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 + 1 while fs > 1 and fm >= fl + 2 * fs do fs *= 2 fl += fs fs = ((fs - 2) * decay) // 32768 fs += 1 val += 1 end if fs <= 1 then local di = rshift(fm - fl, 1) val += di fl += 2 * di end if fm < fl + fs then val = -val else fl += fs end end decUpdate(dec, fl, imin(fl + fs, 32768), 32768) return val end @native local function unquantCoarseEnergy(st: any, start: number, endb: number, intra: boolean, dec: RD.Dec, C: number, LM: number) local oldE = st.oldBandE local probBase = LM * 84 + (if intra then 42 else 0) -- e_prob_model[LM][intra], 0-based local coef, beta if intra then coef = 0 beta = BETA_INTRA else beta = BETA_COEF[LM + 1] coef = PRED_COEF[LM + 1] end local prev0, prev1 = 0, 0 local budget = dec.storage * 8 for i = start, endb - 1 do for c = 0, C - 1 do local t = tell(dec) local qi if budget - t >= 15 then local pi = 2 * imin(i, 20) qi = laplaceDecode(dec, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) elseif budget - t >= 2 then qi = decIcdf(dec, SMALL_ENERGY_ICDF, 1, 2) qi = if band(qi, 1) ~= 0 then -rshift(qi, 1) - 1 else rshift(qi, 1) elseif budget - t >= 1 then qi = if decBitLogp(dec, 1) then -1 else 0 else qi = -1 end local q = qi local k = i + c * NB_EBANDS + 1 local e = max(-9, oldE[k]) local prev = if c == 0 then prev0 else prev1 oldE[k] = coef * e + prev + q prev = prev + q - beta * q if c == 0 then prev0 = prev else prev1 = prev end end end end @native local function unquantFineEnergy(st: any, start: number, endb: number, fineQuant: { number }, dec: RD.Dec, C: number) local oldE = st.oldBandE for i = start, endb - 1 do local extra = fineQuant[i + 1] if extra <= 0 then continue end if tell(dec) + C * extra > dec.storage * 8 then continue end for c = 0, C - 1 do local q2 = decBits(dec, extra) local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 oldE[i + c * NB_EBANDS + 1] += offset end end end @native local function unquantEnergyFinalise(st: any, start: number, endb: number, fineQuant: { number }, finePriority: { number }, bitsLeft: number, dec: RD.Dec, C: number) local oldE = st.oldBandE for prio = 0, 1 do local i = start while i < endb and bitsLeft >= C do if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then i += 1 continue end for c = 0, C - 1 do local q2 = decBits(dec, 1) local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) oldE[i + c * NB_EBANDS + 1] += offset bitsLeft -= 1 end i += 1 end end end -- bit allocation (rate.c) @native local function bits2pulses(bandI: number, LM: number, bits: number): number local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1] local lo, hi = 0, CACHE_BITS[base + 1] bits -= 1 for _ = 1, 6 do local mid = rshift(lo + hi + 1, 1) if CACHE_BITS[base + mid + 1] >= bits then hi = mid else lo = mid end end local loBits = if lo == 0 then -1 else CACHE_BITS[base + lo + 1] if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then return lo end return hi end @native local function pulses2bits(bandI: number, LM: number, pulses: number): number if pulses == 0 then return 0 end local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1] return CACHE_BITS[base + pulses + 1] + 1 end @native local function getPulses(i: number): number if i < 8 then return i end return lshift(8 + band(i, 7), rshift(i, 3) - 1) end -- clt_compute_allocation + interp_bits2pulses (decoder side) @native local function computeAllocation(start: number, endb: number, offsets: { number }, cap: { number }, allocTrim: number, total: number, pulses: { number }, ebits: { number }, finePriority: { number }, C: number, LM: number, ec: RD.Dec) total = imax(total, 0) local len = NB_EBANDS local skipStart = start local skipRsv = if total >= 8 then 8 else 0 total -= skipRsv local intensityRsv, dualStereoRsv = 0, 0 if C == 2 then intensityRsv = LOG2_FRAC_TABLE[endb - start + 1] if intensityRsv > total then intensityRsv = 0 else total -= intensityRsv dualStereoRsv = if total >= 8 then 8 else 0 total -= dualStereoRsv end end local bits1, bits2, thresh, trimOffset = BITS1, BITS2, THRESH, TRIM_OFFSET for j = start, endb - 1 do local w = EB[j + 2] - EB[j + 1] thresh[j + 1] = imax(C * 8, (3 * w * 2 ^ LM * 8) // 16) trimOffset[j + 1] = (C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) // 64 if w * 2 ^ LM == 1 then trimOffset[j + 1] -= C * 8 end end local lo, hi = 1, NB_ALLOC_VECTORS - 1 repeat local done = false local psum = 0 local mid = rshift(lo + hi, 1) for j = endb - 1, start, -1 do local N = EB[j + 2] - EB[j + 1] local bitsj = (C * N * ALLOC[mid * len + j + 1] * 2 ^ LM) // 4 if bitsj > 0 then bitsj = imax(0, bitsj + trimOffset[j + 1]) end bitsj += offsets[j + 1] if bitsj >= thresh[j + 1] or done then done = true psum += imin(bitsj, cap[j + 1]) elseif bitsj >= C * 8 then psum += C * 8 end end if psum > total then hi = mid - 1 else lo = mid + 1 end until lo > hi hi = lo lo -= 1 for j = start, endb - 1 do local N = EB[j + 2] - EB[j + 1] local bits1j = (C * N * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4 local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * N * ALLOC[hi * len + j + 1] * 2 ^ LM) // 4 if bits1j > 0 then bits1j = imax(0, bits1j + trimOffset[j + 1]) end if bits2j > 0 then bits2j = imax(0, bits2j + trimOffset[j + 1]) end if lo > 0 then bits1j += offsets[j + 1] end bits2j += offsets[j + 1] if offsets[j + 1] > 0 then skipStart = j end bits2j = imax(0, bits2j - bits1j) bits1[j + 1] = bits1j bits2[j + 1] = bits2j end -- interp_bits2pulses local bits = pulses local allocFloor = C * 8 local stereo = if C > 1 then 1 else 0 local logM = LM * 8 lo, hi = 0, 64 for _ = 1, 6 do local mid = rshift(lo + hi, 1) local psum = 0 local done = false for j = endb - 1, start, -1 do local tmp = bits1[j + 1] + (mid * bits2[j + 1]) // 64 if tmp >= thresh[j + 1] or done then done = true psum += imin(tmp, cap[j + 1]) elseif tmp >= allocFloor then psum += allocFloor end end if psum > total then hi = mid else lo = mid end end local psum = 0 local done = false for j = endb - 1, start, -1 do local tmp = bits1[j + 1] + (lo * bits2[j + 1]) // 64 if tmp < thresh[j + 1] and not done then if tmp >= allocFloor then tmp = allocFloor else tmp = 0 end else done = true end tmp = imin(tmp, cap[j + 1]) bits[j + 1] = tmp psum += tmp end local codedBands = endb while true do local j = codedBands - 1 if j <= skipStart then total += skipRsv break end local left = total - psum local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0) local bandWidth = EB[codedBands + 1] - EB[j + 1] local bandBits = bits[j + 1] + percoeff * bandWidth + rem if bandBits >= imax(thresh[j + 1], allocFloor + 8) then if decBitLogp(ec, 1) then break end psum += 8 bandBits -= 8 end psum -= bits[j + 1] + intensityRsv if intensityRsv > 0 then intensityRsv = LOG2_FRAC_TABLE[j - start + 1] end psum += intensityRsv if bandBits >= allocFloor then psum += allocFloor bits[j + 1] = allocFloor else bits[j + 1] = 0 end codedBands -= 1 end local intensity, dualStereo = 0, false if intensityRsv > 0 then intensity = start + decUint(ec, codedBands + 1 - start) end if intensity <= start then total += dualStereoRsv dualStereoRsv = 0 end if dualStereoRsv > 0 then dualStereo = decBitLogp(ec, 1) end local left = total - psum local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff for j = start, codedBands - 1 do bits[j + 1] += percoeff * (EB[j + 2] - EB[j + 1]) end for j = start, codedBands - 1 do local tmp = imin(left, EB[j + 2] - EB[j + 1]) bits[j + 1] += tmp left -= tmp end local balance = 0 local j = start while j < codedBands do local N0 = EB[j + 2] - EB[j + 1] local N = N0 * 2 ^ LM local bit = bits[j + 1] + balance local excess if N > 1 then excess = imax(bit - cap[j + 1], 0) bits[j + 1] = bit - excess local den = C * N + (if C == 2 and N > 2 and not dualStereo and j < intensity then 1 else 0) local NClogN = den * (LOGN[j + 1] + logM) local offset = (NClogN // 2) - den * FINE_OFFSET if N == 2 then offset += (den * 8) // 4 end if bits[j + 1] + offset < den * 2 * 8 then offset += NClogN // 4 elseif bits[j + 1] + offset < den * 3 * 8 then offset += NClogN // 8 end local eb = imax(0, bits[j + 1] + offset + den * 4) eb = (eb // den) // 8 if C * eb > (bits[j + 1] // 8) then eb = (bits[j + 1] // 2 ^ stereo) // 8 end eb = imin(eb, MAX_FINE_BITS) finePriority[j + 1] = if eb * (den * 8) >= bits[j + 1] + offset then 1 else 0 bits[j + 1] -= C * eb * 8 ebits[j + 1] = eb else excess = imax(0, bit - C * 8) bits[j + 1] = bit - excess ebits[j + 1] = 0 finePriority[j + 1] = 1 end if excess > 0 then local extraFine = imin(excess // 2 ^ (stereo + BITRES), MAX_FINE_BITS - ebits[j + 1]) ebits[j + 1] += extraFine local extraBits = extraFine * C * 8 finePriority[j + 1] = if extraBits >= excess - balance then 1 else 0 excess -= extraBits end balance = excess j += 1 end while j < endb do ebits[j + 1] = (bits[j + 1] // 2 ^ stereo) // 8 bits[j + 1] = 0 finePriority[j + 1] = if ebits[j + 1] < 1 then 1 else 0 j += 1 end return codedBands, balance, intensity, dualStereo end -- PVQ (cwrs.c, vq.c) @native local function cwrsi(n: number, k: number, i: number, iy: { number }): number local yy = 0 local idx = 1 local p, k0, val while n > 2 do if k >= n then local rowBase = n * UK + 1 p = U[rowBase + k + 1] local neg = i >= p if neg then i -= p end k0 = k local q = U[rowBase + n] if q > i then k = n repeat k -= 1 p = U[k * UK + n + 1] until p <= i else p = U[rowBase + k] while p > i do k -= 1 p = U[rowBase + k] end end i -= p val = if neg then k - k0 else k0 - k iy[idx] = val idx += 1 yy += val * val else p = U[k * UK + n + 1] local q = U[(k + 1) * UK + n + 1] if p <= i and i < q then i -= p iy[idx] = 0 idx += 1 else local neg = i >= q if neg then i -= q end k0 = k repeat k -= 1 p = U[k * UK + n + 1] until p <= i i -= p val = if neg then k - k0 else k0 - k iy[idx] = val idx += 1 yy += val * val end end n -= 1 end p = 2 * k + 1 local neg = i >= p if neg then i -= p end k0 = k k = rshift(i + 1, 1) if k ~= 0 then i -= 2 * k - 1 end val = if neg then k - k0 else k0 - k iy[idx] = val yy += val * val val = if i ~= 0 then -k else k iy[idx + 1] = val yy += val * val return yy end @native local function expRotation1(X: number, len: number, stride: number, c: number, s: number) local ms = -s local p = X + 1 for _ = 0, len - stride - 1 do local x1 = W[p] local x2 = W[p + stride] W[p + stride] = c * x2 + s * x1 W[p] = c * x1 + ms * x2 p += 1 end p = X + len - 2 * stride for _ = len - 2 * stride - 1, 0, -1 do local x1 = W[p] local x2 = W[p + stride] W[p + stride] = c * x2 + s * x1 W[p] = c * x1 + ms * x2 p -= 1 end end local SPREAD_FACTOR = { 15, 10, 5 } @native local function expRotation(X: number, len: number, dir: number, stride: number, K: number, spread: number) if 2 * K >= len or spread == 0 then return end local factor = SPREAD_FACTOR[spread] local gain = len / (len + factor * K) local theta = 0.5 * (gain * gain) local c = cos(0.5 * math.pi * theta) local s = cos(0.5 * math.pi * (1 - theta)) local stride2 = 0 if len >= 8 * stride then stride2 = 1 while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do stride2 += 1 end end len = len // stride for i = 0, stride - 1 do local x = X + i * len if dir < 0 then if stride2 ~= 0 then expRotation1(x, len, stride2, s, c) end expRotation1(x, len, 1, c, s) else expRotation1(x, len, 1, c, -s) if stride2 ~= 0 then expRotation1(x, len, stride2, s, -c) end end end end @native local function renormaliseVector(X: number, N: number, gain: number) local E = 1e-15 for i = X + 1, X + N do local v = W[i] E += v * v end local g = gain / sqrt(E) for i = X + 1, X + N do W[i] *= g end end @native local function algUnquant(X: number, N: number, K: number, spread: number, B: number, dec: RD.Dec, gain: number): number local iy = IY local ft = U[N * UK + K + 1] + U[N * UK + K + 2] local Ryy = cwrsi(N, K, decUint(dec, ft), iy) local g = gain / sqrt(Ryy) for i = 1, N do W[X + i] = iy[i] * g end expRotation(X, N, -1, B, K, spread) if B <= 1 then return 1 end local N0 = N // B local mask = 0 for i = 0, B - 1 do for j = 1, N0 do if iy[i * N0 + j] ~= 0 then mask = bor(mask, lshift(1, i)) break end end end return mask end -- bands (bands.c) type Ctx = { i: number, intensity: number, spread: number, tf_change: number, ec: RD.Dec, remaining_bits: number, seed: number, disable_inv: boolean, avoid_split_noise: boolean, } local ctx: Ctx = { i = 0, intensity = 0, spread = 0, tf_change = 0, ec = (nil :: any), remaining_bits = 0, seed = 0, disable_inv = false, avoid_split_noise = false, } @native local function haar1(X: number, N0: number, stride: number) N0 = rshift(N0, 1) local s = 0.70710678 for i = 0, stride - 1 do for j = 0, N0 - 1 do local a = X + stride * 2 * j + i + 1 local b = a + stride local t1 = s * W[a] local t2 = s * W[b] W[a] = t1 + t2 W[b] = t1 - t2 end end end @native local function deinterleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) local N = N0 * stride local tmp = TMP if hadamard then local ob = stride - 2 for i = 0, stride - 1 do local o = ORDERY[ob + i + 1] * N0 for j = 0, N0 - 1 do tmp[o + j + 1] = W[X + j * stride + i + 1] end end else for i = 0, stride - 1 do for j = 0, N0 - 1 do tmp[i * N0 + j + 1] = W[X + j * stride + i + 1] end end end for k = 1, N do W[X + k] = tmp[k] end end @native local function interleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) local N = N0 * stride local tmp = TMP if hadamard then local ob = stride - 2 for i = 0, stride - 1 do local o = ORDERY[ob + i + 1] * N0 for j = 0, N0 - 1 do tmp[j * stride + i + 1] = W[X + o + j + 1] end end else for i = 0, stride - 1 do for j = 0, N0 - 1 do tmp[j * stride + i + 1] = W[X + i * N0 + j + 1] end end end for k = 1, N do W[X + k] = tmp[k] end end @native local function computeQn(N: number, b: number, offset: number, pulseCap: number, stereo: boolean): number local N2 = 2 * N - 1 if stereo and N == 2 then N2 -= 1 end local qb = tdiv(b + N2 * offset, N2) qb = imin(b - pulseCap - 32, qb) qb = imin(64, qb) if qb < 4 then return 1 end local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3)) return lshift(rshift(qn + 1, 1), 1) end @native local function computeTheta(N: number, b: number, B: number, B0: number, LM: number, stereo: boolean, fill: number) local i = ctx.i local ec = ctx.ec local pulseCap = LOGN[i + 1] + LM * 8 local offset = (pulseCap // 2) - (if stereo and N == 2 then QTHETA_OFFSET_TWOPHASE else QTHETA_OFFSET) local qn = computeQn(N, b, offset, pulseCap, stereo) if stereo and i >= ctx.intensity then qn = 1 end local t0 = tellFrac(ec) local itheta = 0 local inv = false if qn ~= 1 then if stereo and N > 2 then local p0 = 3 local x0 = qn // 2 local ft = p0 * (x0 + 1) + x0 local fs = decDecode(ec, ft) local x if fs < (x0 + 1) * p0 then x = fs // p0 else x = x0 + 1 + (fs - (x0 + 1) * p0) end if x <= x0 then decUpdate(ec, p0 * x, p0 * (x + 1), ft) else decUpdate(ec, (x - 1 - x0) + (x0 + 1) * p0, (x - x0) + (x0 + 1) * p0, ft) end itheta = x elseif B0 > 1 or stereo then itheta = decUint(ec, qn + 1) else local h = rshift(qn, 1) local ft = (h + 1) * (h + 1) local fm = decDecode(ec, ft) local fs, fl if fm < rshift(h * (h + 1), 1) then itheta = rshift(floor(sqrt(8 * fm + 1)) - 1, 1) fs = itheta + 1 fl = rshift(itheta * (itheta + 1), 1) else itheta = rshift(2 * (qn + 1) - floor(sqrt(8 * (ft - fm - 1) + 1)), 1) fs = qn + 1 - itheta fl = ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) end decUpdate(ec, fl, fl + fs, ft) end itheta = (itheta * 16384) // qn elseif stereo then if b > 16 and ctx.remaining_bits > 16 then inv = decBitLogp(ec, 2) end if ctx.disable_inv then inv = false end itheta = 0 end local qalloc = tellFrac(ec) - t0 b -= qalloc local imid, iside, delta if itheta == 0 then imid = 32767 iside = 0 fill = band(fill, lshift(1, B) - 1) delta = -16384 elseif itheta == 16384 then imid = 0 iside = 32767 fill = band(fill, lshift(lshift(1, B) - 1, B)) delta = 16384 else imid = bitexactCos(itheta) iside = bitexactCos(16384 - itheta) delta = fracMul16((N - 1) * 128, bitexactLog2tan(iside, imid)) end return b, fill, inv, imid, iside, delta, itheta, qalloc end @native local function quantBandN1(X: number, Y: number, lowbandOut: number): number local x = X local ec = ctx.ec for _ = 0, (if Y >= 0 then 1 else 0) do local sign = 0 if ctx.remaining_bits >= 8 then sign = decBits(ec, 1) ctx.remaining_bits -= 8 end W[x + 1] = if sign ~= 0 then -1 else 1 x = Y end if lowbandOut >= 0 then W[lowbandOut + 1] = W[X + 1] end return 1 end @native local function quantPartition(X: number, N: number, b: number, B: number, lowband: number, LM: number, gain: number, fill: number): number local i = ctx.i local B0 = B local cm = 0 local split = false if LM ~= -1 and N > 2 then local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + i + 1] split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 end if split then N = rshift(N, 1) local Y = X + N LM -= 1 if B == 1 then fill = bor(band(fill, 1), lshift(fill, 1)) end B = rshift(B + 1, 1) local _inv, imid, iside, delta, itheta, qalloc b, fill, _inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B0, LM, false, fill) local mid = imid / 32768 local side = iside / 32768 if B0 > 1 and band(itheta, 0x3fff) ~= 0 then if itheta > 8192 then delta -= delta // 2 ^ (4 - LM) else delta = imin(0, delta + (N * 8) // 2 ^ (5 - LM)) end end local mbits = imax(0, imin(b, tdiv(b - delta, 2))) local sbits = b - mbits ctx.remaining_bits -= qalloc local nextLowband2 = if lowband >= 0 then lowband + N else -1 local rebalance = ctx.remaining_bits if mbits >= sbits then cm = quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill) rebalance = mbits - (rebalance - ctx.remaining_bits) if rebalance > 24 and itheta ~= 0 then sbits += rebalance - 24 end cm = bor(cm, lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1))) else cm = lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1)) rebalance = sbits - (rebalance - ctx.remaining_bits) if rebalance > 24 and itheta ~= 16384 then mbits += rebalance - 24 end cm = bor(cm, quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill)) end else local q = bits2pulses(i, LM, b) local currBits = pulses2bits(i, LM, q) ctx.remaining_bits -= currBits while ctx.remaining_bits < 0 and q > 0 do ctx.remaining_bits += currBits q -= 1 currBits = pulses2bits(i, LM, q) ctx.remaining_bits -= currBits end if q ~= 0 then cm = algUnquant(X, N, getPulses(q), ctx.spread, B, ctx.ec, gain) else local cmMask = lshift(1, B) - 1 fill = band(fill, cmMask) if fill == 0 then for j = X + 1, X + N do W[j] = 0 end else local seed = ctx.seed if lowband < 0 then for j = X + 1, X + N do seed = lcg(seed) W[j] = signed32(seed) // 1048576 end cm = cmMask else for j = 0, N - 1 do seed = lcg(seed) local tmp = if band(seed, 0x8000) ~= 0 then 1 / 256 else -1 / 256 W[X + j + 1] = W[lowband + j + 1] + tmp end cm = fill end ctx.seed = seed renormaliseVector(X, N, gain) end end end return cm end @native local function quantBand(X: number, N: number, b: number, B: number, lowband: number, LM: number, lowbandOut: number, gain: number, lowbandScratch: number, fill: number): number local N0 = N local NB = N local B0 = B local timeDivide = 0 local recombine = 0 local longBlocks = B0 == 1 local tfChange = ctx.tf_change NB = NB // B if N == 1 then return quantBandN1(X, -1, lowbandOut) end if tfChange > 0 then recombine = tfChange end if lowbandScratch >= 0 and lowband >= 0 and (recombine ~= 0 or (band(NB, 1) == 0 and tfChange < 0) or B0 > 1) then for j = 1, N do W[lowbandScratch + j] = W[lowband + j] end lowband = lowbandScratch end for k = 0, recombine - 1 do if lowband >= 0 then haar1(lowband, rshift(N, k), lshift(1, k)) end fill = bor(BIT_INTERLEAVE[band(fill, 0xF) + 1], lshift(BIT_INTERLEAVE[rshift(fill, 4) + 1], 2)) end B = rshift(B, recombine) NB = lshift(NB, recombine) while band(NB, 1) == 0 and tfChange < 0 do if lowband >= 0 then haar1(lowband, NB, B) end fill = bor(fill, lshift(fill, B)) B = lshift(B, 1) NB = rshift(NB, 1) timeDivide += 1 tfChange += 1 end B0 = B local NB0 = NB if B0 > 1 and lowband >= 0 then deinterleaveHadamard(lowband, rshift(NB, recombine), lshift(B0, recombine), longBlocks) end local cm = quantPartition(X, N, b, B, lowband, LM, gain, fill) if B0 > 1 then interleaveHadamard(X, rshift(NB, recombine), lshift(B0, recombine), longBlocks) end NB = NB0 B = B0 for _ = 0, timeDivide - 1 do B = rshift(B, 1) NB = lshift(NB, 1) cm = bor(cm, rshift(cm, B)) haar1(X, NB, B) end for k = 0, recombine - 1 do cm = BIT_DEINTERLEAVE[cm + 1] haar1(X, rshift(N0, k), lshift(1, k)) end B = lshift(B, recombine) if lowbandOut >= 0 then local n = sqrt(N0) for j = 1, N0 do W[lowbandOut + j] = n * W[X + j] end end return band(cm, lshift(1, B) - 1) end @native local function stereoMerge(X: number, Y: number, mid: number, N: number) local xp, side = 0, 0 for j = 1, N do local y = W[Y + j] xp += y * W[X + j] side += y * y end xp = mid * xp local mm = mid * mid local El = mm + side - 2 * xp local Er = mm + side + 2 * xp if Er < 6e-4 or El < 6e-4 then for j = 1, N do W[Y + j] = W[X + j] end return end local lgain = 1 / sqrt(El) local rgain = 1 / sqrt(Er) for j = 1, N do local l = mid * W[X + j] local r = W[Y + j] W[X + j] = lgain * (l - r) W[Y + j] = rgain * (l + r) end end @native local function quantBandStereo(X: number, Y: number, N: number, b: number, B: number, lowband: number, LM: number, lowbandOut: number, lowbandScratch: number, fill: number): number if N == 1 then return quantBandN1(X, Y, lowbandOut) end local origFill = fill local inv, imid, iside, delta, itheta, qalloc b, fill, inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B, LM, true, fill) local mid = imid / 32768 local side = iside / 32768 local cm if N == 2 then local mbits = b local sbits = 0 if itheta ~= 0 and itheta ~= 16384 then sbits = 8 end mbits -= sbits local c = itheta > 8192 ctx.remaining_bits -= qalloc + sbits local x2, y2 = X, Y if c then x2, y2 = Y, X end local sign = 0 if sbits ~= 0 then sign = decBits(ctx.ec, 1) end sign = 1 - 2 * sign cm = quantBand(x2, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, origFill) W[y2 + 1] = -sign * W[x2 + 2] W[y2 + 2] = sign * W[x2 + 1] local x0, x1 = mid * W[X + 1], mid * W[X + 2] local y0, y1 = side * W[Y + 1], side * W[Y + 2] W[X + 1] = x0 - y0 W[Y + 1] = x0 + y0 W[X + 2] = x1 - y1 W[Y + 2] = x1 + y1 else local mbits = imax(0, imin(b, tdiv(b - delta, 2))) local sbits = b - mbits ctx.remaining_bits -= qalloc local rebalance = ctx.remaining_bits if mbits >= sbits then cm = quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill) rebalance = mbits - (rebalance - ctx.remaining_bits) if rebalance > 24 and itheta ~= 0 then sbits += rebalance - 24 end cm = bor(cm, quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B))) else cm = quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B)) rebalance = sbits - (rebalance - ctx.remaining_bits) if rebalance > 24 and itheta ~= 16384 then mbits += rebalance - 24 end cm = bor(cm, quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill)) end end if N ~= 2 then stereoMerge(X, Y, mid, N) end if inv then for j = Y + 1, Y + N do W[j] = -W[j] end end return cm end @native local function quantAllBands(start: number, endb: number, hasY: boolean, N: number, collapse: { number }, pulses: { number }, shortBlocks: boolean, spread: number, dualStereo: boolean, intensity: number, tfRes: { number }, totalBits: number, balance: number, ec: RD.Dec, LM: number, codedBands: number, seed: number, disableInv: boolean): number local M = lshift(1, LM) local B = if shortBlocks then M else 1 local normOffset = M * EB[start + 1] local C = if hasY then 2 else 1 local norm = NORM_BASE local norm2 = NORM_BASE + M * EB[NB_EBANDS] - normOffset local lowbandScratch = M * EB[EFF_EBANDS] local lowbandOffset = 0 local updateLowband = true ctx.ec = ec ctx.intensity = intensity ctx.seed = seed ctx.spread = spread ctx.disable_inv = disableInv ctx.avoid_split_noise = B > 1 for i = start, endb - 1 do ctx.i = i local last = i == endb - 1 local X = M * EB[i + 1] local Y = if hasY then N + M * EB[i + 1] else -1 local Nb = M * EB[i + 2] - M * EB[i + 1] local t = tellFrac(ec) if i ~= start then balance -= t end local remainingBits = totalBits - t - 1 ctx.remaining_bits = remainingBits local b if i <= codedBands - 1 then local currBalance = tdiv(balance, imin(3, codedBands - i)) b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance))) else b = 0 end if (M * EB[i + 1] - Nb >= M * EB[start + 1] or i == start + 1) and (updateLowband or lowbandOffset == 0) then lowbandOffset = i end if i == start + 1 then local n1 = M * (EB[start + 2] - EB[start + 1]) local n2 = M * (EB[start + 3] - EB[start + 2]) for k = 0, n2 - n1 - 1 do W[norm + n1 + k + 1] = W[norm + 2 * n1 - n2 + k + 1] end if dualStereo then for k = 0, n2 - n1 - 1 do W[norm2 + n1 + k + 1] = W[norm2 + 2 * n1 - n2 + k + 1] end end end local tfChange = tfRes[i + 1] ctx.tf_change = tfChange if last then lowbandScratch = -1 end local effectiveLowband = -1 local xcm, ycm if lowbandOffset ~= 0 and (spread ~= SPREAD_AGGRESSIVE or B > 1 or tfChange < 0) then effectiveLowband = imax(0, M * EB[lowbandOffset + 1] - normOffset - Nb) local foldStart = lowbandOffset repeat foldStart -= 1 until M * EB[foldStart + 1] <= effectiveLowband + normOffset local foldEnd = lowbandOffset - 1 repeat foldEnd += 1 until not (foldEnd < i and M * EB[foldEnd + 1] < effectiveLowband + normOffset + Nb) xcm, ycm = 0, 0 local fi = foldStart repeat xcm = bor(xcm, collapse[fi * C + 1]) ycm = bor(ycm, collapse[fi * C + C]) fi += 1 until fi >= foldEnd else xcm = lshift(1, B) - 1 ycm = xcm end if dualStereo and i == intensity then dualStereo = false for j = 1, M * EB[i + 1] - normOffset do W[norm + j] = 0.5 * (W[norm + j] + W[norm2 + j]) end end if dualStereo then xcm = quantBand(X, Nb, b // 2, B, if effectiveLowband ~= -1 then norm + effectiveLowband else -1, LM, if last then -1 else norm + M * EB[i + 1] - normOffset, 1, lowbandScratch, xcm) ycm = quantBand(Y, Nb, b // 2, B, if effectiveLowband ~= -1 then norm2 + effectiveLowband else -1, LM, if last then -1 else norm2 + M * EB[i + 1] - normOffset, 1, lowbandScratch, ycm) else local lb = if effectiveLowband ~= -1 then norm + effectiveLowband else -1 local lo = if last then -1 else norm + M * EB[i + 1] - normOffset if hasY then xcm = quantBandStereo(X, Y, Nb, b, B, lb, LM, lo, lowbandScratch, bor(xcm, ycm)) else xcm = quantBand(X, Nb, b, B, lb, LM, lo, 1, lowbandScratch, bor(xcm, ycm)) end ycm = xcm end collapse[i * C + 1] = band(xcm, 255) collapse[i * C + C] = band(ycm, 255) balance += pulses[i + 1] + t updateLowband = b > Nb * 8 ctx.avoid_split_noise = false end return ctx.seed end @native local function antiCollapse(st: any, C: number, size: number, LM: number, start: number, endb: number, collapse: { number }, pulses: { number }, seed: number) local logE, prev1logE, prev2logE = st.oldBandE, st.oldLogE, st.oldLogE2 for i = start, endb - 1 do local N0 = EB[i + 2] - EB[i + 1] local depth = rshift((1 + pulses[i + 1]) // N0, LM) local thresh = 0.5 * exp2(-0.125 * depth) local sqrt1 = 1 / sqrt(N0 * 2 ^ LM) for c = 0, C - 1 do local k0 = c * NB_EBANDS + i + 1 local prev1 = prev1logE[k0] local prev2 = prev2logE[k0] if C == 1 then prev1 = max(prev1, prev1logE[NB_EBANDS + i + 1]) prev2 = max(prev2, prev2logE[NB_EBANDS + i + 1]) end local Ediff = max(0, logE[k0] - min(prev1, prev2)) local r = 2 * exp2(-Ediff) if LM == 3 then r *= 1.41421356 end r = min(thresh, r) * sqrt1 local X = c * size + EB[i + 1] * 2 ^ LM local renorm = false local cmask = collapse[i * C + c + 1] for k = 0, 2 ^ LM - 1 do if band(cmask, lshift(1, k)) == 0 then for j = 0, N0 - 1 do seed = lcg(seed) W[X + j * 2 ^ LM + k + 1] = if band(seed, 0x8000) ~= 0 then r else -r end renorm = true end end if renorm then renormaliseVector(X, N0 * 2 ^ LM, 1) end end end end @native local function denormaliseBands(X: number, freq: { number }, logE: { number }, eoff: number, start: number, endb: number, M: number, silence: boolean) local N = M * SHORT_MDCT local bound = M * EB[endb + 1] if silence then bound = 0 start = 0 endb = 0 end local f = 1 local x = X + M * EB[start + 1] if start ~= 0 then for _ = 1, M * EB[start + 1] do freq[f] = 0 f += 1 end end for i = start, endb - 1 do local bandEnd = M * EB[i + 2] local lg = logE[eoff + i + 1] + E_MEANS[i + 1] local g = exp2(min(32, lg)) for _ = M * EB[i + 1], bandEnd - 1 do freq[f] = W[x + 1] * g f += 1 x += 1 end end for k = bound + 1, N do freq[k] = 0 end end @native local function celtSynthesis(st: any, C: number, CC: number, start: number, effEnd: number, isTransient: boolean, LM: number, silence: boolean, N: number) local M = lshift(1, LM) local B, NB, shift if isTransient then B = M NB = SHORT_MDCT shift = MAX_LM else B = 1 NB = SHORT_MDCT * M shift = MAX_LM - LM end local outBase = DECODE_BUFFER_SIZE - N + 1 local oldE = st.oldBandE local freq = FREQ if CC == 2 and C == 1 then denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence) for c = 1, 2 do local mem = st.mem[c] for b = 0, B - 1 do Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) end end elseif CC == 1 and C == 2 then denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence) denormaliseBands(N, FREQ2, oldE, NB_EBANDS, start, effEnd, M, silence) local f2 = FREQ2 for k = 1, N do freq[k] = 0.5 * freq[k] + 0.5 * f2[k] end local mem = st.mem[1] for b = 0, B - 1 do Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) end else for c = 0, CC - 1 do denormaliseBands(c * N, freq, oldE, c * NB_EBANDS, start, effEnd, M, silence) local mem = st.mem[c + 1] for b = 0, B - 1 do Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) end end end end -- comb_filter, in place on mem (1-based base index of sample 0) @native local function combFilter(mem: { number }, base: number, T0: number, T1: number, N: number, g0: number, g1: number, tapset0: number, tapset1: number, overlap: number) if g0 == 0 and g1 == 0 then return end T0 = imax(T0, COMBFILTER_MINPERIOD) T1 = imax(T1, COMBFILTER_MINPERIOD) local ga, gb = COMB_GAINS[tapset0 + 1], COMB_GAINS[tapset1 + 1] local g00, g01, g02 = g0 * ga[1], g0 * ga[2], g0 * ga[3] local g10, g11, g12 = g1 * gb[1], g1 * gb[2], g1 * gb[3] local x1 = mem[base - T1 + 1] local x2 = mem[base - T1] local x3 = mem[base - T1 - 1] local x4 = mem[base - T1 - 2] if g0 == g1 and T0 == T1 and tapset0 == tapset1 then overlap = 0 end local i = 0 while i < overlap do local p = base + i local x0 = mem[p - T1 + 2] local w = WINDOW[i + 1] local f = w * w local of = 1 - f mem[p] = mem[p] + (of * g00) * mem[p - T0] + (of * g01) * (mem[p - T0 + 1] + mem[p - T0 - 1]) + (of * g02) * (mem[p - T0 + 2] + mem[p - T0 - 2]) + (f * g10) * x2 + (f * g11) * (x1 + x3) + (f * g12) * (x0 + x4) x4 = x3 x3 = x2 x2 = x1 x1 = x0 i += 1 end if g1 == 0 then return end -- constant part (comb_filter_const) local p = base + i x4 = mem[p - T1 - 2] x3 = mem[p - T1 - 1] x2 = mem[p - T1] x1 = mem[p - T1 + 1] for q = p, base + N - 1 do local x0 = mem[q - T1 + 2] mem[q] = mem[q] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4) x4 = x3 x3 = x2 x2 = x1 x1 = x0 end end @native local function deemphasis(st: any, CC: number, N: number, pcm: { number }, pbase: number, accum: boolean) local coef0 = PREEMPH local xbase = DECODE_BUFFER_SIZE - N for c = 0, CC - 1 do local x = st.mem[c + 1] local m = st.preemph[c + 1] local y = pbase + c if accum then for j = 1, N do local tmp = x[xbase + j] + 1e-30 + m m = coef0 * tmp pcm[y] += tmp * (1 / 32768) y += CC end else for j = 1, N do local tmp = x[xbase + j] + 1e-30 + m m = coef0 * tmp pcm[y] = tmp * (1 / 32768) y += CC end end st.preemph[c + 1] = m end end @native local function resetState(st: any) st.rng = 0 st.error = 0 st.loss_duration = 0 st.plc_duration = 0 st.last_frame_type = FRAME_NONE st.skip_plc = true st.postfilter_period = 0 st.postfilter_period_old = 0 st.postfilter_gain = 0 st.postfilter_gain_old = 0 st.postfilter_tapset = 0 st.postfilter_tapset_old = 0 st.preemph[1] = 0 st.preemph[2] = 0 for c = 1, st.channels do local m = st.mem[c] for k = 1, DECODE_BUFFER_SIZE + OVERLAP do m[k] = 0 end end for k = 1, 2 * NB_EBANDS do st.oldBandE[k] = 0 st.oldLogE[k] = -28 st.oldLogE2[k] = -28 st.backgroundLogE[k] = 0 end end -- celt_decoder_init(48000, channels) @native function Celt.new(channels: number): any local st = { channels = channels, stream_channels = channels, start = 0, ["end"] = EFF_EBANDS, disable_inv = channels == 1, mem = {}, preemph = { 0, 0 }, oldBandE = table.create(2 * NB_EBANDS, 0), oldLogE = table.create(2 * NB_EBANDS, -28), oldLogE2 = table.create(2 * NB_EBANDS, -28), backgroundLogE = table.create(2 * NB_EBANDS, 0), } for c = 1, channels do st.mem[c] = table.create(DECODE_BUFFER_SIZE + OVERLAP, 0) end resetState(st) return st end Celt.reset = resetState -- noise-based concealment (celt_decode_lost, FRAME_PLC_NOISE) @native local function decodeLost(st: any, N: number, LM: number) local C = st.channels local start = st.start local endb = st["end"] local effEnd = imax(start, imin(endb, EFF_EBANDS)) for c = 1, C do table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) end local decay = 2 ^ LM * 0.0625 if st.last_frame_type ~= FRAME_PLC_NOISE then decay += max(1, imin(160, st.loss_duration) * 0.0625) end local oldE, bg = st.oldBandE, st.backgroundLogE for c = 0, C - 1 do for i = start, endb - 1 do local k = c * NB_EBANDS + i + 1 oldE[k] = max(bg[k], oldE[k] - decay) end end local seed = st.rng for c = 0, C - 1 do for i = start, effEnd - 1 do local boffs = N * c + EB[i + 1] * 2 ^ LM local blen = (EB[i + 2] - EB[i + 1]) * 2 ^ LM for j = 1, blen do seed = lcg(seed) W[boffs + j] = signed32(seed) // 1048576 end renormaliseVector(boffs, blen, 1) end end st.rng = seed celtSynthesis(st, C, C, start, effEnd, false, LM, false, N) local base = DECODE_BUFFER_SIZE - N + 1 for c = 1, C do st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD) st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD) combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old, st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP) if LM ~= 0 then combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, st.postfilter_period, N - SHORT_MDCT, st.postfilter_gain, st.postfilter_gain, st.postfilter_tapset, st.postfilter_tapset, OVERLAP) end end st.postfilter_period_old = st.postfilter_period st.postfilter_gain_old = st.postfilter_gain st.postfilter_tapset_old = st.postfilter_tapset st.skip_plc = true st.loss_duration = imin(10000, st.loss_duration + 2 ^ LM) st.plc_duration = imin(10000, st.plc_duration + 2 ^ LM) st.last_frame_type = FRAME_PLC_NOISE end -- celt_decode_with_ec (buf nil or len <= 1 conceals) @native function Celt.decode(st: any, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, dec: RD.Dec?, accum: boolean): number local CC = st.channels local C = st.stream_channels local start = st.start local endb = st["end"] local LM = 0 while LM <= MAX_LM and lshift(SHORT_MDCT, LM) ~= frameSize do LM += 1 end if LM > MAX_LM then return -1 end local M = lshift(1, LM) if len < 0 or len > 1275 then return -1 end local N = M * SHORT_MDCT local effEnd = imin(endb, EFF_EBANDS) if buf == nil or len <= 1 then decodeLost(st, N, LM) deemphasis(st, CC, N, pcm, pbase, accum) return frameSize end if st.loss_duration == 0 then st.skip_plc = false end if dec == nil then dec = RD.new(buf :: buffer, off, len) end local ec = dec :: RD.Dec local oldBandE, oldLogE, oldLogE2, bgLogE = st.oldBandE, st.oldLogE, st.oldLogE2, st.backgroundLogE if C == 1 then for i = 1, NB_EBANDS do oldBandE[i] = max(oldBandE[i], oldBandE[NB_EBANDS + i]) end end local totalBits = len * 8 local t = tell(ec) local silence if t >= totalBits then silence = true elseif t == 1 then silence = decBitLogp(ec, 15) else silence = false end if silence then t = len * 8 ec.nbits_total += t - tell(ec) end local postfilterGain, postfilterPitch, postfilterTapset = 0, 0, 0 if start == 0 and t + 16 <= totalBits then if decBitLogp(ec, 1) then local octave = decUint(ec, 6) postfilterPitch = lshift(16, octave) + decBits(ec, 4 + octave) - 1 local qg = decBits(ec, 3) if tell(ec) + 2 <= totalBits then postfilterTapset = decIcdf(ec, TAPSET_ICDF, 1, 2) end postfilterGain = 0.09375 * (qg + 1) end t = tell(ec) end local isTransient = false if LM > 0 and t + 3 <= totalBits then isTransient = decBitLogp(ec, 3) t = tell(ec) end local shortBlocks = isTransient local intraEner = if t + 3 <= totalBits then decBitLogp(ec, 3) else false if not intraEner and st.loss_duration ~= 0 then local missing = imin(10, rshift(st.loss_duration, LM)) local safety = if LM == 0 then 1.5 elseif LM == 1 then 0.5 else 0 for c = 0, 1 do for i = start, endb - 1 do local k = c * NB_EBANDS + i + 1 if oldBandE[k] < max(oldLogE[k], oldLogE2[k]) then local E0, E1, E2 = oldBandE[k], oldLogE[k], oldLogE2[k] local slope = max(E1 - E0, 0.5 * (E2 - E0)) slope = min(slope, 2) E0 -= max(0, (1 + missing) * slope) oldBandE[k] = max(-20, E0) else oldBandE[k] = min(min(oldBandE[k], oldLogE[k]), oldLogE2[k]) end oldBandE[k] -= safety end end end unquantCoarseEnergy(st, start, endb, intraEner, ec, C, LM) -- tf_decode local tfRes = TF_RES do local budget = ec.storage * 8 local tt = tell(ec) local logp = if isTransient then 2 else 4 local tfSelectRsv = LM > 0 and tt + logp + 1 <= budget if tfSelectRsv then budget -= 1 end local tfChanged, curr = 0, 0 for i = start, endb - 1 do if tt + logp <= budget then if decBitLogp(ec, logp) then curr = bit32.bxor(curr, 1) end tt = tell(ec) tfChanged = bor(tfChanged, curr) end tfRes[i + 1] = curr logp = if isTransient then 4 else 5 end local tfSelect = 0 local row = TF_SELECT[LM + 1] local ti = if isTransient then 4 else 0 if tfSelectRsv and row[ti + tfChanged + 1] ~= row[ti + 2 + tfChanged + 1] then tfSelect = if decBitLogp(ec, 1) then 1 else 0 end for i = start, endb - 1 do tfRes[i + 1] = row[ti + 2 * tfSelect + tfRes[i + 1] + 1] end end t = tell(ec) local spread = 2 if t + 4 <= totalBits then spread = decIcdf(ec, SPREAD_ICDF, 1, 5) end local cap = CAP for i = 0, NB_EBANDS - 1 do local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2) end local offsets = OFFSETS local dynallocLogp = 6 totalBits *= 8 t = tellFrac(ec) for i = start, endb - 1 do local width = C * (EB[i + 2] - EB[i + 1]) * 2 ^ LM local quanta = imin(width * 8, imax(48, width)) local loopLogp = dynallocLogp local boost = 0 while t + loopLogp * 8 < totalBits and boost < cap[i + 1] do local flag = decBitLogp(ec, loopLogp) t = tellFrac(ec) if not flag then break end boost += quanta totalBits -= quanta loopLogp = 1 end offsets[i + 1] = boost if boost > 0 then dynallocLogp = imax(2, dynallocLogp - 1) end end local allocTrim = if t + 48 <= totalBits then decIcdf(ec, TRIM_ICDF, 1, 7) else 5 local bits = len * 64 - tellFrac(ec) - 1 local antiCollapseRsv = if isTransient and LM >= 2 and bits >= (LM + 2) * 8 then 8 else 0 bits -= antiCollapseRsv local pulses, fineQuant, finePriority = PULSES, FINE_QUANT, FINE_PRIORITY local codedBands, balance, intensity, dualStereo = computeAllocation(start, endb, offsets, cap, allocTrim, bits, pulses, fineQuant, finePriority, C, LM, ec) unquantFineEnergy(st, start, endb, fineQuant, ec, C) for c = 1, CC do table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) end local collapse = COLLAPSE st.rng = quantAllBands(start, endb, C == 2, N, collapse, pulses, shortBlocks, spread, dualStereo, intensity, tfRes, len * 64 - antiCollapseRsv, balance, ec, LM, codedBands, st.rng, st.disable_inv) local antiCollapseOn = false if antiCollapseRsv > 0 then antiCollapseOn = decBits(ec, 1) ~= 0 end unquantEnergyFinalise(st, start, endb, fineQuant, finePriority, len * 8 - tell(ec), ec, C) if antiCollapseOn then antiCollapse(st, C, N, LM, start, endb, collapse, pulses, st.rng) end if silence then for i = 1, C * NB_EBANDS do oldBandE[i] = -28 end end celtSynthesis(st, C, CC, start, effEnd, isTransient, LM, silence, N) local base = DECODE_BUFFER_SIZE - N + 1 for c = 1, CC do st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD) st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD) combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old, st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP) if LM ~= 0 then combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, postfilterPitch, N - SHORT_MDCT, st.postfilter_gain, postfilterGain, st.postfilter_tapset, postfilterTapset, OVERLAP) end end st.postfilter_period_old = st.postfilter_period st.postfilter_gain_old = st.postfilter_gain st.postfilter_tapset_old = st.postfilter_tapset st.postfilter_period = postfilterPitch st.postfilter_gain = postfilterGain st.postfilter_tapset = postfilterTapset if LM ~= 0 then st.postfilter_period_old = st.postfilter_period st.postfilter_gain_old = st.postfilter_gain st.postfilter_tapset_old = st.postfilter_tapset end if C == 1 then for i = 1, NB_EBANDS do oldBandE[NB_EBANDS + i] = oldBandE[i] end end if not isTransient then for i = 1, 2 * NB_EBANDS do oldLogE2[i] = oldLogE[i] oldLogE[i] = oldBandE[i] end else for i = 1, 2 * NB_EBANDS do oldLogE[i] = min(oldLogE[i], oldBandE[i]) end end local maxBgIncrease = imin(160, st.loss_duration + M) * 0.001 for i = 1, 2 * NB_EBANDS do bgLogE[i] = min(bgLogE[i] + maxBgIncrease, oldBandE[i]) end for c = 0, 1 do for i = 0, start - 1 do local k = c * NB_EBANDS + i + 1 oldBandE[k] = 0 oldLogE[k] = -28 oldLogE2[k] = -28 end for i = endb, NB_EBANDS - 1 do local k = c * NB_EBANDS + i + 1 oldBandE[k] = 0 oldLogE[k] = -28 oldLogE2[k] = -28 end end st.rng = ec.rng deemphasis(st, CC, N, pcm, pbase, accum) st.loss_duration = 0 st.plc_duration = 0 st.last_frame_type = FRAME_NORMAL if tell(ec) > 8 * len then return -3 end if ec.error ~= 0 then st.error = 1 end return frameSize end return Celt end __FILES["codecs/audio/Opus/CeltEncoder"] = @native function() -- codecs/audio/Opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms, full band, CBR, long MDCTs only. -- The bitstream side is a port of the libopus 1.6 encoder paths (celt_encoder.c, quant_bands.c, laplace.c, rate.c, -- bands.c, vq.c, cwrs.c; BSD, licenses/libopus-BSD.txt); the analysis is simplified. local RE = __include("codecs/entropy/RangeCoder/Encoder") local T = __include("codecs/audio/Opus/CeltTables") local Mdct = __include("codecs/audio/Mdct") local CeltEncoder = {} local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift local min, max, sqrt, floor, cos, log, atan2 = math.min, math.max, math.sqrt, math.floor, math.cos, math.log, math.atan2 local encBitLogp, encIcdf, encBits, encUint, encEncode, encEncodeBin = RE.bitLogp, RE.icdf, RE.bits, RE.uint, RE.encode, RE.encodeBin local tell, tellFrac = RE.tell, RE.tellFrac local NB_EBANDS = 21 local OVERLAP = 120 local SHORT_MDCT = 120 local BITRES = 3 local MAX_FINE_BITS = 8 local FINE_OFFSET = 21 local QTHETA_OFFSET = 4 local PREEMPH = 0.85000610 local LM = 3 -- 20 ms frames local M = 8 local N = 960 local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 } local ALLOC = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104, } local NB_ALLOC_VECTORS = 11 local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 } local LOGN = T.logN400 local CACHE_INDEX = T.cache_index50 local CACHE_BITS = T.cache_bits50 local CACHE_CAPS = T.cache_caps50 local E_PROB = T.e_prob_model local E_MEANS = { 6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500, 4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500, 3.750000, } local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 } local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 } local BETA_INTRA = 4915 / 32768 local TF_SELECT = { 0, -2, 0, -3, 3, 0, 1, -1 } -- LM 3 local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } local SPREAD_ICDF = { 25, 23, 2, 0 } local SMALL_ENERGY_ICDF = { 2, 1, 0 } local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } local SPREAD_NORMAL = 2 local SPREAD_FACTOR = { 15, 10, 5 } local WINDOW = table.create(OVERLAP, 0) for i = 0, OVERLAP - 1 do local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s) end local PLAN = Mdct.new(2 * N) :: Mdct.Plan -- forward scale matching the decoder's backward MDCT (calibrated against codecs/audio/Opus/Mdct: tests/audio/opus_encode) local MDCT_SCALE = 2 / N -- PVQ codebook sizes U(n, k), flat: U[n * UK + k + 1] local UK = 177 local U = table.create(UK * UK, 0) U[1] = 1 for n = 1, UK - 1 do for k = 1, UK - 1 do U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k] end end @native local function pvqU(n: number, k: number): number return U[n * UK + k + 1] end @native local function imin(a: number, b: number): number return if a < b then a else b end @native local function imax(a: number, b: number): number return if a > b then a else b end @native local function tdiv(a: number, b: number): number local q = a / b return if q >= 0 then floor(q) else -floor(-q) end @native local function fracMul16(a: number, b: number): number return (16384 + a * b) // 32768 end @native local function bitexactCos(x: number): number local x2 = (4096 + x * x) // 8192 x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) return 1 + x2 end @native local function bitexactLog2tan(isin: number, icos: number): number local lc = RE.ilog(icos) local ls = RE.ilog(isin) icos = icos * 2 ^ (15 - lc) isin = isin * 2 ^ (15 - ls) return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) end -- ec_laplace_encode: returns the value actually coded (clamped in the flat tail) @native local function laplaceEncode(enc: RE.Enc, value: number, fs: number, decay: number): number local fl = 0 local val = value if val ~= 0 then local s = if val < 0 then -1 else 0 val = if val < 0 then -val else val fl = fs fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 -- ec_laplace_get_freq1 local i = 1 while fs > 0 and i < val do fs *= 2 fl += fs + 2 fs = (fs * decay) // 32768 i += 1 end if fs == 0 then local ndiMax = 32768 - fl + 1 - 1 ndiMax = rshift(ndiMax - s, 1) local di = imin(val - i, ndiMax - 1) fl += (2 * di + 1 + s) fs = imin(1, 32768 - fl) value = if s ~= 0 then -(i + di) else i + di else fs += 1 if s == 0 then fl += fs end end end encEncodeBin(enc, fl, fl + fs, 15) return value end type State = { channels: number, oldBandE: { number }, preMem: { number }, inMem: { { number } }, frames: number, X: { { number } }, bandLogE: { number }, bandE: { number }, error: { number }, work: { number }, tmp: { number }, iy: { number }, remaining: number, spread: number, dual: boolean, } @native function CeltEncoder.new(channels: number): State local inMem = {} local X = {} for c = 1, channels do inMem[c] = table.create(OVERLAP, 0) X[c] = table.create(N, 0) end return { channels = channels, oldBandE = table.create(2 * NB_EBANDS, 0), preMem = table.create(channels, 0), inMem = inMem, frames = 0, X = X, bandLogE = table.create(2 * NB_EBANDS, 0), bandE = table.create(2 * NB_EBANDS, 0), error = table.create(2 * NB_EBANDS, 0), work = table.create(2 * N, 0), tmp = table.create(2 * N, 0), iy = table.create(256, 0), remaining = 0, spread = SPREAD_NORMAL, dual = false, } end @native local function quantCoarseEnergy(st: State, intra: boolean, enc: RE.Enc, C: number, budget: number, nbBytes: number) local oldE, bandLogE, err = st.oldBandE, st.bandLogE, st.error local probBase = LM * 84 + (if intra then 42 else 0) local coef, beta if intra then coef, beta = 0, BETA_INTRA else coef, beta = PRED_COEF[LM + 1], BETA_COEF[LM + 1] end local maxDecay = min(16, nbBytes / 8) local prev0, prev1 = 0, 0 for i = 0, NB_EBANDS - 1 do for c = 0, C - 1 do local k = c * NB_EBANDS + i + 1 local x = bandLogE[k] local e = max(-9, oldE[k]) local prev = if c == 0 then prev0 else prev1 local f = x - coef * e - prev local qi = floor(0.5 + f) local decayBound = max(-28, oldE[k]) - maxDecay if qi < 0 and x < decayBound then qi += tdiv(decayBound - x, 1) if qi > 0 then qi = 0 end end local t = tell(enc) local bitsLeft = budget - t - 3 * C * (NB_EBANDS - i) if i ~= 0 and bitsLeft < 30 then if bitsLeft < 24 then qi = imin(1, qi) end if bitsLeft < 16 then qi = imax(-1, qi) end end if budget - t >= 15 then local pi = 2 * imin(i, 20) qi = laplaceEncode(enc, qi, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) elseif budget - t >= 2 then qi = imax(-1, imin(qi, 1)) encIcdf(enc, if qi < 0 then 1 else 2 * qi, SMALL_ENERGY_ICDF, 2) elseif budget - t >= 1 then qi = imin(0, qi) encBitLogp(enc, qi ~= 0, 1) else qi = -1 end err[k] = f - qi oldE[k] = coef * e + prev + qi prev = prev + qi - beta * qi if c == 0 then prev0 = prev else prev1 = prev end end end end @native local function quantFineEnergy(st: State, fineQuant: { number }, enc: RE.Enc, C: number) local oldE, err = st.oldBandE, st.error for i = 0, NB_EBANDS - 1 do local extra = fineQuant[i + 1] if extra <= 0 then continue end if tell(enc) + C * extra > enc.storage * 8 then continue end local frac = 2 ^ extra for c = 0, C - 1 do local k = c * NB_EBANDS + i + 1 local q2 = floor((err[k] + 0.5) * frac) q2 = math.clamp(q2, 0, frac - 1) encBits(enc, q2, extra) local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 oldE[k] += offset err[k] -= offset end end end @native local function quantEnergyFinalise(st: State, fineQuant: { number }, finePriority: { number }, bitsLeft: number, enc: RE.Enc, C: number) local oldE, err = st.oldBandE, st.error for prio = 0, 1 do local i = 0 while i < NB_EBANDS and bitsLeft >= C do if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then i += 1 continue end for c = 0, C - 1 do local k = c * NB_EBANDS + i + 1 local q2 = if err[k] < 0 then 0 else 1 encBits(enc, q2, 1) local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) oldE[k] += offset err[k] -= offset bitsLeft -= 1 end i += 1 end end end @native local function bits2pulses(bandI: number, lm: number, bits: number): number local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] local lo, hi = 0, CACHE_BITS[base + 1] bits -= 1 for _ = 1, 6 do local mid = rshift(lo + hi + 1, 1) if CACHE_BITS[base + mid + 1] >= bits then hi = mid else lo = mid end end local loBits = if lo == 0 then -1 else CACHE_BITS[base + lo + 1] if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then return lo end return hi end @native local function pulses2bits(bandI: number, lm: number, pulses: number): number if pulses == 0 then return 0 end local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] return CACHE_BITS[base + pulses + 1] + 1 end @native local function getPulses(i: number): number if i < 8 then return i end return lshift(8 + band(i, 7), rshift(i, 3) - 1) end -- clt_compute_allocation (encoder side): keeps every band it can, no intensity stereo, dual stereo for C == 2 @native local function computeAllocation(offsets: { number }, cap: { number }, allocTrim: number, total: number, pulses: { number }, ebits: { number }, finePriority: { number }, C: number, enc: RE.Enc, wantDual: boolean) local start, endb = 0, NB_EBANDS total = imax(total, 0) local len = NB_EBANDS local skipStart = start local skipRsv = if total >= 8 then 8 else 0 total -= skipRsv local intensityRsv, dualStereoRsv = 0, 0 if C == 2 then intensityRsv = LOG2_FRAC_TABLE[endb - start + 1] if intensityRsv > total then intensityRsv = 0 else total -= intensityRsv dualStereoRsv = if total >= 8 then 8 else 0 total -= dualStereoRsv end end local bits1, bits2, thresh, trimOffset = {}, {}, {}, {} for j = start, endb - 1 do local w = EB[j + 2] - EB[j + 1] thresh[j + 1] = imax(C * 8, (3 * w * 2 ^ LM * 8) // 16) trimOffset[j + 1] = (C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) // 64 if w * 2 ^ LM == 1 then trimOffset[j + 1] -= C * 8 end end local lo, hi = 1, NB_ALLOC_VECTORS - 1 repeat local done = false local psum = 0 local mid = rshift(lo + hi, 1) for j = endb - 1, start, -1 do local Nw = EB[j + 2] - EB[j + 1] local bitsj = (C * Nw * ALLOC[mid * len + j + 1] * 2 ^ LM) // 4 if bitsj > 0 then bitsj = imax(0, bitsj + trimOffset[j + 1]) end bitsj += offsets[j + 1] if bitsj >= thresh[j + 1] or done then done = true psum += imin(bitsj, cap[j + 1]) elseif bitsj >= C * 8 then psum += C * 8 end end if psum > total then hi = mid - 1 else lo = mid + 1 end until lo > hi hi = lo lo -= 1 for j = start, endb - 1 do local Nw = EB[j + 2] - EB[j + 1] local bits1j = (C * Nw * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4 local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * Nw * ALLOC[hi * len + j + 1] * 2 ^ LM) // 4 if bits1j > 0 then bits1j = imax(0, bits1j + trimOffset[j + 1]) end if bits2j > 0 then bits2j = imax(0, bits2j + trimOffset[j + 1]) end if lo > 0 then bits1j += offsets[j + 1] end bits2j += offsets[j + 1] if offsets[j + 1] > 0 then skipStart = j end bits2j = imax(0, bits2j - bits1j) bits1[j + 1] = bits1j bits2[j + 1] = bits2j end -- interp_bits2pulses local bits = pulses local allocFloor = C * 8 local stereo = if C > 1 then 1 else 0 local logM = LM * 8 lo, hi = 0, 64 for _ = 1, 6 do local mid = rshift(lo + hi, 1) local psum = 0 local done = false for j = endb - 1, start, -1 do local tmp = bits1[j + 1] + (mid * bits2[j + 1]) // 64 if tmp >= thresh[j + 1] or done then done = true psum += imin(tmp, cap[j + 1]) elseif tmp >= allocFloor then psum += allocFloor end end if psum > total then hi = mid else lo = mid end end local psum = 0 local done = false for j = endb - 1, start, -1 do local tmp = bits1[j + 1] + (lo * bits2[j + 1]) // 64 if tmp < thresh[j + 1] and not done then if tmp >= allocFloor then tmp = allocFloor else tmp = 0 end else done = true end tmp = imin(tmp, cap[j + 1]) bits[j + 1] = tmp psum += tmp end local codedBands = endb while true do local j = codedBands - 1 if j <= skipStart then total += skipRsv break end local left = total - psum local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0) local bandWidth = EB[codedBands + 1] - EB[j + 1] local bandBits = bits[j + 1] + percoeff * bandWidth + rem if bandBits >= imax(thresh[j + 1], allocFloor + 8) then -- keep every band that can be coded: signal "no more skipping" encBitLogp(enc, true, 1) break end psum -= bits[j + 1] + intensityRsv if intensityRsv > 0 then intensityRsv = LOG2_FRAC_TABLE[j - start + 1] end psum += intensityRsv if bandBits >= allocFloor then psum += allocFloor bits[j + 1] = allocFloor else bits[j + 1] = 0 end codedBands -= 1 end local intensity, dualStereo = 0, false if intensityRsv > 0 then intensity = codedBands -- no intensity stereo encUint(enc, intensity - start, codedBands + 1 - start) end if intensity <= start then total += dualStereoRsv dualStereoRsv = 0 end if dualStereoRsv > 0 then dualStereo = wantDual encBitLogp(enc, dualStereo, 1) end local left = total - psum local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff for j = start, codedBands - 1 do bits[j + 1] += percoeff * (EB[j + 2] - EB[j + 1]) end for j = start, codedBands - 1 do local tmp = imin(left, EB[j + 2] - EB[j + 1]) bits[j + 1] += tmp left -= tmp end local balance = 0 local j = start while j < codedBands do local N0 = EB[j + 2] - EB[j + 1] local Nw = N0 * 2 ^ LM local bit = bits[j + 1] + balance local excess if Nw > 1 then excess = imax(bit - cap[j + 1], 0) bits[j + 1] = bit - excess local den = C * Nw + (if C == 2 and Nw > 2 and not dualStereo and j < intensity then 1 else 0) local NClogN = den * (LOGN[j + 1] + logM) local offset = (NClogN // 2) - den * FINE_OFFSET if Nw == 2 then offset += (den * 8) // 4 end if bits[j + 1] + offset < den * 2 * 8 then offset += NClogN // 4 elseif bits[j + 1] + offset < den * 3 * 8 then offset += NClogN // 8 end local eb = imax(0, bits[j + 1] + offset + den * 4) eb = (eb // den) // 8 if C * eb > (bits[j + 1] // 8) then eb = (bits[j + 1] // 2 ^ stereo) // 8 end eb = imin(eb, MAX_FINE_BITS) finePriority[j + 1] = if eb * (den * 8) >= bits[j + 1] + offset then 1 else 0 bits[j + 1] -= C * eb * 8 ebits[j + 1] = eb else excess = imax(0, bit - C * 8) bits[j + 1] = bit - excess ebits[j + 1] = 0 finePriority[j + 1] = 1 end if excess > 0 then local extraFine = imin(excess // 2 ^ (stereo + BITRES), MAX_FINE_BITS - ebits[j + 1]) ebits[j + 1] += extraFine local extraBits = extraFine * C * 8 finePriority[j + 1] = if extraBits >= excess - balance then 1 else 0 excess -= extraBits end balance = excess j += 1 end while j < endb do ebits[j + 1] = (bits[j + 1] // 2 ^ stereo) // 8 bits[j + 1] = 0 finePriority[j + 1] = if ebits[j + 1] < 1 then 1 else 0 j += 1 end return codedBands, balance, intensity, dualStereo end -- icwrs: the index of the pulse vector iy[1..n] @native local function icwrs(n: number, iy: { number }): number local j = n -- 1-based position of _y[n - 1] local i = if iy[j] < 0 then 1 else 0 local k = math.abs(iy[j]) repeat j -= 1 local nn = n - (j - 1) -- _n - j with 0-based j i += pvqU(nn, k) k += math.abs(iy[j]) if iy[j] < 0 then i += pvqU(nn, k + 1) end until j <= 1 return i end @native local function expRotation1(X: { number }, xo: number, len: number, stride: number, c: number, s: number) local ms = -s local p = xo + 1 for _ = 0, len - stride - 1 do local x1 = X[p] local x2 = X[p + stride] X[p + stride] = c * x2 + s * x1 X[p] = c * x1 + ms * x2 p += 1 end p = xo + len - 2 * stride for _ = len - 2 * stride - 1, 0, -1 do local x1 = X[p] local x2 = X[p + stride] X[p + stride] = c * x2 + s * x1 X[p] = c * x1 + ms * x2 p -= 1 end end -- exp_rotation(X, len, dir = 1, stride, K, spread): the encoder's spreading rotation @native local function expRotation(X: { number }, xo: number, len: number, stride: number, K: number, spread: number) if 2 * K >= len or spread == 0 then return end local factor = SPREAD_FACTOR[spread] local gain = len / (len + factor * K) local theta = 0.5 * (gain * gain) local c = cos(0.5 * math.pi * theta) local s = cos(0.5 * math.pi * (1 - theta)) local stride2 = 0 if len >= 8 * stride then stride2 = 1 while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do stride2 += 1 end end len = len // stride for i = 0, stride - 1 do local x = xo + i * len expRotation1(X, x, len, 1, c, -s) if stride2 ~= 0 then expRotation1(X, x, len, stride2, s, -c) end end end -- op_pvq_search: the K-pulse vector closest to X[xo + 1 .. xo + n] into iy[1..n] @native local function pvqSearch(X: { number }, xo: number, n: number, K: number, iy: { number }, y: { number }, absx: { number }) local sign = y -- reuse: y holds 2 * |pulses| during the search, signs kept in absx's sign local xy, yy = 0, 0 local pulsesLeft = K for j = 1, n do local v = X[xo + j] absx[j] = if v < 0 then -v else v sign[j] = 0 iy[j] = 0 end if K > rshift(n, 1) then local sum = 0 for j = 1, n do sum += absx[j] end if not (sum > 1e-15 and sum < 64) then absx[1] = 1 for j = 2, n do absx[j] = 0 end sum = 1 end local rcp = (K + 0.8) / sum for j = 1, n do local p = floor(rcp * absx[j]) iy[j] = p yy += p * p xy += absx[j] * p sign[j] = 2 * p pulsesLeft -= p end end if pulsesLeft > n + 3 then yy += pulsesLeft * pulsesLeft + pulsesLeft * sign[1] iy[1] += pulsesLeft pulsesLeft = 0 end for _ = 1, pulsesLeft do yy += 1 local best = 1 local rxy = xy + absx[1] local bestNum = rxy * rxy local bestDen = yy + sign[1] for j = 2, n do rxy = xy + absx[j] local num = rxy * rxy local den = yy + sign[j] if bestDen * num > den * bestNum then bestDen, bestNum, best = den, num, j end end xy += absx[best] yy += sign[best] sign[best] += 2 iy[best] += 1 end for j = 1, n do if X[xo + j] < 0 then iy[j] = -iy[j] end end end local SCRATCH_Y = table.create(256, 0) local SCRATCH_A = table.create(256, 0) local ROT = table.create(256, 0) @native local function algQuant(st: State, X: { number }, xo: number, n: number, K: number, enc: RE.Enc) for j = 1, n do ROT[j] = X[xo + j] end expRotation(ROT, 0, n, 1, K, st.spread) local iy = st.iy pvqSearch(ROT, 0, n, K, iy, SCRATCH_Y, SCRATCH_A) encUint(enc, icwrs(n, iy), pvqU(n, K) + pvqU(n, K + 1)) end @native local function computeQn(n: number, b: number, offset: number, pulseCap: number): number local N2 = 2 * n - 1 local qb = tdiv(b + N2 * offset, N2) qb = imin(b - pulseCap - 32, qb) qb = imin(64, qb) if qb < 4 then return 1 end local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3)) return lshift(rshift(qn + 1, 1), 1) end -- quant_partition (encoder, B = 1, mono): returns nothing (no resynthesis) @native local function quantPartition(st: State, bandI: number, X: { number }, xo: number, n: number, b: number, lm: number, enc: RE.Enc) local split = false if lm ~= -1 and n > 2 then local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 end if split then n = rshift(n, 1) local yo = xo + n lm -= 1 -- compute_theta (mono split, B0 = 1: triangular pdf) local pulseCap = LOGN[bandI + 1] + lm * 8 local offset = (pulseCap // 2) - QTHETA_OFFSET local qn = computeQn(n, b, offset, pulseCap) local t0 = tellFrac(enc) local itheta = 0 if qn ~= 1 then local emid, eside = 1e-15, 1e-15 for j = 1, n do emid += X[xo + j] * X[xo + j] eside += X[yo + j] * X[yo + j] end local it = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) itheta = (it * qn + 8192) // 16384 local h = rshift(qn, 1) local ft = (h + 1) * (h + 1) local fs = if itheta <= h then itheta + 1 else qn + 1 - itheta local fl = if itheta <= h then rshift(itheta * (itheta + 1), 1) else ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) encEncode(enc, fl, fl + fs, ft) itheta = (itheta * 16384) // qn end local qalloc = tellFrac(enc) - t0 b -= qalloc local delta if itheta == 0 then delta = -16384 elseif itheta == 16384 then delta = 16384 else local imid = bitexactCos(itheta) local iside = bitexactCos(16384 - itheta) delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) end local mbits = imax(0, imin(b, tdiv(b - delta, 2))) local sbits = b - mbits st.remaining -= qalloc local rebalance = st.remaining if mbits >= sbits then quantPartition(st, bandI, X, xo, n, mbits, lm, enc) rebalance = mbits - (rebalance - st.remaining) if rebalance > 24 and itheta ~= 0 then sbits += rebalance - 24 end quantPartition(st, bandI, X, yo, n, sbits, lm, enc) else quantPartition(st, bandI, X, yo, n, sbits, lm, enc) rebalance = sbits - (rebalance - st.remaining) if rebalance > 24 and itheta ~= 16384 then mbits += rebalance - 24 end quantPartition(st, bandI, X, xo, n, mbits, lm, enc) end else local q = bits2pulses(bandI, lm, b) local currBits = pulses2bits(bandI, lm, q) st.remaining -= currBits while st.remaining < 0 and q > 0 do st.remaining += currBits q -= 1 currBits = pulses2bits(bandI, lm, q) st.remaining -= currBits end if q ~= 0 then algQuant(st, X, xo, n, getPulses(q), enc) end end end -- quant_band_stereo (encoder, N > 2, B = 1): the mid / side angle (step pdf), then mid and side as mono bands; -- qn == 1 falls back to intensity stereo (with the inversion bit when there is room) @native local function quantBandStereo(st: State, i: number, n: number, xo: number, b: number, enc: RE.Enc) local L, R = st.X[1], st.X[2] local pulseCap = LOGN[i + 1] + LM * 8 local offset = (pulseCap // 2) - QTHETA_OFFSET local qn = computeQn(n, b, offset, pulseCap) -- stereo_itheta: the angle between mid and side energies local emid, eside = 1e-15, 1e-15 for j = 1, n do local m = 0.5 * L[xo + j] + 0.5 * R[xo + j] local sd = 0.5 * L[xo + j] - 0.5 * R[xo + j] emid += m * m eside += sd * sd end local itheta = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) local t0 = tellFrac(enc) @native local function intensityStereo() local left, right = st.bandE[i + 1], st.bandE[NB_EBANDS + i + 1] local norm = 1e-15 + sqrt(1e-15 + left * left + right * right) local a1, a2 = left / norm, right / norm for j = 1, n do L[xo + j] = a1 * L[xo + j] + a2 * R[xo + j] end end if qn ~= 1 then itheta = (itheta * qn + 8192) // 16384 local p0 = 3 local x0 = qn // 2 local ft = p0 * (x0 + 1) + x0 if itheta <= x0 then encEncode(enc, p0 * itheta, p0 * (itheta + 1), ft) else encEncode(enc, (itheta - 1 - x0) + (x0 + 1) * p0, (itheta - x0) + (x0 + 1) * p0, ft) end itheta = (itheta * 16384) // qn if itheta == 0 then intensityStereo() else -- stereo_split: mid / side for j = 1, n do local l = 0.70710678 * L[xo + j] local r = 0.70710678 * R[xo + j] L[xo + j] = l + r R[xo + j] = r - l end end else local inv = itheta > 8192 if inv then for j = 1, n do R[xo + j] = -R[xo + j] end end intensityStereo() if b > 16 and st.remaining > 16 then encBitLogp(enc, inv, 2) end itheta = 0 end local qalloc = tellFrac(enc) - t0 b -= qalloc local delta if itheta == 0 then delta = -16384 elseif itheta == 16384 then delta = 16384 else local imid = bitexactCos(itheta) local iside = bitexactCos(16384 - itheta) delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) end local mbits = imax(0, imin(b, tdiv(b - delta, 2))) local sbits = b - mbits st.remaining -= qalloc local rebalance = st.remaining if mbits >= sbits then quantPartition(st, i, L, xo, n, mbits, LM, enc) rebalance = mbits - (rebalance - st.remaining) if rebalance > 24 and itheta ~= 0 then sbits += rebalance - 24 end quantPartition(st, i, R, xo, n, sbits, LM, enc) else quantPartition(st, i, R, xo, n, sbits, LM, enc) rebalance = sbits - (rebalance - st.remaining) if rebalance > 24 and itheta ~= 16384 then mbits += rebalance - 24 end quantPartition(st, i, L, xo, n, mbits, LM, enc) end end -- quant_all_bands (encoder): mono, dual stereo or mid / side stereo @native local function quantAllBands(st: State, C: number, pulses: { number }, dualStereo: boolean, totalBits: number, balance: number, enc: RE.Enc, codedBands: number, intensity: number) for i = 0, NB_EBANDS - 1 do local xo = M * EB[i + 1] local nb = M * EB[i + 2] - M * EB[i + 1] local t = tellFrac(enc) if i ~= 0 then balance -= t end local remainingBits = totalBits - t - 1 st.remaining = remainingBits local b if i <= codedBands - 1 then local currBalance = tdiv(balance, imin(3, codedBands - i)) b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance))) else b = 0 end if dualStereo and i == intensity then dualStereo = false end if C == 2 and dualStereo then quantPartition(st, i, st.X[1], xo, nb, b // 2, LM, enc) quantPartition(st, i, st.X[2], xo, nb, b // 2, LM, enc) elseif C == 2 then quantBandStereo(st, i, nb, xo, b, enc) else quantPartition(st, i, st.X[1], xo, nb, b, LM, enc) end balance += pulses[i + 1] + t end end @native function CeltEncoder.encodeFrame(st: State, pcm: { number }, base: number, stride: number, nbBytes: number): buffer local C = st.channels local work, tmp = st.work, st.tmp local silent = true for c = 1, C do local inMem = st.inMem[c] local m = st.preMem[c] -- tmp[1..1080] = the last 120 pre-emphasised samples + this frame's 960 for k = 1, OVERLAP do tmp[k] = inMem[k] end for k = 0, N - 1 do local x = pcm[base + k * stride + c - 1] * 32768 if x ~= 0 then silent = false end tmp[OVERLAP + k + 1] = x - m m = PREEMPH * x end st.preMem[c] = m for k = 1, OVERLAP do inMem[k] = tmp[N + k] end local q = 420 -- (2N - (N + OVERLAP)) / 2 zeros at each end for k = 1, q do work[k] = 0 work[2 * N - k + 1] = 0 end for k = 1, OVERLAP do work[q + k] = tmp[k] * WINDOW[k] work[q + N + k] = tmp[N + k] * WINDOW[OVERLAP - k + 1] end for k = OVERLAP + 1, N do work[q + k] = tmp[k] end local X = st.X[c] Mdct.forward(PLAN, work, 1, X, 1, 1, MDCT_SCALE) for i = 0, NB_EBANDS - 1 do local a, z = M * EB[i + 1] + 1, M * EB[i + 2] local s = 1e-27 for k = a, z do s += X[k] * X[k] end local E = sqrt(s) st.bandE[(c - 1) * NB_EBANDS + i + 1] = E st.bandLogE[(c - 1) * NB_EBANDS + i + 1] = log(E) / log(2) - E_MEANS[i + 1] local g = 1 / (1e-27 + E) for k = a, z do X[k] *= g end end end local enc = RE.new(nbBytes) local totalBits = nbBytes * 8 local oldE = st.oldBandE if silent then encBitLogp(enc, true, 15) enc.nbits_total += totalBits - tell(enc) RE.done(enc) for i = 1, 2 * NB_EBANDS do oldE[i] = -28 end st.frames += 1 return enc.buf end encBitLogp(enc, false, 15) if tell(enc) + 16 <= totalBits then encBitLogp(enc, false, 1) -- no post-filter end if tell(enc) + 3 <= totalBits then encBitLogp(enc, false, 3) -- not transient end local intra = st.frames == 0 if tell(enc) + 3 <= totalBits then encBitLogp(enc, intra, 3) else intra = false end if C == 1 then for i = 1, NB_EBANDS do oldE[i] = max(oldE[i], oldE[NB_EBANDS + i]) end end quantCoarseEnergy(st, intra, enc, C, totalBits, nbBytes) -- tf_encode: no changes do local budget = totalBits local tt = tell(enc) local logp = 4 if tt + logp + 1 <= budget then budget -= 1 end for _ = 0, NB_EBANDS - 1 do if tt + logp <= budget then encBitLogp(enc, false, logp) tt = tell(enc) end logp = 5 end -- tf_select is only coded when it changes something: not for LM 3 without changes local _ = TF_SELECT end if tell(enc) + 4 <= totalBits then encIcdf(enc, st.spread, SPREAD_ICDF, 5) end local cap = {} for i = 0, NB_EBANDS - 1 do local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2) end local offsets = table.create(NB_EBANDS, 0) local total8 = totalBits * 8 local t = tellFrac(enc) for i = 0, NB_EBANDS - 1 do if t + 6 * 8 < total8 and 0 < cap[i + 1] then encBitLogp(enc, false, 6) -- no dynamic allocation boost t = tellFrac(enc) end end if t + 48 <= total8 then encIcdf(enc, 5, TRIM_ICDF, 7) end local bits = nbBytes * 64 - tellFrac(enc) - 1 local pulses, fineQuant, finePriority = table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0) local codedBands, balance, intensity, dualStereo = computeAllocation(offsets, cap, 5, bits, pulses, fineQuant, finePriority, C, enc, st.dual) quantFineEnergy(st, fineQuant, enc, C) quantAllBands(st, C, pulses, dualStereo, nbBytes * 64, balance, enc, codedBands, intensity) quantEnergyFinalise(st, fineQuant, finePriority, totalBits - tell(enc), enc, C) RE.done(enc) if C == 1 then for i = 1, NB_EBANDS do oldE[NB_EBANDS + i] = oldE[i] end end st.frames += 1 st.lastError = enc.error return enc.buf end CeltEncoder.FRAME = N CeltEncoder.DELAY = OVERLAP -- the decoder's output lags the input by the MDCT overlap return CeltEncoder end __FILES["codecs/audio/Opus/CeltTables"] = function() -- codecs/audio/Opus/CeltTables: from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, licenses/). return { logN400 = { 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36, }, cache_index50 = { -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41, 82, 82, 123, 164, 200, 222, 0, 0, 0, 0, 0, 0, 0, 0, 41, 41, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, 41, 41, 41, 41, 41, 41, 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305, 318, 328, 336, 123, 123, 123, 123, 123, 123, 123, 123, 240, 240, 240, 240, 305, 305, 305, 318, 318, 343, 351, 358, 364, 240, 240, 240, 240, 240, 240, 240, 240, 305, 305, 305, 305, 343, 343, 343, 351, 351, 370, 376, 382, 387, }, cache_bits50 = { 40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28, 31, 34, 36, 38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50, 51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, 63, 63, 65, 66, 67, 68, 69, 70, 71, 71, 40, 20, 33, 41, 48, 53, 57, 61, 64, 66, 69, 71, 73, 75, 76, 78, 80, 82, 85, 87, 89, 91, 92, 94, 96, 98, 101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123, 124, 126, 128, 40, 23, 39, 51, 60, 67, 73, 79, 83, 87, 91, 94, 97, 100, 102, 105, 107, 111, 115, 118, 121, 124, 126, 129, 131, 135, 139, 142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35, 28, 49, 65, 78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149, 153, 159, 165, 171, 176, 180, 185, 189, 192, 199, 205, 211, 216, 220, 225, 229, 232, 239, 245, 251, 21, 33, 58, 79, 97, 112, 125, 137, 148, 157, 166, 174, 182, 189, 195, 201, 207, 217, 227, 235, 243, 251, 17, 35, 63, 86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250, 25, 31, 55, 75, 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180, 185, 190, 200, 208, 215, 222, 229, 235, 240, 245, 255, 16, 36, 65, 89, 110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, 11, 41, 74, 103, 128, 151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138, 163, 186, 207, 227, 246, 12, 39, 71, 99, 123, 144, 164, 182, 198, 214, 228, 241, 253, 9, 44, 81, 113, 142, 168, 192, 214, 235, 255, 7, 49, 90, 127, 160, 191, 220, 247, 6, 51, 95, 134, 170, 203, 234, 7, 47, 87, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57, 106, 151, 192, 231, 5, 59, 111, 158, 202, 243, 5, 55, 103, 147, 187, 224, 5, 60, 113, 161, 206, 248, 4, 65, 122, 175, 224, 4, 67, 127, 182, 234, }, cache_caps50 = { 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224, 224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, 160, 160, 160, 160, 160, 160, 160, 160, 185, 185, 185, 185, 193, 193, 193, 183, 183, 172, 138, 64, 38, 240, 240, 240, 240, 240, 240, 240, 240, 207, 207, 207, 207, 204, 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185, 185, 185, 193, 193, 193, 193, 193, 193, 193, 183, 183, 172, 138, 65, 39, 207, 207, 207, 207, 207, 207, 207, 207, 204, 204, 204, 204, 201, 201, 201, 188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 194, 194, 194, 184, 184, 173, 139, 65, 39, 204, 204, 204, 204, 204, 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175, 140, 66, 40, }, e_prob_model = { 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79, 92, 78, 90, 79, 116, 41, 115, 40, 114, 40, 132, 26, 132, 26, 145, 17, 161, 12, 176, 10, 177, 11, 24, 179, 48, 138, 54, 135, 54, 132, 53, 134, 56, 133, 55, 132, 55, 132, 61, 114, 70, 96, 74, 88, 75, 88, 87, 74, 89, 66, 91, 67, 100, 59, 108, 50, 120, 40, 122, 37, 97, 43, 78, 50, 83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, 93, 74, 93, 74, 109, 40, 114, 36, 117, 34, 117, 34, 143, 17, 145, 18, 146, 19, 162, 12, 165, 10, 178, 7, 189, 6, 190, 8, 177, 9, 23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, 73, 91, 78, 89, 86, 80, 92, 66, 93, 64, 102, 59, 103, 60, 104, 60, 117, 52, 123, 44, 138, 35, 133, 31, 97, 38, 77, 45, 61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, 112, 38, 124, 26, 132, 27, 136, 19, 140, 20, 155, 14, 159, 16, 158, 18, 170, 13, 177, 10, 187, 8, 192, 6, 175, 9, 159, 10, 21, 178, 59, 110, 71, 86, 75, 85, 84, 83, 91, 66, 88, 73, 87, 72, 92, 75, 98, 72, 105, 58, 107, 54, 115, 52, 114, 55, 112, 56, 129, 51, 132, 40, 150, 33, 140, 29, 98, 35, 77, 42, 42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, 120, 36, 119, 33, 127, 33, 134, 34, 139, 21, 147, 23, 152, 20, 158, 25, 154, 26, 166, 21, 173, 16, 184, 13, 184, 10, 150, 13, 139, 15, 22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, 96, 67, 101, 73, 107, 72, 113, 55, 118, 52, 125, 52, 118, 52, 117, 55, 135, 49, 137, 39, 157, 32, 145, 29, 97, 33, 77, 40, }, } end __FILES["codecs/audio/Opus/Decoder"] = @native function() -- codecs/audio/Opus/Decoder: the Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c). -- SILK / hybrid / CELT mode switching, redundant CELT frames of mode transitions, cross-fades, PLC, multistream. local RD = __include("codecs/entropy/RangeCoder/Decoder") local Packet = __include("codecs/audio/Opus/Packet") local Celt = __include("codecs/audio/Opus/Celt") local Silk = __include("codecs/audio/Opus/Silk") local Decoder = {} local MODE_SILK, MODE_HYBRID, MODE_CELT = Packet.MODE_SILK_ONLY, Packet.MODE_HYBRID, Packet.MODE_CELT_ONLY local BW_NB, BW_MB, BW_WB, BW_SWB = Packet.BW_NB, Packet.BW_MB, Packet.BW_WB, Packet.BW_SWB local F20, F10, F5, F2_5 = 960, 480, 240, 120 local min, max = math.min, math.max local readu8 = buffer.readu8 local WINDOW = Celt.window local TRANS = table.create(F5 * 2, 0) local REDUND = table.create(F5 * 2, 0) local SILKTMP = table.create(F10 * 2, 0) local SILENCE = buffer.create(2) buffer.writeu8(SILENCE, 0, 0xFF) buffer.writeu8(SILENCE, 1, 0xFF) local EMPTY_EC = RD.new(buffer.create(0), 0, 0) local OFFS = table.create(48, 0) local SIZES = table.create(48, 0) type State = { channels: number, celt: any, silk: any, ctrl: any, stream_channels: number, frame_size: number, mode: number, bandwidth: number, prev_mode: number, prev_redundancy: boolean, last_packet_duration: number, rangeFinal: number, } @native function Decoder.new(channels: number): State return { channels = channels, celt = Celt.new(channels), silk = Silk.new(channels), ctrl = { nChannelsAPI = channels, nChannelsInternal = channels, API_sampleRate = 48000, internalSampleRate = 16000, payloadSize_ms = 20, }, stream_channels = channels, frame_size = 120, mode = 0, bandwidth = 0, prev_mode = 0, prev_redundancy = false, last_packet_duration = 0, rangeFinal = 0, } end @native function Decoder.reset(st: State) Celt.reset(st.celt) Silk.reset(st.silk) st.stream_channels = st.channels st.frame_size = 120 st.mode = 0 st.bandwidth = 0 st.prev_mode = 0 st.prev_redundancy = false st.last_packet_duration = 0 st.rangeFinal = 0 end -- out = w^2 * in2 + (1 - w^2) * in1 over `overlap` samples per channel @native local function smoothFade(in1: { number }, b1: number, in2: { number }, b2: number, out: { number }, bo: number, overlap: number, ch: number) for c = 0, ch - 1 do for i = 0, overlap - 1 do local w = WINDOW[i + 1] w *= w local k = i * ch + c out[bo + k] = w * in2[b2 + k] + (1 - w) * in1[b1 + k] end end end @native local function decodeFrame(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number local ch = st.channels local celt = st.celt if frameSize < F2_5 then return -2 end frameSize = min(frameSize, 2880) local data = buf if len <= 1 then data = nil frameSize = min(frameSize, st.frame_size) end local audiosize, mode, bandwidth local dec = EMPTY_EC if data then audiosize = st.frame_size mode = st.mode bandwidth = st.bandwidth dec = RD.new(data, off, len) else audiosize = frameSize mode = if st.prev_redundancy then MODE_CELT else st.prev_mode bandwidth = 0 if mode == 0 then for i = 0, audiosize * ch - 1 do pcm[pbase + i] = 0 end return audiosize end if audiosize > F20 then repeat local ret = decodeFrame(st, nil, 0, 0, pcm, pbase, min(audiosize, F20)) if ret < 0 then return ret end pbase += ret * ch audiosize -= ret until audiosize <= 0 return frameSize elseif audiosize < F20 then if audiosize > F10 then audiosize = F10 elseif mode ~= MODE_SILK and audiosize > F5 and audiosize < F10 then audiosize = F5 end end end local celtAccum = mode ~= MODE_CELT local transition = false if data and st.prev_mode > 0 and ((mode == MODE_CELT and st.prev_mode ~= MODE_CELT and not st.prev_redundancy) or (mode ~= MODE_CELT and st.prev_mode == MODE_CELT)) then transition = true end if transition and mode == MODE_CELT then decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize)) end if audiosize > frameSize then return -1 end frameSize = audiosize if mode ~= MODE_CELT then local tooSmall = frameSize < F10 local sarr, sbase = pcm, pbase if tooSmall then sarr, sbase = SILKTMP, 1 end if st.prev_mode == MODE_CELT then Silk.reset(st.silk) end local ctrl = st.ctrl ctrl.payloadSize_ms = max(10, 1000 * audiosize // 48000) if data then ctrl.nChannelsInternal = st.stream_channels if mode == MODE_SILK then ctrl.internalSampleRate = if bandwidth == BW_NB then 8000 elseif bandwidth == BW_MB then 12000 else 16000 else ctrl.internalSampleRate = 16000 end end local lost = if data == nil then 1 else 0 local decoded = 0 repeat local ret, n = Silk.decode(st.silk, ctrl, lost, decoded == 0, dec, sarr, sbase + decoded * ch) if ret ~= 0 or n <= 0 then if lost ~= 0 or n <= 0 then n = frameSize - decoded for i = 0, n * ch - 1 do sarr[sbase + decoded * ch + i] = 0 end else return -3 end end decoded += n until decoded >= frameSize if tooSmall then for i = 0, frameSize * ch - 1 do pcm[pbase + i] = SILKTMP[i + 1] end end end local startBand = 0 local redundancy, celtToSilk = false, false local redundancyBytes = 0 if mode ~= MODE_CELT and data and RD.tell(dec) + 17 + (if mode == MODE_HYBRID then 20 else 0) <= 8 * len then if mode == MODE_HYBRID then redundancy = RD.bitLogp(dec, 12) else redundancy = true end if redundancy then celtToSilk = RD.bitLogp(dec, 1) redundancyBytes = if mode == MODE_HYBRID then RD.uint(dec, 256) + 2 else len - bit32.rshift(RD.tell(dec) + 7, 3) len -= redundancyBytes if len * 8 < RD.tell(dec) then len = 0 redundancyBytes = 0 redundancy = false end dec.storage -= redundancyBytes end end if mode ~= MODE_CELT then startBand = 17 end if redundancy then transition = false end if transition and mode ~= MODE_CELT then decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize)) end if bandwidth ~= 0 then celt["end"] = if bandwidth == BW_NB then 13 elseif bandwidth == BW_MB or bandwidth == BW_WB then 17 elseif bandwidth == BW_SWB then 19 else 21 end celt.stream_channels = st.stream_channels local redundantRng = 0 if redundancy and celtToSilk then celt.start = 0 Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false) redundantRng = celt.rng end celt.start = startBand local celtRet = 0 if mode ~= MODE_SILK then local celtFrameSize = min(F20, frameSize) if mode ~= st.prev_mode and st.prev_mode > 0 and not st.prev_redundancy then Celt.reset(celt) end celtRet = Celt.decode(celt, data, off, len, pcm, pbase, celtFrameSize, if data then dec else nil, celtAccum) st.rangeFinal = celt.rng else if st.prev_mode == MODE_HYBRID and not (redundancy and celtToSilk and st.prev_redundancy) then celt.start = 0 Celt.decode(celt, SILENCE, 0, 2, pcm, pbase, F2_5, nil, celtAccum) end st.rangeFinal = if data then dec.rng else 0 end if redundancy and not celtToSilk then Celt.reset(celt) celt.start = 0 Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false) redundantRng = celt.rng local b = pbase + ch * (frameSize - F2_5) smoothFade(pcm, b, REDUND, 1 + ch * F2_5, pcm, b, F2_5, ch) end if redundancy and celtToSilk and (st.prev_mode ~= MODE_SILK or st.prev_redundancy) then for i = 0, F2_5 * ch - 1 do pcm[pbase + i] = REDUND[1 + i] end smoothFade(REDUND, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch) end if transition then if audiosize >= F5 then for i = 0, ch * F2_5 - 1 do pcm[pbase + i] = TRANS[1 + i] end smoothFade(TRANS, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch) else smoothFade(TRANS, 1, pcm, pbase, pcm, pbase, F2_5, ch) end end if len <= 1 then st.rangeFinal = 0 else st.rangeFinal = bit32.bxor(st.rangeFinal, redundantRng) end st.prev_mode = mode st.prev_redundancy = redundancy and not celtToSilk if celtRet < 0 then return celtRet end return audiosize end -- opus_decode_native (buf nil or len 0: conceal frameSize samples) @native function Decoder.decode(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, selfDelimited: boolean?): (number, number) local ch = st.channels if buf == nil or len == 0 then if frameSize % 120 ~= 0 then return -1, 0 end local count = 0 repeat local ret = decodeFrame(st, nil, 0, 0, pcm, pbase + count * ch, frameSize - count) if ret <= 0 then return if ret < 0 then ret else -3, 0 end count += ret until count >= frameSize st.last_packet_duration = count return count, 0 end local b = buf :: buffer local toc = readu8(b, off) local packetMode = Packet.mode(toc) local packetBandwidth = Packet.bandwidth(toc) local packetFrameSize = Packet.samplesPerFrame(toc, 48000) local packetChannels = Packet.channels(toc) local count, _, packetOffset = Packet.parse(b, off, len, OFFS, SIZES, selfDelimited) if count < 0 then return -4, 0 end if count * packetFrameSize > frameSize then return -2, 0 end st.mode = packetMode st.bandwidth = packetBandwidth st.frame_size = packetFrameSize st.stream_channels = packetChannels local nb = 0 for i = 1, count do local ret = decodeFrame(st, b, OFFS[i], SIZES[i], pcm, pbase + nb * ch, frameSize - nb) if ret < 0 then return ret, 0 end nb += ret end st.last_packet_duration = nb return nb, packetOffset end -- multistream (channel mapping families 0 / 1 / 255) type MS = { channels: number, streams: number, coupled: number, mapping: { number }, decoders: { State }, tmp: { number }, } @native function Decoder.newMultistream(channels: number, streams: number, coupled: number, mapping: { number }): MS local decs = {} for s = 0, streams - 1 do decs[s + 1] = Decoder.new(if s < coupled then 2 else 1) end return { channels = channels, streams = streams, coupled = coupled, mapping = mapping, decoders = decs, tmp = table.create(5760 * 2, 0), } end @native function Decoder.resetMultistream(ms: MS) for _, d in ms.decoders do Decoder.reset(d) end end @native local function copyOut(ms: MS, id: number, src: { number }, sc: number, sstride: number, pcm: { number }, pbase: number, n: number) local nch = ms.channels for c = 0, nch - 1 do if ms.mapping[c + 1] == id then local o = pbase + c local s = 1 + sc for _ = 1, n do pcm[o] = src[s] o += nch s += sstride end end end end -- opus_multistream_decode_native @native function Decoder.decodeMultistream(ms: MS, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number local doPlc = buf == nil or len == 0 frameSize = min(frameSize, 5760) if not doPlc and len < 2 * ms.streams - 1 then return -4 end local tmp = ms.tmp for s = 0, ms.streams - 1 do local d = ms.decoders[s + 1] if not doPlc and len <= 0 then return -3 end local ret, packetOffset = Decoder.decode(d, if doPlc then nil else buf, off, if doPlc then 0 else len, tmp, 1, frameSize, s ~= ms.streams - 1) if not doPlc then off += packetOffset len -= packetOffset end if ret <= 0 then return if ret < 0 then ret else -3 end frameSize = ret if s < ms.coupled then copyOut(ms, s * 2, tmp, 0, 2, pcm, pbase, frameSize) copyOut(ms, s * 2 + 1, tmp, 1, 2, pcm, pbase, frameSize) else copyOut(ms, s + ms.coupled, tmp, 0, 1, pcm, pbase, frameSize) end end local nch = ms.channels for c = 0, nch - 1 do if ms.mapping[c + 1] == 255 then local o = pbase + c for _ = 1, frameSize do pcm[o] = 0 o += nch end end end return frameSize end @native function Decoder.writeF32(src: { number }, base: number, count: number, gain: number, out: buffer, o: number) local writef32 = buffer.writef32 if gain == 1 then for i = base + 1, base + count do writef32(out, o, src[i]) o += 4 end else for i = base + 1, base + count do writef32(out, o, src[i] * gain) o += 4 end end end @native function Decoder.writeDownmix(src: { number }, base: number, n: number, srcCh: number, matrix: { number }, gain: number, out: buffer, o: number) local writef32 = buffer.writef32 local p = base for _ = 1, n do local l, r = 0, 0 for c = 0, srcCh - 1 do local v = src[p + c + 1] l += v * matrix[c * 2 + 1] r += v * matrix[c * 2 + 2] end writef32(out, o, l * gain) writef32(out, o + 4, r * gain) o += 8 p += srcCh end end return Decoder end __FILES["codecs/audio/Opus/Mdct"] = @native function() -- codecs/audio/Opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over the kiss_fft radix 5 / 3 / 4 / 2 stages. -- N = 1920 >> shift (FFT sizes 480 .. 60). Kept apart from codecs/audio/Mdct: CELT keeps only the middle N / 2 of the -- full IMDCT, so the shared transform was 2-3x slower and changed the output bits. local Mdct = {} local sin, cos, pi = math.sin, math.cos, math.pi type Plan = { n: number, factors: { number }, bitrev: { number }, twr: { number }, twi: { number }, trig: { number }, -- MDCT twiddles: (-sin, cos) pairs, N / 2 values fr: { number }, fi: { number }, } local FACTORS = { [0] = { 5, 96, 3, 32, 4, 8, 2, 4, 4, 1 }, [1] = { 5, 48, 3, 16, 4, 4, 4, 1 }, [2] = { 5, 24, 3, 8, 2, 4, 4, 1 }, [3] = { 5, 12, 3, 4, 4, 1 }, } @native local function bitrevTable(f: { number }, fout: number, fpos: number, fstride: number, factors: { number }, fi: number) local p = factors[fi] local m = factors[fi + 1] if m == 1 then for j = 0, p - 1 do f[fpos + 1] = fout + j fpos += fstride end else for j = 0, p - 1 do bitrevTable(f, fout, fpos, fstride * p, factors, fi + 2) fpos += fstride fout += m end end end local plans: { Plan } = {} for shift = 0, 3 do local N = 1920 // 2 ^ shift local n = N // 4 local factors = FACTORS[shift] local bitrev = table.create(n, 0) bitrevTable(bitrev, 0, 0, 1, factors, 1) local twr, twi = table.create(n, 0), table.create(n, 0) for k = 0, n - 1 do local ph = -2 * pi * k / n twr[k + 1] = cos(ph) twi[k + 1] = sin(ph) end local N2, N4 = N // 2, N // 4 local trig = table.create(N2, 0) for i = 0, N4 - 1 do trig[2 * i + 1] = -sin(2 * pi * (i + 0.125) / N) trig[2 * i + 2] = cos(2 * pi * (i + 0.125) / N) end plans[shift + 1] = { n = n, factors = factors, bitrev = bitrev, twr = twr, twi = twi, trig = trig, fr = table.create(n, 0), fi = table.create(n, 0), } end @native local function bfly2(fr: { number }, fi: { number }, N: number) local tw = 0.7071067812 local p = 1 for _ = 1, N do local tr, ti = fr[p + 4], fi[p + 4] fr[p + 4] = fr[p] - tr fi[p + 4] = fi[p] - ti fr[p] += tr fi[p] += ti local a, b = fr[p + 5], fi[p + 5] tr = (a + b) * tw ti = (b - a) * tw fr[p + 5] = fr[p + 1] - tr fi[p + 5] = fi[p + 1] - ti fr[p + 1] += tr fi[p + 1] += ti tr = fi[p + 6] ti = -fr[p + 6] fr[p + 6] = fr[p + 2] - tr fi[p + 6] = fi[p + 2] - ti fr[p + 2] += tr fi[p + 2] += ti a, b = fr[p + 7], fi[p + 7] tr = (b - a) * tw ti = -(b + a) * tw fr[p + 7] = fr[p + 3] - tr fi[p + 7] = fi[p + 3] - ti fr[p + 3] += tr fi[p + 3] += ti p += 8 end end @native local function bfly4(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) if m == 1 then local p = 1 for _ = 1, N do local r0, i0 = fr[p], fi[p] local r1, i1 = fr[p + 1], fi[p + 1] local r2, i2 = fr[p + 2], fi[p + 2] local r3, i3 = fr[p + 3], fi[p + 3] local s0r, s0i = r0 - r2, i0 - i2 r0 += r2 i0 += i2 local s1r, s1i = r1 + r3, i1 + i3 fr[p + 2] = r0 - s1r fi[p + 2] = i0 - s1i fr[p] = r0 + s1r fi[p] = i0 + s1i s1r, s1i = r1 - r3, i1 - i3 fr[p + 1] = s0r + s1i fi[p + 1] = s0i - s1r fr[p + 3] = s0r - s1i fi[p + 3] = s0i + s1r p += 4 end else local m2, m3 = 2 * m, 3 * m for i = 0, N - 1 do local p = i * mm + 1 local t1, t2, t3 = 1, 1, 1 for _ = 0, m - 1 do local ar, ai = fr[p + m], fi[p + m] local wr, wi = twr[t1], twi[t1] local s0r, s0i = ar * wr - ai * wi, ar * wi + ai * wr ar, ai = fr[p + m2], fi[p + m2] wr, wi = twr[t2], twi[t2] local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr ar, ai = fr[p + m3], fi[p + m3] wr, wi = twr[t3], twi[t3] local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr local f0r, f0i = fr[p], fi[p] local s5r, s5i = f0r - s1r, f0i - s1i f0r += s1r f0i += s1i local s3r, s3i = s0r + s2r, s0i + s2i local s4r, s4i = s0r - s2r, s0i - s2i fr[p + m2] = f0r - s3r fi[p + m2] = f0i - s3i t1 += fstride t2 += fstride * 2 t3 += fstride * 3 fr[p] = f0r + s3r fi[p] = f0i + s3i fr[p + m] = s5r + s4i fi[p + m] = s5i - s4r fr[p + m3] = s5r - s4i fi[p + m3] = s5i + s4r p += 1 end end end end @native local function bfly3(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) local m2 = 2 * m local epi3i = twi[fstride * m + 1] for i = 0, N - 1 do local p = i * mm + 1 local t1, t2 = 1, 1 for _ = 1, m do local ar, ai = fr[p + m], fi[p + m] local wr, wi = twr[t1], twi[t1] local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr ar, ai = fr[p + m2], fi[p + m2] wr, wi = twr[t2], twi[t2] local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr local s3r, s3i = s1r + s2r, s1i + s2i local s0r, s0i = s1r - s2r, s1i - s2i t1 += fstride t2 += fstride * 2 local f0r, f0i = fr[p], fi[p] local fmr, fmi = f0r - s3r * 0.5, f0i - s3i * 0.5 s0r *= epi3i s0i *= epi3i fr[p] = f0r + s3r fi[p] = f0i + s3i fr[p + m2] = fmr + s0i fi[p + m2] = fmi - s0r fr[p + m] = fmr - s0i fi[p + m] = fmi + s0r p += 1 end end end @native local function bfly5(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) local yar, yai = twr[fstride * m + 1], twi[fstride * m + 1] local ybr, ybi = twr[fstride * 2 * m + 1], twi[fstride * 2 * m + 1] for i = 0, N - 1 do local p0 = i * mm + 1 local p1, p2, p3, p4 = p0 + m, p0 + 2 * m, p0 + 3 * m, p0 + 4 * m for u = 0, m - 1 do local s0r, s0i = fr[p0], fi[p0] local k = u * fstride local ar, ai = fr[p1], fi[p1] local wr, wi = twr[k + 1], twi[k + 1] local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr ar, ai = fr[p2], fi[p2] wr, wi = twr[2 * k + 1], twi[2 * k + 1] local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr ar, ai = fr[p3], fi[p3] wr, wi = twr[3 * k + 1], twi[3 * k + 1] local s3r, s3i = ar * wr - ai * wi, ar * wi + ai * wr ar, ai = fr[p4], fi[p4] wr, wi = twr[4 * k + 1], twi[4 * k + 1] local s4r, s4i = ar * wr - ai * wi, ar * wi + ai * wr local s7r, s7i = s1r + s4r, s1i + s4i local s10r, s10i = s1r - s4r, s1i - s4i local s8r, s8i = s2r + s3r, s2i + s3i local s9r, s9i = s2r - s3r, s2i - s3i fr[p0] = s0r + (s7r + s8r) fi[p0] = s0i + (s7i + s8i) local s5r = s0r + (s7r * yar + s8r * ybr) local s5i = s0i + (s7i * yar + s8i * ybr) local s6r = s10i * yai + s9i * ybi local s6i = -(s10r * yai + s9r * ybi) fr[p1] = s5r - s6r fi[p1] = s5i - s6i fr[p4] = s5r + s6r fi[p4] = s5i + s6i local s11r = s0r + (s7r * ybr + s8r * yar) local s11i = s0i + (s7i * ybr + s8i * yar) local s12r = s9i * yai - s10i * ybi local s12i = s10r * ybi - s9r * yai fr[p2] = s11r + s12r fi[p2] = s11i + s12i fr[p3] = s11r - s12r fi[p3] = s11i - s12i p0 += 1 p1 += 1 p2 += 1 p3 += 1 p4 += 1 end end end -- opus_fft_impl (bit-reversed input) @native local function fftImpl(pl: Plan) local factors = pl.factors local fr, fi, twr, twi = pl.fr, pl.fi, pl.twr, pl.twi local fstride = { 1 } local L = 0 local m repeat local p = factors[2 * L + 1] m = factors[2 * L + 2] fstride[L + 2] = fstride[L + 1] * p L += 1 until m == 1 m = factors[2 * L] for i = L - 1, 0, -1 do local m2 = if i ~= 0 then factors[2 * i] else 1 local radix = factors[2 * i + 1] if radix == 2 then bfly2(fr, fi, fstride[i + 1]) elseif radix == 4 then bfly4(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) elseif radix == 3 then bfly3(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) else bfly5(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) end m = m2 end end -- clt_mdct_backward @native function Mdct.backward(inp: { number }, inBase: number, out: { number }, outBase: number, window: { number }, overlap: number, shift: number, stride: number) local pl = plans[shift + 1] local N4 = pl.n local N2 = N4 * 2 local trig = pl.trig local bitrev = pl.bitrev local fr, fi = pl.fr, pl.fi -- pre-rotate, storing in bit-reversed order (real and imaginary swapped: an FFT is used instead of an IFFT) local xp1 = inBase local xp2 = inBase + stride * (N2 - 1) for i = 0, N4 - 1 do local x1 = inp[xp1] local x2 = inp[xp2] local t0, t1 = trig[2 * i + 1], trig[2 * i + 2] local rev = bitrev[i + 1] + 1 fi[rev] = x2 * t1 + x1 * t0 fr[rev] = x1 * t1 - x2 * t0 xp1 += 2 * stride xp2 -= 2 * stride end fftImpl(pl) local h = outBase + (overlap // 2) for k = 0, N4 - 1 do local re = fi[k + 1] local im = fr[k + 1] local t0, t1 = trig[2 * k + 1], trig[2 * k + 2] out[h + 2 * k] = re * t1 + im * t0 out[h + N2 - 1 - 2 * k] = re * t0 - im * t1 end -- mirror on both sides for TDAC local xp = outBase + overlap - 1 local yp = outBase for i = 0, overlap // 2 - 1 do local x1 = out[xp] local x2 = out[yp] local w1 = window[i + 1] local w2 = window[overlap - i] out[yp] = x2 * w2 - x1 * w1 out[xp] = x2 * w1 + x1 * w2 xp -= 1 yp += 1 end end return Mdct end __FILES["codecs/audio/Opus/Packet"] = @native function() -- codecs/audio/Opus/Packet: Opus packet framing (RFC 6716 section 3): the TOC byte and frame packing codes 0-3, with padding. local Packet = {} local readu8 = buffer.readu8 local band, rshift = bit32.band, bit32.rshift Packet.MODE_SILK_ONLY = 1000 Packet.MODE_HYBRID = 1001 Packet.MODE_CELT_ONLY = 1002 -- bandwidths as in libopus (OPUS_BANDWIDTH_NARROWBAND .. FULLBAND) Packet.BW_NB = 1101 Packet.BW_MB = 1102 Packet.BW_WB = 1103 Packet.BW_SWB = 1104 Packet.BW_FB = 1105 @native function Packet.mode(toc: number): number if band(toc, 0x80) ~= 0 then return Packet.MODE_CELT_ONLY elseif band(toc, 0x60) == 0x60 then return Packet.MODE_HYBRID else return Packet.MODE_SILK_ONLY end end @native function Packet.bandwidth(toc: number): number if band(toc, 0x80) ~= 0 then local bw = 1102 + band(rshift(toc, 5), 3) if bw == 1102 then bw = 1101 end return bw elseif band(toc, 0x60) == 0x60 then return if band(toc, 0x10) ~= 0 then 1105 else 1104 else return 1101 + band(rshift(toc, 5), 3) end end @native function Packet.channels(toc: number): number return if band(toc, 4) ~= 0 then 2 else 1 end @native function Packet.samplesPerFrame(toc: number, Fs: number): number if band(toc, 0x80) ~= 0 then local a = band(rshift(toc, 3), 3) return bit32.lshift(Fs, a) // 400 elseif band(toc, 0x60) == 0x60 then return if band(toc, 0x08) ~= 0 then Fs // 50 else Fs // 100 else local a = band(rshift(toc, 3), 3) if a == 3 then return Fs * 60 // 1000 end return bit32.lshift(Fs, a) // 100 end end @native function Packet.samples(buf: buffer, off: number, len: number): number if len < 1 then return -1 end local toc = readu8(buf, off) local c = band(toc, 3) local count if c == 0 then count = 1 elseif c ~= 3 then count = 2 else if len < 2 then return -1 end count = band(readu8(buf, off + 1), 0x3F) end local n = count * Packet.samplesPerFrame(toc, 48000) if n * 25 > 48000 * 3 then return -1 end return n end @native local function parseSize(buf: buffer, p: number, len: number): (number, number) if len < 1 then return -1, -1 end local b0 = readu8(buf, p) if b0 < 252 then return 1, b0 elseif len < 2 then return -1, -1 end return 2, 4 * readu8(buf, p + 1) + b0 end -- opus_packet_parse_impl; self-delimited packets (multistream) carry an explicit size for the last frame @native function Packet.parse(buf: buffer, off: number, len: number, offsets: { number }, sizes: { number }, selfDelimited: boolean?): (number, number, number) if len < 1 then return -1, 0, 0 end local toc = readu8(buf, off) local framesize = Packet.samplesPerFrame(toc, 48000) local p = off + 1 len -= 1 local lastSize = len local count local cbr = false local pad = 0 local c = band(toc, 3) if c == 0 then count = 1 elseif c == 1 then count = 2 cbr = true if not selfDelimited then if band(len, 1) ~= 0 then return -1, toc, 0 end lastSize = len // 2 sizes[1] = lastSize end elseif c == 2 then count = 2 local bytes, s = parseSize(buf, p, len) if bytes < 0 then return -1, toc, 0 end len -= bytes if s < 0 or s > len then return -1, toc, 0 end sizes[1] = s p += bytes lastSize = len - s else if len < 1 then return -1, toc, 0 end local ch = readu8(buf, p) p += 1 count = band(ch, 0x3F) if count <= 0 or framesize * count > 5760 then return -1, toc, 0 end len -= 1 if band(ch, 0x40) ~= 0 then local pb repeat if len <= 0 then return -1, toc, 0 end pb = readu8(buf, p) p += 1 len -= 1 local tmp = if pb == 255 then 254 else pb len -= tmp pad += tmp until pb ~= 255 end if len < 0 then return -1, toc, 0 end cbr = band(ch, 0x80) == 0 if not cbr then lastSize = len for i = 1, count - 1 do local bytes, s = parseSize(buf, p, len) if bytes < 0 then return -1, toc, 0 end len -= bytes if s < 0 or s > len then return -1, toc, 0 end sizes[i] = s p += bytes lastSize -= bytes + s end if lastSize < 0 then return -1, toc, 0 end elseif not selfDelimited then lastSize = len // count if lastSize * count ~= len then return -1, toc, 0 end for i = 1, count - 1 do sizes[i] = lastSize end end end if selfDelimited then local bytes, s = parseSize(buf, p, len) if bytes < 0 then return -1, toc, 0 end len -= bytes if s < 0 or s > len then return -1, toc, 0 end p += bytes sizes[count] = s if cbr then if s * count > len then return -1, toc, 0 end for i = 1, count - 1 do sizes[i] = s end elseif bytes + s > lastSize then return -1, toc, 0 end else if lastSize > 1275 then return -1, toc, 0 end sizes[count] = lastSize end for i = 1, count do offsets[i] = p p += sizes[i] end return count, toc, pad + (p - off) end return Packet end __FILES["codecs/audio/Opus/Silk"] = @native function() -- codecs/audio/Opus/Silk: SILK decoder, a bit-exact port of the libopus fixed-point SILK decoder (silk/dec_API.c and what -- it calls; BSD, licenses/). C int32 / int16 values are Luau numbers; int32 x int32 products are split to stay below 2^53. local RD = __include("codecs/entropy/RangeCoder/Decoder") local T = __include("codecs/audio/Opus/SilkTables") local icdf = RD.icdf local bitLogp = RD.bitLogp local countlz = bit32.countlz local floor = math.floor local Silk = {} local P2 = table.create(64, 0) for s = 1, 63 do P2[s] = 2 ^ s end @native local function p2(s: number): number if s == 0 then return 1 end return P2[s] end @native local function s16(x: number): number x = x % 65536 if x >= 32768 then return x - 65536 end return x end @native local function i32(x: number): number x = x % 4294967296 if x >= 2147483648 then return x - 4294967296 end return x end @native local function sat16(x: number): number if x > 32767 then return 32767 elseif x < -32768 then return -32768 end return x end @native local function addSat32(a: number, b: number): number local s = a + b if s > 2147483647 then return 2147483647 elseif s < -2147483648 then return -2147483648 end return s end @native local function subSat32(a: number, b: number): number local s = a - b if s > 2147483647 then return 2147483647 elseif s < -2147483648 then return -2147483648 end return s end -- silk_CLZ32 of a non-negative int32 @native local function clz32(x: number): number return countlz(x) end -- silk_SMULWW (64-bit form): (a * b) >> 16, exact @native local function mulww(a: number, b: number): number return a * (b // 65536) + (a * (b % 65536)) // 65536 end -- floor(a * b / 2^s) for int32 a, b and s >= 16, exact @native local function mulshr(a: number, b: number, s: number): number local t = a * (b // 65536) + (a * (b % 65536)) // 65536 if s == 16 then return t end return t // P2[s - 16] end @native local function smmul(a: number, b: number): number return mulshr(a, b, 32) end -- silk_RSHIFT_ROUND (shift >= 1) @native local function rround(a: number, s: number): number return (a + p2(s - 1)) // P2[s] end @native local function lshiftSat32(a: number, sh: number): number if sh == 0 then return a end local m = P2[sh] local lo, hi = -2147483648 // m, 2147483647 // m if a < lo then a = lo elseif a > hi then a = hi end return a * m end -- C integer division (truncation toward zero) @native local function tdiv(a: number, b: number): number local q = a / b if q >= 0 then return floor(q) end return -floor(-q) end -- low 32 bits of a * b, as int32 @native local function imul32(a: number, b: number): number a = a % 4294967296 local ah, al = a // 65536, a % 65536 return i32(((ah * b) % 65536) * 65536 + al * b) end @native local function silkRand(seed: number): number return i32(907633515 + imul32(seed, 196314165)) end @native local function rshift(a: number, s: number): number if s == 0 then return a end return a // P2[s] end @native local function silkINVERSE32_varQ(b32: number, Qres: number): number local b_headrm = clz32(math.abs(b32)) - 1 local b32_nrm = b32 * p2(b_headrm) local b32_inv = tdiv(536870911, b32_nrm // 65536) local result = b32_inv * 65536 local err_Q32 = i32((536870912 - (b32_nrm * b32_inv) // 65536) * 8) result = i32(result + mulww(err_Q32, b32_inv)) local lshift = 61 - b_headrm - Qres if lshift <= 0 then return lshiftSat32(result, -lshift) elseif lshift < 32 then return result // P2[lshift] end return 0 end @native local function silkDIV32_varQ(a32: number, b32: number, Qres: number): number local a_headrm = clz32(math.abs(a32)) - 1 local a32_nrm = a32 * p2(a_headrm) local b_headrm = clz32(math.abs(b32)) - 1 local b32_nrm = b32 * p2(b_headrm) local b32_inv = tdiv(536870911, b32_nrm // 65536) local result = (a32_nrm * s16(b32_inv)) // 65536 a32_nrm = i32(a32_nrm - i32(smmul(b32_nrm, result) * 8)) result = result + (a32_nrm * s16(b32_inv)) // 65536 local lshift = 29 + a_headrm - b_headrm - Qres if lshift < 0 then return lshiftSat32(result, -lshift) elseif lshift < 32 then return rshift(result, lshift) end return 0 end @native local function silkLog2lin(inLog_Q7: number): number if inLog_Q7 < 0 then return 0 elseif inLog_Q7 >= 3967 then return 2147483647 end local out = p2(inLog_Q7 // 128) local frac_Q7 = inLog_Q7 % 128 local t = frac_Q7 + (frac_Q7 * (128 - frac_Q7) * -174) // 65536 if inLog_Q7 < 2048 then out = out + (out * t) // 128 else out = out + (out // 128) * t end return out end @native local function silkSQRT_APPROX(x: number): number if x <= 0 then return 0 end local lz = clz32(x) local rot = 24 - lz local r if rot == 0 then r = x elseif rot < 0 then r = bit32.lrotate(x, -rot) else r = bit32.rrotate(x, rot) end local frac_Q7 = bit32.band(r, 0x7f) local y = if bit32.band(lz, 1) ~= 0 then 32768 else 46214 y = y // p2(lz // 2) y = y + (y * (213 * frac_Q7)) // 65536 return y end -- silk_sum_sqr_shift: energy, shift @native local function sumSqrShift(x: { number }, xo: number, len: number): (number, number) local shft = 31 - clz32(len) local nrg = len local i = 0 while i < len - 1 do local a, b = x[xo + i], x[xo + i + 1] nrg = i32(nrg + rshift(a * a + b * b, shft)) i += 2 end if i < len then local a = x[xo + i] nrg = i32(nrg + rshift(a * a, shft)) end shft = math.max(0, shft + 3 - clz32(nrg)) nrg = 0 i = 0 while i < len - 1 do local a, b = x[xo + i], x[xo + i + 1] nrg = i32(nrg + rshift(a * a + b * b, shft)) i += 2 end if i < len then local a = x[xo + i] nrg = i32(nrg + rshift(a * a, shft)) end return nrg, shft end -- silk_bwexpander (int16 coefficients), ar 1-based @native local function bwexpander(ar: { number }, d: number, chirp_Q16: number) local chirp_minus_one_Q16 = chirp_Q16 - 65536 for i = 1, d - 1 do ar[i] = s16((chirp_Q16 * ar[i] + 32768) // 65536) chirp_Q16 += (chirp_Q16 * chirp_minus_one_Q16 + 32768) // 65536 end ar[d] = s16((chirp_Q16 * ar[d] + 32768) // 65536) end @native local function bwexpander32(ar: { number }, d: number, chirp_Q16: number) local chirp_minus_one_Q16 = chirp_Q16 - 65536 for i = 1, d - 1 do ar[i] = i32(mulww(chirp_Q16, ar[i])) chirp_Q16 += (chirp_Q16 * chirp_minus_one_Q16 + 32768) // 65536 end ar[d] = i32(mulww(chirp_Q16, ar[d])) end -- silk_LPC_fit: a_QIN (int32, QIN) -> a_QOUT (int16, QOUT) @native local function lpcFit(a_QOUT: { number }, a_QIN: { number }, QOUT: number, QIN: number, d: number) local sh = QIN - QOUT local idx = 0 local i = 0 while i < 10 do local maxabs = 0 for k = 1, d do local absval = math.abs(a_QIN[k]) if absval > maxabs then maxabs = absval idx = k - 1 end end maxabs = rround(maxabs, sh) if maxabs > 32767 then maxabs = math.min(maxabs, 163838) local chirp_Q16 = 65470 - tdiv((maxabs - 32767) * 16384, (maxabs * (idx + 1)) // 4) bwexpander32(a_QIN, d, chirp_Q16) else break end i += 1 end if i == 10 then for k = 1, d do a_QOUT[k] = sat16(rround(a_QIN[k], sh)) a_QIN[k] = a_QOUT[k] * P2[sh] end else for k = 1, d do a_QOUT[k] = s16(rround(a_QIN[k], sh)) end end end local A_LIMIT = 16773022 local INV_GAIN_MIN = 107374 local Atmp_QA = table.create(16, 0) -- RSHIFT_ROUND64(SMULL(a, b), Q) @native local function mulRound(a: number, b: number, Q: number): number if Q == 1 then local p = a * b return p // 2 + p % 2 end if Q - 1 >= 16 then return (mulshr(a, b, Q - 1) + 1) // 2 end return ((a * b) // P2[Q - 1] + 1) // 2 end @native local function lpcInversePredGainQA(A_QA: { number }, order: number): number local invGain_Q30 = 1073741824 local k = order - 1 while k > 0 do local ak = A_QA[k + 1] if ak > A_LIMIT or ak < -A_LIMIT then return 0 end local rc_Q31 = -(ak * 128) local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 if invGain_Q30 < INV_GAIN_MIN then return 0 end local mult2Q = 32 - clz32(math.abs(rc_mult1_Q30)) local rc_mult2 = silkINVERSE32_varQ(rc_mult1_Q30, mult2Q + 30) for n = 0, (k + 1) // 2 - 1 do local tmp1 = A_QA[n + 1] local tmp2 = A_QA[k - n] local t64 = mulRound(subSat32(tmp1, mulRound(tmp2, rc_Q31, 31)), rc_mult2, mult2Q) if t64 > 2147483647 or t64 < -2147483648 then return 0 end A_QA[n + 1] = t64 t64 = mulRound(subSat32(tmp2, mulRound(tmp1, rc_Q31, 31)), rc_mult2, mult2Q) if t64 > 2147483647 or t64 < -2147483648 then return 0 end A_QA[k - n] = t64 end k -= 1 end local a0 = A_QA[1] if a0 > A_LIMIT or a0 < -A_LIMIT then return 0 end local rc_Q31 = -(a0 * 128) local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 if invGain_Q30 < INV_GAIN_MIN then return 0 end return invGain_Q30 end @native local function lpcInversePredGain(A_Q12: { number }, order: number): number local DC_resp = 0 for k = 1, order do DC_resp += A_Q12[k] Atmp_QA[k] = A_Q12[k] * 4096 end if DC_resp >= 4096 then return 0 end return lpcInversePredGainQA(Atmp_QA, order) end local ordering16 = { 0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1 } local ordering10 = { 0, 9, 6, 3, 4, 5, 8, 1, 2, 7 } local cos_LSF_QA = table.create(16, 0) local polyP = table.create(9, 0) local polyQ = table.create(9, 0) local a32_QA1 = table.create(16, 0) local LSFCos = T.LSFCosTab_FIX_Q12 -- out[0..dd] (1-based storage), from interleaved cLSF starting at C index c0 @native local function findPoly(out: { number }, cLSF: { number }, c0: number, dd: number) out[1] = 65536 out[2] = -cLSF[c0 + 1] for k = 1, dd - 1 do local ftmp = cLSF[c0 + 2 * k + 1] out[k + 2] = out[k] * 2 - (ftmp * out[k + 1] + 32768) // 65536 for n = k, 2, -1 do out[n + 1] += out[n - 1] - (ftmp * out[n] + 32768) // 65536 end out[2] -= ftmp end end -- silk_NLSF2A: a_Q12 (1-based, d entries) from NLSF (1-based) @native local function nlsf2a(a_Q12: { number }, NLSF: { number }, d: number) local ordering = if d == 16 then ordering16 else ordering10 for k = 1, d do local nl = NLSF[k] local f_int = nl // 256 local f_frac = nl - f_int * 256 local cos_val = LSFCos[f_int + 1] local delta = LSFCos[f_int + 2] - cos_val cos_LSF_QA[ordering[k] + 1] = (cos_val * 256 + delta * f_frac + 8) // 16 end local dd = d // 2 findPoly(polyP, cos_LSF_QA, 0, dd) findPoly(polyQ, cos_LSF_QA, 1, dd) for k = 0, dd - 1 do local Ptmp = polyP[k + 2] + polyP[k + 1] local Qtmp = polyQ[k + 2] - polyQ[k + 1] a32_QA1[k + 1] = -Qtmp - Ptmp a32_QA1[d - k] = Qtmp - Ptmp end lpcFit(a_Q12, a32_QA1, 12, 17, d) local i = 0 while lpcInversePredGain(a_Q12, d) == 0 and i < 16 do bwexpander32(a32_QA1, d, 65536 - P2[i + 1]) for k = 1, d do a_Q12[k] = s16((a32_QA1[k] + 16) // 32) end i += 1 end end -- silk_LPC_analysis_filter: out[oo + ix] for ix in [0, len), from inp[io + ix]; B 1-based Q12 @native local function lpcAnalysisFilter(out: { number }, oo: number, inp: { number }, io: number, B: { number }, len: number, d: number) for ix = d, len - 1 do local base = io + ix - 1 local acc = 0 for j = 0, d - 1 do acc += inp[base - j] * B[j + 1] end local out32_Q12 = i32(inp[base + 1] * 4096 - acc) out[oo + ix] = sat16((out32_Q12 + 2048) // 4096) end for j = 0, d - 1 do out[oo + j] = 0 end end local CB_NB_MB = { nVectors = 32, order = 10, quantStepSize_Q16 = 11796, CB1_NLSF_Q8 = T.NLSF_CB1_NB_MB_Q8, CB1_Wght_Q9 = T.NLSF_CB1_Wght_Q9, CB1_iCDF = T.NLSF_CB1_iCDF_NB_MB, pred_Q8 = T.NLSF_PRED_NB_MB_Q8, ec_sel = T.NLSF_CB2_SELECT_NB_MB, ec_iCDF = T.NLSF_CB2_iCDF_NB_MB, deltaMin_Q15 = T.NLSF_DELTA_MIN_NB_MB_Q15, } local CB_WB = { nVectors = 32, order = 16, quantStepSize_Q16 = 9830, CB1_NLSF_Q8 = T.NLSF_CB1_WB_Q8, CB1_Wght_Q9 = T.NLSF_CB1_WB_Wght_Q9, CB1_iCDF = T.NLSF_CB1_iCDF_WB, pred_Q8 = T.NLSF_PRED_WB_Q8, ec_sel = T.NLSF_CB2_SELECT_WB, ec_iCDF = T.NLSF_CB2_iCDF_WB, deltaMin_Q15 = T.NLSF_DELTA_MIN_WB_Q15, } local ec_ix = table.create(16, 0) local pred_Q8 = table.create(16, 0) local res_Q10 = table.create(16, 0) @native local function nlsfUnpack(CB: any, CB1_index: number) local order = CB.order local sel = CB.ec_sel local pq = CB.pred_Q8 local p = CB1_index * order // 2 for i = 0, order - 1, 2 do p += 1 local entry = sel[p] ec_ix[i + 1] = (bit32.band(entry // 2, 7)) * 9 pred_Q8[i + 1] = pq[i + bit32.band(entry, 1) * (order - 1) + 1] ec_ix[i + 2] = (bit32.band(entry // 32, 7)) * 9 pred_Q8[i + 2] = pq[i + bit32.band(entry // 16, 1) * (order - 1) + 2] end end @native local function nlsfStabilize(NLSF: { number }, NDeltaMin: { number }, L: number) local loops = 0 while loops < 20 do local min_diff = NLSF[1] - NDeltaMin[1] local I = 0 for i = 1, L - 1 do local diff = NLSF[i + 1] - (NLSF[i] + NDeltaMin[i + 1]) if diff < min_diff then min_diff = diff I = i end end local diff = 32768 - (NLSF[L] + NDeltaMin[L + 1]) if diff < min_diff then min_diff = diff I = L end if min_diff >= 0 then return end if I == 0 then NLSF[1] = NDeltaMin[1] elseif I == L then NLSF[L] = 32768 - NDeltaMin[L + 1] else local min_center = 0 for k = 0, I - 1 do min_center += NDeltaMin[k + 1] end min_center += NDeltaMin[I + 1] // 2 local max_center = 32768 for k = L, I + 1, -1 do max_center -= NDeltaMin[k + 1] end max_center -= NDeltaMin[I + 1] // 2 local c = (NLSF[I] + NLSF[I + 1] + 1) // 2 -- silk_LIMIT_32(c, min_center, max_center) if min_center > max_center then if c > min_center then c = min_center elseif c < max_center then c = max_center end else if c > max_center then c = max_center elseif c < min_center then c = min_center end end c = s16(c) NLSF[I] = s16(c - NDeltaMin[I + 1] // 2) NLSF[I + 1] = s16(NLSF[I] + NDeltaMin[I + 1]) end loops += 1 end -- fall back: insertion sort, then clamp for i = 2, L do local value = NLSF[i] local j = i - 1 while j >= 1 and value < NLSF[j] do NLSF[j + 1] = NLSF[j] j -= 1 end NLSF[j + 1] = value end NLSF[1] = math.max(NLSF[1], NDeltaMin[1]) for i = 2, L do NLSF[i] = math.max(NLSF[i], sat16(NLSF[i - 1] + NDeltaMin[i])) end NLSF[L] = math.min(NLSF[L], 32768 - NDeltaMin[L + 1]) for i = L - 1, 1, -1 do NLSF[i] = math.min(NLSF[i], NLSF[i + 1] - NDeltaMin[i + 1]) end end -- silk_NLSF_decode: pNLSF_Q15 (1-based) from indices (1-based: [1] = CB1 index) @native local function nlsfDecode(pNLSF_Q15: { number }, NLSFIndices: { number }, CB: any) nlsfUnpack(CB, NLSFIndices[1]) local order = CB.order local step = CB.quantStepSize_Q16 local out_Q10 = 0 for i = order - 1, 0, -1 do local pred = (out_Q10 * pred_Q8[i + 1]) // 256 out_Q10 = NLSFIndices[i + 2] * 1024 if out_Q10 > 0 then out_Q10 -= 102 elseif out_Q10 < 0 then out_Q10 += 102 end out_Q10 = pred + (out_Q10 * step) // 65536 res_Q10[i + 1] = out_Q10 end local base = NLSFIndices[1] * order local cb, w = CB.CB1_NLSF_Q8, CB.CB1_Wght_Q9 for i = 1, order do local v = tdiv(res_Q10[i] * 16384, w[base + i]) + cb[base + i] * 128 if v < 0 then v = 0 elseif v > 32767 then v = 32767 end pNLSF_Q15[i] = v end nlsfStabilize(pNLSF_Q15, CB.deltaMin_Q15, order) end local RES_COPY, RES_UP2, RES_IIR_FIR = 0, 1, 2 local up2_hq_0 = { 1746, 14986, 39083 - 65536 } local up2_hq_1 = { 6854, 25769, 55542 - 65536 } local FIR12 = T.resampler_frac_FIR_12 local delay_matrix_dec = { { 4, 0, 2, 0, 0, 0 }, { 0, 9, 4, 7, 4, 4 }, { 0, 3, 12, 7, 7, 7 }, } @native local function rateID(R: number): number local a = R // 4096 - (if R > 16000 then 1 else 0) if R > 24000 then a = a // 2 end return math.min(5, a - 1) end @native local function newResampler(): any return { sIIR = table.create(6, 0), sFIR = table.create(8, 0), delayBuf = table.create(96, 0), buf = table.create(2 * 160 + 8, 0), resampler_function = RES_COPY, batchSize = 0, invRatio_Q16 = 0, inputDelay = 0, Fs_in_kHz = 0, Fs_out_kHz = 0, } end @native local function copyResampler(dst: any, src: any) for i = 1, 6 do dst.sIIR[i] = src.sIIR[i] end for i = 1, 8 do dst.sFIR[i] = src.sFIR[i] end for i = 1, 96 do dst.delayBuf[i] = src.delayBuf[i] end dst.resampler_function = src.resampler_function dst.batchSize = src.batchSize dst.invRatio_Q16 = src.invRatio_Q16 dst.inputDelay = src.inputDelay dst.Fs_in_kHz = src.Fs_in_kHz dst.Fs_out_kHz = src.Fs_out_kHz end @native local function resamplerInit(S: any, Fs_Hz_in: number, Fs_Hz_out: number): number table.clear(S.sIIR) table.clear(S.sFIR) table.clear(S.delayBuf) for i = 1, 6 do S.sIIR[i] = 0 end for i = 1, 8 do S.sFIR[i] = 0 end for i = 1, 96 do S.delayBuf[i] = 0 end if (Fs_Hz_in ~= 8000 and Fs_Hz_in ~= 12000 and Fs_Hz_in ~= 16000) or Fs_Hz_out < Fs_Hz_in then return -1 -- the decoder only upsamples (or copies) end S.inputDelay = delay_matrix_dec[rateID(Fs_Hz_in) + 1][rateID(Fs_Hz_out) + 1] or 0 S.Fs_in_kHz = Fs_Hz_in // 1000 S.Fs_out_kHz = Fs_Hz_out // 1000 S.batchSize = S.Fs_in_kHz * 10 local up2x = 0 if Fs_Hz_out > Fs_Hz_in then if Fs_Hz_out == Fs_Hz_in * 2 then S.resampler_function = RES_UP2 else S.resampler_function = RES_IIR_FIR up2x = 1 end else S.resampler_function = RES_COPY end local inv = (Fs_Hz_in * p2(14 + up2x)) // Fs_Hz_out * 4 while mulww(inv, Fs_Hz_out) < Fs_Hz_in * p2(up2x) do inv += 1 end S.invRatio_Q16 = inv return 0 end -- silk_resampler_private_up2_HQ: out[oo + 2k], out[oo + 2k + 1] from inp[io + k] @native local function up2HQ(S: { number }, out: { number }, oo: number, inp: { number }, io: number, len: number) local s0, s1, s2, s3, s4, s5 = S[1], S[2], S[3], S[4], S[5], S[6] local c00, c01, c02 = up2_hq_0[1], up2_hq_0[2], up2_hq_0[3] local c10, c11, c12 = up2_hq_1[1], up2_hq_1[2], up2_hq_1[3] for k = 0, len - 1 do local in32 = inp[io + k] * 1024 local Y = in32 - s0 local X = (Y * c00) // 65536 local out32_1 = s0 + X s0 = in32 + X Y = out32_1 - s1 X = (Y * c01) // 65536 local out32_2 = s1 + X s1 = out32_1 + X Y = out32_2 - s2 X = Y + (Y * c02) // 65536 out32_1 = s2 + X s2 = out32_2 + X out[oo + 2 * k] = sat16((out32_1 + 512) // 1024) Y = in32 - s3 X = (Y * c10) // 65536 out32_1 = s3 + X s3 = in32 + X Y = out32_1 - s4 X = (Y * c11) // 65536 out32_2 = s4 + X s4 = out32_1 + X Y = out32_2 - s5 X = Y + (Y * c12) // 65536 out32_1 = s5 + X s5 = out32_2 + X out[oo + 2 * k + 1] = sat16((out32_1 + 512) // 1024) end S[1], S[2], S[3], S[4], S[5], S[6] = s0, s1, s2, s3, s4, s5 end @native local function iirFirInterpol(out: { number }, oo: number, buf: { number }, max_index_Q16: number, incr: number): number local index_Q16 = 0 while index_Q16 < max_index_Q16 do local ti = ((index_Q16 % 65536) * 12) // 65536 local b = index_Q16 // 65536 + 1 -- buf is 1-based local f0 = ti * 4 local f1 = (11 - ti) * 4 local res_Q15 = buf[b] * FIR12[f0 + 1] + buf[b + 1] * FIR12[f0 + 2] + buf[b + 2] * FIR12[f0 + 3] + buf[b + 3] * FIR12[f0 + 4] + buf[b + 4] * FIR12[f1 + 4] + buf[b + 5] * FIR12[f1 + 3] + buf[b + 6] * FIR12[f1 + 2] + buf[b + 7] * FIR12[f1 + 1] out[oo] = sat16((res_Q15 + 16384) // 32768) oo += 1 index_Q16 += incr end return oo end @native local function iirFir(S: any, out: { number }, oo: number, inp: { number }, io: number, inLen: number) local buf = S.buf local sFIR = S.sFIR for i = 1, 8 do buf[i] = sFIR[i] end local incr = S.invRatio_Q16 local nSamplesIn while true do nSamplesIn = math.min(inLen, S.batchSize) up2HQ(S.sIIR, buf, 9, inp, io, nSamplesIn) oo = iirFirInterpol(out, oo, buf, nSamplesIn * 131072, incr) io += nSamplesIn inLen -= nSamplesIn if inLen > 0 then local o = nSamplesIn * 2 for i = 1, 8 do buf[i] = buf[o + i] end else break end end local o = nSamplesIn * 2 for i = 1, 8 do sFIR[i] = buf[o + i] end end @native local function resampleBlock(S: any, out: { number }, oo: number, inp: { number }, io: number, len: number) local f = S.resampler_function if f == RES_IIR_FIR then iirFir(S, out, oo, inp, io, len) elseif f == RES_UP2 then up2HQ(S.sIIR, out, oo, inp, io, len) else for i = 0, len - 1 do out[oo + i] = inp[io + i] end end end -- silk_resampler: out[1..] from inp[io .. io + inLen - 1] @native local function resampler(S: any, out: { number }, inp: { number }, io: number, inLen: number) local fin = S.Fs_in_kHz local delay = S.inputDelay local nSamples = fin - delay local db = S.delayBuf for i = 0, nSamples - 1 do db[delay + i + 1] = inp[io + i] end resampleBlock(S, out, 1, db, 1, fin) resampleBlock(S, out, 1 + S.Fs_out_kHz, inp, io + nSamples, inLen - fin) for i = 0, delay - 1 do db[i + 1] = inp[io + inLen - delay + i] end end @native local function newChannel(): any return { prev_gain_Q16 = 65536, exc_Q14 = table.create(320, 0), sLPC_Q14_buf = table.create(16, 0), outBuf = table.create(480, 0), lagPrev = 0, LastGainIndex = 0, fs_kHz = 0, fs_API_hz = 0, nb_subfr = 0, frame_length = 0, subfr_length = 0, ltp_mem_length = 0, LPC_order = 0, prevNLSF_Q15 = table.create(16, 0), first_frame_after_reset = 1, pitch_lag_low_bits_iCDF = T.uniform4_iCDF, pitch_contour_iCDF = T.pitch_contour_iCDF, nFramesDecoded = 0, nFramesPerPacket = 0, ec_prevSignalType = 0, ec_prevLagIndex = 0, VAD_flags = { 0, 0, 0 }, LBRR_flag = 0, LBRR_flags = { 0, 0, 0 }, resampler_state = newResampler(), psNLSF_CB = CB_NB_MB, indices = { signalType = 0, quantOffsetType = 0, GainsIndices = { 0, 0, 0, 0 }, NLSFIndices = table.create(17, 0), NLSFInterpCoef_Q2 = 0, lagIndex = 0, contourIndex = 0, PERIndex = 0, LTPIndex = { 0, 0, 0, 0 }, LTP_scaleIndex = 0, Seed = 0, }, sCNG = { CNG_exc_buf_Q14 = table.create(320, 0), CNG_smth_NLSF_Q15 = table.create(16, 0), CNG_synth_state = table.create(16, 0), CNG_smth_Gain_Q16 = 0, rand_seed = 3176576, fs_kHz = 0, }, lossCnt = 0, prevSignalType = 0, sPLC = { pitchL_Q8 = 0, LTPCoef_Q14 = table.create(5, 0), prevLPC_Q12 = table.create(16, 0), last_frame_lost = 0, rand_seed = 0, randScale_Q14 = 0, conc_energy = 0, conc_energy_shift = 0, prevLTP_scale_Q14 = 0, prevGain_Q16 = { 65536, 65536 }, fs_kHz = 0, nb_subfr = 2, subfr_length = 20, }, -- per-frame decoder control (silk_decoder_control) and scratch ctrl = { pitchL = { 0, 0, 0, 0 }, Gains_Q16 = { 0, 0, 0, 0 }, PredCoef_Q12 = { table.create(16, 0), table.create(16, 0) }, LTPCoef_Q14 = table.create(20, 0), LTP_scale_Q14 = 0, }, pulses = table.create(336, 0), out = table.create(322, 0), -- samplesOut1_tmp: [1], [2] = the 2 buffered samples, frame from [3] } end @native local function decoderSetFs(ch: any, fs_kHz: number, fs_API_Hz: number): number local ret = 0 ch.subfr_length = 5 * fs_kHz local frame_length = ch.nb_subfr * ch.subfr_length if ch.fs_kHz ~= fs_kHz or ch.fs_API_hz ~= fs_API_Hz then ret += resamplerInit(ch.resampler_state, fs_kHz * 1000, fs_API_Hz) ch.fs_API_hz = fs_API_Hz end if ch.fs_kHz ~= fs_kHz or frame_length ~= ch.frame_length then if fs_kHz == 8 then ch.pitch_contour_iCDF = if ch.nb_subfr == 4 then T.pitch_contour_NB_iCDF else T.pitch_contour_10_ms_NB_iCDF else ch.pitch_contour_iCDF = if ch.nb_subfr == 4 then T.pitch_contour_iCDF else T.pitch_contour_10_ms_iCDF end if ch.fs_kHz ~= fs_kHz then ch.ltp_mem_length = 20 * fs_kHz if fs_kHz == 8 or fs_kHz == 12 then ch.LPC_order = 10 ch.psNLSF_CB = CB_NB_MB else ch.LPC_order = 16 ch.psNLSF_CB = CB_WB end if fs_kHz == 16 then ch.pitch_lag_low_bits_iCDF = T.uniform8_iCDF elseif fs_kHz == 12 then ch.pitch_lag_low_bits_iCDF = T.uniform6_iCDF else ch.pitch_lag_low_bits_iCDF = T.uniform4_iCDF end ch.first_frame_after_reset = 1 ch.lagPrev = 100 ch.LastGainIndex = 10 ch.prevSignalType = 0 local ob, sl = ch.outBuf, ch.sLPC_Q14_buf for i = 1, 480 do ob[i] = 0 end for i = 1, 16 do sl[i] = 0 end end ch.fs_kHz = fs_kHz ch.frame_length = frame_length end return ret end local LTP_gain_iCDF = { T.LTP_gain_iCDF_0, T.LTP_gain_iCDF_1, T.LTP_gain_iCDF_2 } local LTP_vq_Q7 = { T.LTP_gain_vq_0, T.LTP_gain_vq_1, T.LTP_gain_vq_2 } local LBRR_flags_iCDF = { T.LBRR_flags_2_iCDF, T.LBRR_flags_3_iCDF } @native local function decodeIndices(ch: any, d: any, FrameIndex: number, decode_LBRR: boolean, condCoding: number) local ind = ch.indices local Ix if decode_LBRR or ch.VAD_flags[FrameIndex + 1] ~= 0 then Ix = icdf(d, T.type_offset_VAD_iCDF, 1, 8) + 2 else Ix = icdf(d, T.type_offset_no_VAD_iCDF, 1, 8) end local signalType = Ix // 2 ind.signalType = signalType ind.quantOffsetType = Ix % 2 local gi = ind.GainsIndices if condCoding == 2 then gi[1] = icdf(d, T.delta_gain_iCDF, 1, 8) else gi[1] = icdf(d, T.gain_iCDF, signalType * 8 + 1, 8) * 8 gi[1] += icdf(d, T.uniform8_iCDF, 1, 8) end for i = 2, ch.nb_subfr do gi[i] = icdf(d, T.delta_gain_iCDF, 1, 8) end local CB = ch.psNLSF_CB local ni = ind.NLSFIndices ni[1] = icdf(d, CB.CB1_iCDF, (signalType // 2) * CB.nVectors + 1, 8) nlsfUnpack(CB, ni[1]) for i = 1, CB.order do Ix = icdf(d, CB.ec_iCDF, ec_ix[i] + 1, 8) if Ix == 0 then Ix -= icdf(d, T.NLSF_EXT_iCDF, 1, 8) elseif Ix == 8 then Ix += icdf(d, T.NLSF_EXT_iCDF, 1, 8) end ni[i + 1] = Ix - 4 end if ch.nb_subfr == 4 then ind.NLSFInterpCoef_Q2 = icdf(d, T.NLSF_interpolation_factor_iCDF, 1, 8) else ind.NLSFInterpCoef_Q2 = 4 end if signalType == 2 then local absolute = true if condCoding == 2 and ch.ec_prevSignalType == 2 then local delta = icdf(d, T.pitch_delta_iCDF, 1, 8) if delta > 0 then ind.lagIndex = s16(ch.ec_prevLagIndex + delta - 9) absolute = false end end if absolute then ind.lagIndex = icdf(d, T.pitch_lag_iCDF, 1, 8) * (ch.fs_kHz // 2) ind.lagIndex += icdf(d, ch.pitch_lag_low_bits_iCDF, 1, 8) end ch.ec_prevLagIndex = ind.lagIndex ind.contourIndex = icdf(d, ch.pitch_contour_iCDF, 1, 8) ind.PERIndex = icdf(d, T.LTP_per_index_iCDF, 1, 8) local tab = LTP_gain_iCDF[ind.PERIndex + 1] for k = 1, ch.nb_subfr do ind.LTPIndex[k] = icdf(d, tab, 1, 8) end if condCoding == 0 then ind.LTP_scaleIndex = icdf(d, T.LTPscale_iCDF, 1, 8) else ind.LTP_scaleIndex = 0 end end ch.ec_prevSignalType = signalType ind.Seed = icdf(d, T.uniform4_iCDF, 1, 8) end local shell0, shell1, shell2, shell3 = T.shell_code_table0, T.shell_code_table1, T.shell_code_table2, T.shell_code_table3 local shellOff = T.shell_code_table_offsets @native local function split(d: any, p: number, tab: { number }): (number, number) if p > 0 then local a = icdf(d, tab, shellOff[p + 1] + 1, 8) return a, p - a end return 0, 0 end @native local function shellDecoder(out: { number }, o: number, d: any, pulses4: number) local p3a, p3b = split(d, pulses4, shell3) local p2a, p2b = split(d, p3a, shell2) local p1a, p1b = split(d, p2a, shell1) out[o], out[o + 1] = split(d, p1a, shell0) out[o + 2], out[o + 3] = split(d, p1b, shell0) p1a, p1b = split(d, p2b, shell1) out[o + 4], out[o + 5] = split(d, p1a, shell0) out[o + 6], out[o + 7] = split(d, p1b, shell0) p2a, p2b = split(d, p3b, shell2) p1a, p1b = split(d, p2a, shell1) out[o + 8], out[o + 9] = split(d, p1a, shell0) out[o + 10], out[o + 11] = split(d, p1b, shell0) p1a, p1b = split(d, p2b, shell1) out[o + 12], out[o + 13] = split(d, p1a, shell0) out[o + 14], out[o + 15] = split(d, p1b, shell0) end local sum_pulses = table.create(20, 0) local nLshifts = table.create(20, 0) local signIcdf = { 0, 0 } -- pulses[1 .. frame_length (rounded up to 16)] @native local function decodePulses(d: any, pulses: { number }, signalType: number, quantOffsetType: number, frame_length: number) local RateLevelIndex = icdf(d, T.rate_levels_iCDF, (signalType // 2) * 9 + 1, 8) local iter = frame_length // 16 if iter * 16 < frame_length then iter += 1 end local ppb = T.pulses_per_block_iCDF for i = 1, iter do nLshifts[i] = 0 local s = icdf(d, ppb, RateLevelIndex * 18 + 1, 8) while s == 17 do nLshifts[i] += 1 s = icdf(d, ppb, 9 * 18 + 1 + (if nLshifts[i] == 10 then 1 else 0), 8) if nLshifts[i] > 30 then break -- corrupt stream guard end end sum_pulses[i] = s end for i = 1, iter do local o = (i - 1) * 16 + 1 if sum_pulses[i] > 0 then shellDecoder(pulses, o, d, sum_pulses[i]) else for k = 0, 15 do pulses[o + k] = 0 end end end local lsb = T.lsb_iCDF for i = 1, iter do local nLS = nLshifts[i] if nLS > 0 then local o = (i - 1) * 16 + 1 for k = 0, 15 do local abs_q = pulses[o + k] for _ = 1, nLS do abs_q = abs_q * 2 + icdf(d, lsb, 1, 8) end pulses[o + k] = abs_q end sum_pulses[i] += nLS * 32 end end -- silk_decode_signs local signTab = T.sign_iCDF local base = 7 * (quantOffsetType + signalType * 2) local blocks = (frame_length + 8) // 16 for i = 1, blocks do local p = sum_pulses[i] if p > 0 then signIcdf[1] = signTab[base + math.min(p % 32, 6) + 1] local o = (i - 1) * 16 + 1 for j = 0, 15 do local q = pulses[o + j] if q > 0 then pulses[o + j] = q * (icdf(d, signIcdf, 1, 8) * 2 - 1) end end end end end local pNLSF_Q15 = table.create(16, 0) local pNLSF0_Q15 = table.create(16, 0) @native local function gainsDequant(gain_Q16: { number }, ind: { number }, ch: any, conditional: boolean, nb_subfr: number) local prev = ch.LastGainIndex for k = 1, nb_subfr do if k == 1 and not conditional then prev = math.max(ind[k], prev - 16) else local ind_tmp = ind[k] - 4 local thr = 8 + prev if ind_tmp > thr then prev += ind_tmp * 2 - thr else prev += ind_tmp end end if prev < 0 then prev = 0 elseif prev > 63 then prev = 63 end gain_Q16[k] = silkLog2lin(math.min((1907825 * prev) // 65536 + 2090, 3967)) end ch.LastGainIndex = prev end local CB_lags = { [8] = { [4] = { T.CB_lags_stage2, 11 }, [2] = { T.CB_lags_stage2_10_ms, 3 } }, [0] = { [4] = { T.CB_lags_stage3, 34 }, [2] = { T.CB_lags_stage3_10_ms, 12 } }, } @native local function decodeParameters(ch: any, ctrl: any, condCoding: number) local ind = ch.indices gainsDequant(ctrl.Gains_Q16, ind.GainsIndices, ch, condCoding == 2, ch.nb_subfr) local order = ch.LPC_order nlsfDecode(pNLSF_Q15, ind.NLSFIndices, ch.psNLSF_CB) nlsf2a(ctrl.PredCoef_Q12[2], pNLSF_Q15, order) if ch.first_frame_after_reset == 1 then ind.NLSFInterpCoef_Q2 = 4 end local prevNLSF = ch.prevNLSF_Q15 if ind.NLSFInterpCoef_Q2 < 4 then local c = ind.NLSFInterpCoef_Q2 for i = 1, order do pNLSF0_Q15[i] = prevNLSF[i] + (c * (pNLSF_Q15[i] - prevNLSF[i])) // 4 end nlsf2a(ctrl.PredCoef_Q12[1], pNLSF0_Q15, order) else local a, b = ctrl.PredCoef_Q12[1], ctrl.PredCoef_Q12[2] for i = 1, order do a[i] = b[i] end end for i = 1, order do prevNLSF[i] = pNLSF_Q15[i] end if ch.lossCnt ~= 0 then bwexpander(ctrl.PredCoef_Q12[1], order, 63570) bwexpander(ctrl.PredCoef_Q12[2], order, 63570) end if ind.signalType == 2 then -- silk_decode_pitch local fs = ch.fs_kHz local cbinfo = CB_lags[if fs == 8 then 8 else 0][ch.nb_subfr] local cb, cbk_size = cbinfo[1], cbinfo[2] local min_lag, max_lag = 2 * fs, 18 * fs local lag = min_lag + ind.lagIndex for k = 0, ch.nb_subfr - 1 do local v = lag + cb[k * cbk_size + ind.contourIndex + 1] if v < min_lag then v = min_lag elseif v > max_lag then v = max_lag end ctrl.pitchL[k + 1] = v end local vq = LTP_vq_Q7[ind.PERIndex + 1] for k = 0, ch.nb_subfr - 1 do local Ix = ind.LTPIndex[k + 1] for i = 1, 5 do ctrl.LTPCoef_Q14[k * 5 + i] = vq[Ix * 5 + i] * 128 end end ctrl.LTP_scale_Q14 = T.LTPScales_table_Q14[ind.LTP_scaleIndex + 1] else for k = 1, ch.nb_subfr do ctrl.pitchL[k] = 0 end for k = 1, 5 * ch.nb_subfr do ctrl.LTPCoef_Q14[k] = 0 end ind.PERIndex = 0 ctrl.LTP_scale_Q14 = 0 end end local sLTP = table.create(320, 0) local sLTP_Q15 = table.create(640, 0) local res_Q14 = table.create(80, 0) local sLPC_Q14 = table.create(96, 0) local A_Q12_tmp = table.create(16, 0) local QuantOffsets = { { 100, 240 }, { 32, 100 } } -- silk_decode_core: xq[xo .. xo + frame_length - 1] @native local function decodeCore(ch: any, ctrl: any, xq: { number }, xo: number, pulses: { number }) local ind = ch.indices local exc = ch.exc_Q14 local offset_Q10 = QuantOffsets[ind.signalType // 2 + 1][ind.quantOffsetType + 1] local NLSF_interpolation_flag = ind.NLSFInterpCoef_Q2 < 4 local frame_length = ch.frame_length local subfr_length = ch.subfr_length local ltp_mem_length = ch.ltp_mem_length local order = ch.LPC_order local outBuf = ch.outBuf local rand_seed = ind.Seed for i = 1, frame_length do rand_seed = silkRand(rand_seed) local p = pulses[i] local e = p * 16384 if e > 0 then e -= 1280 elseif e < 0 then e += 1280 end e += offset_Q10 * 16 if rand_seed < 0 then e = -e end exc[i] = e rand_seed = i32(rand_seed + p) end local sl = ch.sLPC_Q14_buf for i = 1, 16 do sLPC_Q14[i] = sl[i] end local pexc = 0 -- C offset into exc local pxq = xo local sLTP_buf_idx = ltp_mem_length -- C index into sLTP_Q15 local lag = 0 for k = 0, ch.nb_subfr - 1 do local A_Q12 = ctrl.PredCoef_Q12[k // 2 + 1] for i = 1, order do A_Q12_tmp[i] = A_Q12[i] end local Bo = k * 5 -- C offset into LTPCoef_Q14 local B = ctrl.LTPCoef_Q14 local signalType = ind.signalType local gain = ctrl.Gains_Q16[k + 1] local Gain_Q10 = gain // 64 local inv_gain_Q31 = silkINVERSE32_varQ(gain, 47) local gain_adj_Q16 if gain ~= ch.prev_gain_Q16 then gain_adj_Q16 = silkDIV32_varQ(ch.prev_gain_Q16, gain, 16) for i = 1, 16 do sLPC_Q14[i] = i32(mulww(gain_adj_Q16, sLPC_Q14[i])) end else gain_adj_Q16 = 65536 end ch.prev_gain_Q16 = gain if ch.lossCnt ~= 0 and ch.prevSignalType == 2 and ind.signalType ~= 2 and k < 2 then for i = 1, 5 do B[Bo + i] = 0 end B[Bo + 3] = 4096 signalType = 2 ctrl.pitchL[k + 1] = ch.lagPrev end if signalType == 2 then lag = ctrl.pitchL[k + 1] if k == 0 or (k == 2 and NLSF_interpolation_flag) then local start_idx = ltp_mem_length - lag - order - 2 if start_idx < 1 then start_idx = 1 -- corrupt stream guard (C asserts start_idx > 0) end if k == 2 then for i = 0, 2 * subfr_length - 1 do outBuf[ltp_mem_length + i + 1] = xq[xo + i] end end lpcAnalysisFilter(sLTP, start_idx + 1, outBuf, start_idx + k * subfr_length + 1, A_Q12, ltp_mem_length - start_idx, order) if k == 0 then inv_gain_Q31 = ((inv_gain_Q31 * ctrl.LTP_scale_Q14) // 65536) * 4 end for i = 0, lag + 1 do sLTP_Q15[sLTP_buf_idx - i] = (inv_gain_Q31 * sLTP[ltp_mem_length - i]) // 65536 end else if gain_adj_Q16 ~= 65536 then for i = 0, lag + 1 do local j = sLTP_buf_idx - i sLTP_Q15[j] = i32(mulww(gain_adj_Q16, sLTP_Q15[j])) end end end end local presArr, presOff if signalType == 2 then local b0, b1, b2, b3, b4 = B[Bo + 1], B[Bo + 2], B[Bo + 3], B[Bo + 4], B[Bo + 5] local pl = sLTP_buf_idx - lag + 2 + 1 -- 1-based index of pred_lag_ptr[0] for i = 1, subfr_length do local pred = 2 pred += (sLTP_Q15[pl] * b0) // 65536 pred += (sLTP_Q15[pl - 1] * b1) // 65536 pred += (sLTP_Q15[pl - 2] * b2) // 65536 pred += (sLTP_Q15[pl - 3] * b3) // 65536 pred += (sLTP_Q15[pl - 4] * b4) // 65536 pl += 1 local r = exc[pexc + i] + pred * 2 res_Q14[i] = r sLTP_buf_idx += 1 sLTP_Q15[sLTP_buf_idx] = r * 2 end presArr, presOff = res_Q14, 0 else presArr, presOff = exc, pexc end local a0, a1, a2, a3, a4, a5, a6, a7, a8, a9 = A_Q12_tmp[1], A_Q12_tmp[2], A_Q12_tmp[3], A_Q12_tmp[4], A_Q12_tmp[5], A_Q12_tmp[6], A_Q12_tmp[7], A_Q12_tmp[8], A_Q12_tmp[9], A_Q12_tmp[10] local wide = order == 16 local a10, a11, a12, a13, a14, a15 = A_Q12_tmp[11], A_Q12_tmp[12], A_Q12_tmp[13], A_Q12_tmp[14], A_Q12_tmp[15], A_Q12_tmp[16] for i = 1, subfr_length do local j = 16 + i -- 1-based index of sLPC_Q14[MAX_LPC_ORDER + i - 1 (C)] + 1 local pred = order // 2 pred += (sLPC_Q14[j - 1] * a0) // 65536 pred += (sLPC_Q14[j - 2] * a1) // 65536 pred += (sLPC_Q14[j - 3] * a2) // 65536 pred += (sLPC_Q14[j - 4] * a3) // 65536 pred += (sLPC_Q14[j - 5] * a4) // 65536 pred += (sLPC_Q14[j - 6] * a5) // 65536 pred += (sLPC_Q14[j - 7] * a6) // 65536 pred += (sLPC_Q14[j - 8] * a7) // 65536 pred += (sLPC_Q14[j - 9] * a8) // 65536 pred += (sLPC_Q14[j - 10] * a9) // 65536 if wide then pred += (sLPC_Q14[j - 11] * a10) // 65536 pred += (sLPC_Q14[j - 12] * a11) // 65536 pred += (sLPC_Q14[j - 13] * a12) // 65536 pred += (sLPC_Q14[j - 14] * a13) // 65536 pred += (sLPC_Q14[j - 15] * a14) // 65536 pred += (sLPC_Q14[j - 16] * a15) // 65536 end pred = i32(pred) local v = addSat32(presArr[presOff + i], lshiftSat32(pred, 4)) sLPC_Q14[j] = v xq[pxq + i - 1] = sat16((mulww(v, Gain_Q10) + 128) // 256) end for i = 1, 16 do sLPC_Q14[i] = sLPC_Q14[subfr_length + i] end pexc += subfr_length pxq += subfr_length end for i = 1, 16 do sl[i] = sLPC_Q14[i] end end local HARM_ATT_Q15 = { 32440, 31130 } local PLC_RAND_ATTENUATE_V_Q15 = { 31130, 26214 } local PLC_RAND_ATTENUATE_UV_Q15 = { 32440, 29491 } @native local function plcReset(ch: any) local plc = ch.sPLC plc.pitchL_Q8 = ch.frame_length * 128 plc.prevGain_Q16[1] = 65536 plc.prevGain_Q16[2] = 65536 plc.subfr_length = 20 plc.nb_subfr = 2 end @native local function cngReset(ch: any) local step = tdiv(32767, ch.LPC_order + 1) local acc = 0 local cng = ch.sCNG for i = 1, ch.LPC_order do acc += step cng.CNG_smth_NLSF_Q15[i] = acc end cng.CNG_smth_Gain_Q16 = 0 cng.rand_seed = 3176576 end @native local function plcUpdate(ch: any, ctrl: any) local plc = ch.sPLC local nb = ch.nb_subfr ch.prevSignalType = ch.indices.signalType local LTP_Gain_Q14 = 0 local coef = plc.LTPCoef_Q14 if ch.indices.signalType == 2 then local j = 0 while j * ch.subfr_length < ctrl.pitchL[nb] do if j == nb then break end local t = 0 local o = (nb - 1 - j) * 5 for i = 1, 5 do t += ctrl.LTPCoef_Q14[o + i] end if t > LTP_Gain_Q14 then LTP_Gain_Q14 = t for i = 1, 5 do coef[i] = ctrl.LTPCoef_Q14[o + i] end plc.pitchL_Q8 = ctrl.pitchL[nb - j] * 256 end j += 1 end for i = 1, 5 do coef[i] = 0 end coef[3] = LTP_Gain_Q14 if LTP_Gain_Q14 < 11469 then local scale_Q10 = tdiv(11469 * 1024, math.max(LTP_Gain_Q14, 1)) for i = 1, 5 do coef[i] = (s16(coef[i]) * s16(scale_Q10)) // 1024 end elseif LTP_Gain_Q14 > 15565 then local scale_Q14 = tdiv(15565 * 16384, math.max(LTP_Gain_Q14, 1)) for i = 1, 5 do coef[i] = (s16(coef[i]) * s16(scale_Q14)) // 16384 end end else plc.pitchL_Q8 = ch.fs_kHz * 18 * 256 for i = 1, 5 do coef[i] = 0 end end local p = ctrl.PredCoef_Q12[2] for i = 1, ch.LPC_order do plc.prevLPC_Q12[i] = p[i] end plc.prevLTP_scale_Q14 = ctrl.LTP_scale_Q14 plc.prevGain_Q16[1] = ctrl.Gains_Q16[nb - 1] plc.prevGain_Q16[2] = ctrl.Gains_Q16[nb] plc.subfr_length = ch.subfr_length plc.nb_subfr = nb end local excBuf = table.create(160, 0) local plcLTP = table.create(320, 0) local plcLTP_Q14 = table.create(640, 0) local A_plc = table.create(16, 0) @native local function plcConceal(ch: any, ctrl: any, frame: { number }, fo: number) local plc = ch.sPLC local ltp_mem_length = ch.ltp_mem_length local order = ch.LPC_order local prevGain_Q10_0 = plc.prevGain_Q16[1] // 64 local prevGain_Q10_1 = plc.prevGain_Q16[2] // 64 if ch.first_frame_after_reset ~= 0 then for i = 1, 16 do plc.prevLPC_Q12[i] = 0 end end -- silk_PLC_energy local sl, nb = ch.subfr_length, ch.nb_subfr local exc = ch.exc_Q14 for k = 0, 1 do local g = if k == 0 then prevGain_Q10_0 else prevGain_Q10_1 for i = 0, sl - 1 do excBuf[k * sl + i + 1] = sat16(i32(mulww(exc[i + (k + nb - 2) * sl + 1], g)) // 256) end end local energy1, shift1 = sumSqrShift(excBuf, 1, sl) local energy2, shift2 = sumSqrShift(excBuf, sl + 1, sl) local rand_off -- C offset into exc_Q14 if rshift(energy1, shift2) < rshift(energy2, shift1) then rand_off = math.max(0, (plc.nb_subfr - 1) * plc.subfr_length - 128) else rand_off = math.max(0, plc.nb_subfr * plc.subfr_length - 128) end local B = plc.LTPCoef_Q14 local rand_scale_Q14 = plc.randScale_Q14 local att = math.min(1, ch.lossCnt) + 1 local harm_Gain_Q15 = HARM_ATT_Q15[att] local rand_Gain_Q15 = if ch.prevSignalType == 2 then PLC_RAND_ATTENUATE_V_Q15[att] else PLC_RAND_ATTENUATE_UV_Q15[att] bwexpander(plc.prevLPC_Q12, order, 64881) for i = 1, order do A_plc[i] = plc.prevLPC_Q12[i] end if ch.lossCnt == 0 then rand_scale_Q14 = 16384 if ch.prevSignalType == 2 then for i = 1, 5 do rand_scale_Q14 -= B[i] end rand_scale_Q14 = math.max(3277, s16(rand_scale_Q14)) rand_scale_Q14 = s16((rand_scale_Q14 * s16(plc.prevLTP_scale_Q14)) // 16384) else local invGain_Q30 = lpcInversePredGain(plc.prevLPC_Q12, order) local down = math.min(1073741824 // 8, invGain_Q30) down = math.max(1073741824 // 256, down) down = down * 8 rand_Gain_Q15 = ((down * s16(rand_Gain_Q15)) // 65536) // 16384 end end local rand_seed = plc.rand_seed local lag = (plc.pitchL_Q8 + 128) // 256 local sLTP_buf_idx = ltp_mem_length local idx = ltp_mem_length - lag - order - 2 if idx < 1 then idx = 1 end lpcAnalysisFilter(plcLTP, idx + 1, ch.outBuf, idx + 1, A_plc, ltp_mem_length - idx, order) local inv_gain_Q30 = silkINVERSE32_varQ(plc.prevGain_Q16[2], 46) inv_gain_Q30 = math.min(inv_gain_Q30, 1073741823) for i = idx + order, ltp_mem_length - 1 do plcLTP_Q14[i + 1] = (inv_gain_Q30 * plcLTP[i + 1]) // 65536 end for _ = 0, ch.nb_subfr - 1 do local pl = sLTP_buf_idx - lag + 2 + 1 local b0, b1, b2, b3, b4 = B[1], B[2], B[3], B[4], B[5] for _ = 1, sl do local pred = 2 pred += (plcLTP_Q14[pl] * b0) // 65536 pred += (plcLTP_Q14[pl - 1] * b1) // 65536 pred += (plcLTP_Q14[pl - 2] * b2) // 65536 pred += (plcLTP_Q14[pl - 3] * b3) // 65536 pred += (plcLTP_Q14[pl - 4] * b4) // 65536 pl += 1 rand_seed = silkRand(rand_seed) local ri = (rand_seed // 33554432) % 128 sLTP_buf_idx += 1 plcLTP_Q14[sLTP_buf_idx] = i32((pred + (exc[rand_off + ri + 1] * s16(rand_scale_Q14)) // 65536) * 4) end for j = 1, 5 do B[j] = (harm_Gain_Q15 * s16(B[j])) // 32768 end rand_scale_Q14 = (s16(rand_scale_Q14) * s16(rand_Gain_Q15)) // 32768 plc.pitchL_Q8 = plc.pitchL_Q8 + (plc.pitchL_Q8 * 655) // 65536 plc.pitchL_Q8 = math.min(plc.pitchL_Q8, 18 * ch.fs_kHz * 256) lag = (plc.pitchL_Q8 + 128) // 256 end -- LPC synthesis in place over plcLTP_Q14, starting at C offset ltp_mem_length - 16 local base = ltp_mem_length - 16 -- C offset of sLPC_Q14_ptr local slb = ch.sLPC_Q14_buf for i = 1, 16 do plcLTP_Q14[base + i] = slb[i] end for i = 0, ch.frame_length - 1 do local j = base + 16 + i + 1 -- 1-based index of sLPC_Q14_ptr[16 + i] local pred = order // 2 for t = 1, order do pred += (plcLTP_Q14[j - t] * A_plc[t]) // 65536 end pred = i32(pred) local v = addSat32(plcLTP_Q14[j], lshiftSat32(pred, 4)) plcLTP_Q14[j] = v frame[fo + i] = sat16((mulww(v, prevGain_Q10_1) + 128) // 256) end for i = 1, 16 do slb[i] = plcLTP_Q14[base + ch.frame_length + i] end plc.rand_seed = rand_seed plc.randScale_Q14 = s16(rand_scale_Q14) for i = 1, 4 do ctrl.pitchL[i] = lag end end @native local function plcGlueFrames(ch: any, frame: { number }, fo: number, length: number) local plc = ch.sPLC if ch.lossCnt ~= 0 then plc.conc_energy, plc.conc_energy_shift = sumSqrShift(frame, fo, length) plc.last_frame_lost = 1 else if plc.last_frame_lost ~= 0 then local energy, energy_shift = sumSqrShift(frame, fo, length) if energy_shift > plc.conc_energy_shift then plc.conc_energy = rshift(plc.conc_energy, energy_shift - plc.conc_energy_shift) elseif energy_shift < plc.conc_energy_shift then energy = rshift(energy, plc.conc_energy_shift - energy_shift) end if energy > plc.conc_energy then local LZ = clz32(plc.conc_energy) - 1 plc.conc_energy = i32(plc.conc_energy * p2(LZ)) energy = rshift(energy, math.max(24 - LZ, 0)) local frac_Q24 = tdiv(plc.conc_energy, math.max(energy, 1)) local gain_Q16 = silkSQRT_APPROX(frac_Q24) * 16 local slope_Q16 = tdiv(65536 - gain_Q16, length) * 4 for i = 0, length - 1 do frame[fo + i] = (gain_Q16 * frame[fo + i]) // 65536 gain_Q16 += slope_Q16 if gain_Q16 > 65536 then break end end end end plc.last_frame_lost = 0 end end local A_cng = table.create(16, 0) local CNG_sig = table.create(336, 0) @native local function cng(ch: any, ctrl: any, frame: { number }, fo: number, length: number) local c = ch.sCNG if ch.fs_kHz ~= c.fs_kHz then cngReset(ch) c.fs_kHz = ch.fs_kHz end local order = ch.LPC_order if ch.lossCnt == 0 and ch.prevSignalType == 0 then local sm = c.CNG_smth_NLSF_Q15 for i = 1, order do sm[i] += ((ch.prevNLSF_Q15[i] - sm[i]) * 16348) // 65536 end local max_Gain_Q16, subfr = 0, 0 for i = 0, ch.nb_subfr - 1 do if ctrl.Gains_Q16[i + 1] > max_Gain_Q16 then max_Gain_Q16 = ctrl.Gains_Q16[i + 1] subfr = i end end local eb = c.CNG_exc_buf_Q14 local sl = ch.subfr_length for i = (ch.nb_subfr - 1) * sl, 1, -1 do eb[sl + i] = eb[i] end for i = 1, sl do eb[i] = ch.exc_Q14[subfr * sl + i] end for i = 1, ch.nb_subfr do local g = ctrl.Gains_Q16[i] c.CNG_smth_Gain_Q16 += ((g - c.CNG_smth_Gain_Q16) * 4634) // 65536 if mulww(c.CNG_smth_Gain_Q16, 46396) > g then c.CNG_smth_Gain_Q16 = g end end end if ch.lossCnt ~= 0 then local gain_Q16 = i32(mulww(ch.sPLC.randScale_Q14, ch.sPLC.prevGain_Q16[2])) if gain_Q16 >= 2097152 or c.CNG_smth_Gain_Q16 > 8388608 then gain_Q16 = (gain_Q16 // 65536) * (gain_Q16 // 65536) gain_Q16 = i32((c.CNG_smth_Gain_Q16 // 65536) * (c.CNG_smth_Gain_Q16 // 65536) - gain_Q16 * 32) gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 65536) else gain_Q16 = i32(mulww(gain_Q16, gain_Q16)) gain_Q16 = i32(i32(mulww(c.CNG_smth_Gain_Q16, c.CNG_smth_Gain_Q16)) - gain_Q16 * 32) gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 256) end local gain_Q10 = gain_Q16 // 64 -- silk_CNG_exc local exc_mask = 255 while exc_mask > length do exc_mask //= 2 end local seed = c.rand_seed for i = 1, length do seed = silkRand(seed) local idx = bit32.band((seed // 16777216) % 256, exc_mask) CNG_sig[16 + i] = c.CNG_exc_buf_Q14[idx + 1] end c.rand_seed = seed nlsf2a(A_cng, c.CNG_smth_NLSF_Q15, order) for i = 1, 16 do CNG_sig[i] = c.CNG_synth_state[i] end for i = 0, length - 1 do local j = 16 + i + 1 local pred = order // 2 for t = 1, order do pred += (CNG_sig[j - t] * A_cng[t]) // 65536 end pred = i32(pred) local v = addSat32(CNG_sig[j], lshiftSat32(pred, 4)) CNG_sig[j] = v frame[fo + i] = sat16(frame[fo + i] + sat16((mulww(v, gain_Q10) + 128) // 256)) end for i = 1, 16 do c.CNG_synth_state[i] = CNG_sig[length + i] end else for i = 1, order do c.CNG_synth_state[i] = 0 end end end -- silk_decode_frame: writes frame_length samples to out[fo ..] @native local function decodeFrame(ch: any, d: any, out: { number }, fo: number, lostFlag: number, condCoding: number): number local L = ch.frame_length local ctrl = ch.ctrl ctrl.LTP_scale_Q14 = 0 if lostFlag == 0 or (lostFlag == 2 and ch.LBRR_flags[ch.nFramesDecoded + 1] == 1) then local pulses = ch.pulses decodeIndices(ch, d, ch.nFramesDecoded, lostFlag ~= 0, condCoding) decodePulses(d, pulses, ch.indices.signalType, ch.indices.quantOffsetType, L) decodeParameters(ch, ctrl, condCoding) decodeCore(ch, ctrl, out, fo, pulses) local mv_len = ch.ltp_mem_length - L local ob = ch.outBuf for i = 1, mv_len do ob[i] = ob[L + i] end for i = 0, L - 1 do ob[mv_len + i + 1] = out[fo + i] end -- silk_PLC (update) if ch.fs_kHz ~= ch.sPLC.fs_kHz then plcReset(ch) ch.sPLC.fs_kHz = ch.fs_kHz end plcUpdate(ch, ctrl) ch.lossCnt = 0 ch.prevSignalType = ch.indices.signalType ch.first_frame_after_reset = 0 else if ch.fs_kHz ~= ch.sPLC.fs_kHz then plcReset(ch) ch.sPLC.fs_kHz = ch.fs_kHz end plcConceal(ch, ctrl, out, fo) ch.lossCnt += 1 local mv_len = ch.ltp_mem_length - L local ob = ch.outBuf for i = 1, mv_len do ob[i] = ob[L + i] end for i = 0, L - 1 do ob[mv_len + i + 1] = out[fo + i] end end cng(ch, ctrl, out, fo, L) plcGlueFrames(ch, out, fo, L) ch.lagPrev = ctrl.pitchL[ch.nb_subfr] return L end @native local function stereoDecodePred(d: any, pred_Q13: { number }) local n = icdf(d, T.stereo_pred_joint_iCDF, 1, 8) local ix02 = n // 5 local ix12 = n - 5 * ix02 local ix00 = icdf(d, T.uniform3_iCDF, 1, 8) local ix01 = icdf(d, T.uniform5_iCDF, 1, 8) local ix10 = icdf(d, T.uniform3_iCDF, 1, 8) local ix11 = icdf(d, T.uniform5_iCDF, 1, 8) local q = T.stereo_pred_quant_Q13 for c = 1, 2 do local a = if c == 1 then ix00 + 3 * ix02 else ix10 + 3 * ix12 local b = if c == 1 then ix01 else ix11 local low_Q13 = q[a + 1] local step_Q13 = ((q[a + 2] - low_Q13) * 6554) // 65536 pred_Q13[c] = low_Q13 + s16(step_Q13) * (2 * b + 1) end pred_Q13[1] -= pred_Q13[2] end -- x1, x2: samplesOut1_tmp arrays (C index j at [j + 1]) @native local function stereoMSToLR(state: any, x1: { number }, x2: { number }, pred_Q13: { number }, fs_kHz: number, frame_length: number) x1[1], x1[2] = state.sMid[1], state.sMid[2] x2[1], x2[2] = state.sSide[1], state.sSide[2] state.sMid[1], state.sMid[2] = x1[frame_length + 1], x1[frame_length + 2] state.sSide[1], state.sSide[2] = x2[frame_length + 1], x2[frame_length + 2] local pred0 = state.pred_prev_Q13[1] local pred1 = state.pred_prev_Q13[2] local interp = 8 * fs_kHz local denom_Q16 = tdiv(65536, interp) local delta0 = (s16(pred_Q13[1] - pred0) * s16(denom_Q16) + 32768) // 65536 local delta1 = (s16(pred_Q13[2] - pred1) * s16(denom_Q16) + 32768) // 65536 for n = 0, frame_length - 1 do if n < interp then pred0 += delta0 pred1 += delta1 elseif n == interp then pred0 = pred_Q13[1] pred1 = pred_Q13[2] end local sum = (x1[n + 1] + x1[n + 3] + x1[n + 2] * 2) * 512 sum = x2[n + 2] * 256 + (sum * s16(pred0)) // 65536 sum = sum + ((x1[n + 2] * 2048) * s16(pred1)) // 65536 x2[n + 2] = sat16((sum + 128) // 256) end if frame_length <= interp then -- the second loop never ran; the C code still ends with pred = pred_Q13 end state.pred_prev_Q13[1] = pred_Q13[1] state.pred_prev_Q13[2] = pred_Q13[2] for n = 0, frame_length - 1 do local a, b = x1[n + 2], x2[n + 2] x1[n + 2] = sat16(a + b) x2[n + 2] = sat16(a - b) end end type State = any @native function Silk.new(apiChannels: number): State return { ch = { newChannel(), newChannel() }, sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } }, nChannelsAPI = 0, nChannelsInternal = 0, prev_decode_only_middle = 0, MS_pred_Q13 = { 0, 0 }, resampOut = table.create(960, 0), apiChannels = apiChannels, } end -- silk_ResetDecoder (keeps nChannelsAPI / nChannelsInternal, like libopus) @native function Silk.reset(st: State) st.ch[1] = newChannel() st.ch[2] = newChannel() for _, ch in st.ch do cngReset(ch) plcReset(ch) end st.sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } } st.prev_decode_only_middle = 0 end @native local function initChannel(st: State, n: number) local ch = newChannel() cngReset(ch) plcReset(ch) st.ch[n] = ch end @native function Silk.decode(st: State, ctrl: any, lostFlag: number, firstFrame: boolean, d: any, out: { number }, outBase: number): (number, number) local ret = 0 local nInt = ctrl.nChannelsInternal local nAPI = ctrl.nChannelsAPI local chs = st.ch local decode_only_middle = 0 local MS_pred_Q13 = st.MS_pred_Q13 MS_pred_Q13[1], MS_pred_Q13[2] = 0, 0 if nInt ~= 1 and nInt ~= 2 then return -200, 0 end if firstFrame then for n = 1, nInt do chs[n].nFramesDecoded = 0 end end if nInt > st.nChannelsInternal then initChannel(st, 2) end local ch1 = chs[1] local stereo_to_mono = nInt == 1 and st.nChannelsInternal == 2 and ctrl.internalSampleRate == 1000 * ch1.fs_kHz if ch1.nFramesDecoded == 0 then for n = 1, nInt do local ch = chs[n] local ms = ctrl.payloadSize_ms if ms == 0 or ms == 10 then ch.nFramesPerPacket = 1 ch.nb_subfr = 2 elseif ms == 20 then ch.nFramesPerPacket = 1 ch.nb_subfr = 4 elseif ms == 40 then ch.nFramesPerPacket = 2 ch.nb_subfr = 4 elseif ms == 60 then ch.nFramesPerPacket = 3 ch.nb_subfr = 4 else return -203, 0 end local fs_kHz_dec = ctrl.internalSampleRate // 1024 + 1 if fs_kHz_dec ~= 8 and fs_kHz_dec ~= 12 and fs_kHz_dec ~= 16 then return -200, 0 end ret += decoderSetFs(ch, fs_kHz_dec, ctrl.API_sampleRate) end end if nAPI == 2 and nInt == 2 and (st.nChannelsAPI == 1 or st.nChannelsInternal == 1) then local s = st.sStereo s.pred_prev_Q13[1], s.pred_prev_Q13[2] = 0, 0 s.sSide[1], s.sSide[2] = 0, 0 copyResampler(chs[2].resampler_state, ch1.resampler_state) end st.nChannelsAPI = nAPI st.nChannelsInternal = nInt if ctrl.API_sampleRate > 48000 or ctrl.API_sampleRate < 8000 then return -200, 0 end if lostFlag ~= 1 and ch1.nFramesDecoded == 0 then for n = 1, nInt do local ch = chs[n] for i = 1, ch.nFramesPerPacket do ch.VAD_flags[i] = if bitLogp(d, 1) then 1 else 0 end ch.LBRR_flag = if bitLogp(d, 1) then 1 else 0 end for n = 1, nInt do local ch = chs[n] ch.LBRR_flags[1], ch.LBRR_flags[2], ch.LBRR_flags[3] = 0, 0, 0 if ch.LBRR_flag ~= 0 then if ch.nFramesPerPacket == 1 then ch.LBRR_flags[1] = 1 else local sym = icdf(d, LBRR_flags_iCDF[ch.nFramesPerPacket - 1], 1, 8) + 1 for i = 0, ch.nFramesPerPacket - 1 do ch.LBRR_flags[i + 1] = bit32.band(bit32.rshift(sym, i), 1) end end end end if lostFlag == 0 then -- skip all LBRR data for i = 0, ch1.nFramesPerPacket - 1 do for n = 1, nInt do local ch = chs[n] if ch.LBRR_flags[i + 1] ~= 0 then if nInt == 2 and n == 1 then stereoDecodePred(d, MS_pred_Q13) if chs[2].LBRR_flags[i + 1] == 0 then decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) end end local condCoding = if i > 0 and ch.LBRR_flags[i] ~= 0 then 2 else 0 decodeIndices(ch, d, i, true, condCoding) decodePulses(d, ch.pulses, ch.indices.signalType, ch.indices.quantOffsetType, ch.frame_length) end end end end end if nInt == 2 then local fd = ch1.nFramesDecoded if lostFlag == 0 or (lostFlag == 2 and ch1.LBRR_flags[fd + 1] == 1) then stereoDecodePred(d, MS_pred_Q13) if (lostFlag == 0 and chs[2].VAD_flags[fd + 1] == 0) or (lostFlag == 2 and chs[2].LBRR_flags[fd + 1] == 0) then decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) else decode_only_middle = 0 end else MS_pred_Q13[1] = st.sStereo.pred_prev_Q13[1] MS_pred_Q13[2] = st.sStereo.pred_prev_Q13[2] end end if nInt == 2 and decode_only_middle == 0 and st.prev_decode_only_middle == 1 then local c2 = chs[2] for i = 1, 480 do c2.outBuf[i] = 0 end for i = 1, 16 do c2.sLPC_Q14_buf[i] = 0 end c2.lagPrev = 100 c2.LastGainIndex = 10 c2.prevSignalType = 0 c2.first_frame_after_reset = 1 end local has_side if lostFlag == 0 then has_side = decode_only_middle == 0 else has_side = st.prev_decode_only_middle == 0 or (nInt == 2 and lostFlag == 2 and chs[2].LBRR_flags[chs[2].nFramesDecoded + 1] == 1) end local nSamplesOutDec = ch1.frame_length for n = 1, nInt do local ch = chs[n] if n == 1 or has_side then local FrameIndex = ch1.nFramesDecoded - (n - 1) local condCoding if FrameIndex <= 0 then condCoding = 0 elseif lostFlag == 2 then condCoding = if ch.LBRR_flags[FrameIndex] ~= 0 then 2 else 0 elseif n > 1 and st.prev_decode_only_middle ~= 0 then condCoding = 1 else condCoding = 2 end nSamplesOutDec = decodeFrame(ch, d, ch.out, 3, lostFlag, condCoding) else local o = ch.out for i = 3, nSamplesOutDec + 2 do o[i] = 0 end end ch.nFramesDecoded += 1 end local o1 = ch1.out if nAPI == 2 and nInt == 2 then stereoMSToLR(st.sStereo, o1, chs[2].out, MS_pred_Q13, ch1.fs_kHz, nSamplesOutDec) else local sMid = st.sStereo.sMid o1[1], o1[2], sMid[1], sMid[2] = sMid[1], sMid[2], o1[nSamplesOutDec + 1], o1[nSamplesOutDec + 2] end local nSamplesOut = (nSamplesOutDec * ctrl.API_sampleRate) // (ch1.fs_kHz * 1000) local ro = st.resampOut local scale = 1 / 32768 for n = 1, math.min(nAPI, nInt) do resampler(chs[n].resampler_state, ro, chs[n].out, 2, nSamplesOutDec) if nAPI == 2 then local b = outBase + n - 1 for i = 0, nSamplesOut - 1 do out[b + 2 * i] = ro[i + 1] * scale end else for i = 0, nSamplesOut - 1 do out[outBase + i] = ro[i + 1] * scale end end end if nAPI == 2 and nInt == 1 then if stereo_to_mono then resampler(chs[2].resampler_state, ro, o1, 2, nSamplesOutDec) for i = 0, nSamplesOut - 1 do out[outBase + 1 + 2 * i] = ro[i + 1] * scale end else for i = 0, nSamplesOut - 1 do out[outBase + 1 + 2 * i] = out[outBase + 2 * i] end end end if lostFlag == 1 then for i = 1, st.nChannelsInternal do chs[i].LastGainIndex = 10 end else st.prev_decode_only_middle = decode_only_middle end return ret, nSamplesOut end -- the pitch lag of the last frame at 48 kHz (decControl->prevPitchLag), 0 when unvoiced @native function Silk.prevPitchLag(st: State): number local ch = st.ch[1] if ch.prevSignalType == 2 then local mult = { 6, 4, 3 } return ch.lagPrev * mult[(ch.fs_kHz - 8) // 4 + 1] end return 0 end return Silk end __FILES["codecs/audio/Opus/SilkTables"] = function() -- codecs/audio/Opus/SilkTables: SILK decoder tables (generated from libopus silk/tables_*.c, pitch_est_tables.c, resampler_rom.c; BSD, see -- licenses/). Multi-dimensional C arrays are flattened row-major; every array is 1-based. local T = {} T.LTP_per_index_iCDF = { 179, 99, 0, } T.LTP_gain_iCDF_0 = { 71, 56, 43, 30, 21, 12, 6, 0, } T.LTP_gain_iCDF_1 = { 199, 165, 144, 124, 109, 96, 84, 71, 61, 51, 42, 32, 23, 15, 8, 0, } T.LTP_gain_iCDF_2 = { 241, 225, 211, 199, 187, 175, 164, 153, 142, 132, 123, 114, 105, 96, 88, 80, 72, 64, 57, 50, 44, 38, 33, 29, 24, 20, 16, 12, 9, 5, 2, 0, } T.LTP_gain_vq_0 = { 4, 6, 24, 7, 5, 0, 0, 2, 0, 0, 12, 28, 41, 13, -4, -9, 15, 42, 25, 14, 1, -2, 62, 41, -9, -10, 37, 65, -4, 3, -6, 4, 66, 7, -8, 16, 14, 38, -3, 33, } T.LTP_gain_vq_1 = { 13, 22, 39, 23, 12, -1, 36, 64, 27, -6, -7, 10, 55, 43, 17, 1, 1, 8, 1, 1, 6, -11, 74, 53, -9, -12, 55, 76, -12, 8, -3, 3, 93, 27, -4, 26, 39, 59, 3, -8, 2, 0, 77, 11, 9, -8, 22, 44, -6, 7, 40, 9, 26, 3, 9, -7, 20, 101, -7, 4, 3, -8, 42, 26, 0, -15, 33, 68, 2, 23, -2, 55, 46, -2, 15, 3, -1, 21, 16, 41, } T.LTP_gain_vq_2 = { -6, 27, 61, 39, 5, -11, 42, 88, 4, 1, -2, 60, 65, 6, -4, -1, -5, 73, 56, 1, -9, 19, 94, 29, -9, 0, 12, 99, 6, 4, 8, -19, 102, 46, -13, 3, 2, 13, 3, 2, 9, -21, 84, 72, -18, -11, 46, 104, -22, 8, 18, 38, 48, 23, 0, -16, 70, 83, -21, 11, 5, -11, 117, 22, -8, -6, 23, 117, -12, 3, 3, -8, 95, 28, 4, -10, 15, 77, 60, -15, -1, 4, 124, 2, -4, 3, 38, 84, 24, -25, 2, 13, 42, 13, 31, 21, -4, 56, 46, -1, -1, 35, 79, -13, 19, -7, 65, 88, -9, -14, 20, 4, 81, 49, -29, 20, 0, 75, 3, -17, 5, -9, 44, 92, -8, 1, -3, 22, 69, 31, -6, 95, 41, -12, 5, 39, 67, 16, -4, 1, 0, -6, 120, 55, -36, -13, 44, 122, 4, -24, 81, 5, 11, 3, 7, 2, 0, 9, 10, 88, } T.NLSF_CB1_WB_Q8 = { 7, 23, 38, 54, 69, 85, 100, 116, 131, 147, 162, 178, 193, 208, 223, 239, 13, 25, 41, 55, 69, 83, 98, 112, 127, 142, 157, 171, 187, 203, 220, 236, 15, 21, 34, 51, 61, 78, 92, 106, 126, 136, 152, 167, 185, 205, 225, 240, 10, 21, 36, 50, 63, 79, 95, 110, 126, 141, 157, 173, 189, 205, 221, 237, 17, 20, 37, 51, 59, 78, 89, 107, 123, 134, 150, 164, 184, 205, 224, 240, 10, 15, 32, 51, 67, 81, 96, 112, 129, 142, 158, 173, 189, 204, 220, 236, 8, 21, 37, 51, 65, 79, 98, 113, 126, 138, 155, 168, 179, 192, 209, 218, 12, 15, 34, 55, 63, 78, 87, 108, 118, 131, 148, 167, 185, 203, 219, 236, 16, 19, 32, 36, 56, 79, 91, 108, 118, 136, 154, 171, 186, 204, 220, 237, 11, 28, 43, 58, 74, 89, 105, 120, 135, 150, 165, 180, 196, 211, 226, 241, 6, 16, 33, 46, 60, 75, 92, 107, 123, 137, 156, 169, 185, 199, 214, 225, 11, 19, 30, 44, 57, 74, 89, 105, 121, 135, 152, 169, 186, 202, 218, 234, 12, 19, 29, 46, 57, 71, 88, 100, 120, 132, 148, 165, 182, 199, 216, 233, 17, 23, 35, 46, 56, 77, 92, 106, 123, 134, 152, 167, 185, 204, 222, 237, 14, 17, 45, 53, 63, 75, 89, 107, 115, 132, 151, 171, 188, 206, 221, 240, 9, 16, 29, 40, 56, 71, 88, 103, 119, 137, 154, 171, 189, 205, 222, 237, 16, 19, 36, 48, 57, 76, 87, 105, 118, 132, 150, 167, 185, 202, 218, 236, 12, 17, 29, 54, 71, 81, 94, 104, 126, 136, 149, 164, 182, 201, 221, 237, 15, 28, 47, 62, 79, 97, 115, 129, 142, 155, 168, 180, 194, 208, 223, 238, 8, 14, 30, 45, 62, 78, 94, 111, 127, 143, 159, 175, 192, 207, 223, 239, 17, 30, 49, 62, 79, 92, 107, 119, 132, 145, 160, 174, 190, 204, 220, 235, 14, 19, 36, 45, 61, 76, 91, 108, 121, 138, 154, 172, 189, 205, 222, 238, 12, 18, 31, 45, 60, 76, 91, 107, 123, 138, 154, 171, 187, 204, 221, 236, 13, 17, 31, 43, 53, 70, 83, 103, 114, 131, 149, 167, 185, 203, 220, 237, 17, 22, 35, 42, 58, 78, 93, 110, 125, 139, 155, 170, 188, 206, 224, 240, 8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239, 13, 16, 41, 66, 73, 86, 95, 111, 128, 137, 150, 163, 183, 206, 225, 241, 17, 25, 37, 52, 63, 75, 92, 102, 119, 132, 144, 160, 175, 191, 212, 231, 19, 31, 49, 65, 83, 100, 117, 133, 147, 161, 174, 187, 200, 213, 227, 242, 18, 31, 52, 68, 88, 103, 117, 126, 138, 149, 163, 177, 192, 207, 223, 239, 16, 29, 47, 61, 76, 90, 106, 119, 133, 147, 161, 176, 193, 209, 224, 240, 15, 21, 35, 50, 61, 73, 86, 97, 110, 119, 129, 141, 175, 198, 218, 237, } T.NLSF_CB1_WB_Wght_Q9 = { 3657, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2963, 2963, 2925, 2846, 3216, 3085, 2972, 3056, 3056, 3010, 3010, 3010, 2963, 2963, 3010, 2972, 2888, 2846, 2846, 2726, 3920, 4014, 2981, 3207, 3207, 2934, 3056, 2846, 3122, 3244, 2925, 2846, 2620, 2553, 2780, 2925, 3516, 3197, 3010, 3103, 3019, 2888, 2925, 2925, 2925, 2925, 2888, 2888, 2888, 2888, 2888, 2753, 5054, 5054, 2934, 3573, 3385, 3056, 3085, 2793, 3160, 3160, 2972, 2846, 2513, 2540, 2753, 2888, 4428, 4149, 2700, 2753, 2972, 3010, 2925, 2846, 2981, 3019, 2925, 2925, 2925, 2925, 2888, 2726, 3620, 3019, 2972, 3056, 3056, 2873, 2806, 3056, 3216, 3047, 2981, 3291, 3291, 2981, 3310, 2991, 5227, 5014, 2540, 3338, 3526, 3385, 3197, 3094, 3376, 2981, 2700, 2647, 2687, 2793, 2846, 2673, 5081, 5174, 4615, 4428, 2460, 2897, 3047, 3207, 3169, 2687, 2740, 2888, 2846, 2793, 2846, 2700, 3122, 2888, 2963, 2925, 2925, 2925, 2925, 2963, 2963, 2963, 2963, 2925, 2925, 2963, 2963, 2963, 4202, 3207, 2981, 3103, 3010, 2888, 2888, 2925, 2972, 2873, 2916, 3019, 2972, 3010, 3197, 2873, 3760, 3760, 3244, 3103, 2981, 2888, 2925, 2888, 2972, 2934, 2793, 2793, 2846, 2888, 2888, 2660, 3854, 4014, 3207, 3122, 3244, 2934, 3047, 2963, 2963, 3085, 2846, 2793, 2793, 2793, 2793, 2580, 3845, 4080, 3357, 3516, 3094, 2740, 3010, 2934, 3122, 3085, 2846, 2846, 2647, 2647, 2846, 2806, 5147, 4894, 3225, 3845, 3441, 3169, 2897, 3413, 3451, 2700, 2580, 2673, 2740, 2846, 2806, 2753, 4109, 3789, 3291, 3160, 2925, 2888, 2888, 2925, 2793, 2740, 2793, 2740, 2793, 2846, 2888, 2806, 5081, 5054, 3047, 3545, 3244, 3056, 3085, 2944, 3103, 2897, 2740, 2740, 2740, 2846, 2793, 2620, 4309, 4309, 2860, 2527, 3207, 3376, 3376, 3075, 3075, 3376, 3056, 2846, 2647, 2580, 2726, 2753, 3056, 2916, 2806, 2888, 2740, 2687, 2897, 3103, 3150, 3150, 3216, 3169, 3056, 3010, 2963, 2846, 4375, 3882, 2925, 2888, 2846, 2888, 2846, 2846, 2888, 2888, 2888, 2846, 2888, 2925, 2888, 2846, 2981, 2916, 2916, 2981, 2981, 3056, 3122, 3216, 3150, 3056, 3010, 2972, 2972, 2972, 2925, 2740, 4229, 4149, 3310, 3347, 2925, 2963, 2888, 2981, 2981, 2846, 2793, 2740, 2846, 2846, 2846, 2793, 4080, 4014, 3103, 3010, 2925, 2925, 2925, 2888, 2925, 2925, 2846, 2846, 2846, 2793, 2888, 2780, 4615, 4575, 3169, 3441, 3207, 2981, 2897, 3038, 3122, 2740, 2687, 2687, 2687, 2740, 2793, 2700, 4149, 4269, 3789, 3657, 2726, 2780, 2888, 2888, 3010, 2972, 2925, 2846, 2687, 2687, 2793, 2888, 4215, 3554, 2753, 2846, 2846, 2888, 2888, 2888, 2925, 2925, 2888, 2925, 2925, 2925, 2963, 2888, 5174, 4921, 2261, 3432, 3789, 3479, 3347, 2846, 3310, 3479, 3150, 2897, 2460, 2487, 2753, 2925, 3451, 3685, 3122, 3197, 3357, 3047, 3207, 3207, 2981, 3216, 3085, 2925, 2925, 2687, 2540, 2434, 2981, 3010, 2793, 2793, 2740, 2793, 2846, 2972, 3056, 3103, 3150, 3150, 3150, 3103, 3010, 3010, 2944, 2873, 2687, 2726, 2780, 3010, 3432, 3545, 3357, 3244, 3056, 3010, 2963, 2925, 2888, 2846, 3019, 2944, 2897, 3010, 3010, 2972, 3019, 3103, 3056, 3056, 3010, 2888, 2846, 2925, 2925, 2888, 3920, 3967, 3010, 3197, 3357, 3216, 3291, 3291, 3479, 3704, 3441, 2726, 2181, 2460, 2580, 2607, } T.NLSF_CB1_iCDF_WB = { 225, 204, 201, 184, 183, 175, 158, 154, 153, 135, 119, 115, 113, 110, 109, 99, 98, 95, 79, 68, 52, 50, 48, 45, 43, 32, 31, 27, 18, 10, 3, 0, 255, 251, 235, 230, 212, 201, 196, 182, 167, 166, 163, 151, 138, 124, 110, 104, 90, 78, 76, 70, 69, 57, 45, 34, 24, 21, 11, 6, 5, 4, 3, 0, } T.NLSF_CB2_SELECT_WB = { 0, 0, 0, 0, 0, 0, 0, 1, 100, 102, 102, 68, 68, 36, 34, 96, 164, 107, 158, 185, 180, 185, 139, 102, 64, 66, 36, 34, 34, 0, 1, 32, 208, 139, 141, 191, 152, 185, 155, 104, 96, 171, 104, 166, 102, 102, 102, 132, 1, 0, 0, 0, 0, 16, 16, 0, 80, 109, 78, 107, 185, 139, 103, 101, 208, 212, 141, 139, 173, 153, 123, 103, 36, 0, 0, 0, 0, 0, 0, 1, 48, 0, 0, 0, 0, 0, 0, 32, 68, 135, 123, 119, 119, 103, 69, 98, 68, 103, 120, 118, 118, 102, 71, 98, 134, 136, 157, 184, 182, 153, 139, 134, 208, 168, 248, 75, 189, 143, 121, 107, 32, 49, 34, 34, 34, 0, 17, 2, 210, 235, 139, 123, 185, 137, 105, 134, 98, 135, 104, 182, 100, 183, 171, 134, 100, 70, 68, 70, 66, 66, 34, 131, 64, 166, 102, 68, 36, 2, 1, 0, 134, 166, 102, 68, 34, 34, 66, 132, 212, 246, 158, 139, 107, 107, 87, 102, 100, 219, 125, 122, 137, 118, 103, 132, 114, 135, 137, 105, 171, 106, 50, 34, 164, 214, 141, 143, 185, 151, 121, 103, 192, 34, 0, 0, 0, 0, 0, 1, 208, 109, 74, 187, 134, 249, 159, 137, 102, 110, 154, 118, 87, 101, 119, 101, 0, 2, 0, 36, 36, 66, 68, 35, 96, 164, 102, 100, 36, 0, 2, 33, 167, 138, 174, 102, 100, 84, 2, 2, 100, 107, 120, 119, 36, 197, 24, 0, } T.NLSF_CB2_iCDF_WB = { 255, 254, 253, 244, 12, 3, 2, 1, 0, 255, 254, 252, 224, 38, 3, 2, 1, 0, 255, 254, 251, 209, 57, 4, 2, 1, 0, 255, 254, 244, 195, 69, 4, 2, 1, 0, 255, 251, 232, 184, 84, 7, 2, 1, 0, 255, 254, 240, 186, 86, 14, 2, 1, 0, 255, 254, 239, 178, 91, 30, 5, 1, 0, 255, 248, 227, 177, 100, 19, 2, 1, 0, } T.NLSF_PRED_WB_Q8 = { 175, 148, 160, 176, 178, 173, 174, 164, 177, 174, 196, 182, 198, 192, 182, 68, 62, 66, 60, 72, 117, 85, 90, 118, 136, 151, 142, 160, 142, 155, } T.NLSF_DELTA_MIN_WB_Q15 = { 100, 3, 40, 3, 3, 3, 5, 14, 14, 10, 11, 3, 8, 9, 7, 3, 347, } T.NLSF_CB1_NB_MB_Q8 = { 12, 35, 60, 83, 108, 132, 157, 180, 206, 228, 15, 32, 55, 77, 101, 125, 151, 175, 201, 225, 19, 42, 66, 89, 114, 137, 162, 184, 209, 230, 12, 25, 50, 72, 97, 120, 147, 172, 200, 223, 26, 44, 69, 90, 114, 135, 159, 180, 205, 225, 13, 22, 53, 80, 106, 130, 156, 180, 205, 228, 15, 25, 44, 64, 90, 115, 142, 168, 196, 222, 19, 24, 62, 82, 100, 120, 145, 168, 190, 214, 22, 31, 50, 79, 103, 120, 151, 170, 203, 227, 21, 29, 45, 65, 106, 124, 150, 171, 196, 224, 30, 49, 75, 97, 121, 142, 165, 186, 209, 229, 19, 25, 52, 70, 93, 116, 143, 166, 192, 219, 26, 34, 62, 75, 97, 118, 145, 167, 194, 217, 25, 33, 56, 70, 91, 113, 143, 165, 196, 223, 21, 34, 51, 72, 97, 117, 145, 171, 196, 222, 20, 29, 50, 67, 90, 117, 144, 168, 197, 221, 22, 31, 48, 66, 95, 117, 146, 168, 196, 222, 24, 33, 51, 77, 116, 134, 158, 180, 200, 224, 21, 28, 70, 87, 106, 124, 149, 170, 194, 217, 26, 33, 53, 64, 83, 117, 152, 173, 204, 225, 27, 34, 65, 95, 108, 129, 155, 174, 210, 225, 20, 26, 72, 99, 113, 131, 154, 176, 200, 219, 34, 43, 61, 78, 93, 114, 155, 177, 205, 229, 23, 29, 54, 97, 124, 138, 163, 179, 209, 229, 30, 38, 56, 89, 118, 129, 158, 178, 200, 231, 21, 29, 49, 63, 85, 111, 142, 163, 193, 222, 27, 48, 77, 103, 133, 158, 179, 196, 215, 232, 29, 47, 74, 99, 124, 151, 176, 198, 220, 237, 33, 42, 61, 76, 93, 121, 155, 174, 207, 225, 29, 53, 87, 112, 136, 154, 170, 188, 208, 227, 24, 30, 52, 84, 131, 150, 166, 186, 203, 229, 37, 48, 64, 84, 104, 118, 156, 177, 201, 230, } T.NLSF_CB1_Wght_Q9 = { 2897, 2314, 2314, 2314, 2287, 2287, 2314, 2300, 2327, 2287, 2888, 2580, 2394, 2367, 2314, 2274, 2274, 2274, 2274, 2194, 2487, 2340, 2340, 2314, 2314, 2314, 2340, 2340, 2367, 2354, 3216, 2766, 2340, 2340, 2314, 2274, 2221, 2207, 2261, 2194, 2460, 2474, 2367, 2394, 2394, 2394, 2394, 2367, 2407, 2314, 3479, 3056, 2127, 2207, 2274, 2274, 2274, 2287, 2314, 2261, 3282, 3141, 2580, 2394, 2247, 2221, 2207, 2194, 2194, 2114, 4096, 3845, 2221, 2620, 2620, 2407, 2314, 2394, 2367, 2074, 3178, 3244, 2367, 2221, 2553, 2434, 2340, 2314, 2167, 2221, 3338, 3488, 2726, 2194, 2261, 2460, 2354, 2367, 2207, 2101, 2354, 2420, 2327, 2367, 2394, 2420, 2420, 2420, 2460, 2367, 3779, 3629, 2434, 2527, 2367, 2274, 2274, 2300, 2207, 2048, 3254, 3225, 2713, 2846, 2447, 2327, 2300, 2300, 2274, 2127, 3263, 3300, 2753, 2806, 2447, 2261, 2261, 2247, 2127, 2101, 2873, 2981, 2633, 2367, 2407, 2354, 2194, 2247, 2247, 2114, 3225, 3197, 2633, 2580, 2274, 2181, 2247, 2221, 2221, 2141, 3178, 3310, 2740, 2407, 2274, 2274, 2274, 2287, 2194, 2114, 3141, 3272, 2460, 2061, 2287, 2500, 2367, 2487, 2434, 2181, 3507, 3282, 2314, 2700, 2647, 2474, 2367, 2394, 2340, 2127, 3423, 3535, 3038, 3056, 2300, 1950, 2221, 2274, 2274, 2274, 3404, 3366, 2087, 2687, 2873, 2354, 2420, 2274, 2474, 2540, 3760, 3488, 1950, 2660, 2897, 2527, 2394, 2367, 2460, 2261, 3028, 3272, 2740, 2888, 2740, 2154, 2127, 2287, 2234, 2247, 3695, 3657, 2025, 1969, 2660, 2700, 2580, 2500, 2327, 2367, 3207, 3413, 2354, 2074, 2888, 2888, 2340, 2487, 2247, 2167, 3338, 3366, 2846, 2780, 2327, 2154, 2274, 2287, 2114, 2061, 2327, 2300, 2181, 2167, 2181, 2367, 2633, 2700, 2700, 2553, 2407, 2434, 2221, 2261, 2221, 2221, 2340, 2420, 2607, 2700, 3038, 3244, 2806, 2888, 2474, 2074, 2300, 2314, 2354, 2380, 2221, 2154, 2127, 2287, 2500, 2793, 2793, 2620, 2580, 2367, 3676, 3713, 2234, 1838, 2181, 2753, 2726, 2673, 2513, 2207, 2793, 3160, 2726, 2553, 2846, 2513, 2181, 2394, 2221, 2181, } T.NLSF_CB1_iCDF_NB_MB = { 212, 178, 148, 129, 108, 96, 85, 82, 79, 77, 61, 59, 57, 56, 51, 49, 48, 45, 42, 41, 40, 38, 36, 34, 31, 30, 21, 12, 10, 3, 1, 0, 255, 245, 244, 236, 233, 225, 217, 203, 190, 176, 175, 161, 149, 136, 125, 114, 102, 91, 81, 71, 60, 52, 43, 35, 28, 20, 19, 18, 12, 11, 5, 0, } T.NLSF_CB2_SELECT_NB_MB = { 16, 0, 0, 0, 0, 99, 66, 36, 36, 34, 36, 34, 34, 34, 34, 83, 69, 36, 52, 34, 116, 102, 70, 68, 68, 176, 102, 68, 68, 34, 65, 85, 68, 84, 36, 116, 141, 152, 139, 170, 132, 187, 184, 216, 137, 132, 249, 168, 185, 139, 104, 102, 100, 68, 68, 178, 218, 185, 185, 170, 244, 216, 187, 187, 170, 244, 187, 187, 219, 138, 103, 155, 184, 185, 137, 116, 183, 155, 152, 136, 132, 217, 184, 184, 170, 164, 217, 171, 155, 139, 244, 169, 184, 185, 170, 164, 216, 223, 218, 138, 214, 143, 188, 218, 168, 244, 141, 136, 155, 170, 168, 138, 220, 219, 139, 164, 219, 202, 216, 137, 168, 186, 246, 185, 139, 116, 185, 219, 185, 138, 100, 100, 134, 100, 102, 34, 68, 68, 100, 68, 168, 203, 221, 218, 168, 167, 154, 136, 104, 70, 164, 246, 171, 137, 139, 137, 155, 218, 219, 139, } T.NLSF_CB2_iCDF_NB_MB = { 255, 254, 253, 238, 14, 3, 2, 1, 0, 255, 254, 252, 218, 35, 3, 2, 1, 0, 255, 254, 250, 208, 59, 4, 2, 1, 0, 255, 254, 246, 194, 71, 10, 2, 1, 0, 255, 252, 236, 183, 82, 8, 2, 1, 0, 255, 252, 235, 180, 90, 17, 2, 1, 0, 255, 248, 224, 171, 97, 30, 4, 1, 0, 255, 254, 236, 173, 95, 37, 7, 1, 0, } T.NLSF_PRED_NB_MB_Q8 = { 179, 138, 140, 148, 151, 149, 153, 151, 163, 116, 67, 82, 59, 92, 72, 100, 89, 92, } T.NLSF_DELTA_MIN_NB_MB_Q15 = { 250, 3, 6, 3, 3, 3, 4, 3, 3, 3, 461, } T.pitch_lag_iCDF = { 253, 250, 244, 233, 212, 182, 150, 131, 120, 110, 98, 85, 72, 60, 49, 40, 32, 25, 19, 15, 13, 11, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, } T.pitch_delta_iCDF = { 210, 208, 206, 203, 199, 193, 183, 168, 142, 104, 74, 52, 37, 27, 20, 14, 10, 6, 4, 2, 0, } T.pitch_contour_iCDF = { 223, 201, 183, 167, 152, 138, 124, 111, 98, 88, 79, 70, 62, 56, 50, 44, 39, 35, 31, 27, 24, 21, 18, 16, 14, 12, 10, 8, 6, 4, 3, 2, 1, 0, } T.pitch_contour_NB_iCDF = { 188, 176, 155, 138, 119, 97, 67, 43, 26, 10, 0, } T.pitch_contour_10_ms_iCDF = { 165, 119, 80, 61, 47, 35, 27, 20, 14, 9, 4, 0, } T.pitch_contour_10_ms_NB_iCDF = { 113, 63, 0, } T.stereo_pred_quant_Q13 = { -13732, -10050, -8266, -7526, -6500, -5000, -2950, -820, 820, 2950, 5000, 6500, 7526, 8266, 10050, 13732, } T.stereo_pred_joint_iCDF = { 249, 247, 246, 245, 244, 234, 210, 202, 201, 200, 197, 174, 82, 59, 56, 55, 54, 46, 22, 12, 11, 10, 9, 7, 0, } T.stereo_only_code_mid_iCDF = { 64, 0, } T.LBRR_flags_2_iCDF = { 203, 150, 0, } T.LBRR_flags_3_iCDF = { 215, 195, 166, 125, 110, 82, 0, } T.lsb_iCDF = { 120, 0, } T.LTPscale_iCDF = { 128, 64, 0, } T.type_offset_VAD_iCDF = { 232, 158, 10, 0, } T.type_offset_no_VAD_iCDF = { 230, 0, } T.NLSF_interpolation_factor_iCDF = { 243, 221, 192, 181, 0, } T.LTPScales_table_Q14 = { 15565, 12288, 8192, } T.uniform3_iCDF = { 171, 85, 0, } T.uniform4_iCDF = { 192, 128, 64, 0, } T.uniform5_iCDF = { 205, 154, 102, 51, 0, } T.uniform6_iCDF = { 213, 171, 128, 85, 43, 0, } T.uniform8_iCDF = { 224, 192, 160, 128, 96, 64, 32, 0, } T.NLSF_EXT_iCDF = { 100, 40, 16, 7, 3, 1, 0, } T.gain_iCDF = { 224, 112, 44, 15, 3, 2, 1, 0, 254, 237, 192, 132, 70, 23, 4, 0, 255, 252, 226, 155, 61, 11, 2, 0, } T.delta_gain_iCDF = { 250, 245, 234, 203, 71, 50, 42, 38, 35, 33, 31, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, } T.LSFCosTab_FIX_Q12 = { 8192, 8190, 8182, 8170, 8152, 8130, 8104, 8072, 8034, 7994, 7946, 7896, 7840, 7778, 7714, 7644, 7568, 7490, 7406, 7318, 7226, 7128, 7026, 6922, 6812, 6698, 6580, 6458, 6332, 6204, 6070, 5934, 5792, 5648, 5502, 5352, 5198, 5040, 4880, 4718, 4552, 4382, 4212, 4038, 3862, 3684, 3502, 3320, 3136, 2948, 2760, 2570, 2378, 2186, 1990, 1794, 1598, 1400, 1202, 1002, 802, 602, 402, 202, 0, -202, -402, -602, -802, -1002, -1202, -1400, -1598, -1794, -1990, -2186, -2378, -2570, -2760, -2948, -3136, -3320, -3502, -3684, -3862, -4038, -4212, -4382, -4552, -4718, -4880, -5040, -5198, -5352, -5502, -5648, -5792, -5934, -6070, -6204, -6332, -6458, -6580, -6698, -6812, -6922, -7026, -7128, -7226, -7318, -7406, -7490, -7568, -7644, -7714, -7778, -7840, -7896, -7946, -7994, -8034, -8072, -8104, -8130, -8152, -8170, -8182, -8190, -8192, } T.pulses_per_block_iCDF = { 125, 51, 26, 18, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 198, 105, 45, 22, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 213, 162, 116, 83, 59, 43, 32, 24, 18, 15, 12, 9, 7, 6, 5, 3, 2, 0, 239, 187, 116, 59, 28, 16, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 250, 229, 188, 135, 86, 51, 30, 19, 13, 10, 8, 6, 5, 4, 3, 2, 1, 0, 249, 235, 213, 185, 156, 128, 103, 83, 66, 53, 42, 33, 26, 21, 17, 13, 10, 0, 254, 249, 235, 206, 164, 118, 77, 46, 27, 16, 10, 7, 5, 4, 3, 2, 1, 0, 255, 253, 249, 239, 220, 191, 156, 119, 85, 57, 37, 23, 15, 10, 6, 4, 2, 0, 255, 253, 251, 246, 237, 223, 203, 179, 152, 124, 98, 75, 55, 40, 29, 21, 15, 0, 255, 254, 253, 247, 220, 162, 106, 67, 42, 28, 18, 12, 9, 6, 4, 3, 2, 0, } T.rate_levels_iCDF = { 241, 190, 178, 132, 87, 74, 41, 14, 0, 223, 193, 157, 140, 106, 57, 39, 18, 0, } T.shell_code_table0 = { 128, 0, 214, 42, 0, 235, 128, 21, 0, 244, 184, 72, 11, 0, 248, 214, 128, 42, 7, 0, 248, 225, 170, 80, 25, 5, 0, 251, 236, 198, 126, 54, 18, 3, 0, 250, 238, 211, 159, 82, 35, 15, 5, 0, 250, 231, 203, 168, 128, 88, 53, 25, 6, 0, 252, 238, 216, 185, 148, 108, 71, 40, 18, 4, 0, 253, 243, 225, 199, 166, 128, 90, 57, 31, 13, 3, 0, 254, 246, 233, 212, 183, 147, 109, 73, 44, 23, 10, 2, 0, 255, 250, 240, 223, 198, 166, 128, 90, 58, 33, 16, 6, 1, 0, 255, 251, 244, 231, 210, 181, 146, 110, 75, 46, 25, 12, 5, 1, 0, 255, 253, 248, 238, 221, 196, 164, 128, 92, 60, 35, 18, 8, 3, 1, 0, 255, 253, 249, 242, 229, 208, 180, 146, 110, 76, 48, 27, 14, 7, 3, 1, 0, } T.shell_code_table1 = { 129, 0, 207, 50, 0, 236, 129, 20, 0, 245, 185, 72, 10, 0, 249, 213, 129, 42, 6, 0, 250, 226, 169, 87, 27, 4, 0, 251, 233, 194, 130, 62, 20, 4, 0, 250, 236, 207, 160, 99, 47, 17, 3, 0, 255, 240, 217, 182, 131, 81, 41, 11, 1, 0, 255, 254, 233, 201, 159, 107, 61, 20, 2, 1, 0, 255, 249, 233, 206, 170, 128, 86, 50, 23, 7, 1, 0, 255, 250, 238, 217, 186, 148, 108, 70, 39, 18, 6, 1, 0, 255, 252, 243, 226, 200, 166, 128, 90, 56, 30, 13, 4, 1, 0, 255, 252, 245, 231, 209, 180, 146, 110, 76, 47, 25, 11, 4, 1, 0, 255, 253, 248, 237, 219, 194, 163, 128, 93, 62, 37, 19, 8, 3, 1, 0, 255, 254, 250, 241, 226, 205, 177, 145, 111, 79, 51, 30, 15, 6, 2, 1, 0, } T.shell_code_table2 = { 129, 0, 203, 54, 0, 234, 129, 23, 0, 245, 184, 73, 10, 0, 250, 215, 129, 41, 5, 0, 252, 232, 173, 86, 24, 3, 0, 253, 240, 200, 129, 56, 15, 2, 0, 253, 244, 217, 164, 94, 38, 10, 1, 0, 253, 245, 226, 189, 132, 71, 27, 7, 1, 0, 253, 246, 231, 203, 159, 105, 56, 23, 6, 1, 0, 255, 248, 235, 213, 179, 133, 85, 47, 19, 5, 1, 0, 255, 254, 243, 221, 194, 159, 117, 70, 37, 12, 2, 1, 0, 255, 254, 248, 234, 208, 171, 128, 85, 48, 22, 8, 2, 1, 0, 255, 254, 250, 240, 220, 189, 149, 107, 67, 36, 16, 6, 2, 1, 0, 255, 254, 251, 243, 227, 201, 166, 128, 90, 55, 29, 13, 5, 2, 1, 0, 255, 254, 252, 246, 234, 213, 183, 147, 109, 73, 43, 22, 10, 4, 2, 1, 0, } T.shell_code_table3 = { 130, 0, 200, 58, 0, 231, 130, 26, 0, 244, 184, 76, 12, 0, 249, 214, 130, 43, 6, 0, 252, 232, 173, 87, 24, 3, 0, 253, 241, 203, 131, 56, 14, 2, 0, 254, 246, 221, 167, 94, 35, 8, 1, 0, 254, 249, 232, 193, 130, 65, 23, 5, 1, 0, 255, 251, 239, 211, 162, 99, 45, 15, 4, 1, 0, 255, 251, 243, 223, 186, 131, 74, 33, 11, 3, 1, 0, 255, 252, 245, 230, 202, 158, 105, 57, 24, 8, 2, 1, 0, 255, 253, 247, 235, 214, 179, 132, 84, 44, 19, 7, 2, 1, 0, 255, 254, 250, 240, 223, 196, 159, 112, 69, 36, 15, 6, 2, 1, 0, 255, 254, 253, 245, 231, 209, 176, 136, 93, 55, 27, 11, 3, 2, 1, 0, 255, 254, 253, 252, 239, 221, 194, 158, 117, 76, 42, 18, 4, 3, 2, 1, 0, } T.shell_code_table_offsets = { 0, 0, 2, 5, 9, 14, 20, 27, 35, 44, 54, 65, 77, 90, 104, 119, 135, } T.sign_iCDF = { 254, 49, 67, 77, 82, 93, 99, 198, 11, 18, 24, 31, 36, 45, 255, 46, 66, 78, 87, 94, 104, 208, 14, 21, 32, 42, 51, 66, 255, 94, 104, 109, 112, 115, 118, 248, 53, 69, 80, 88, 95, 102, } T.CB_lags_stage2_10_ms = { 0, 1, 0, 0, 0, 1, } T.CB_lags_stage3_10_ms = { 0, 0, 1, -1, 1, -1, 2, -2, 2, -2, 3, -3, 0, 1, 0, 1, -1, 2, -1, 2, -2, 3, -2, 3, } T.CB_lags_stage2 = { 0, 2, -1, -1, -1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 2, 1, 0, 1, 1, 0, 0, -1, -1, } T.CB_lags_stage3 = { 0, 0, 1, -1, 0, 1, -1, 0, -1, 1, -2, 2, -2, -2, 2, -3, 2, 3, -3, -4, 3, -4, 4, 4, -5, 5, -6, -5, 6, -7, 6, 5, 8, -9, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0, 1, -1, -1, 1, -1, 2, 1, -1, 2, -2, -2, 2, -2, 2, 2, 3, -3, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, -1, 1, 0, 0, 2, 1, -1, 2, -1, -1, 2, -1, 2, 2, -1, 3, -2, -2, -2, 3, 0, 1, 0, 0, 1, 0, 1, -1, 2, -1, 2, -1, 2, 3, -2, 3, -2, -2, 4, 4, -3, 5, -3, -4, 6, -4, 6, 5, -5, 8, -6, -5, -7, 9, } T.resampler_frac_FIR_12 = { 189, -600, 617, 30567, 117, -159, -1070, 29704, 52, 221, -2392, 28276, -4, 529, -3350, 26341, -48, 758, -3956, 23973, -80, 905, -4235, 21254, -99, 972, -4222, 18278, -107, 967, -3957, 15143, -103, 896, -3487, 11950, -91, 773, -2865, 8798, -71, 611, -2143, 5784, -46, 425, -1375, 2996, } return T end __FILES["codecs/audio/Pcm"] = function() -- codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Convert = __include("codecs/audio/Pcm/Convert") local Pcm = {} Pcm.Convert = Convert -- Channel order. Decoders return WAVE (WAVEFORMATEXTENSIBLE) order: FL FR C LFE BL BR (SL SR) ..., as FLAC, WAV and -- AAC store it. Vorbis and Opus (mapping family 1) store the Vorbis order (FL C FR ... LFE last); WAVE_FROM_VORBIS[n][i] -- is the Vorbis-order channel (1-based) that WAVE-order channel i holds, for n = 1 .. 8 channels. Pcm.WAVE_FROM_VORBIS = { { 1 }, { 1, 2 }, { 1, 3, 2 }, -- L C R -> L R C { 1, 2, 3, 4 }, -- FL FR RL RR { 1, 3, 2, 4, 5 }, -- FL C FR RL RR -> FL FR C RL RR { 1, 3, 2, 6, 4, 5 }, -- FL C FR RL RR LFE -> FL FR C LFE RL RR { 1, 3, 2, 7, 6, 4, 5 }, -- FL C FR SL SR RC LFE -> FL FR C LFE RC SL SR { 1, 3, 2, 8, 6, 7, 4, 5 }, -- FL C FR SL SR RL RR LFE -> FL FR C LFE RL RR SL SR } type Source = { sampleRate: number, channels: number, frames: number, tags: Types.Tags, read: (self: Source, n: number, out: buffer?) -> (buffer, number), err: Err.Err?, } local function audioRead(self: any, n: number, out: buffer?): (buffer, number) local a = self._audio local ch = a.channels local left = a.frames - self._pos if n > left then n = left end if n <= 0 then return out or buffer.create(0), 0 end local bytes = n * ch * 4 local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes) buffer.copy(b, 0, a.samples, self._pos * ch * 4, bytes) self._pos += n return b, n end local function decoderRead(self: any, n: number, out: buffer?): (buffer, number) if self._done then return out or buffer.create(0), 0 end local ok, b, got = pcall(self._dec.read, self._dec, n, out) if not ok then self._done = true self.err = Err.new(Err.CORRUPT, "source decoder failed: " .. tostring(b)) return out or buffer.create(0), 0 end if type(b) ~= "buffer" or type(got) ~= "number" or got <= 0 then self._done = true return out or buffer.create(0), 0 end local ch = self.channels if buffer.len(b) < got * ch * 4 then got = buffer.len(b) // (ch * 4) end return b, got end function Pcm.source(v: any): (Source?, Err.Err?) if type(v) ~= "table" then return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") end local sr, ch = v.sampleRate, v.channels if type(sr) ~= "number" or sr <= 0 or sr ~= sr or type(ch) ~= "number" or ch < 1 or ch ~= math.floor(ch) then return nil, Err.new(Err.ARG, "bad sampleRate or channels") end if v.kind == "audio" and type(v.samples) == "buffer" then local frames = v.frames if type(frames) ~= "number" or frames < 0 or buffer.len(v.samples) < frames * ch * 4 then return nil, Err.new(Err.ARG, "the Audio's samples buffer is shorter than frames * channels * 4") end return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = audioRead, _audio = v, _pos = 0 } :: any, nil end if type(v.read) == "function" then local frames = if type(v.frames) == "number" and v.frames > 0 then v.frames else 0 return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = decoderRead, _dec = v, _done = false } :: any, nil end return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") end function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) local ch = src.channels local cap = math.max(src.frames, 4096) local data = buffer.create(cap * ch * 4) local total = 0 local limit = maxFrames or 2 ^ 31 local tmp: buffer? = nil if src.frames > 0 and src.frames <= limit then local b, n = src:read(src.frames, data) if n > 0 then if b ~= data then buffer.copy(data, 0, b, 0, math.min(n, cap) * ch * 4) end total = math.min(n, cap) end end while true do local b, n = src:read(16384, tmp) if n <= 0 then break end tmp = b if total + n > limit then return nil, Err.new(Err.LIMIT, string.format("more than %d frames", limit)) end if total + n > cap then cap = math.max(cap * 2, total + n) local nd = buffer.create(cap * ch * 4) buffer.copy(nd, 0, data, 0, total * ch * 4) data = nd end buffer.copy(data, total * ch * 4, b, 0, n * ch * 4) total += n end if src.err then return nil, src.err end local a = Types.Audio.new(src.sampleRate, ch, 0) a.frames = total if buffer.len(data) == total * ch * 4 then a.samples = data else a.samples = buffer.create(total * ch * 4) buffer.copy(a.samples, 0, data, 0, total * ch * 4) end a.tags = table.clone(src.tags) return a, nil end function Pcm.drain(dec: any, source: { [string]: any }?, maxFrames: number?): (Types.Audio?, Err.Err?) local src, err = Pcm.source(dec) if not src then return nil, err end local a, cerr = Pcm.collect(src, maxFrames) if not a then return nil, cerr end if Err.is(dec.error) then return nil, dec.error end a.tags = dec.tags or {} a.meta.source = source or dec.source return a, nil end function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: number, sampleRate: number, fmt: string, tags: Types.Tags?): (Types.Decoder?, Err.Err?) local size = Convert.SIZE[fmt] if not size then return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) end if channels < 1 or sampleRate <= 0 or frames < 0 or offset < 0 or offset + frames * channels * size > buffer.len(buf) then return nil, Err.new(Err.ARG, "bad raw PCM layout") end local pos = 0 local frameBytes = channels * size local dec = { sampleRate = sampleRate, channels = channels, frames = frames, duration = frames / sampleRate, bitrate = sampleRate * frameBytes * 8, tags = tags or {}, } function dec.read(_self: any, n: number, out: buffer?): (buffer, number) n = math.clamp(math.floor(n), 0, frames - pos) local bytes = n * channels * 4 local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes) if n > 0 then Convert.decode(buf, offset + pos * frameBytes, fmt, n * channels, b, 0) pos += n end return b, n end function dec.seek(_self: any, seconds: number) local f = math.floor(seconds * sampleRate + 0.5) pos = if f ~= f then 0 else math.clamp(f, 0, frames) end function dec.position(_self: any): number return pos / sampleRate end return dec :: any, nil end function Pcm.audioDecoder(a: Types.Audio): Types.Decoder local d = Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) :: any d.bitrate = a.sampleRate * a.channels * 32 return d end function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Err?) local size = Convert.SIZE[fmt] if not size then return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) end local ch = src.channels local total = 0 local tmp: buffer? = nil while true do local b, n = src:read(8192, tmp) if n <= 0 then break end tmp = b local at = w:reserve(n * ch * size) Convert.encode(b, 0, n * ch, fmt, w.buf, at) w.pos = at + n * ch * size total += n end if src.err then return nil, src.err end return total, nil end function Pcm.reorder(buf: buffer, offset: number, frames: number, channels: number, map: { number }) local tmp = table.create(channels, 0) local readf32, writef32 = buffer.readf32, buffer.writef32 for f = 0, frames - 1 do local p = offset + f * channels * 4 for c = 1, channels do tmp[c] = readf32(buf, p + (map[c] - 1) * 4) end for c = 1, channels do writef32(buf, p + (c - 1) * 4, tmp[c]) end end end function Pcm.toInt(x: number, bits: number): number local s = 2 ^ (bits - 1) local v = math.floor(x * s + 0.5) if v ~= v then return 0 end if v >= s then return s - 1 elseif v < -s then return -s end return v end function Pcm.fromInt(v: number, bits: number): number return v / 2 ^ (bits - 1) end return Pcm end __FILES["codecs/audio/Pcm/Convert"] = @native function() -- codecs/audio/Pcm/Convert: raw sample formats <-> interleaved f32. -- Integers map to v / 2^(bits-1) (as ffmpeg does). G.711 A-law / mu-law per ITU-T G.711 (the classic Sun g711.c -- algorithm, written from the spec). local Convert = {} local readu8, readi8, readi16, readi32, readu32 = buffer.readu8, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readu32 local readf32, readf64, writef32, writef64 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writef64 local writeu8, writeu16, writeu32, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei16, buffer.writei32 local floor = math.floor local byteswap = bit32.byteswap local SIZE: { [string]: number } = { u8 = 1, s8 = 1, s16le = 2, s16be = 2, s24le = 3, s24be = 3, s32le = 4, s32be = 4, f32le = 4, f32be = 4, f64le = 8, f64be = 8, alaw = 1, ulaw = 1, } Convert.SIZE = SIZE Convert.BITS = { u8 = 8, s8 = 8, s16le = 16, s16be = 16, s24le = 24, s24be = 24, s32le = 32, s32be = 32, f32le = 32, f32be = 32, f64le = 64, f64be = 64, alaw = 16, ulaw = 16, } local ALAW = table.create(256, 0) local ULAW = table.create(256, 0) for code = 0, 255 do local a = bit32.bxor(code, 0x55) local t = bit32.band(a, 0x0F) * 16 local seg = bit32.rshift(bit32.band(a, 0x70), 4) if seg == 0 then t += 8 elseif seg == 1 then t += 0x108 else t = (t + 0x108) * 2 ^ (seg - 1) end ALAW[code + 1] = if bit32.band(a, 0x80) ~= 0 then t else -t local u = bit32.bxor(code, 0xFF) local m = (bit32.band(u, 0x0F) * 8 + 0x84) * 2 ^ bit32.rshift(bit32.band(u, 0x70), 4) ULAW[code + 1] = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84 end local SEG_AEND = { 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF } local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF } @native local function segment(v: number, ends: { number }): number for i = 1, 8 do if v <= ends[i] then return i - 1 end end return 8 end @native local function alawEncode(pcm: number): number local mask local v = floor(pcm / 8) -- 13-bit magnitude domain if v >= 0 then mask = 0xD5 else mask = 0x55 v = -v - 1 end local seg = segment(v, SEG_AEND) local aval if seg >= 8 then aval = 0x7F else aval = seg * 16 if seg < 2 then aval += bit32.band(floor(v / 2), 0x0F) else aval += bit32.band(floor(v / 2 ^ seg), 0x0F) end end return bit32.bxor(aval, mask) end @native local function ulawEncode(pcm: number): number local v = floor(pcm / 4) -- 14-bit local mask if v < 0 then v = -v mask = 0x7F else mask = 0xFF end if v > 8159 then v = 8159 end v += 0x21 local seg = segment(v, SEG_UEND) local uval if seg >= 8 then uval = 0x7F else uval = seg * 16 + bit32.band(floor(v / 2 ^ (seg + 1)), 0x0F) end return bit32.bxor(uval, mask) end Convert.alawEncode = alawEncode Convert.ulawEncode = ulawEncode Convert.ALAW = ALAW Convert.ULAW = ULAW @native function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst: buffer, d: number): boolean if fmt == "s16le" then for i = 0, count - 1 do writef32(dst, d + i * 4, readi16(src, so + i * 2) / 32768) end elseif fmt == "s16be" then for i = 0, count - 1 do local p = so + i * 2 local v = readu8(src, p) * 256 + readu8(src, p + 1) if v >= 32768 then v -= 65536 end writef32(dst, d + i * 4, v / 32768) end elseif fmt == "u8" then for i = 0, count - 1 do writef32(dst, d + i * 4, (readu8(src, so + i) - 128) / 128) end elseif fmt == "s8" then for i = 0, count - 1 do writef32(dst, d + i * 4, readi8(src, so + i) / 128) end elseif fmt == "s24le" then for i = 0, count - 1 do local p = so + i * 3 local v = readu8(src, p) + readu8(src, p + 1) * 256 + readi8(src, p + 2) * 65536 writef32(dst, d + i * 4, v / 8388608) end elseif fmt == "s24be" then for i = 0, count - 1 do local p = so + i * 3 local v = readi8(src, p) * 65536 + readu8(src, p + 1) * 256 + readu8(src, p + 2) writef32(dst, d + i * 4, v / 8388608) end elseif fmt == "s32le" then for i = 0, count - 1 do writef32(dst, d + i * 4, readi32(src, so + i * 4) / 2147483648) end elseif fmt == "s32be" then for i = 0, count - 1 do local v = byteswap(readu32(src, so + i * 4)) if v >= 2147483648 then v -= 4294967296 end writef32(dst, d + i * 4, v / 2147483648) end elseif fmt == "f32le" then buffer.copy(dst, d, src, so, count * 4) elseif fmt == "f32be" then for i = 0, count - 1 do writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) end elseif fmt == "f64le" then for i = 0, count - 1 do writef32(dst, d + i * 4, readf64(src, so + i * 8)) end elseif fmt == "f64be" then local tmp = buffer.create(8) for i = 0, count - 1 do local p = so + i * 8 writeu32(tmp, 0, byteswap(readu32(src, p + 4))) writeu32(tmp, 4, byteswap(readu32(src, p))) writef32(dst, d + i * 4, readf64(tmp, 0)) end elseif fmt == "alaw" then for i = 0, count - 1 do writef32(dst, d + i * 4, ALAW[readu8(src, so + i) + 1] / 32768) end elseif fmt == "ulaw" then for i = 0, count - 1 do writef32(dst, d + i * 4, ULAW[readu8(src, so + i) + 1] / 32768) end else return false end return true end @native local function q(x: number, s: number): number local v = floor(x * s + 0.5) if v ~= v then return 0 end if v >= s then return s - 1 elseif v < -s then return -s end return v end @native function Convert.encode(src: buffer, so: number, count: number, fmt: string, dst: buffer, d: number): boolean if fmt == "s16le" then for i = 0, count - 1 do writei16(dst, d + i * 2, q(readf32(src, so + i * 4), 32768)) end elseif fmt == "s16be" then for i = 0, count - 1 do local v = q(readf32(src, so + i * 4), 32768) % 65536 writeu16(dst, d + i * 2, (v % 256) * 256 + v // 256) end elseif fmt == "u8" then for i = 0, count - 1 do writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) + 128) end elseif fmt == "s8" then for i = 0, count - 1 do writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) % 256) end elseif fmt == "s24le" then for i = 0, count - 1 do local v = q(readf32(src, so + i * 4), 8388608) % 16777216 local p = d + i * 3 writeu8(dst, p, v % 256) writeu8(dst, p + 1, (v // 256) % 256) writeu8(dst, p + 2, v // 65536) end elseif fmt == "s24be" then for i = 0, count - 1 do local v = q(readf32(src, so + i * 4), 8388608) % 16777216 local p = d + i * 3 writeu8(dst, p, v // 65536) writeu8(dst, p + 1, (v // 256) % 256) writeu8(dst, p + 2, v % 256) end elseif fmt == "s32le" then for i = 0, count - 1 do writei32(dst, d + i * 4, q(readf32(src, so + i * 4), 2147483648)) end elseif fmt == "s32be" then for i = 0, count - 1 do writeu32(dst, d + i * 4, byteswap(q(readf32(src, so + i * 4), 2147483648) % 4294967296)) end elseif fmt == "f32le" then buffer.copy(dst, d, src, so, count * 4) elseif fmt == "f32be" then for i = 0, count - 1 do writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) end elseif fmt == "f64le" then for i = 0, count - 1 do writef64(dst, d + i * 8, readf32(src, so + i * 4)) end elseif fmt == "f64be" then local tmp = buffer.create(8) for i = 0, count - 1 do writef64(tmp, 0, readf32(src, so + i * 4)) local p = d + i * 8 writeu32(dst, p, byteswap(readu32(tmp, 4))) writeu32(dst, p + 4, byteswap(readu32(tmp, 0))) end elseif fmt == "alaw" then for i = 0, count - 1 do writeu8(dst, d + i, alawEncode(q(readf32(src, so + i * 4), 32768))) end elseif fmt == "ulaw" then for i = 0, count - 1 do writeu8(dst, d + i, ulawEncode(q(readf32(src, so + i * 4), 32768))) end else return false end return true end return Convert end __FILES["codecs/audio/Qoa"] = @native function() -- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA). -- Ported from qoa.h (phoboslab/qoa, Dominic Szablewski, MIT: licenses/qoa-LICENSE.txt); encoding is byte-for-byte -- qoa.h's, including its 32-bit wrap in the reciprocal division. local readu8, readu32, readf32, writef32, writeu32 = buffer.readu8, buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 local readi32, writei32 = buffer.readi32, buffer.writei32 local band, rshift, bor, lshift, byteswap = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.byteswap local floor = math.floor local Qoa = {} Qoa.SLICE_LEN = 20 Qoa.SLICES_PER_FRAME = 256 Qoa.FRAME_LEN = 256 * 20 Qoa.MAX_CHANNELS = 255 local QUANT = { 7, 7, 7, 5, 5, 3, 3, 1, 0, 0, 2, 2, 4, 4, 6, 6, 6 } -- residual -8 .. 8 -> code local RECIP = { 65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32 } -- DEQ[sf * 8 + q + 1] local DEQ = { 1, -1, 3, -3, 5, -5, 7, -7, 5, -5, 18, -18, 32, -32, 49, -49, 16, -16, 53, -53, 95, -95, 147, -147, 34, -34, 113, -113, 203, -203, 315, -315, 63, -63, 210, -210, 378, -378, 588, -588, 104, -104, 345, -345, 621, -621, 966, -966, 158, -158, 528, -528, 950, -950, 1477, -1477, 228, -228, 760, -760, 1368, -1368, 2128, -2128, 316, -316, 1053, -1053, 1895, -1895, 2947, -2947, 422, -422, 1405, -1405, 2529, -2529, 3934, -3934, 548, -548, 1828, -1828, 3290, -3290, 5117, -5117, 696, -696, 2320, -2320, 4176, -4176, 6496, -6496, 868, -868, 2893, -2893, 5207, -5207, 8099, -8099, 1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933, 1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005, 1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336, } @native local function be32(b: buffer, p: number): number return byteswap(readu32(b, p)) end @native local function s16(v: number): number return if v >= 32768 then v - 65536 else v end @native function Qoa.frameSize(ch: number, slices: number): number return 8 + 16 * ch + 8 * slices * ch end type FrameInfo = { channels: number, rate: number, samples: number, size: number } @native function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string?) if avail < 8 then return nil, "truncated frame header" end local hi, lo = be32(b, p), be32(b, p + 4) local ch = rshift(hi, 24) local rate = band(hi, 0xFFFFFF) local samples = rshift(lo, 16) local size = band(lo, 0xFFFF) if ch == 0 or rate == 0 or samples == 0 then return nil, "bad frame header" end local slices = (samples + 19) // 20 local head = 8 + 16 * ch if slices > 256 or size < head or slices * ch > (size - head) // 8 then return nil, "bad frame size" end if size > avail then return nil, "truncated frame" end return { channels = ch, rate = rate, samples = samples, size = size }, nil end @native function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: number): (number?, number | string) local info, msg = Qoa.frameInfo(b, p, avail) if not info then return nil, msg :: string end local ch, samples = info.channels, info.samples for c = 0, ch - 1 do local lp = p + 8 + c * 16 local hA, hB, hC, hD = be32(b, lp), be32(b, lp + 4), be32(b, lp + 8), be32(b, lp + 12) local h0, h1, h2, h3 = s16(rshift(hA, 16)), s16(band(hA, 0xFFFF)), s16(rshift(hB, 16)), s16(band(hB, 0xFFFF)) local w0, w1, w2, w3 = s16(rshift(hC, 16)), s16(band(hC, 0xFFFF)), s16(rshift(hD, 16)), s16(band(hD, 0xFFFF)) local sp = p + 8 + 16 * ch + c * 8 local o = (d + c) * 4 local os = ch * 4 local s0 = 0 while s0 < samples do local hi, lo = be32(b, sp), be32(b, sp + 4) local base = rshift(hi, 28) * 8 + 1 local n = math.min(20, samples - s0) for k = 0, n - 1 do local q if k < 9 then q = band(rshift(hi, 25 - 3 * k), 7) elseif k == 9 then q = band(hi, 1) * 4 + rshift(lo, 30) else q = band(rshift(lo, 57 - 3 * k), 7) end local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192 local dq = DEQ[base + q] local r = pred + dq if r > 32767 then r = 32767 elseif r < -32768 then r = -32768 end writef32(dst, o, r / 32768) o += os local delta = dq // 16 w0 += if h0 < 0 then -delta else delta w1 += if h1 < 0 then -delta else delta w2 += if h2 < 0 then -delta else delta w3 += if h3 < 0 then -delta else delta h0, h1, h2, h3 = h1, h2, h3, r end s0 += 20 sp += 8 * ch end end return samples, info.size end -- LMS state: 8 i32 per channel (history 0..3, weights 0..3); initial weights 0, 0, -1, 2 (<< 13) @native function Qoa.newLms(ch: number): buffer local st = buffer.create(32 * ch) for c = 0, ch - 1 do writei32(st, c * 32 + 24, -8192) writei32(st, c * 32 + 28, 16384) end return st end @native local function toS16(x: number): number local v = floor(x * 32768 + 0.5) if v ~= v then return 0 elseif v > 32767 then return 32767 elseif v < -32768 then return -32768 end return v end -- qoa.h's qoa_div: a rounding division by the scale factor through its .16 reciprocal (in 32-bit int arithmetic, which -- wraps for big residuals at scale factor 0), rounding away from zero @native local function qdiv(v: number, sf: number): number local x = v * RECIP[sf + 1] + 32768 if x >= 2147483648 or x < -2147483648 then x = (x + 2147483648) % 4294967296 - 2147483648 end local n = x // 65536 local sv = if v > 0 then 1 elseif v < 0 then -1 else 0 local sn = if n > 0 then 1 elseif n < 0 then -1 else 0 return n + sv - sn end @native function Qoa.encodeFrame(x: buffer, xf: number, n: number, ch: number, rate: number, lms: buffer, out: buffer, p: number): number local slices = (n + 19) // 20 local size = Qoa.frameSize(ch, slices) writeu32(out, p, byteswap(bor(lshift(ch, 24), rate))) writeu32(out, p + 4, byteswap(bor(lshift(n, 16), size))) for c = 0, ch - 1 do local so = c * 32 -- the history and weights as big-endian i16 x 4 for i = 0, 3 do local hv = band(readi32(lms, so + i * 4), 0xFFFF) local wv = band(readi32(lms, so + 16 + i * 4), 0xFFFF) buffer.writeu8(out, p + 8 + c * 16 + i * 2, rshift(hv, 8)) buffer.writeu8(out, p + 8 + c * 16 + i * 2 + 1, band(hv, 255)) buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2, rshift(wv, 8)) buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2 + 1, band(wv, 255)) end end local xs = table.create(20, 0) local codes = table.create(20, 0) local best = table.create(20, 0) local prevSf = table.create(ch, 0) local sp = p + 8 + 16 * ch for s = 0, slices - 1 do local len = math.min(20, n - s * 20) for c = 0, ch - 1 do for k = 1, len do xs[k] = toS16(readf32(x, ((xf + s * 20 + k - 1) * ch + c) * 4)) end local so = c * 32 local H0, H1, H2, H3 = readi32(lms, so), readi32(lms, so + 4), readi32(lms, so + 8), readi32(lms, so + 12) local W0, W1, W2, W3 = readi32(lms, so + 16), readi32(lms, so + 20), readi32(lms, so + 24), readi32(lms, so + 28) local bestRank, bestSf = math.huge, 0 local b0, b1, b2, b3, bw0, bw1, bw2, bw3 = H0, H1, H2, H3, W0, W1, W2, W3 for sfi = 0, 15 do local sf = (sfi + prevSf[c + 1]) % 16 local h0, h1, h2, h3, w0, w1, w2, w3 = H0, H1, H2, H3, W0, W1, W2, W3 local rank = 0 local base = sf * 8 + 1 for k = 1, len do local v = xs[k] local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192 local res = v - pred local sc = qdiv(res, sf) if sc > 8 then sc = 8 elseif sc < -8 then sc = -8 end local q = QUANT[sc + 9] local dq = DEQ[base + q] local r = pred + dq if r > 32767 then r = 32767 elseif r < -32768 then r = -32768 end local sq = w0 * w0 + w1 * w1 + w2 * w2 + w3 * w3 if sq >= 2147483648 then -- C int arithmetic sq = (sq + 2147483648) % 4294967296 - 2147483648 end local pen = sq // 262144 - 0x8ff if pen < 0 then pen = 0 end local e = v - r rank += e * e + pen * pen if rank > bestRank then break end local delta = dq // 16 w0 += if h0 < 0 then -delta else delta w1 += if h1 < 0 then -delta else delta w2 += if h2 < 0 then -delta else delta w3 += if h3 < 0 then -delta else delta h0, h1, h2, h3 = h1, h2, h3, r codes[k] = q end if rank < bestRank then bestRank, bestSf = rank, sf b0, b1, b2, b3, bw0, bw1, bw2, bw3 = h0, h1, h2, h3, w0, w1, w2, w3 for k = 1, len do best[k] = codes[k] end end end prevSf[c + 1] = bestSf writei32(lms, so, b0) writei32(lms, so + 4, b1) writei32(lms, so + 8, b2) writei32(lms, so + 12, b3) writei32(lms, so + 16, bw0) writei32(lms, so + 20, bw1) writei32(lms, so + 24, bw2) writei32(lms, so + 28, bw3) -- the slice: sf in the top 4 bits, then the codes, unused codes 0 local hi, lo = bestSf * 268435456, 0 for k = 0, 19 do local q = if k < len then best[k + 1] else 0 if k < 9 then hi += q * 2 ^ (25 - 3 * k) elseif k == 9 then hi += rshift(q, 2) lo += band(q, 3) * 1073741824 else lo += q * 2 ^ (57 - 3 * k) end end writeu32(out, sp, byteswap(hi)) writeu32(out, sp + 4, byteswap(lo)) sp += 8 end end return size end return Qoa end __FILES["codecs/audio/Resample"] = @native function() -- codecs/audio/Resample: sample-rate conversion by band-limited (Kaiser-windowed sinc) polyphase interpolation. -- New in rosetta. -- -- The filter is a polyphase table: exact phases when to / gcd(from, to) <= 4096 (44100 <-> 48000: 160 phases), -- else 4096 phases with linear interpolation between them. Each phase is normalised to unit DC gain. The cutoff is a -- fraction (default 0.97) of the lower Nyquist frequency. -- -- quality zero crossings per side Kaiser beta stop band -- "low" 8 6 ~ -60 dB -- "medium" 16 (default) 8 ~ -80 dB -- "high" 32 10 ~ -100 dB -- -- Output frame j sits at input time j * from / to (centred filter, zero outside the input); n input frames give -- floor(n * to / from + 0.5) output frames. local Resample = {} type Options = { quality: ("low" | "medium" | "high")?, cutoff: number?, } type Resampler = { from: number, to: number, channels: number, process: (self: Resampler, src: buffer, frames: number, out: buffer?) -> (buffer, number), flush: (self: Resampler, out: buffer?) -> (buffer, number), } local QUALITY = { low = { 8, 6 }, medium = { 16, 8 }, high = { 32, 10 } } local MAX_EXACT = 4096 local INTERP_PHASES = 4096 local floor, sin, pi, sqrt, max, min = math.floor, math.sin, math.pi, math.sqrt, math.max, math.min local readf32, writef32 = buffer.readf32, buffer.writef32 @native local function besselI0(x: number): number local sum, term = 1, 1 for k = 1, 80 do term *= (x / (2 * k)) ^ 2 sum += term if term < sum * 1e-16 then break end end return sum end @native local function gcd(a: number, b: number): number while b ~= 0 do a, b = b, a % b end return a end type Filter = { taps: number, half: number, phases: number, exact: boolean, h: { number }, -- phase p, tap k: h[p * taps + k + 1] } -- phase p: an output p / phases past an input sample; tap k multiplies input floor(t) - half + 1 + k @native local function makeFilter(ratio: number, phases: number, exact: boolean, zc: number, beta: number, cut: number): Filter local cutoff = cut * min(1, ratio) local width = zc / cutoff -- in input samples, each side local half = math.ceil(width) local taps = 2 * half local i0b = besselI0(beta) local n = if exact then phases else phases + 1 local h = table.create(n * taps, 0) for p = 0, n - 1 do local frac = p / phases local sum = 0 local base = p * taps for k = 0, taps - 1 do local d = (k - half + 1) - frac -- input position minus output position local r = d / width local v = 0 if r > -1 and r < 1 then local x = d * cutoff local s = if x == 0 then 1 else sin(pi * x) / (pi * x) v = s * besselI0(beta * sqrt(1 - r * r)) / i0b end h[base + k + 1] = v sum += v end if sum ~= 0 then for k = 1, taps do h[base + k] /= sum end end end return { taps = taps, half = half, phases = phases, exact = exact, h = h } end type State = { from: number, to: number, channels: number, f: Filter, step: number, -- M = from / g: the input advance per output frame, in units of 1 / L L: number, -- to / g hist: { number }, histFrames: number, base: number, inFrames: number, outPos: number, done: boolean, process: any, flush: any, } @native local function run(st: State, limitOut: number, out: buffer?): (buffer, number) local f = st.f local taps, half, h = f.taps, f.half, f.h local ch = st.channels local hist, base, histFrames = st.hist, st.base, st.histFrames local L, M = st.L, st.step local j0 = st.outPos -- outputs j with floor(j * M / L) - half + taps <= available frames (zero beyond the end after flush) local avail = base + histFrames local jmax = limitOut if not st.done then -- the last tap must be buffered: floor(j * M / L) + half <= avail - 1, i.e. j * M < (avail - half) * L local lim = floor(((avail - half) * L - 1) / M) if lim + 1 < jmax then jmax = lim + 1 end end local n = jmax - j0 if n <= 0 then return out or buffer.create(0), 0 end local bytes = n * ch * 4 local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes) local exact = f.exact local phases = f.phases local o = 0 for j = j0, jmax - 1 do local num = j * M local ip = num // L -- floor(t) local first = ip - half + 1 local rel = first - base local kLo = if rel < 0 then -rel else 0 local kHi = taps - 1 if rel + kHi >= histFrames then kHi = histFrames - 1 - rel end if exact then local hb = (num - ip * L) * taps + 1 -- phase * taps + 1 for c = 0, ch - 1 do local acc = 0 local hi = (rel + kLo) * ch + c + 1 for k = kLo, kHi do acc += hist[hi] * h[hb + k] hi += ch end writef32(b, o, acc) o += 4 end else local fp = (num - ip * L) / L * phases local p = floor(fp) local a = fp - p local hb = p * taps + 1 local hb2 = hb + taps for c = 0, ch - 1 do local acc, acc2 = 0, 0 local hi = (rel + kLo) * ch + c + 1 for k = kLo, kHi do local x = hist[hi] acc += x * h[hb + k] acc2 += x * h[hb2 + k] hi += ch end writef32(b, o, acc + (acc2 - acc) * a) o += 4 end end end st.outPos = jmax local keepFrom = (jmax * M) // L - half + 1 local drop = keepFrom - base if drop > 0 then if drop >= histFrames then st.hist = {} st.histFrames = 0 st.base = base + histFrames else local nh: { number } = table.create((histFrames - drop) * ch) :: any table.move(hist, drop * ch + 1, histFrames * ch, 1, nh) st.hist = nh st.histFrames = histFrames - drop st.base = base + drop end end return b, n end @native local function process(self: State, src: buffer, frames: number, out: buffer?): (buffer, number) if self.done or type(src) ~= "buffer" or type(frames) ~= "number" or frames <= 0 then return out or buffer.create(0), 0 end local ch = self.channels frames = min(floor(frames), buffer.len(src) // (ch * 4)) local hist = self.hist local p = self.histFrames * ch for i = 0, frames * ch - 1 do hist[p + i + 1] = readf32(src, i * 4) end self.histFrames += frames self.inFrames += frames return run(self, math.huge, out) end @native local function flush(self: State, out: buffer?): (buffer, number) if self.done then return out or buffer.create(0), 0 end self.done = true local total = floor(self.inFrames * self.to / self.from + 0.5) return run(self, total, out) end @native function Resample.new(from: number, to: number, channels: number, opts: Options?): (Resampler?, string?) if type(from) ~= "number" or type(to) ~= "number" or from ~= from or to ~= to or from <= 0 or to <= 0 or from > 2 ^ 24 or to > 2 ^ 24 then return nil, "bad sample rates" end if type(channels) ~= "number" or channels < 1 or channels > 256 or channels ~= floor(channels) then return nil, "bad channel count" end local q: { number }? = QUALITY[(opts and opts.quality) or "medium"] if not q then return nil, "quality must be low, medium or high" end local cut = (opts and opts.cutoff) or 0.97 if type(cut) ~= "number" or not (cut >= 0.5 and cut <= 1) then return nil, "cutoff must be 0.5 .. 1" end -- positions are exact integers: output j sits at input j * M / L (non-integer rates: to 1 / 1000 Hz) local scale = if from ~= floor(from) or to ~= floor(to) then 1000 else 1 local fi: number = floor(from * scale + 0.5) local ti: number = floor(to * scale + 0.5) local g: number = gcd(fi, ti) local L: number, M: number = ti // g, fi // g local exact = L <= MAX_EXACT local phases = if exact then L else INTERP_PHASES local st: State = { from = from, to = to, channels = channels, -- the same rate: a pass-through (tap 0 is the input frame itself) f = if L == 1 and M == 1 then { taps = 2, half = 1, phases = 1, exact = true, h = { 1, 0 } } else makeFilter(to / from, phases, exact, q[1], q[2], cut), step = M, L = L, hist = {}, histFrames = 0, base = 0, inFrames = 0, outPos = 0, done = false, process = process, flush = flush, } return st :: any, nil end @native function Resample.buffer(src: buffer, frames: number, channels: number, from: number, to: number, opts: Options?): (buffer?, number | string) local rs, err = Resample.new(from, to, channels, opts) if not rs then return nil, err :: string end if type(src) ~= "buffer" or type(frames) ~= "number" or frames < 0 or buffer.len(src) < frames * channels * 4 then return nil, "the buffer is shorter than frames * channels * 4" end local total = floor(frames * to / from + 0.5) local out = buffer.create(total * channels * 4) local got = 0 local chunk = 65536 local tmp: buffer? = nil local pos = 0 while pos < frames do local n = min(chunk, frames - pos) local part = buffer.create(n * channels * 4) buffer.copy(part, 0, src, pos * channels * 4, n * channels * 4) local b, m = rs:process(part, n, tmp) tmp = b if m > 0 then buffer.copy(out, got * channels * 4, b, 0, m * channels * 4) got += m end pos += n end local b, m = rs:flush(tmp) if m > 0 then buffer.copy(out, got * channels * 4, b, 0, m * channels * 4) got += m end return out, got end @native function Resample.source(src: any, to: number, opts: Options?): (any, string?) if type(src) ~= "table" or type(src.read) ~= "function" then return nil, "needs a source" end local rs, err = Resample.new(src.sampleRate, to, src.channels, opts) if not rs then return nil, err end local ch = src.channels local pending = buffer.create(0) local pendingFrames, pendingPos = 0, 0 local ended = false local out = { sampleRate = to, channels = ch, frames = if src.frames > 0 then floor(src.frames * to / src.sampleRate + 0.5) else 0, tags = src.tags, err = nil :: any, } local inTmp: buffer? = nil @native function out.read(self: any, n: number, dst: buffer?): (buffer, number) n = floor(n) while pendingFrames - pendingPos <= 0 and not ended do local b: buffer, m: number = (src :: any):read(math.max(1024, floor(n * src.sampleRate / to) + 64), inTmp) inTmp = b local r: buffer, k: number if m <= 0 then ended = true self.err = src.err r, k = rs:flush() else r, k = rs:process(b, m) end if k > 0 then pending, pendingFrames, pendingPos = r, k, 0 end end local k = min(n, pendingFrames - pendingPos) if k <= 0 then return dst or buffer.create(0), 0 end local bytes = k * ch * 4 local b = if dst and buffer.len(dst) >= bytes then dst else buffer.create(bytes) buffer.copy(b, 0, pending, pendingPos * ch * 4, bytes) pendingPos += k return b, k end return out, nil end return Resample end __FILES["codecs/audio/SoundFont"] = function() -- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. -- The synth is a port of TinySoundFont (tsf.h v0.9, MIT, (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt). local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Parse = __include("codecs/audio/SoundFont/Parse") local Synth = __include("codecs/audio/SoundFont/Synth") local Fallback = __include("codecs/audio/SoundFont/Fallback") local SoundFont = {} type SoundFont = Parse.SoundFont type State = Synth.State SoundFont.Synth = Synth SoundFont.defaultRegion = Parse.defaultRegion function SoundFont.sniff(r: Bytes.Reader): boolean return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk" end function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?) local r: Bytes.Reader if type(src) == "string" then r = Bytes.reader(buffer.fromstring(src)) elseif type(src) == "buffer" then r = Bytes.reader(src) elseif type(src) == "table" and type(src.buf) == "buffer" then r = Bytes.reader(src.buf, src.pos, src.limit - src.pos) else return nil, Err.new(Err.ARG, "soundfont: expected a buffer, string or Reader") end local ok, sf, err = pcall(Parse.parse, r, opts) if not ok then return nil, Err.new(Err.CORRUPT, "soundfont parser failed: " .. tostring(sf)) end return sf, err end function SoundFont.fallback(): SoundFont return Fallback.build() end function SoundFont.isSoundFont(v: any): boolean return type(v) == "table" and v.kind == "soundfont" and type(v.samples) == "buffer" and type(v.presets) == "table" end function SoundFont.synth(sf: SoundFont?, sampleRate: number?, opts: { gain: number?, maxVoices: number? }?): State return Synth.new(sf or Fallback.build(), sampleRate or 44100, opts and opts.gain, opts and opts.maxVoices) end return SoundFont end __FILES["codecs/audio/SoundFont/Fallback"] = function() -- codecs/audio/SoundFont/Fallback: the built-in General MIDI set (generated waveforms per GM family, drum kit on bank 128). -- No third-party code. local Parse = __include("codecs/audio/SoundFont/Parse") local Fallback = {} local CYCLE = 256 local NOISE = 32768 local C4 = 261.6255653005986 local function hzToCents(hz: number): number return 1200 * math.log(hz / 8.176, 2) end local cached: any = nil function Fallback.build(): any if cached then return cached end local waves = { "sine", "triangle", "square", "saw" } local count = #waves * CYCLE + NOISE local samples = buffer.create((count + 1) * 4) local starts: { [string]: number } = {} for w, name in waves do local base = (w - 1) * CYCLE starts[name] = base for i = 0, CYCLE - 1 do local ph = i / CYCLE local v if name == "sine" then v = math.sin(2 * math.pi * ph) elseif name == "triangle" then v = if ph < 0.25 then 4 * ph elseif ph < 0.75 then 2 - 4 * ph else 4 * ph - 4 elseif name == "square" then v = if ph < 0.5 then 0.6 else -0.6 else v = (1 - 2 * ph) * 0.7 end buffer.writef32(samples, (base + i) * 4, v) end end local noiseStart = #waves * CYCLE starts.noise = noiseStart local seed = 12345 for i = 0, NOISE - 1 do seed = (seed * 1103515245 + 12345) % 2147483648 buffer.writef32(samples, (noiseStart + i) * 4, (seed / 1073741824 - 1) * 0.7) end local function region(wave: string, fields: { [string]: number }): { [string]: number } local r = Parse.defaultRegion() local s = starts[wave] r.offset = s r.loopMode = 1 r.loopStart = s if wave == "noise" then r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + NOISE, s + NOISE - 1, 44100, 60 else r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + CYCLE, s + CYCLE - 1, CYCLE * C4, 60 end r.aRelease = 0.08 for k, v in fields do r[k] = v end return r end local families: { { any } } = { { "piano", "triangle", { aDecay = 2.5, aSustain = 0, aRelease = 0.25 } }, { "chromatic", "sine", { aDecay = 1.2, aSustain = 0, aRelease = 0.3 } }, { "organ", "square", { aAttack = 0.005, aRelease = 0.05, filterFc = hzToCents(5000) } }, { "guitar", "saw", { aDecay = 1.5, aSustain = 0, aRelease = 0.15, filterFc = hzToCents(3000) } }, { "bass", "triangle", { aDecay = 1.5, aSustain = 0.4, aRelease = 0.1 } }, { "strings", "saw", { aAttack = 0.08, aRelease = 0.3, filterFc = hzToCents(4000), freqVibLFO = hzToCents(5.5), vibLfoToPitch = 8, delayVibLFO = 0.2 } }, { "ensemble", "saw", { aAttack = 0.12, aRelease = 0.4, filterFc = hzToCents(3500), freqVibLFO = hzToCents(5), vibLfoToPitch = 10 } }, { "brass", "saw", { aAttack = 0.03, aRelease = 0.12, filterFc = hzToCents(1200), mAttack = 0.05, mDecay = 0.3, mSustain = 0.4, modEnvToFilterFc = 2400 } }, { "reed", "square", { aAttack = 0.02, aRelease = 0.08, filterFc = hzToCents(2500) } }, { "pipe", "sine", { aAttack = 0.04, aRelease = 0.12, freqVibLFO = hzToCents(5), vibLfoToPitch = 12, delayVibLFO = 0.3 } }, { "lead", "square", { aAttack = 0.005, aRelease = 0.1, filterFc = hzToCents(6000) } }, { "pad", "saw", { aAttack = 0.4, aRelease = 0.8, filterFc = hzToCents(1800), freqModLFO = hzToCents(0.5), modLfoToFilterFc = 600 } }, { "synthfx", "triangle", { aAttack = 0.2, aRelease = 1.0, freqModLFO = hzToCents(3), modLfoToVolume = 60 } }, { "ethnic", "saw", { aDecay = 1.0, aSustain = 0, aRelease = 0.2, filterFc = hzToCents(3000) } }, { "percussive", "sine", { aDecay = 0.4, aSustain = 0, aRelease = 0.1, mDecay = 0.1, mSustain = 0, modEnvToPitch = 1200 } }, { "sfx", "noise", { aAttack = 0.05, aRelease = 0.5, filterFc = hzToCents(3000) } }, } local presets = {} for program = 0, 127 do local f = families[program // 8 + 1] table.insert(presets, { name = "fallback " .. f[1], preset = program, bank = 0, regions = { region(f[2], f[3]) } }) end local kit = {} local function drum(lo: number, hi: number, wave: string, fields: { [string]: number }) local r = region(wave, fields) r.lokey, r.hikey = lo, hi r.sampleRate *= 2 ^ ((fields.semis or 0) / 12) r.semis = nil :: any table.insert(kit, r) end local sweep = { mDecay = 0.06, mSustain = 0, modEnvToPitch = 2400 } local function with(a: { [string]: number }, b: { [string]: number }): { [string]: number } local c = table.clone(a) for k, v in b do c[k] = v end return c end drum(0, 34, "noise", { aDecay = 0.1, aSustain = 0, keytrack = 0, filterFc = hzToCents(4000) }) drum(35, 36, "sine", with(sweep, { aDecay = 0.35, aSustain = 0, aRelease = 0.05, keytrack = 0, semis = -26 })) drum(37, 37, "noise", { aDecay = 0.05, aSustain = 0, keytrack = 0, filterFc = hzToCents(5000) }) drum(38, 38, "noise", { aDecay = 0.2, aSustain = 0, keytrack = 0, filterFc = hzToCents(6000) }) drum(39, 39, "noise", { aDecay = 0.15, aSustain = 0, keytrack = 0, filterFc = hzToCents(8000) }) drum(40, 40, "noise", { aDecay = 0.18, aSustain = 0, keytrack = 0, filterFc = hzToCents(7000) }) for _, k in { 41, 43, 45, 47, 48, 50 } do drum(k, k, "sine", with(sweep, { aDecay = 0.4, aSustain = 0, semis = (k - 41) - 12, keytrack = 0 })) end drum(42, 42, "noise", { aDecay = 0.05, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) drum(44, 44, "noise", { aDecay = 0.08, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) drum(46, 46, "noise", { aDecay = 0.45, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) drum(49, 49, "noise", { aDecay = 1.5, aSustain = 0, keytrack = 0, semis = 7 }) drum(51, 51, "noise", { aDecay = 1.0, aSustain = 0, keytrack = 0, semis = 10, filterFc = hzToCents(9000) }) drum(52, 59, "noise", { aDecay = 1.2, aSustain = 0, keytrack = 0, semis = 5 }) drum(60, 127, "noise", { aDecay = 0.12, aSustain = 0, keytrack = 30, filterFc = hzToCents(5000) }) table.insert(presets, { name = "fallback drums", preset = 0, bank = 128, regions = kit }) cached = { kind = "soundfont", info = { name = "rosetta fallback" }, samples = samples, sampleCount = count, presets = presets, sampleHeaders = {}, instruments = {}, meta = { source = { format = "fallback" } }, } return cached end return Fallback end __FILES["codecs/audio/SoundFont/Parse"] = function() -- codecs/audio/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader, zones merged into regions as TinySoundFont does. -- After tsf.h v0.9 (MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt) tsf_load_presets / -- tsf_region_operator / tsf_region_envtosecs. Unlike tsf.h, initialAttenuation is cB * 0.04 dB (FluidSynth's -- EMU-compatible scale; tsf uses 0.01). local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Parse = {} type Region = { [string]: number } type Preset = { name: string, preset: number, bank: number, regions: { Region } } type SoundFont = { kind: "soundfont", info: { [string]: string }, samples: buffer, -- f32 mono, sampleCount + 1 floats (a zero pad sample past the end) sampleCount: number, presets: { Preset }, sampleHeaders: { { [string]: any } }, instruments: { { name: string, zones: number } }, meta: { [string]: any }, } local GEN_INSTRUMENT, GEN_SAMPLEID = 41, 53 -- generator op -> { field, mode, limit }. modes: f / i (value, merged by adding then clamping), a (sample address -- add), a15 (coarse address add: * 32768), kr / vr (key / velocity range), loop, group, key (overriding root key) local LIM12K5K = { 1, -12000, 5000 } local LIM12K8K = { 1, -12000, 8000 } local LIM1200 = { 1, -1200, 1200 } local GEN: { [number]: { any } } = { [0] = { "offset", "a" }, [1] = { "stop", "a" }, [2] = { "loopStart", "a" }, [3] = { "loopEnd", "a" }, [4] = { "offset", "a15" }, [5] = { "modLfoToPitch", "i", { 1, -12000, 12000 } }, [6] = { "vibLfoToPitch", "i", { 1, -12000, 12000 } }, [7] = { "modEnvToPitch", "i", { 1, -12000, 12000 } }, [8] = { "filterFc", "i", { 1, 1500, 13500 } }, [9] = { "filterQ", "i", { 1, 0, 960 } }, [10] = { "modLfoToFilterFc", "i", { 1, -12000, 12000 } }, [11] = { "modEnvToFilterFc", "i", { 1, -12000, 12000 } }, [12] = { "stop", "a15" }, [13] = { "modLfoToVolume", "i", { 1, -960, 960 } }, [17] = { "pan", "f", { 0.001, -0.5, 0.5 } }, [21] = { "delayModLFO", "f", LIM12K5K }, [22] = { "freqModLFO", "i", { 1, -16000, 4500 } }, [23] = { "delayVibLFO", "f", LIM12K5K }, [24] = { "freqVibLFO", "i", { 1, -16000, 4500 } }, [25] = { "mDelay", "f", LIM12K5K }, [26] = { "mAttack", "f", LIM12K8K }, [27] = { "mHold", "f", LIM12K5K }, [28] = { "mDecay", "f", LIM12K8K }, [29] = { "mSustain", "f", { 1, 0, 1000 } }, [30] = { "mRelease", "f", LIM12K8K }, [31] = { "mKeyHold", "f", LIM1200 }, [32] = { "mKeyDecay", "f", LIM1200 }, [33] = { "aDelay", "f", LIM12K5K }, [34] = { "aAttack", "f", LIM12K8K }, [35] = { "aHold", "f", LIM12K5K }, [36] = { "aDecay", "f", LIM12K8K }, [37] = { "aSustain", "f", { 1, 0, 1440 } }, [38] = { "aRelease", "f", LIM12K8K }, [39] = { "aKeyHold", "f", LIM1200 }, [40] = { "aKeyDecay", "f", LIM1200 }, [43] = { "", "kr" }, [44] = { "", "vr" }, [45] = { "loopStart", "a15" }, [48] = { "attenuation", "f", { 0.04, 0, 57.6 } }, [50] = { "loopEnd", "a15" }, [51] = { "transpose", "i" }, [52] = { "tune", "i" }, [54] = { "loopMode", "loop" }, [56] = { "keytrack", "i" }, [57] = { "group", "group" }, [58] = { "keycenter", "key" }, } local MERGE: { { any } } = {} do local seen: { [string]: boolean } = {} for op = 0, 58 do local g = GEN[op] if g and (g[2] == "f" or g[2] == "i" or g[2] == "a") and not seen[g[1]] then seen[g[1]] = true table.insert(MERGE, g) end end end local FIELDS = { "loopMode", "sampleRate", "lokey", "hikey", "lovel", "hivel", "group", "offset", "stop", "loopStart", "loopEnd", "transpose", "tune", "keycenter", "keytrack", "attenuation", "pan", "filterQ", "filterFc", "modEnvToPitch", "modEnvToFilterFc", "modLfoToFilterFc", "modLfoToVolume", "delayModLFO", "freqModLFO", "modLfoToPitch", "delayVibLFO", "freqVibLFO", "vibLfoToPitch", "aDelay", "aAttack", "aHold", "aDecay", "aSustain", "aRelease", "aKeyHold", "aKeyDecay", "mDelay", "mAttack", "mHold", "mDecay", "mSustain", "mRelease", "mKeyHold", "mKeyDecay", "sampleIndex", } -- tsf_region_clear (relative: a preset zone, all zero so values add to the instrument's) local function clear(relative: boolean): Region local r: Region = {} for _, f in FIELDS do r[f] = 0 end r.hikey, r.hivel, r.keycenter = 127, 127, 60 if relative then return r end r.keytrack = 100 r.keycenter = -1 for _, p in { "a", "m" } do for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do r[p .. s] = -12000 end end r.filterFc = 13500 r.delayModLFO, r.delayVibLFO = -12000, -12000 return r end local function copy(r: Region): Region local c: Region = {} for k, v in r do c[k] = v end return c end function Parse.defaultRegion(): Region local r = clear(false) r.keycenter = 60 for _, p in { "a", "m" } do for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do r[p .. s] = 0 end end r.aSustain, r.mSustain = 1, 1 r.delayModLFO, r.delayVibLFO = 0, 0 return r end -- set one generator (tsf_region_operator with an amount); lo / hi = the two bytes, s = signed 16, w = unsigned 16 local function operator(r: Region, op: number, lo: number, hi: number, s: number, w: number) local g = GEN[op] if not g then return end local mode = g[2] if mode == "f" or mode == "i" then r[g[1]] = s elseif mode == "a" then r[g[1]] += s elseif mode == "a15" then r[g[1]] += s * 32768 elseif mode == "kr" then r.lokey, r.hikey = lo, hi elseif mode == "vr" then r.lovel, r.hivel = lo, hi elseif mode == "loop" then local m = w % 4 r.loopMode = if m == 3 then 2 elseif m == 1 then 1 else 0 elseif mode == "group" then r.group = w elseif mode == "key" then r.keycenter = s end end -- merge(zone, preset): zone += preset, then clamp (tsf_region_operator without an amount) local function merge(z: Region, p: Region) for _, g in MERGE do local f = g[1] local v = z[f] + p[f] local lim = g[3] if lim then v *= lim[1] v = math.clamp(v, lim[2], lim[3]) end z[f] = v end end local function tc2s(tc: number): number return 2 ^ (tc / 1200) end -- envtosecs (tsf_region_envtosecs): timecents to seconds; hold / decay stay in timecents when they scale by key local function envToSecs(r: Region, p: string, sustainIsGain: boolean) for _, s in { "Delay", "Attack", "Release" } do local v = r[p .. s] r[p .. s] = if v < -11950 then 0 else tc2s(v) end if r[p .. "KeyHold"] == 0 then local v = r[p .. "Hold"] r[p .. "Hold"] = if v < -11950 then 0 else tc2s(v) end if r[p .. "KeyDecay"] == 0 then local v = r[p .. "Decay"] r[p .. "Decay"] = if v < -11950 then 0 else tc2s(v) end local sus = r[p .. "Sustain"] if sus < 0 then sus = 0 elseif sustainIsGain then sus = if -sus / 10 > -100 then 10 ^ (-sus / 10 * 0.05) else 0 else sus = 1 - sus / 1000 end r[p .. "Sustain"] = sus end type Hydra = { [string]: { { number } } } -- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte) local LAYOUT: { [string]: { number } } = { phdr = { 20, 2, 2, 2, 4, 4, 4 }, pbag = { 2, 2 }, pmod = { 2, 2, -2, 2, 2 }, pgen = { 2, 2 }, inst = { 20, 2 }, ibag = { 2, 2 }, imod = { 2, 2, -2, 2, 2 }, igen = { 2, 2 }, shdr = { 20, 4, 4, 4, 4, 4, 1, -1, 2, 2 }, } local RECSIZE: { [string]: number } = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 } local INFO_NAMES = { isng = "engine", INAM = "name", irom = "rom", ICRD = "date", IENG = "author", IPRD = "product", ICOP = "copyright", ICMT = "comment", ISFT = "software", } type Options = { maxRegions: number?, maxSamples: number? } function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) local maxRegions = opts and opts.maxRegions or 1000000 local maxSamples = opts and opts.maxSamples or 2 ^ 28 if r:string(4) ~= "RIFF" then return r:fail(Err.CORRUPT, "not a RIFF file") end local riffSize = r:u32le() if r:string(4) ~= "sfbk" then return r:fail(Err.CORRUPT, "not a SoundFont (no sfbk)") end if r.err then return nil, r.err end local body = r:sub(12, math.max(0, riffSize - 4)) local info: { [string]: string } = {} local hydra: Hydra = {} local smpl: Bytes.Reader? = nil local sm24: Bytes.Reader? = nil local version = "" while body:remaining() >= 8 do local id, size = body:string(4), body:u32le() local chunk = body:slice(size) if size % 2 == 1 and body:remaining() > 0 then body:skip(1) end if id == "LIST" and chunk:remaining() >= 4 then local kind = chunk:string(4) while chunk:remaining() >= 8 do local sid, ssize = chunk:string(4), chunk:u32le() local sub = chunk:slice(ssize) if ssize % 2 == 1 and chunk:remaining() > 0 then chunk:skip(1) end if kind == "INFO" then if sid == "ifil" and sub:remaining() >= 4 then local major, minor = sub:u16le(), sub:u16le() version = string.format("%d.%02d", major, minor) elseif INFO_NAMES[sid] then info[INFO_NAMES[sid]] = sub:fixed(sub:remaining()) end elseif kind == "sdta" then if sid == "smpl" and not smpl then smpl = sub elseif sid == "sm24" then sm24 = sub end elseif kind == "pdta" then local layout = LAYOUT[sid] if layout and not hydra[sid] then local rs = RECSIZE[sid] local n = sub:remaining() // rs local recs = table.create(n) :: { { number } } for i = 1, n do local rec = {} for _, w in layout do if w == 20 then table.insert(rec, 0) sub:skip(20) elseif w == 4 then table.insert(rec, sub:u32le()) elseif w == 2 then table.insert(rec, sub:u16le()) elseif w == -2 then table.insert(rec, sub:i16le()) elseif w == 1 then table.insert(rec, sub:u8()) else table.insert(rec, sub:i8()) end end recs[i] = rec end hydra[sid] = recs if sid == "phdr" or sid == "inst" or sid == "shdr" then local names = table.create(n) for i = 0, n - 1 do names[i + 1] = sub:sub(i * rs, 20):fixed(20) end hydra[sid .. "Names"] = names :: any end end end end end end if not smpl then return nil, Err.new(Err.CORRUPT, "no sample data (sdta smpl)") end for _, k in { "phdr", "pbag", "pgen", "inst", "ibag", "igen", "shdr" } do if not hydra[k] or #hydra[k] == 0 then return nil, Err.new(Err.CORRUPT, "incomplete hydra: no " .. k .. " records") end end local sr = smpl :: Bytes.Reader local count = sr:remaining() // 2 if count > maxSamples then return nil, Err.new(Err.LIMIT, string.format("%d samples is over the %d sample limit", count, maxSamples)) end local samples = buffer.create((count + 1) * 4) do local b, p = sr.buf, sr.pos local readi16, writef32 = buffer.readi16, buffer.writef32 local s24 = sm24 if s24 and s24:remaining() >= count then local q = s24.pos local readu8 = buffer.readu8 for i = 0, count - 1 do writef32(samples, i * 4, (readi16(b, p + i * 2) * 256 + readu8(s24.buf, q + i)) / 8388607) end else s24 = nil for i = 0, count - 1 do writef32(samples, i * 4, readi16(b, p + i * 2) / 32767) end end sm24 = s24 end -- tsf_load_presets local phdr, pbag, pgen = hydra.phdr, hydra.pbag, hydra.pgen local inst, ibag, igen, shdr = hydra.inst, hydra.ibag, hydra.igen, hydra.shdr local phdrNames, instNames, shdrNames = (hydra :: any).phdrNames, (hydra :: any).instNames, (hydra :: any).shdrNames local nInst = #inst - 1 -- the last record of each list is the terminal one local nShdr = #shdr - 1 local function range(list: { { number } }, i: number, field: number, limit: number): (number, number) local a = list[i][field] + 1 local b = if list[i + 1] then list[i + 1][field] + 1 else a return math.max(1, a), math.min(b, limit + 1) end local presets: { Preset } = {} local regionTotal = 0 for pi = 1, #phdr - 1 do local ph = phdr[pi] local preset: Preset = { name = phdrNames[pi], preset = ph[2], bank = ph[3], regions = {} } local globalRegion = clear(true) local b0, b1 = range(phdr, pi, 4, #pbag) for bi = b0, b1 - 1 do local presetRegion = copy(globalRegion) local hadInstrument = false local g0, g1 = range(pbag, bi, 1, #pgen) for gi = g0, g1 - 1 do local pg = pgen[gi] local op, amount = pg[1], pg[2] local lo, hi = amount % 256, amount // 256 local s = if amount >= 32768 then amount - 65536 else amount if op == GEN_INSTRUMENT then hadInstrument = true if amount < nInst then local instRegion = clear(false) local ib0, ib1 = range(inst, amount + 1, 2, #ibag) for ibi = ib0, ib1 - 1 do local zone = copy(instRegion) local hadSample = false local ig0, ig1 = range(ibag, ibi, 1, #igen) for igi = ig0, ig1 - 1 do local ig = igen[igi] local iop, iamt = ig[1], ig[2] if iop == GEN_SAMPLEID then hadSample = true if iamt >= nShdr then break end local ok = not (zone.hikey < presetRegion.lokey or zone.lokey > presetRegion.hikey) and not (zone.hivel < presetRegion.lovel or zone.lovel > presetRegion.hivel) if ok then local z = copy(zone) z.lokey = math.max(z.lokey, presetRegion.lokey) z.hikey = math.min(z.hikey, presetRegion.hikey) z.lovel = math.max(z.lovel, presetRegion.lovel) z.hivel = math.min(z.hivel, presetRegion.hivel) merge(z, presetRegion) envToSecs(z, "a", true) envToSecs(z, "m", false) z.delayModLFO = if z.delayModLFO < -11950 then 0 else tc2s(z.delayModLFO) z.delayVibLFO = if z.delayVibLFO < -11950 then 0 else tc2s(z.delayVibLFO) local sh = shdr[iamt + 1] local sStart, sEnd, sLoopStart, sLoopEnd = sh[2], sh[3], sh[4], sh[5] z.offset = math.clamp(z.offset + sStart, 0, count) local stop = z.stop + sEnd if stop > 0 and stop < count then stop += 1 else stop = count end z.stop = math.clamp(stop, 0, count) z.loopStart = math.clamp(z.loopStart + sLoopStart, 0, count) local le = z.loopEnd + sLoopEnd if sLoopEnd > 0 then le -= 1 end z.loopEnd = math.clamp(le, 0, count) if z.keycenter == -1 then z.keycenter = sh[7] end z.tune += sh[8] z.sampleRate = sh[6] z.sampleIndex = iamt regionTotal += 1 if regionTotal > maxRegions then return nil, Err.new(Err.LIMIT, "over " .. maxRegions .. " regions") end table.insert(preset.regions, z) end break -- sampleID ends a zone's generator list else local ilo, ihi = iamt % 256, iamt // 256 operator(zone, iop, ilo, ihi, if iamt >= 32768 then iamt - 65536 else iamt, iamt) end end if ibi == ib0 and not hadSample then instRegion = zone -- the instrument's global zone end end end break -- instrument ends a preset zone's generator list else operator(presetRegion, op, lo, hi, s, amount) end end if bi == b0 and not hadInstrument then globalRegion = presetRegion -- the preset's global zone end end table.insert(presets, preset) end -- sorted by bank, then preset, then file order (tsf's sortedIndex) for i, p in presets do (p :: any)._order = i end table.sort(presets, function(a: Preset, b: Preset): boolean if a.bank ~= b.bank then return a.bank < b.bank end if a.preset ~= b.preset then return a.preset < b.preset end return (a :: any)._order < (b :: any)._order end) for _, p in presets do (p :: any)._order = nil end local headers = table.create(nShdr) :: { { [string]: any } } for i = 1, nShdr do local sh = shdr[i] headers[i] = { name = shdrNames[i], start = sh[2], stop = sh[3], loopStart = sh[4], loopEnd = sh[5], sampleRate = sh[6], originalPitch = sh[7], pitchCorrection = sh[8], link = sh[9], type = sh[10], } end local instruments = table.create(nInst) :: { { name: string, zones: number } } for i = 1, nInst do instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) } end local sf: SoundFont = { kind = "soundfont", info = info, samples = samples, sampleCount = count, presets = presets, sampleHeaders = headers, instruments = instruments, meta = { source = { format = "sf2", version = version, sm24 = sm24 ~= nil } }, } return sf, nil end return Parse end __FILES["codecs/audio/SoundFont/Synth"] = @native function() -- codecs/audio/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. -- A port of TinySoundFont (tsf.h v0.9, MIT, (c) 2017-2025 Bernhard Schelling, based on SFZero (c) 2012 Steve Folta; -- licenses/TinySoundFont-LICENSE.txt). Unlike tsf.h, the envelope gain is ramped across each 64-sample block. local Synth = {} local readf32, writef32, blen = buffer.readf32, buffer.writef32, buffer.len local exp, log, sqrt, tan, floor = math.exp, math.log, math.sqrt, math.tan, math.floor local NONE, DELAY, ATTACK, HOLD, DECAY, SUSTAIN, RELEASE, DONE = 0, 1, 2, 3, 4, 5, 6, 7 local BLOCK = 64 -- TSF_RENDER_EFFECTSAMPLEBLOCK: envelopes / LFOs / filter cutoff update per block local FASTRELEASE = 0.01 local PI = math.pi local LOOP_NONE, LOOP_SUSTAIN = 0, 2 type Env = { segment: number, isExp: boolean, isAmp: boolean, vel: number, level: number, slope: number, untilNext: number, delay: number, attack: number, hold: number, decay: number, sustain: number, release: number, } type Lfo = { untilStart: number, level: number, delta: number } type Voice = { preset: number, key: number, channel: number, held: boolean, region: { [string]: number }, pitchIn: number, pitchOut: number, pos: number, gainDB: number, panL: number, panR: number, playIndex: number, loopStart: number, loopEnd: number, amp: Env, mod: Env, lpActive: boolean, qinv: number, a0: number, a1: number, b1: number, b2: number, z1: number, z2: number, modlfo: Lfo, viblfo: Lfo, } type Channel = { preset: number, bank: number, pitchWheel: number, midiPan: number, midiVolume: number, midiExpression: number, midiRPN: number, midiData: number, sustain: boolean, panOffset: number, gainDB: number, pitchRange: number, tuning: number, } type State = { presets: { { regions: { { [string]: number } }, preset: number, bank: number } }, lookup: { [number]: number }, samples: buffer, rate: number, gainDB: number, voices: { Voice }, maxVoices: number, playIndex: number, channels: { Channel }, } @native local function tc2s(tc: number): number return 2 ^ (tc / 1200) end @native local function cents2Hz(c: number): number return 8.176 * 2 ^ (c / 1200) end @native local function db2gain(db: number): number return if db > -100 then 10 ^ (db * 0.05) else 0 end @native local function gain2db(g: number): number return if g <= 0.00001 then -100 else 20 * math.log10(g) end @native local function releaseSamples(e: Env, rate: number): number return floor((if e.release <= 0 then FASTRELEASE else e.release) * rate) end @native local function nextSegment(e: Env, active: number, rate: number) local seg = active if seg == NONE then e.untilNext = floor(e.delay * rate) if e.untilNext > 0 then e.segment, e.isExp, e.level, e.slope = DELAY, false, 0, 0 return end seg = DELAY end if seg == DELAY then e.untilNext = floor(e.attack * rate) if e.untilNext > 0 then if not e.isAmp then -- the mod env attack scales with velocity (1 = full duration, 127 = 0.125 x) e.untilNext = floor(e.attack * ((145 - e.vel) / 144) * rate) end e.segment, e.isExp, e.level = ATTACK, false, 0 e.slope = if e.untilNext > 0 then 1 / e.untilNext else 1 return end seg = ATTACK end if seg == ATTACK then e.untilNext = floor(e.hold * rate) if e.untilNext > 0 then e.segment, e.isExp, e.level, e.slope = HOLD, false, 1, 0 return end seg = HOLD end if seg == HOLD then e.untilNext = floor(e.decay * rate) if e.untilNext > 0 then e.segment, e.level = DECAY, 1 if e.isAmp then local mystery = -9.226 / e.untilNext -- LinuxSampler's decay curve (as tsf.h) e.slope = exp(mystery) e.isExp = true if e.sustain > 0 then e.untilNext = floor(log(e.sustain) / mystery) end else e.slope = -1 / e.untilNext e.untilNext = floor(e.decay * (1 - e.sustain) * rate) e.isExp = false end return end seg = DECAY end if seg == DECAY then e.segment, e.level, e.slope, e.untilNext, e.isExp = SUSTAIN, e.sustain, 0, 0x7FFFFFFF, false return end if seg == SUSTAIN then e.segment = RELEASE e.untilNext = math.max(1, releaseSamples(e, rate)) if e.isAmp then e.slope = exp(-9.226 / e.untilNext) e.isExp = true else e.slope = -e.level / e.untilNext e.isExp = false end return end e.segment, e.isExp, e.level, e.slope, e.untilNext = DONE, false, 0, 0, 0x7FFFFFF end @native local function envSetup(e: Env, r: { [string]: number }, p: string, key: number, vel: number, isAmp: boolean, rate: number) e.delay, e.attack, e.hold, e.decay = r[p .. "Delay"], r[p .. "Attack"], r[p .. "Hold"], r[p .. "Decay"] e.sustain, e.release = r[p .. "Sustain"], r[p .. "Release"] local kh, kd = r[p .. "KeyHold"], r[p .. "KeyDecay"] if kh ~= 0 then local h = e.hold + kh * (60 - key) e.hold = if h < -10000 then 0 else tc2s(h) end if kd ~= 0 then local d = e.decay + kd * (60 - key) e.decay = if d < -10000 then 0 else tc2s(d) end e.vel, e.isAmp = vel, isAmp nextSegment(e, NONE, rate) end @native local function envProcess(e: Env, n: number, rate: number) local slope = e.slope if slope ~= 0 then if e.isExp then e.level *= slope ^ n else e.level += slope * n end end e.untilNext -= n if e.untilNext <= 0 then nextSegment(e, e.segment, rate) end end @native local function newEnv(): Env return { segment = DONE, isExp = false, isAmp = false, vel = 0, level = 0, slope = 0, untilNext = 0, delay = 0, attack = 0, hold = 0, decay = 0, sustain = 0, release = 0 } end @native local function lowpassSetup(v: Voice, fc: number) -- the biquad from earlevel.com (as tsf.h) local k = tan(PI * fc) local kk = k * k local norm = 1 / (1 + k * v.qinv + kk) v.a0 = kk * norm v.a1 = 2 * v.a0 v.b1 = 2 * (kk - 1) * norm v.b2 = (1 - k * v.qinv + kk) * norm end @native local function lfoSetup(l: Lfo, delay: number, freqCents: number, rate: number) l.untilStart = floor(delay * rate) l.delta = 4 * cents2Hz(freqCents) / rate l.level = 0 end @native local function lfoProcess(l: Lfo, n: number) if l.untilStart > n then l.untilStart -= n return end l.level += l.delta * n if l.level > 1 then l.delta = -l.delta l.level = 2 - l.level elseif l.level < -1 then l.delta = -l.delta l.level = -2 - l.level end end @native local function calcPitch(v: Voice, shift: number, rate: number) local r = v.region local note = v.key + r.transpose + r.tune / 100 local adjusted = r.keycenter + (note - r.keycenter) * (r.keytrack / 100) + shift v.pitchIn = adjusted * 100 v.pitchOut = r.sampleRate / (tc2s(r.keycenter * 100) * rate) end @native local function setPan(v: Voice, pan: number) if pan <= -0.5 then v.panL, v.panR = 1, 0 elseif pan >= 0.5 then v.panL, v.panR = 0, 1 else v.panL, v.panR = sqrt(0.5 - pan), sqrt(0.5 + pan) end end @native local function channelShift(c: Channel): number return if c.pitchWheel == 8192 then c.tuning else (c.pitchWheel / 16383 * c.pitchRange * 2) - c.pitchRange + c.tuning end @native local function voiceEnd(s: State, v: Voice) nextSegment(v.amp, SUSTAIN, s.rate) nextSegment(v.mod, SUSTAIN, s.rate) if v.region.loopMode == LOOP_SUSTAIN then v.loopEnd = v.loopStart end end @native local function voiceEndQuick(s: State, v: Voice) v.amp.release = 0 nextSegment(v.amp, SUSTAIN, s.rate) v.mod.release = 0 nextSegment(v.mod, SUSTAIN, s.rate) end @native local function newVoice(): Voice return { preset = -1, key = 0, channel = 0, held = false, region = {}, pitchIn = 0, pitchOut = 0, pos = 0, gainDB = 0, panL = 0, panR = 0, playIndex = 0, loopStart = 0, loopEnd = 0, amp = newEnv(), mod = newEnv(), lpActive = false, qinv = 0, a0 = 0, a1 = 0, b1 = 0, b2 = 0, z1 = 0, z2 = 0, modlfo = { untilStart = 0, level = 0, delta = 0 }, viblfo = { untilStart = 0, level = 0, delta = 0 }, } end @native local function newChannel(): Channel return { preset = 1, bank = 0, pitchWheel = 8192, midiPan = 8192, midiVolume = 16383, midiExpression = 16383, midiRPN = 0xFFFF, midiData = 0, sustain = false, panOffset = 0, gainDB = 0, pitchRange = 2, tuning = 0, } end @native function Synth.new(sf: any, rate: number, gain: number?, maxVoices: number?): State local lookup: { [number]: number } = {} for i, p in sf.presets do local k = p.bank * 128 + p.preset if lookup[k] == nil then lookup[k] = i end end local s: State = { presets = sf.presets, lookup = lookup, samples = sf.samples, rate = rate, gainDB = gain2db(gain or 0.5), voices = {}, maxVoices = maxVoices or 256, playIndex = 0, channels = {}, } for ch = 1, 16 do s.channels[ch] = newChannel() end for ch = 0, 15 do Synth.program(s, ch, 0) end return s end @native local function presetIndex(s: State, bank: number, preset: number): number return s.lookup[bank * 128 + preset] or -1 end @native function Synth.noteOn(s: State, ch: number, key: number, velocity: number) local c = s.channels[ch + 1] if not c then return end if velocity <= 0 then Synth.noteOff(s, ch, key) return end local pi = c.preset local preset = s.presets[pi] if not preset then return end local vel = math.min(velocity, 127) / 127 local midiVel = floor(vel * 127) local rate = s.rate local voices = s.voices local playIndex = s.playIndex s.playIndex += 1 for _, region in preset.regions do if key < region.lokey or key > region.hikey or midiVel < region.lovel or midiVel > region.hivel then continue end local voice: Voice? = nil if region.group ~= 0 then for _, v in voices do if v.preset == pi and v.region.group == region.group then voiceEndQuick(s, v) elseif v.preset == -1 and not voice then voice = v end end else for _, v in voices do if v.preset == -1 then voice = v break end end end if not voice then if #voices < s.maxVoices then local v = newVoice() table.insert(voices, v) voice = v else local best = -1e18 for _, v in voices do if v.amp.segment == RELEASE then local done = releaseSamples(v.amp, rate) - v.amp.untilNext if done > best then best, voice = done, v end end end if not voice then continue end end end local v = voice :: Voice v.region = region v.preset = pi v.key = key v.channel = ch v.playIndex = playIndex v.held = false v.gainDB = s.gainDB - region.attenuation - gain2db(1 / vel) + c.gainDB calcPitch(v, channelShift(c), rate) setPan(v, region.pan + c.panOffset) v.pos = region.offset local doLoop = region.loopMode ~= LOOP_NONE and region.loopStart < region.loopEnd v.loopStart = if doLoop then region.loopStart else 0 v.loopEnd = if doLoop then region.loopEnd else 0 envSetup(v.amp, region, "a", key, midiVel, true, rate) envSetup(v.mod, region, "m", key, midiVel, false, rate) local fc = if region.filterFc <= 13500 then cents2Hz(region.filterFc) / rate else 1 v.qinv = 1 / 10 ^ ((region.filterQ / 10) / 20) v.z1, v.z2 = 0, 0 v.lpActive = fc < 0.499 if v.lpActive then lowpassSetup(v, fc) end lfoSetup(v.modlfo, region.delayModLFO, region.freqModLFO, rate) lfoSetup(v.viblfo, region.delayVibLFO, region.freqVibLFO, rate) end end @native function Synth.noteOff(s: State, ch: number, key: number) local c = s.channels[ch + 1] if not c then return end local first = -1 for _, v in s.voices do if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held then if first == -1 or v.playIndex < first then first = v.playIndex end end end if first == -1 then return end for _, v in s.voices do if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held and v.playIndex == first then if c.sustain then v.held = true else voiceEnd(s, v) end end end end @native local function applyPitch(s: State, ch: number, c: Channel) local shift = channelShift(c) for _, v in s.voices do if v.preset ~= -1 and v.channel == ch then calcPitch(v, shift, s.rate) end end end @native local function setVolume(s: State, ch: number, c: Channel, volume: number) local db = gain2db(volume) if db == c.gainDB then return end local change = db - c.gainDB for _, v in s.voices do if v.preset ~= -1 and v.channel == ch then v.gainDB += change end end c.gainDB = db end @native local function setChannelPan(s: State, ch: number, c: Channel, pan: number) for _, v in s.voices do if v.preset ~= -1 and v.channel == ch then setPan(v, v.region.pan + pan - 0.5) end end c.panOffset = pan - 0.5 end @native local function setTuning(s: State, ch: number, c: Channel, tuning: number) if c.tuning ~= tuning then c.tuning = tuning applyPitch(s, ch, c) end end @native local function setPitchRange(s: State, ch: number, c: Channel, range: number) if c.pitchRange ~= range then c.pitchRange = range if c.pitchWheel ~= 8192 then applyPitch(s, ch, c) end end end @native local function setSustain(s: State, ch: number, c: Channel, on: boolean) if c.sustain == on then return end c.sustain = on if on then return end for _, v in s.voices do if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE and v.held then voiceEnd(s, v) end end end -- channel 9: drums (bank 128) @native function Synth.program(s: State, ch: number, program: number) local c = s.channels[ch + 1] if not c then return end local bank = c.bank % 32768 local idx if ch == 9 then idx = presetIndex(s, 128 + bank, program) if idx == -1 then idx = presetIndex(s, 128, program) end if idx == -1 then idx = presetIndex(s, 128, 0) end if idx == -1 then idx = presetIndex(s, bank, program) end else idx = presetIndex(s, bank, program) end if idx == -1 then idx = presetIndex(s, 0, program) end if idx ~= -1 then c.preset = idx end end @native function Synth.pitchBend(s: State, ch: number, value: number) local c = s.channels[ch + 1] if not c or c.pitchWheel == value then return end c.pitchWheel = value applyPitch(s, ch, c) end @native function Synth.control(s: State, ch: number, cc: number, value: number) local c = s.channels[ch + 1] if not c then return end local volume, pan, data = false, false, false if cc == 7 then c.midiVolume = c.midiVolume % 128 + value * 128 volume = true elseif cc == 39 then c.midiVolume = c.midiVolume - c.midiVolume % 128 + value volume = true elseif cc == 11 then c.midiExpression = c.midiExpression % 128 + value * 128 volume = true elseif cc == 43 then c.midiExpression = c.midiExpression - c.midiExpression % 128 + value volume = true elseif cc == 10 then c.midiPan = c.midiPan % 128 + value * 128 pan = true elseif cc == 42 then c.midiPan = c.midiPan - c.midiPan % 128 + value pan = true elseif cc == 6 then c.midiData = c.midiData % 128 + value * 128 data = true elseif cc == 38 then c.midiData = c.midiData - c.midiData % 128 + value data = true elseif cc == 0 then c.bank = 0x8000 + value -- bank select MSB alone acts like LSB (as tsf.h) elseif cc == 32 then c.bank = (if c.bank >= 0x8000 then (c.bank % 128) * 128 else 0) + value elseif cc == 101 then local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN c.midiRPN = rpn % 128 + value * 128 elseif cc == 100 then local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN c.midiRPN = rpn - rpn % 128 + value elseif cc == 98 or cc == 99 then c.midiRPN = 0xFFFF elseif cc == 64 then setSustain(s, ch, c, value >= 64) elseif cc == 120 then for _, v in s.voices do if v.preset ~= -1 and v.channel == ch and (v.amp.segment < RELEASE or v.amp.release ~= 0) then voiceEndQuick(s, v) end end elseif cc == 123 then for _, v in s.voices do if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE then voiceEnd(s, v) end end elseif cc == 121 then c.midiVolume, c.midiExpression, c.midiPan, c.bank, c.midiRPN, c.midiData = 16383, 16383, 8192, 0, 0xFFFF, 0 setVolume(s, ch, c, 1) setChannelPan(s, ch, c, 0.5) setPitchRange(s, ch, c, 2) setTuning(s, ch, c, 0) end if volume then -- the cube gives a decent MIDI volume curve (tsf.h) setVolume(s, ch, c, ((c.midiVolume / 16383) * (c.midiExpression / 16383)) ^ 3) elseif pan then setChannelPan(s, ch, c, c.midiPan / 16383) elseif data then if c.midiRPN == 0 then setPitchRange(s, ch, c, c.midiData // 128 + 0.01 * (c.midiData % 128)) elseif c.midiRPN == 1 then local t = c.tuning setTuning(s, ch, c, (if t < 0 then math.ceil(t) else floor(t)) + (c.midiData - 8192) / 8192) elseif c.midiRPN == 2 and cc == 6 then local t = c.tuning setTuning(s, ch, c, (value - 64) + (t - (if t < 0 then math.ceil(t) else floor(t)))) end end end @native function Synth.midi(s: State, status: number, d1: number, d2: number) local kind, ch = status // 16, status % 16 if kind == 9 then Synth.noteOn(s, ch, d1, d2) elseif kind == 8 then Synth.noteOff(s, ch, d1) elseif kind == 11 then Synth.control(s, ch, d1, d2) elseif kind == 12 then Synth.program(s, ch, d1) elseif kind == 14 then Synth.pitchBend(s, ch, d1 + d2 * 128) end end @native function Synth.reset(s: State) for _, v in s.voices do v.preset = -1 end for ch = 1, 16 do s.channels[ch] = newChannel() end for ch = 0, 15 do Synth.program(s, ch, 0) end end @native function Synth.active(s: State): number local n = 0 for _, v in s.voices do if v.preset ~= -1 then n += 1 end end return n end @native local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSamples: number) local region = v.region local input = s.samples local rate = s.rate local modEnvToPitch, modEnvToFilterFc = region.modEnvToPitch, region.modEnvToFilterFc local modLfoToPitch, modLfoToFilterFc, modLfoToVolume = region.modLfoToPitch, region.modLfoToFilterFc, region.modLfoToVolume local vibLfoToPitch = region.vibLfoToPitch local updateModEnv = modEnvToPitch ~= 0 or modEnvToFilterFc ~= 0 local updateModLfo = v.modlfo.delta ~= 0 and (modLfoToPitch ~= 0 or modLfoToFilterFc ~= 0 or modLfoToVolume ~= 0) local updateVibLfo = v.viblfo.delta ~= 0 and vibLfoToPitch ~= 0 local loopStart, loopEnd = v.loopStart, v.loopEnd local isLooping = loopStart < loopEnd local endD = region.stop local loopEndD = loopEnd + 1 local loopLen = loopEnd - loopStart + 1 local pos = v.pos local lpActive, a0, a1, b1, b2, z1, z2 = v.lpActive, v.a0, v.a1, v.b1, v.b2, v.z1, v.z2 local dynamicLowpass = modLfoToFilterFc ~= 0 or modEnvToFilterFc ~= 0 local dynamicPitch = modLfoToPitch ~= 0 or modEnvToPitch ~= 0 or vibLfoToPitch ~= 0 local dynamicGain = modLfoToVolume ~= 0 local filterFc = region.filterFc local pitchRatio = if dynamicPitch then 0 else tc2s(v.pitchIn) * v.pitchOut local noteGain = if dynamicGain then 0 else db2gain(v.gainDB) local o = frame * 8 while numSamples > 0 do local block = if numSamples > BLOCK then BLOCK else numSamples numSamples -= block if dynamicLowpass then local fres = filterFc + v.modlfo.level * modLfoToFilterFc + v.mod.level * modEnvToFilterFc local fc = if fres <= 13500 then cents2Hz(fres) / rate else 1 lpActive = fc < 0.499 if lpActive then lowpassSetup(v, fc) a0, a1, b1, b2 = v.a0, v.a1, v.b1, v.b2 end end if dynamicPitch then pitchRatio = tc2s(v.pitchIn + (v.modlfo.level * modLfoToPitch + v.viblfo.level * vibLfoToPitch + v.mod.level * modEnvToPitch)) * v.pitchOut end if dynamicGain then noteGain = db2gain(v.gainDB + v.modlfo.level * modLfoToVolume * 0.1) end local gainMono = noteGain * v.amp.level envProcess(v.amp, block, rate) if updateModEnv then envProcess(v.mod, block, rate) end if updateModLfo then lfoProcess(v.modlfo, block) end if updateVibLfo then lfoProcess(v.viblfo, block) end -- ramp the gain across the block to the envelope's next level (tsf.h steps it per block: zipper noise) local gainNext = noteGain * v.amp.level local step = (gainNext - gainMono) / block local panL, panR = v.panL, v.panR local g = gainMono local k = block while k > 0 and pos < endD do k -= 1 local ip = floor(pos) local np = if ip >= loopEnd and isLooping then loopStart else ip + 1 local s0 = readf32(input, ip * 4) local val = s0 + (readf32(input, np * 4) - s0) * (pos - ip) if lpActive then local y = val * a0 + z1 z1 = val * a1 + z2 - b1 * y z2 = val * a0 - b2 * y val = y end val *= g g += step writef32(out, o, readf32(out, o) + val * panL) writef32(out, o + 4, readf32(out, o + 4) + val * panR) o += 8 pos += pitchRatio if pos >= loopEndD and isLooping then pos -= loopLen end end o += k * 8 if not (pos < endD) or v.amp.segment == DONE then v.preset = -1 return end end v.pos = pos v.lpActive, v.z1, v.z2 = lpActive, z1, z2 end @native function Synth.render(s: State, out: buffer, frame: number, n: number) local room = blen(out) // 8 - frame if frame < 0 or room <= 0 then return end if n > room then n = room end if n <= 0 then return end -- the sample buffer must hold every region's range + the pad sample (checked once against hand-made SoundFonts) local count = blen(s.samples) // 4 - 1 for _, v in s.voices do if v.preset ~= -1 then local r = v.region if r.stop > count or r.loopEnd > count or r.offset < 0 or r.loopStart < 0 or v.pos < 0 then v.preset = -1 else voiceRender(s, v, out, frame, n) end end end end return Synth end __FILES["codecs/audio/Stream"] = function() -- codecs/audio/Stream: the streaming Types.Decoder over a packetised codec (gapless trim, seeking with pre-roll). -- New in rosetta. local Err = __include("core/Err") local Stream = {} type Spec = { count: number, start: (i: number) -> number, decode: (i: number) -> (number?, Err.Err?), pcm: () -> { number } | buffer, reset: () -> (), skip: number?, stop: number?, preroll: number?, cumulative: boolean?, -- frames after a packet = frames before + its output (default: start(i) + its output) scale: number?, ints: boolean?, } function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) local sr, ch = dec.sampleRate, dec.channels local count = spec.count local skip = spec.skip or 0 local stopAt = spec.stop or spec.start(count + 1) local frames = math.max(0, stopAt - skip) local preroll = spec.preroll or 0 local decodeP, pcmOf, startOf = spec.decode, spec.pcm, spec.start local nextPacket = 1 local decoded = 0 local pendPos, pendN = 0, 0 local dropUntil = skip local pos = 0 local failed: Err.Err? = nil dec.error = nil local function fill(): boolean while true do if nextPacket > count or decoded >= stopAt then return false end local i = nextPacket nextPacket += 1 local first = if spec.cumulative then decoded else startOf(i) local n, e = decodeP(i) if not n then failed = e or Err.new(Err.CORRUPT, "packet " .. i .. " failed") dec.error = failed return false end decoded = first + n local a = math.max(first, dropUntil) local b = math.min(decoded, stopAt) if b > a then pendPos, pendN = a - first, b - first return true end end end local scale = spec.scale or 1 local function pull(n: number, out: buffer?, asInt: boolean): (buffer, number) local want = math.max(0, math.floor(n)) local need = want * ch * 4 local ob = if out and buffer.len(out) >= need then out else buffer.create(need) local got = 0 local writef32, writei32 = buffer.writef32, buffer.writei32 while got < want do if pendPos >= pendN then if failed or not fill() then break end end local take = math.min(want - got, pendN - pendPos) local src = pcmOf() local q = got * ch * 4 local s = pendPos * ch if type(src) == "buffer" then if scale == 1 and not asInt then buffer.copy(ob, q, src, s * 4, take * ch * 4) else for k = 0, take * ch - 1 do local v = buffer.readf32(src, (s + k) * 4) if asInt then writei32(ob, q, v) else writef32(ob, q, v * scale) end q += 4 end end elseif asInt then for k = 1, take * ch do writei32(ob, q, src[s + k]) q += 4 end elseif scale == 1 then for k = 1, take * ch do writef32(ob, q, src[s + k]) q += 4 end else for k = 1, take * ch do writef32(ob, q, src[s + k] * scale) q += 4 end end pendPos += take got += take end pos += got return ob, got end function dec.read(_self: any, n: number, out: buffer?): (buffer, number) return pull(n, out, false) end if spec.ints then function dec.readInt(_self: any, n: number, out: buffer?): (buffer, number) return pull(n, out, true) end end function dec.seek(_self: any, seconds: number) local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0 local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip local lo, hi, found = 1, count, 1 while lo <= hi do local mid = (lo + hi) // 2 if startOf(mid) <= target then found = mid lo = mid + 1 else hi = mid - 1 end end found = math.max(1, found - preroll) spec.reset() nextPacket = found decoded = if count > 0 then startOf(found) else 0 dropUntil = target pendPos, pendN = 0, 0 failed = nil dec.error = nil pos = target - skip end function dec.position(_self: any): number return pos / sr end if count > 0 and frames > 0 and not fill() and failed then return nil, failed end return dec, nil end return Stream end __FILES["codecs/audio/Tracker"] = function() -- codecs/audio/Tracker: the shared tracker engine behind music/mod, s3m, xm and it, and the formats mapped onto them. -- Written from the format documents (ProTracker 2.3, the XM spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / -- OpenMPT were used only as reference players for tests. -- -- Pattern cells are 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 = C-0; C-4 = 49 -- plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5 speed), 253 note fade, 254 note cut, -- 255 key off. MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored; S3M / IT effects 1..26 (A = 1), -- S3M volume 0 = none else volume + 1, IT volume byte + 1 (0 = none). Extension effects (Tracker.EXT): 0x40 / 0x41 note -- slide up / down, 0x42 / 0x43 with retrigger (param = ticks per step << 4 | semitones), 0x44 / 0x45 auto portamento -- up / down (669), 0x46 frequency adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED). -- -- Pitch: linear P = (ref - note) * 64 - transpose, frequency = base * 2^(-P/768). Amiga: P = 1712 * 8363 / base * -- 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add 4 per effect unit in both). -- MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT: base = c5speed, ref 61. local Err = __include("core/Err") local Types = __include("Types") local Player = __include("codecs/audio/Tracker/Player") local Mixer = __include("codecs/audio/Tracker/Mixer") local Pcm = __include("codecs/audio/Tracker/Pcm") local Tables = __include("codecs/audio/Tracker/Tables") local Tracker = {} Tracker.Pcm = Pcm Tracker.Tables = Tables type Envelope = { enabled: boolean, ticks: { number }, values: { number }, loop: boolean, loopStart: number, loopEnd: number, sustain: boolean, susStart: number, susEnd: number, carry: boolean?, filter: boolean?, raw: any?, } type Pattern = { rows: number, data: buffer } type RenderOptions = { sampleRate: number?, interpolation: ("linear" | "none")?, stereoSeparation: number?, loop: boolean?, maxDuration: number?, } local CELL = 5 Tracker.EXT = Player.EXT Tracker.st2Tempo = Tables.st2Tempo local FAMILIES = { mod = true, s3m = true, xm = true, it = true } function Tracker.family(m: any): string? local f = m.engine or m.format return if type(f) == "string" and FAMILIES[f] then f else nil end function Tracker.newModule(format: string, channels: number, engine: string?): any local fam = engine or format local m = { kind = "music", format = format, engine = engine, title = "", channels = channels, speed = 6, tempo = 125, globalVolume = 128, mixVolume = 48, order = {}, restart = 0, linear = fam == "xm" or fam == "it", instrumentMode = fam == "xm" or fam == "it", flags = {}, channelPan = {}, channelVolume = {}, channelMute = {}, patterns = {}, instruments = {}, samples = {}, meta = {}, render = Tracker.renderMethod, } for i = 1, channels do m.channelVolume[i] = 64 if fam == "mod" then local k = (i - 1) % 4 m.channelPan[i] = if k == 0 or k == 3 then 64 else 192 -- the Amiga's L R R L, at OpenMPT's default width else m.channelPan[i] = 128 end end return m end function Tracker.newPattern(rows: number, channels: number): Pattern return { rows = rows, data = buffer.create(rows * channels * CELL) } end function Tracker.newSample(name: string?): any return { name = name or "", data = buffer.create(0), length = 0, channels = 1, bits = 8, loopStart = 0, loopEnd = 0, loopType = 0, susStart = 0, susEnd = 0, susType = 0, volume = 64, globalVolume = 64, pan = nil :: number?, c5speed = 8363, relativeNote = 0, finetune = 0, vibType = 0, vibSweep = 0, vibDepth = 0, vibRate = 0, } end function Tracker.newEnvelope(): Envelope return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 } end function Tracker.newInstrument(name: string?): any local sm, nm = table.create(120, 0), table.create(120, 0) for i = 1, 120 do nm[i] = i end return { name = name or "", sampleMap = sm, noteMap = nm, volEnv = nil :: Envelope?, panEnv = nil :: Envelope?, pitchEnv = nil :: Envelope?, fadeout = 0, nna = 0, dct = 0, dca = 0, globalVolume = 128, pan = nil :: number?, pps = 0, ppc = 60, cutoff = nil :: number?, resonance = nil :: number?, vibType = 0, vibSweep = 0, vibDepth = 0, vibRate = 0, } end function Tracker.cell(m: any, pattern: number, row: number, channel: number): (number?, number, number, number, number) local p = m.patterns[pattern + 1] if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then return nil, 0, 0, 0, 0 end local o = (row * m.channels + channel - 1) * CELL local d = p.data return buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) end function Tracker.setCell(m: any, pattern: number, row: number, channel: number, note: number, ins: number, vol: number, fx: number, param: number): boolean local p = m.patterns[pattern + 1] if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then return false end local o = (row * m.channels + channel - 1) * CELL local d = p.data buffer.writeu8(d, o, note % 256) buffer.writeu8(d, o + 1, ins % 256) buffer.writeu8(d, o + 2, vol % 256) buffer.writeu8(d, o + 3, fx % 256) buffer.writeu8(d, o + 4, param % 256) return true end local function num(v: any, lo: number, hi: number): boolean return type(v) == "number" and v == v and v >= lo and v <= hi end local function fixEnvelope(e: any): (any, string?) if e == nil then return nil end if type(e) ~= "table" or type(e.ticks) ~= "table" or type(e.values) ~= "table" then return nil, "bad envelope" end local n = math.min(#e.ticks, #e.values) local last = -1 for i = 1, n do local t, v = e.ticks[i], e.values[i] if not num(t, 0, 1e6) or not num(v, -64, 64) or t <= last then -- points must go forward: keep the valid prefix n = i - 1 break end last = t end for i = #e.ticks, n + 1, -1 do e.ticks[i] = nil end for i = #e.values, n + 1, -1 do e.values[i] = nil end if n == 0 then e.enabled = false end local function idx(v: any): number return if num(v, 1, math.max(1, n)) then math.floor(v) else 1 end e.loopStart, e.loopEnd = idx(e.loopStart), idx(e.loopEnd) e.susStart, e.susEnd = idx(e.susStart), idx(e.susEnd) if e.loopEnd < e.loopStart then e.loop = false end if e.susEnd < e.susStart then e.sustain = false end return e end local function fixLoop(s0: any, e0: any, t0: any, len: number): (number, number, number) if not num(t0, 0, 2) or t0 == 0 or not num(s0, -2 ^ 52, 2 ^ 52) or not num(e0, -2 ^ 52, 2 ^ 52) then return 0, 0, 0 end local s: number = math.floor(math.clamp(s0, 0, len)) local e: number = math.floor(math.clamp(e0, 0, len)) local t: number = math.floor(t0) if e - s < 1 or t == 0 then return 0, 0, 0 end if t == 2 and e - s < 2 then t = 1 end return s, e, t end function Tracker.validate(m: any): (boolean?, Err.Err?) if type(m) ~= "table" then return nil, Err.new(Err.ARG, "not a module") end if not Tracker.family(m) then return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.engine or m.format)) end if m.preamp ~= nil and not num(m.preamp, 0, 256) then m.preamp = nil end if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then return nil, Err.new(Err.ARG, "bad channel count") end if type(m.order) ~= "table" or type(m.patterns) ~= "table" or type(m.samples) ~= "table" then return nil, Err.new(Err.ARG, "module without order / patterns / samples") end m.instruments = if type(m.instruments) == "table" then m.instruments else {} m.flags = if type(m.flags) == "table" then m.flags else {} m.channelPan = if type(m.channelPan) == "table" then m.channelPan else {} m.channelVolume = if type(m.channelVolume) == "table" then m.channelVolume else {} m.channelMute = if type(m.channelMute) == "table" then m.channelMute else {} for i = 1, m.channels do local p = m.channelPan[i] if p ~= 512 and not num(p, 0, 256) then m.channelPan[i] = 128 end if not num(m.channelVolume[i], 0, 64) then m.channelVolume[i] = 64 end end m.speed = if num(m.speed, 1, 255) then math.floor(m.speed) else 6 m.tempo = if num(m.tempo, 1, 1000) then m.tempo else 125 m.globalVolume = if num(m.globalVolume, 0, 128) then m.globalVolume else 128 m.mixVolume = if num(m.mixVolume, 0, 256) then m.mixVolume else 48 m.restart = if num(m.restart, 0, 1e6) then math.floor(m.restart) else 0 for i, o in m.order do if not num(o, 0, 255) then return nil, Err.new(Err.ARG, "bad order entry " .. i) end end for i, p in m.patterns do if type(p) ~= "table" or not num(p.rows, 1, 1024) or type(p.data) ~= "buffer" or buffer.len(p.data) < p.rows * m.channels * CELL then return nil, Err.new(Err.ARG, "bad pattern " .. (i - 1)) end end for i, s in m.samples do if type(s) ~= "table" then return nil, Err.new(Err.ARG, "bad sample " .. i) end local nch = if s.channels == 2 then 2 else 1 s.channels = nch if not num(s.length, 0, 2 ^ 31) or type(s.data) ~= "buffer" or buffer.len(s.data) < math.floor(s.length) * nch * 4 then return nil, Err.new(Err.ARG, "sample " .. i .. ": data shorter than its length") end s.length = math.floor(s.length) s.loopStart, s.loopEnd, s.loopType = fixLoop(s.loopStart or 0, s.loopEnd or 0, s.loopType or 0, s.length) s.susStart, s.susEnd, s.susType = fixLoop(s.susStart or 0, s.susEnd or 0, s.susType or 0, s.length) s.volume = if num(s.volume, 0, 64) then s.volume else 64 s.globalVolume = if num(s.globalVolume, 0, 64) then s.globalVolume else 64 if s.pan ~= nil and not num(s.pan, 0, 256) then s.pan = nil end s.c5speed = if num(s.c5speed, 1, 1e7) then s.c5speed else 8363 s.relativeNote = if num(s.relativeNote, -128, 127) then s.relativeNote else 0 s.finetune = if num(s.finetune, -128, 127) then s.finetune else 0 end for i, ins in m.instruments do if type(ins) ~= "table" or type(ins.sampleMap) ~= "table" or type(ins.noteMap) ~= "table" then return nil, Err.new(Err.ARG, "bad instrument " .. i) end for n = 1, 120 do if not num(ins.sampleMap[n], 0, 1e6) then ins.sampleMap[n] = 0 end if not num(ins.noteMap[n], 1, 120) then ins.noteMap[n] = n end end local err ins.volEnv, err = fixEnvelope(ins.volEnv) if err then return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) end ins.panEnv, err = fixEnvelope(ins.panEnv) if err then return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) end ins.pitchEnv, err = fixEnvelope(ins.pitchEnv) if err then return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) end ins.fadeout = if num(ins.fadeout, 0, 65535) then ins.fadeout else 0 ins.globalVolume = if num(ins.globalVolume, 0, 128) then ins.globalVolume else 128 if ins.pan ~= nil and not num(ins.pan, 0, 256) then ins.pan = nil end if ins.cutoff ~= nil and not num(ins.cutoff, 0, 127) then ins.cutoff = nil end if ins.resonance ~= nil and not num(ins.resonance, 0, 127) then ins.resonance = nil end end return true, nil end local Decoder = {} Decoder.__index = Decoder function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?) local ok, err = Tracker.validate(m) if not ok then return nil, err end local sr = opts and opts.sampleRate or 44100 local maxFrames = (opts and opts.maxDuration or 3600) * sr local st = Player.new(m, sr, { stereoSeparation = 100 }) local frames = 0 while frames < maxFrames do local f = Player.tick(st) if f == 0 and st.ended then break end frames += f end return math.min(frames, maxFrames) / sr, nil end local function newPlayer(self: any) self.st = Player.new(self.module, self.sampleRate, self.opts) self.st.ramp = math.max(1, math.floor(self.sampleRate * 0.0015)) self.left = 0 self.pos = 0 end function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?) local o: RenderOptions = opts or {} local sr = o.sampleRate or 44100 if type(sr) ~= "number" or sr < 1000 or sr > 384000 then return nil, Err.new(Err.ARG, "sampleRate must be 1000..384000") end local seconds, err = Tracker.duration(m, o) if not seconds then return nil, err end local frames = math.floor(seconds * sr + 0.5) local self = setmetatable({ sampleRate = sr, channels = 2, frames = frames, duration = frames / sr, bitrate = 0, tags = { title = m.title or "" }, module = m, opts = o, linear = o.interpolation ~= "none", maxFrames = (o.maxDuration or 3600) * sr, st = nil :: any, left = 0, pos = 0, }, Decoder) newPlayer(self) return self :: any, nil end function Tracker.renderMethod(self: any, opts: RenderOptions?): Types.Decoder local dec = Tracker.render(self, opts) return dec :: any end local function run(self: any, out: buffer?, n: number): number local st = self.st local done = 0 while done < n do if self.left <= 0 then if self.pos + done >= self.maxFrames then break end local f = Player.tick(st) if f == 0 and st.ended then break end self.left = f if f == 0 then continue end end local k = math.min(self.left, n - done) Mixer.mix(st, out, done, k, self.linear) self.left -= k done += k end self.pos += done return done end function Decoder.read(self: any, n: number, out: buffer?): (buffer, number) n = math.max(0, math.floor(tonumber(n) or 0)) local o = out if o == nil or buffer.len(o) < n * 8 then o = buffer.create(n * 8) else buffer.fill(o, 0, 0, n * 8) end local got = run(self, o, n) return o :: buffer, got end function Decoder.seek(self: any, seconds: number) local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate)) newPlayer(self) local chunk = 65536 while self.pos < target do local got = run(self, nil, math.min(chunk, target - self.pos)) if got == 0 then break end end for _, v in self.st.voices do v.gl, v.gr = 0, 0 end end function Decoder.position(self: any): number return self.pos / self.sampleRate end return Tracker end __FILES["codecs/audio/Tracker/Load"] = function() -- codecs/audio/Tracker/Load: helpers mapping other tracker formats' effects onto the engine's S3M / IT or MOD / XM families. -- Ported from OpenMPT's ModCommand helpers (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight, -- CPattern::WriteEffect; BSD licence, licenses/openmpt-LICENSE.txt). local Err = __include("core/Err") local Player = __include("codecs/audio/Tracker/Player") local Pcm = __include("codecs/audio/Tracker/Pcm") local Tables = __include("codecs/audio/Tracker/Tables") local Load = {} local EXT = Player.EXT local IT: { [string]: number } = { speed = 1, jump = 2, ["break"] = 3, volslide = 4, portadown = 5, portaup = 6, toneporta = 7, vibrato = 8, tremor = 9, arpeggio = 10, vibratovol = 11, toneportavol = 12, chanvol = 13, chanvolslide = 14, offset = 15, panslide = 16, retrig = 17, tremolo = 18, s3mex = 19, tempo = 20, finevibrato = 21, globalvol = 22, globalvolslide = 23, panning8 = 24, panbrello = 25, noteslideup = EXT.NOTE_SLIDE_UP, noteslidedown = EXT.NOTE_SLIDE_DOWN, noteslideupretrig = EXT.NOTE_SLIDE_UP_RETRIG, noteslidedownretrig = EXT.NOTE_SLIDE_DOWN_RETRIG, autoportaup = EXT.AUTO_PORTA_UP, autoportadown = EXT.AUTO_PORTA_DOWN, freqadjust = EXT.FREQ_ADJUST, } Load.IT = IT -- OpenMPT's effect weights (low to high): which of two effects a cell keeps when only one fits local WEIGHT: { [string]: number } = {} for i, n in { "none", "keyoff", "tremolo", "finevibrato", "vibrato", "panbrello", "s3mex", "modex", "panslide", "panning8", "noteslideupretrig", "noteslideup", "noteslidedownretrig", "noteslidedown", "portaup", "autoportaup", "portadown", "autoportadown", "volslide", "vibratovol", "volume", "volume8", "offset", "tremor", "retrig", "arpeggio", "toneporta", "toneportavol", "chanvolslide", "chanvol", "globalvolslide", "globalvol", "tempo", "speed", "jump", "break", } do WEIGHT[n] = i end local GLOBAL = { jump = true, ["break"] = true, speed = true, tempo = true, globalvol = true, globalvolslide = true } -- OpenMPT's IsGlobalCommand function Load.isGlobal(name: string?, param: number): boolean if name == nil then return false end if GLOBAL[name] then return true end local x = param // 16 if name == "modex" then return x == 0 or x == 6 or x == 0xE elseif name == "s3mex" then return x == 6 or x == 0xB or x == 0xE end return false end -- OpenMPT's ConvertModCommand local MODFX: { [number]: string } = { [0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [5] = "toneportavol", [6] = "vibratovol", [7] = "tremolo", [8] = "panning8", [9] = "offset", [10] = "volslide", [11] = "jump", [12] = "volume", [13] = "break", [14] = "modex", [15] = "tempo", [16] = "globalvol", [17] = "globalvolslide", [20] = "keyoff", [25] = "panslide", [27] = "retrig", [29] = "tremor", } function Load.modCommand(cmd: number, param: number): (string?, number) if cmd == 0 and param == 0 then return nil, 0 elseif cmd == 0xF and param < 0x20 then return "speed", param end local n = MODFX[cmd] if n == "break" then param = (param // 16) * 10 + param % 16 end return n, param end -- OpenMPT's ConvertToVolCommand (force: fit with some loss of precision) function Load.itVolume(name: string?, param: number, force: boolean): number? if name == "volume" then return math.min(param, 64) + 1 elseif name == "volume8" then if not force and param % 4 ~= 0 then return nil end return (param + 3) // 4 + 1 elseif name == "portaup" or name == "portadown" then if not force and (param % 4 ~= 0 or param >= 0xE0) then return nil end return (if name == "portaup" then 115 else 105) + math.min(param // 4, 9) + 1 elseif name == "toneporta" then if param >= 0xF0 then return 193 + 9 + 1 end for n = 0, 9 do local v = Tables.IT_VOLPORTA[n + 1] if (force and param <= v) or param == v then return 193 + n + 1 end end return nil elseif name == "vibrato" then if force then param = math.min(param % 16, 9) elseif param % 16 > 9 or param >= 16 then return nil end return 203 + param % 16 + 1 elseif name == "panning8" then return 128 + (if param == 255 then 64 else param // 4) + 1 elseif name == "volslide" then local x, y = param // 16, param % 16 if param == 0 then return nil elseif y == 0 then return 85 + math.min(x, 9) + 1 elseif x == 0 then return 95 + math.min(y, 9) + 1 elseif y == 0xF then return 65 + math.min(x, 9) + 1 elseif x == 0xF then return 75 + math.min(y, 9) + 1 end return nil elseif name == "s3mex" and param // 16 == 8 then return 128 + (param % 16) * 4 + 2 + 1 end return nil end function Load.itEffect(name: string?, param: number): (number, number) if name == nil then return 0, 0 end if name == "modex" then local x, y = param // 16, param % 16 if x == 1 then return IT.portaup, 0xF0 + y elseif x == 2 then return IT.portadown, 0xF0 + y elseif x == 9 then return IT.retrig, y elseif x == 0xA then return IT.volslide, y * 16 + 0xF elseif x == 0xB then return IT.volslide, 0xF0 + y end local s = ({ [3] = 1, [4] = 3, [5] = 2, [6] = 0xB, [7] = 4, [8] = 8, [0xC] = 0xC, [0xD] = 0xD, [0xE] = 0xE })[x] if s then return IT.s3mex, s * 16 + y end return 0, 0 end local code = IT[name] if code == nil then return 0, 0 end return code, param end -- OpenMPT's FillInTwoCommands function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number, string?, number, string?, number) if e1 ~= nil and e1 == e2 then e2 = nil -- the same effect twice: keep one (most are absolute; slides are kept once too, a simplification) end for n = 0, 3 do local v = Load.itVolume(e1, p1, n > 1) if e1 == nil or v then if v == nil and (e2 == "volume" or e2 == "volume8") then -- the engine's IT family sets volumes in the volume column only return Load.itVolume(e2, p2, true) or 0, nil, 0, nil, 0 end return v or 0, e2, p2, nil, 0 end e1, p1, e2, p2 = e2, p2, e1, p1 end if (WEIGHT[e1 :: string] or 0) > (WEIGHT[e2 :: string] or 0) then e1, p1, e2, p2 = e2, p2, e1, p1 end return 0, e2, p2, e1, p1 end -- OpenMPT's CPattern::WriteEffect function Load.writeEffect(m: any, pattern: number, row: number, fx: number, param: number, retry: string?, channel: number?, multiple: boolean?): boolean local p = m.patterns[pattern + 1] if not p then return false end local fam = m.engine or m.format local modLike = fam == "mod" or fam == "xm" local nch = m.channels local d = p.data local guard = 0 while row >= 0 and row < p.rows and guard < 1024 do guard += 1 local c0, c1 = 1, nch if channel then c0, c1 = channel, channel end for c = c0, c1 do local o = (row * nch + c - 1) * 5 if not multiple and buffer.readu8(d, o + 3) == fx and (fx ~= 0 or not modLike) then return true end end for c = c0, c1 do local o = (row * nch + c - 1) * 5 local f, q = buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) if f == 0 and (not modLike or q == 0) then buffer.writeu8(d, o + 3, fx) buffer.writeu8(d, o + 4, param) return true end end if retry == "next" then row += 1 elseif retry == "prev" then row -= 1 else return false end end return false end function Load.readSample(buf: buffer, offset: number, frames: number, spec: any, s: any, budget: { left: number }): (boolean?, Err.Err?) local nch = spec.channels or 1 local bps = spec.bits // 8 local limit = math.min(spec.limit or buffer.len(buf), buffer.len(buf)) local avail = math.max(0, limit - offset) // (nch * bps) local n = math.max(0, math.min(math.floor(frames), avail)) budget.left -= n * nch * 4 if budget.left < 0 then return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") end local data = Pcm.decode(buf, offset, n, spec) if not data then return nil, Err.new(Err.TRUNCATED, "sample data", offset) end s.data, s.length, s.bits, s.channels = data, n, spec.bits, nch return true, nil end -- S3M / MOD pattern breaks store the row as two decimal digits function Load.bcd(n: number): number n = math.clamp(math.floor(n), 0, 99) return (n // 10) * 16 + n % 10 end return Load end __FILES["codecs/audio/Tracker/Mixer"] = @native function() -- codecs/audio/Tracker/Mixer: tracker voice mixing (loops, IT sustain loops, IT two-pole resonant filter, click ramps). -- No third-party code. local floor, ceil, min = math.floor, math.ceil, math.min local readf32, writef32 = buffer.readf32, buffer.writef32 local Mixer = {} @native local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number) local data: buffer = v.data local nch = v.nch local inc = v.inc if not (inc > 0 and inc < 1e6) then return end local len = v.len local hi = len - 1 local i = 0 local guard = 0 while i < n do guard += 1 if guard > n + 64 then return end local s, e, t if v.keyOn and v.susT > 0 then s, e, t = v.susS, v.susE, v.susT elseif v.loopT > 0 then s, e, t = v.loopS, v.loopE, v.loopT else s, e, t = 0, len, 0 end local p = v.p local dir = v.dir local count if dir > 0 then local lim = if t == 2 then e - 1 else e if p >= lim then if t == 0 then v.active = false return elseif t == 1 then p = s + (p - e) % (e - s) else p = 2 * (e - 1) - p if p < s then p = s end v.dir = -1 end v.p = p continue end count = ceil((lim - p) / inc) else if p < s then p = 2 * s - p if p > e - 1 then p = e - 1 end v.p = p v.dir = 1 continue end count = floor((p - s) / inc) + 1 end if count < 1 then count = 1 end local m = min(n - i, count) local step = inc * dir if out == nil then v.p = p + step * m i += m continue end local wrapJ = if t == 1 then s else e - 1 local gl, gr = v.gl, v.gr local rl = v.rampN local dl, dr = 0, 0 local tl, tr = v.tl, v.tr if rl > 0 then dl, dr = (tl - gl) / rl, (tr - gr) / rl end local fOn = v.fOn local fa, fb0, fb1 = v.fa, v.fb0, v.fb1 local y1l, y2l, y1r, y2r = v.y1l, v.y2l, v.y1r, v.y2r local o = (off + i) * 8 for _ = 1, m do local idx = floor(p) if idx > hi then idx = hi elseif idx < 0 then idx = 0 end local j = idx + 1 if j >= e then j = wrapJ end if j > hi then j = hi end local xl, xr if nch == 1 then local a = readf32(data, idx * 4) if linear then local b = readf32(data, j * 4) xl = a + (b - a) * (p - idx) else xl = a end if fOn then local y = xl * fa + y1l * fb0 + y2l * fb1 y2l, y1l = y1l, y xl = y end xr = xl else local al = readf32(data, idx * 8) local ar = readf32(data, idx * 8 + 4) if linear then local f = p - idx xl = al + (readf32(data, j * 8) - al) * f xr = ar + (readf32(data, j * 8 + 4) - ar) * f else xl, xr = al, ar end if fOn then local y = xl * fa + y1l * fb0 + y2l * fb1 y2l, y1l = y1l, y xl = y y = xr * fa + y1r * fb0 + y2r * fb1 y2r, y1r = y1r, y xr = y end end if rl > 0 then gl += dl gr += dr rl -= 1 if rl == 0 then gl, gr = tl, tr end end writef32(out, o, readf32(out, o) + xl * gl) writef32(out, o + 4, readf32(out, o + 4) + xr * gr) o += 8 p += step end v.p = p v.gl, v.gr, v.rampN = gl, gr, rl v.y1l, v.y2l, v.y1r, v.y2r = y1l, y2l, y1r, y2r i += m end local _ = ramp end @native function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean) for _, v in st.voices do if v.active and v.data then mixVoice(v, out, off, n, linear, 0) end end end return Mixer end __FILES["codecs/audio/Tracker/Pcm"] = @native function() -- codecs/audio/Tracker/Pcm: raw 8 / 16-bit tracker sample data (signed / unsigned, XM / IT 2.15 delta coding, -- interleaved or planar stereo) <-> f32. local readu8, readi8, readu16, readi16 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16 local writef32, readf32, writeu8, writei16 = buffer.writef32, buffer.readf32, buffer.writeu8, buffer.writei16 local floor = math.floor local Pcm = {} type Spec = { bits: number, signed: boolean, delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag) channels: number?, planar: boolean?, -- stereo stored as all left then all right (XM, IT); default interleaved bigEndian: boolean?, } @native function Pcm.bytes(frames: number, spec: Spec): number return frames * (spec.channels or 1) * (spec.bits // 8) end @native function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer? local nch = spec.channels or 1 local bps = spec.bits // 8 local total = frames * nch if frames < 0 or off < 0 or off + total * bps > buffer.len(buf) then return nil end local out = buffer.create(total * 4) local planar = spec.planar and nch == 2 for c = 0, nch - 1 do local acc = 0 for i = 0, frames - 1 do local k = if planar then c * frames + i else i * nch + c local v if bps == 1 then if spec.signed then v = readi8(buf, off + k) else v = readu8(buf, off + k) - 128 end if spec.delta then acc = (acc + v + 128) % 256 - 128 v = acc end writef32(out, (i * nch + c) * 4, v / 128) else local p = off + k * 2 if spec.bigEndian then v = readu8(buf, p) * 256 + readu8(buf, p + 1) if spec.signed and v >= 32768 then v -= 65536 end elseif spec.signed then v = readi16(buf, p) else v = readu16(buf, p) end if not spec.signed then v -= 32768 end if spec.delta then acc = (acc + v + 32768) % 65536 - 32768 v = acc end writef32(out, (i * nch + c) * 4, v / 32768) end end end return out end @native function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer local nch = spec.channels or 1 local bps = spec.bits // 8 local out = buffer.create(frames * nch * bps) local planar = spec.planar and nch == 2 local avail = buffer.len(samples) // 4 for c = 0, nch - 1 do local prev = 0 for i = 0, frames - 1 do local si = i * nch + c local x = if si < avail then readf32(samples, si * 4) else 0 local k = if planar then c * frames + i else i * nch + c if bps == 1 then local v = math.clamp(floor(x * 128 + 0.5), -128, 127) local w = v if spec.delta then w = (v - prev) % 256 prev = v else w = if spec.signed then v % 256 else v + 128 end writeu8(out, k, w) else local v = math.clamp(floor(x * 32768 + 0.5), -32768, 32767) local w = v if spec.delta then w = (v - prev + 32768) % 65536 - 32768 prev = v elseif not spec.signed then w = v + 32768 if w >= 32768 then w -= 65536 end end writei16(out, k * 2, w) end end end return out end @native function Pcm.bitsNeeded(samples: buffer): number for i = 0, buffer.len(samples) // 4 - 1 do local x = readf32(samples, i * 4) * 128 if x ~= floor(x) then return 16 end end return 8 end return Pcm end __FILES["codecs/audio/Tracker/Player"] = @native function() -- codecs/audio/Tracker/Player: the tracker sequencer for the MOD, S3M, XM and IT effect families. -- Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes, ST3 TECH.DOC, ITTECH.TXT); -- no third-party code. local Tables = __include("codecs/audio/Tracker/Tables") local wave64, autoWave = Tables.wave64, Tables.autoWave local AMIGA = Tables.AMIGA local AMIGA_PAL = Tables.AMIGA_PAL local floor, min, max, clamp, abs = math.floor, math.min, math.max, math.clamp, math.abs local readu8 = buffer.readu8 local Player = {} local MOD, S3M, XM, IT = 1, 2, 3, 4 Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT } local EXT = { NOTE_SLIDE_UP = 0x40, NOTE_SLIDE_DOWN = 0x41, NOTE_SLIDE_UP_RETRIG = 0x42, NOTE_SLIDE_DOWN_RETRIG = 0x43, AUTO_PORTA_UP = 0x44, AUTO_PORTA_DOWN = 0x45, FREQ_ADJUST = 0x46, TEMPO_256 = 0x47, -- set the tempo to 256 + param (0x48: 512 + param, 0x49: 768 + param) } Player.EXT = EXT local BG_VOICES = 64 @native local function newVoice(): any return { active = false, chan = 0, bg = false, data = nil :: buffer?, nch = 1, len = 0, loopS = 0, loopE = 0, loopT = 0, susS = 0, susE = 0, susT = 0, p = 0, dir = 1, inc = 0, smp = nil :: any, smpIdx = 0, ins = nil :: any, insIdx = 0, note = 0, vol = 0, pan = 128, chanVol = 64, period = 0, periodOut = 0, base = 8363, keyOn = true, fading = false, fade = 65536, volEnvPos = 0, panEnvPos = 0, pitchEnvPos = 0, volEnvOn = true, panEnvOn = true, pitchEnvOn = true, envVol = 64, envPan = 0, envPitch = 0, avPos = 0, avAmp = 0, gl = 0, gr = 0, tl = 0, tr = 0, started = false, cutoff = 127, reso = 0, fOn = false, fa = 1, fb0 = 0, fb1 = 0, y1l = 0, y2l = 0, y1r = 0, y2r = 0, tremorMute = false, surround = false, rampN = 0, owner = 0, order = 0, } end @native local function newChannel(i: number, pan: number, vol: number): any return { idx = i, voice = nil :: any, note = 0, realNote = 0, insIdx = 0, smpIdx = 0, smp = nil :: any, vol = 0, pan = pan, basePan = pan, chanVol = vol, period = 0, target = 0, portaSpeed = 0, base = 8363, finetune = nil :: number?, fx = 0, param = 0, vcmd = 0, mPortaUp = 0, mPortaDn = 0, mFineUp = 0, mFineDn = 0, mXFineUp = 0, mXFineDn = 0, mVolSlide = 0, mFineVolUp = 0, mFineVolDn = 0, mOffset = 0, mHighOffset = 0, mPanSlide = 0, mGVolSlide = 0, mRetrig = 0, mTremor = 0, mArp = 0, mS3M = 0, mEF = 0, mChanVolSlide = 0, mTempo = 0, mVolCol = 0, mS = 0, vibSpeed = 0, vibDepth = 0, vibPos = 0, vibWave = 0, tremSpeed = 0, tremDepth = 0, tremPos = 0, tremWave = 0, panbSpeed = 0, panbDepth = 0, panbPos = 0, panbWave = 0, vibDelta = 0, tremDelta = 0, panbDelta = 0, arp = 0, loopRow = 0, loopCount = 0, retrigCount = 0, tremorCount = 0, tremorOn = true, delayTick = -1, dNote = 0, dIns = 0, dVol = 0, cutTick = -1, keyOffTick = -1, nna = -1, surround = false, cutoff = 127, reso = 0, volEnvOn = true, panEnvOn = true, pitchEnvOn = true, muted = false, triggered = false, autoPorta = 0, -- auto portamento (EXT 0x44 / 0x45): period units per tick, + down autoTone = false, hzAdd = 0, -- EXT 0x46: Hz added to the frequency (669) slideCount = 0, mNoteSlide = 0, tonePortaRow = false, } end @native function Player.new(m: any, sampleRate: number, opts: any): any local fmt = FAMILY[m.engine or m.format] or MOD local flags = m.flags local ptPeriods = fmt == MOD or flags.periods == "amiga" local st: any = { m = m, fmt = fmt, sr = sampleRate, nch = m.channels, speed = m.speed, tempo = m.tempo, gvol = m.globalVolume, linear = m.linear, insMode = m.instrumentMode and #m.instruments > 0, oldFx = m.flags.oldEffects or false, compatG = m.flags.compatGxx or false, fastSlides = flags.fastSlides or false, amigaLimits = flags.amigaLimits or false, ptPeriods = ptPeriods, hz = flags.periods == "hz", hzScale = if type(flags.hzSlide) == "number" then flags.hzSlide else 1, hzTone = if type(flags.hzTonePorta) == "number" then flags.hzTonePorta else 1, fastPortas = flags.fastPortas or false, autoTonePorta = flags.autoTonePorta or false, autoReset = flags.autoReset or false, st2Tempo = flags.st2Tempo or false, oktSlides = flags.oktSlides or false, ft2Pan = flags.panLaw == "ft2", envHold = flags.envRowHold or false, ord = 0, row = 0, tick = 0, pat = nil :: any, patIdx = -1, patDelay = 0, patDelayRep = 0, fineDelay = 0, jumpOrd = -1, ft2BreakPos = 0, breakRow = -1, loopJump = -1, ended = false, visited = {} :: { [number]: boolean }, chans = {}, voices = {}, age = 0, tickFrames = 0, frac = 0, separation = math.clamp((opts and opts.stereoSeparation or 100) / 100, 0, 2), master = 1, rows = 0, ramp = 64, amiga = if ptPeriods then AMIGA_PAL else AMIGA, loopAllowed = opts and opts.loop or false, } for i = 1, m.channels do local pan = m.channelPan[i] or 128 local cv = m.channelVolume[i] or 64 local c = newChannel(i, pan, cv) c.basePan = pan c.muted = m.channelMute[i] or false if pan == 512 then -- surround marker c.pan = 128 c.surround = true end st.chans[i] = c end for i = 1, m.channels + BG_VOICES do st.voices[i] = newVoice() end st.master = Player.masterGain(m, fmt) Player.startOrder(st, 0, 0) return st end -- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at -- volume 64 on one centred channel) @native function Player.masterGain(m: any, fmt: number): number if type(m.preamp) == "number" then return m.preamp / 128 -- OpenMPT's sample pre-amp, as set by the format's loader end if fmt == IT or fmt == S3M then return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the mix / master volume, 64 = 0.5 end if fmt == XM then return 0.375 -- OpenMPT's XM pre-amp (48 / 128), whatever the channel count end -- MOD: OpenMPT scales by the channel count (4 channels: 0.5; 2 / channels between 2 and 8) return 2 / clamp(m.channels, 2, 8) end @native function Player.startOrder(st: any, ord: number, row: number) local m = st.m local order = m.order local n = #order local guard = 0 local o = ord while true do guard += 1 if guard > n + 2 then st.ended = true return end if o >= n then o = m.restart or 0 if o >= n or o < 0 then o = 0 end if n == 0 then st.ended = true return end end local p = order[o + 1] if p == 255 then o = n -- the end marker: wrap to the restart position elseif p == 254 or m.patterns[p + 1] == nil then o += 1 else st.ord = o st.patIdx = p st.pat = m.patterns[p + 1] st.row = if row < st.pat.rows then row else 0 return end end end @native local function advanceRow(st: any) if st.stopAfterRow then st.ended = true return end local loopRow = st.loopJump if st.jumpOrd >= 0 or st.breakRow >= 0 then local o = if st.jumpOrd >= 0 then st.jumpOrd else st.ord + 1 local r = if st.breakRow >= 0 then st.breakRow else 0 st.jumpOrd, st.breakRow, st.loopJump = -1, -1, -1 st.ft2BreakPos = 0 Player.startOrder(st, o, r) return end if loopRow >= 0 then st.loopJump = -1 -- the rows inside a pattern loop are played again on purpose: forget them for the song-end check for r = loopRow, st.row do st.visited[st.ord * 1024 + r] = nil end st.row = loopRow return end st.row += 1 if st.row >= st.pat.rows then -- FT2 (XM): the next pattern starts at the row a pattern loop last jumped to (the E6x "bug" FT2 players keep) local r = if st.fmt == XM then st.ft2BreakPos else 0 st.ft2BreakPos = 0 Player.startOrder(st, st.ord + 1, r) end end @native local function notePeriod(st: any, note: number, smp: any, ft: number?): (number, number) local base, ref, tr if st.fmt == MOD or st.fmt == XM then base, ref = 8363, 49 tr = (smp.relativeNote or 0) * 64 + (ft or smp.finetune or 0) / 2 else base, ref, tr = smp.c5speed or 8363, 61, 0 if base <= 0 then base = 8363 end end local plin = (ref - note) * 64 - tr if st.hz then -- periods are frequencies (Hz, rounded as OpenMPT does): the sample's rate at C-5 return floor((smp.c5speed or 8363) * 2 ^ ((note - 61) / 12)), base end if st.ptPeriods then -- ProTracker: integer periods from the finetune tables (finetune 0 table scaled by 2^(-ft / 96), rounded) local ftp = (ft or smp.finetune or 0) / 16 local n = note + (if st.fmt == MOD or st.fmt == XM then smp.relativeNote or 0 else 0) return 4 * floor(Tables.noteToPeriod(n) * 2 ^ (-ftp / 12 / 8) + 0.5), base end if st.linear then return plin, base end return 1712 * 8363 / base * 2 ^ (plin / 768), base end @native local function arpPeriod(st: any, period: number, semis: number): number if semis == 0 then return period end if st.hz then return period * 2 ^ (semis / 12) end if st.linear then return period - semis * 64 end return period * 2 ^ (-semis / 12) end @native local function clampPeriod(st: any, c: any) if st.hz then c.period = clamp(c.period, 1, 1e6) elseif st.linear then c.period = clamp(c.period, -6000, 6000) elseif st.amigaLimits then c.period = clamp(c.period, 113 * 4, 856 * 4) else c.period = clamp(c.period, 1, 1e6) end end -- pitch slides in period units (positive: down; 4 per effect unit); in Hz mode the frequency moves units * hzSlide Hz the other way @native local function slide(st: any, c: any, units: number) if st.hz then c.period -= units * st.hzScale else c.period += units end clampPeriod(st, c) end @native local function allocVoice(st: any): any local best, bestScore = nil, math.huge for _, v in st.voices do if not v.active and v.owner == 0 then return v end if v.bg then local s = (v.vol * v.envVol * v.fade) / 1e9 + v.order * 1e-9 if s < bestScore then best, bestScore = v, s end end end if best then best.active = false return best end for _, v in st.voices do if not v.active then local c = st.chans[v.owner] if c and c.voice == v then c.voice = nil end return v end end return st.voices[1] end @native local function keyOff(st: any, v: any) if not v or not v.active then return end v.keyOn = false local ins = v.ins if st.fmt == XM then if not (ins and ins.volEnv and ins.volEnv.enabled) then v.vol = 0 local c = st.chans[v.chan] if c and c.voice == v then c.vol = 0 end else v.fading = true end elseif st.fmt == IT then if ins then local env = ins.volEnv if not (env and env.enabled and v.volEnvOn) or env.loop then v.fading = true end end end end @native local function noteFade(v: any) if v and v.active then v.fading = true end end @native local function cutVoice(v: any) if v then v.active = false end end @native local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: any) local v = c.voice if v == nil or v.bg then v = allocVoice(st) c.voice = v v.owner = c.idx end local wasActive = v.active v.active = smp.length > 0 and smp.data ~= nil v.chan = c.idx v.bg = false v.smp = smp v.smpIdx = smpIdx v.data = smp.data v.nch = smp.channels or 1 v.len = smp.length v.loopS, v.loopE, v.loopT = smp.loopStart, smp.loopEnd, smp.loopType v.susS, v.susE, v.susT = smp.susStart or 0, smp.susEnd or 0, smp.susType or 0 v.p = 0 v.dir = 1 v.ins = ins v.insIdx = insIdx v.note = note v.period = period v.periodOut = period v.base = base st.age += 1 v.order = st.age if keepEnv ~= true then if keepEnv ~= "release" then v.keyOn = true v.fading = false end v.fade = 65536 v.volEnvPos, v.panEnvPos, v.pitchEnvPos = 0, 0, 0 v.avPos, v.avAmp = 0, 0 v.envVol, v.envPan, v.envPitch = 64, 0, 0 v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true v.y1l, v.y2l, v.y1r, v.y2r = 0, 0, 0, 0 end if not wasActive then v.gl, v.gr = 0, 0 end return v end -- IT new note actions on the channel's current voice (and duplicate checks on all its voices) @native local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: number, smpIdx: number) if ins and ins.dct and ins.dct > 0 then for _, u in st.voices do if u.active and u.chan == c.idx and u.insIdx == insIdx then local dup = (ins.dct == 1 and u.note == note) or (ins.dct == 2 and u.smpIdx == smpIdx) or ins.dct == 3 if dup then local a = ins.dca or 0 if a == 0 then cutVoice(u) elseif a == 1 then keyOff(st, u) else noteFade(u) end end end end end local v = c.voice if v == nil or not v.active then return end local nna = c.nna if nna < 0 then nna = if v.ins then (v.ins.nna or 0) else 0 end if nna == 0 then -- cut: the voice is reused for the new note (a short click is avoided by its ramp from the old gains) v.active = false return end v.bg = true v.owner = 0 c.voice = nil if nna == 2 then keyOff(st, v) elseif nna == 3 then noteFade(v) end end @native local function isPorta(st: any, fx: number, vcmd: number): boolean local f = st.fmt if f == MOD then return fx == 3 or fx == 5 elseif f == XM then return fx == 3 or fx == 5 or (vcmd >= 0xF0) end -- S3M / IT: G (7) or L (12); IT volume column g (193..202, stored + 1) return fx == 7 or fx == 12 or (f == IT and vcmd >= 194 and vcmd <= 203) end @native local function resolve(st: any, insIdx: number, note: number): (any, number, any, number) local m = st.m if st.insMode then local ins = m.instruments[insIdx] if not ins or note < 1 or note > 120 then return nil, 0, ins, note end local si = ins.sampleMap[note] or 0 local rn = ins.noteMap[note] or note local smp = m.samples[si] return smp, si, ins, rn end local smp = m.samples[insIdx] return smp, insIdx, nil, note end @native local function setInstrumentDefaults(st: any, c: any, smp: any, ins: any) if smp then c.vol = smp.volume end if st.fmt == IT then -- IT: a sample's or instrument's default panning holds for its notes; the channel panning (set by the -- effects) comes back for the others local p = (smp and smp.pan) or (ins and ins.pan) c.pan = p or c.basePan if p then c.surround = false end elseif smp and smp.pan then c.pan = smp.pan c.basePan = c.pan c.surround = false end if ins and st.fmt == IT then if ins.cutoff then c.cutoff = ins.cutoff end if ins.resonance then c.reso = ins.resonance end end end @native local function sampleOffset(st: any, c: any, v: any) local f = st.fmt local fx, param = c.fx, c.param local off = -1 if (f == MOD or f == XM) and fx == 9 then if param > 0 then c.mOffset = param end off = (if f == XM then c.mOffset else param) * 256 elseif (f == S3M or f == IT) and fx == 15 then if param > 0 then c.mOffset = param end off = c.mOffset * 256 + (if f == IT then c.mHighOffset * 65536 else 0) end if off > 0 and v and v.active then if off >= v.len then if v.loopT > 0 and f ~= MOD then off = v.loopS elseif f == MOD and v.loopT > 0 then off = v.loopS else v.active = false return end end v.p = off end end @native local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: number) local f = st.fmt local m = st.m local porta = isPorta(st, c.fx, vcmd) local hasNote = note >= 1 and note <= 120 if insIdx > 0 then local valid = if st.insMode then m.instruments[insIdx] ~= nil else m.samples[insIdx] ~= nil if valid then c.insIdx = insIdx local n = if hasNote then note else c.note local smp, _, ins = resolve(st, insIdx, if n > 0 then n else 61) setInstrumentDefaults(st, c, smp, ins) if not hasNote then local v = c.voice if f == XM and v then -- an instrument number alone (FT2 / OpenMPT): the playing note's envelopes restart (key on, no -- fadeout); the new instrument applies from the next note v.keyOn, v.fading, v.fade = true, false, 65536 v.volEnvPos, v.panEnvPos, v.avPos, v.avAmp = 0, 0, 0, 0 elseif (f == MOD or f == S3M) and smp then c.smp, c.smpIdx = smp, insIdx end end elseif f == XM and hasNote then -- an empty instrument: the note stops the channel c.insIdx = insIdx if c.voice then c.voice.active = false end hasNote = false end end if hasNote then local useIns = c.insIdx local smp, smpIdx, ins, realNote = resolve(st, useIns, note) if smp == nil then if (f == MOD or f == S3M) and c.smp then smp, smpIdx = c.smp, c.smpIdx end end if smp then local ft = c.finetune local period, base = notePeriod(st, realNote, smp, ft) local v = c.voice if porta and ((v and v.active) or f == MOD or f == XM) then -- tone portamento: a new target, no new note (ProTracker / FT2 never start a note with it) c.target = period if st.fmt == IT or st.fmt == S3M then c.note = note end else if f == IT and st.insMode then newNoteAction(st, c, ins, useIns, realNote, smpIdx) end -- FT2: a note without an instrument number restarts the sample only (envelopes, key off and -- fadeout carry on); with another instrument than the playing one, its envelopes and fadeout start -- over but a key off stays local keep: any = false if f == XM and insIdx == 0 and c.voice ~= nil then keep = if c.voice.ins == ins then true else "release" end c.triggered = true c.hzAdd = 0 c.tremorOn = true c.retrigCount = 0 v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep) v.patNote = note c.period, c.target, c.base = period, period, base c.note, c.realNote = note, realNote c.smp, c.smpIdx = smp, smpIdx if insIdx > 0 or f == MOD or f == S3M then -- volume was set by the instrument; MOD / S3M keep the channel volume end if c.vibWave < 4 then c.vibPos = 0 end if c.tremWave < 4 then c.tremPos = 0 end v.cutoff, v.reso = c.cutoff, c.reso v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true c.nna = -1 sampleOffset(st, c, v) end elseif f == IT or f == XM then -- a note mapped to no sample cuts if c.voice and not porta then if f == IT and st.insMode then newNoteAction(st, c, nil, 0, note, 0) end if c.voice then c.voice.active = false end end end elseif note == 255 then if f == S3M or f == MOD then cutVoice(c.voice) elseif c.voice then keyOff(st, c.voice) end elseif note == 254 then cutVoice(c.voice) if f ~= IT then c.vol = 0 end elseif note == 253 then noteFade(c.voice) end -- the volume column's set-volume / set-panning parts (the rest runs with the effects) if vcmd > 0 then if f == S3M then c.vol = min(vcmd - 1, 64) elseif f == XM then if vcmd >= 0x10 and vcmd <= 0x50 then c.vol = vcmd - 0x10 elseif vcmd >= 0xC0 and vcmd <= 0xCF then c.pan = (vcmd - 0xC0) * 16 c.basePan = c.pan end elseif f == IT then local v = vcmd - 1 if v <= 64 then c.vol = v elseif v >= 128 and v <= 192 then c.pan = (v - 128) * 4 c.basePan = c.pan c.surround = false end end end end @native local function volSlideMod(c: any, param: number) local x, y = param // 16, param % 16 if x > 0 then c.vol = min(64, c.vol + x) else c.vol = max(0, c.vol - y) end end @native local function tonePorta(st: any, c: any, speed: number) if c.period == c.target then return end if st.hz then speed *= st.hzScale * st.hzTone end if c.period < c.target then c.period = min(c.period + speed, c.target) else c.period = max(c.period - speed, c.target) end end @native local function vibrato(st: any, c: any, scale: number) c.vibDelta = wave64(c.vibWave % 4, c.vibPos) * c.vibDepth * scale c.vibPos = (c.vibPos + c.vibSpeed) % 64 end @native local function tremolo(c: any, scale: number) c.tremDelta = floor(wave64(c.tremWave % 4, c.tremPos) * c.tremDepth * scale) c.tremPos = (c.tremPos + c.tremSpeed) % 64 end @native local function retrigVoice(st: any, c: any) local v = c.voice if v and v.smp then v.active = v.smp.length > 0 v.p = 0 v.dir = 1 end end @native local function retrigVolume(c: any, x: number) if x == 0 or x == 8 then return end local mul = Tables.RETRIG_MUL[x + 1] if mul ~= 1 then c.vol = floor(c.vol * mul) else c.vol += Tables.RETRIG_ADD[x + 1] end c.vol = clamp(c.vol, 0, 64) end -- S3M / IT D-style slide: fine parts only on tick 0, normal parts on other ticks (fast: normal parts on tick 0 too) @native local function dSlide(value: number, param: number, tick: number, fast: boolean, hi: number): number local x, y = param // 16, param % 16 if y == 0xF and x > 0 then if tick == 0 then return min(hi, value + x) end return value elseif x == 0xF and y > 0 then if tick == 0 then return max(0, value - y) end return value end if tick == 0 and not fast then return value end if y == 0 then return min(hi, value + x) elseif x == 0 then return max(0, value - y) end return value end @native local function fxModXm(st: any, c: any, tick: number) local fx, param = c.fx, c.param local xm = st.fmt == XM local x, y = param // 16, param % 16 if fx == 0 then if param ~= 0 then local k = tick % 3 c.arp = if k == 1 then x elseif k == 2 then y else 0 end elseif fx == 1 then if xm and param > 0 then c.mPortaUp = param end if tick > 0 or st.fastPortas then slide(st, c, -(if xm then c.mPortaUp else param) * 4) end elseif fx == 2 then if xm and param > 0 then c.mPortaDn = param end if tick > 0 or st.fastPortas then slide(st, c, (if xm then c.mPortaDn else param) * 4) end elseif fx == 3 or fx == 5 then if fx == 3 and param > 0 then c.portaSpeed = param end if tick > 0 or st.fastPortas then tonePorta(st, c, c.portaSpeed * 4) end elseif fx == 4 or fx == 6 then if fx == 4 then if x > 0 then c.vibSpeed = x end if y > 0 then c.vibDepth = y end end if tick > 0 then vibrato(st, c, 8 / 255) end elseif fx == 7 then if x > 0 then c.tremSpeed = x end if y > 0 then c.tremDepth = y end if tick > 0 then tremolo(c, 1 / 64) end elseif fx == 8 then if tick == 0 then c.pan = param c.basePan = c.pan c.surround = false end elseif fx == 0xB then if tick == 0 then st.jumpOrd = param if st.breakRow < 0 then st.breakRow = 0 end end elseif fx == 0xC then if tick == 0 then c.vol = min(param, 64) end elseif fx == 0xD then if tick == 0 then local r = x * 10 + y if r > 63 then r = 0 end st.breakRow = r end elseif fx == 0xE then if x == 1 then if xm and y > 0 then c.mFineUp = y end if tick == 0 then slide(st, c, -(if xm then c.mFineUp else y) * 4) end elseif x == 2 then if xm and y > 0 then c.mFineDn = y end if tick == 0 then slide(st, c, (if xm then c.mFineDn else y) * 4) end elseif x == 4 then c.vibWave = y % 8 elseif x == 6 then if tick == 0 then if y == 0 then c.loopRow = st.row elseif c.loopCount == 0 then c.loopCount = y st.loopJump = c.loopRow st.ft2BreakPos = c.loopRow else c.loopCount -= 1 if c.loopCount > 0 then st.loopJump = c.loopRow end st.ft2BreakPos = c.loopRow end end elseif x == 7 then c.tremWave = y % 8 elseif x == 8 then if tick == 0 then -- FT2 ignores E8x in XM; OpenMPT (the reference) applies it c.pan = y * 17 c.basePan = c.pan c.surround = false end elseif x == 9 then if y > 0 and tick > 0 and tick % y == 0 then retrigVoice(st, c) end elseif x == 0xA then if xm and y > 0 then c.mFineVolUp = y end if tick == 0 then c.vol = min(64, c.vol + (if xm then c.mFineVolUp else y)) end elseif x == 0xB then if xm and y > 0 then c.mFineVolDn = y end if tick == 0 then c.vol = max(0, c.vol - (if xm then c.mFineVolDn else y)) end elseif x == 0xC then if tick == y then c.vol = 0 end elseif x == 0xE then if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then st.patDelay = y end end elseif fx == 0xF then if tick == 0 then if param == 0 then if not xm then st.stopAfterRow = true -- ProTracker F00: the song stops (after this row, as OpenMPT plays it) end elseif param < 32 then st.speed = param else st.tempo = param end end elseif fx == 16 then -- G if tick == 0 then st.gvol = min(param, 64) * 2 end elseif fx == 17 then -- H if param > 0 then c.mGVolSlide = param end if tick > 0 then local p = c.mGVolSlide local px, py = p // 16, p % 16 if px > 0 then st.gvol = min(128, st.gvol + px * 2) else st.gvol = max(0, st.gvol - py * 2) end end elseif fx == 20 then -- K if tick == param then keyOff(st, c.voice) end elseif fx == 21 then -- L if tick == 0 and c.voice then c.voice.volEnvPos = param c.voice.panEnvPos = param end elseif fx == 25 then -- P if param > 0 then c.mPanSlide = param end if tick > 0 then local p = c.mPanSlide local px, py = p // 16, p % 16 if px > 0 then c.pan = min(255, c.pan + px) c.basePan = c.pan else c.pan = max(0, c.pan - py) c.basePan = c.pan end end elseif fx == 27 then -- R if x > 0 then c.mRetrig = c.mRetrig % 16 + x * 16 end if y > 0 then c.mRetrig = (c.mRetrig // 16) * 16 + y end local interval = c.mRetrig % 16 if tick == 0 and c.triggered then c.retrigCount = 0 else c.retrigCount += 1 end if interval > 0 and c.retrigCount >= interval then c.retrigCount = 0 retrigVolume(c, c.mRetrig // 16) retrigVoice(st, c) end elseif fx == 29 then -- T if param > 0 then c.mTremor = param end elseif fx == 33 then -- X if x == 1 then if y > 0 then c.mXFineUp = y end if tick == 0 then slide(st, c, -c.mXFineUp) end elseif x == 2 then if y > 0 then c.mXFineDn = y end if tick == 0 then slide(st, c, c.mXFineDn) end end end -- the volume slide half of 5xy / 6xy and Axy if fx == 0xA or fx == 5 or fx == 6 then if xm then if param > 0 then c.mVolSlide = param end if tick > 0 or st.fastSlides then volSlideMod(c, c.mVolSlide) end elseif tick > 0 or st.fastSlides then volSlideMod(c, param) end end -- tremor (XM Txy): on x + 1 ticks, off y + 1 ticks if fx == 29 and tick > 0 then local on, off = c.mTremor // 16 + 1, c.mTremor % 16 + 1 c.tremorCount %= on + off c.tremorOn = c.tremorCount < on c.tremorCount += 1 end end -- the XM volume column (everything but set volume / set panning, done by trigger) @native local function volColXm(st: any, c: any, tick: number) local v = c.vcmd if v < 0x60 then return end local hi, lo = v // 16, v % 16 if hi == 6 then if tick > 0 then c.vol = max(0, c.vol - lo) end elseif hi == 7 then if tick > 0 then c.vol = min(64, c.vol + lo) end elseif hi == 8 then if tick == 0 then c.vol = max(0, c.vol - lo) end elseif hi == 9 then if tick == 0 then c.vol = min(64, c.vol + lo) end elseif hi == 0xA then if lo > 0 then c.vibSpeed = lo end elseif hi == 0xB then if lo > 0 then c.vibDepth = lo end if tick > 0 then vibrato(st, c, 8 / 255) end elseif hi == 0xD then if tick > 0 then c.pan = max(0, c.pan - lo) c.basePan = c.pan end elseif hi == 0xE then if tick > 0 then c.pan = min(255, c.pan + lo) c.basePan = c.pan end elseif hi == 0xF then if lo > 0 then c.portaSpeed = lo * 16 end if tick > 0 then tonePorta(st, c, c.portaSpeed * 4) end end end -- the parameter after memory: IT keeps one memory per effect group, ST3 one memory for most effects @native local function mem(st: any, c: any, field: string, param: number): number if st.fmt == S3M then if param > 0 then c.mS3M = param end return c.mS3M end if param > 0 then c[field] = param end return c[field] end @native local function portaS3m(st: any, c: any, p: number, tick: number, sign: number) if p >= 0xF0 then if tick == 0 then slide(st, c, sign * (p % 16) * 4) end elseif p >= 0xE0 then if tick == 0 then slide(st, c, sign * (p % 16)) end elseif tick > 0 or st.fastPortas then slide(st, c, sign * p * 4) end end @native local function fxS3mIt(st: any, c: any, tick: number) local fx, param = c.fx, c.param local it = st.fmt == IT if fx == 1 then -- A speed if tick == 0 and param > 0 then if st.st2Tempo then st.speed, st.tempo = Tables.st2Tempo(param) else st.speed = param end end elseif fx == 2 then -- B jump if tick == 0 then st.jumpOrd = param if st.breakRow < 0 then st.breakRow = 0 end end elseif fx == 3 then -- C break if tick == 0 then st.breakRow = if it then param else (param // 16) * 10 + param % 16 end elseif fx == 4 or fx == 11 or fx == 12 then -- D volume slide (K, L: + vibrato / tone portamento) local p = mem(st, c, "mVolSlide", param) c.vol = dSlide(c.vol, p, tick, st.fastSlides, 64) elseif fx == 5 then -- E porta down local p = mem(st, c, "mEF", param) portaS3m(st, c, p, tick, 1) elseif fx == 6 then -- F porta up local p = mem(st, c, "mEF", param) portaS3m(st, c, p, tick, -1) elseif fx == 9 then -- I tremor local p = mem(st, c, "mTremor", param) if tick > 0 or not it then local on, off = p // 16, p % 16 if it and st.oldFx or not it then on, off = on + 1, off + 1 end on, off = max(on, 1), max(off, 1) c.tremorCount %= on + off c.tremorOn = c.tremorCount < on c.tremorCount += 1 end elseif fx == 10 then -- J arpeggio local p = mem(st, c, "mArp", param) local k = tick % 3 c.arp = if k == 1 then p // 16 elseif k == 2 then p % 16 else 0 elseif fx == 13 then -- M channel volume if tick == 0 and param <= 64 then c.chanVol = param end elseif fx == 14 then -- N channel volume slide local p = mem(st, c, "mChanVolSlide", param) c.chanVol = dSlide(c.chanVol, p, tick, false, 64) elseif fx == 16 then -- P panning slide (0..64 scale x 4) local p = mem(st, c, "mPanSlide", param) local pan64 = c.pan / 4 local x, y = p // 16, p % 16 if y == 0xF and x > 0 then if tick == 0 then pan64 = max(0, pan64 - x) end elseif x == 0xF and y > 0 then if tick == 0 then pan64 = min(64, pan64 + y) end elseif tick > 0 then if y == 0 then pan64 = max(0, pan64 - x) elseif x == 0 then pan64 = min(64, pan64 + y) end end c.pan = pan64 * 4 c.basePan = c.pan c.surround = false elseif fx == 17 then -- Q retrigger + volume change local p = mem(st, c, "mRetrig", param) local interval = p % 16 if interval > 0 then if tick == 0 and c.retrigCount <= 0 then c.retrigCount = interval end if tick > 0 then c.retrigCount -= 1 if c.retrigCount <= 0 then c.retrigCount = interval retrigVolume(c, p // 16) retrigVoice(st, c) end end end elseif fx == 18 then -- R tremolo if param // 16 > 0 then c.tremSpeed = param // 16 end if param % 16 > 0 then c.tremDepth = param % 16 end if tick > 0 then tremolo(c, 1 / 64) end elseif fx == 19 then -- S extended local p = if it then mem(st, c, "mS", param) else mem(st, c, "mS", param) local x, y = p // 16, p % 16 if x == 3 then c.vibWave = y % 8 elseif x == 4 then c.tremWave = y % 8 elseif x == 5 then c.panbWave = y % 8 elseif x == 6 then if tick == 0 then st.fineDelay += y end elseif x == 7 then if tick == 0 then if y <= 2 then for _, u in st.voices do if u.active and u.bg and u.chan == c.idx then if y == 0 then cutVoice(u) elseif y == 1 then keyOff(st, u) else noteFade(u) end end end elseif y <= 6 then c.nna = y - 3 else local v = c.voice if v then if y == 7 then v.volEnvOn = false elseif y == 8 then v.volEnvOn = true elseif y == 9 then v.panEnvOn = false elseif y == 10 then v.panEnvOn = true elseif y == 11 then v.pitchEnvOn = false elseif y == 12 then v.pitchEnvOn = true end end end end elseif x == 8 then if tick == 0 then c.pan = y * 17 c.basePan = c.pan c.surround = false end elseif x == 9 then if tick == 0 and y == 1 then c.surround = true end elseif x == 0xA then if tick == 0 then c.mHighOffset = y end elseif x == 0xB then if tick == 0 then if y == 0 then c.loopRow = st.row elseif c.loopCount == 0 then c.loopCount = y st.loopJump = c.loopRow else c.loopCount -= 1 if c.loopCount > 0 then st.loopJump = c.loopRow elseif it then c.loopRow = st.row + 1 end end end elseif x == 0xC then local at = if y == 0 and it then 1 else y if tick == at and (y > 0 or it) then if it then cutVoice(c.voice) end c.vol = 0 end elseif x == 0xE then if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then st.patDelay = y end end elseif fx == 20 then -- T tempo if param >= 0x20 then if tick == 0 then st.tempo = param end elseif it then if param > 0 then c.mTempo = param end local p = c.mTempo if tick > 0 then if p >= 0x10 then st.tempo = min(255, st.tempo + (p - 0x10)) else st.tempo = max(32, st.tempo - p) end end end elseif fx == 22 then -- V global volume if tick == 0 then if it then if param <= 128 then st.gvol = param end else st.gvol = min(param, 64) * 2 end end elseif fx == 23 then -- W global volume slide local p = mem(st, c, "mGVolSlide", param) st.gvol = dSlide(st.gvol, p, tick, false, 128) elseif fx == 24 then -- X panning if tick == 0 then if it then c.pan = param c.basePan = c.pan c.surround = false elseif param <= 0x80 then c.pan = param * 2 c.basePan = c.pan c.surround = false elseif param == 0xA4 then c.surround = true end end elseif fx == 25 then -- Y panbrello if param // 16 > 0 then c.panbSpeed = param // 16 end if param % 16 > 0 then c.panbDepth = param % 16 end c.panbDelta = wave64(c.panbWave % 4, c.panbPos // 4) * c.panbDepth / 16 c.panbPos = (c.panbPos + c.panbSpeed) % 256 elseif fx == 26 then -- Z MIDI macro: the default IT macros (Z00..Z7F cutoff, Z80..Z8F resonance) if tick == 0 then if param < 0x80 then c.cutoff = param elseif param < 0x90 then c.reso = (param - 0x80) * 8 end if c.voice then c.voice.cutoff, c.voice.reso = c.cutoff, c.reso end end end -- tone portamento (G, L) if fx == 7 or fx == 12 then if fx == 7 then if st.fmt == S3M then if param > 0 then c.portaSpeed = param end elseif st.compatG then if param > 0 then c.portaSpeed = param end else if param > 0 then c.mEF = param end c.portaSpeed = c.mEF end end if tick > 0 or st.fastPortas then tonePorta(st, c, c.portaSpeed * 4) end end -- vibrato (H, U, K) if fx == 8 or fx == 21 or fx == 11 then if fx ~= 11 then if param // 16 > 0 then c.vibSpeed = param // 16 end if param % 16 > 0 then c.vibDepth = param % 16 end end local scale = if fx == 21 then 2 / 255 else 8 / 255 if it and not st.oldFx then scale /= 2 end if tick > 0 or (it and not st.oldFx) then vibrato(st, c, scale) end end end -- the IT volume column (value stored + 1): slides, portamento, vibrato @native local function volColIt(st: any, c: any, tick: number) local v = c.vcmd - 1 if v < 65 then return end if v <= 74 then local p = v - 65 if p > 0 then c.mVolCol = p end if tick == 0 then c.vol = min(64, c.vol + c.mVolCol) end elseif v <= 84 then local p = v - 75 if p > 0 then c.mVolCol = p end if tick == 0 then c.vol = max(0, c.vol - c.mVolCol) end elseif v <= 94 then local p = v - 85 if p > 0 then c.mVolCol = p end if tick > 0 then c.vol = min(64, c.vol + c.mVolCol) end elseif v <= 104 then local p = v - 95 if p > 0 then c.mVolCol = p end if tick > 0 then c.vol = max(0, c.vol - c.mVolCol) end elseif v <= 114 then local p = (v - 105) * 4 if p > 0 then c.mEF = p end if tick > 0 then slide(st, c, c.mEF * 4) end elseif v <= 124 then local p = (v - 115) * 4 if p > 0 then c.mEF = p end if tick > 0 then slide(st, c, -c.mEF * 4) end elseif v >= 193 and v <= 202 then local p = Tables.IT_VOLPORTA[v - 192] or 0 if p > 0 then if st.compatG then c.portaSpeed = p else c.mEF = p c.portaSpeed = p end end if tick > 0 then tonePorta(st, c, c.portaSpeed * 4) end elseif v >= 203 and v <= 212 then local d = v - 203 if d > 0 then c.vibDepth = d end if tick > 0 or not st.oldFx then vibrato(st, c, if st.oldFx then 8 / 255 else 4 / 255) end end end @native local function fxExt(st: any, c: any, tick: number) local fx, param = c.fx, c.param if fx >= EXT.NOTE_SLIDE_UP and fx <= EXT.NOTE_SLIDE_DOWN_RETRIG then -- note slides (PTM, Oktalyzer): every (param >> 4) ticks by (param & 15) semitones; Oktalyzer (flags.oktSlides): -- 1x = every tick, 5x = once on the first tick if tick == 0 then if param // 16 > 0 then c.mNoteSlide = (param // 16) * 16 + c.mNoteSlide % 16 end if param % 16 > 0 then c.mNoteSlide = (c.mNoteSlide // 16) * 16 + param % 16 end c.slideCount = c.mNoteSlide // 16 end local p = c.mNoteSlide local go if st.oktSlides then go = p // 16 == 1 or tick == 0 else go = false if tick > 0 then c.slideCount -= 1 go = c.slideCount == 0 end end if go and c.smp and c.realNote > 0 then c.slideCount = p // 16 local up = fx == EXT.NOTE_SLIDE_UP or fx == EXT.NOTE_SLIDE_UP_RETRIG c.realNote = clamp(c.realNote + (if up then p % 16 else -(p % 16)), 1, 120) c.period = notePeriod(st, c.realNote, c.smp, c.finetune) if fx >= EXT.NOTE_SLIDE_UP_RETRIG then retrigVoice(st, c) end end elseif fx == EXT.AUTO_PORTA_UP or fx == EXT.AUTO_PORTA_DOWN then if tick == 0 then c.autoPorta = (if fx == EXT.AUTO_PORTA_UP then -param else param) * 4 end elseif fx == EXT.FREQ_ADJUST then if tick == 0 then c.hzAdd = param * 80 end elseif fx >= EXT.TEMPO_256 and fx <= EXT.TEMPO_256 + 2 then if tick == 0 then st.tempo = (fx - EXT.TEMPO_256 + 1) * 256 + param end end -- auto slides: every tick (fast portamentos) or every tick but the first if tick > 0 or st.fastPortas then if c.autoPorta ~= 0 then slide(st, c, c.autoPorta) end if c.autoTone and not c.tonePortaRow then tonePorta(st, c, c.portaSpeed * 4) end end end @native local function noteDelayOf(st: any, fx: number, param: number): number if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 0xD then return param % 16 elseif (st.fmt == S3M or st.fmt == IT) and fx == 19 and param // 16 == 0xD then return param % 16 end return 0 end @native local function finetuneOf(st: any, fx: number, param: number): number? if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 5 then local y = param % 16 if st.fmt == MOD then return (if y >= 8 then y - 16 else y) * 16 end return (y - 8) * 16 end return nil end @native local function runEffects(st: any, c: any, tick: number) c.vibDelta, c.arp = 0, 0 if (c.fx >= 0x40 and c.fx < 0x50) or c.autoPorta ~= 0 or c.autoTone then fxExt(st, c, tick) end if st.fmt == MOD or st.fmt == XM then fxModXm(st, c, tick) if st.fmt == XM then volColXm(st, c, tick) end else if st.fmt == IT then volColIt(st, c, tick) end fxS3mIt(st, c, tick) end -- keep the tremolo / panbrello offsets only while their effect runs local fx = c.fx if st.fmt == MOD or st.fmt == XM then if fx ~= 7 then c.tremDelta = 0 end -- XM: a tremor that ends in its off phase keeps the channel silent until the next note (OpenMPT / FT2) else if fx ~= 18 then c.tremDelta = 0 end if fx ~= 9 then c.tremorOn = true end if fx ~= 25 then c.panbDelta = 0 end end end @native local function processRow(st: any) local m = st.m local pat = st.pat local nch = st.nch local data = pat.data local base = st.row * nch * 5 st.visited[st.ord * 1024 + st.row] = true st.rows += 1 for i = 1, nch do local c = st.chans[i] local o = base + (i - 1) * 5 local note, ins, vcmd, fx, param = readu8(data, o), readu8(data, o + 1), readu8(data, o + 2), readu8(data, o + 3), readu8(data, o + 4) if (st.fmt == MOD or st.fmt == XM) and fx == 0 and param == 0 then fx = 255 end c.fx, c.param, c.vcmd = fx, param, vcmd c.cutTick, c.keyOffTick = -1, -1 if st.autoReset and fx ~= 0 and fx ~= 255 then -- 669: any effect stops the auto slides c.autoPorta, c.autoTone = 0, false end local tp = isPorta(st, fx, vcmd) c.tonePortaRow = tp if tp and st.autoTonePorta then c.autoTone = param ~= 0 or not st.autoReset or not isPorta(st, fx, 0) end c.triggered = false local delay = noteDelayOf(st, fx, param) c.finetune = finetuneOf(st, fx, param) if delay > 0 then c.delayTick, c.dNote, c.dIns, c.dVol = delay, note, ins, vcmd else c.delayTick = -1 trigger(st, c, note, ins, vcmd) end runEffects(st, c, 0) end local _ = m end @native local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean): (number, number, boolean) local ticks, values = env.ticks, env.values local n = #ticks if n == 0 then return 0, pos, true end local value if pos <= ticks[1] then value = values[1] elseif pos >= ticks[n] then value = values[n] else local i = 1 while i < n and ticks[i + 1] <= pos do i += 1 end local t0, t1 = ticks[i], ticks[i + 1] if t1 > t0 then value = values[i] + (values[i + 1] - values[i]) * (pos - t0) / (t1 - t0) else value = values[i + 1] end end local nextPos = pos + 1 local ended = false -- sustain / loop: only when the position runs over the end point (a position set past it, by Lxx, runs on) -- FT2 jumps when the position reaches the end tick (its value is not played: a loop lasts end - start ticks), -- IT after playing it (end - start + 1 ticks) local se, le = ticks[env.susEnd], ticks[env.loopEnd] local over = if it then 1 else 0 if keyOn and env.sustain and se and pos <= se and nextPos >= se + over then nextPos = ticks[env.susStart] or nextPos elseif env.loop and le and pos <= le and nextPos >= le + over then nextPos = ticks[env.loopStart] or nextPos elseif nextPos > ticks[n] then nextPos = ticks[n] ended = true end return value, nextPos, ended end @native local function updateVoice(st: any, v: any) local ins = v.ins local it = st.fmt == IT local envVol, envPan, envPitch = 64, 0, 0 local filterEnv = nil if ins then local hold = st.envHold and st.tick == 0 -- MED: the envelopes do not move on a row's first tick local e = ins.volEnv if e and e.enabled and v.volEnvOn then local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn, it) envVol, v.volEnvPos = val, if hold then v.volEnvPos else np if ended and it then if val <= 0 then v.active = false return end v.fading = true end end e = ins.panEnv if e and e.enabled and v.panEnvOn then local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn, it) envPan, v.panEnvPos = val, if hold then v.panEnvPos else np end e = ins.pitchEnv if e and e.enabled and v.pitchEnvOn then local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn, it) v.pitchEnvPos = if hold then v.pitchEnvPos else np if e.filter then filterEnv = val else envPitch = val end end if v.fading then local fo = ins.fadeout or 0 v.fade -= if it then fo * 64 else fo * 2 if v.fade <= 0 then v.fade = 0 v.active = false return end end end v.envVol = envVol -- auto-vibrato: XM per instrument, IT per sample local avSrc = if it then v.smp else ins local avDelta = 0 if avSrc and (avSrc.vibDepth or 0) > 0 then local depth = avSrc.vibDepth local sweep = avSrc.vibSweep or 0 if it then -- IT: the depth ramps up by the rate (vibSweep here) every tick, in 1/256 steps local target = depth * 256 if sweep == 0 then v.avAmp = target elseif v.avAmp < target then v.avAmp = min(target, v.avAmp + sweep) end avDelta = autoWave(avSrc.vibType or 0, v.avPos, true) * v.avAmp / (256 * 64) * 4 else if sweep == 0 then v.avAmp = depth * 256 elseif v.keyOn then v.avAmp = min(depth * 256, v.avAmp + depth * 256 / sweep) end avDelta = autoWave(avSrc.vibType or 0, v.avPos, false) * v.avAmp / (256 * 64) end v.avPos = (v.avPos + (avSrc.vibRate or 0)) % 256 end local P = v.periodOut + avDelta local freq if st.hz then freq = max(0, P + (v.hzAdd or 0)) elseif st.linear then freq = v.base * 2 ^ (-P / 768) else freq = if P > 0 then st.amiga / P else 0 end if envPitch ~= 0 then freq *= 2 ^ (envPitch / 24) end v.inc = freq / st.sr local smp = v.smp local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128 -- channel, sample and instrument global volumes (64 / 64 / 128 unless an IT file, or another format's loader, -- sets them) vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1) if v.tremorMute then vol = 0 end local pan = v.pan if it and ins and (ins.pps or 0) ~= 0 then pan = clamp(pan + ((v.patNote or v.note) - (ins.ppc or 60) - 1) * ins.pps / 2, 0, 256) end if envPan ~= 0 then local range = 128 - abs(pan - 128) pan += envPan * range / 32 end pan = clamp(pan, 0, 256) pan = clamp(128 + (pan - 128) * st.separation, 0, 256) local g = vol * st.master if v.surround then v.tl, v.tr = g * 0.5, -g * 0.5 elseif st.ft2Pan then -- FT2's square-root pan law (OpenMPT's CompatibleFT2 mix levels), pan at most 255 local p = min(pan, 255) v.tl, v.tr = g * math.sqrt((256 - p) / 256), g * math.sqrt(p / 256) else v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256 end v.rampN = st.ramp local cutoff = v.cutoff if filterEnv ~= nil or cutoff < 127 or v.reso > 0 then local cc = cutoff if filterEnv ~= nil then cc = cutoff * (filterEnv + 32) / 64 end local fhz = 110 * 2 ^ (0.25 + cc / 24) fhz = clamp(fhz, 120, min(20000, st.sr / 2)) local dmp = 10 ^ (-v.reso * (24 / 128) / 20) local fc = fhz * 2 * math.pi / st.sr local d = (1 - 2 * dmp) * fc if d > 2 then d = 2 end d = (2 * dmp - d) / fc local e = 1 / (fc * fc) local den = 1 + d + e v.fa, v.fb0, v.fb1 = 1 / den, (d + e + e) / den, -e / den v.fOn = not (cc >= 127 and v.reso == 0) else v.fOn = false end end @native function Player.tick(st: any): number if st.ended then return 0 end local tick = st.tick if tick == 0 and st.patDelayRep == 0 then local key = st.ord * 1024 + st.row if st.visited[key] and not st.loopAllowed then st.ended = true return 0 end if st.visited[key] then table.clear(st.visited) end st.fineDelay = 0 processRow(st) else local t = tick % st.speed local rep = tick >= st.speed or st.patDelayRep > 0 for i = 1, st.nch do local c = st.chans[i] if c.delayTick == tick and not rep then c.delayTick = -1 trigger(st, c, c.dNote, c.dIns, c.dVol) end if rep and t == 0 then c.vibDelta, c.arp = 0, 0 else runEffects(st, c, if t == 0 then 1 else t) end end end if st.ended then return 0 end for i = 1, st.nch do local c = st.chans[i] local v = c.voice if v and v.active and v.chan == i and not v.bg then local P = arpPeriod(st, c.period, c.arp) + (if st.hz then -c.vibDelta * st.hzScale else c.vibDelta) v.period, v.periodOut, v.base = c.period, P, c.base v.hzAdd = c.hzAdd v.vol = clamp(c.vol + c.tremDelta, 0, 64) if c.muted then v.vol = 0 end v.pan = clamp(c.pan + c.panbDelta, 0, 256) v.surround = c.surround v.chanVol = c.chanVol v.tremorMute = not c.tremorOn v.cutoff, v.reso = c.cutoff, c.reso end end for _, v in st.voices do if v.active then updateVoice(st, v) end end -- frames for this tick: 2.5 / tempo seconds, truncated per tick (as OpenMPT does) local frames = floor(st.sr * 2.5 / max(1, st.tempo)) st.tick += 1 if st.tick >= st.speed + st.fineDelay then st.tick = 0 if st.patDelayRep < st.patDelay then st.patDelayRep += 1 else st.patDelay, st.patDelayRep = 0, 0 advanceRow(st) end end return frames end return Player end __FILES["codecs/audio/Tracker/Tables"] = @native function() -- codecs/audio/Tracker/Tables: tracker lookup tables, from the public format documents (ProTracker 2.3 effect docs, -- FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT). local Tables = {} -- the ProTracker half-sine (32 steps, 0..255) local SINE32 = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 } local RANDOM: { number } = {} do local s = 12345 for i = 1, 64 do s = (s * 1103515245 + 12345) % 2147483648 RANDOM[i] = (s // 65536) % 511 - 255 end end @native function Tables.wave64(kind: number, pos: number): number local p = pos % 64 if kind == 1 then return 255 - p * 8 elseif kind == 2 then return if p < 32 then 255 else -255 elseif kind == 3 then return RANDOM[p + 1] end local v = SINE32[(p % 32) + 1] return if p >= 32 then -v else v end local SINE256: { number } = {} for i = 0, 255 do SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5) end @native function Tables.autoWave(kind: number, pos: number, it: boolean): number local p = pos % 256 if it then if kind == 1 then return 64 - (p + 1) // 2 elseif kind == 2 then return if p < 128 then 64 else -64 elseif kind == 3 then return RANDOM[(p % 64) + 1] // 4 end return SINE256[p + 1] end if kind == 1 then return if p < 128 then 64 else -64 elseif kind == 2 then return 64 - (p + 1) // 2 elseif kind == 3 then return (p + 1) // 2 - 64 end return SINE256[p + 1] end -- ProTracker periods, finetune 0, C-0 .. B-4; note 1 = C-0 (FT2 numbering), C-2 (428) = note 49 plays at 8363 Hz local PERIODS = { 3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1812, 1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906, 856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453, 428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226, 214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113, 107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56, } Tables.PERIODS = PERIODS Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1) @native function Tables.periodToNote(period: number): number if period <= 0 then return 0 end for i = 1, #PERIODS do if PERIODS[i] == period then return i + Tables.PERIOD_FIRST_NOTE - 1 end end local n = 49 + math.floor(12 * math.log(428 / period) / math.log(2) + 0.5) return math.clamp(n, 1, 120) end @native function Tables.noteToPeriod(note: number): number local i = note - Tables.PERIOD_FIRST_NOTE + 1 if i >= 1 and i <= #PERIODS then return PERIODS[i] end return math.max(1, math.floor(428 * 2 ^ ((49 - note) / 12) + 0.5)) end -- IT volume column "g" (tone portamento) speeds Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 } -- XM Rxy / S3M-IT Qxy volume changes: kind 0 add, 1 multiply; value Tables.RETRIG_ADD = { 0, -1, -2, -4, -8, -16, 0, 0, 0, 1, 2, 4, 8, 16, 0, 0 } Tables.RETRIG_MUL = { 1, 1, 1, 1, 1, 1, 2 / 3, 0.5, 1, 1, 1, 1, 1, 1, 1.5, 2 } -- frequency = AMIGA / period; period 1712 plays an 8363 Hz sample at its base rate (FT2 / ST3 units, 4x ProTracker's) Tables.AMIGA = 8363 * 1712 -- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz) Tables.AMIGA_PAL = 7093789.2 / 2 * 4 -- Scream Tracker 2 tempo byte as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at 23863 Hz, as a fractional BPM) local ST2_FACTOR = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 } @native function Tables.st2Tempo(byte: number): (number, number) local hi, lo = byte // 16, byte % 16 local d = 50 - (ST2_FACTOR[hi + 1] * lo) // 16 -- never 0; negative at tempo 06..0F (C integer division truncates) local spt = if d > 0 then 23863 // d else -(23863 // -d) if spt <= 0 then spt += 65536 end return math.max(hi, 1), math.floor((23863 * 50000 + spt) / (spt * 2)) / 10000 end return Tables end __FILES["codecs/audio/Tta"] = function() -- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. -- From the TTA1 format description (22-byte header and seek table with CRC-32s, frames of 256 / 245 seconds); no libtta / -- ffmpeg code (LGPL). Format 2 (password) is UNSUPPORTED. local Err = __include("core/Err") local Crc32 = __include("core/Crc32") local Decode = __include("codecs/audio/Tta/Decode") local Tta = {} type Info = { format: number, channels: number, bitsPerSample: number, sampleRate: number, samples: number, frameLength: number, -- samples per frame (256 * rate / 245) frames: number, offsets: { number }, sizes: { number }, } function Tta.info(buf: buffer, at: number, limit: number): (Info?, Err.Err?) if at + 22 > limit then return nil, Err.new(Err.TRUNCATED, "truncated header") end if buffer.readstring(buf, at, 4) ~= "TTA1" then return nil, Err.new(Err.CORRUPT, "no TTA1 header") end if Crc32.of(buf, at, 18) ~= buffer.readu32(buf, at + 18) then return nil, Err.new(Err.CHECKSUM, "header CRC mismatch", at) end local format = buffer.readu16(buf, at + 4) local info: Info = { format = format, channels = buffer.readu16(buf, at + 6), bitsPerSample = buffer.readu16(buf, at + 8), sampleRate = buffer.readu32(buf, at + 10), samples = buffer.readu32(buf, at + 14), frameLength = 0, frames = 0, offsets = {}, sizes = {}, } if format == 2 then return nil, Err.new(Err.UNSUPPORTED, "password-protected TTA") elseif format ~= 1 then return nil, Err.new(Err.UNSUPPORTED, "TTA format " .. format) end local bits = info.bitsPerSample if bits ~= 8 and bits ~= 16 and bits ~= 24 then return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit TTA") end if info.channels < 1 or info.sampleRate < 1 then return nil, Err.new(Err.CORRUPT, "bad header") end info.frameLength = (256 * info.sampleRate) // 245 if info.frameLength < 1 then return nil, Err.new(Err.CORRUPT, "bad sample rate") end local frames = (info.samples + info.frameLength - 1) // info.frameLength info.frames = frames local st = at + 22 if st + frames * 4 + 4 > limit then return nil, Err.new(Err.TRUNCATED, "truncated seek table") end if Crc32.of(buf, st, frames * 4) ~= buffer.readu32(buf, st + frames * 4) then return nil, Err.new(Err.CHECKSUM, "seek table CRC mismatch", st) end local o = st + frames * 4 + 4 for i = 1, frames do local size = buffer.readu32(buf, st + (i - 1) * 4) info.offsets[i] = o info.sizes[i] = size o += size end return info, nil end type Decoder = { info: Info, pcm: { number }, limit: number, frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?), state: Decode.State, } local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) local info = self.info if i < 1 or i > info.frames then return nil, Err.new(Err.ARG, "no frame " .. i) end local o, size = info.offsets[i], info.sizes[i] if o + size > self.limit then return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " runs past the end", o) end local n = if i < info.frames then info.frameLength else info.samples - (info.frames - 1) * info.frameLength local got, msg = Decode.frame(self.state, buf, o, size, n, self.pcm) if not got then return nil, Err.from(msg, o) end return got, nil end function Tta.decoder(info: Info, limit: number): Decoder return { info = info, pcm = table.create(info.frameLength * info.channels, 0), limit = limit, frame = frame, state = Decode.state(info.channels, info.bitsPerSample // 8), } end return Tta end __FILES["codecs/audio/Tta/Decode"] = @native function() -- codecs/audio/Tta/Decode: one TTA1 frame -> samples, from the TTA1 format description; no libtta / ffmpeg code. -- Bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). local Crc32 = __include("core/Crc32") local readu8, readu32 = buffer.readu8, buffer.readu32 local band, rshift = bit32.band, bit32.rshift local min, max, floor = math.min, math.max, math.floor local Decode = {} local TWO31, TWO32 = 2147483648, 4294967296 local INV31 = 1 / TWO31 local PAD = 16 local P2: { number } = table.create(40, 0) for i = 0, 39 do P2[i + 1] = 2 ^ i end local ONES: { number } = table.create(256, 0) for b = 0, 255 do local n, v = 0, b while v % 2 == 1 do n += 1 v //= 2 end ONES[b + 1] = n end @native local function longUnary(S: buffer, pos: number, lim: number): (number?, number) local unary = 0 while pos <= lim do local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) local ones = ONES[band(w, 255) + 1] if ones < 8 then return unary + ones, pos + ones + 1 end unary += 8 pos += 8 end return nil, pos end type State = { channels: number, bytes: number, S: buffer, R: { number }, Q: { number }, X: { number }, L: { number }, E: { number }, last: { number }, cur: { number }, } @native function Decode.state(channels: number, bytes: number): State return { channels = channels, bytes = bytes, S = buffer.create(4096), R = table.create(channels * 4, 0), Q = table.create(channels * 8, 0), X = table.create(channels * 8, 0), L = table.create(channels * 8, 0), E = table.create(channels, 0), last = table.create(channels, 0), cur = table.create(channels, 0), } end @native function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, P: { number }): (number?, string?) if len < 4 then return nil, "truncated frame" end local dlen = len - 4 if Crc32.of(buf, o, dlen) ~= readu32(buf, o + dlen) then return nil, "checksum: frame CRC mismatch" end local S = st.S if buffer.len(S) < dlen + PAD then S = buffer.create(dlen + PAD + 4096) st.S = S end buffer.copy(S, 0, buf, o, dlen) buffer.fill(S, dlen, 0, PAD) local C, bytes = st.channels, st.bytes local shift = if bytes == 2 then 9 else 10 -- the filter's precision per sample size local fdiv = 2 ^ shift local round = fdiv // 2 local pk = if bytes == 1 then 16 else 32 -- the fixed predictor: last * (pk - 1) / pk local R, Q, X, L, E, last, cur = st.R, st.Q, st.X, st.L, st.E, st.last, st.cur for c = 0, C - 1 do R[c * 4 + 1], R[c * 4 + 2], R[c * 4 + 3], R[c * 4 + 4] = 10, 10, 16384, 16384 E[c + 1], last[c + 1] = 0, 0 for i = 1, 8 do Q[c * 8 + i], X[c * 8 + i], L[c * 8 + i] = 0, 0, 0 end end local pos = 0 local lim = dlen * 8 local c = 0 for idx = 1, n * C do do if pos > lim then return nil, "truncated frame" end local unary local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) local ones = ONES[band(w, 255) + 1] if ones < 8 then unary = ones pos += ones + 1 else local u, p2 = longUnary(S, pos, lim) if not u then return nil, "truncated frame" end unary, pos = u, p2 end local rb = c * 4 local k0, k1, s0, s1 = R[rb + 1], R[rb + 2], R[rb + 3], R[rb + 4] local deep = unary > 0 local k if deep then k = k1 unary -= 1 else k = k0 end local value = unary if k > 0 then local bits if k <= 24 then bits = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), P2[k + 1] - 1) else local lo = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), 0xFFFF) local p2 = pos + 16 bits = lo + band(rshift(readu32(S, rshift(p2, 3)), band(p2, 7)), P2[k - 15] - 1) * 65536 end pos += k value = unary * P2[k + 1] + bits end if deep then s1 += value - s1 // 16 if k1 > 0 and s1 < P2[k1 + 5] then k1 -= 1 elseif s1 > P2[k1 + 6] then k1 += 1 end value += P2[k0 + 1] end s0 += value - s0 // 16 if k0 > 0 and s0 < P2[k0 + 5] then k0 -= 1 elseif s0 > P2[k0 + 6] then k0 += 1 end R[rb + 1] = math.min(k0, 31) R[rb + 2] = math.min(k1, 31) R[rb + 3] = s0 R[rb + 4] = s1 local odd = value % 2 -- odd -> (v + 1) / 2, even -> -v / 2 (branch-free) value = (value + odd) // 2 * (2 * odd - 1) -- the adaptive filter: the weights step toward the sign of the last residual local fb = c * 8 local err = E[c + 1] -- (one assignment per statement: LuaJIT cannot coalesce long multiple assignments) local dq = max(-1, min(1, err)) local x1, x2, x3, x4 = X[fb + 1], X[fb + 2], X[fb + 3], X[fb + 4] local x5, x6, x7, x8 = X[fb + 5], X[fb + 6], X[fb + 7], X[fb + 8] local q1 = Q[fb + 1] + x1 * dq local q2 = Q[fb + 2] + x2 * dq local q3 = Q[fb + 3] + x3 * dq local q4 = Q[fb + 4] + x4 * dq local q5 = Q[fb + 5] + x5 * dq local q6 = Q[fb + 6] + x6 * dq local q7 = Q[fb + 7] + x7 * dq local q8 = Q[fb + 8] + x8 * dq Q[fb + 1] = q1 Q[fb + 2] = q2 Q[fb + 3] = q3 Q[fb + 4] = q4 Q[fb + 5] = q5 Q[fb + 6] = q6 Q[fb + 7] = q7 Q[fb + 8] = q8 local l2, l3, l4, l5 = L[fb + 2], L[fb + 3], L[fb + 4], L[fb + 5] local l6, l7, l8 = L[fb + 6], L[fb + 7], L[fb + 8] local sum = round + L[fb + 1] * q1 + l2 * q2 + l3 * q3 + l4 * q4 + l5 * q5 + l6 * q6 + l7 * q7 + l8 * q8 if sum >= TWO31 or sum < -TWO31 then sum = (sum + TWO31) % TWO32 - TWO31 end -- the steps follow the delay line's signs (x 1, 2, 2, 4) X[fb + 1] = x2 X[fb + 2] = x3 X[fb + 3] = x4 X[fb + 4] = x5 X[fb + 5] = 1 + 2 * floor(l5 * INV31) -- -1 for a negative value, else 1 (branch-free) X[fb + 6] = 2 + 4 * floor(l6 * INV31) X[fb + 7] = 2 + 4 * floor(l7 * INV31) X[fb + 8] = 4 + 8 * floor(l8 * INV31) E[c + 1] = value value += sum // fdiv -- the delay line: the last value and its first and second differences local n7 = value - l8 local n6 = n7 - l7 L[fb + 1] = l2 L[fb + 2] = l3 L[fb + 3] = l4 L[fb + 4] = l5 L[fb + 5] = n6 - l6 L[fb + 6] = n6 L[fb + 7] = n7 L[fb + 8] = value value += (last[c + 1] * (pk - 1)) // pk last[c + 1] = value cur[c + 1] = value end c += 1 if c == C then -- inter-channel decorrelation: the last channel carries half the previous one, the others are differences c = 0 local o = idx - C if C == 1 then P[idx] = cur[1] elseif C == 2 then local a = cur[1] local b = cur[2] + (if a >= 0 then a // 2 else -((-a) // 2)) P[o + 1], P[o + 2] = b - a, b else local a = cur[C - 1] cur[C] += if a >= 0 then a // 2 else -((-a) // 2) for r = C - 1, 1, -1 do cur[r] = cur[r + 1] - cur[r] end for k = 1, C do P[o + k] = cur[k] end end end end if pos > lim then return nil, "truncated frame" end return n, nil end return Decode end __FILES["codecs/audio/Vorbis"] = function() -- codecs/audio/Vorbis: the Vorbis I decoder without its container. -- A Luau port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt). local Vorbis = { Setup = __include("codecs/audio/Vorbis/Setup"), Codebook = __include("codecs/audio/Vorbis/Codebook"), Packet = __include("codecs/audio/Vorbis/Packet"), Tables = __include("codecs/audio/Vorbis/Tables"), } return Vorbis end __FILES["codecs/audio/Vorbis/Codebook"] = @native function() -- codecs/audio/Vorbis/Codebook: the Vorbis LSB-first bit reader and codebooks (Vorbis I spec sections 2 and 3). -- Ported from stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt). Reading past the packet end gives -- zero bits and sets eop (the spec's end-of-packet condition); an invalid codeword also sets eop and decodes to -1. local Codebook = {} local readu8 = buffer.readu8 local floor = math.floor local POW = table.create(41, 0) for i = 0, 40 do POW[i + 1] = 2 ^ i end type Br = { buf: buffer, pos: number, limit: number, acc: number, cnt: number, pad: number, eop: boolean, } @native function Codebook.reader(buf: buffer, offset: number, size: number): Br return { buf = buf, pos = offset, limit = offset + size, acc = 0, cnt = 0, pad = 0, eop = false } end @native local function bits(br: Br, n: number): number if n == 0 then return 0 end local acc, cnt = br.acc, br.cnt if cnt < n then local b, p, lim = br.buf, br.pos, br.limit repeat if p < lim then acc += readu8(b, p) * POW[cnt + 1] p += 1 else br.pad += 8 end cnt += 8 until cnt >= n br.pos = p end local m = POW[n + 1] local v = acc % m br.acc = (acc - v) / m cnt -= n br.cnt = cnt if cnt < br.pad then br.eop = true br.pad = cnt end return v end Codebook.bits = bits -- ilog (spec 9.2.1) @native local function ilog(x: number): number local n = 0 while x > 0 do n += 1 x = floor(x / 2) end return n end Codebook.ilog = ilog -- float32_unpack (spec 9.2.2) @native local function float32Unpack(x: number): number local mantissa = x % 2097152 local sign = x >= 2147483648 local exp = floor((x % 2147483648) / 2097152) local v = mantissa * 2 ^ (exp - 788) return if sign then -v else v end type Book = { dims: number, entries: number, fastBits: number, fastLen: { number }, -- per fastBits-bit prefix: code length (> 0), 0 = continue in the tree, -1 = invalid fastSym: { number }, -- symbol, or the tree node to continue from c0: { number }, -- tree: child for bit 0 / 1: > 0 node, < 0 leaf (-symbol - 1), 0 none c1: { number }, lookup: number, vq: { number }?, used: number, } local MAX_ENTRIES = 2 ^ 20 local MAX_VQ = 2 ^ 22 -- lookup1_values(entries, dims): the largest r with r^dims <= entries @native local function lookup1Values(entries: number, dims: number): number local r = floor(math.exp(math.log(entries) / dims)) if floor((r + 1) ^ dims) <= entries then r += 1 end if (r + 1) ^ dims <= entries then return -1 end if floor(r ^ dims) > entries then return -1 end return r end -- assign codewords (spec 3.2.1: in entry order, the lowest free leaf) and build the decode tree + fast table @native local function build(book: Book, lengths: { number }): string? local n = book.entries local c0, c1 = book.c0, book.c1 local nodes = 1 c0[1], c1[1] = 0, 0 local available = table.create(33, 0) -- available[l]: the free code at depth l, as a 32-bit left-aligned value + 1 (0 = none) local first = true local used = 0 local maxLen = 0 for i = 0, n - 1 do local len = lengths[i + 1] if len > 0 then local code: number if first then first = false code = 0 for l = 1, len do available[l + 1] = POW[33 - l] + 1 end else local z = len while z > 0 and available[z + 1] == 0 do z -= 1 end if z == 0 then return "over-subscribed codebook" end code = available[z + 1] - 1 available[z + 1] = 0 for y = len, z + 1, -1 do available[y + 1] = code + POW[33 - y] + 1 end end local node = 1 for d = 1, len do local bit = floor(code / POW[33 - d]) % 2 local child = if bit == 0 then c0[node] else c1[node] if d == len then if child ~= 0 then return "ambiguous codeword" end if bit == 0 then c0[node] = -(i + 1) else c1[node] = -(i + 1) end else if child < 0 then return "ambiguous codeword" elseif child == 0 then nodes += 1 c0[nodes], c1[nodes] = 0, 0 child = nodes if bit == 0 then c0[node] = child else c1[node] = child end end node = child end end used += 1 if len > maxLen then maxLen = len end end end book.used = used local fb = math.clamp(maxLen, 1, 10) book.fastBits = fb local size = POW[fb + 1] local fl, fs = table.create(size, -1), table.create(size, 0) for idx = 0, size - 1 do local node = 1 local v = idx for d = 1, fb do local bit = v % 2 v = (v - bit) / 2 local child = if bit == 0 then c0[node] else c1[node] if child < 0 then fl[idx + 1], fs[idx + 1] = d, -child - 1 break elseif child == 0 then break end node = child if d == fb then fl[idx + 1], fs[idx + 1] = 0, node end end end book.fastLen, book.fastSym = fl, fs return nil end @native function Codebook.read(br: Br): (Book?, string?) if bits(br, 24) ~= 0x564342 then return nil, "bad codebook sync" end local dims = bits(br, 16) local entries = bits(br, 24) local ordered = bits(br, 1) if br.eop then return nil, "setup header ends in a codebook" end if dims == 0 and entries ~= 0 then return nil, "codebook with 0 dimensions" end if entries > MAX_ENTRIES then return nil, "codebook with " .. entries .. " entries" end local lengths = table.create(entries, 0) if ordered == 1 then local cur = 0 local len = bits(br, 5) + 1 while cur < entries do local num = bits(br, ilog(entries - cur)) if len >= 32 or cur + num > entries or br.eop then return nil, "bad ordered codebook lengths" end for k = cur + 1, cur + num do lengths[k] = len end cur += num len += 1 end else local sparse = bits(br, 1) for j = 1, entries do if sparse == 0 or bits(br, 1) == 1 then local l = bits(br, 5) + 1 if l == 32 then return nil, "codeword length 32" end lengths[j] = l end end end if br.eop then return nil, "setup header ends in a codebook" end local book: Book = { dims = dims, entries = entries, fastBits = 1, fastLen = {}, fastSym = {}, c0 = {}, c1 = {}, lookup = 0, vq = nil, used = 0, } local err = build(book, lengths) if err then return nil, err end local lookup = bits(br, 4) if lookup > 2 then return nil, "lookup type " .. lookup end book.lookup = lookup if lookup > 0 then local minimum = float32Unpack(bits(br, 32)) local delta = float32Unpack(bits(br, 32)) local valueBits = bits(br, 4) + 1 local seq = bits(br, 1) == 1 local nvalues if lookup == 1 then nvalues = lookup1Values(entries, dims) if nvalues < 0 then return nil, "bad lookup1 size" end else nvalues = entries * dims end if nvalues == 0 then return nil, "empty lookup table" end if entries * dims > MAX_VQ or nvalues > MAX_VQ then return nil, "lookup table too large" end local mults = table.create(nvalues, 0) for j = 1, nvalues do mults[j] = bits(br, valueBits) end if br.eop then return nil, "setup header ends in a lookup table" end -- expand to one vector per entry (spec 3.2.1, "VQ lookup table vector representation") local vq = table.create(entries * dims, 0) for e = 0, entries - 1 do local last = 0 local div = 1 for k = 0, dims - 1 do local off if lookup == 1 then off = floor(e / div) % nvalues div *= nvalues else off = e * dims + k end local v = mults[off + 1] * delta + minimum + last if seq then last = v end vq[e * dims + k + 1] = v end end book.vq = vq end return book, nil end @native local function decode(br: Br, book: Book): number local fb = book.fastBits local acc, cnt = br.acc, br.cnt if cnt < fb then local b, p, lim = br.buf, br.pos, br.limit repeat if p < lim then acc += readu8(b, p) * POW[cnt + 1] p += 1 else br.pad += 8 end cnt += 8 until cnt >= fb br.pos = p br.acc, br.cnt = acc, cnt end local idx = acc % POW[fb + 1] + 1 local l = book.fastLen[idx] if l > 0 then local m = POW[l + 1] br.acc = (acc - acc % m) / m cnt -= l br.cnt = cnt if cnt < br.pad then br.eop = true br.pad = cnt return -1 end return book.fastSym[idx] elseif l == 0 then bits(br, fb) local node = book.fastSym[idx] local c0, c1 = book.c0, book.c1 while true do local child = if bits(br, 1) == 0 then c0[node] else c1[node] if br.eop then return -1 end if child < 0 then return -child - 1 elseif child == 0 then br.eop = true return -1 end node = child end end br.eop = true return -1 end Codebook.decode = decode return Codebook end __FILES["codecs/audio/Vorbis/Packet"] = @native function() -- codecs/audio/Vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8). -- Floors, residues and coupling ported from stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt). The -- overlap follows libvorbis: each packet after the first returns the n_prev/4 + n_cur/4 samples between the two window -- centres, so granule positions count exactly the samples returned (the first packet returns none). local Codebook = __include("codecs/audio/Vorbis/Codebook") local Setup = __include("codecs/audio/Vorbis/Setup") local Tables = __include("codecs/audio/Vorbis/Tables") local Mdct = __include("codecs/audio/Mdct") local Packet = {} local bits, decode = Codebook.bits, Codebook.decode local ilog = Codebook.ilog local INV_DB = Tables local RANGE = { 256, 128, 86, 64 } type State = { channels: number, n0: number, n1: number, setup: Setup.Setup, plans: { [number]: Mdct.Plan }, slopes: { [number]: { number } }, spec: { { number } }, frame: { { number } }, tail: { { number } }, tailLen: number, prevN: number, out: { { number } }, finalY: { { number } }, step2: { number }, inter: { number }, zero: { boolean }, reallyZero: { boolean }, partClass: { { { number } } }, } @native function Packet.new(id: Setup.Ident, setup: Setup.Setup): State? local n0, n1, ch = id.blocksize0, id.blocksize1, id.channels local plans: { [number]: Mdct.Plan } = {} local slopes: { [number]: { number } } = {} for _, n in { n0, n1 } do local p = Mdct.new(n) if not p then return nil end plans[n] = p local w = Mdct.window("vorbis", n) :: { number } local half = table.create(n // 2, 0) for i = 1, n // 2 do half[i] = w[i] end slopes[n // 2] = half end @native local function arrays(len: number): { { number } } local t = table.create(ch) for c = 1, ch do t[c] = table.create(len, 0) end return t end local partClass = table.create(ch) for c = 1, ch do partClass[c] = {} end return { channels = ch, n0 = n0, n1 = n1, setup = setup, plans = plans, slopes = slopes, spec = arrays(n1 // 2), frame = arrays(n1), tail = arrays(n1 // 2), tailLen = 0, prevN = 0, out = arrays(n1), finalY = arrays(math.max(2, setup.maxFloorValues)), step2 = table.create(math.max(2, setup.maxFloorValues), 0), inter = table.create(n1 // 2 * ch, 0), zero = table.create(ch, false), reallyZero = table.create(ch, false), partClass = partClass, } end @native function Packet.reset(st: State) st.prevN = 0 st.tailLen = 0 end @native function Packet.blocksize(st: State, b: buffer, off: number, size: number): number if size < 1 then return 0 end local br = Codebook.reader(b, off, size) if bits(br, 1) ~= 0 then return 0 end local m = bits(br, st.setup.modeBits) local mode = st.setup.modes[m + 1] if not mode or br.eop then return 0 end return if mode.blockflag == 1 then st.n1 else st.n0 end @native local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number local dy = y1 - y0 local adx = x1 - x0 local off = ((if dy < 0 then -dy else dy) * (x - x0)) // adx return if dy < 0 then y0 - off else y0 + off end -- multiply out[x0 .. x1) by the floor line from (x0, y0) to (x1, y1) (stb draw_line) @native local function drawLine(out: { number }, x0: number, y0: number, x1: number, y1: number, n: number) local dy = y1 - y0 local adx = x1 - x0 local ady = if dy < 0 then -dy else dy local base = if dy < 0 then -(ady // adx) else ady // adx local sy = if dy < 0 then base - 1 else base + 1 ady -= (if base < 0 then -base else base) * adx if x1 > n then x1 = n end local x, y, err = x0, y0, 0 if x < x1 then out[x + 1] *= INV_DB[y % 256 + 1] x += 1 while x < x1 do err += ady if err >= adx then err -= adx y += sy else y += base end out[x + 1] *= INV_DB[y % 256 + 1] x += 1 end end end @native local function floorDecode(st: State, br: Codebook.Br, g: Setup.Floor1, finalY: { number }): boolean if bits(br, 1) == 0 then return false end local books = st.setup.books local range = RANGE[g.multiplier] local yb = ilog(range) - 1 finalY[1] = bits(br, yb) finalY[2] = bits(br, yb) local offset = 2 for j = 1, g.partitions do local pclass = g.partitionClass[j] + 1 local cdim = g.classDims[pclass] local cbits = g.classSubs[pclass] local csub = 2 ^ cbits local cval = 0 if cbits > 0 then cval = decode(br, books[g.classMaster[pclass] + 1]) if cval < 0 then return false end end local subs = g.subBooks[pclass] for _ = 1, cdim do local book = subs[cval % csub + 1] cval = cval // csub if book >= 0 then local v = decode(br, books[book + 1]) if v < 0 then return false end finalY[offset + 1] = v else finalY[offset + 1] = 0 end offset += 1 end end if br.eop then return false end -- step 1: amplitude value synthesis local step2 = st.step2 step2[1], step2[2] = 1, 1 local xl, low, high = g.xlist, g.low, g.high for j = 2, g.values - 1 do local lo, hi = low[j + 1], high[j + 1] local pred = predict(xl[j + 1], xl[lo + 1], xl[hi + 1], finalY[lo + 1], finalY[hi + 1]) local val = finalY[j + 1] local highroom = range - pred local lowroom = pred local room = if highroom < lowroom then highroom * 2 else lowroom * 2 if val ~= 0 then step2[lo + 1], step2[hi + 1], step2[j + 1] = 1, 1, 1 if val >= room then if highroom > lowroom then finalY[j + 1] = val - lowroom + pred else finalY[j + 1] = pred - val + highroom - 1 end elseif val % 2 == 1 then finalY[j + 1] = pred - (val + 1) // 2 else finalY[j + 1] = pred + val // 2 end else step2[j + 1] = 0 finalY[j + 1] = pred end end for j = 1, g.values do if step2[j] == 0 then finalY[j] = -1 end end return true end -- multiply target[1 .. n2] by the floor curve (stb do_floor) @native local function floorCurve(g: Setup.Floor1, finalY: { number }, target: { number }, n2: number) local mult = g.multiplier local lx, ly = 0, finalY[1] * mult local sorted, xl = g.sorted, g.xlist for q = 2, g.values do local j = sorted[q] + 1 local fy = finalY[j] if fy >= 0 then local hy = fy * mult local hx = xl[j] if lx ~= hx then drawLine(target, lx, ly, hx, hy, n2) end lx, ly = hx, hy end end if lx < n2 then local v = INV_DB[ly % 256 + 1] for j = lx + 1, n2 do target[j] *= v end end end @native local function partition(br: Codebook.Br, book: Codebook.Book, target: { number }, offset: number, psize: number, rtype: number, limit: number): boolean local vq = book.vq if not vq then br.eop = true -- a scalar book in a vector context: invalid stream return false end local dims = book.dims if rtype == 0 then local step = psize // dims for k = 0, step - 1 do local e = decode(br, book) if e < 0 then return false end local base = e * dims for i = 0, dims - 1 do local at = offset + k + i * step if at < limit then target[at + 1] += vq[base + i + 1] end end end else local k = 0 while k < psize do local e = decode(br, book) if e < 0 then return false end local base = e * dims local len = math.min(dims, psize - k) local at = offset + k for i = 0, len - 1 do if at + i < limit then target[at + i + 1] += vq[base + i + 1] end end k += dims end end return true end @native local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: { { number } | false }, ch: number, n2: number) local books = st.setup.books local rtype = r.type local cbook = books[r.classbook + 1] local classwords = cbook.dims for j = 1, ch do local t = targets[j] if t then for i = 1, n2 do (t :: { number })[i] = 0 end end end local any = false for j = 1, ch do if targets[j] then any = true end end if not any then return end local psize = r.partSize local rb = r.books local classdata = r.classdata if rtype == 2 and ch > 1 then local total = n2 * ch local inter = st.inter for i = 1, total do inter[i] = 0 end local lb = math.min(r.begin, total) local le = math.min(r.finish, total) local partRead = (le - lb) // psize local pc = st.partClass[1] local done = false for pass = 1, 8 do if done then break end local pcount, classSet = 0, 1 while pcount < partRead do if pass == 1 then local q = decode(br, cbook) if q < 0 then done = true break end pc[classSet] = classdata[q + 1] end local cls = pc[classSet] local i = 0 while i < classwords and pcount < partRead do local b = rb[cls[i + 1] + 1][pass] if b >= 0 then if not partition(br, books[b + 1], inter, r.begin + pcount * psize, psize, 1, total) then done = true break end end i += 1 pcount += 1 end if done then break end classSet += 1 end end for j = 1, ch do local t = targets[j] if t then local tt = t :: { number } local v = j for i = 1, n2 do tt[i] = inter[v] v += ch end end end return end local lb = math.min(r.begin, n2) local le = math.min(r.finish, n2) local partRead = (le - lb) // psize local pcs = st.partClass for pass = 1, 8 do local pcount, classSet = 0, 1 while pcount < partRead do if pass == 1 then for j = 1, ch do if targets[j] then local q = decode(br, cbook) if q < 0 then return end pcs[j][classSet] = classdata[q + 1] end end end local i = 0 while i < classwords and pcount < partRead do for j = 1, ch do local t = targets[j] if t then local c = pcs[j][classSet][i + 1] local b = rb[c + 1][pass] if b >= 0 then if not partition(br, books[b + 1], t :: { number }, r.begin + pcount * psize, psize, rtype, n2) then return end end end end i += 1 pcount += 1 end classSet += 1 end end end @native function Packet.decode(st: State, b: buffer, off: number, size: number): number if size < 1 then return -1 end local setup = st.setup local br = Codebook.reader(b, off, size) if bits(br, 1) ~= 0 then return -1 end local mode = setup.modes[bits(br, setup.modeBits) + 1] if not mode then return -1 end local n, prevLong, nextLong if mode.blockflag == 1 then n = st.n1 prevLong = bits(br, 1) == 1 nextLong = bits(br, 1) == 1 else n = st.n0 prevLong, nextLong = false, false end if br.eop then return -1 end local n2 = n // 2 local n0 = st.n0 local leftStart, leftEnd, rightStart, rightEnd if mode.blockflag == 1 and not prevLong then leftStart, leftEnd = (n - n0) // 4, (n + n0) // 4 else leftStart, leftEnd = 0, n2 end if mode.blockflag == 1 and not nextLong then rightStart, rightEnd = (n * 3 - n0) // 4, (n * 3 + n0) // 4 else rightStart, rightEnd = n2, n end local map = setup.mappings[mode.mapping + 1] local ch = st.channels local spec, zero, reallyZero = st.spec, st.zero, st.reallyZero for c = 1, ch do local s = map.mux[c] + 1 local g = setup.floors[map.submapFloor[s] + 1] local ok = floorDecode(st, br, g, st.finalY[c]) zero[c] = not ok reallyZero[c] = not ok end -- channels coupled to a non-silent channel are decoded too for i = 1, map.couplingSteps do local m, a = map.magnitude[i] + 1, map.angle[i] + 1 if not zero[m] or not zero[a] then zero[m], zero[a] = false, false end end for i = 1, map.submaps do local targets: { { number } | false } = {} local k = 0 for c = 1, ch do if map.mux[c] == i - 1 then k += 1 targets[k] = if zero[c] then false else spec[c] end end residue(st, br, setup.residues[map.submapResidue[i] + 1], targets, k, n2) end for i = map.couplingSteps, 1, -1 do local m, a = spec[map.magnitude[i] + 1], spec[map.angle[i] + 1] for j = 1, n2 do local mv, av = m[j], a[j] local m2, a2 if mv > 0 then if av > 0 then m2, a2 = mv, mv - av else a2, m2 = mv, mv + av end else if av > 0 then m2, a2 = mv, mv + av else a2, m2 = mv, mv - av end end m[j], a[j] = m2, a2 end end local plan = st.plans[n] local lslope = st.slopes[leftEnd - leftStart] local rslope = st.slopes[rightEnd - rightStart] for c = 1, ch do local sp = spec[c] local fr = st.frame[c] if reallyZero[c] then for j = 1, n do fr[j] = 0 end else local s = map.mux[c] + 1 floorCurve(setup.floors[map.submapFloor[s] + 1], st.finalY[c], sp, n2) Mdct.inverse(plan, sp, 1, 1, fr, 1) for j = 1, leftStart do fr[j] = 0 end local L = leftEnd - leftStart for j = 0, L - 1 do fr[leftStart + j + 1] *= lslope[j + 1] end local R = rightEnd - rightStart for j = 0, R - 1 do fr[rightStart + j + 1] *= rslope[R - j] end for j = rightEnd + 1, n do fr[j] = 0 end end end -- overlap-add with the previous frame; return the samples between the two centres local prevN = st.prevN local count = 0 if prevN > 0 then count = prevN // 4 + n // 4 local o = prevN // 4 - n // 4 -- this frame starts o samples after the previous centre local tl = st.tailLen for c = 1, ch do local out, tail, fr = st.out[c], st.tail[c], st.frame[c] for j = 0, count - 1 do local v = if j < tl then tail[j + 1] else 0 local fi = j - o if fi >= 0 then v += fr[fi + 1] end out[j + 1] = v end end end local tl = rightEnd - n2 for c = 1, ch do local tail, fr = st.tail[c], st.frame[c] for j = 1, tl do tail[j] = fr[n2 + j] end end st.tailLen = tl st.prevN = n return count end return Packet end __FILES["codecs/audio/Vorbis/Setup"] = @native function() -- codecs/audio/Vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2). -- Ported from stb_vorbis 1.22 start_decoder (public domain / MIT, licenses/stb_vorbis-LICENSE.txt). Floor 0 is -- rejected as unsupported, as stb_vorbis does. local Codebook = __include("codecs/audio/Vorbis/Codebook") local Setup = {} local bits, ilog = Codebook.bits, Codebook.ilog local readu8, readu32 = buffer.readu8, buffer.readu32 type Ident = { channels: number, sampleRate: number, bitrateMax: number, bitrateNominal: number, bitrateMin: number, blocksize0: number, blocksize1: number, } type Floor1 = { partitions: number, partitionClass: { number }, classDims: { number }, classSubs: { number }, classMaster: { number }, subBooks: { { number } }, multiplier: number, xlist: { number }, values: number, sorted: { number }, low: { number }, high: { number }, } type Residue = { type: number, begin: number, finish: number, partSize: number, classifications: number, classbook: number, books: { { number } }, classdata: { { number } }, } type Mapping = { submaps: number, couplingSteps: number, magnitude: { number }, angle: { number }, mux: { number }, submapFloor: { number }, submapResidue: { number }, } type Mode = { blockflag: number, mapping: number } type Setup = { books: { Codebook.Book }, floors: { Floor1 }, residues: { Residue }, mappings: { Mapping }, modes: { Mode }, modeBits: number, maxFloorValues: number, } @native local function isVorbis(b: buffer, o: number, n: number, kind: number): boolean return n >= 7 and readu8(b, o) == kind and buffer.readstring(b, o + 1, 6) == "vorbis" end Setup.isVorbis = isVorbis @native function Setup.ident(b: buffer, o: number, n: number): (Ident?, string?) if not isVorbis(b, o, n, 1) then return nil, "not a Vorbis identification header" end if n < 30 then return nil, "short identification header" end if readu32(b, o + 7) ~= 0 then return nil, "Vorbis version " .. readu32(b, o + 7) end local ch = readu8(b, o + 11) local rate = readu32(b, o + 12) local bs = readu8(b, o + 28) local l0, l1 = bs % 16, bs // 16 if ch == 0 or rate == 0 then return nil, "no channels or no sample rate" end if l0 < 6 or l0 > 13 or l1 < 6 or l1 > 13 or l0 > l1 then return nil, "bad blocksizes" end if readu8(b, o + 29) % 2 == 0 then return nil, "identification header framing bit not set" end return { channels = ch, sampleRate = rate, bitrateMax = buffer.readi32(b, o + 16), bitrateNominal = buffer.readi32(b, o + 20), bitrateMin = buffer.readi32(b, o + 24), blocksize0 = 2 ^ l0, blocksize1 = 2 ^ l1, }, nil end @native function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?) if not isVorbis(b, o, n, 3) then return nil, nil end local p, e = o + 7, o + n if p + 4 > e then return nil, nil end local vlen = readu32(b, p) p += 4 if vlen > e - p then return nil, nil end local vendor = buffer.readstring(b, p, vlen) p += vlen local list = {} if p + 4 > e then return vendor, list end local count = readu32(b, p) p += 4 for _ = 1, count do if p + 4 > e then break end local len = readu32(b, p) p += 4 if len > e - p then break end table.insert(list, buffer.readstring(b, p, len)) p += len end return vendor, list end @native function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, string?) if not isVorbis(b, o, n, 5) then return nil, "not a Vorbis setup header" end local br = Codebook.reader(b, o + 7, n - 7) local channels = id.channels local books: { Codebook.Book } = {} local nbooks = bits(br, 8) + 1 for i = 1, nbooks do local book, err = Codebook.read(br) if not book then return nil, "codebook " .. (i - 1) .. ": " .. tostring(err) end books[i] = book end -- time domain transforms (placeholders) local ntimes = bits(br, 6) + 1 for _ = 1, ntimes do if bits(br, 16) ~= 0 then return nil, "bad time domain transform" end end local floors: { Floor1 } = {} local maxValues = 0 local nfloors = bits(br, 6) + 1 for i = 1, nfloors do local ftype = bits(br, 16) if ftype == 0 then return nil, "floor 0" elseif ftype ~= 1 then return nil, "bad floor type " .. ftype end local parts = bits(br, 5) local pclass = table.create(parts, 0) local maxClass = -1 for j = 1, parts do pclass[j] = bits(br, 4) if pclass[j] > maxClass then maxClass = pclass[j] end end local cdims, csubs, cmaster, subBooks = {}, {}, {}, {} for j = 1, maxClass + 1 do cdims[j] = bits(br, 3) + 1 csubs[j] = bits(br, 2) cmaster[j] = -1 if csubs[j] > 0 then cmaster[j] = bits(br, 8) if cmaster[j] >= nbooks then return nil, "bad floor master book" end end local sb = {} for k = 1, 2 ^ csubs[j] do sb[k] = bits(br, 8) - 1 if sb[k] >= nbooks then return nil, "bad floor subclass book" end end subBooks[j] = sb end local mult = bits(br, 2) + 1 local rangebits = bits(br, 4) local xlist = { 0, 2 ^ rangebits } for j = 1, parts do local c = pclass[j] for _ = 1, cdims[c + 1] do table.insert(xlist, bits(br, rangebits)) end end local values = #xlist if values > 65 * 8 then return nil, "too many floor points" end if br.eop then return nil, "setup header ends in a floor" end local order = table.create(values, 0) for j = 1, values do order[j] = j - 1 end table.sort(order, @native function(a: number, c: number): boolean return xlist[a + 1] < xlist[c + 1] end) for j = 1, values - 1 do if xlist[order[j] + 1] == xlist[order[j + 1] + 1] then return nil, "duplicate floor x" end end local low, high = table.create(values, 0), table.create(values, 0) for j = 2, values - 1 do local lo, hi = -1, 65536 local x = xlist[j + 1] for k = 0, j - 1 do local xv = xlist[k + 1] if xv > lo and xv < x then low[j + 1], lo = k, xv end if xv < hi and xv > x then high[j + 1], hi = k, xv end end end floors[i] = { partitions = parts, partitionClass = pclass, classDims = cdims, classSubs = csubs, classMaster = cmaster, subBooks = subBooks, multiplier = mult, xlist = xlist, values = values, sorted = order, low = low, high = high, } if values > maxValues then maxValues = values end end local residues: { Residue } = {} local nres = bits(br, 6) + 1 for i = 1, nres do local rtype = bits(br, 16) if rtype > 2 then return nil, "bad residue type " .. rtype end local rbegin, rend = bits(br, 24), bits(br, 24) local psize = bits(br, 24) + 1 local ncls = bits(br, 6) + 1 local cbook = bits(br, 8) if rend < rbegin then return nil, "residue end before begin" end if cbook >= nbooks then return nil, "bad residue classbook" end local cascade = table.create(ncls, 0) for j = 1, ncls do local lowBits = bits(br, 3) local highBits = if bits(br, 1) == 1 then bits(br, 5) else 0 cascade[j] = highBits * 8 + lowBits end local rbooks = {} for j = 1, ncls do local row = table.create(8, -1) local c = cascade[j] for k = 1, 8 do if c % 2 == 1 then row[k] = bits(br, 8) if row[k] >= nbooks then return nil, "bad residue book" end end c = c // 2 end rbooks[j] = row end if br.eop then return nil, "setup header ends in a residue" end -- class numbers of each classbook entry (stb's classdata) local cb = books[cbook + 1] local cw = cb.dims if cb.entries * cw > 2 ^ 22 then return nil, "residue classbook too large" end local classdata = table.create(cb.entries) for j = 0, cb.entries - 1 do local row = table.create(cw, 0) local tmp = j for k = cw, 1, -1 do row[k] = tmp % ncls tmp = tmp // ncls end classdata[j + 1] = row end residues[i] = { type = rtype, begin = rbegin, finish = rend, partSize = psize, classifications = ncls, classbook = cbook, books = rbooks, classdata = classdata, } end local mappings: { Mapping } = {} local nmaps = bits(br, 6) + 1 local chBits = ilog(channels - 1) for i = 1, nmaps do if bits(br, 16) ~= 0 then return nil, "bad mapping type" end local submaps = if bits(br, 1) == 1 then bits(br, 4) + 1 else 1 local steps = 0 local mag, ang = {}, {} if bits(br, 1) == 1 then steps = bits(br, 8) + 1 if steps > channels then return nil, "too many coupling steps" end for k = 1, steps do mag[k] = bits(br, chBits) ang[k] = bits(br, chBits) if mag[k] >= channels or ang[k] >= channels or mag[k] == ang[k] then return nil, "bad coupling channels" end end end if bits(br, 2) ~= 0 then return nil, "mapping reserved bits set" end local mux = table.create(channels, 0) if submaps > 1 then for j = 1, channels do mux[j] = bits(br, 4) if mux[j] >= submaps then return nil, "bad channel mux" end end end local sf, sr = {}, {} for j = 1, submaps do bits(br, 8) sf[j] = bits(br, 8) sr[j] = bits(br, 8) if sf[j] >= nfloors or sr[j] >= nres then return nil, "bad submap floor / residue" end end mappings[i] = { submaps = submaps, couplingSteps = steps, magnitude = mag, angle = ang, mux = mux, submapFloor = sf, submapResidue = sr, } end local modes: { Mode } = {} local nmodes = bits(br, 6) + 1 for i = 1, nmodes do local bf = bits(br, 1) local wt, tt = bits(br, 16), bits(br, 16) local m = bits(br, 8) if wt ~= 0 or tt ~= 0 or m >= nmaps then return nil, "bad mode" end modes[i] = { blockflag = bf, mapping = m } end if br.eop then return nil, "setup header truncated" end if bits(br, 1) ~= 1 then return nil, "setup header framing bit not set" end return { books = books, floors = floors, residues = residues, mappings = mappings, modes = modes, modeBits = ilog(nmodes - 1), maxFloorValues = maxValues, }, nil end return Setup end __FILES["codecs/audio/Vorbis/Tables"] = function() -- codecs/audio/Vorbis/Tables: the floor 1 inverse dB table (Vorbis I specification section 10.1, as in stb_vorbis 1.22, -- public domain / MIT, licenses/stb_vorbis-LICENSE.txt). return table.freeze({ 1.0649863e-07, 1.1341951e-07, 1.2079015e-07, 1.2863978e-07, 1.3699951e-07, 1.4590251e-07, 1.5538408e-07, 1.6548181e-07, 1.7623575e-07, 1.8768855e-07, 1.9988561e-07, 2.1287530e-07, 2.2670913e-07, 2.4144197e-07, 2.5713223e-07, 2.7384213e-07, 2.9163793e-07, 3.1059021e-07, 3.3077411e-07, 3.5226968e-07, 3.7516214e-07, 3.9954229e-07, 4.2550680e-07, 4.5315863e-07, 4.8260743e-07, 5.1396998e-07, 5.4737065e-07, 5.8294187e-07, 6.2082472e-07, 6.6116941e-07, 7.0413592e-07, 7.4989464e-07, 7.9862701e-07, 8.5052630e-07, 9.0579828e-07, 9.6466216e-07, 1.0273513e-06, 1.0941144e-06, 1.1652161e-06, 1.2409384e-06, 1.3215816e-06, 1.4074654e-06, 1.4989305e-06, 1.5963394e-06, 1.7000785e-06, 1.8105592e-06, 1.9282195e-06, 2.0535261e-06, 2.1869758e-06, 2.3290978e-06, 2.4804557e-06, 2.6416497e-06, 2.8133190e-06, 2.9961443e-06, 3.1908506e-06, 3.3982101e-06, 3.6190449e-06, 3.8542308e-06, 4.1047004e-06, 4.3714470e-06, 4.6555282e-06, 4.9580707e-06, 5.2802740e-06, 5.6234160e-06, 5.9888572e-06, 6.3780469e-06, 6.7925283e-06, 7.2339451e-06, 7.7040476e-06, 8.2047000e-06, 8.7378876e-06, 9.3057248e-06, 9.9104632e-06, 1.0554501e-05, 1.1240392e-05, 1.1970856e-05, 1.2748789e-05, 1.3577278e-05, 1.4459606e-05, 1.5399272e-05, 1.6400004e-05, 1.7465768e-05, 1.8600792e-05, 1.9809576e-05, 2.1096914e-05, 2.2467911e-05, 2.3928002e-05, 2.5482978e-05, 2.7139006e-05, 2.8902651e-05, 3.0780908e-05, 3.2781225e-05, 3.4911534e-05, 3.7180282e-05, 3.9596466e-05, 4.2169667e-05, 4.4910090e-05, 4.7828601e-05, 5.0936773e-05, 5.4246931e-05, 5.7772202e-05, 6.1526565e-05, 6.5524908e-05, 6.9783085e-05, 7.4317983e-05, 7.9147585e-05, 8.4291040e-05, 8.9768747e-05, 9.5602426e-05, 0.00010181521, 0.00010843174, 0.00011547824, 0.00012298267, 0.00013097477, 0.00013948625, 0.00014855085, 0.00015820453, 0.00016848555, 0.00017943469, 0.00019109536, 0.00020351382, 0.00021673929, 0.00023082423, 0.00024582449, 0.00026179955, 0.00027881276, 0.00029693158, 0.00031622787, 0.00033677814, 0.00035866388, 0.00038197188, 0.00040679456, 0.00043323036, 0.00046138411, 0.00049136745, 0.00052329927, 0.00055730621, 0.00059352311, 0.00063209358, 0.00067317058, 0.00071691700, 0.00076350630, 0.00081312324, 0.00086596457, 0.00092223983, 0.00098217216, 0.0010459992, 0.0011139742, 0.0011863665, 0.0012634633, 0.0013455702, 0.0014330129, 0.0015261382, 0.0016253153, 0.0017309374, 0.0018434235, 0.0019632195, 0.0020908006, 0.0022266726, 0.0023713743, 0.0025254795, 0.0026895994, 0.0028643847, 0.0030505286, 0.0032487691, 0.0034598925, 0.0036847358, 0.0039241906, 0.0041792066, 0.0044507950, 0.0047400328, 0.0050480668, 0.0053761186, 0.0057254891, 0.0060975636, 0.0064938176, 0.0069158225, 0.0073652516, 0.0078438871, 0.0083536271, 0.0088964928, 0.009474637, 0.010090352, 0.010746080, 0.011444421, 0.012188144, 0.012980198, 0.013823725, 0.014722068, 0.015678791, 0.016697687, 0.017782797, 0.018938423, 0.020169149, 0.021479854, 0.022875735, 0.024362330, 0.025945531, 0.027631618, 0.029427276, 0.031339626, 0.033376252, 0.035545228, 0.037855157, 0.040315199, 0.042935108, 0.045725273, 0.048696758, 0.051861348, 0.055231591, 0.058820850, 0.062643361, 0.066714279, 0.071049749, 0.075666962, 0.080584227, 0.085821044, 0.091398179, 0.097337747, 0.10366330, 0.11039993, 0.11757434, 0.12521498, 0.13335215, 0.14201813, 0.15124727, 0.16107617, 0.17154380, 0.18269168, 0.19456402, 0.20720788, 0.22067342, 0.23501402, 0.25028656, 0.26655159, 0.28387361, 0.30232132, 0.32196786, 0.34289114, 0.36517414, 0.38890521, 0.41417847, 0.44109412, 0.46975890, 0.50028648, 0.53279791, 0.56742212, 0.60429640, 0.64356699, 0.68538959, 0.72993007, 0.77736504, 0.82788260, 0.88168307, 0.9389798, 1.0, }) end __FILES["codecs/audio/VorbisComment"] = function() -- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value"; Vorbis, Opus, FLAC) <-> Types.Tags. local VorbisComment = {} type Field = { key: string, value: string } local TO_TAG: { [string]: string } = { tracknumber = "track", discnumber = "disc", description = "comment" } local TO_FIELD: { [string]: string } = { track = "TRACKNUMBER", disc = "DISCNUMBER" } function VorbisComment.tagKey(name: string): string local k = string.lower(name) return TO_TAG[k] or k end function VorbisComment.fieldName(key: string): string return TO_FIELD[key] or string.upper(key) end function VorbisComment.tags(comments: { string }): ({ [string]: string }, { Field }) local tags: { [string]: string } = {} local raw: { Field } = {} for _, s in comments do local eq = string.find(s, "=", 1, true) if eq then local name, v = string.sub(s, 1, eq - 1), string.sub(s, eq + 1) table.insert(raw, { key = string.upper(name), value = v }) local k = VorbisComment.tagKey(name) local old = tags[k] tags[k] = if old then old .. "; " .. v else v end end return tags, raw end function VorbisComment.fields(tags: { [any]: any }): { string } local keys = {} for k, v in tags do if type(k) == "string" and type(v) == "string" then table.insert(keys, k) end end table.sort(keys) local out: { string } = table.create(#keys) :: any for i, k in keys do out[i] = VorbisComment.fieldName(k) .. "=" .. tags[k] end return out end return VorbisComment end __FILES["codecs/audio/WavPack"] = function() -- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). -- Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). Not supported: DSD, pre-4.0 -- streams (version < 0x402). local Err = __include("core/Err") local Block = __include("codecs/audio/WavPack/Block") local WavPack = {} type Header = { size: number, -- the whole block (ckSize + 8) version: number, index: number, -- the first sample of the block (40 bits) total: number, -- total samples of the file (-1: unknown) samples: number, flags: number, crc: number, } local RATES = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 } WavPack.MONO, WavPack.HYBRID, WavPack.FLOAT, WavPack.INITIAL, WavPack.FINAL = 4, 8, 0x80, 0x800, 0x1000 WavPack.DSD = 0x80000000 function WavPack.header(buf: buffer, at: number, limit: number?): (Header?, string?) local lim = math.min(limit or buffer.len(buf), buffer.len(buf)) if at < 0 or at + 32 > lim then return nil, "truncated block header" end if buffer.readstring(buf, at, 4) ~= "wvpk" then return nil, "no block header" end local ck = buffer.readu32(buf, at + 4) local version = buffer.readu16(buf, at + 8) if ck % 2 == 1 or ck < 24 or ck > 0x1000000 then return nil, "bad block size" end if version < 0x402 or version > 0x410 then return nil, "unsupported: stream version " .. string.format("0x%x", version) end local total = buffer.readu32(buf, at + 12) local tu8 = buffer.readu8(buf, at + 11) local h: Header = { size = ck + 8, version = version, index = buffer.readu32(buf, at + 16) + buffer.readu8(buf, at + 10) * 4294967296, total = if total == 0xFFFFFFFF then -1 else total + tu8 * 4294967296 - tu8, samples = buffer.readu32(buf, at + 20), flags = buffer.readu32(buf, at + 24), crc = buffer.readu32(buf, at + 28), } if at + h.size > lim then return nil, "truncated block" end return h, nil end type Info = { channels: number, channelMask: number, sampleRate: number, bitsPerSample: number, bytesPerSample: number, float: boolean, hybrid: boolean, md5: string?, version: number, } function WavPack.info(buf: buffer, at: number, limit: number?): (Info?, Err.Err?) local h, herr = WavPack.header(buf, at, limit) if not h then return nil, Err.from(herr, at) end local m, merr = Block.meta(buf, at, h.size) if not m then return nil, Err.from(merr, at) end local flags = h.flags if bit32.band(flags, WavPack.DSD) ~= 0 then return nil, Err.new(Err.UNSUPPORTED, "DSD audio") end local bytes = bit32.band(flags, 3) + 1 local info: Info = { channels = if bit32.band(flags, WavPack.MONO) ~= 0 then 1 else 2, channelMask = 0, sampleRate = 44100, bitsPerSample = bytes * 8 - bit32.band(bit32.rshift(flags, 13), 31), bytesPerSample = bytes, float = bit32.band(flags, WavPack.FLOAT) ~= 0, hybrid = bit32.band(flags, WavPack.HYBRID) ~= 0, version = h.version, } info.channelMask = if info.channels == 1 then 4 else 3 local sr = bit32.band(bit32.rshift(flags, 23), 15) if sr < 15 then info.sampleRate = RATES[sr + 1] end local o = m[0x27] -- ID_SAMPLE_RATE if o and (m[0x27 + 256] == 3 or m[0x27 + 256] == 4) then local rate = buffer.readu8(buf, o) + buffer.readu8(buf, o + 1) * 256 + buffer.readu8(buf, o + 2) * 65536 if m[0x27 + 256] == 4 then rate += bit32.band(buffer.readu8(buf, o + 3), 0x7F) * 16777216 end info.sampleRate = rate end o = m[0xD] -- ID_CHANNEL_INFO if o then local len = m[0xD + 256] if len == 0 or len > 7 then return nil, Err.new(Err.CORRUPT, "bad channel info", o) end local mask = 0 if len >= 6 then info.channels = buffer.readu8(buf, o) + bit32.band(buffer.readu8(buf, o + 2), 0xF) * 256 + 1 mask = buffer.readu8(buf, o + 3) + buffer.readu8(buf, o + 4) * 256 + buffer.readu8(buf, o + 5) * 65536 if len == 7 then mask += buffer.readu8(buf, o + 6) * 16777216 end else info.channels = buffer.readu8(buf, o) for k = 1, len - 1 do mask += buffer.readu8(buf, o + k) * 256 ^ (k - 1) end end info.channelMask = mask end if info.channels < 1 then return nil, Err.new(Err.CORRUPT, "no channels") end if info.sampleRate < 1 then return nil, Err.new(Err.CORRUPT, "bad sample rate") end return info, nil end function WavPack.md5(buf: buffer, at: number, limit: number?): string? local h = WavPack.header(buf, at, limit) if not h then return nil end local m = Block.meta(buf, at, h.size) if not m then return nil end local o = m[0x26] if not o or m[0x26 + 256] ~= 16 then return nil end local hex = table.create(16, "") for k = 0, 15 do hex[k + 1] = string.format("%02x", buffer.readu8(buf, o + k)) end return table.concat(hex) end type Decoder = { channels: number, pcm: { number }, frame: (self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?) -> (number?, Err.Err?), state: Block.State, } local function frame(self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?): (number?, Err.Err?) local C = self.channels local n = -1 local c0 = 0 for i, at in blocks do if c0 >= C then break end local h, herr = WavPack.header(buf, at) if not h then return nil, Err.from(herr, at) end if n < 0 then n = h.samples if n * C > 16777216 then return nil, Err.new(Err.LIMIT, "a frame of " .. n .. " samples x " .. C .. " channels", at) end if #self.pcm < n * C then self.pcm = table.create(n * C, 0) end elseif h.samples ~= n then return nil, Err.new(Err.CORRUPT, "blocks of a frame differ in length", at) end local cb, cp, cs = nil, nil, nil if cbuf and cblocks and cblocks[i] then local ch = WavPack.header(cbuf, cblocks[i]) if ch and ch.samples == h.samples and ch.index == h.index then cb, cp, cs = cbuf, cblocks[i], ch.size end end local got, msg = Block.decode(self.state, buf, at, h.size, self.pcm, c0, C, cb, cp, cs) if not got then return nil, Err.from(msg, at) end c0 += got end if n < 0 then return 0, nil end if c0 < C then return nil, Err.new(Err.CORRUPT, "a frame is missing channels") end return n, nil end function WavPack.decoder(channels: number): Decoder return { channels = channels, pcm = table.create(4096 * channels, 0), frame = frame, state = Block.state(), } end WavPack.checksum = Block.checksum WavPack.meta = Block.meta return WavPack end __FILES["codecs/audio/WavPack/Block"] = @native function() -- codecs/audio/WavPack/Block: one WavPack 4 / 5 block (one mono or stereo stream of a frame) -> samples. -- Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt): unpack.c, read_words.c, -- unpack_floats.c, decorr_utils.c / entropy_utils.c, open_utils.c. DSD blocks are UNSUPPORTED. local Tables = __include("codecs/audio/WavPack/Tables") local readu8, readi8, readu16, readi16, readu32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32 local writeu32, readf32 = buffer.writeu32, buffer.readf32 local band, rshift, countlz = bit32.band, bit32.rshift, bit32.countlz local exp2s, log2, restoreWeight = Tables.exp2s, Tables.log2, Tables.restoreWeight local sign, clamp = math.sign, math.clamp local Block = {} local TWO32 = 4294967296 local P2: { number } = table.create(34, 0) for i = 0, 33 do P2[i + 1] = 2 ^ i end local ONES: { number } = table.create(256, 0) for b = 0, 255 do local n, v = 0, b while v % 2 == 1 do n += 1 v = v // 2 end ONES[b + 1] = n end local MONO_FLAG, HYBRID, JOINT, CROSS, SHAPE, FLOAT, INT32 = 4, 8, 0x10, 0x20, 0x40, 0x80, 0x100 local HBITRATE, HBALANCE, NEW_SHAPING, FALSE_STEREO, DSD = 0x200, 0x400, 0x20000000, 0x40000000, 0x80000000 local FLOAT_SHIFT_ONES, FLOAT_SHIFT_SAME, FLOAT_SHIFT_SENT, FLOAT_ZEROS_SENT, FLOAT_NEG_ZEROS = 1, 2, 4, 8, 0x10 local PAD = 64 -- zero bytes after each copied bitstream: reads past the end stay in the buffer local MAX_SAMPLES = 2 ^ 20 local D2, D1 = 17, 9 -- the first data index of the work table (stereo / mono): 8 frames of history in front type Meta = { [number]: number } -- id -> offset; id + 256 -> byte length @native function Block.meta(buf: buffer, p: number, size: number): (Meta?, string?) local m: Meta = {} local q, stop = p + 32, p + size while stop - q >= 2 do local id = readu8(buf, q) local len = readu8(buf, q + 1) * 2 q += 2 if band(id, 0x80) ~= 0 then if stop - q < 2 then return nil, "truncated metadata" end len += readu8(buf, q) * 512 + readu8(buf, q + 1) * 131072 q += 2 id -= 0x80 end local odd = 0 if band(id, 0x40) ~= 0 then if len == 0 then return nil, "odd-sized empty metadata" end id -= 0x40 len -= 1 odd = 1 end if stop - q < len + odd then return nil, "truncated metadata" end m[id] = q m[id + 256] = len q += len + odd end return m, nil end @native function Block.checksum(buf: buffer, p: number, m: Meta): boolean local o = m[0x2F] if not o then return true end local len = m[0x2F + 256] if len ~= 2 and len ~= 4 then return false end local words = (o - 2 - p) // 2 local csum = TWO32 - 1 for i = 0, words - 1 do csum = (csum * 3 + readu16(buf, p + i * 2)) % TWO32 end if len == 4 then return readu32(buf, o) == csum end csum = bit32.bxor(csum, rshift(csum, 16)) return readu16(buf, o) == band(csum, 0xFFFF) end type Reader = { b: buffer, p: number, e: number, n: number } type State = { [string]: any } @native function Block.state(): State return { W = table.create(D2 + 2 * 4096, 0), term = table.create(16, 0), delta = table.create(16, 0), wA = table.create(16, 0), wB = table.create(16, 0), sA = table.create(16 * 8, 0), sB = table.create(16 * 8, 0), med = table.create(6, 0), slow = { 0, 0 }, limit = { 0, 0 }, bacc = { 0, 0 }, bdelta = { 0, 0 }, sacc = { 0, 0 }, sdelta = { 0, 0 }, err = { 0, 0 }, R1 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, R2 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, R3 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, scratch = buffer.create(4), } end @native local function openReader(R: Reader, buf: buffer, o: number, len: number) if buffer.len(R.b) < len + PAD then R.b = buffer.create(len + PAD + 1024) else buffer.fill(R.b, len, 0, PAD) end buffer.copy(R.b, 0, buf, o, len) R.p = 0 R.e = len * 8 R.n = len + PAD end @native local function bits(R: Reader, n: number): number if n <= 0 then return 0 end local p = R.p local byte = rshift(p, 3) if byte + 8 > R.n then R.p = R.e + 1 return 0 end local b = R.b if n <= 25 then R.p = p + n return band(rshift(readu32(b, byte), band(p, 7)), P2[n + 1] - 1) end local lo = band(rshift(readu32(b, byte), band(p, 7)), 0xFFFF) p += 16 R.p = p + n - 16 return lo + band(rshift(readu32(b, rshift(p, 3)), band(p, 7)), P2[n - 15] - 1) * 65536 end @native local function bit(R: Reader): number return bits(R, 1) end @native local function trailing(R: Reader, max: number): number local c = 0 while c < max do local p = R.p local byte = rshift(p, 3) if byte + 8 > R.n then R.p = R.e + 1 return max end local ones = ONES[band(rshift(readu32(R.b, byte), band(p, 7)), 255) + 1] if ones < 8 then if c + ones >= max then R.p = p + (max - c) return max end R.p = p + ones + 1 return c + ones end c += 8 R.p = p + 8 end R.p -= c - max return max end -- the "Elias gamma"-like count (cbits ones, a zero, cbits - 1 bits) -> value | nil (33 ones) @native local function gamma(R: Reader): number? local c = trailing(R, 33) if c == 33 then return nil end if c < 2 then return c end return bits(R, c - 1) + P2[c] end -- read_code @native local function readCode(R: Reader, maxcode: number): number if maxcode < 2 then return if maxcode == 1 then bits(R, 1) else 0 end local bc = 32 - countlz(maxcode) local extras = P2[bc + 1] - maxcode - 1 local code = bits(R, bc - 1) if code >= extras then code = code * 2 - extras + bits(R, 1) end return code end -- ones(R) -> the unary count with its escape (LIMIT_ONES = 16) | nil (the end marker) @native local function onesCount(R: Reader): number? local c = trailing(R, 17) if c == 17 then return nil end if c == 16 then local g = gamma(R) if not g then return nil end c = g + 16 end return c end -- get_words_lossless @native local function wordsLossless(st: State, count: number, d: number): boolean local R: Reader = st.R1 local b, pos, lim = R.b, R.p, R.e local W = st.W local med = st.med local stereo = d == D2 local a0, a1, a2, c0, c1, c2 = med[4], med[5], med[6], med[1], med[2], med[3] if not stereo then a0, a1, a2, c0, c1, c2 = med[1], med[2], med[3], 0, 0, 0 end local hz, ho, za = 0, 0, 0 for idx = d, d + count - 1 do if stereo then a0, a1, a2, c0, c1, c2 = c0, c1, c2, a0, a1, a2 end if pos > lim then return false end if hz ~= 0 then hz = 0 local maxcode = a0 // 16 a0 -= ((a0 + 126) // 128) * 2 local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) local low, used = 0, 0 if maxcode < 2 then if maxcode == 1 then low, used = band(w, 1), 1 end else local bc = 32 - countlz(maxcode) if bc > 24 then R.p = pos low = readCode(R, maxcode) pos = R.p w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) else local extras = P2[bc + 1] - maxcode - 1 low = band(w, P2[bc] - 1) if low >= extras then low = low * 2 - extras + band(rshift(w, bc - 1), 1) used = bc else used = bc - 1 end end end if band(rshift(w, used), 1) ~= 0 then W[idx] = -low - 1 else W[idx] = low end pos += used + 1 continue end if a0 < 2 and ho == 0 and c0 < 2 then if za > 0 then za -= 1 if za > 0 then W[idx] = 0 continue end else R.p = pos local g = gamma(R) pos = R.p if not g then return false end za = g if za > 0 then a0, a1, a2, c0, c1, c2 = 0, 0, 0, 0, 0, 0 W[idx] = 0 continue end end end local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) local ones = ONES[band(w, 255) + 1] if ones == 8 then ones = 8 + ONES[band(rshift(w, 8), 255) + 1] end if ones < 16 then pos += ones + 1 else if band(w, 0x10000) ~= 0 then return false end R.p = pos + 17 local g = gamma(R) pos = R.p if not g then return false end ones = g + 16 end local hold = ho ho = band(ones, 1) hz = 1 - ho ones = ones // 2 + hold local low, high if ones == 0 then low = 0 high = a0 // 16 a0 -= ((a0 + 126) // 128) * 2 else low = a0 // 16 + 1 a0 += ((a0 + 128) // 128) * 5 if ones == 1 then high = low + a1 // 16 a1 -= ((a1 + 62) // 64) * 2 else low += a1 // 16 + 1 a1 += ((a1 + 64) // 64) * 5 if ones == 2 then high = low + a2 // 16 a2 -= ((a2 + 30) // 32) * 2 else low += (ones - 2) * (a2 // 16 + 1) high = low + a2 // 16 a2 += ((a2 + 32) // 32) * 5 end end end local maxcode = high - low w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) local used = 0 if maxcode < 2 then if maxcode == 1 then low += band(w, 1) used = 1 end else if maxcode >= 536870912 then return false end local bc = 32 - countlz(maxcode) if bc > 24 then R.p = pos low += readCode(R, maxcode) pos = R.p w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) else local extras = P2[bc + 1] - maxcode - 1 local code = band(w, P2[bc] - 1) if code >= extras then code = code * 2 - extras + band(rshift(w, bc - 1), 1) used = bc else used = bc - 1 end low += code end end if band(rshift(w, used), 1) ~= 0 then W[idx] = -low - 1 else W[idx] = low end pos += used + 1 end R.p = pos return pos <= lim end @native local function updateErrorLimit(st: State, flags: number, mono: boolean) local bacc, bdelta, slow, limit = st.bacc, st.bdelta, st.slow, st.limit bacc[1] = (bacc[1] + bdelta[1]) % TWO32 local br0 = bacc[1] // 65536 if mono then if band(flags, HBITRATE) ~= 0 then local sl0 = (slow[1] + 128) // 256 limit[1] = if sl0 - br0 > -256 then exp2s(sl0 - br0 + 256) % TWO32 else 0 else limit[1] = exp2s(br0) % TWO32 end return end bacc[2] = (bacc[2] + bdelta[2]) % TWO32 local br1 = bacc[2] // 65536 if band(flags, HBITRATE) ~= 0 then local sl0 = (slow[1] + 128) // 256 local sl1 = (slow[2] + 128) // 256 if band(flags, HBALANCE) ~= 0 then local balance = (sl1 - sl0 + br1 + 1) // 2 if balance > br0 then br1 = br0 * 2 br0 = 0 elseif -balance > br0 then br0 = br0 * 2 br1 = 0 else br1 = br0 + balance br0 = br0 - balance end end limit[1] = if sl0 - br0 > -256 then exp2s(sl0 - br0 + 256) % TWO32 else 0 limit[2] = if sl1 - br1 > -256 then exp2s(sl1 - br1 + 256) % TWO32 else 0 else limit[1] = exp2s(br0) % TWO32 limit[2] = exp2s(br1) % TWO32 end end -- get_word @native local function getWord(st: State, chan: number, flags: number, mono: boolean): (number?, number) local R: Reader = st.R1 local med = st.med local mb = chan * 3 local correction = 0 if R.p > R.e then return nil, 0 end if med[1] < 2 and st.hz == 0 and st.ho == 0 and med[4] < 2 then if st.za > 0 then st.za -= 1 if st.za > 0 then local s = st.slow s[chan + 1] -= (s[chan + 1] + 128) // 256 return 0, 0 end else local g = gamma(R) if not g then return nil, 0 end st.za = g if g > 0 then local s = st.slow s[chan + 1] -= (s[chan + 1] + 128) // 256 for k = 1, 6 do med[k] = 0 end return 0, 0 end end end local ones if st.hz ~= 0 then ones = 0 st.hz = 0 else local c = onesCount(R) if not c then return nil, 0 end ones = c if st.ho ~= 0 then st.ho = band(ones, 1) ones = ones // 2 + 1 else st.ho = band(ones, 1) ones = ones // 2 end st.hz = 1 - st.ho end if band(flags, HYBRID) ~= 0 and chan == 0 then updateErrorLimit(st, flags, mono) end local m0, m1, m2 = med[mb + 1], med[mb + 2], med[mb + 3] local low, high if ones == 0 then low = 0 high = m0 // 16 m0 -= ((m0 + 126) // 128) * 2 else low = m0 // 16 + 1 m0 += ((m0 + 128) // 128) * 5 if ones == 1 then high = low + m1 // 16 m1 -= ((m1 + 62) // 64) * 2 else low += m1 // 16 + 1 m1 += ((m1 + 64) // 64) * 5 if ones == 2 then high = low + m2 // 16 m2 -= ((m2 + 30) // 32) * 2 else low += (ones - 2) * (m2 // 16 + 1) high = low + m2 // 16 m2 += ((m2 + 32) // 32) * 5 end end end med[mb + 1], med[mb + 2], med[mb + 3] = m0 % TWO32, m1 % TWO32, m2 % TWO32 low = band(low % TWO32, 0x7FFFFFFF) high = band(high % TWO32, 0x7FFFFFFF) if low > high then high = low end local mid = (high + low + 1) // 2 local limit = st.limit[chan + 1] if limit == 0 then mid = readCode(R, high - low) + low else while high - low > limit do if R.p > R.e then return nil, 0 end if bits(R, 1) == 1 then low = mid mid = (high + low + 1) // 2 else high = mid - 1 mid = (high + low + 1) // 2 end end end local sign = bits(R, 1) if st.wvc and limit ~= 0 then local value = readCode(st.R2, high - low) + low correction = if sign == 1 then mid - value else value - mid end if band(flags, HBITRATE) ~= 0 then local s = st.slow s[chan + 1] = s[chan + 1] - (s[chan + 1] + 128) // 256 + log2(mid) end return if sign == 1 then -mid - 1 else mid, correction end -- the decorrelation passes over the whole block (stereo, from W[D2]): unpack.c decorr_stereo_pass @native local function passesStereo(st: State, n: number) local W = st.W local last = D2 + 2 * n - 2 local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB for t = 1, st.nterms do local term, delta, wA, wB = terms[t], deltas[t], wAs[t], wBs[t] local so = (t - 1) * 8 if term > 8 then local a0, a1, b0, b1 = sA[so + 1], sA[so + 2], sB[so + 1], sB[so + 2] local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 for i = D2, last, 2 do local sam = a0 + (a0 - a1) // dv local x = W[i] local o = (wA * sam + 512) // 1024 + x wA += delta * sign(sam * x) a1, a0 = a0, o W[i] = o sam = b0 + (b0 - b1) // dv x = W[i + 1] o = (wB * sam + 512) // 1024 + x wB += delta * sign(sam * x) b1, b0 = b0, o W[i + 1] = o end elseif term > 0 then for j = 0, term - 1 do W[D2 + 2 * (j - term)] = sA[so + j + 1] W[D2 + 1 + 2 * (j - term)] = sB[so + j + 1] end local back = 2 * term for i = D2, last, 2 do local sam = W[i - back] local x = W[i] W[i] = (wA * sam + 512) // 1024 + x wA += delta * sign(sam * x) sam = W[i + 1 - back] x = W[i + 1] W[i + 1] = (wB * sam + 512) // 1024 + x wB += delta * sign(sam * x) end elseif term == -1 then local sa = sA[so + 1] for i = D2, last, 2 do local x = W[i] local sam = x + (wA * sa + 512) // 1024 wA = clamp(wA + delta * sign(sa * x), -1024, 1024) W[i] = sam x = W[i + 1] sa = x + (wB * sam + 512) // 1024 wB = clamp(wB + delta * sign(sam * x), -1024, 1024) W[i + 1] = sa end elseif term == -2 then local sb = sB[so + 1] for i = D2, last, 2 do local x = W[i + 1] local sam = x + (wB * sb + 512) // 1024 wB = clamp(wB + delta * sign(sb * x), -1024, 1024) W[i + 1] = sam x = W[i] sb = x + (wA * sam + 512) // 1024 wA = clamp(wA + delta * sign(sam * x), -1024, 1024) W[i] = sb end else -- -3 local sa, sb = sA[so + 1], sB[so + 1] for i = D2, last, 2 do local x = W[i] local samA = x + (wA * sa + 512) // 1024 wA = clamp(wA + delta * sign(sa * x), -1024, 1024) x = W[i + 1] local samB = x + (wB * sb + 512) // 1024 wB = clamp(wB + delta * sign(sb * x), -1024, 1024) W[i], W[i + 1] = samA, samB sa, sb = samB, samA end end end end -- the decorrelation passes (mono, from W[D1]): unpack.c decorr_mono_pass @native local function passesMono(st: State, n: number) local W = st.W local last = D1 + n - 1 local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA for t = 1, st.nterms do local term, delta, wA = terms[t], deltas[t], wAs[t] local so = (t - 1) * 8 if term > 8 then local a0, a1 = sA[so + 1], sA[so + 2] local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 for i = D1, last do local sam = a0 + (a0 - a1) // dv local x = W[i] local o = (wA * sam + 512) // 1024 + x wA += delta * sign(sam * x) a1, a0 = a0, o W[i] = o end else for j = 0, term - 1 do W[D1 + j - term] = sA[so + j + 1] end for i = D1, last do local sam = W[i - term] local x = W[i] W[i] = (wA * sam + 512) // 1024 + x wA += delta * sign(sam * x) end end end end @native local function shaped(st: State, c: number, flags: number, correction: number): number -- returns the value to subtract (temp) and updates the error state (noise shaping, unpack.c) local sacc, sdelta, err = st.sacc, st.sdelta, st.err sacc[c] = (sacc[c] + sdelta[c]) % TWO32 local sw = sacc[c] // 65536 if sw >= 32768 then sw -= 65536 end local temp = -((sw * err[c] + 512) // 1024) if band(flags, NEW_SHAPING) ~= 0 and sw < 0 and temp ~= 0 then if temp == err[c] then temp = if temp < 0 then temp + 1 else temp - 1 end err[c] = temp - correction else err[c] = -correction end return temp end @native local function hybridMono(st: State, n: number, flags: number): boolean local W = st.W local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA local nterms = st.nterms local m = 0 local crc = TWO32 - 1 for i = 0, n - 1 do local word, corr = getWord(st, 0, flags, true) if not word then return false end local rw = word for t = 1, nterms do local term, so = terms[t], (t - 1) * 8 local sam, k if term > 8 then sam = if term % 2 == 1 then 2 * sA[so + 1] - sA[so + 2] else (3 * sA[so + 1] - sA[so + 2]) // 2 sA[so + 2] = sA[so + 1] k = 0 else sam = sA[so + m + 1] k = band(m + term, 7) end local temp = (wAs[t] * sam + 512) // 1024 + rw wAs[t] += deltas[t] * sign(sam * rw) sA[so + k + 1] = temp rw = temp end m = band(m + 1, 7) if band(flags, SHAPE) ~= 0 then local temp = shaped(st, 1, flags, corr) rw += corr - temp else rw += corr end crc = (crc * 3 + rw) % TWO32 W[D1 + i] = rw end st.crcv = crc return true end @native local function hybridStereo(st: State, n: number, flags: number): boolean local W = st.W local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB local nterms = st.nterms local m = 0 local crc = TWO32 - 1 local cross = band(flags, CROSS) ~= 0 local joint = band(flags, JOINT) ~= 0 for i = 0, n - 1 do local left, corr0 = getWord(st, 0, flags, false) if not left then return false end local right, corr1 = getWord(st, 1, flags, false) if not right then return false end local leftc, rightc = 0, 0 if cross then leftc, rightc = left + corr0, right + corr1 for t = 1, nterms do local term, so = terms[t], (t - 1) * 8 if term > 0 then local samA, samB if term > 8 then if term % 2 == 1 then samA = 2 * sA[so + 1] - sA[so + 2] samB = 2 * sB[so + 1] - sB[so + 2] else samA = (3 * sA[so + 1] - sA[so + 2]) // 2 samB = (3 * sB[so + 1] - sB[so + 2]) // 2 end else samA, samB = sA[so + m + 1], sB[so + m + 1] end leftc += (wAs[t] * samA + 512) // 1024 rightc += (wBs[t] * samB + 512) // 1024 elseif term == -1 then leftc += (wAs[t] * sA[so + 1] + 512) // 1024 rightc += (wBs[t] * leftc + 512) // 1024 else rightc += (wBs[t] * sB[so + 1] + 512) // 1024 if term == -3 then leftc += (wAs[t] * sA[so + 1] + 512) // 1024 else leftc += (wAs[t] * rightc + 512) // 1024 end end end if joint then rightc -= leftc // 2 leftc += rightc end end for t = 1, nterms do local term, delta, so = terms[t], deltas[t], (t - 1) * 8 if term > 0 then local samA, samB, k if term > 8 then if term % 2 == 1 then samA = 2 * sA[so + 1] - sA[so + 2] samB = 2 * sB[so + 1] - sB[so + 2] else samA = (3 * sA[so + 1] - sA[so + 2]) // 2 samB = (3 * sB[so + 1] - sB[so + 2]) // 2 end sA[so + 2] = sA[so + 1] sB[so + 2] = sB[so + 1] k = 0 else samA, samB = sA[so + m + 1], sB[so + m + 1] k = band(m + term, 7) end local left2 = (wAs[t] * samA + 512) // 1024 + left local right2 = (wBs[t] * samB + 512) // 1024 + right wAs[t] += delta * sign(samA * left) wBs[t] += delta * sign(samB * right) left, right = left2, right2 sA[so + k + 1], sB[so + k + 1] = left, right elseif term == -1 then local sa = sA[so + 1] local left2 = left + (wAs[t] * sa + 512) // 1024 wAs[t] = clamp(wAs[t] + delta * sign(sa * left), -1024, 1024) left = left2 local right2 = right + (wBs[t] * left2 + 512) // 1024 wBs[t] = clamp(wBs[t] + delta * sign(left2 * right), -1024, 1024) right = right2 sA[so + 1] = right else local sb = sB[so + 1] local right2 = right + (wBs[t] * sb + 512) // 1024 wBs[t] = clamp(wBs[t] + delta * sign(sb * right), -1024, 1024) right = right2 if term == -3 then right2 = sA[so + 1] sA[so + 1] = right end local left2 = left + (wAs[t] * right2 + 512) // 1024 wAs[t] = clamp(wAs[t] + delta * sign(right2 * left), -1024, 1024) left = left2 sB[so + 1] = left end end m = band(m + 1, 7) if not cross then leftc, rightc = left + corr0, right + corr1 if joint then rightc -= leftc // 2 leftc += rightc end end if joint then right -= left // 2 left += right end if band(flags, SHAPE) ~= 0 then local temp = shaped(st, 1, flags, leftc - left) left = leftc - temp temp = shaped(st, 2, flags, rightc - right) right = rightc - temp else left, right = leftc, rightc end crc = (crc * 9 + left * 3 + right) % TWO32 W[D2 + 2 * i], W[D2 + 2 * i + 1] = left, right end st.crcv = crc return true end @native local function readMeta(st: State, buf: buffer, m: Meta, flags: number, version: number): string? local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 local o = m[2] if o then -- decorrelation terms local cnt = m[2 + 256] if cnt > 16 then return "too many decorrelation terms" end st.nterms = cnt for i = 0, cnt - 1 do local v = readu8(buf, o + i) local t = cnt - i local term = band(v, 0x1F) - 5 if term == 0 or term < -3 or (term > 8 and term < 17) or term > 18 or (mono and term < 0) then return "bad decorrelation term" end st.term[t] = term st.delta[t] = band(rshift(v, 5), 7) end end local nterms = st.nterms o = m[3] if o then -- weights, from the last pass back for t = 1, nterms do st.wA[t], st.wB[t] = 0, 0 end local cnt = m[3 + 256] if not mono then cnt //= 2 end if cnt > nterms then return "too many decorrelation weights" end local q = o for t = nterms, nterms - cnt + 1, -1 do st.wA[t] = restoreWeight(readi8(buf, q)) q += 1 if not mono then st.wB[t] = restoreWeight(readi8(buf, q)) q += 1 end end end local sA, sB = st.sA, st.sB o = m[4] if o then -- decorrelation samples, from the last pass back for k = 1, nterms * 8 do sA[k], sB[k] = 0, 0 end local q, stop = o, o + m[4 + 256] if version == 0x402 and band(flags, HYBRID) ~= 0 then if q + (if mono then 2 else 4) > stop then return "bad decorrelation samples" end st.err[1] = exp2s(readi16(buf, q)) q += 2 if not mono then st.err[2] = exp2s(readi16(buf, q)) q += 2 end end local t = nterms while t >= 1 and q < stop do local term, so = st.term[t], (t - 1) * 8 if term > 8 then if q + (if mono then 4 else 8) > stop then return "bad decorrelation samples" end sA[so + 1], sA[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) q += 4 if not mono then sB[so + 1], sB[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) q += 4 end elseif term < 0 then if q + 4 > stop then return "bad decorrelation samples" end sA[so + 1], sB[so + 1] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) q += 4 else for k = 1, term do if q + (if mono then 2 else 4) > stop then return "bad decorrelation samples" end sA[so + k] = exp2s(readi16(buf, q)) q += 2 if not mono then sB[so + k] = exp2s(readi16(buf, q)) q += 2 end end end t -= 1 end if q ~= stop then return "bad decorrelation samples" end end o = m[5] if o then -- entropy medians if m[5 + 256] ~= (if mono then 6 else 12) then return "bad entropy variables" end for k = 0, (if mono then 2 else 5) do st.med[k + 1] = exp2s(readu16(buf, o + k * 2)) % TWO32 end end o = m[6] if o then -- hybrid profile local q, stop = o, o + m[6 + 256] local w = if mono then 2 else 4 if band(flags, HBITRATE) ~= 0 then if q + w > stop then return "bad hybrid profile" end st.slow[1] = exp2s(readu16(buf, q)) % TWO32 if not mono then st.slow[2] = exp2s(readu16(buf, q + 2)) % TWO32 end q += w end if q + w > stop then return "bad hybrid profile" end st.bacc[1] = readu16(buf, q) * 65536 if not mono then st.bacc[2] = readu16(buf, q + 2) * 65536 end q += w if q < stop then if q + w > stop then return "bad hybrid profile" end st.bdelta[1] = exp2s(readi16(buf, q)) if not mono then st.bdelta[2] = exp2s(readi16(buf, q + 2)) end q += w if q < stop then return "bad hybrid profile" end end end o = m[7] if o then -- noise shaping local len = m[7 + 256] if len == 2 then st.sacc[1] = (restoreWeight(readi8(buf, o)) * 65536) % TWO32 st.sacc[2] = (restoreWeight(readi8(buf, o + 1)) * 65536) % TWO32 elseif len >= (if mono then 4 else 8) then st.err[1] = exp2s(readi16(buf, o)) st.sacc[1] = exp2s(readi16(buf, o + 2)) % TWO32 if not mono then st.err[2] = exp2s(readi16(buf, o + 4)) st.sacc[2] = exp2s(readi16(buf, o + 6)) % TWO32 end local q = o + (if mono then 4 else 8) if len == (if mono then 6 else 12) then st.sdelta[1] = exp2s(readi16(buf, q)) % TWO32 if not mono then st.sdelta[2] = exp2s(readi16(buf, q + 2)) % TWO32 end end else return "bad shaping weights" end end o = m[8] if o then if m[8 + 256] ~= 4 then return "bad float info" end st.fflags, st.fshift, st.fmaxexp = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2) end o = m[9] if o then if m[9 + 256] ~= 4 then return "bad int32 info" end st.isent, st.izeros, st.iones, st.idups = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2), readu8(buf, o + 3) end return nil end -- float_values (R = the wvx stream or nil) @native local function floatValue(st: State, v: number, R: Reader?): number local fflags, exp = st.fflags, st.fmaxexp local mant, e, sign = 0, 0, 0 if v == 0 then if R then if band(fflags, FLOAT_ZEROS_SENT) ~= 0 then if bits(R, 1) == 1 then mant = bits(R, 23) if exp >= 25 then e = bits(R, 8) end sign = bits(R, 1) elseif band(fflags, FLOAT_NEG_ZEROS) ~= 0 then sign = bits(R, 1) end end end else v = (v * P2[band(st.fshift, 31) + 1]) % TWO32 if v >= 2147483648 then v -= TWO32 end if v < 0 then v = -v sign = 1 end if R then if v == 0x1000000 then if bits(R, 1) == 1 then mant = bits(R, 23) end e = 255 else local shift = 0 if exp > 0 then while v < 0x800000 do exp -= 1 if exp == 0 then break end shift += 1 v *= 2 end end shift = band(shift, 31) if shift > 0 then if band(fflags, FLOAT_SHIFT_ONES) ~= 0 or (band(fflags, FLOAT_SHIFT_SAME) ~= 0 and bits(R, 1) == 1) then v += P2[shift + 1] - 1 elseif band(fflags, FLOAT_SHIFT_SENT) ~= 0 then local mask = P2[shift + 1] - 1 local zeros = 0 local maxOnes, minZeros = st.fmaxones, st.fminzeros if maxOnes > 0 and shift > maxOnes then zeros = shift - maxOnes end if minZeros > zeros then zeros = if minZeros > shift then shift else minZeros end local sc = shift - zeros if sc > 0 then v = bit32.bor(v % TWO32, band(bits(R, sc) * P2[zeros + 1], mask)) end end end mant = band(v % TWO32, 0x7FFFFF) e = band(exp, 255) end else if v >= 0x1000000 then while band(v, 0xF000000) ~= 0 do v //= 2 exp += 1 end elseif exp > 0 then local shift = 0 while v < 0x800000 do exp -= 1 if exp == 0 then break end shift += 1 v *= 2 end shift = band(shift, 31) if shift > 0 and band(fflags, FLOAT_SHIFT_ONES) ~= 0 then v += P2[shift + 1] - 1 end end mant = band(v % TWO32, 0x7FFFFF) e = band(exp, 255) end end if R then st.crcx = (st.crcx * 27 + mant * 9 + e * 3 + sign) % TWO32 end local sc = st.scratch writeu32(sc, 0, sign * 2147483648 + e * 8388608 + mant) return readf32(sc, 0) end -- fixup_samples + false stereo + interleave @native local function emit(st: State, flags: number, n: number, d: number, P: { number }, c0: number, C: number, lossy: boolean) local W = st.W local s = if d == D2 then 2 else 1 local count = n * s local R: Reader? = if st.wvx then st.R3 else nil if band(flags, FLOAT) ~= 0 then for k = 0, count - 1 do W[d + k] = floatValue(st, W[d + k], R) end else local shift = band(rshift(flags, 13), 31) if band(flags, INT32) ~= 0 then local sent, zeros, ones, dups = band(st.isent, 31), band(st.izeros, 31), band(st.iones, 31), band(st.idups, 31) if R then local maxw = st.imaxw local crc = st.crcx for k = d, d + count - 1 do local v = W[k] if sent > 0 then if maxw > 0 then local pv = if v < 0 then -v - 1 else v local width = (32 - countlz(pv)) + sent local btr = sent if width > maxw then btr -= width - maxw end if width <= maxw or btr > 0 then v = (v * P2[btr + 1] + bits(R, btr)) * P2[sent - btr + 1] else v *= P2[sent + 1] end else v = v * P2[sent + 1] + bits(R, sent) end end if zeros > 0 then v *= P2[zeros + 1] elseif ones > 0 then v = (v + 1) * P2[ones + 1] - 1 elseif dups > 0 then local lo = v % 2 v = (v + lo) * P2[dups + 1] - lo end v %= TWO32 if v >= 2147483648 then v -= TWO32 end crc = (crc * 9 + (v % 65536) * 3 + (v // 65536) % 65536) % TWO32 W[k] = v end st.crcx = crc elseif sent == 0 and zeros + ones + dups > 0 then while lossy and band(flags, 3) == 3 and shift < 8 do if zeros > 0 then zeros -= 1 elseif ones > 0 then ones -= 1 elseif dups > 0 then dups -= 1 else break end shift += 1 end for k = d, d + count - 1 do local v = W[k] if zeros > 0 then v *= P2[zeros + 1] elseif ones > 0 then v = (v + 1) * P2[ones + 1] - 1 elseif dups > 0 then local lo = v % 2 v = (v + lo) * P2[dups + 1] - lo end W[k] = v end else shift += zeros + sent + ones + dups end end shift = band(shift, 31) if lossy then local bytes = band(flags, 3) local top = if bytes == 0 then 127 elseif bytes == 1 then 32767 elseif bytes == 2 then 8388607 else 2147483647 local minv, maxv = (-top - 1) // P2[shift + 1], top // P2[shift + 1] local mul = P2[shift + 1] for k = d, d + count - 1 do local v = W[k] if v < minv then v = minv elseif v > maxv then v = maxv end W[k] = v * mul end elseif shift > 0 then local mul = P2[shift + 1] for k = d, d + count - 1 do W[k] *= mul end end end if s == 2 then if c0 == 0 and C == 2 then for k = 0, count - 1 do P[k + 1] = W[d + k] end elseif c0 + 2 <= C then for i = 0, n - 1 do P[i * C + c0 + 1] = W[d + 2 * i] P[i * C + c0 + 2] = W[d + 2 * i + 1] end else for i = 0, n - 1 do P[i * C + c0 + 1] = W[d + 2 * i] end end elseif band(flags, FALSE_STEREO) ~= 0 and c0 + 2 <= C then for i = 0, n - 1 do local v = W[d + i] P[i * C + c0 + 1] = v P[i * C + c0 + 2] = v end elseif C == 1 then for k = 0, n - 1 do P[k + 1] = W[d + k] end else for i = 0, n - 1 do P[i * C + c0 + 1] = W[d + i] end end end @native function Block.decode(st: State, buf: buffer, p: number, size: number, P: { number }, c0: number, C: number, cbuf: buffer?, cp: number?, csize: number?): (number?, string?) local version = readu16(buf, p + 8) local n = readu32(buf, p + 20) local flags = readu32(buf, p + 24) local crcWant = readu32(buf, p + 28) if band(flags, DSD) ~= 0 then return nil, "unsupported: DSD audio" end if version < 0x402 or version > 0x410 then return nil, "unsupported: stream version " .. version end if n > MAX_SAMPLES then return nil, "limit: block of " .. n .. " samples" end if band(flags, MONO_FLAG + FALSE_STEREO) == MONO_FLAG + FALSE_STEREO then return nil, "bad block flags" end local mm, merr = Block.meta(buf, p, size) if not mm then return nil, merr end local m: Meta = mm local cm: Meta = {} local cb: buffer = buf local hasC = false if cbuf and cp and csize then local cmeta, cerr = Block.meta(cbuf, cp, csize) if not cmeta then return nil, cerr end cm, cb, hasC = cmeta, cbuf, true crcWant = readu32(cbuf, cp + 28) end st.nterms = 0 local sA, sB, wA, wB = st.sA, st.sB, st.wA, st.wB for k = 1, 128 do sA[k], sB[k] = 0, 0 end for t = 1, 16 do wA[t], wB[t] = 0, 0 end local med = st.med for k = 1, 6 do med[k] = 0 end st.slow[1], st.slow[2], st.limit[1], st.limit[2] = 0, 0, 0, 0 st.bacc[1], st.bacc[2], st.bdelta[1], st.bdelta[2] = 0, 0, 0, 0 st.sacc[1], st.sacc[2], st.sdelta[1], st.sdelta[2], st.err[1], st.err[2] = 0, 0, 0, 0, 0, 0 st.fflags, st.fshift, st.fmaxexp, st.fminzeros, st.fmaxones = 0, 0, 0, 0, 0 st.isent, st.izeros, st.iones, st.idups, st.imaxw = 0, 0, 0, 0, 0 st.hz, st.ho, st.za = 0, 0, 0 st.crcx = TWO32 - 1 st.wvc, st.wvx = false, false local e = readMeta(st, buf, m, flags, version) if e then return nil, e end if hasC then e = readMeta(st, cb, cm, flags, version) if e then return nil, e end end local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 local out = if band(flags, MONO_FLAG) ~= 0 then 1 else 2 if n == 0 then return out, nil end local o = m[0xA] if not o or m[0xA + 256] == 0 or m[0xA + 256] % 2 == 1 then return nil, "no audio bitstream" end openReader(st.R1, buf, o, m[0xA + 256]) if hasC then local co = cm[0xB] if co and cm[0xB + 256] > 0 and cm[0xB + 256] % 2 == 0 then openReader(st.R2, cb, co, cm[0xB + 256]) st.wvc = true end end -- the wvx stream: in the wv block (pure lossless) or the wvc block (hybrid lossless) local xb, xm = buf, m if hasC and (cm[0xC] or cm[0x2C]) then xb, xm = cb, cm end local xid = if xm[0x2C] then 0x2C elseif xm[0xC] then 0xC else nil if xid then local xo, xl = xm[xid], xm[xid + 256] if xl <= 4 or xl % 2 == 1 then return nil, "bad wvx bitstream" end st.crcwvx = readu32(xb, xo) openReader(st.R3, xb, xo + 4, xl - 4) st.wvx = true if xid == 0x2C then if band(flags, FLOAT) ~= 0 then st.fminzeros = bits(st.R3, 5) st.fmaxones = bits(st.R3, 5) else st.imaxw = bits(st.R3, 5) end end end local hybrid = band(flags, HYBRID) ~= 0 local d = if mono then D1 else D2 local W = st.W if #W < d + 2 * n then W = table.create(d + 2 * n + 64, 0) st.W = W end local crc = TWO32 - 1 if not st.wvc then if hybrid then if mono then for i = 0, n - 1 do local v = getWord(st, 0, flags, true) if not v then return nil, "bad audio bitstream" end W[d + i] = v end else for i = 0, n - 1 do local l = getWord(st, 0, flags, false) local r = l and getWord(st, 1, flags, false) if not l or not r then return nil, "bad audio bitstream" end W[d + 2 * i], W[d + 2 * i + 1] = l, r end end elseif not wordsLossless(st, if mono then n else 2 * n, d) then return nil, "bad audio bitstream" end if mono then passesMono(st, n) for k = d, d + n - 1 do crc = (crc * 3 + W[k]) % TWO32 end else passesStereo(st, n) local last = d + 2 * n - 2 if band(flags, JOINT) ~= 0 then for k = d, last, 2 do local l = W[k] local r = W[k + 1] - l // 2 l += r W[k], W[k + 1] = l, r crc = (crc * 9 + l * 3 + r) % TWO32 end else for k = d, last, 2 do crc = (crc * 9 + W[k] * 3 + W[k + 1]) % TWO32 end end end else local ok = if mono then hybridMono(st, n, flags) else hybridStereo(st, n, flags) if not ok then return nil, "bad audio bitstream" end crc = st.crcv end if st.R1.p > st.R1.e or (st.wvc and st.R2.p > st.R2.e) then return nil, "truncated audio bitstream" end if crc ~= crcWant then return nil, "checksum: block CRC mismatch" end emit(st, flags, n, d, P, c0, C, hybrid and not st.wvc) if st.wvx and (st.R3.p > st.R3.e or st.crcx ~= st.crcwvx) then return nil, "checksum: wvx CRC mismatch" end return out, nil end Block.bits = bits Block.bit = bit return Block end __FILES["codecs/audio/WavPack/Tables"] = @native function() -- codecs/audio/WavPack/Tables: the log2 / exp2 tables, wp_log2, wp_exp2s, restore_weight. Ported from WavPack 5.9.0 -- entropy_utils.c (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). local band, rshift, lshift, countlz = bit32.band, bit32.rshift, bit32.lshift, bit32.countlz local Tables = {} local LOG2: { number } = { 0, 1, 3, 4, 6, 7, 9, 10, 11, 13, 14, 16, 17, 18, 20, 21, 22, 24, 25, 26, 28, 29, 30, 32, 33, 34, 36, 37, 38, 40, 41, 42, 44, 45, 46, 47, 49, 50, 51, 52, 54, 55, 56, 57, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 178, 179, 180, 181, 182, 183, 184, 185, 185, 186, 187, 188, 189, 190, 191, 192, 192, 193, 194, 195, 196, 197, 198, 198, 199, 200, 201, 202, 203, 203, 204, 205, 206, 207, 208, 208, 209, 210, 211, 212, 212, 213, 214, 215, 216, 216, 217, 218, 219, 220, 220, 221, 222, 223, 224, 224, 225, 226, 227, 228, 228, 229, 230, 231, 231, 232, 233, 234, 234, 235, 236, 237, 238, 238, 239, 240, 241, 241, 242, 243, 244, 244, 245, 246, 247, 247, 248, 249, 249, 250, 251, 252, 252, 253, 254, 255, 255, } local EXP2: { number } = { 0, 1, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 14, 15, 16, 16, 17, 18, 19, 19, 20, 21, 22, 22, 23, 24, 25, 25, 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 36, 36, 37, 38, 39, 40, 40, 41, 42, 43, 44, 44, 45, 46, 47, 48, 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 58, 58, 59, 60, 61, 62, 63, 64, 65, 65, 66, 67, 68, 69, 70, 71, 72, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 149, 150, 151, 152, 153, 154, 155, 156, 157, 159, 160, 161, 162, 163, 164, 165, 166, 168, 169, 170, 171, 172, 173, 175, 176, 177, 178, 179, 180, 182, 183, 184, 185, 186, 188, 189, 190, 191, 192, 194, 195, 196, 197, 198, 200, 201, 202, 203, 205, 206, 207, 208, 210, 211, 212, 214, 215, 216, 217, 219, 220, 221, 222, 224, 225, 226, 228, 229, 230, 232, 233, 234, 236, 237, 238, 240, 241, 242, 244, 245, 246, 248, 249, 250, 252, 253, 255, } @native function Tables.exp2s(lg: number): number if lg < 0 then local v = Tables.exp2s(-lg) v = -(if v >= 2147483648 then v - 4294967296 else v) return if v >= 2147483648 then v - 4294967296 else v end local value = bit32.bor(EXP2[band(lg, 255) + 1], 0x100) local k = lg // 256 local r = if k <= 9 then rshift(value, 9 - k) else lshift(value, band(k - 9, 31)) return if r >= 2147483648 then r - 4294967296 else r end @native function Tables.log2(v: number): number v = (v + rshift(v, 9)) % 4294967296 if v < 256 then local dbits = 32 - countlz(v) return dbits * 256 + LOG2[band(lshift(v, 9 - dbits), 255) + 1] end local dbits = 32 - countlz(v) return dbits * 256 + LOG2[band(rshift(v, dbits - 9), 255) + 1] end @native function Tables.restoreWeight(w: number): number local r = w * 8 if r > 0 then r += (r + 64) // 128 end return r end return Tables end __FILES["codecs/compress/Brotli"] = function() -- codecs/compress/Brotli: Brotli (RFC 7932) decompression, with the large-window extension. -- The static dictionary, context table and word transforms come from google/brotli (MIT, licenses/brotli-LICENSE.txt) -- through codecs/compress/Brotli/Static (tools/brotli_static.py). local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Crc32 = __include("core/Crc32") local Base64 = __include("core/Base64") local Deflate = __include("codecs/compress/Deflate") local Decode = __include("codecs/compress/Brotli/Decode") local StaticData = __include("codecs/compress/Brotli/Static") local Brotli = {} type Options = { maxBytes: number?, largeWindow: boolean?, } -- the tables are base64 text (trusted, generated by tools/brotli_static.py) local function unbase64(s: string): buffer return Base64.decode(s) or buffer.create(0) end local static: Decode.Static? = nil local function tables(): (Decode.Static?, Err.Err?) if static then return static, nil end local z = unbase64(table.concat(StaticData.dictionary)) local dict, err = Deflate.zlib(z, 0, nil, StaticData.dictionarySize) if not dict then return nil, err end if Crc32.of(dict) ~= StaticData.dictionaryCrc then return nil, Err.new(Err.CHECKSUM, "brotli: static dictionary damaged") end static = { dictionary = dict, context = unbase64(table.concat(StaticData.context)), prefixSuffix = unbase64(StaticData.prefixSuffix), prefixSuffixMap = StaticData.prefixSuffixMap, transforms = StaticData.transforms, } return static, nil end function Brotli.dictionary(): buffer? local s = tables() return if s then s.dictionary else nil end function Brotli.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = Bytes.span("Brotli.decompress", buf, offset, length) if not b then return nil, aerr end local maxBytes = if opts and opts.maxBytes then opts.maxBytes else 2 ^ 30 if type(maxBytes) ~= "number" or maxBytes < 0 then return nil, Err.new(Err.ARG, "Brotli.decompress: bad maxBytes") end local large = not (opts and opts.largeWindow == false) if l == 0 then return nil, Err.new(Err.TRUNCATED, "brotli: empty input", o) end local S, serr = tables() if not S then return nil, serr end local out, size, consumed = Decode.decompress(b, o, l, maxBytes, S, large) if not out then local e = Err.from(size, o) e.message = "brotli: " .. e.message return nil, e end local res = out if buffer.len(out) ~= size then res = buffer.create(size) buffer.copy(res, 0, out, 0, size) end return res, consumed end return Brotli end __FILES["codecs/compress/Brotli/Decode"] = @native function() -- codecs/compress/Brotli/Decode: a Brotli (RFC 7932) decoder, with the large-window extension (windows 10..30). -- Written from the RFC, with google/brotli c/dec/decode.c (MIT) as the authority on edge cases. -- Prefix table entry: symbol * 32 + length (length < 16), or a link offset * 32 + 16 + subtable bits (8-bit primary). local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 local bcreate, bcopy, blen, bfill = buffer.create, buffer.copy, buffer.len, buffer.fill local Decode = {} type Static = { dictionary: buffer, -- 122784 bytes context: buffer, -- 2048 bytes: 4 modes x (256 for p1, 256 for p2) prefixSuffix: buffer, -- length-prefixed strings prefixSuffixMap: { number }, transforms: { number }, -- 121 x (prefix id, type, suffix id) } local CL_ORDER = { 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15 } local CLP_LEN = { 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4 } local CLP_VAL = { 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5 } local BL_OFF = { 1, 5, 9, 13, 17, 25, 33, 41, 49, 65, 81, 97, 113, 145, 177, 209, 241, 305, 369, 497, 753, 1265, 2289, 4337, 8433, 16625, } local BL_BITS = { 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13, 24 } local INS_BASE = { 0, 1, 2, 3, 4, 5, 6, 8, 10, 14, 18, 26, 34, 50, 66, 98, 130, 194, 322, 578, 1090, 2114, 6210, 22594 } local INS_EXTRA = { 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 12, 14, 24 } local CPY_BASE = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 18, 22, 30, 38, 54, 70, 102, 134, 198, 326, 582, 1094, 2118 } local CPY_EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 24 } local CELL_INS = { 0, 0, 0, 0, 8, 8, 0, 16, 8, 16, 16 } local CELL_CPY = { 0, 8, 0, 8, 0, 8, 16, 0, 16, 8, 16 } -- static dictionary: bits of the word index per word length 0..24 (index + 1), and the offsets local NDBITS = { 0, 0, 0, 0, 10, 10, 11, 11, 10, 10, 10, 10, 10, 9, 9, 8, 7, 7, 8, 7, 7, 6, 6, 5, 5 } local DOFF = table.create(25, 0) do local o = 0 for l = 4, 24 do DOFF[l + 1] = o o += l * 2 ^ NDBITS[l + 1] end end local NTRANSFORMS = 121 local MAX_ALLOWED_DISTANCE = 0x7FFFFFFC local REV8 = bcreate(256) for i = 0, 255 do local r, v = 0, i for _ = 1, 8 do r = r * 2 + v % 2 v = v // 2 end writeu8(REV8, i, r) end @native local function reverse(code: number, len: number): number local r = readu8(REV8, band(code, 255)) * 256 + readu8(REV8, band(rshift(code, 8), 255)) return rshift(r, 16 - len) end local count = table.create(16, 0) local nextc = table.create(16, 0) local subBits = table.create(256, 0) local subOff = table.create(256, 0) @native local function prepare(lens: buffer, n: number): number for l = 1, 16 do count[l] = 0 end local used = 0 for s = 0, n - 1 do local l = readu8(lens, s) if l > 0 then count[l] += 1 used += 1 end end if used <= 1 then return 256 end local left = 1 for l = 1, 15 do left = left * 2 - count[l] if left < 0 then return -1 end end -- canonical codes: the first code of length l is (first(l - 1) + count(l - 1)) * 2 local code = 0 for l = 1, 15 do nextc[l] = code code = (code + count[l]) * 2 end for i = 1, 256 do subBits[i] = 0 end local nc = table.clone(nextc) for s = 0, n - 1 do local l = readu8(lens, s) if l > 8 then local c = nc[l] nc[l] = c + 1 local pre = band(reverse(c, l), 255) local k = l - 8 if k > subBits[pre + 1] then subBits[pre + 1] = k end elseif l > 0 then nc[l] += 1 end end local size = 256 for i = 1, 256 do local k = subBits[i] if k > 0 then subOff[i] = size size += lshift(1, k) end end return size end @native local function build(lens: buffer, n: number, T: buffer, at: number) local single = -1 local used = 0 for s = 0, n - 1 do if readu8(lens, s) > 0 then used += 1 single = s end end if used <= 1 then local e = (if single < 0 then 0 else single) * 32 for i = 0, 255 do writeu32(T, (at + i) * 4, e) end return end for i = 1, 256 do local k = subBits[i] if k > 0 then writeu32(T, (at + i - 1) * 4, subOff[i] * 32 + 16 + k) end end for s = 0, n - 1 do local l = readu8(lens, s) if l > 0 then local c = nextc[l] nextc[l] = c + 1 local rev = reverse(c, l) local e = s * 32 + l if l <= 8 then local step = lshift(1, l) local i = rev while i < 256 do writeu32(T, (at + i) * 4, e) i += step end else local pre = band(rev, 255) local sb = subBits[pre + 1] local base = at + subOff[pre + 1] local step = lshift(1, l - 8) local i = rshift(rev, 8) local lim = lshift(1, sb) while i < lim do writeu32(T, (base + i) * 4, e) i += step end end end end end -- largest distance alphabet under MAX_ALLOWED_DISTANCE, as the reference's BrotliCalculateDistanceCodeLimit @native local function distanceLimit(maxDistance: number, npostfix: number, ndirect: number): number if maxDistance <= ndirect then return maxDistance + 16 end local offset = maxDistance + 1 - ndirect - 1 offset = rshift(offset, npostfix) + 4 local ndistbits = 0 local tmp = offset // 2 while tmp ~= 0 do ndistbits += 1 tmp = rshift(tmp, 1) end ndistbits -= 1 local half = band(rshift(offset, ndistbits), 1) local group = bor(lshift(ndistbits - 1, 1), half) if group == 0 then return ndirect + 16 end group -= 1 local postfix = lshift(1, npostfix) - 1 return bor(lshift(group, npostfix), postfix) + ndirect + 16 + 1 end @native function Decode.decompress(src: buffer, off: number, len: number, maxBytes: number, S: Static, largeWindow: boolean): (buffer?, any, number?) local lim = off + len local ip = off local bb, bc = 0, 0 @native local function fill() while bc <= 24 do local byte = 0 if ip < lim then byte = readu8(src, ip) end ip += 1 bb = bor(bb, lshift(byte, bc)) bc += 8 end end @native local function bits(n: number): number if bc < n then fill() end local v = band(bb, lshift(1, n) - 1) bb = rshift(bb, n) bc -= n return v end @native local function bitsLong(n: number): number if n <= 24 then return bits(n) end local lo = bits(16) return lo + bits(n - 16) * 65536 end @native local function overrun(): boolean return (ip - lim) * 8 > bc end local T = bcreate(4096 * 4) local tpos = 0 local LENS = bcreate(1128) local CLL = bcreate(18) local CLT = bcreate(256 * 4) @native local function decodeSym(base: number): number if bc < 15 then fill() end local e = readu32(T, (base + band(bb, 255)) * 4) local l = band(e, 31) if l >= 16 then e = readu32(T, (base + rshift(e, 5) + band(rshift(bb, 8), lshift(1, l - 16) - 1)) * 4) l = band(e, 31) end bb = rshift(bb, l) bc -= l return rshift(e, 5) end @native local function install(n: number): number local size = prepare(LENS, n) if size < 0 then return -1 end local need = (tpos + size) * 4 if need > blen(T) then local nt = bcreate(math.max(blen(T) * 2, need)) bcopy(nt, 0, T, 0, tpos * 4) T = nt end build(LENS, n, T, tpos) local base = tpos tpos += size return base end @native local function readCode(alphabetMax: number, limit: number): number bfill(LENS, 0, 0, limit) local hskip = bits(2) if hskip == 1 then local nsym = bits(2) + 1 local maxBits = 0 local x = alphabetMax - 1 while x > 0 do maxBits += 1 x = rshift(x, 1) end local s1, s2, s3, s4 = -1, -1, -1, -1 for i = 1, nsym do local v = bits(maxBits) if v >= limit then return -1 end if i == 1 then s1 = v elseif i == 2 then s2 = v elseif i == 3 then s3 = v else s4 = v end end if nsym >= 2 and (s1 == s2 or s1 == s3 or s1 == s4 or (nsym >= 3 and (s2 == s3 or s2 == s4)) or (nsym == 4 and s3 == s4)) then return -1 end if nsym == 1 then writeu8(LENS, s1, 1) elseif nsym == 2 then writeu8(LENS, s1, 1) writeu8(LENS, s2, 1) elseif nsym == 3 then writeu8(LENS, s1, 1) writeu8(LENS, s2, 2) writeu8(LENS, s3, 2) else if bits(1) == 0 then writeu8(LENS, s1, 2) writeu8(LENS, s2, 2) writeu8(LENS, s3, 2) writeu8(LENS, s4, 2) else writeu8(LENS, s1, 1) writeu8(LENS, s2, 2) writeu8(LENS, s3, 3) writeu8(LENS, s4, 3) end end return install(limit) end -- complex: the code length code bfill(CLL, 0, 0, 18) local space, num = 32, 0 for i = hskip + 1, 18 do if bc < 4 then fill() end local ix = band(bb, 15) local v = CLP_VAL[ix + 1] local dl = CLP_LEN[ix + 1] bb = rshift(bb, dl) bc -= dl writeu8(CLL, CL_ORDER[i], v) if v ~= 0 then space -= rshift(32, v) num += 1 if space <= 0 then break end end end if not (num == 1 or space == 0) then return -1 end -- its table (lengths <= 5) do local size = prepare(CLL, 18) if size ~= 256 then return -1 end build(CLL, 18, CLT, 0) end -- the symbol code lengths local sym, prev, rep, repLen = 0, 8, 0, 0 space = 32768 while sym < limit and space > 0 do if bc < 15 then fill() end local e = readu32(CLT, band(bb, 255) * 4) local l = band(e, 31) bb = rshift(bb, l) bc -= l local cl = rshift(e, 5) if cl < 16 then rep = 0 writeu8(LENS, sym, cl) if cl ~= 0 then prev = cl space -= rshift(32768, cl) end sym += 1 else local extra = if cl == 16 then 2 else 3 local d = bits(extra) local newLen = if cl == 16 then prev else 0 if repLen ~= newLen then rep = 0 repLen = newLen end local old = rep if rep > 0 then rep = (rep - 2) * lshift(1, extra) end rep += d + 3 local delta = rep - old if sym + delta > limit then return -1 end if repLen ~= 0 then bfill(LENS, sym, repLen, delta) space -= delta * rshift(32768, repLen) end sym += delta end if overrun() then return -1 end end if space ~= 0 then return -1 end return install(limit) end @native local function varLen8(): number if bits(1) == 0 then return 0 end local n = bits(3) if n == 0 then return 1 end return bits(n) + lshift(1, n) end @native local function blockLen(base: number): number local code = decodeSym(base) return BL_OFF[code + 1] + bits(BL_BITS[code + 1]) end @native local function readContextMap(size: number): (number, buffer) local ntrees = varLen8() + 1 local map = bcreate(size) if ntrees < 2 then return ntrees, map end local rleMax = 0 if bits(1) == 1 then rleMax = bits(4) + 1 end local base = readCode(ntrees + rleMax, ntrees + rleMax) if base < 0 then return -1, map end local i = 0 while i < size do local code = decodeSym(base) if code == 0 then i += 1 elseif code > rleMax then writeu8(map, i, code - rleMax) i += 1 else local reps = lshift(1, code) + bits(code) if i + reps > size then return -1, map end i += reps end if overrun() then return -1, map end end if bits(1) == 1 then -- inverse move-to-front local mtf = table.create(256, 0) for k = 1, 256 do mtf[k] = k - 1 end for k = 0, size - 1 do local idx = readu8(map, k) local v = mtf[idx + 1] writeu8(map, k, v) if idx > 0 then table.move(mtf, 1, idx, 2) mtf[1] = v end end end return ntrees, map end -- RFC 7932 9.1: stream header fill() local wbits local large = false if bits(1) == 0 then wbits = 16 else local n = bits(3) if n ~= 0 then wbits = 17 + n else local m = bits(3) if m == 1 then if not largeWindow then return nil, "unsupported: large-window brotli (pass opts.largeWindow = true)" end if bits(1) == 1 then return nil, "bad window bits" end large = true wbits = bits(6) if wbits < 10 or wbits > 30 then return nil, "bad large window bits" end elseif m ~= 0 then wbits = 8 + m else wbits = 17 end end end local maxBackward = 2 ^ wbits - 16 local dict = S.dictionary local LUT = S.context local PS = S.prefixSuffix local PSMAP = S.prefixSuffixMap local TRANS = S.transforms local WORD = bcreate(64) local out = bcreate(math.max(256, math.min(len * 4, maxBytes))) local op = 0 -- distance ring buffer: last, second, third, fourth local d0, d1, d2, d3 = 4, 11, 15, 16 while true do -- RFC 7932 9.2: meta-block header if overrun() then return nil, "truncated stream" end local isLast = bits(1) == 1 if isLast and bits(1) == 1 then break -- ISLASTEMPTY end local mn = bits(2) local mlen = 0 if mn == 3 then -- metadata if bits(1) ~= 0 then return nil, "reserved bit set" end local nbytes = bits(2) for i = 0, nbytes - 1 do local b = bits(8) if i + 1 == nbytes and nbytes > 1 and b == 0 then return nil, "exuberant metadata length byte" end mlen += b * 2 ^ (8 * i) end if nbytes > 0 then mlen += 1 end local pad = band(bc, 7) if pad > 0 and bits(pad) ~= 0 then return nil, "nonzero padding" end ip -= rshift(bc, 3) bb, bc = 0, 0 if ip + mlen > lim then return nil, "truncated metadata" end ip += mlen if isLast then break end continue end local nib = mn + 4 for i = 0, nib - 1 do local v = bits(4) if i + 1 == nib and nib > 4 and v == 0 then return nil, "exuberant nibble" end mlen += v * 2 ^ (4 * i) end mlen += 1 local uncompressed = false if not isLast then uncompressed = bits(1) == 1 end if op + mlen > maxBytes then return nil, "limit: output over " .. maxBytes .. " bytes" end if op + mlen + 8 > blen(out) then local nb = bcreate(math.min(math.max(blen(out) * 2, op + mlen + 8), maxBytes + 8)) bcopy(nb, 0, out, 0, op) out = nb end if uncompressed then local pad = band(bc, 7) if pad > 0 and bits(pad) ~= 0 then return nil, "nonzero padding" end ip -= rshift(bc, 3) bb, bc = 0, 0 if ip + mlen > lim then return nil, "truncated uncompressed block" end bcopy(out, op, src, ip, mlen) ip += mlen op += mlen if isLast then break end continue end -- RFC 7932 9.3: compressed meta-block data tpos = 0 -- block types / counts: 1 = literals, 2 = commands, 3 = distances local nbtL, nbtI, nbtD = 1, 1, 1 local btTreeL, btTreeI, btTreeD = 0, 0, 0 local blTreeL, blTreeI, blTreeD = 0, 0, 0 local cntL, cntI, cntD = 1073741824, 1073741824, 1073741824 for c = 1, 3 do local nbt = varLen8() + 1 local btt, blt, cnt = 0, 0, 1073741824 if nbt >= 2 then btt = readCode(nbt + 2, nbt + 2) if btt < 0 then return nil, "bad block type code" end blt = readCode(26, 26) if blt < 0 then return nil, "bad block count code" end cnt = blockLen(blt) end if c == 1 then nbtL, btTreeL, blTreeL, cntL = nbt, btt, blt, cnt elseif c == 2 then nbtI, btTreeI, blTreeI, cntI = nbt, btt, blt, cnt else nbtD, btTreeD, blTreeD, cntD = nbt, btt, blt, cnt end end if overrun() then return nil, "truncated meta-block header" end local npostfix = bits(2) local ndirect = lshift(bits(4), npostfix) local postMask = lshift(1, npostfix) - 1 local modes = table.create(nbtL, 0) for i = 1, nbtL do modes[i] = bits(2) end local ntreesL, cmapL = readContextMap(64 * nbtL) if ntreesL < 0 then return nil, "bad literal context map" end local ntreesD, cmapD = readContextMap(4 * nbtD) if ntreesD < 0 then return nil, "bad distance context map" end local litBase = table.create(ntreesL, 0) for i = 1, ntreesL do local b = readCode(256, 256) if b < 0 then return nil, "bad literal code" end litBase[i] = b end local cmdBase = table.create(nbtI, 0) for i = 1, nbtI do local b = readCode(704, 704) if b < 0 then return nil, "bad insert-and-copy code" end cmdBase[i] = b end local distMax = 16 + ndirect + lshift(if large then 62 else 24, npostfix + 1) local distLimit = if large then distanceLimit(MAX_ALLOWED_DISTANCE, npostfix, ndirect) else distMax local distBase = table.create(ntreesD, 0) for i = 1, ntreesD do local b = readCode(distMax, distLimit) if b < 0 then return nil, "bad distance code" end distBase[i] = b end if overrun() then return nil, "truncated meta-block header" end local litMap = table.create(64 * nbtL, 0) for i = 0, 64 * nbtL - 1 do litMap[i + 1] = litBase[readu8(cmapL, i) + 1] end local distMap = table.create(4 * nbtD, 0) for i = 0, 4 * nbtD - 1 do distMap[i + 1] = distBase[readu8(cmapD, i) + 1] end local typeL, prevL = 0, 1 local typeI, prevI = 0, 1 local typeD, prevD = 0, 1 local lutBase = modes[1] * 512 local litSlice = 0 local cmdTree = cmdBase[1] local distSlice = 0 local remaining = mlen while remaining > 0 do if ip > lim + 4 then return nil, "truncated stream" end if cntI == 0 then local t = decodeSym(btTreeI) if t == 1 then t = typeI + 1 elseif t == 0 then t = prevI else t -= 2 end if t >= nbtI then t -= nbtI end prevI, typeI = typeI, t cntI = blockLen(blTreeI) cmdTree = cmdBase[t + 1] end cntI -= 1 local cmd = decodeSym(cmdTree) local cell = rshift(cmd, 6) local insCode = CELL_INS[cell + 1] + band(rshift(cmd, 3), 7) local cpyCode = CELL_CPY[cell + 1] + band(cmd, 7) local insLen = INS_BASE[insCode + 1] local ie = INS_EXTRA[insCode + 1] if ie > 0 then insLen += bits(ie) end local cpyLen = CPY_BASE[cpyCode + 1] local ce = CPY_EXTRA[cpyCode + 1] if ce > 0 then cpyLen += bits(ce) end if insLen > remaining then return nil, "insert past the meta-block end" end if insLen > 0 then local p1 = if op > 0 then readu8(out, op - 1) else 0 local p2 = if op > 1 then readu8(out, op - 2) else 0 for _ = 1, insLen do if cntL == 0 then local t = decodeSym(btTreeL) if t == 1 then t = typeL + 1 elseif t == 0 then t = prevL else t -= 2 end if t >= nbtL then t -= nbtL end prevL, typeL = typeL, t cntL = blockLen(blTreeL) lutBase = modes[t + 1] * 512 litSlice = t * 64 end cntL -= 1 local ctx = bor(readu8(LUT, lutBase + p1), readu8(LUT, lutBase + 256 + p2)) local base = litMap[litSlice + ctx + 1] if bc < 16 then if ip + 2 <= lim then bb = bor(bb, lshift(readu16(src, ip), bc)) ip += 2 bc += 16 else fill() end end local e = readu32(T, (base + band(bb, 255)) * 4) local l = band(e, 31) if l >= 16 then e = readu32(T, (base + rshift(e, 5) + band(rshift(bb, 8), lshift(1, l - 16) - 1)) * 4) l = band(e, 31) end bb = rshift(bb, l) bc -= l local lit = rshift(e, 5) writeu8(out, op, lit) op += 1 p2 = p1 p1 = lit end remaining -= insLen if remaining == 0 then break end end local dist local push = true if cell < 2 then dist = d0 push = false else if cntD == 0 then local t = decodeSym(btTreeD) if t == 1 then t = typeD + 1 elseif t == 0 then t = prevD else t -= 2 end if t >= nbtD then t -= nbtD end prevD, typeD = typeD, t cntD = blockLen(blTreeD) distSlice = t * 4 end cntD -= 1 local dctx = if cpyLen > 4 then 3 else cpyLen - 2 local dcode = decodeSym(distMap[distSlice + dctx + 1]) if dcode < 16 then if dcode == 0 then dist = d0 push = false elseif dcode == 1 then dist = d1 elseif dcode == 2 then dist = d2 elseif dcode == 3 then dist = d3 elseif dcode < 10 then local k = (dcode - 2) // 2 -- 4,5 -> 1; 6,7 -> 2; 8,9 -> 3 dist = if dcode % 2 == 0 then d0 - k else d0 + k else local k = (dcode - 8) // 2 -- 10,11 -> 1; ... dist = if dcode % 2 == 0 then d1 - k else d1 + k end if dist <= 0 then return nil, "bad distance" end elseif dcode < 16 + ndirect then dist = dcode - 15 else local x = dcode - ndirect - 16 local ndistbits = 1 + rshift(x, npostfix + 1) local hcode = rshift(x, npostfix) local lcode = band(x, postMask) local offset = (2 + band(hcode, 1)) * 2 ^ ndistbits - 4 dist = (offset + bitsLong(ndistbits)) * 2 ^ npostfix + lcode + ndirect + 1 end end local maxDist = if op < maxBackward then op else maxBackward if dist > maxDist then -- a static dictionary word if dist > MAX_ALLOWED_DISTANCE or cpyLen < 4 or cpyLen > 24 then return nil, "bad dictionary reference" end local nb = NDBITS[cpyLen + 1] local addr = dist - maxDist - 1 local widx = band(addr, lshift(1, nb) - 1) local tidx = rshift(addr, nb) if tidx >= NTRANSFORMS then return nil, "bad dictionary transform" end local woff = DOFF[cpyLen + 1] + widx * cpyLen -- transform into WORD local pfx = PSMAP[TRANS[tidx * 3 + 1] + 1] local ttype = TRANS[tidx * 3 + 2] local sfx = PSMAP[TRANS[tidx * 3 + 3] + 1] local w = 0 local pl = readu8(PS, pfx) for k = 1, pl do writeu8(WORD, w, readu8(PS, pfx + k)) w += 1 end local wl = cpyLen local wo = woff if ttype <= 9 then wl -= ttype elseif ttype >= 12 and ttype <= 20 then local skip = ttype - 11 wo += skip wl -= skip end local ws = w if wl > 0 then bcopy(WORD, w, dict, wo, wl) w += wl end if ttype == 10 then -- uppercase the first character local c = readu8(WORD, ws) if c < 0xC0 then if c >= 97 and c <= 122 then writeu8(WORD, ws, c - 32) end elseif c < 0xE0 then writeu8(WORD, ws + 1, bit32.bxor(readu8(WORD, ws + 1), 32)) else writeu8(WORD, ws + 2, bit32.bxor(readu8(WORD, ws + 2), 5)) end elseif ttype == 11 then local p = ws local left = wl while left > 0 do local c = readu8(WORD, p) local step if c < 0xC0 then if c >= 97 and c <= 122 then writeu8(WORD, p, c - 32) end step = 1 elseif c < 0xE0 then writeu8(WORD, p + 1, bit32.bxor(readu8(WORD, p + 1), 32)) step = 2 else writeu8(WORD, p + 2, bit32.bxor(readu8(WORD, p + 2), 5)) step = 3 end p += step left -= step end end local sl = readu8(PS, sfx) for k = 1, sl do writeu8(WORD, w, readu8(PS, sfx + k)) w += 1 end if w == 0 and dist <= 120 then return nil, "empty dictionary word" end if w > remaining then return nil, "dictionary word past the meta-block end" end bcopy(out, op, WORD, 0, w) op += w remaining -= w else if cpyLen > remaining then return nil, "copy past the meta-block end" end if push then d3, d2, d1, d0 = d2, d1, d0, dist end local from = op - dist if dist >= cpyLen then bcopy(out, op, out, from, cpyLen) else for k = 0, cpyLen - 1 do writeu8(out, op + k, readu8(out, from + k)) end end op += cpyLen remaining -= cpyLen end end if isLast then break end end -- the final byte's padding bits must be zero local pad = band(bc, 7) if pad > 0 and bits(pad) ~= 0 then return nil, "nonzero padding at the end" end ip -= rshift(bc, 3) if ip > lim then return nil, "truncated stream" end return out, op, ip end return Decode end __FILES["codecs/compress/Brotli/Static"] = function() -- codecs/compress/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see -- licenses/brotli-LICENSE.txt) - do not edit. The RFC 7932 static dictionary (122784 bytes, deflated, base64), -- the context lookup table (Appendix B, 4 modes x 512) and the 121 word transforms (Appendix B). return { dictionarySize = 122784, dictionaryCrc = 1362545412, dictionary = { "eNo8velyHMe1LvrbiOA7lNpni8Q20QBJTSYGB0dJ3hq4Bcq+2z4ORXZVdncB1VWtyiqATUkR4ICB4ABSnAXOMyUCIDhiIIGI", "wxeg/pH/FOeiuhsR9yHu962EbBkS0J2VlcMavrVyrZWJX9FeNBgGflEHupgUlNvvRp72VKJMORqMwqBm/ES7flKLqjrsS00S", "+P26GGs9GMX9id6X1LSKowEdFyKvFuCXYhRXClHUXw1ULfAHdOCHuqyDajmqaON7uhLFfNYLorCUlHVlwNeDRT/0qqqE99ZM", "MQ2CslZeouOKVm5ZxVoV46iSxKmuqLhfFQKdVqOw7JfKGKcOVOiFetDoAR2GGI+rjC5ESbkamSQ12qsoT5fRpqzx3rJKQlXR", "n/lhfyGISsbfrwtoj/GhXT/690M8E69vdf5UjgJPh54Z9JPyF+gfw/AG0YfxS2GCtmU1oEvoy2gduioIqiopD2r8N0hNRYdp", "0Q8qVRUnfZEfJmXfBL5JSlGEsWpvEPMc1AbfFUwFc1eBiTCcKPbdMt5vAmWSRCtMt1Ir4pl+PywN+kGg8fmgir0Cni36sd6D", "NesPo0GFDvPVsFTB+ieYbBApr4S1NzoohlGiK6lbLmquRViLI7ffd6MwCl0dYJ/K2BPP194n2J84DXQZ66b61D4/LEZukBYC", "NWgCbUxZBUXDPURf+6NQb+ro+A/8x7jYoL2go1i5uhCk2P80HtS6v4i/yyCaEtYJm4j9xtjLOsSa9PfralJVBp361TiKKp/s", "/fwz0Eu4t1YFPaJTPNOvdbUYqBLopx+r4xUxnwTjjbHnCWi2L61UE6yWh/4wBnwPCgYtYvS1fqwV1iEpYl9UmkSgjTjvgoZU", "0A+6rg5gTTz0XwGtY0eTJI3DQoQf0Ak4IYgjo9M42GCw8HEUaDwKUkwMlht7q7GPgZfvq5bAGpUBFdfwTAJaDg0Ixouj6t9A", "025UrW3Kd+S62lWPSbAQAXbDx8uwPlXwWb7kF7EGiWvMX0qxquEN4bulpDPGfmCMSYB5GuWjO+XhHQ72L+iLyiFopL8axZib", "SdZ/va3NA112tRd6qlEUFzhvrOHX+d78IOimAn7dXN3X+Sn2MlZh/yD6HlQhaCggMXn/7PhXZ1WlwSDW26Sx/l8b1v9xUPlJ", "BXsD2jOlSJsSeAJbU6piLO+0tTkB6CcN/QT7xn76QYeVQciPfZUgZ8jTmOLmjuo+LB3GPoj5RkExCtGnHxhVxLfoWVWNCzkQ", "o+9iEA0WVKFmqio04Iv3MN4P8APWMaD9BHwXDPr9PmRCYhIQTuxj+qX2ADw4qFV/gr3YDZkDvseahAZ72I/trsVpaPrSoAZJ", "1r8J/ZUiFZQgAgzep72S9r3unNGJeR/f5fvMX97DmP2is8FEEfYRcgJ0mKQFvV+TGkKMQ3ug6QTcHGHrQF5xZdNH1X0uZEAZ", "617AOPaDlgciLLIytRg8C5oMqhijj/VyQf9b8K4+7H2iSqbgJwa0FYD5kn4IsBC024UFLmHR/tr75RdemtS+oHxRga5FKdY9", "wRL5YZ/av9+lbKppU/RNeXBwMB/7Bn0WTDXWA5swD/ytN2Ni28GPHsaxpaNjYwF7DirA2OIQssQrRPvyReXHAcaD9WLfcV+K", "OWu37Bc3vFMFnekBP/hfG3KgibgS4FkP9FCFfN7Y0dHBWXqxGiynYIpqlBTT0CuAj8qxLkKyBP26ZhL0UQa9g/ch13WwCcRo", "Uj/Bo8FXvb05inzsSe3jXXtzWDOtfNAch+R7BkvbGaqBWgkMkfhV88c///nPGAdko1cDv5vWTueHarn6F8juAHwdDELB7C9v", "zf6zfV2LA+EEeRXkW1q2fYh+qqkpQ5MkWJpOFzTwn+1d7WVouA+xRpAxSQwZ5rz7rgNtEmA/oV1AVRhExYeM6verCfYfOgr6", "IdAl0EwVm/Ee1nRdy7oWl/QNmZDHYLoKcY8Gg1aw16XUh5wOsFEGrwaTKEqkqNLuV0rv/vGjzUEKXYt+sZSdIKpaCfRWTiqU", "EoEXp6XdX+3aFUI+hVjDv4BYA1Ih1n6AOgC8hfVzQP9xrINaATrIgFa8tF+HyihXVfUgaKOUBsW9m7dsLYPWQPdJCTIFwh+6", "L40hr2qbMP/161s7WztzPRUDoeWDf/zYM5AvBQ3OgRzfu+mjrdh6QwbA/IMPsIhF0MP/HbpoClHNQIbk0UVuz5e9ewsYTz/2", "rrXzhx+gvGpYN2/D1//V+m2qPOxNvQ0Ktw3/g9Cv4pl1wB3J3k1/3jrgu5B+Xs3ThaQHE4MsC0LNcUaDezd9sNWDbNMDKti7", "6cOtAdYfdAtyVEEV/BNGAwr8YEo61M7/HTpjoiJkU0Unvshx01XeAtmYxkXggCp0SVcS90Dn+q3fv7MB/9UYV7MAeoJ8iTs6", "WjsrftDvtLX1+HEUAud4HnhrEPtkIj+opolp7zPtwAa1vZs3b/20d/sXezd3bFWeqmCt8K7NPX0Qgus3OuuhYpO9mzdtdTAf", "6FmIel9VIFu62qs9JkqDzz79Yhf4EXglxhq8t7WrvKnnI6wtREDXn0Gnezve21oB1tr63gf/AA1oP3TL/wPMBfLimFfWt7aC", "rmPsSUlDp4K0QuCe0Nu65cN/fBMVv1n/r9ZO0NZGtG0kkIk14oZoMCiAF7a+/8E//qoG1Ba8r+X7H1r+Y8eW/9i65b1/9Oli", "cdf/s+dTyNLygA91B9I2wBfoY/XblDoU/AD6ga5KsHb5AujQA72WgUUgL4CRwmTrlg/+8cnevXvaNndsKkbQ1Ohj1xc7nX0Q", "OFvff+8f27/c+T8e+uhs+aFF7/PR/v1/QL8Z0E6y/ofWTmCRBKzeqYDmfvihq/2f/r/yn0H/9Ff+z6NBvCcBzSnPM5AWAdhx", "X2fLH36AyIpC7GUeiqGj4/1WrEWtD6LegKjAsZCzURFr0eps7ugAjYOHsRiAf8Cp4Im45mJfkxooSwNT+FGYhzJzoedKeC90", "Yv59rNOecn4n5AGgnuCrEHzdD1qBplEh9OE+0IkLum/xoHPdwK+2Qvh8iOewDh07/7bTfPivnq4EfEkE7P/pT62D2DeAjKgK", "5RFVE6j8QO/e9t8GdBK2bf5gb0B5Dlr/+qvPnEIaAJdH/Z0/rGv5ZNe2neC5VlUoQF6rcMOmP38EfFamUOhq90FbkCUpcTRw", "gl/V37e1vNPRsbk1BND/56Z/df7zX50tn0UlB3olWdfyhz9AX5agUysFyKfW79a1dJAmsA/90db/D3INa92zzmxtb3fwIKQi", "8W1pQ+t3LWjqQG+ux/SqXqqg/1SS/+uej1uxsd+mUYL/toDHISF/WAdSeA8/7+PnA/x8iJ+P8PPnzR3yzyb8bMbPFvyg3Wa0", "24x2m9FuM9ptRrstaLcF7bag3Ra024J2W9BuC9ptYX/4bBO+24Q2m9C2A8904NkOfNeBNh1o24Fn0AEWAz9oh3+B0PDzEX4+", "xM8H+HkfP+/hZwt+NuNnE37Q7iO0+wjtPkK7j9DuI7T7CO0+QruP0O4jtPsI7T5Euw/R7kO0+xDtPkS7D9HuQ7T7EO0+RLsP", "0e4DtPsA7T5Auw/Q7gO0+wDtPkC7D9DuA7T7AO3eR7v30e59tHsf7d5Hu/fR7n20ex/t3ke79zHjDs76vU1b/gy1hMnjf8Cs", "UeXVdVgTiSboqgLHJJEXlYHLXQgs9Wo2KvgQ0K+mlDKvpgZ8D3rDEHFFkEsRLRL8rlzsref3RbDdIuDUELqYFgWkKTg2KEXf", "pq/uE9WG6BM6AlAAnAMdVFB9fB/JOVKlVFVTQMwwAksCe0OGBalPVQcjpxbBnlAQjnHVx/sLeGfABkHk+RH4Iua4/NfPXz98", "/RI/S69f/Dr0+uGvQ78e+vWgfPb09TI+XcJfc2j1Er8/kb+WXj/Dd0v4ZO7X4deX0fYp/pn99Sh6OPr6x1+P/noA3z7C74/w", "38vs4/Xs66v49yJ6wlOvr72+hc+fvr6EtgfR7op8+gL9P3x9Hj9n8HP510P4fBbve/r6At7/9PX865f47AX+uYHnDr1+9vbA", "2/E3N9+OvB1+cxc/828PvT2Mv8fezL6ZwTd38f2Rt6Nvx94efjuMn0P4hL+Pvrn35jF+P/zmNp4dlT7G3x7EM6P47Bf0dI+/", "Sdtx/H4YbfnfQ2+eSK/DaD/8duTNz/hsHG1G3kzJE8P45gne/gTY3STYeB0FsKYTmOWwg7E7QHW0+gk5CsSHMb811P607AF/", "QEOwLXy36MNyJqiMqzRzoaKB8mBtAZHBTIdIiD3gP6MBatMqPQaG7gIDcqQRB3N/EL/QZIutAAYwpOUOO7sKiQ7sg/fqOIZh", "HEL3qkKUJvQLAFgmAa3BQMz+BDYJpBmMUKDDuCTuBSO2OamHsNmFWeqmxoXRE9PoCwo0YwjRYIMIlSl6JWC3K9o7Fby75lOz", "0ltgAL9D2qHsHq8H2oCeARwCPoCSfxeAsRPzgIkdxa6uUkHTkIZGK/mhKuIJ6FI/AZZMNb0Z+AK4BqpT70siQFciZPSMT/Fs", "mADEG1NI/SAR0xdKQAN9pV4NzOjRvA49Q1MT/8XSlWEK0+ViwJpQa1DHaAzoQ1eARz9FiFUb0EC5plz098G8xoDCCOgvpucF", "2BQ4CzpSBTEM7JgWrfk2hX7GklR1Oa2oEFqargtf/AvQztD2XgEc6cK0cSlasOLA6OUAdlEoxs8gRI2mQ8fQm2I8dg0REesC", "pg9rPk3KMJPwLF5nsNhJeZDuGU7aA+m5xGIJlzOtJLAnKFTihM6U2g5Ihn5acDF9S9hQWKqBqmkij7jGd9RSMdO5TC4WNsHm", "xQ5ALemqmlZpHhtVrQa1T7m/BeCqUlqFcKSfhNSEXrCmhua4wQbFEFDYWgrCfrpaaKYRcAMamBSPVZU8i+5JWyG9LiGJhr4j", "7e0lsXLg5mNyAERbCHxAb06EhS0q0C/9SjWVggi5WwbTDzR9Fe2coEdvlvEAd2uwygIaSyrpS2G+JmX6KGBXmpCDLtBN4Eb0", "J9AZxwlqekSMW3P5b4BjOlgMJWv/ILcZeE6HVV+7hPV+UMRENc1Kch70vF+ByapIHT6MQMIeNAcp02WnST1gv9QtF7jOcVQD", "KjL9GpsHFIP5kSzAYA5XAmA9KcuOEl3VomIRJOFGVc3FhIkFFgd64E5brxzEQkx/CPRHnMREUwq2OKYahdhQETIwMQh3eyky", "PiPVgVartch1YWrqYrIVuN2UQcUJ1wAmJRmHfjeTxoA7Rb6SBIyN5lqlSdSJ3Ul0nvZXhUwCY08F/0PKMXgZpgp0iyUexKd4", "L83eEFLQp3PCLX/F/uiKhISM3TLBj6anz9DNaLwoLcCSqoVuAm6iFR4NYi91sUY2gPUCs5h2KShhABsK3qW30uwgX/ZSchF4", "1/rE0wg7KgDOc3UHLfBeis0q+DOg3wUglxJBJDUMeApz6wQ19PQYuuSMonMCm2c0kSvleCiDxgZUsYT4M6GL1dDHxm9rZDDY", "5Nh8Q18vBXdM7g5LMKC39HDLSgTd7ZUU8peb7O0hc6Jd6CURpA9ghO9toAO0QI8IPX7spQgjzSd5B4F4fGvFNf8ajCa0ddrb", "YYIpjwZaqVZNdlHK01rt3EVipS8459K6g3QME3HlwrzI9ZCJgfjVAJ0YsIT9/dqUADwSDPe9njiiYxjf1tjBRtEdhDSeG1N3", "+CUY0YOQ0J4CAWNBjO6hR0aH33zd++4ft/y5k1h33zckaigCDC3sA+X3qX15RavBgGXKdL059B0TvEOehtCmoRrI9dAJEIrX", "i95EkAVWA/I+inupe4gysYMQCvQTmz5VFfEQwOz2QXPglFhR5WAem3sUbDhgLzAjuChWubb29r/TBWrohzJ0HJs9ZGLMMilT", "54V0TvzFYAAJmJckCPBFCZfQ/VrEzmiossFcD9YfjB2nlLFQ9H+jPt9NyZAPdcItaYH5XHO+a6FHkh5zQ7cWSQWr7YEGvuVi", "J7H4DAtRTMc/ZAeGC2FLv0hCqtR+vJkmlfiz6dMzO8jY4G5IOEp0nhMYOpToCMVa0+ddIbtQq1Ge+kbc215K0az3KVOMwe10", "j2z8/nsxVKo5jBWbR7dELqJ7oasQt/cUMa/Y0Cfn6WpSduwJANjUpZTnaYM4LzshY0oh3VRmkKPiaDshXLpzdF9DZWFGn2Pm", "Tj6f72oHdA1LBU6ahyAOPYedPFYAecdxDdICxK6L1BUl/Q3PQfIV0gZgiMK32K4qT1DkoKCrPYl76P4xHLyjQCEUQDR1A4iw", "feASOg3KPKUxVLgufc2OgRA3gGqhuIaNswGUSie69w0xBF2fRrA7SahfTmKEGcnnHp0AnYNUJ5ib0RtaO3POdsIjPJru66M7", "vgqZGNDJ09Pa6Rc3tFHIegrAEfDK6N2EVpg9z132abOXqhJKgpPRlZ6CinM9eRO73QklAwRYd84lOiyD1mqb3xPRl6RVH3RZ", "Iw6rgukxCZCG+KoNZUceAl3z+EAH9A+adteYdp5AdPKIAgIlLRYLPjqlZ9/Q/dfRD05TsGPXtdCrD0yjU93tfPdD50fiBeSR", "yne0fxUPm1zO1wdZlXm85cTkZ4JUQ89yrqbKUdRKZ/k2IlCeVhkw4qYe2EBpiQ5msdK7abOYH1qxgnR0dlYpVehSNDxfMB37", "Pujo4KlBTvy4BaqORGHBKj5EGdFbAAbraqdzGTOCcGrj5pGk8phHyx8qZBIH9v6fd2/77672OCrpuEi3/g7yzGY6THnIY+hJ", "6gJjJgl98WYzxwIIFva3Ot9/7wT0DPI0J/hjB0SaA3JyeG7nDXLFKeA6+9TW//eg8UHVXfTcx4AONR57wH4j/MWCVRPqme2U", "na3OO92OR8xKrwddLRWoo35dq8C8DHiilqcb26kSO4Onwxo9iYYIJ7eJyzFIQE4PVqV377av9pK2HB84NtzowJanO6GFADc/", "4AMMiCsV8iUEX0LL8ACM0DoKq+Rf8kxL1AbcwlMJOWox1JQOnW8hvS7fKS8q6PXcTN/r3tRBhdDJ4zonvzlf8XmIlqPbG1AD", "27ODmKsAcag3c6TY5NY/8Zfv6cQG/0ETl8nimzZ35ByqWIi+nnUtVBDdng8QQI7HF1hwys6WPxaLRTARIAsRXo7wAcoaj7XS", "+7xJeAE4qxpahzPsIW7FIR5VuFzEHCctp0OmDbzW5tHQank3SDrpeTVb3/voH108u22LUzAaT54cKkig9X4xFaqm28nlOqEM", "oI+4apt4IgHxr0K60SNKw+6o+z8273YojWCaF3SXXyk5+Mn1bHSKfYa/OTmu3+d7o+p2ntjlQj0Y1HZiT/rd/Vqwsh8QK5NJ", "3u8pqm9zPfvLbW64qQO72bYp19pJFN7N00LotzSoUZYYOpM6sXpd79BjETg89ICyWye77/TRliDHO9ytPDh3XcsgcQnPPkxK", "cePxqKMApulPyFvgo5zDM1rgZwyNThDw97eg0TSq+CaCLQIZ6mk526FnxFRTGqCvZiM6TV5dT3xIXKCARNEnIjCep5OgzBRy", "hn6UmENT6KwCkQq4WoHKitS36aspelWMefU4iFQt9VRR8/iB3hAAo4R2ZoRRJZGhh8UIBfOMNlL0dgRpiUdktYhHk9YBghUh", "AgBdGPpUOT6FAb2aMhyLAkBLPXHa0HqPgHx1SLwIu8kjwxLs6fjVdcAiztj1477IiNtGxURWgBZpNSrTjSpkgLdBZwCaR1Dv", "yoQ8xic005yqAgdqHq354geCKHF9VQS05PGRD7iHha1CUkSFFNMkuo4VSCzgn4ooEign3o9+CzTiMASQAV706nEl4iSjPv4J", "XPNqocwmXIMa4L+rKmkfMDLQUFxMqUjwoqgE+0D5JeDiAa4LHVgAfFh87iWWt4L3gLagr7F3dFmFYQQBBgDlYszgHrpgDRbH", "p1OqDE0WmwigFyuFVQUzvnocQnLtj+hYEN+UGeCYVTWqYaQhQRYYjp9FLtg5luMj2EgYC4WIy8fo1jL0koQkmvDVddp8vthA", "sJ1ARq4MV9GWDEgbmDvsAAwDqwF0rQmTdRWaGGqR3eBpxkLQLQZ0Sy8aaKgU0PPGV2MhKgoimdaxXcDQB1V/a99hFI0gNyrT", "qTfgqz4IXyDoV/epc0jyMWxi0E2fAnmDnmF+qYAaWQeaZjDQnJI9BFiNTJDyuB6bjK4CrhueoIUd008ohMQwBpcHnQN4OUYF", "IvGiAWAmQ7efUZVCxENbj+18RWwrvKBMCqsdALkPqwvZTyMO0/NdhcV4NdUX8VXYMqWFpygKwAZ+bFIdcASRKYrHhh5GbrdM", "kOsIy53+KO6qgkUWEZYp0m5C3RBon+EXhSigCxOrBiIE+OKAXh2QfXMZB4MnYGuAGNgjB3SdO40OeC5F1yclyH1SJ5mdfIKZ", "UCkpAmb85oq9lYDh0RUlC2ithnXDJgUVoMuIAFKcqTQrgFB8TIvTh+wCZWMSEPiUJcDzVXHGisGmRKgZn8e43DLaGwDmEDz4", "WNN900fkqBVdsuZd2qqdXkQtjY6h8Al6UutUAw0ZOudqhsMXdVHgoUwca4HhLk+v0yoNX5AeDFvKnrQCtYWnQpi6lDyENaBA", "WAbVtAB9iacYLwM8ZUjnFbBgrBgkROeYAZ/GLiYUyyFrLB4nWBVaoIRmKI5bFvcE9odOx1iXMCo/YZwL2BaWEscJ3o2CtBLS", "0oohFmlxi8OwR/v0XABIl5JyEfINZmdMFzgWDrgOVAxZSy7GBLR4x9JKBStAyzzm6mqvap1N+2CeeVXIOrcmKiChlU8WBYS3", "0gR6F5IE1hywRMkT41IcXUachEBSPnZ6UMz1qgYxajJeqQYJmRLr0pFQBHPHjDNCD65QUlQsAgaDDTFAOhChYtNChW4I+gLF", "yWrSKqN/gNECmEt0E3ni4AU8K/OkOpX+y6DUQRANZio+W/NloU+7ibgFjfX2gqwhW9xyLHFbFYwQBE+fXVloLKSyxTgxR4h7", "kBrnCn77NlV05CWUOXSwGToguYOchcS08KAK44dZSSsbaxXxcBkWFPrB0n9GmYPpJHRKYW0ptitE8BqyWTNqSHtJVCoFWtzQ", "oGueHpNufdeFIgUVEVdVatRkgypJYI3I4XVSFCd3WbAlo5tyPYxp0x7ovZgGwsk1sVXFY8J9By2AtlwMh9KpZP2QRu9zGYZC", "D0CJ+4rxlGUxilDzibjErYfbYL8wNigH6CfGeUTxAClTfyUrRjYHgZEpCS6oh13MxDB6AIBbNiPnEPzRKaOTknh4yFMkINAk", "0FmRIKEGERpURNDQW+zCTCa3+qHE2ylSyw5x3kWyy+LPhVTxvEDv4gkkxeEgHZgl5dYqwuPY7LRUZmyXFrCt6YMv+SHHraCZ", "fL4LCsElFocAkbMCT/xkhPaMfVEcfyTnqUI/NTERGQ4BNefS3oQcAL+XPU1JHQstgWOJAVKIi6TCWMGaL55J4TUtrnvzhcgW", "L6V8sN5EOTswjPrSHiGFdSzBFPIDcC5Wr0RvO893C8I7dOUxGgusYz4W2UWfLC0jelZdWauCeFmBYmNVBR1g96wvDMKDdA5I", "l9QwC9JeFZZj0mYHUaW8rTDkp0SPIxR8CnEMWc/4FoAf9N3rxn41wRjonCeR0qqByPN8ciodYSR7zrFNvAhYR6wDqBACQQkN", "8CRFe3SuaG+HrCEWmA60Mp0VKmB8IeMJcw7sG8gNrgls9+/otcEAi/6+SI4LPhE6zzM8ZoML4UEKIL4AXMPkAwXUVf5KJGEi", "M+I5Bvk8gQzyhP63C6fD+kiTmriGKd9KUdIrEkxR0gOpCUVDKnG0ViOIRZxwB2PNbz4XCS9aCLRN93yv6AIR84Yj0N67YcFU", "O+nUN1oMcYeqOvS66LZ1eD7uy3lNdw7MCmwh0X3ASgMSPUFraKuzt6wdjx61kpxLme27Pv70C+dzsAT1Mh31rtgDZZHMSkyK", "T+UtFDyJ2VXBZutekaXgd3CDh7/dxB4LgHfA6b3CF/mWli9DcepojyZLrmcPcLhfFWeWKUtkAnYNPXwpUiKWtRciNqH4E3tF", "2niaThu6b4Oas0HnS/mCLjPuIiKdYCIgHJ4DaIkCxA9PncS1mxjCQpmVb+zxk7eFBv73hHSeorfVrfEECEpOYl9h0O9nlB6l", "vdBPT0HXIP3axP9P6VRNRBt6xDOh3h1FdAgoRn+KQ6TlG4rsnHhgRQ4bk3PaYcPlxRqLJDJVKCH+ch+j0Tg+bDCkmT8gnBsW", "Jcpqp3XH0h7NqWqV2gzMk+uRw0XDGNd+wwhgMcFcemyhbTBnjFZvg1IHSuSyEQRjP/eIhu0qxBjLIJVLLKd04pfR3vff0y3E", "+ed6fKvFwGOqRs7P9TDWCPJEh7A/IddSyhCAuFDc/GYTPYPfi/rhGuIjOU3J0XODt5OIOjkTJbpMBZvkjIGfgMhjHpQUsRzJ", "VnE8OHLild8mWkAOloyxx32UG94n1rlPf2D89d7dbR/l5OjR2S5aIO/8HeiGB4V+JP5i4LeQsUEx0GbS99+pRKqQPsXXAgQF", "AZ8ABYEPYNmUuONkTXpJnO98EysstKoJenHxSnoNcz1lkRhcDB7mkb/lCMnIeWqnLIMnztcuWArC3dzDtjZGtkJC+UkNk2G0", "CJ5XqXjDnE1ymhEVEvqnidOMElfXRufT0KWjRHs14SAHOgT6RQ6O85To2pMTodo3JNb8bkF0dFxr73PRmIHRjl/cI5gNe92v", "a62dEksrpnVJsJkcL5udgoF/YJDud2AfNN+OPrvai0LhcrKZLwoeljMK0yWeXh7cOB1VfFZRIDoMS0zgGGYAbDfBJ56cxxlG", "zfjh++KMolMInEU7IMwTEG1QAyoRGwCr941MSSjBCG8qOSneWBTtJuhLYtFpAWOYG4Q74l7BgaRd9uzVcj0t/0lht7fMbYbm", "wUz7CGlqjGXvaudRb7EGHIsufNgzcU2OcLt3iBQVR5yj5ITlG4FxPIZVHuXSAHSxi7WV85aWXrEOnJ10BrsEJrGc/BvxaHvb", "6L52GMEb1Lx/ny/nepgDwHFS4MlpuqHZnBqJR6CT8p//6pQ4hHwphfETAx8w0pUj3MrTWe19SXDh8Fgj50DKpTyRwSbDROBh", "mJw1Y5UAU4rALtBoO6wlBoMZUlSOhHtF+7S0/B1SOVEgm1iiA7biQUZXx0QniaxertX5k5OTHe8ppOQIOcc1n4uOpsYhkqwK", "BKRM5jFVrmdAwg7EBo7lLBMaCmCFlmBC11oi2B6bB80UqoGefoY/G8qNXI8cTZtuOR+WA2GnLL11WIZvafk0dBwJk9gDO7Xf", "b5NFxDsgB7eLxpezQadNaGmzyBzmSOR6OsTl+qVIuTYRTxXSFQiDdMt4RqdD2NGR4Agj1kGrFuuP6NuPGRuXcxxrJEjPbcL8", "0F+79lW3ypEqcyb8kEY7ECMDOYyca6yTo2+n5Q/kwR4Gh/0Bn3s9LfJtS0GVGTcUc5NKjLQFT5Zg0VZljiau4t8SMTO2MjdV", "PzfamB5aeXm6MX9g9ZczK8vX6wdm8Hk2+bI+dmpl8cHK3NDK3M/Z8INsYq4xfb1xcqQ5vZBdnswmZlYWb9cvHc/Gr9fPP1s9", "/wTNVhYWVhbuZqcPNEd/zp7Prrw4sDL3U/3q7calo9nz2ysvLzUPnGk8Xqw/ul6/dKTx8lTjl4v1I0P4vTlzGN3yvcuHOKRf", "rjXO3KuPPV+9c271+lM+ODRcH0fLmdXz06s3LjQm57LhxytzR5svX9ZPXmo8ubHychmPNF9iVM+yS/caC8src4to2Xx6uH7u", "YvPuyOqNU9nklezW8frje9nIMb598VL9zLPm+YlsZDibnq+fuNc8fjKbO5hdWqg/G8M6NO4vYF7ZxKls7tDK4tDK/Fh2+2U2", "cbRx5mr9yWI2udQ4MspvZ89mdw7Wr1yqHzlax7PnHq6eX6xfGsIv9XPz2YuJ7Nj5lYUH9YmTK0uTHPbCifrkk+zWT83li1g0", "LEhj8Wrj6u3VA6frc3P1sYlsfjk7NZ4NP1tZPIf+m9fvZdNHsuF7jQeyHS9+yk5daC5PNq8faxycz0YXG0fG6pcPNc48zaZO", "rsyda5w91pxeak5fz4aPN5/M189ebB58lI1fy4Zvc9jj99AtdjY7O4Kdyo7/lE3faJx4iEVbmRuvP32Ouay8PJs9f9RYnGjg", "2XtDzZk7jcWRxq2l7NhC4+Ji9vJs/dID7N3qpaHmnQMri8/r117Uz8zUjx0A2axeHF49vVQ/cRu/Z9PPssUFDKYOApg4unph", "uDmzWH98Nls6uvLyeOPlNF5Rf3pidehI/eh9rEb92vPs5ensyPFsbKQxu1g/8SPmmE1eW5kDXd2qXziNVc1Onli9+nhlHjM9", "3jz0cnUIyziKZqC0xt1TIBJQJj7HS7Nbo9nJMRBPdusuRoLxY+ka18407j9bmTuN9ljS1UP3Vq/PNyan8fbV0WPN5Qv1CzPZ", "i6Hs7tH6oeFs5ClWtXn4FGiSdHX6QOPIsWxuOhu/j0+yY+dIXQsn2f/UHfx/Zf5adulhdnmo/nSieXesPn4WDUD5jXtHsVD1", "2YP1oROgIvBLNnQxG7+KcYJK8RUGgFmjcXN6Jrt6AkQIysFCcU9fztaPTjYPXMhuPqxfOLGyuMjdOXA7W3heP/uwfny6sXSC", "3Dr7svnyzsri0cbi8ZWXI5gFV+zpAdAqWBJcBm7lXGYu1y8sNW4tkJAWJrPjZ7ERYFtQFNa8fuUkxz+5VD8/DFLEyLPh55gX", "OgGVZmPnwTXYx2zuHCgtmxlpXDsAtiLdnribjT3js8cWsqsLIA+sLUaF9iCq1dHjnCOod+FYdu5S/cENUC+oEV1hkckFC5PN", "oUPNmbOgdpLi1fnm9BQGTII8s5wtXKqPYbsXGidmshuHVu9crM/NZCePcRnvzYIS8NTqEETNUDb9E/du4hQ3/fSB+rXRbHRE", "XneiefdmNvIYI8TCikw7iv6zifHmk5tY0vrYOUgYMAJkzsriTXBc4+4MFiS7DW5dwDpzpmeGsjPT2SiG8bBxZxESJls4A5mD", "ZUF7UCOG1HhxrrkEwXIV3Ae515y5QSrF1l8C/z6mcLhyOFsaA+/Xf5yqn1lqLB5uLI5ijo2pc43JJ+AakEQ2Plm/fBt0Vb94", "cPXcaQrPsYeNQ1Or5++hk9Uz06BerPPq5SvZ3Fzz6GxzZqpxcSlbuJPNHatfmiQ93H5cnznTXDrU4BhGmncPc2XIidMk+PP3", "6odBnwcaj5ayl/fr5yHGKZ1Wf7lAaXMPgmt+9fIN7OPq6Kns1mHIfIiX1YsnQYqQeKunn4HdyCmY1NjIysIvjSP3yRqLE82T", "t+vPIWGucYTTz7CzjbvHQXIih59jUmS68evUJqfGm9MPIUmofRaPNp/cWx2daJx5TlJ8OZudPp69OEsVMH4bLTFm7sXyL6tD", "V7Mf72FVufUPf4Ikx0QaZx43Z0il9WvXsSPNmdvZiZFs4lE28TO4oLl8BmK/+WRqZf5hdvJ44+5DESYjoCgy4MwT8hTE8sKZ", "bOq+yM/T1C/3jmYLE6CT5tiD+qVD2enr7I2b+CybPrSyfLk+fqs5BJlzZmVxPLt1v/Hz+WziJkRrfehAY/wZ/31kPhv7pTl9", "C6/LlodXry9C5kMjZA8n+NKxU9kQqZTf/vwj9G92bLh+9MHqwZuQD3gvJSHk58gwxdFJTG2enA7+vTuCma5evAHGpN5cHsVQ", "G2dmoVNIqJCcowuyzsfxVX3qJqQ6Jli/cLV+dnhl4Sjoh/r32ijmSPk/fr25dBqciDeC/LDjjetD0BcUZQsjZJnFhcYU6Pk0", "tBsV0MlDkLckKiiXsR+zmXm8t3kE/D5DjTxyjPwLWXHpauOnw3z2l6ONqSONhbsQ5tkViKaJ1Z+PZdNXyONjzzB9DBVQAeNp", "TC0Jvx/NTlzNxibr569RTUADAhIMHSWuAHePjdaPjWbHz5MLzk+tTo5kkzdEJwpzQa1PXqtP3WoM3wWV1p/PZpceY44kOejT", "51eEzq+CyDEe6JHmMub1AgqCzE55eBqcK3qEuoZqZeYwVFvz7pFs6Tw55fgJqrOFqWz6GIinfvgqv5o+0rw5jAbg0NWD09QR", "EIMLd1ZvXiUKuviycfhZ8+UDopTx2+xt+iGRDGT7dbz3GBifu/bwFMXIaUiwS83by+BEbOLq8I/Zwnk8Dn23snih/mAJEgDq", "nlILuzx9jAKWyOQcNB006eqNkWzmBVEW5ntsERQCucH/L05kw3Nc1clr2fzjbAJccBhcmd24Aj6tXz4JdESyvHFlZf4o3tU8", "QE1aPzuGHSdtzz8BMIOyI8WCIMG2M0eAN6C2Vpan62fms4mDK3Mn6kdOZ8cfgkMhjSnlbjxs3j1IcDJ1gWDs0VLj9pXmieey", "UPcx2cbi3cbi1MrLa8AhlP/QifeuAylBlBFvQAbeuro6Ody8eKJ+Gurs0urNE8AY5Menz6HlSZ8vTwPVNK5OEbJevo6Vrz9a", "bJw731w+SYSzcBezgLqHxMOyNMeAYMdAmcSfk1eBEMhWZydWgaBI24fxCqLHh4cotB+PEjECwY7faz65CgWRjYBP0dUywCeo", "t37uJeHNxPnm9D0sDnkWCHni+OqdMaKsFwsUv0N3m8cOZWB5IOSjF1denFo9/wjrCSKklrl0vHl3iIJ94iAeAbNASJIHsb/L", "l5szwFFLK/N3wODciKdHoRkbd4ncwOBcHCiy6Z+aB683blPv1M9NAYkBXVAHYYXHr4B3sJvArqujo5zXydtQXkQj2LvJabLb", "2Cw0b/3UYaKLS0eof2+NNm++JKqBIL20gKWD1sumzoO8sdGQnxTyI2DYU0RNl2+QI4AeKQ+vQLCwt4dPQGCgXuGmcWCY5sMb", "+H/94jS4iVJlDmQzvvLiGqXB2C/1qWP1yUf1o7dFj0wSNg8fJwdN/EyNef4ZFfHj0ea98ebSEvgLnMIdnL5BGDl0AL0BeONd", "MBlolTx5AundePYIuJTIHxpq9GewD5gd74KWAdQBua5evs/9WqCGpRwG3b6AAroJ/Z6NXVu9eIuLPzbXHD+IhQJuwY7UH1yv", "n52Dys4enqImHfsROA2asX5ERgV+PHmCCHD4nrz3KWTLysvHUDqNqTNQDUQay5dXf7oEoYcX1W8OgcawF9g76AJMs/7oR240", "ZPXcXOPMT83RxxzPyRFiQiA96EpAmluAxM/w0uaV49n8XOPOBDE/UNbLG1RkoyPAupQngKywccYe1ocu1w+BCE9QjxyfABdA", "E2FqxM+3X4I7aMIcOwJRSVKEBJuHuXSJBPbiF9AMtpvGyxFIj8MgRWx3/fIyaBUgDSILjEZz6cJpzI6QbxycMkkRDZvi+CgW", "nGp64Q7368h98tTZJwCiGN7q0DVKTtLY+dWr9yFPmk/m2A8miK2cnFs9f4nSGNrh5Sw1HawqyHPgmel5rjCWa1yspMvXIQ9p", "KgI9TnNrQPACcp5ls8NgHEjO5vIVMCkUUHYcduISHqRp8Pxudvs2RAStGGg9GLCXb1uTFjQM2iPNQJlC6UDaj1/h4oOp74xB", "o2GDwF+rZy5iozmFk2PAexDp2dALEBgnO3mqcfkm9DJEE62whZ+hnlYvUJ1Roh5Zrh8dhphdPbssHLdAFAGLCVoYtsniE3AZ", "hHN9fil7fiebeAzuXll8CRKCpgCLwaqC9oeso1EG2jhzNTsF8+omuAnwlTY46OcFqGK+eeQRSA7zwr7TVAQ3QWLAwD8M+jlO", "UT98l9sHTQrBuHySZAOhtHy++fgmMdszAPLR7NJVQuWnF+uzV2HZUQGduEfoC6MP4788RX165C6tM5Dl0DVIG4IWtJlfFlty", "oT4x0Vx+mE1cgJVEll+8Sn4/Irxw8X5zZokQ6xglNnEjLDi89MQiddCR47DKaR3MPwEV1S8fxNhAAytzL0G9VN8Xod1G6pd+", "5hwhb2mkwM69CQlDLHRkLLt8vrnwC3YB880WRjBs4HYSnvAL7fFLV5uz8vkh2AKXCHcPTjemZwEtaKfPHoQSzCbOQZZSG8JQ", "nZzDyoO1iYrHRlZ/vAq7Bn82rk8TV0NWLx2lZXR5CFZD/QoshYvNGSCiaaKg6cvNJ5chUQlabp7A3OsnxFqHhTXzYzZ9DTwC", "sUO4df9s85dzjXNL+AqGCSUDRgLB+8tFatLDy41fbtdnJkSkTGW3LEeP4BNqn1v3609ug62IJCceNg7cBEUBo2LK9J/M/Qx9", "lE1foDsCJgOQ/+Qc1fTYhcbZ24S+eGoJZt0YjaOlZQLpySlQIO3QseVs9mj92gTFEYxErDbIZvRJ4+cDpKgDpwWIPhB3ymkw", "Rf36TVLs+GMIk2ziTnbrHPl3+BDwPE0AAoYLwGzZ5KRo5+vNn4HST6z+dLJx9wDWist19zBUZ/3ZWPPJfDY8Cy7Lli8AONFJ", "BSN07g73/eRxTLZx8QV9Iy+GYElRjVKznxdNQUqDxIBNQctRLDj8jt5grYiJehU6moCfaJM+KKIUIIHLV6GqsNfgAsqxYfoo", "sDhURi8uNO4OYRkB/LAmEKGrB8brY49IRRM36dtZuJU9nCXqWL4M81wsCDDyQbyasoWYii6ybHaWJAd1efgquLU+PU6Kun6l", "fvJS9vBoNgtleoIG2tjz5pMbtJVuPly9CthGdxA+IZy7/BPlxvwjmEWYHUUcMNXkOC3oi6fwySr4/dgwpLr40J7REnw6SQgH", "Q+DopAicYxgMZdqFmcalF43L2AtAlCfZPSiISSJJrM/xX+g6eHGhfugayDK7OUphODzbPDJDJ9jwMF00D+5gx1cvAic/w1yI", "XoBAJmZgk+J10JL0PMBygXVJG2SJHoMbL9DPyovzAL318xP0g8FaxKZg47DRU+hwBpSzOnSQAvbEVew1QBfFIDo5NwpaArRu", "LC5DyjXuEQU1FsewYjQ6jtyHHUcfy8lLjaMAgZPY8ZW52xR6D+eay5eykYuc8qUjsGQbv2Cdj8B+ac5eB5lhoTjy2y8bi5fx", "YXb8AA3b5UPN5UlMCoYA9BGdTi8uZOPLbInBP7jZfDqRzcNCOUNnJnACmOvkKdEODymogbuml4AVIXP4lqeHgWDJNdeerP40", "0bg8ROl06y6dgRdm6jNnSSEXFyirj50jl00fI+Ngs66egPCk+QPxC6V/5DTkbePMDfo37hwUD9U9Wn/LlxuAWJPXGk+uUT4A", "WwJ7H7xHXDS5RG/k4UlRPeCRm1BbAplo41ODTx+pn/ixDuA3e2R19JhIuUmYbzRs7y+s3jkH8EyL49zh1fuzRNdzR9GG6zAC", "6578AjN8Zf7I6oXH2fAR7D79US8OrixMZyMABkcbJ+5Txy3dwr4TQz48BaUMOqE9fm+WWnv4ObptnFkEaCF6eUyjFeqeWBRA", "+tBL0DYdd9cfUEfDsrh0tD43XL/9U/3klcaDU/QSXzuwukhUBsoh2c9ebR6dwHYTnc4tNqavr154Vp9+2ry3mI2MN5YXmzOn", "IITBONmBn4iIXrxYmT9Bo296hlv2/Hbj6FB9+OjKPADnXOPEDJn6KsTRItd8+SnRyBU6e4HiuJKwlI8tYzpuyjAOHQ74jOvz", "Yt+TEMnYD33XjxJfV6pRNYq/TbWbMlCFJ55eJAGzoQRsGtY7iJUEzoZhVCnEWuJnw6qOmYSlGL8qIaXG9VNPeXLOHqk0RJ/S", "j/HkE4maj6uxxnuNLr1aCCWO1AxEjOWQwFLDdJJQlVWBucslOUhjSK6R0EIOm9Eo36Z+1QY+GomtNSoopaFyozjWkU3uZEiv", "H6s49guMPkRvZRm55gE4DzI4TlUp+GsRiYw7Zai5YaDfq6lQK8btuNoG4UrsqITmFhRDcGOJhcV4UsbpSWxPVGHAZjDAaEB+", "jvnKKhkJwDUSpBtKVQAlkbyG51CMZuYpu6eZzx0VecYmkZ5G4mEiZk74SoIzOUesmBtVqjZzWxuJ9uGuxXiBL+GZPL+1kZCx", "xH8aj/E3mGPs+qoaeRgEs7WTyPM5UPxeCCSomFECmGvA+h1+5Ma+8bGbzEPCTqXsAb/rIikEqxJjZSW9SmsGRkUSQC0Ryp6S", "HlRU5OphBdBUt/HgnCujjJyVG4lVixizZPtnNChWKpK4QSNR1waT9Rlly5wRCaM2sdr/6jHeWfA505QxblGgvSjRIfYXk321", "YCQ6j9GyfqgY14TxcmWUy7CmyH113fP3S9wnY//wlGR7Ke7+flK4H0TYRY6ZJB+/ur/PxztePa7q/aQqTw28mvJ0pAd4dllV", "zAKuaIaQM5SVaUBMlyi+uu76gasKeEgigiV81UOfeDrqU1XMQoJhTUEoRCKnjYTRxhItHBZltbHX3HGG+hpJ1+VMMfeCHxRU", "RI4A4ZArDWOYlMQ3etHrJ68Xf534dVSy5BdeP8TPHLPefz0unzz69YDkyj/G78u/DuHzg9Lm6a9H8HNI8up/kk9m8dtzyalf", "tJn2r3+UZ5clC3+KvUmPL34dxacvmK2Pvxf5b2bx49klyep/jNZr378+w7G9vsr38jv0Jxn8kmH/4vWC9PdY+n/E3mVsL15f", "f33v9Un89yGevWtnIc8+km/xJMZ9Q8b8RD7jW1/IfGXW+PZH+QRv+XVYZs2+WWOALZ/gn5fo+Uf7xrWxMdf/x99HiGcPrPXA", "NkPocfbfFQPm8MRLWdMr8g/XekTe/lDa2DoGrCywJJUDltAzx2nrFyz9egC9Pfnt1tnfbo/+dmv+t9tj8vvQb7fm5JOzv91a", "kk+O/nbrzG+3Hv5262f59z35dkIa4P/Lv92akqdG+SA/QZtb8tS8/HtEHpyXNjP8hf9eYhs2vo3f+xR5Wlpe4v/51PBvtx78", "duuO/H7+t1tj8tWS/D4hnUzLG+/9duvpWp8c1e3f/413XZCRXPq9nyF5nfTD359Ky3vyyb3f+0T7IzKL6d9XYFpaYgyP5JM5", "6W1anrojn5yWp0bkwwfSYEo+eSDd/sQH+dU9aXNe1nZIeht6M//28Nsjb27z329H3zx8c/fNjTfTb2bfzL+ZwT93f/8cP0+l", "rsPC2/E3s1LJYYT1GdCeNRhG0H72zTO0O/z20NtR/H0Xn469HX57UOo8zEslh7vyOVuwYsPP6Pkgqzug36k399ET3vv2AD57", "jt7u4e2z0vI2R4XfhtHiLlrOcLRSW2JcKknMv3mGb8ffHsDvU29+kbdybKPo9ybf+ObB2kxG8ftj1qLAeEbezMiYHsu7ZjE7", "zpRVJR6ylgRa3pTaFMPo0Y74Z5kJRoCnWKPiKZ56gp8pfDIm1SpYDeOujJZP8D2znNfvz2KEN9H3GOZ5F0/fXPt8hG+TsXAm", "Y/jnIMeLliNvprna8tvP0ucw3nj3zXWZ3bi0Yeun3BtZn9m3B1kdg6vENZZ9mZFx3JT2WGfs3c9cXTwxgs8eoI9hGcPP3JM3", "D/DbfazSCFqO463DaM9ZLLx5hE9GMIfH3HEZz2Gp0sEVtqM7iPW5J/O+yxVGTzeFRli14zr3RMYxvLZ3h1jRA9+S5n7GNxzV", "vX+v+mNZmUPyrnmhihmMD+OSt3Id5qW3Uel/lDMH3cy+ec4xSGyY5AYxRpKxp2mQlBnkGhRtBLbAOgY8pVWJRpQwJY+VNaS6", "g0SqFZUp+1HYZWPsJeQkrgHuSE6vRNMzXZ+622YCmDgNQ8l+jvg4qxEwkldik5ldwzzOQR1I0UXgMzfQaSilF0LNrPZ+ohsV", "1rwa1KpNyzcS0Deg3Br6ZLR5r50Ry9GgU8+X3IhYS3ZyLPPFGwosP1H2pWiEzQMwa+HKfAvDXXXMeFdGyLD4QJmR0YGNu88r", "T3IepbKH9ga1RDsLtnSZVO2lLsvc8C+AGYZ8Mp3NVaFNnvBMKtMV0MzcIrfMtIU0ljoWzDJhwZECwEVNopSldKdivqcUbouZ", "mIDvKopp7tqGJRpZAgKCkFgBgygxzg8gRyc1m48ha81UMonJ9xJAnxLTFBhpaxiWyXi4QHJ3CdZCQneGKNcI4jFcpowzzEmC", "vphSV5XUhICxTDaXZGMfOsMjeLtsJ+uuoW/7pd7H4FmzlltRYLymq3dxpqa8w9JZUo4ZcrVHwqUdYERb9oGh8YkakOg7GgiY", "u6QblXQvSIGV7ohn45qnXUY2MVmVySO+4f6x7geWmMUT/IR1Nhm8WJKEuoD0wZQBLS2NDXSS+hisUSH5rizeCHhtsxyMTcow", "Nj6bRbu4ZiQw7ABjgH3JDiFpeH6JyLzqu1yebbbmSoXGBldeMeg3sDtt02SsRaQCEC4p0mZPtNuweCNxnQCNWuLGGCnL+aUm", "cQraZnaYv1lqTZlsENQ0k8485kgwYI0B/sJjA34ESImFxOccpSQdCM13tadBz7oWBr2yqEAgdUkkns8PGcHH0E2m8pW0slNh", "ATSAeonA115V0gzC1L5/p527qySt+++W1RhJmzIpB2zkgsrBI9rbxvIhTMmgfQPSKHGrHBvnZoN6GcdHatiWMussKelE5i6p", "LYZDwV977Ba7SvjXJsgwz0CSXYjqXc38AW6wrLUh1cEy6d4kb/rECgGn2wn1oLPD7oNNbfJ6SSEq+MLKHsoQX0o4kEnA1+SH", "HcxuK0k9ogILMjJk0xS05JJILLj2duo0MUzpCUnzEr8f2zo7LCaTDOq15P6gZuz8QFKcdK9lX8iXKslzX9kv+AkTft9pa9th", "hYfUwGFC9QD3IUolCnQt72UtOWaDFVrVlDagFjndnbMh9w4DzqUwh1DIp2JLck9ABcwiApvVbGKLadvEmoItkogQV3ZYYcXi", "tKHNCiKBVZlaU2KBFIZJWsEpMfza+5jUH0IKMwvIY2htXOnxYbmknh4sa0tSzATxeu2OuSphoP42qwNsTpEt8ARuCH0+L9JG", "15jngpXfwezAUlRmyRFV+9hyODOGQLQbrQgSkgIpatalLpEZB0i7hoGJknsFwqcACmr5lhYmC+C1DojMA+2AA7ZDMmBzd1Dq", "QkliiR2Wm/TRSn8aSy3qnCMZ2DaNw9C+9aUoM7MVPrMivZxKwqMfOmwFSaD82OzACjKdmRmGKijENjzblzyrQFqXtrIOb3fO", "Zk84a0lKjPTHmoGZK37KLJB+zHZbhWVI1S5PcuP/Zef+udXaTEtxkkgiO7tzVKaB3seoaVJBIpkHBUbODmip+KXjNpt+Z9Pp", "DGsy4HGW98Xcd4MZitE+KjcGJkNX0WgWYQWVtc+vpJWyFXKQK74X1CCfK1KFFFQCBY9xsuy3xHsbqW2FqWAE2uZWp6z2GiqT", "1ECeeKvTa3FIzAzFVFOWRJXaVxZWYM1EN1ImU8ChZ7xPCXnn7RJss6hkl0eN7BhdIhd/FUGUJ45N5zB7lOtb0czcgLTqDEr5", "Ioa7bh3UDst+bxMtuZalYb6x2XosuYRJK1cEBCsoY9+l6Ib2tjoSyptYMFSg1jVJATtR9BPGRWOAvVbAszIp1gwSGB2aSiTy", "hXXy8B/fOCxozrnHRounBFvB+tTdOVF1IGhWFhpgzD9TEbgPUrm0ormi+/D+is0HjrVNDNqqxa3mYZEc1gVieLYCD4tKHlQ1", "LrmzLWUeq80yMzss+LJZZUaKwEGPs2iakdQQDEIqYKxrqbKmNTR6LKmRLuuNVxPBbgwkjiVZzQZt2zROFgJjipyzfj0ZDwKE", "c4cyDSSHFcIcMsSqeQuwtAJZgimZVi3igslqpjUvST6Sceyu5SFBk4hrx/rCPBvU79gcnFiKrjFOn7WK9C4J8ocwFm2/lmS5", "w0I/X3xmQQhZTuiQyjZ+Y1MimNJBOmNAdK6HQjwgLJTOqAjwXRsgZ/9aGpn2/pqyPDL1UVUqxEELV8zeMlSccSrRfqIbbqMv", "ZVmY1qgtM0PAU9xtFYraWGb5Le19GdQqABrfWCFpE1mNFKfCxACpQt9dy6K06YyMzwdSFB9uIsJDdsTmx0qRsaBWsomwUiIL", "9GeL1FDxsRurFC3l51mVouxXWbDHZ2qtiC7JziFMYUEiL01kq5gdymxECxkT+b4kvBYwGYE5hNstngf65Xt/cKQwzx4LJ6Ei", "Ka1Ysh4kthuEAUFv0xONZNJpbxd5hxqnSG3PVFwAHt5XAGnTq2UubXaVdlsozTyyqMgiJiwfJKWLqK5D5lyyXNaGjtZ2lpLu", "k+raFBfWjOhNdLWsQyYQ6NCJCmJUSHmmdS2fS+aZwxXDUHOOFL2xKcsGemU3iLyl5XOwkWNzs4zE8mMfrNQr+gLJWCQDQ6PD", "VMobMusCFoqsEgsmuT6MEYB0Y/osLX2sWSzA2c4iOWnFlibqSQZ9QWYREzNqrO7O8nMKuDzWjk2jYA0Z2mPlmE5EMi3ZUXKy", "BFxClLJq8boWZ4c17kDr4EmW9DcYIN/uKCNv98E+klrYRbbo6WLlewAJQQ7rWmy+nrFj0XZBthLMohfXIuNNNv1Ayou1OMbu", "WMHWzLIJp86glrS8jg5brw30DiIEDKUEk8ofEJ4+VbhT8HmtQo3XWzgsaupwA1kcHX+9GyuohE5e18DK26y8FpY2WOLdiX8B", "VTF5j/TpMzWEpYD4hm1WlPwNsAz25wCIkV+mFDLGZQlCFYhqdbr/boWHVAmDiHVEndpkFa9LSWIvE5GwmM42yN/YFx1X1jt/", "N1cTKBKP6S4DnBHTljsLioLFsDA3RwYJSKMYIgNrSh3uKNqUtD6BR9nZX5mSCMghmSaS8EY1YdM0bBqIs1tyXRyiGbJvrUpy", "k9KHLm3Fii91EUPHL1qjKbEJYR4JCK9tt1KgYLNt2sRu2cqKnGL3My07L/lTuR6MDG9NYIMEWqw90rzk/OA7LHLqJ7vlsgGP", "eU/kC+oBZaQ+Xq4Hs+Q62zRZAEjeGNDDazGcgtwygk1VjkitCg3UuNYumVP5ooUAHvYE6ozFaaDZXIvZpeSB2DK0vvxEtH2Y", "ikj6q9RQd0RUmoTQD38WpfgkZQG4kmW9WHvTChRnsBxxuCTSlEU0pDCFAcjHeGXpWDJT8t1tQrfplZoFDsv4czejCreTSAlE", "Rf2HF9mkxa5CjZvpfGEh6h7r7LApryynSfZg4hJ0eS/YA/1JTbegtoeaCRIycniCRcsmpZVMo9TYKgnMGaZ2MpKVbHiFCpaJ", "9YRoZSnJa6LFDqFjkwg3tNlELDEjcj20ehK/2mtNZ1vpwOxN434MQgqn6jgvJTQ3CC5oaSlYGpTSdbyGg3maa5Ufur9iXYzY", "k2zyoFblPSi+mMX+7ylELZLqtPWPaSAMJIdmRi5SEAkGU8CV8vACHbSbrvlDjBRTxcR2WieXXdaWrY5UApS6bzzGSiEcKmJQ", "YavonsL49kl1O0lvXddiqxzk/7KvEjgDcq+N2GqsAMc6Atwk3qmANhr4uK2tpzUPjo032Iw9w8tV8ADrQOF/Ylbv139jGigI", "RdJEQeOx251r32N9SB6zy+lJEsyXWCC4R0ppOLy1xvHDv7JyW1neTIBpbbUuyUbvUY7AYN7bEK6XK0Xijc4u6+EpwrYjKiPD", "RPEnKc2h2jY/tjUOZCogG1oun0uZlcDm+pk9a46ljUBVnuPYvME19w9L1EomfREs3WJLYJiP5SYdZ5u1c/hsRYmes5UxABBr", "LHEnOkBEM9sbSi8gXt+wdhwsc9bJj5iEBhycxDtstZLPUwNkYv5uzSsYVBXBpuK9o7bGen4qeaIbpXZmUGunnfuNAsvInQJS", "i2DDtlTKLJJFQW7Wu7Xx01A4DpCYO/aJdnhJj00FN9vkMLbW8oc/sOLYThiVGkLI2mqSDJfrYWo3WEZwz369DXZfWVU22NIR", "31kGqqbSdauosQ0267Fl57a92/7p/CdxInCF2EU0KhKMXhLX6YVjdcWa843U+1svYgayTFI5jV/cQNjwaSLDfZeX0HQ6uR6p", "Q8sbbkAvX1ofp7ZAl1fiiOxh7mZYEvTjRKGU+xVYUay5lHzkKuuXSqDzB0Na1az5GQ6QPIVRwxI3DN/xChCQcM6BRdyd85iy", "HVXtGxLMgRRgM2QNjH+OgtUpwc0qcGm8t3aKpLDJggoYgnJ+QNS/+A6hXrdZ7ytr8+o0VtaHJEfaYJUgICYaXJuYqBkjzr9i", "TQSRVF8p+mRtDNpNdlqsSJMVy9Mie+rYgiuSj4lePpOSB852atioSG0o7sWQF8dQDYJS+umk7E8kOXm9TYzMObaUTfeglabU", "8l/5pc4WmR/LYXCG27BRGx03TqV+Desa5Hrox0S/UnDTsJgdjWwaBunvhqaxWcEO2JAuCsGK3U7LOil6mURSZOAra7HvsX7h", "3RZr7KGjgKV5pHTF3/yYpLVWkGGHdWvtsWjU5sJ3VgkVWOtC0eX5mVirjq1jYraFAExhzep35yvr2tllrXJrfhjXUjk2HZRi", "oRgdKGL1tNlCNF9YPCi5oACZv1eHUCwnZEtyGN6yRHAixYKMSL5CjfpW6nbH/egT9AmCrAF80hXI79C5svKMF0Zh41paeqEo", "nfVSBXm9rbph+nWNBcNF9wcBU9TRUirWtnbSO6kHHVutx5Fa2RCmscMEZiml0Lk22k7xvUIfSZ63sQmwDr0ROij2Wq/Kbi1J", "2wOihLXUQzJlemChlhL6l4BkXamZQHXusEoUtafZmfZTKtoyQRvFIPaTQSvyeAsRNkA5kmKc25orJ0mVbwYn2qoTLVJ2KKjZ", "WjSxaw0HMjp7F1wX9trjBPo78aKA5ZyTWtHaFhTyADXa2lUmpaNJ94oV6ZQtXX8lJU5CqR9gkm0B3SlKlI14PWheCfbN9eQF", "hnpeJDiraBeE9VfRhv4QlZR3Wo23w7qObc0b02qVDYawBtN4IxxRghVd9Ml9ag3Nol9MNC/BcXgZW15Kd+blWoLQK9py8rDV", "WEoIPBVIvnYJ8tvtdj7Hy/NiZEP6WWRctQVAlCN1rVl/DUvACvYUAuL/cgpitsS82cyh9Uw177BWgsPgFsH6sVQlWStyxAoK", "iWinROoBB1HqFWO6WtDZ5+Ks2MTDLvp7YEFC6W237mGi/kgeYIjRgOVbqRAP8Cw17DxeswKRYWs6OFJoRHufWb/3J1IQypEb", "n2q8OAh/1cTbBGkqBTMkaogQg5Xocz1GRlDiVT+gwe2Sld3KqnXY7NjWXvoYyphnZ9gAB5omZe01z9YjMCwO7IBYrEuPZTa5", "xdSNWAkldo6lSCkAgEehubzITWUhy6ytL8X0WZmmmFoPlGOLXvTsZrk3U6O2FzjVh830vrbHHhyuuBQiHvLYM0VHnAGuTgVc", "OJ9be9rm87doGhNhUtDiW4Ms2MH6aP4+EhG1fcV3/9gh/yPhxfRLeYCmji005oi2BWIBscgKAps63VJfmOdArNph9lhQynsM", "iCMTeW8xFef0gNy5VLK1mKADxMZnbBQsWanirdfqvBjymKaXTjSKuNFc8gercNjSZ228JYb+AhWSWWxmPZbSIRprzUNrbmgV", "p1FrpxQOtoxHrW2lDU9TqY5in3X5bMkjw/Kr+LGeWfC6Q2G3Q9C2sdWnnO2pGJprNYz2WqsA7Cv0XdWsWlGKPFal26tKpM9t", "wlRbqbYgWL6SCi2gdIZgyQ2UEEi29MG7n7EgUBAOaocsscOex/01hVQ3FWuv0LVCXSUnEw4kvuFYIOJowEnV8PUbhfhgTUVs", "HbSIhmQ5WtYnobVBq3ANJkBVEIba8la2apjZzhoPsdT/4QE4+R6i2dIgL890WH4+ht6Od1s3Ux9Pr2F9ii7P5615TGgSstyN", "w6tTbGki1sMB34fyn8TGJOYcOb6JHdYIpgTF68JIbigTqoMMqVVAgWIQ8HYLHXfYshCEB0C/Fo/n2v/T6XrnnzvESHO6I3GO", "OLRdwUdytZvnWPRLs8X8W70YxxoXEIZ4YFAOB11jq5/x2kqWTuGNkBSAmD+Xbs1HKtLNcWypuB/Ea7fBFhIss9haIdo3aFWd", "nZjHWm37wWOOF8E0ia1zPO+Igh4czOewnwUxiEtS8T3aynXDWucdcZxZd5H5/vvvfugc9AUCREVTC+3y8JzUSE1STQ8niZ1V", "V/bGKhVB6hhbwM4aKl1gp15ApW3WC27N3Ly1BpMd1hoUgsw5f/cDgI+KSWHFFnjnWIrdKvhSWzcvVwJssMUQHVt30EidmKgY", "siaaCnbYk2zWsguU3FWABZHbAIJam3XxtNkii13tgd/T0pJ3xL0IxiMVQ/zS0b9rzScudb6cAV+JrVZltcoApEfPXpwGgp5j", "cca5lhsJClivLw0oCMtk+qjfVk/c2G2JaMNa4TTxswIBS5F31mrG8n0ulUuc/+I9q15trRoUi/ezM/Gle9vlilcj1fu72gnq", "iG1sPUcCeEjhsl8h1dCMKGAbxY7Ls84/S4PD3uS1jpxWEpm8vefRE+dDlcXSkpqlr62+EHTtM3vSqxxhhU90XBAejf1+ULKt", "h5hfK/coxf/Wjr6rvAQS7CSetNix8tOhjxMmHdAF73ikUxRMEltMJGfjjsNTjwrvLvVjkbTQcX7yXxb5AwtHoR/Zeo3OWnnA", "NT1hSxLSNUpvaK6VF6ltEGdAwMNtShRbVW1t0Bv32KgBLCPvGHToE+/OOVaf+aE4A7rsMYatbPO3nq7/3Q6RSBcQT6QtWDcs", "yBoD3ooSljtWlHmn21mPv+kOlWtr4wQrYWvBbN0WqwKQHKUw5u5adxGri3G2cgrYZisGbgQpUW+w+jK+o8oEq+0IuHIhS6nR", "GVcSfWudt1IVn2Jm7SzSajxMnbW4d1gL0xavMj3WbJWVoNcP2LMQ2JJ6jkRWYCpiFeSrZmvO+Ytjb45JQE486mLJdmyqrbdo", "pMg+RsY7ROjG8Eg3hBWCEtB5d46KyJ5JMc5juyrAngnt+diamBF3A89gEzmC22YEvtpKdIbc58dkXfoJaXaDfj5hxeEo3Lzm", "uXRdogtbJNRhOX4enVqY1iq36G2oUpqhe+uTBZv9NQ1qWMY/OTkiXB5w0u0KtEanE+hRLGG6+hy57XT9n9ZDHVpE7NgaalQ2", "HI6ts2d4uTJ3hWfeaq0QqNNlSYpgSw4h2XIDS7aBEUguMDHAtLwSOu/IuZpcYCIlOvF7rd3yb6EkyAeKgRv+qb3zQi4bAfSz", "8GBzdZ+zpbqvT24zycutSI6yFVTzMFSIWCw9t3WLT66T9EnVJAVj87ZPR1Sk021rt26krcOb6WxhQFtgik4yBiDxOkxHGVuz", "1JMCgrGtzd/iUAlHUmWViLpo6YX6MaTH16Hbg0tOdWXPDwctrBgsixeWZ13g4kLcw/s+rS/HsSfE3aKkgCBS2vbaN+I/U7JF", "zjav4sfi7t2nvU5b/db53MYo7SFdb3QoSWI/IpbiEWIsChb8ztKJ3Tm59oSFoOxhMNGvkpmIkBX0K8JYbj1wsFgVIn/ei+Ww", "phl4Mk0M5JIp1tBtUYoIAr9A9kRipNlCaUaIL6TDDOxfIWziwYovINHzxam9m4ezMF7FM7fBFs+kP7KKbmych0NioFKgNcEj", "V547G3ctzIDFrH4vJtdGQw1bBSsZurlma0+adqtGd8QRBqwcW++RVzBwYomYgyIgsA9aNF3rd4wdg4wTgBVYU4+XVUGj7Zb/", "5SxP5+SKB+UwySOqGSIph3fF8BKN0B4GxxUrwdKCXMEQa4llIxQDRVqY1iPBj5iYlht2v7BHBn5oywFHshh/Z0nW9eYLe6wq", "RSZVKMcJtANEO0JmEbTZcr01Iiu5Hlc0nq3L+R1hPysBSg1V8KBEhuSt79+RSmEb5N6mXE/KGvq5HqeXDmU6LQZEBUD7QltB", "f2L/CH1Z8BjCBpO2p3KOY48j6DIBWW3I7fzy8x2RDTgUPmdchJg5zn/ZsA1bU5CHyBJPFFH9DloI3WlhWuKtCWqRIWEFBhV9", "HszqIR4Wz5elnvWiRaHBpb6vt50hXLBvo8SWCpNaYdYu3lwSX0x1hw0hya/VobZlXyVYocwDWJ47MuiQss6VXkS38aTCsSFc", "jB0wNBXKUsyQ8VmcAGSDjYXrLlg/Hw0paMzubodulS5Lri1SbpRnWXJUK8y4Vnw0Lxg9CqnYoT7z1ofIMyxaNqDfYhTbArGO", "rVWIacs9Y5GVkbboX55yUEhMIrR2WG+9sZWAOWjMhkQKjibKwo5acc+9IwmTTnzMyJ7/YWFZlJG0C/gnJQwZeiIwzR5bfVOw", "8AA4mFc9fGrBui0BvlE5cobDx7EUX0j9P0duANExb31n2Wx2rX6vizsYid98gy1ibFGFiBrMtc0y4B6peylLK7Ai5lZZK+kb", "W/96o8RZSNipH3kb6XO357fWryaBg3K4vhbjydqVBK61bTYQJZFzw1q/xRqigte1kJuwK4qhV1EYpixaGuywAY7i7GdCkVBr", "FAuQoNcGi4rmG/GhG8t9ZbZEXpuNazZfujwq42UNNNIsBzj0fOGBndbroOnUI2IxZZ6r8Z62gCd3gXUz4c9uP5GYFQZYDVBO", "2NBSUShrxQ2NJboWa6TlfZqO0IPW9LJ68xvl8NIxgKF+lry3oVAbiagxsW8sgcplYbx/hCuw0UbbQcHKwhSE8SpyhxzUp9SB", "d+wZn0M+EzVhiI1tDWXH0pkRNBHXbJF049hDoj02fglChltnY8i9otx6yIN1coccw/sho/QAVKig6TGzLnFeZ8TFYolfWD72", "YFpigoJAbthzlC3e6diK33l2TQ32mRJcwSPhNPkECwgqEOu6UOPxmrV6eBrm+VI4uiBhTDUxfQJl9ZiRWpeJIY+VSB70voax", "Lqbm97rSTvfXvXym1x6T2bKYRs5oQY6yAnlKC7zPnrRv5HWQPIdNpV6ksFMQWPDUbuXKN9/YuqyfqBgiz2uXO5esjBNMSe8q", "Y70YcMEy80CH/TVsnvqaGXCelgPNdS3bElb+VXKEndp7tWobeU90QGMLf+V61qpgym2LjgJcpzcc1MOFlQr22Ly1gG0RAg6r", "ojrftdj4I94HzUlvFGak9qJ3lJba33n/tOaOu0po4hPWWqYkkqCFtbqS31miZRwdfR5FiU3lgvCOcswPI6vYtzMgaZCxOEnM", "HEdesoWVFV3KAVTouObaR/HXhpEuXdROBNasS+ubNhslVraePZbDxFtofcodjJoHCLyOjf7dRGwZam3aS3KKYXwbXFa0KmF7", "WgS4imx5zi5xvkNex9z/aIc9MhArxw9tDdC14HFRnwDesG4HAPZtdXznB16ixRM2hx3JjToq4NFZyPBfysH2JOW1jyxmy4Pw", "XrBeReJ/eQzY5nQppxzb6xagrJ0vvtzr2HL6G2VPFIRf7Nia+XTTJ1bDiim5rsUq+3zZcoeMkKdgPo9ncmTOXE9UAH5i+WKe", "aEc5qoeiL4oda7SLwVowxKSaux+KJU/ZDNJXLCKf6L/yNi8d/w997+84hFNYbYYgSPgv5bRjbJQeRkqg8RcbjGrzJdbUtVPw", "5e5KUbDdOSyGzCgRu/orSbfYaCtAO7aAtmPjUQblHlhQJ/0myqlan1VkBXyb3cBOG3pki6k7tiqyja/Qg1Wri+WCJkfKnmPS", "ypF4ig2+KLc1x0KnPfvW4f4ag5PEMUF5RfL5zh4LcZSqWsMwyFf07IhXnT77FrlojTpQfOn/O+3o2LJDic/QURLp8Ic/2GhV", "4UxI0q7eHV99umfvVzaAxVZbb5eg82jf9tqn3obcPkkANRsH7TEnxmKEKIsOuMyW5XcsQDXO13ToytlhWUk5cuyRbHGhxvLa", "PFCzBx3WsPXabSF+ez1XOBAFxCh4A0/5lGXYgj2+/9Qew4vHuBTxwB4DtWzk2DiyLuuzUJ0sC93VbsugG4mvUolFDjYFINaO", "rQEu/N1eVo7Y7FUbXfsJ9VE3PWRcZ+ZFAwn8TUnIX/c//9W5oZja2uSmvUfc4XS9QaN+atdF+KHrHXsAZBwbErJd+30SWQUl", "+OqaZ8P2JSNbpxCo/ZDRJaX9ACYKhCP+to43RVNL9WlmP+D9ib0EpsLUYDeqvrpektsoYXIwSFouVIncJOUVVKmECLMLkr80", "UPYuBya1m39nxCuefb66z/gJ11fGfqdsDlVk0/FZpZ3pvjbuQoWvFvBcpJj77TFLmLG6FQyiwEsfqdlsSnxkb5KCPdwnNpFg", "4nK0lm8uWUVexHLqJcaIyqUbTCXnFX68nZE4f8CGq3Kc0asFXsUcie6IjE1timySkL3CSbJOYhag57VOfoQB8ZakiuS4RzZj", "3GjrDJJrtZj3gqWKaX3qV7NRImE6vDLK80uRXEnhyT6gM3EN+EpZZxxWgtlTpZQO/NgWADBrtQX4l6/FzOeFREzkgvB7NZWk", "vEgp5L1MzDrnDUgUvX1RUfSKkmwrnrfxOyURchDSkuFusGAMhsbo/VePQwmbSiRfFgO0Sfn2ygPDW39cVi9wXbaE7YOpx3Jx", "l9yfy6hEXuoTv7pOWyf21yoTmMravjNLfwo4D3QTKrvkUpQBY+HtQj7vtqowc5wS59VCKFeERXIhWIXXhGFZlVQEkHh/xlrI", "bdkVe20zbTGe1vMwnX8T5DMuCzypgKPW0pB4aaacAPKki04XuaM45h2i9paA32+y0fts2o145LEfdKJSSnKrEjnZ9xiCU1tL", "RDRrUw7WEunM/jaJdti6lnYDnFBk7o22yQsJ78di2j0rrici32zKiFnL1vGIX/mgBO7KfH3J26L/iY5HRpGRnplZxVB0G0em", "Ahr3RJ826EjHa7lcQI9GEuhoy4M6Al7fTKy/lrsjwo7qdC2XzkgyAYFGWJN0JVUwEl0pOXo81x2wt3HDmFf7GTsmERSML7TH", "9OL1xIsHrGxzutbOkmmAMzaDxw8MREuikojCtaQcryC3B7Ee/aBYGmv7Jp42OvLMWnbSZ2v7bL07zJu0+W1y6zXfD3nLGIkK", "OJCBM78nFliFHdTkYJ0ZNHK7a0y2UFQGRS73ALNZtLhvJSpUbqaRGPuEaUb/P1tv2iTXeV4JyrtR3eh9X69T7WZhXKgC5OkJ", "N6pQDhAkRcgkxRAgq2c8PYpblbeqLpmVWZ03s4CkpAgQJLiJFGVbpGSZNkURJCEIAEGAAAFw+wD7q4L8ZDDmizuCpKiJmd8w", "85xznue9b6JHC6oql3vf+67Pcp5z0DaQVSBOp2TsKmQieVywWq6kghTLn7y6s+nbVkQmeoeiQaHMRiwqxbpKoXSWtyCNYi8w", "zsj6U4yuzVMY+PZ923aoHAh/H2YRVVqHlLjcxPgDaoroHKx+zANi8W1uRnUjggB25RGyiJiPfC57Zs/PTQjfsiGUtkHV3a86", "EMQ2ZxHXUA4FXoW0ETCfx5j6XaIcJmU9XIV6rEJVnG9ElaFyBshIr55qHGje3Rg0RE0AsIP2A+QKN6zc2sI5sOFFndKGWV6y", "TWnMMJkKBjqF79I9baJmXXgRosfgJ4Spr9mHKhaerouXH3BsxJhXR0KK2X3X690rdX/BC85iHWq6sb5Ixoi329YLDhubAMes", "7xEgIt4NoqNdPCSWg0TeVlfZNff6OgFggAuMGif9dQ/wLTsav7uviMLTEeXYgeDHAjoc+4dUAYaIrLP+E0pa66MN1T7bPGcY", "kUBU7qOoq0XYQoW6qxPKxYPeHgvVPklh0rXK91XOT8YqNiB8gJ5E5Fjrf9DDQKs6rIt5ayt2pIBMpxBCGqLFEyZtvFSokSJP", "qJr0JgCAYL0q12j7HBB5W6iVMy91hK2D86NLZXQiurRP/wfBm+YdhbS6vGQG59IINTDcj1TqVUHQmaE2thYl3o66pXihPfvd", "1nmwzLyWuvEC7QbBTEQpBZnAOG4OsJ9H3TgCAnaKVkqOdZZhjcEVUulrXX5NdTNF4aWK9/i+IY6h1REPa6p2aF+D1wO72QN9", "M17j29A+NwuRtVKQ9uur3EnKBNZ1jMH3HB0PnCUN7obnnSoCuV98JfZ/1cl0vWy7QV4H+8FKbfse8itQBavWhbWqgV4ilBtQ", "BaZ//ZyZMKFj8+5+GWo9AkZQcE77TavL5lZX+igLy17n3bC8ZKYoHLLWuHrdJCrfHEHelVYX1r9QqACHYp+3VWYeqO1fdjc8", "o+aNzTczDoTAY7h+mS6wjQwl2/k/7Jhm8WDQrdMc5bZwj0o3CulIdZY7hfSXilmtO2g24n4elZ3h+T1cRbjSOqsudX5gEGru", "k4teZweTG7p/tBqwroEKAUrD3D5s5V5sLO2QfcXnVarUkKWAMSnbf/U84x4yWUteOeKYA4CoeA7TT7KfS72a85plTTZ01O1m", "4R0CV6vVkiJ7y5p/iC8KFiqUQ7ULAVycew6ULjYlfThahYdp93Yc2T6uPzuPHSnQ6dUPcYZ5GLHY5W6jF1t1pZszM8PFZguH", "6sebkHPvc144i0DjsHmGE7An4ZxEtY9HFCc4i3HePzDusuLRS7DnkYbGdQpfwKpxh+IeQfIduE2luUkSeqO024jlGTw/oYFU", "8pyaLxQW7dYEqxQqfVitdsv8290pVLnqwCgWEWL7c+ieOwmqfiRQqpK7yH3GFqRXJYNxioahzJ/eZF9xG3OAtwkMdBufNlTh", "sM8Si4aaMtZuFDpX1yZ3mQ+DM59BYBuhqOJxFHTj5bN9ohoI8N/m/PgaCprLzSjsGn7d2TG0D6xOnD8AgQqu7LVedQx25UG3", "k3vl0SHnk9q7LN1JKlxxvIusZBbryZxWTONlp7MwN30TUJi+E0UU1PHCCaD6xGbBgwILbgCLzgL7znA0XvfCpP2dDueh/XEU", "uzNxGdxou1QEs/WjrGen8H20i921Udkf98X/CLXoemsR1fJ32LN13EuH7wCdauHZOgXmFmaQkC0oizQLXKqP3PcwXAjdOs9D", "w1L0Qd04rHFmh3OKOBGHHR62OmyfRUgJ+xvKVWkDM/dAxUaGKFWFwnWwBUdvf0fwnTsdJON2YiP1zE5RDb06vOsxzsnmFtDf", "IC1BFA8OG+pT/HxZopofDhgBexsnEZmH7hliLIXiS/uDPEXbR2d53gHI2vfAAlKrEm7cW8cRNe9pKG9/10vYCy+ebe5U/SNU", "jjAPmy/7Pt9xkLyWG3Uth4iLOuNJU7odxBpJa+AdbjfRQbUHmC9U7D4hoqG35jClwkyyjdq8FufoKFgxtFLD04cfN2G2lPX+", "2g+RDUPQVLsYqhT5/IVjjxsHChdeR1bt/r3f+0//effeDion4Eu68z4sgquDyo379ngGYQQfCXPZCUGa3V6DxBCA9aNjfQq6", "ce15b9MGQXFUuzDf0vH9bd7Pi66XKjfrqGg0f3Rm5gABCtBAwj7G4NESSABWB92E1+wsI7qEc8kJZgDcHmGjecAmN4JoBGXb", "cziIfR7kJKzltH0c+6hXKzYqlpzZoeIdzAux7Xg0fnE0EDJjaYE46uXBgz3EA0ovfkM8jlXde7zU1BkQmq/4vHXui24xe9Q2", "uo1ivtDzwQ7BPkZ7qi22HjrFSuHzqfACi44TVhTOr4IgDe3DRackWPTirEBDaF8re3M+/wJBP6/SiY55Fyy5WfbwHlACq7a7", "A/UGborRhs1He5AuHZqm+o8wve125tMRlkfxWrs/VxvbL2IUB5MGmqZgs8ruwEtfOohjmJ3TW/J0uNcSLi15EuXroIzZar7p", "1CGNk0fEtCy8srOg7HYf9r3ynEsrik/2vByq8A238Kp5r19ulhRLLYJnwZlYUBZoe7xAWbCr5N/3JrucjGJUHmNpBcpA8L63", "e8Y5Jxrs8uMbZxppMx8ZFO6oan7tnDGzCfqqE9s1rQvrhl612dFrNsknQGgOhr3ubUA39bqo1PDh2h/0OO5vb24dWwToe3fh", "ddlO+tP483S3S9nrdm5sblEFWfEBpHlYVKXy8dgm9/A+nN9CRy95QeXBiO8ggLJWH5vxheLHW7HkG77TZDTMjwE2LzqYonDD", "ys2bgiXmtm8z/QNqA2eDiVpEZsIwj8T7sx7V7oJ12HecRqmwnjebYFl2EPK40t/DoqF9pOJSxSXQVE3Lxveteal2HqI2qfX/", "BE5BvG/37jhf0i5mSeqmcFaPhv1k4+TUA5g35qP04fTaZm8zUtig/djpYCM+UCLjiywQ+FEa51DpLK+Xm7qhypYLZEuw3nw+", "FUiqE/2KXYhxpa19e7eOFfP+Aa9WaRxr/IVe+dAEO2sfcTbrIPYv61+4DXRo7dh5LqDW0oK7m/7+vi8seKDPucMK91sLZbY7", "hRPeeDradgqHkTmJzMyspOB2zUoMbteGGTej5sG6drtxONi88eP+Xz0yuvHO8MEbr1VggAOzG0OkN37SJ0rMzEoP4rt2NzTT", "GQlv+ogsY4LTDqsHPo4Dj/bHuijXBys1HCQP4zce4IaKHgyrEvsQzk+EbMY3fmLXp72N70/IkKpuGGzduA633NZ6MwBvqOwL", "nLvcJxA37SHsQI3EPuJRCEaPEPWmf4HIBrhoPV6Ghoxqa50nFBraWzcu0c8wz9SMKUbkm3Lzxk9g+G4zWmIbA9iHuqQr3aKj", "xoLVcuhFmIMtFKyhMgT3tedh0gJhUF/gnmxo+D1w6d64NOyaa/IQsiiDh8pIjAiASxVRG1gx/KB9Zc9OHICflDLRdmzj5HFf", "Kmvic/536UmDxvuvJHdsvT0o8Ye1kZzG9lz4g7yoykPAjwfnTCQrzC4k8gS4jgHC7CU6sV+XiEvifp7isL16lYy6pbW6RwXs", "mu+vIcqC1xmBh10T/gZDRY0KDDjuyN40KyXDW1UwcskPK4cejxkoSoO/4Vlq/sHAe+DGpW0kDBR/Gw1GN36yCgPD3n8ARMnU", "lLf2Kx1VwnUdw31CAgQNUHUqihes926cQ5Jgm/0jHjv/HuYRMzuIuw4wn0nOAXXkiqWn2BPwi83PG5fMgRkg0sN+Y3kRROGx", "yuBfiZ3XdiT2E8fD+mmwpf5nHqHG/WnvDlBMuW3XgRokrgewSr1SDz0uWNKu4boiQLYsNU3tUzfOIRDZvXEJZZTOj4F1x4wK", "OKlvnBsg9b0Kzhtbudh3ze6BvWwOAvpnBZEYMDsBds7ifTsPS40//C70I8XMh+ulyrMHNM4wuxjvBPpQ4+GZnHPmHGyTZ5g0", "YA+BRhqUUSPGu1n9p0QT0Ck3zoEdmEzZFZfv+tg+v42vWbtsmYLxONh9G3smOxseYn7mxhsl8iOAO3sCSvG2iicBlVE9v9io", "ZNLWpS1ewKX1HIAcif9ZJb+V57psHqh/SmffvfDB5Q8fBpMtfn544sOnEw+w/cTfzib8zgfP6XOJuRd8vGDTJc/whyf9c9d4", "TXAL6zpXdR8w3/Lzfj37v96/QKbhN+w6aM1V+wT/xmfJ2Pse+XivWUsedRbid8VpTFbg96w9+nkNd/rwONpsf+H+4j9+R+9/", "+B22/Qm//1WwAztr8pvOASzW3gvO83uBbX+D9yTvsH0DjMDPgtEXf/GpT4Bx2a6NluP53uY18P3L/J49l7fP2qPPkEMZ7Wc7", "0D68QgZk3OfbHz7Gfvo2RoOtAH/wm9ZuMSdf5tXe5HOqny7a7094f73D8blqz3bBGZsfIQvyBfsW2Yrtt/f4xBd8XL79wVvk", "Z/4O+YovYZzIenzJ+++at/oE2aXftc/o++/5817wn5g9x9mjV+1anBd87WnMG84jMUWTs9nae5U8sI+KD/bmGbCzfnSSvLBi", "jP0JX79ARtRHyX571k77p8Rue/PHYteFBQAuV7LFXv7oYed8bVlo8c2n7N0n7JU3wcFq74tLV5yzr/HbT4Bn9ubL9u5P7Yrn", "ybir/58jeyyu8ig5ep8AV+vNKzev33zL2szrOgPwI3wH98dVXycD8KP2qdPe/kduvkl2WXAFnwTHrjPRvgZeXbTL3nsVHL1o", "qf18i8yy4Islm67aj1Zbi8Xi+4a1/KQ/78NgsP3oBLl5T/J6F52V9ydgyLWfrztj7VPsUbDhiuP4J2CSxXfJtotvnkV/2Gdf", "Jkfxk84g/Brvfc566Br74Yr99abf45J951H1J3h8+e3Xyb37mnhv7W4/CR5esvNeEWcyx/Rh3d+5es/Y+w/fvMLrovfOs28x", "Lqe9fa/pfbITg8eYPL3k30Wfn5RVaKP1svfv6+Rsfs3H9DE8D/mbz3BkTpJ/+Dx+07h8zv/zS/7fX/b//qr/93O/9Mu/8qu/", "9uu/8Ru//mu/+iu//Euf+80dM3/n7+78e3//7/+9nX/378zs+M1/8A//0T/+J//0n/3zf/7P/uk/+cf/6B/+g3/xL//Vv/43", "//bf/ft//+/+7b/51//qX/6L/9f+E/fA779kP3/Z//9L/v9f4Xvxp//2m/7fz7FRv2JN+bXP/frnfiPiWoqyogIlMuSST1Cs", "eHMTFUATO3zqHqIsJFeC4X7HkTsWjpGDiZAycxRQpol6TygdVKONtjq7GirmRWKpFR7j5sm5W4/gNUCyw044zOZnMOa8TGoO", "GPGdwqt17LweKy3DpCUgegMPaylsUfcm8ufE2dtDTKhyEgrQ5qNCEJxgnmMu4pdGvMJggx0Nx0z0A/TCDH4nMlFbqNRHmRBA", "5GqG55CdWc08QFQvMVKY4BPVMQA6wPCLmDYzafJcds4QnY3vI6VB4q3b6wHzRpNvBfAy0m8NMW1woA+4Y9kEkqLpwpFFLLsp", "yRIzapOjzjRgFgxxVmZMELcASL85tj1GZJ0Na2lBXJ+gLlTs0W7DpKa11kbMmoH0L17BpQSdeqjqxi26pKzro27MnoWYutGG", "+cx9mzr3eTKtmF+zljWzuxZhv/NxNut1jVfZh1GzGhR95jKKMYWkrg2raUDNB/dzuxKSDe4/gilIPCJ1gMTgRPHEOkXKwTtp", "swexaeWo62aTXDX4TEWVdTPXDvSqYwzdl1uKvHUDiNIQt43QlLOj2URaW0OsEskthdmXWcGK9wUutl8WItCI8h4mHxxtu7+z", "EqPMzN1R0PyxbsY+AyjnjdfKurnbJvbk6GCA/F0pj9uBOI0tEBL8zLCaAbe/w2xZ+N4okSOKoXvQ3A8W04AzDhdubnecDwJ/", "a2NccHnGQ+zhWgbfEUAGFWnFCkaFUPZON29NqvaOBa4Qc9hCuaoyFTMBeWhYZYPB9fxC2RP5LWkDHQfg5RadBQflV907Y1lt", "oQLqUH80CzkVBpXHfa8ntXuxyTNKU1oz7rPJQuxgxcQr6KvFpFd1R0cHBRgbGhXFjIQVZOW6Ux13lllD3i9RlqM8Z/d2IpZZ", "FT1Uin7EhCDK5OEzIEhMHlLUFsbTNHfCmVqxGyw5WHI5EuX23WZMhG7Uoy6qINyu88XKZwJcIaZ/zU2yizPvvsnCqyaAUfN1", "n1gC0p8JA3Qw9mcHL42bQNmQzgXkf1XgnRoWRmA4+wKUo2B2XUSbnDWi3WWp/ArgzUzXTJwSrjdBdSfHNBLEi0IKOERJ6TXR", "Zdu+Yfs6eVPwBc7ymhkru7J4OEHJgNWGEC25nvCoABRubQxARVltWudtVQEOaohqAoxiV8SbQcnHKyshRz6pzcEqUnEs+uf0", "OzbSdtGMPSvo0XWk8ZWGbNIZ4PdC+WDd5YyyNqO6YyV4ym3jti1OUUzPUncDXtVE/nymGTfKuHsGo9jTbNVDnFy9yIXPbNag", "7TBPTVly6zFn10A8GVWzNoFEYWaN94DXA2Rrq0A77jTM2HsFcupi0+eO7aRaZK/VgBEAgQcUOTVS+mCPiaKVMY7+L3mwsCDS", "npQOHn7tlr11nLQbmwFwaoBJIbmzsOH9irmR8VBgLSyDyL4ojS48jJekEdinzNNsQEUETZPBIPL8XYxKrm4UgRbp7o686F3V", "yhCshkUkcIvIJO4j5AGbnS1A5rpx+KKCDpZMD5GK/R3NzFUwuZY6gA44YK6QPQR2g2Neanw3OuMP8E9kjQNlU2wSoGBHCeE7", "JGddW9Nki8jkDg+xk8eDx/G8zVknS2OBbYkixYF1+9GNQeAUPTDUqE6lhpOuVCVzkUJBYgJsY0/riu23BiTAA7LzTtAy61R2", "QIIgc2EtxDoj5WLCPOETDD9FFq4LUmAaHLtji6z6GCMA4Xs+NxziBozCskinImleOLds1b3Pw8FFnFZLawA3wLI65AjAohj0", "V3rjodl1Y2aX+YD1lrhAGnKRFfda/7GKplwZyMxwdl+vLwRsvUIXwLwQpbTtWn2QHxDl190mG2WzdcyB/6u+MXbNKN3fMXum", "4wg7SlSI1LYIcKSrXAyGgRZrPN1XdQ8DvYcnLLtdJqRmY44UHqKvWNpCLiQ3SsEdbc+B7f1wbO/gLrJuoWjWiOxuwerWdWjX", "sPkSwup4PPAesFBF2xe4tTyd6jVx1loAnhFYskdZqUEeQijIOmy1o2SkBg/HsUUnctyoQH4PBibCRcfDyL5VkeDr2jFR9sXb", "4FsTcnc1cKBUIUB7VIlsK+IOh/VMfO+lsAIIj8wwE4GlmeiEpBHzJGxWo8IuVOc7inc+ttOlNaLxQJWB1Q1CKNCPNySWIkF+", "jcJ71AfZEVQEaoaoHBCe8MSCQQ6LrxSwVF1YjPvOAWjr9EESbXQKp6+LZFclehZySm9WZJ4K3NJkBTsnUh1l4dznHB3MSuwA", "/dHy0sJ9g+FRO2RhMhNdxGGyLc5xtfBOhrOBpIA9D2T2xDmAQc40kpVM6BbRDX7czLtaAjZ8eTdDm1jbHDggKDTK5jKwllG1", "lKCrF2EnKphXBNMppaxgi5enln3mQHsEECkEeT6HAh6ohzh3bZKxzg11mWKl2K5QcI4OrpysoR6R68UzWzjBRBoL2oset7gu", "lDiGg6Nkh+LujrIsUUzYfAv8bbM56IEypWqIwbc9jLYoLXHQa7LCkuDzDbOWWS5HvoXKNzRSo29hFybbKPAILCBi1ZYgvKog", "AwMIk/oYZe4tuE4/zEvhNe1id8a5TAI1THzK+zWaopt0Iu4XuLzskSQd4489cxUWmjmqIB0ewqQRPkLUVoDL/NYfHSQHZGfZ", "URiHHVxWOMuCbZUVzmv71nxxiBxKyLWp01TwMEIKVlDCeWGgBIoiKLFxUuzeZHc4qLLZaPyPnBjHxn+3YDZrbmQjV4hOWK9G", "B1lNSq8f47W0oMTiMkugNr3YuRYlpyzqRkwDNB2BBaapxv2+PyLLIdJ7giXV1dGv1W68mf2nJxUfg50ReFqyffyhbXoPjW0v", "nRWBQ29CmwzutNJ38OuExwR7z7ZtawUY9bY1bb5WP1hvYbbKuiC4RJRqE1kdR1EoYs3HSR95aAeQwT4UV3M5YgKNpwzZkYYo", "6eyJ3ser3WnXkZq3q5or2GOV8wUuR0r0EO0xPMIR0Z6y2JWblBcobTYs5sKBcRd2HTtsSUzB05w2NvYphOzZMPSKKHIxazGm", "R8LsUXkDcorYhDF7+rbvrwMx5Al12xy2UAMGTCTZ3EkJ3FPlp5jBQfQf5zpa3AV5n6Yi9o3SSyydVQX07kqCF+L1BJ2GfZqb", "flk4B3gP+1hDuiSGZgZrX/ZJWzj1ka1l+ne1dJw2cXCYmdvjOid8paFZ4moo5MMgpz2FA2wufSOwmCqlJkvfuu7lkk5I3DIh", "af7g5roANeSaA2UX7G9wT1bSn+HXI0mOk3xUbm5BYIN7Lwbli0PS8q6X9JJQ2Cz1DRCSdIsSVYMYsUGfFLgYOHzra/DRvAKc", "tqjwyEc2aJ8PQykKCCQUJgMq7xDaRjxs9q2DYfvFc3WdtLrCWqxI2b8UyEZHtu2ccTduFQg5HSUBSlguWahvvxdFSDw4zhQ4", "kDXaSLsDwu6Ui6CSmogFhdw7A+s6mqY4NMU5jJ1R1eZgARiy1LH5angK7gHZPr/OCrRRRR4ALFFUKOqQxKaOiztX+lwAQDrL", "fi9CxxXWq0T6aEuYghbcE4A2ECcjvEqzcpEHhg17cAMUYDVYO1Q5YDOVCD9wtDU1FjOS9nr2mYApKIZGAgkP05FApjQDg3Em", "RiFIMbENBxy86XZBsDA+CDUDrGkUh4TggFm5oDcDyL0M6MyS2RE9cDyohZvg0UMA1zaZmRmnLnYuvdFAZTkIXnndRLMcFURh", "CTu0W1JR4y2OBVJ/GCYq2sLuLh2412PJr287YMI66hpbNHedpeqgjezKSoUu8H0jqkSao4iKmF3Yj0hFlNLuI5feCuIboka3", "bziBfbEXBhWCgstuafUm4rDFnMTOj2M7ANxFVLSxyphNjbhLIa4qcNlUtq+gV5sIDdmeNTywLoC0wj5ikN/aMEstaklszq4D", "ZRRFGHNrZrsxxESDAdZH4JSWQELFbRBrhxp2IiyAxUiD4cEKxQBmRCOiCLsFG35Ee+bEc2QPeJgSXzoHETQ3m4SVXLCA4xAP", "8LRZMhqB5ZEzOKEMWgsiALhN+ETdI2GvglSPW2UMyn6xWQBSjKMfRo5TpoJtpSHUP1Ua2C08ShQx6kkC5a5yywSJoYeIrKO6", "fda3Y+DInlVEqV8M9xdYY4/rlEWrQqY4m3vHg6FopICOAbmhTfAi0g1gMyFEa0Z23ai7LHujIPU1UbIzZlusunUB5lPUlUcQ", "bASSO8gsyBjAwRZndoCklpacuWFZ9dnWhsDp9ANovRynzR4SXHB79xq9OQa+UcHMQ5xejRnkpMuVehd2LS+onGM8WjSNgk4X", "EYPd57TXvclBHp92UuCCot9FdTv6CNOPRy3eovktiKAY2MWMAR6eJg03wu3h0UOzRG6Ik01vVPfaUhlvkiwYVFe2ymcjLrYJ", "4YJmMCq3ogyzLHzE7kByAFcUfTRPT5ekkGCLNRGsyt/EccRidBlUdjNsT52C5obZJLDy0BuOZ61TRVHj5A+rg4h5FlEcVJIb", "QaVGYAKySVmyGp66EQ65dE7TesTFCmxcEeD7WBeF2Ghshgge77hGmruMhWPf5QRAC3dGgH2/E2XOdyvZ1VWgzgsFE7BL2HWo", "hbO04BUn3qma4SAmqViDhzbY0tf3KRRx95F77yEtBHzXyT7n7j64geCg75A8TMhEhgxeuAPF7kCv+kFvrm/U76HkhqU1ZZxN", "xMahuHotkhQ9lG1Vf/3S2I6x0Xi7/utLf/W0/QnB7L96xn/522uP/u3V7//t1R9/+v1XPn3h7Gdn/lKAvU/OfV+IPfvl/3nu", "hf/r8rn/+/k3P756/eO3j3987YnPzr/08/Pfh1b92e99dv4Cvnj6O5/99PlPnjn+6QvPfPLUS5/82emPr//JZw9/7+fv/vGn", "T7z/yQsXPr7+2sfvv/Hxte/+4pHTnzx+/edPPvHzU+99+p0/+eylpz999QV78bPvvvvpj9757P0///jq8U/PvfLp917/+O0f", "fHL+L35x5unPXn/45z96+JPXvvfJH//g43d++OlzFz595vwn1//00ytPfPbmtc+On/zkqb/85OTZT86f+uz86c/OX//k6euf", "vvXGJy9c+uTqiU//5Nyn33vP2vPJ09//+PpZe+WTU699cu7Vn3/vxc+uPPXpX7xi//7cHue7j+Hi77/06cOvW5sDTtjY3Ltx", "znyGAUw3TORypQRsGxmSMUFw1dAxYN0EEjT7qieYE2wt5G1thrtTY0t6TITXyo3ryOmy+lxoISq1kyVA3g2CsUIPOvy07g7C", "eBtuh5OVkIQAXgHUR5oUgqH6MGZZm65zuYUzJlxkU3uAa6DKaELvVseE36nW+ca5st688RLsi0DJlsOAVw2ZcwHSEuX2vKmZ", "cTd+soYqfUhkOSZLIDIV0+oWxMlhpr7Ug1a915/bpusAqsYjZnVp2z9SFWXjNduDxkFZoVprPW+NufHS6kh1JQRGeh/WjiSz", "V9DL7FUsHDY1nsJR3oSrEcZX9rzuhcwL9gK4EMhaCS+9BItTH3qG/Yes+dVDEUA2L7/H2VIGjK9xswxTYAhkZR9IvJeYyQAk", "lxgxtJmTZKv0bwVasAmYZPT8oAlR7ROUxH7fJbchOn6CwtgSBb/Kf1/hu5f51gV+7PFQIpdI+cN/e+rP/S18/iz/fZWK3dfi", "OlIlv8YPPxvXOc5m6Kavshmn4+unujWYKgarjUuAo0kX/vaVE9QvP83PnOfvp/j7T/n1CxRHv8oXT0WTLoZsue7+WNziQqiG", "X4m3rCXP85WLvJ2a9FzcSyLlZ6mnftybil9+yKd4mndUj10MhfLnKXD+ZOiUv8r/nZLOOq+gTrgSeucn+d3v86bn4i7fD7l3", "9eSFTK9dA/dkiMRz4LyfraMedplzvPWi9zYe8NsUYn8uOuFk3Ov7Idx+ir2R1NZfjI46wQ+rPd+Nm56PHlPL34tBtz+fCpX6", "H8a9vhtdpAtKEv59vqjevsi+0nw4GwOtx9FcfS969Tg74Sybd5qt1dcfj4Y9htddV17zWXNVo/MkW3suZOwvxFO84FPF+/m8", "PxfePcN/X4gHfCXudZztvxaq9mrkj+JPffhhPrJW0Cm+mGbLqWjeq2yzfj/jDUabn+YjXIn2vBpT6/W4qZr6OgeXN/I2H3f+", "Dgh8QT6GxS6RXd85czBwLMUD5XapksUEYKEym9gslrYCm8PEGiXXYANJu2GpjHfFKIktzHVpvrBnL658WFcOEFADtoju6nC8", "uQJr0jZks66B9HkIu1NPjiquchCSLlDILJ1voyYS2kM/9ymkVfMI6MtW9mi2/dZP7yo+WmZPvrQZdRadIiWxQzFR3ygFKnGV", "CTMTxyCaL2776oHdw1Qtn1BIDYIOimSzLXSUv1aSg3g0aINv80UyEmtWEOAbCCqsDJHRUH6XPJrytuvEvLu/8/nA3JPnzQ05", "NxXwvNXRRrLIzhmCvkLitha2RupU9daRNIL3Q8y6dATYVsmI9bgXYzlPx/jLa7MduMo9Ykk8fc1+9iRsIwU++IVfSVnFrydM", "GNP/5jINuv2Bl8QuMYLNq6A4Ti4pSaG26M2CdtPusr+zlAU46VxQerJu5ml6e0rMrnJw0Hefju4V/N8RBm03LfyUGIemxVjl", "nJEy0RPZOWNNBWOGqq5n4xyeI29m6atnGAriAI7g7dvTCnCFSaRw+hyAuqlmKdQC+uqUgeoEy0qncBSDnd/JpF9IaJWZ0B5n", "y8zOA7Z969iiu5pb5jKiwmNjEond1ci7i84OYBrWyHtCsLuVoB8gChPTa4QTK8YJVmBsTDYmWwOKxDbzykbP7lokSxdD2ESN", "uHowODrxvHexh9ingUHrkNByy1lgnB8D9QZj1eZFdBd9imzJSLlQkSl2603PJ9o8OCggVdQwIt0DJ44m0urqeEvDOoDDtsZy", "LtRIUtp+OHCUmdeD12JIQJEDuEVil1p3YE692kmVTFSRo6xVyrEvdKsY/dU017bGYEbBVaoeuR9URezjQTVbAQa2wo/nRsI5", "yapUtiC5it2NvbHywCguVInDD1bF1slp0CBuu8Jc8BfTPjkzcwe91GKU8oTwOGr5f0jHsD5p5LGcEep2N30NMhLB51hKGQGF", "lRAzug8CPlREW6kmA415cCVVXa8KtL8cSSTGEl8LYgSo+p2EDtg5E7woi4VjdFjTSdliVJ2S2xVE+gn8FHEtcC0xg8+WOhZt", "50yRIB+BxygKRdD4bCvOu0tWOoWLSPrJ/gvOgqp/P6vnxyhrQsaUiXpgJcyPQT3oZrBHERfCDGjZY2AHlZzHigbFuMXnGQ5h", "PMNZG8B+2S8cVuSoxIcwEwF4RGAC1ccUtmwiygZGB2Td8HiMeRJQuvGFmBu2WzhOdTYFtckqinmEE4zy8eAh6jh3etfTzMMJ", "kW5bwgjFTr3Wrt9jiZtDcIi1cS9wVMMG9WhgGhtvEl7C3Crap/hEf2CHoh2yo0Xn/0BgV4xfNQvjhBtyFXBMj3E/ohMB6Fud", "pNAcSMSRTMEg2f5MNeUh1q8ME5/jZOforSooTW5GrvOezU5PZGMsSXe/J2GLA/Bke06vN1b2cA2MxwzvcvZx679fu5l9eW/6", "7laDeDROTiKzmENRuSieyGY2XkDmeUAtANvAQONacc0kwHETeYbeZDmBCAdkSwazMYJvQ/ZuvUnMLMS91woJEcyVEo+we9yT", "LIWv9gOHiTioko0zCfpcK/ho7x4cRGKUYABKPdwv4VNi7kgLhCxnoBGKwxGFnxPLA+thBcuxq+xMN4HdIwDnSFSs1j7ML6BT", "bB9S9t6BZLqy+HfBx/M/pWx4QJdXQTnp7q6CvrBpYnUvLSS75LbajKk9i0VdLAUcd5XIJoFfEvi3UTQY6y3YjnqT0UA8vURl", "owZshHDzbif//dZM7Fhefw5bRRXVD5FDqNJ+ABA7H23Z1wzxHAMPSd5blX1W3c7FWqiEQWANOgLOEs4QJgOhxCPJigSUUTjX", "lbJ5sCKXGwGPpPX2WCjjkoXHYJdSKlOQA8w1asTRvkKgYaMSw5GnvBtFb7G5Ouue7RFKbDUkBaUEMNhhUy4pnfHNl7Tz88R2", "/FpYHmQ3wkZDzA96kSQ0O9o5iYAS+3Q5OSAJ898wbMskSWR4quaOtIclMH2jPOWYujEqH0WfFJ5dIBUjqaYTlngHAwpEwbh5", "ir2zCp3SFsnkXN8cHVYpYnknWLfS+MjkJLRz4WgY6+h7xsfMdrPOWQ+mkRJRnEITS5klZNw6MoY7uxYdSHG0FBqNSu4soTDz", "a39HsIk7ETV2hh6bX75z9iYOQYPXMdjyU3ec9oNUWdH/cna6xB474zBVJIRpJ5Lrl8hem+QwabSOHDJvG7nkqtH5B9IMWwPo", "gnvnTEqOOiKEIX/UgxKU+Luxi+qka4gq6rmHJpgT/TemtLGPz8Z8mU2o4EZCENgVUh6mWSInLUxoHUHIk5A9hVhueTakcmQW", "BO9LqYmnn98CpxWBZbRuth107vp/2L1Jf4z7eknKQ7D11pxkgOTLtBSxs9rVbXfn/EPgstoKkFBBNhmSwQKyrisnnOsXgnli", "sNYcdcDVvHtP1v19Jg1gbxwdIpvbL1YmCUzTJFjoXuw73WF5tOyt9QblaB/IfGtI2hD3kvDnLay/kZI2TqQ7knW9Ag0xWqpb", "yUeELSCQAe2rPgvKnUUSMEsviCgEGsMqww4nUB880hI5lNJ51XqYa16Y0pCN0qY9QcM67bv3J1+8V8fMOSzPAexdesHMDuzy", "NJiahE2kfp9EGO5BFbMiBEjGCyogIUamy4mQF0RDeK3ugbRqU4Z38x6BOQfDSYK7fiEVrUB92O0ceJoVR1B9D1m+sMtxN3Bs", "oCcJS1wxVxGImp6Uhg4n+96Z/KxjQG3mp66zY3SQ8C2UJwABsyelhWaqBKElfGjOddI4Ex3cMbNFtUqgOWTDIfOc8uE214JD", "LhmWRVtcVRYIpg9ZpOFw8A7gQhDA0gro0/K1HdgZOVL2shDSHriQVMBQSCmVx4FYLcyCJ7qpLNaqo+DPF8ZJ8wf9JxQy0CwJ", "GbF8AKr0lGYr0pTQHkFCeOfErMhwXJOvI0UhZhTzR55e6H/c404qJhfV+noCfoPZAOlY20HuTzGZg8kKCghxZzldeedCCymQ", "EpPNiN0PNE33wdt27Vp01RX6Bi27LdYnfHZ/BfcIYEqTMMhFSYg++HQSttIsc8TvMKfuT7EgO09cpPP+FCsQkyBjChUlvK0F", "LrFAsMpR6iRuVAlYnPDsBGOD9GfPnj0gRRsU66iySh6kYwZgj5NsxWe7AFbdxp5gNwCJa4P+g9WEe8hi6K7uu7sK+1SFIpQA", "jmKUQpqw9IOGqy5qHpbWdpVAHUXCbBXOTwnLSEyPiJ9IFRQeKTOr2CSA7hNoKRh2duxg3yMqEvaVTVTnvwP6mDYQ8joQmBAN", "XndcudKdJJsxqrDIxOVnthQonhwmJjkul5ez145EkdIc0lmyn7/ibJ1lX4gBFH/cmayCB20o5eeldRmVf4yMVfrGEJ7rOvD8", "TVuRCV+oNr91SGbKrRoFNOJApWJYv+uovhJt7tJyC+ywrwBcfDX5EKjdQRzJrE336GGNbJGLUj4sPZ8yrP/tSsLO5KRxjt3e", "RJ4SQj2ek7P2sSdX0QL6phwjWpFmd1YjWz1jrTMeizqYk/s5m8qpDmZ+aOEoB84wblUQaRjRbbPRcsqmgF1gCvry/f0Ee51x", "XWIbVZyNiiwGN1BRdoooM7inrqwvwNgzk5B3AowTjaBhJhSjC/FcASErPSV3ecmJDdfHlWNJbAnQgg+gyG2Nc+7S0xxuyv9V", "JcV4C4xMQOCuqwz3AaHUEgqdPNjyU+YTiux2ISI4+tYrFBZPVZUUJGVdZtW0529UpM2vSsQZ0M1+IV0wGfS7j/qclD1wmCB+", "PLnbQzVMEZ+d+6gbCgGHgauhYL3eVx0t/lfA4sowS5o6VX1207k6jrrRwObY1gEgIg/YMiLg2xXRfyDxVh0uWd8OCgBljx9V", "rbBFyu7kMOEnji2mjFKsjyZwJIQbqqQDJotOq2Qp0O4cwUdEZYNwXHNFsDGp1gLnfoLKYh9x0knn8Mb4AhvC430hRSHWq4i3", "M0EjH6zqydKpUgFwgQoy7XCgc0xkZWYD7zeDjMBVDhcU42pK2oH7RSBx2AcAHYBvkWsVKx5I4aSVJ39Ge854CH8+GEMHrt4i", "RKV2i6NRbVKkouq5yNRwpx5rPyC8jthv3EOyX6lCu0kgteIO7btAGAtUuHfPHkKneXOXMAtMDBmKXTEbG/Kg8FunqgZCb+6C", "zbXhmGFoFTqTemcZqlsyYSKKU/bcj+qON11IDou+iJ0NcHet/iLBm1ON7TwSErtZ90JrrlfaoeX4InvsbiqR70lKryhHYofG", "ZUrKVxGEhU14ILEBFTsKHy8Usx+CxUDgTJ5MCZmaPPDtStg52JgNdlvSwWuUIbLpUsgFbCqopmAOgItTKjzwZ4a1WIcHW46C", "FBJZa58TtewLSI1zhrkYBgCTdSPhRErYKS5FVuIJ8bFMDMGgwDqg+DhlSlUwhXdXhgFd9zgrXAzWf3AXXfU4HIV7Gl3F56QY", "XwU2w2yHug3Y8DHTuuAOkNCz1vmqcLN7ir3VJv6/eHuKySykAAdOEjhLdCA9I7GQWAUgNiO7cJRiBbZzjmxrGa5vJBt9Z/DG", "zq6JXxOCjq43ywgfbZWdM4V5CaWiTStC4sMIAUe6lwRJ3YAxRmIkC4d5YYwOxt4+1xacoAQbrSPzN02dcZMoCArHrdovy+lU", "S/XpSx40g/Qd4iiErs1L+q+zsACmc8+RkugOMMdge7ezFj7YaulVj0LQd4sAGvZT9kH8tmA+/Jsf/80f/83pv/mzvznz0cNk", "ebv0fz4NAqUh3Er4+5UUNrnTEJ7TwFNzRBNZzWy68uzhu+OV2j8n26t2NjQiaVpkUJN21kraF3gtobpQxUn3F3PfgVnINzpL", "GaNbvEdAeOsBVVd4t6g1qwfkO1BbBisOvkpl11UCbzWMQOILjfLx2KHDfkmaHWTTUsaYWXOzDXAeiXlfT6lYUA0tr549j726", "Ap5CuN6l0F+CW0l7w9oceLQmeOhQ9uOgpcYr/6qHyiBVqKJfAL+y5t+4BNGFRC4BvRdrptk6DykWWTPt7rAxzzZTPCVtvGtI", "V4iBDTUS4lgLWoWKIql0WchXdIVMRG+IXerDE/4afrsIDqYP3vnwWbIoXeerj5MTCbxTb9jPt+39yx+8Rz6mxEtFVqTr/Ake", "q/fJM/V2YpO61PJRicmJd3kruJM+PJHeBQfWVXIrXSVr0xVyYLGl+NwHLzp31XX7zJvOlOQMUeK2+vBZewd8WI/oKROP1DVn", "nMJvaN9x9sE7/FecXuKeupYYsk4mDqgL3hvgy3pHjF/4BFuIb3mbrS3B8oS7PWI9B4ap9/1537Qnv8DvXo3fnN9JfFn4Hlip", "2vui9e+x19VmMYqRQYx3fpx98Tb/5nfttUfwCpmoNCJvk/tLHFJvpue47KMWo/U4+a9ejHHzz13NrnwtnpqcW3wXbF7ip7L7", "vUSOquvOOAYurHc++GG6x3WO6CVv73voU2e0wni866MfrGRXxT+GsbQ+xbixD1L/vcf7XiZ/2A/Jn4U+ORX3BZ8Z2uIjJU6y", "92PmWAvBEvasXU1j+eyHjzl72An75gle400yrF0gs9jJdL0LH/xF6g22hU8SM+KCPTl4zZ7mGF3AtXyUj/Np43OaZ9f5u7N6", "2Zi/o1krdjP2+1X99uF3fG68w3l0iXMXHGRsH9nKnkmsZRjbd/E0ad6/w3Zr7n7X2nTSrnoRLFo3z9x8/aMnb76Ck8JZwfRT", "HGLXwAoldinxfpGF6+TNs2TWeuqjJ8C0ZZ8TH1awjMV3r9irr5Cv6mG99tGJm5f8G9ecj+scmMvIIPUoT6wz+M3+PWGtAlvX", "6+QPwzfeJPcUmLXIZmXvvmX3f8p+c5Ywu7I9B65i93kLrFrkKCOX2c3r1oIz+JZ94zRfA6+VnhWcYedTbzzl7XvDP3fi5mX7", "rz0D23EycaqR/4yf/2nwscWz8Wm838guJtayR8RrhiuBSY3Phh56nc/zE3J+vYG2qE/BiGavgSHM+8Ce9wS5tx6z755ka8TQ", "hc9dZk+etB56A0/EfiALnL3PpxGTGBnbToPbLI0CPneJXGInwWQG1jH2Pe74pPjMwI7mn8PdzqonfKStpX43tsaZzbzvnZPu", "tTTGL2NmgDUuWM78Kuc5lpx/N1/15z2hUSSj2uvW9pP2/K/dfAs9jJlorXmU4/aWva4Zpj7XTD5LprM3Me7qe/vU686U9xZm", "THP75Ei5DlakWUmNMEO4twUtzK/Xa/6qzmUC30LlWli4njvdnTYLlirGYPyL5MtMN+GneLGqv10PB0SneI6NsBiEZLcAyKqI", "K9rsls3GYqoqR1mEpxqXFpQGpyeJmJmnuz35H6i1asQgMyP7GxTJbrPR+xJNV2d5TwvwqURCAM/BAT4C4qB21aO7IudxORz3", "uw94RJOwpoCGkEd4y73IauR6ybPjYW/W4RebeAqmQxphenaDaplOCFMyKFajyW/X3dVGsto8ezP/pfu/+E1ybH0zWUmjSsm7", "JZBpt5mexaU2W7JhlpJ1F9yumZm7o2xSejGCSiLctA9J5cXVQUIySn+5UObdXFSY9fs7ItVg0xGW+d+qElZ5Iiqpulsbg5GT", "HAWDDMIOvdFiM94CtFGJH+ByJvexOopmffAyWfdtlsdUv7e/01gjHtIn7miHO7FM9cDe76QyxdJCSDYtjzYY4Vuph91hldiu", "hF/jPMNIRZ7RI1h11QAw0njGL8Vam5kdydNpkSLdqHijUpSYyBAadp66Onh6ASfo/i/tlGtj4IsM9rIqGQXPIV/CPlOcNLz+", "NVxRYUPzvw+srTMfMVJo2J25e21yQRl5MJxtzKmDB09UTF8e20olmSwnxCChQknBamnX2o2XWmgRIysqeawpGcoQWt3fpqNp", "Dd41v64pPruLZjg9rd4dFRTJGFfotN5hrSAzO/VYGflWqSv5qwh8aJG1wQWFI+jkhiIIy3cDltOspFhlAWV5X2R3tGsoeKts", "Zc23ACABTYXQTDjAxlOQTHk7Kowd1Z8UigN1U5ypkPCSYo8DwgOQcrmXMhEF8kZLLcC13XfsOpTJxiWiQoYbSBFkbijn6AuN", "yEiSAlXhzEExzuNqqMRDUl6+dOIb7E2oLWgTrT+a7G6TfSBf94GVTCtnB3rfNpYeamMHgBP0MRMJpqwZGxAakSCnr9hkqRHX", "sG27SDgnh4RhekpLwhP4hBD4GHcrFW8SktIMV/d3FpZaeKOnOIKkxWeqe6rIrC8tpARfyCdif6jJRqW6ZRYHkg4OB9Wq5w48", "X1AVEqlmMHBeB9p9qAVeH9bSv6sOtPtOUrAETJmxb1Y/KqrHQFuqmy1mWwg2+teT7k6ys3fPnt9GDMU5L5ZayAPLPDHK+zu7", "5hORUFrzg/6X+5GhKkKwD7kJZyVCAHoo/I7KDbPEgiJn5HrqlcNbwBTNofYYD1g65688dspyFtzZifJJGe9249rbRv8LSeXw", "CrsWbZFqsidCEGgcgvkN0u59B5AiYgSkc1/bZ0KFd5ZbnD6Dry7fhC84vuG3UrxlcevYYuFnZ8jgIdLouRTGczedH6Lb5gUK", "B9Apm98MPGS9tPE/x7B0SVexqj5zGoGVSVt90NaDYgsqIvl/VASDisdtAZKGCFu5+t/GtR+siocxuEvForFQi8Kf2K/foLQG", "sGT74gAogEZCJBqImKqt1ehyUwCiB6iWLrY18t4kIH7UnHECJeT6fOLE600OZZv5qAjORy+cmzB2yop8QA1dloxPD6xjSRC6", "xOwc0a1QDKGjw8idYb3ZXzhBMFie3OW2qVgjQuPOaFOScoe2T4h5IBaaUJEFhF4UnG5CLVQMGd4l0oQDNR/ZOFL2rBLgmXyd", "ZYp7RoLeDCKb0mD0G0AdSmqjAgitubYQo9gabtbhCl2hzZ+qFdbUwOs0A96UTVfKACXHodIJxhyicllCH5o/hOxQLJ39IAZS", "dPWhw18OnSSS3wyGAMm16axC7CJkE3HBLpKU2keDQI0Vy5yW+xLV4SwmHLvEbGVHjcdOIAqhhQeaENqwi0VBNNnCKmGW2rgw", "qB3dGGmPuhmPTWNy7ZwJEZolhwUf0bm5VWvfAWzLE3Mhmwn6mEAoUCzOGTxoEPUFPxRZoXKgRHMJdDUomnLCQbizNcrKIgGR", "giMVR12ChzbOxUFen2SyNqEaZ1e4W0JfWE2RjWdqTJSgdW8iRhTBXYNupzcJXTCkSeEPlMRVrvn+jvnr8D372oZKHQQ2C0hY", "E8qttt5CvMcGlstfRlmzgaWjEvdSVKUgAWKSjC+HphiWNEGKzEp1WpgxMQXYQJt9pNDT12yui/pvo2rR24XT4yL/MOCJz3wv", "OQ6i6VR8FRuuQKvI7jqlmjVvQ9YkODbsKD/kgnSdsO+sVf2U423BkpwwXmwxM5PZk4kytT17llS7cOc2IWuS6rK7dgok0Cs7", "vr4OmcdaT0FZNofzSfQJi4aZ15rvHGxPp6iNsadQoorT895xMiJxSCFVYX+2h+UXsKP7B9x6xV+b9bEg8lipRkcrkWeE0Bum", "RiKa7iWXdhtGTIBAI0FAtK2fWdvVwh1H7ij+C1gBnKyVkB4um/7qRKg7cgXa1xwihvXbbe31NqFfhBNkDZ1PbAMFiSdkShxo", "jSfsUa7/ExArniJkpQaWjPum+CnmWtcnSl2snfdPRQS8OK8JNtDayTJ043JlBWeD0tLrERFoUo6oaL3xItRQw04VPpP5eZmL", "Afbm8RVn8N4Q8bav3d1uushWueyqNnpOFMgEk7do6JYCNzEOgKBqLcY8Azo3WpDk5YCZRKjbStXW59ldv3jvEWnAHWitbRjQ", "bq3cmUIGc/QAaVAm3V/cC9NwhRlhzRIUjm2QrGWDtlhUY7nzWgm1eC/NWwEiATvxjkqomb6I/WgOt8hKwg09Q2+rkVgLO4IO", "tfZkoAlJwwN9xC52OWxhnvBLfvd2VsvXFG1dKfc+na6aUcypJsob2vckuqjy+iMyyhTy0fhADiHaUBachG5I7daU1dpIaIqV", "SRrjKDjDCjfHfrQbRKhJQs6MC7d0sQiUvq5REzhorXiccwAJlF2FQ+yWYiMmeQBqToQuwJRrDc65pYV0slbyz+lWpx3mdw+1", "/kVbIdrQB9jNPN18kSIjIdFFKtdktamUicdXaGqDQQqAZBlwWaWj7T9Rh8NbaOm5FCbGOxGjo5TYSfasEV4PB/ldMNwJSx8k", "zzKmbfUSB0DRtiidhGETqCdFOIqSGEP739ZWnZj5e9BUDQXnFda8smUkFOLMOKp6AnbAZmXmp1SLj0RNiDkECTrfHGldowDR", "kaHHK1KREk6zpK3vbKL4CDnvMnmLdiJiYpHIRxrKkExtIaG/n7BxdT/x7lddx0HCUdFPzp1U9UcYG7kt7Lr3ModMGyXohDMs", "GIz0xjkYbdK25YzBOshyuFR0GuV1D8HmknY29nXnxSSesVs40oigNa0T0Nw1gobIOeG43U+GCupukzvK6zJHye7jksYyACK7", "oIkG3kEW6bF1ZIEU8WYQpZrNdShVBM21EMRmRDojOm42U8MISXG5speCmmUv5YjNjSJ3kk1nTiOUoj+oOUmHzUYyqU0UZXFs", "s9dv9g3W95vdksrcUy38sdHBVGvoJOLsNqAUQdMIwCfLqQhKblHcMyHCgT3VmuM+CruTFLRloDrIf7tZ+TaoqBpPnLZID8Rc", "sGCw0zOGp/6l2dzw4MKB4zCkNlSx2Jbyz8lRJ4bH2vBgVW1pjKPSucEGWFADvdFMhiZI56A78TZeoZNpo8mAK0GYi47BxZIS", "8oxRMQ+nQS7TGgTyQEyNUJSlKcGJyBpr7wey+gM+Qo7bUCH/bx3qHKjIblAWQmsQaCR2rmIB6C1BHnqTO9ucxM62/MWH0KbD", "3HJrcO5paypwW6dBdOg+xigqGdzRdfqc0B+fAjoCQQsmeQcQeilHs69vJ8YiKQKX6IAWoDEnratAorL7sLYG8AQws8xDE4yL", "BgUPd8HGvGQcEyZEE9AlhGoOqDif6tKKQxHfH7HG1AtUE3ctqgy0VdjOrWdjLL1e09mKYLttCmuqKCpt4o8UsNo5s0Nu984Z", "9K+fZGsC1edqudheuS5o8HmNDtf8oEi2t0IR7LOj8n5xSAwTEJI+jRITQ2rjem6mCK5AcjM28oPIYkiWwLYio1htz6ygzcNC", "Cfd5VxanKUjQOOg7Csu93yVqK6iCo2XQ2BfQUPAQBPObncFQOqxXhvV4kxXyOupqZ0i1JQ1WUd9T2wJYxh+Am4M+97AK9CkN", "SD1rSGJjEwMRoG+vcOIVcQnGjLrlPaW+yXryh8xZpqoyJq1iWHZtH/Xd3XKSWP1ROKkDEui7sXTgweXRpszkk2kdN94YIMKB", "IRdcO3Hju1YE2d25BUn9Q14Axo/AW8faD/r3YgV8GScRYGSqwAxdV+s+8EQhb2J+gSYtFY7Ds9QJGSeZTl7GB8oi8Wajf70N", "iWe0HnlxAfnPyZtHUwhT3adBoB8ZxiL1Rrt42bKkuKPDx1GLAei2z97fes3S7PDVkrDuR8EWus7q+JWJusZh+w4/dWYuRxFv", "oRDJHj7q/V29Y6TiG96KZOC9Nqo2z6WnwkGnnIYxEr5YoWIV+KaE+XH9fHX+cHAkTKExQQ7ci0zbWksIgO/4OZ5kOAC3LzZA", "YEpEKVXbu+Te9KgMM406BAdrwrS6oeWxldFgr3XBnbapAq0pFxXGaWI/Q1bZa0AL7WCad2RPVXrHLw+fLxSESRJbBem7G4Xc", "jbrdu8QyVsVuv1FvcV16LNMDgsqkht0r3DEpDJX6tt/shKR+NmcJu5RbVJEwuxvaaVV8GBsTRrMXEaDERYNJ626CnV3oVPiv", "ELNIhXGlR384Qg4HVexVEeS6H1zVo+5y3y2nWtTTJC8GjWJi8aEHyOxLyjStjPoQJfeOCgQ1NokNGVRMgyk9zIi3rDds0KDl", "bWeJh8jusV3QX01llDiEGyxLkNLe2YZOQokci6EN9bQMM3OufTD0heMWFgk0lSpKsXjls3jk1H3gMB/UlgULz4WLk8zObdA3", "LRA8ZvXCGs5gFG248DXGonXwwP3T936QrSIXrcXHt5xBZA/1Eg5EDX1yLccJu2OH112pfKuIWjIPhJHM1bwd8fHZ3R6I3Six", "ZfYnLZfDXAixjKE7sxURARQ3uWYIGGZ9CNysa6aqIEBs86CHFFGvjxB8r17WoiqgNU5jhPprXcnjfg0GliOyWTzdRgRSGBcn", "juhUyRzcxA6ONeHjBjs8ppyOWo68bB3OXY9XYbIqbCIqYAEwpEexSgN6KJkwVaQtt24SrX/92jJWzYWyTYFJW4b00ah1Mpng", "SMWmYZ+yxqU6iO0/hWxtWKrkQx5uLf6W32nOqzSEiw6up8ZJ2Onlk4Cf+5kK8PkOTXcvXlHxGSZoVH2gz1wEysyDBBPB6e/a", "GGBwwPzmiuUiO8b4Vnr4mkaO2yVYTm6tiJ6G642V06IpcCMfpNVtny6wUIM0kRP3UHGuiTuXWS/hIBLlrafV4Yf7EzvRPSxi", "8Uy4aRlkZvNcsWRA6LsciptfkYugQSLjVEsSrMBwdPveffwAocm9RD2LSi7Fz2yWwzD2EfKngOmzeWsqOe1yX1NzjrQRLakz", "0Hg63Pr+wXHzheKbjEcVDMCECcRkyFYEKEQzw20w6kLoGqWCi1AFkn0GyZGeYsVwX0hCoeqfPinwuWDMgCQnuz9Jf1BEYs4Z", "WRolOBREtVOEuyWU7SuWPWyidn/BzTo47e4wwYFVOKSRoklwmszRkJVLw88qSMFp1Jf6W7QX6iNpt1ftFKc9gFGx9IrE373Z", "hvB9B4fv39LMzZGeHnk2M7fStj3vPBBNHnGp+zsyiNCordpxsm4shiY5TCnhhdhNSh26Ep+o07cjZ+mrkF2icwW/7siIwiCr", "wCLdrtsaEguidUF9C+6TiMk2WC0enWZloHYk2IgD7RwesURZY3tYzh/0Cg1zj/wWUsUpe04PwvCNIi64m23VCPiUrbyWQvNS", "iivHfboE3Fa2fd9xYA3WZKpMkmfpNlfKlhwdOOMGEyfyVmHhtat7jj3qNBp9Gnsuz+B79bwX8mJOJJjj6iTRytv2NihA16M0", "GNO9yg+loBnXRc+XU+IhUR4dcZYB6MkPiZwmcmob4KQtYpdnfLkCp12jfYfJYqcd5L6+ns7NI23ynI1UnNSLcilPmkz3OTfH", "vyYhpImXQzc9m6r9v3oGRPSpKqYJorhuqe5TiUdL2tvyRCLlssoA0Y1zpeavl8n0o5qlJOxCgunqB2iHt/UnTRTcoI6QIgo8", "FgEGKTdrEpJVdnWhQ0JBindz0z1IGXmLtgInFeNYI+GxIp7dLbtuWuITq2DO1S0Sca/tNmOXl2/gjoKnl/S9qTamEd3Pqtec", "jLt1qUIewgXgGor7kR+wVd41W+iBEtzrUVfUDDxXyv71ZCpoUphqXrNnQ5XbUM1B5NisITxx8EeyJ+FncQDo3WqEBLgFJw9L", "kRxzo8gWf+3bFrCexoKkNnYTkIsF/TejGaJ92Ncp9iWGsAzh2yBcHPpYIbWAHWVhIRE1zXxZmrDCEgXe0X4Hb52nKvYl4U5z", "jboV2NV3M5zGHTO4zDKAafSglHNbfMFCFm504kwUIM4WGT4oa/9CC8BarRYWjh49Or8+GKz3XGHnoZAVHoS1nGWxFXseel0k", "HT5FGZXZrNTVwiEBbLtv7++ZfSlxxQmI86JBGdCvzV4S59hm81zxR1hUkFN42/b+5+yaoVFiJ2KW/+5+YU/7md0ZporHM7Je", "KzZeyy0IBlI7a95BtyX6jtt23TVmMg2ewhxxEdsekkr53/2IogyGfgJ1QfTtPpjQFaGXqrphDrcdWF5d31DWqoDoCWrv24D1", "/VW/30x629YB5YHWLJ5bwig7Jx+QwwsOHQZLStD8Ay1iS6dnP8sWINObZIi0GYcfCWid0J5lz9yIA0H2leGYmhQIr8WJFUm8", "/Vkk0CWtpVM83x11oaRjDW4ZJMvewUE78LfNZTCcUCMFai2l0WHWtY3IQJFNFnXcWxYtq8xSW7LaudMOr1XKXdel0B0CWmZo", "u678LYH0Ez+oPeMd9hlvdJP121ISU7MxTTLfOHRgiK4p2tJyhiGq0hotcSrPfvXwLvjR/S79m1kHGymfOF9kDkagBVarToYy", "EpadaYLFg4wdHqWnAZBsRPeSdU6Xxn0TiK1l3lKV9c9ilup/YGxmcFAijtwQs/mRp3cOgTdAhsVchs7/HeeVdPw4edQV5GmK", "JKU97LTcvAmE7kh4lAJgPvurqpZPdbzWn9gfPOnQshcDK7kJPeyQO9/c8n2VRRP7O/ZVMz6jypZ2v6OdGJGQ4NFwXC0eZrX2", "wsKd91mPY1xcbEU8UkqqIUwce0WGHi0Sy5vNn4NZGxJ3CbjtfuuPIC239l93717+Vhv/n0muB5XcE2hwziWl5Cl7LbnSzkzN", "cnBkWyoqOBv0CUqzwocmkHbcb5lBKfUaoibBuWh9kp0jRZIyL5id7ce4Z07+QmAlxHaLoKzziYmeSohDnBeutrOUZZm/OKaF", "K7d0m4DRHkK7HsCN1INcSVtuczPzfeRD6Zu0gH1yBTq6dCbHdiq0ZJvD1rEiS1HsTerk9rxZvcveTQDg0pi25yNhM+6LrzMc", "qLizeQE4CyStG3U+1v4vJSbvTtHHMqaD0jQtzHC1uj1U1O3zy1k0MTumZrJhLBILWJJo0e6CzSzQ/dlaMEentxb7c2YMF3Er", "QnGDLy7LfUyU2ImiBfMtR3CBeoS9wlEXS6/tRcc2e/t0BrWsGmC1RfpSki2JPJWOVJUGLAfPJtFte8Iv2fHWuAN+f7bPo/4j", "yC0Qw9rNm+wbZkfHLneFuL7g0tp2izmMrGaiaIHcH0TJCRNoisSBI34eet8LWeShoIryRt21SbBoQ2rXXyEOV3udmLCSfjfG", "BQF8d0jx/VD23ZFVR7mabSkmcgGRqNQJcIOixA2F7OukOio1H1sn9w2gDs6pNJdVejUzO1qf1/byFOqpWugcqRiD5HfWXN6C", "Goa75jtFy1eyle0z+Hw8Msfd8+I72nTOzEzm2COQ1gsOuRYoWdztWY274PW2Z0STwey1r6atGINxG4Z5QXDOYJwtUiiZ09RD", "Hd9oYVD7soBikYW2i6TcKrRVb+DFIaGPXOXxWXv9QNGCWzNocJGhFbpCban9y3lJizJ1jK+utDl5IsuF76li3JlfjSAzQzbd", "btVGMdoKtbasp+wdhsTMqPgqxFLsycP66HpYmnfvU7ZVuRBy+ESSuw1rFll5YHOoT63MOeZs29uW9Wbr74BShNOf8JkUHAKt", "9CD8ha0sF8VNrnf7eAXfyQ7ILMhXyOPnUuoO26iuqGus+T0SpBSJ1u1QZgvRiPN9L3On2klbQMg3jddwY2x/SfqYvlucX/55", "4rwY7BlqAmVx3yIYzciYxOsQptKwn73N5bBKCUD8HoDzZpNymzovCpUrAQJPIUtHvgJ9FzBlG9CEL3f4AWEQXCNe/UngfyX2", "j8OkqsTOX/ZbT2bnTEDzHNaS1Ktxwfs8E5QW7xa2V7gW2odbxjqIGJYg/B83nuYLvBQ4F+PMZa7WnzcyRggV6azRv23cr1OI", "F2mL66g/KFLebVhFiWhvEvse5upyhphnMs1zcvxi6DBmNljkMJRFS0BAduYhbJu1AMTUZVCIDm9RG9LTVnzhYOZ3ZEkFrzXU", "asZtuKeTj9mNQ4Y/BTCy/fdY1KjiubLtqsjOMuXpnH0WdkbhuSOBeRQCJgebl6ukvLvOGsZOJSzo+SumLomraZCQ9XofbhNJ", "qzTAQp5ymM38uEOjliwQGdE4f61ZXOKww5V7EsL4QOaDO9KQ0zgr22syG6YvbjG1M0kJgzmKvrCnMktWVPEwMWsjcQQd1Vpf", "GfS6i4lbTqqayPcSLpQKlbCnteV1tbQmFPGgtGzxtXJYHDo04gohuWoT6zhD73NbLp1ljzn8FqHO+RyhS667hpHfItYg+rq1", "pVcmwhQp+n0wxVIkzAprohu+iZ8FWf69AEN04Q7N/W3AOdv3Bn3PlBMgk8E3WTMTe4u8ZeFeApjoqDqiNrtZCaPOL1eZV9h3", "K2op/Gxl37i9TbRWVssetajcNJmZ8h0iAz84S7UqwpI4JtaRzb7YG5ezwylVPHl9pZfINlk5fdPJYjs6H4kXsH219VlCB4Ix", "B+bQCk7YATZ5N6KdDa4zGmx1Eis4ka8JCZ0jkncGjyuSDW63EK6g7DXzBo0riIwkQp0qexppGkY/u/AI8gHqTy+Oamv6uB96", "KSB9NI97qFRYfhYaEEDKVC9kV9Ne4XV7OOur4MGT1m7YsUQQl0OKacbewTPUF0GS/WVGMBVrNswh+9o0fwokZl9erVo/EnmA", "4F/DXAo/BmtTQHbNHCYUjoY/G3W+jjH262flXr5PSiqDh06Cb7VBq8ztnsHnSUEqrlmqtGeJF25JDbTi4Ozs6Sy3nPNikpPe", "PAsApEhL/9cewGkOHJgVyacmEPjBld3Hrh6s6sgQrsrawKJK2WOWHVQpCYv1Fnn7OmPBD4ycP+8o1g7sVSSB4C9kAP0ZXV0x", "hEGIJdsuBISlxwf30zNKaCJXKWVfpTN3Lhj9uI4a4OckS9FkcZ4o/58wN2qHraeZQ54W5kgnWTDUJyGpWM5DMPGMWULdZOdU", "Yn3A1uFrFgFowqloMkBMp5fmvO1vLG5GjLG1EggL39RBTtn0hMg5Sk13rY3AaABd5HhbFqK3+zDYWMcpt+p9y8WfhLxRR0N7", "8iu0S6PiMecFlh6TKzNgD0Z0uFLpZMriBvzJK31cmJY2AfqtZJ7fy8H9+lpfkONY9zWutmauaiO0h3YwZR512GXb8JqqTGR8", "aI/V3h702zjyvFLCIyhtTDKzM4cMz/jBHsj0CctZQ22gs/wVWPTFnZuAdkc+XntLEdnFuWQXMRtfJIpk9A+3kXqtms3KnJez", "B87gh0WVIP5mk5jpE/t5qrzS3ujF2/0B9xwsGtlGseNUycGx8TrUgtzmVrL4j3TqtZ6TrjSsSoGauJ9sUjHCc63al1R5uBqe", "SW8CYhUW9CGGhlFxOPd2varetI6ZzQLZLXsz8hRu52DDjbhNyXxN6hauWX+yqEEjbtdrVDjPh5rjR1H5MdhMVSIobAj/16uY", "/CxLe8g89c5Go+D8hh3eCK2QfNW5KPfBuDjkmvXQYTsxzhMK46rRLciSwH1DMwJrQPukelKH+KjncYBR4CzCrm/asgd2Qct2", "UVNOurX9ErhXMvduK7b1Tk1FvyAkyNNarvuJLkJx+wTrUgHWyNe7g6Csy+zpVAPrWCIHuUzirJbygqq3j9gi0t6lsz+qTX2f", "GUectiSgy21vooJrgqfTodD2g9lZTZXgbaDCRlx64NrNkWuw0122MTgX0D+t33TYk9gTVXhXguSuVBn3z96F/+N/b37nm/b/", "/7CwXu36BjyBo0X1rUW3SXiWoyAr8WQHogTC3xuDVEyTylvIAFymOTyE6r1KCJsdWQFQqk5P9o/2ooxHCSzRnsf5g11VltP5", "4AXy610i095LHx7/4H2yE14lQ93/+Pt7wS8GRq5Pz738i59+7+Or5z59/nGpQvvv1x5Ov3/6wpO/+LPvQnz52asfX7/+6YU/", "/vR7739y/YVf/OD9Xzz+9CdvvWn/+/mp9z5+54cfX33742tPfvqnz3z87gs/v/T2z99+0T7583PPf3rpuc9ee9TXHdPg1hND", "wQxCWwUggtWBx+uUKrctknGwLrVxBwEa8HwcPxNMmGUXNZS4/o2XJMocrw8aKdMxugzloZXygZIiy0KBl0rWT6DBrOsDGWCf", "uKdeGdIepuqwmdpiYnDezTGM18BJRKG4c3k2daT6G/JggmGzfcYykBm4jgSD0IzuQHHaeC7wreh32xfT77hY5M4qyN1tVg5X", "iHjdIEeJhPSzwCEpgg+0xUrIj5Zk7gNnIBj6fkRmw4fB/NfyQgbv5odPi00S7H/OxdjydoJd8jhZH8nKKPZJu8Jl8m8GW2Gw", "cYKRMd3rw2cxhzk7L+bXcd5Ocg2KjTLuzb/f/eBdclW+yZl/BX8l5kKwFaZr2qdwxTfIU3ktu1fGjUh+xavkFNU9gxPzcrr+", "ZbIjBrflVb5HZk3ru78k66ZYDhNPpn267cNHwHNJzsi37XnxLGA0fRKsoc7YeSnjCr3kPXwBDJ1gF/U+AQdly2552Z6e/WPj", "En0D9saL6Fd7oredefECWUy/bc9+0V5zBtAPLvEq79v3vp1xSF7Onv0C+0nMnW87iyi5J8li+ra37k3xsHLE9JmrfKY3nEcV", "MwBPRh5P8kGKLfNdu8N1tuCqX8fHEcyVZJa0e9sT4u/H2QLMz9S2D37czlvxYHJuvWM/T/isuZZ9F8/yPvk33wPzJUfxCjhl", "OQP55Pbd98lpeoH9o/aKm/V9zXUbr6uJKRbvvu88tO/wOfwzU8/yXjYWV3U/zrn32jnMO2sGXI31RX7OEx+8lK2dd8QRCy7R", "xKJ6ifPoXTwfn7ZdL5fR1zbCXF8ZB+jlliPU2vIIP33RWvGseFR9TYnhVuP7LtcA5u13bOa+y3Vz3H57x/l3n8jbz/V4wVfg", "NY7/BbLEnuB1cN+37F7tHMY4tuso8aFq1rG/sf/8uXPZWv9k2twnqMJ8IbSkT7r+uDTQITkd0tIuIS2NbPvAM3zrufjlvVDH", "ts+81EqQt9eRkPSr2TXPhHw5Zabx+gm+ci7UtE9l7TlOifb32s/j38tt2yDqndS6dd9rVPc+Hdd/Lj5zNvTQk0Q1BcT983qK", "F1zBXNd06fYX23u195WE95P85Tl+/vVMFPsqb6fW6rne4r+P8bmeC1Xu90Oa/AobJiH4aDZe/wE758XpZzzePpe0s11zPPXS", "cyGA/lpIvZ/M9OWlO6+HPc/7/kV8S/3/cvRJel4b2Xd43/SMJ+IzL/JBrlA1/pkQ6U5j/UKM4Ono27jmK09kguZn4u5prI+H", "IPjp0Cg/Ec9+JsbouGvEe1/FOOL1s7z+j3jZ1OdqyQW2860Y8RN8MX3m2yHdfnFqPni/XWPXnfJffF2kOXA8nlrC7q/GvV7g", "k56AXry3/2powV9tHznNW78C+x+ffyHrq8uxgq7ysqejP0+7wH3bZvXVD0JC/WL7XN6rx9mex+PzbB6ufIptvsCePMFeutiO", "na+j90JK/rFs37gcr59u57D6DXPsbHzlWnxen7ka6/Qam3eKn9R80/x/MfrkVAzKlZgDavMVb7DGvZ2rqQ8fj/X+BK92Jfrk", "1Wx/OJ49Y7bn+BNFl+K+qT0XqFaf9hneF1c7n82fND+Pxyy9zLcoZO/j9Xw2x07GnHmFN01rTWvh+en98zi/pbV2ns/+flxH", "81+b/HPTe/61+Myr2ZzRxL6Y7QM/jT45Gzv5Kd+j8JXz0bDv84nS9S/ECnqn7Qe89Vi8dSZG/HSMAluibmnX+/NTe0U7uLHW", "fJ5f9odN+4P/qbHQ3Hua1+e08V36QnvG+fOmfj7JP6/yM2ejkc/6M/pnrsYAXcye8fH493le4TJffys7Ky/4d7Fv6Lx7JY07", "2aLBi/0UGZLfJJ/0I4n1+dLNt4Kx+aOHwS790Um+foWMyC1Xs5iUT968SDbvxAOeGJZfyziWX7crvA5ecPBpBzM4Xp3iEH9U", "zNi430cn/F7hAZNVmrzXev0s2uRs0xecdRy/n8Nn/ZrnPjrBK6k9b5D3Oq75mr13EozUdp2r/nkwdD/GT4Hf+vHgKCeL9MuJ", "m/yNmz/mU4Br/HR23yfIz822OcO5GKkvkbVbjN/g5j6J52efBjP2G+Q3f0x84+KuJo/4JfJP6/VHyGJ+xvvtMT7laTFW3zyD", "58d1+OoV8qU/xdfBYn4GfZC+S45u5+s+zW+87tcXb7nag2u/5c943ubBUzcv8YpvJL7un2b/XiaDtvd5y3VuM6Ptk/PgQ/dx", "P+vs2i13/OPxehpT8Htfw9yLsYhnvPkqWqN+sKs647j112NkLg927xgXzLw3fP68br89wStj/l+3v8CTfpktiLlxmozvZ7xt", "V/E644qI/MFtb+VEEfnfn8HMxA3u2FNSaqyPhx697LfvkG46wsokH0Y13mBzdheTIeJrmQDFg8ieRLRW6+HqeNMjjvM5NjjH", "5DdLtyAx29x2RmYFnAd4EDxn2/IpBZ11J4m8B5cmK9C3Iak7b/90gkh0qFR70CciHHYv8jurG2PQnqjYwjO/+5n8i8wMg+wR", "ht0aQtbaExoZBuLzawFCZ6XAXRnqtdhUFqrsV/YoxLknYHAIjDvhTxZMQZ6kIxBZh6FniSrt7yCymZjODo+3kB4sDkKTK4cW", "F62uaW8ydx8D3g6T3Tq22Da8pfqrq+bOfO7Mjwb3ICt70LpstkUgkVmghdc5TbIH/e/KQCRzHslW0STGIdF9O0Z5DSwc4Alv", "yEIC5ed7UV+IKF6/KpFNHJaixRhmuTgJ3aXkYyHFPu8qxraDTM1JbIlFcZrBDaFO2rpt0ntkGKCUw2Yqwvlg55HOYNY4UkGH", "be7eBRY7wE1zvElLKMMyR1yINZ2A+SRmeGtOkNFwhTm4QZH2xNbrUAqHDSeqa+GwKVqdhGVnc5j1kQwKg6wX0xc2NVTs0CTi", "4cRFZ698EWlFsvKiPDFPmiKfss0cNapGW9r9/Z3FIitceGDctEUnXlziRGxjpgCU1nPonlAdKHZsQQLCGWsLyHq0+AZTQJGO", "nMkD3EWOGg6egUrcFYFhsr52hQKJ2pct1krMAs5H7VxVntKw6TJU2oEE60POS6fPJC7BMSIZf/nSgqQVYuvMqzSc7SdgkCzS", "WrHZ9SAZk4auzlqkynfcJyu97k1aWWZbC8y9iAtkOAUWWsyQoyAuTbR3vYnQa9/MoWzebo52wAKWcrzFIC9uaPn8pdtM2hP7", "zPq+hWO7mw17lqM2G3e39Shcp+KoZzblvgxBPucoCOFJMnxR1dLZOSrTJRY57bO8S4txRLI3R4zEVh1CsUOKWoJ9KMe4zbUJ", "TfvoghNh87hLNHki9Aht854TdpSrQhm0lMyA94gX3nPe/YyjMhVSkKoFqU58CryqG4NNxNUlA64C/lIg3jSjsCXl6M9G21nC", "1Yhrh0DBVCFJFHzVap43OVTv870g/lFCUgydOumKDCPcKVo+i+WpRGoCDjn/UAxe1VWKzGFIh+xs2R2Aku1xr+/DK21wIhaD", "HDrh14n5DrBYUgM9CLCEJqTgA8HpKXyKnXxJ7rfdYeuy7wQrEnV3iJP+yB+uaIvBbFuez8tMxMEevCKB08LQZ3UvO2cOBSEG", "4emEPBacL1WOA513YWNJAPv6qaMTnSETs9Px3sxKJ6IA7FGBJBWEL7Go4sOZ5EVCIjeOvNLK8jLIjUFstxmetDfBHr+1FazC", "ThjO04X7W8Lkm2lFTCo+tjSFPnbgt6rglQZVhvUIksVBoiJaa8q3IgvpEs68pBaviARC55STIhVVERGCiogZL4lIkB9s3y07", "pkitnPOyplqcK/kmiv0gzbBtIskzt6Vk9jFxZDtVNlKzKY+t2qAoTIhimU3yT+N0DAhnWyLQKWKZidssAWtsIhzId/8WtGct", "2JEXzmYsf71JXknaxDnJPYR4ZK9z7RaZ3k7R6sg452Ui9Snb2jdS6hBOwx5NG11Ar2VeTNcSWHNEVIeTwU7FtlIAhHeTPjQh", "WYuW+BswdxKZJKaY9Iudx6/I8fAsXa5LHYetkHFG2VbAPhgNBg8WgfEJ7ijOnaxgqDdZ8j2VP4IsW1snuGxjKhBgVaAE1T6R", "EQiCQTQKWm3Ltdddz8f+yQt053LzuAke8YlqFXweOHsZBYMJgGw1PW213+HVik742dZyNUfIVupILhiAga7ddzCD480dmnZf", "/Dxlr2A4Q2LG6Yz8DMZMszvxPFwZmEkd9FezeQlohkbrFBm5JwDhTd0k5qpE5+xQlCgZb4J+lAA4lVe11EMsGOLsycs2m9YS", "4gV9wo3NKMEhcQSrUMwMvRYTl2EDSTxO+jK6qWt1b7MIhu3dqkJUgW+oJnBSRCGldorWKKkbF70PMj7XZMbe7oA1AcnGqCNZ", "rajkCQhXy9jWiorYRRwrVhAFXofQsh/vZosFPtBZmbgiWyFeu9qOvBQR52nCimG/7tVetHp3BrQvDuTLOZHs42NOm6GTKVPk", "KkpWFlWp5CvmNfG3wTsDcz9IBEQ+7AxSMFenbM9Us9qItkOsHEDzfbFlzxqstUTRxF5tVwl8FR1PACAReCqFtA7J69S2a7A+", "/f8U288JwkZ0JEQfbGFESQT2kHTaUisnqYI0hVfT2yqhY1Zl7DJQ8mGrl/PK7cyBQnminyOofwn+PBa05UQDBZWRo/Q+zjmA", "HJuc1b6ayQ8JWe7+Ryob8HrlFrqVyOeJLIxKBnGax3Sz+8xMzarEKkq2BqFc+YPciMEF1VpCACETcbzbp3NeCstyIM70phIT", "7ZaLD6RiW5w/2YS1PbEKTXj360UjBEINovo8ppNvVdrDA1s8kw9J2ePWJTJaLJlUWtmSYcOMiFjAxMkkU4VPzuDQeDgJTGb9", "bsiPkBcGZWx+tNX9rHBoYVlwrChXzskbMnr2RqdC0H25365dLI+ebXqxHsS8udW07PRewqThx/6caNN79baqpHz2hgJIb3LX", "IMMKfyW3/TNiO9IatQeacJy+2KOW2gGBAel2Yvgwi5ZbaqsaqNoQCnMeJeBr6QzLn6PvNmoE/xPJ0CRcX3rSsJLTruZ8oOKU", "yUtZSheueogreCGvsC3z+mKCtEKbJPQ7iDtGUYdcSGujK22VXXCPH0kQYrMY7cXtOjZvB1fK3yR6MXz0ln4KG74L+TEs4gXK", "qnjMKpntsROU0vHSCZBt79ZsGWa9mGjJ1kg4WXJF5oSzTINVBGbTZrwqcTQpcquG7kuKfvUGZfegWZBmDZO7vY0zi8JLPZXX", "sJQ9EV16JYoIl3DIEOWZSq6gbp55lMlKxXgx3huqIgHBJ3fLXVW3PSRIhRWA1OR0kcO4yAr40Wf3R4EOQ0Duo3ShBF+gjuco", "MG2y+QJzGTU2DqJPYNHSNpIEW1/MajKW8rqHSaZmhcOCCNqj1dAsypwcsvxqcHdgI0jbICq6g5yZrU7vwLIjkjv8IevcuhcO", "L3fYft9eRLkF/Mngrckfu1n20A/jqMF8J+Psji8X9335SHHgniN3fsVJ4mV5sl6lWfj9xq63X0eoQ1VbqK1NwY08MBDA2zGV", "Z1om6N6kjchg70ucAYMmcxFsVwI/12Zw4Tn1oKZ/zj/Tp7EQhkUL/VYpblQZN9ViXr3Y7sg2cRYzZYp98lyDgTXxu4j4r80Q", "+Pmis1w9699ZKa0XyuJe25kn4/5g2DxoFt+Dmzde6emP/oQ/xeH11y+RxcvTEKtSigFnXUu+pTxIgoSi4fzDJRlbxbNyc6Ve", "H3N13DHAmQlt2NvmitvKrrTpPbhWb6JEhTkKMzlCsd05JDJ/IhIq8hH2OTbb/ZicEcRWwXJuRCQSK6ftXkOdg/d3cvIVPpb4", "qN9hKQ/OLe+Hb/jbv3vgt79wl/1vaSo1Ej9tcph3sjCVBvrWrnxZzjcZNdDsgame2F/0zas4MByWExQZTMV6pk6cxa8CGzwa", "Uy5jMtdZzjkppu6+vP82zgzbO6vRbYWrT7mNPFfkwfulXp2xklDYMykXZpSi2KtHlFbyJ1L6QwJCnWJmKoCeZFtLl3HbLFTZ", "BiLOkKRIso5trfA8Gz3vD11MBStEJxG8/BnXPHlJE3FJdzI/FccuDuYpvEYjFY2JGklFgXbvzvv+fpA6FVLCIEmlHwxIrsB4", "KhKdj0RikqjXVHyCFVTJiFEnp0rasq1cFqNia8eEd7zqvdTO1m1Ws7VH1tQKmFGMrXHrdGpfx06fcQkWU6kV3ySxQUUtYlp/", "OcOD7Tx5OmJ3pgVn4357qylhV5tydWeWplISGVMv6h5cxUHfW9IU88wMy8xSBbkkD8NmqNtYEiqgdy0WDzTzdbfYbzO+VVfY", "s+e3O1PbaaF6qIPmbA4AYmf0PIKTa7kxWkxlWPaO8nAI1HWtoSmajTmSVFy2OHs2ffbMP9BkSycTeqV6F7e3yIyz2u5O7Vuz", "R+cz/bFZmeyjLv4ZLqe4FaZSeSjP5c4VU1GTgw9VdvaE1pynzv8AIk6DzTbrBBsFyT+aJHSsxYkXteOzUyEwMA+2ClkZP15K", "jkQtXJuaY9KLz3WbeuI25x+yHWhmCSzCtoCSv7o8dRnXTXSHZnYqRb5jagtbnsootdWVaGum2IejPi9PXhaxc8SGPDbne89q", "OVwhRZVtK91qZsoLjudkpmD3wlTAONO1kxBkthMtTSVkw1GUesqR+r9ff99u/Yf1f3/78ZHCP40byb7wKFG57/N7plILU2mc", "JRqMzk5UdSO3D+ujU0wdTjNTzm5RrZrl29SlqIFlzUakqmW7QH8uTfkzZGohr2wYZDLBERmt6ZeGJOZUtKFw/94T2Yopx+7m", "sXQflc6U4zoVfitcAsxHumnfSGTVu7GJA3uBiVhEbsEdCN9fAlQh9EbGtRO7InS29AKnW6q8dslWO1j7g1HrmGGitpWesKjN", "6wOziYMGpKgZafLWzMSsS5z3xBu0GRs0NCO6c5+sFXw/kKeeikznx9zZdJLQ/1uaOpqLKXNGenLRHvoOie6AO6aXe9cyfFNS", "u91RyHwSfoDq5LTepFy9TMao5Jgx3IFXGF8DdUsNZhsu8ixabdNjyg7ZObWKi0xpliGU2Ktx0Z1T69bVnv00mUo2izttGDz6", "1HhLiYksJAFXssi58DLRjxR7WImjxFe4Fm7upYH3I54UplnYVNrBYCXXaXttpRYQYclEsSkvCaBQL4Xd6mwFFEVuGU/hboop", "X7JYnMIvZUwNXAEZ6Klp2aGIHgA8IAlZZ9ztNo1arjJabFM7eybdd+vZURdTE2bKLgc0yomi0ULy9lOKEnMw0sBiexpWPId9", "H2EPphz5H0IvLrnlUneMfgOLCicuo6b8XvJkM1K8vVvHMh4NjxY6nzfCA6KY8HW7Y/oB8zgpNkjbi3oe6fEgn9zBJsQTVGM7", "5eilALGCdhnPp7OAZPW0zs3k0b4UhRHXSx7OnWrmaHYKiSfYCsttUWfbRtgkceqs3lhV5NhIQZx89TVVpP7UL3szNkHP86S+", "9spxDxs4bb67/ZnuoPd8m5edmUppZrKELuDBjB1TL20dLfYyD8GkvHUizCcKRKlhz8X4kkagaN9KpkgFvqVWl4lCJAgjQdsW", "K+DrME9boEu5VY/KWLc7ZzK8UePMlEmihGiOsdKkx+695247fb5SkaKEecgEU2uwo3VDu52WVerPqYRJ04yHa1JISZZc4lID", "csAWIGN3q5Ov29nZevQpFR2U85mhd2jKLg8vK+kWZMp9UhMKdnJGkr2Lq+4dreJ8rNsqQrsHp/wjnaI4zDBqXEpJ6m1qJq9m", "7Dr2ySmndWe9JpFrCl+tgS9augNBk1+nNHzCxXE03aK+z/tTc8Jp1QZtPgvxuK0qG/cDLVOF3WVmanuL0167APslnSuzU8t/", "CrDXTMvVStg6xC6UVYsdemE5n2jFFESS62g8BOgztDUSb86iW55ra2vfmpmfmd4oWkEZRi+T9ixSVFMTm4mXtC/RgkgBO/cU", "wyNqdcXtKlOpAqa4W+zuVFNWMu1G6xHZ9uI/sUNvEMlDCd7kLvRURG23q4+1e0HkGTwD5wRjPBsDtyVGrSQIbndPJHJilGmz", "sfZJ2eqB4aRWY7Lk/OjBgkeAYaMqsusyux4sNTnUwH7keIkiM5Zmds5Mxcil5pXkcRK8k7ti1k5bM23I3WckUiiOdDjq4goy", "+F2ZxPee9poQYetM4S0y5doChy33rIjYu/Th/k5/0Ckk9BbSy4cOzZn9a+2iI4+2tFLAEYath5BvapOnHLEcrSgwa/I3SwYZ", "AqFh/ZKpxSYSt2Ducunu4BZqk1w5m54d7Z7yrptWj8lzYGXSYSAaONHCDAYuQNP2vvw2eQGZj8cfU2cjNo/Mymu9KAmmJaFy", "sxRammzZZ0zaeVaVvloSeAx8aqZQk84rRrCc39RmgZ/MTfL/WjbQLKgIyzg6XVp6gyIjTHNosq+VEE31ZVbkJ7qiMYH7yPyc", "Daq8rko6WwL0VZH4ySctmj09EbZkSjxN7SFb8pVDCXTHjlvv3sqbZ8eW9e4ULDAStG6fedbCF8VU8Hw1dgEl5Kbw+XMtRxYg", "f1P++9IUhtxW2Fbz4GAD3HjNgzbd81jCBz9C7b/YND64htrl9q9k3Wc8C/WW/mJ1OuvRWef9HlkIogI/f+8a68jf9hr563lV", "ur37F6pF/x+/BwaA9pofPv3BRXIMiAUh+6S9/6xzL5BvgH9dV3W8V3nnd3jZWoB68KusT8+YF+yv9ppgI3h4igsgq4H/8Dtk", "HQGfA655kXwHqjEHN8LD6Rrvsg798dQrZJNgb7zLevg/ZXX7RVaSP+u98h5ZBq5O1e6DNeAyq9HfJafES1PPh0r9ZxIvw8Pk", "gnjzw0dwt5blAJ/0yv4LXhl/nfX1aM+7vGu6A0Yp64nL/HmJte/+vfTeOx/8iJ9+m6wGF7wa7bGbZ26+/tGT6benokKIVVxX", "WMnl9VRtdZuq5lId2xusO3qV1WRRcRd1Ri/bZ67YXy9NVXGpnurMzctZddJr+SfZGrumV1W9rGoqr3tCjd9Z+96j/t4J1kzp", "KlduXkd1lz/Dw6gBs08+4d97g9Vjp6cq2aItqGCLtrx88zzr397wmq2Hswqyl6f+OsPnfQp1g/jroxNtrVbUgPn9zrNi7C1d", "kz15xv695pVcT6EKzu+nerRzdpVr9l3VsD3qNWJngjXH+/OJrJ7tZdQhtnfPn8HudAb1a+m966oHhCia2YMC1AwXkxCmTqJQ", "evEDvzMd1c0khUkHKvmVKILBdocNzXOlyLl8sxXMW/qt7mCVnFQMPjqzp22JFbJES9MB46nMnFm+01v5dHKnaQNh6xXSelMh", "3RmCSFYhTLtKqG2knuDnA7qo+GFKVuaJmyYiO94qj24o790pMmsvHS7g6RQocWb68ItLRXy8DSPQeZ4KbdMXzfy1XYtTruqU", "6d9Z3jWdhVuZyum0z7s6GDxY3xJBXPgW+uobsp337VnMNURAB+o65n6p+elkB47ZzDuaQn3NzOTJYzs7l6ZHJUu/4cqdKWxB", "p63bcFbqIhdh8SRqzCt5bCks2VmeihpOW19L5ujq80cHw24zF9naQulaF/BOrN0ZeyoEI6atNWvV0arXa2ULipzFfed0MMN7", "xcWwZzLV9jBpPPqblNBH9Yorxrqxl6pWphyefdOpqqViOhUfyQC3Xr5IzftEyTsd4vy8Z15tNt5v3T1piebUjDZtgXogT4NF", "EIgTudXy7hRTa6WFm2nGw6ltbcovD7F6B8eKgxvj4epGJlyMD0/7vcR3ZYtHQJYNQs3MiPvWrtnc0tJYx+M2CceqS/s0azKA", "5n3MChCml5am8MsZ1GM87M0yxty6pM0t3k+k5WQOT1VX9pNXmwWs2jQF75v5PRklID7fei4KhBVTSRXGjdr+i+oq93xaQC8R", "k9O72fLRpGnNqUIq1K+DvByX3p9peGdGf3izwf3rkshmmAanpPueOZF7Fk0Sp2W2ykRrFrIviKZM5dlCHnzcugNFsOQy5JSH", "IYvct7MRzRFUjMP0euVW2ihZE9lGX5N2pd6V6IwjZlcmmY680yfactaNiHZelzq9tga2qi0NSOtYIIZyuu707umNUSTwyS/M", "wmThymZxpq/2JbVoT4jBW57egnKQI0Ohg637h4Otcr0MtmTXYM5qUCL6mpV9YIKIVs5c+fU+IKFVH/Gfw4iX2jO2eWfd6BDz", "UmlU2q2KW2FWGLttc1Z+7HawTk7jWZwLNMX7p2qord3T6B7FcxOcLi92CTR2mwWf2kR3zpiDn0tZpbmqTYY5EcdLYpVphrol", "sa9uihxkHEeMajoXi2kYDpZGprkj5sNiVpyIu5LKoMQM2yNV4oc5+AubW6pHxYom3ccZ0nSIoCmxAD0TjBznM76pi8H/821n", "hgFdyemgFbqYcVKdDoqP51peF3z4ojNWnXreaUyc4eeHwZHyPslAzjltjr97xVmYnPUlb1Vilfl+ECslUpHg2sJ94/POoWRN", "fZJfOR8sNO8Hscy1jFvG2vwIOEbwlR/xyj8m7cmpjHXqhaDKec6v7Jd6MThzxMTyfHbZn5IZ5ulgUzkdzUj8MGJAejXePTtF", "OuTMJ8H8k4jC0qB4T55yWien5HqYb50NypfX4+snguPl1YwDJyihcKM/j1bpvuJ4eSsa/0LQlD0ZvEan+JZor07wjk/wymIM", "+3YQOp0JEq2X+fuPg48op38RW9FPgwHmGfaMrvx83Pck5+EzbOd7+PcV0nk5y9BVp9DB76eiD58NZio90bmYPz9AY3ApsYG9", "yktdjUF81Se2P8K1eN7oSZ9sz/ArifnqtSA7ej9olC5H152K532VVEIvxndPx3WuxBhpbiQeuVdj0p4KSqIXggXoTMZy9lZM", "Zt3ieKygRD+VWHROxWp6OHaDx7NReC8YgcQv9JJTD+HDz8WIvx6sRKdjLTzil/J19O244Ivs57SfnGi3CO9MNemHMduD18uv", "LG6fi/HhmLHek4k0LLoOH3vOv4K3RNkUXF748/W40QuxNYFFatg0v5NrbOweTWd5+HLO5T5KIGGm1acN7pmlW2AYxVRdWa9e", "vsUrHnnN6Lzt5bzU/KodQg+2ma1i+jzZfYtJOxPXT351Oe2y71q8JTcE9HLXzB0ZKPuKW2zVFp9Ec2hf8LF7KLa4XbhklGv3", "gTIKXcewqpcYiYVGGigCqv1C4LXewi2e3wzgGLneWKJ1Ce3ZbpfwuXvoe1TDhB9WQWzR3DIAC7fECpwD2SzTZmJX2OxMm5B7", "RyQO39/5OjL3D3aWyUlTtMjLDO0NON7izC0Rg7liOptf0sRuNbtucdaX0v09w7h4SwcIp9CaqsTq5OWZxTTiKXN+VJeZ6XDB", "CgpXM3zN5OOS/6Gz3LnFo5opiqm0Ki689z9lhR2eb7qjWivNDptVQVeiUClunzwkVXDnqwdx0DdHG/b+N9F/39wGfDVzDbNf", "BXS5xQ/JMLDAeTQ5Lzi+cFhZpyRpk+sNqwZHy8ftxH2O1EgG5FTJCK7JXugPZCt2luWqtFjJvMSR411M40GnZ9eePb4+dpt5", "WELwQ0WaKHlRfCjzo0k6Quc/09aDFusqZvCq3PDOtMO/+y4W0DLDXDaD/twty2FHc/vkSLmOjP9ss+uP9vzXW0zbpflbXmhn", "ggJkt7FZt93mfsNtWX6MHehBoRQEbPF9jmvfou9RFEv65RYfZOThjDR/V27ZXxLHuEStd/3suZ+9bf9962fv/uzaz67/7Oz/", "V9e19UZ1XeHnjMR/OJkosq16ZqBEVYPHExmbNFRJQKlRUvWhGs+MzcDYQ+eMsa2oUoyBkqSERAolQlVCCgmOG6gDcRgIxlL7", "B/Abj/BSqf+ie932XvvCiy8z57ova6+91re+b/ccsAFjzJzyIA8w0r2DEfABRuDvINcxRtjN788xUwGRfOT79fMdzPl7j77F", "s79AhmDgE97GnMCXmEXYwm8pY0GMysj5jL/943UEnvmUmQN3sHse8xiQHdji7MQWZwUe4RNc2j3HPLzEGg05mB3kG14jNlvz", "/Px+u5/w+21jvgSZss0ZW3574NHb+KzUPltBdmTTRfcVJx7zkqm49nmIdHNcWUX84aeNX/+gMglrwNT2ZJ3Pv/vkPnDm0fWe", "3AKWMryD4yajsz6yXH0XkO9Nvsf7I9/ehuQRPJ6zb8wTnKVPgmd0nHd8v153ptvXYi02l0+53GLN1VAyYVk1XKPQxiHIjS1d", "OKmqlhgK0DJds7gi14+a+znZYRVQDCdSVSuFYPE3RQwQ9EJ/EggesToLHFnjSK7sRouBeXPYOYvQX4KUaMsZfFSd7y7gFMbJ", "LOqe2SGQlOwZi1j2mBv2FLxIC9QqV/3MKKw6EnPmJvTcFoDE21O4Y4oij2N/6yASmR7pF0H1+lxJ5ohC6H2wLXVwQK5dEG9m", "vDgBonmj2Rutzmmsdx3FftFZEBfC4JNdETvu/M1iw5h/8wNCI7Wq56GB6lOATQYZNIhu2hqgKFExVGU09HhxsT9b+nWxVnAo", "TQtIPN2qd1RYEsJY1JtZ3sLoeLjaZaE7hEAfieshxkSXU8GjA4JjliSXaBnwK28QkKCKxlXdKuLuZtvLxVrQtXsKUGrTKjVB", "l52IMSgWDG8GCyogGWcziqNOGo/LLFr1HFTlW9nJdgeQNT2gEgxcR8IaNfp2xFg+JAnCHT3exRBWNsGKuaLgYV+fcwId+y4H", "Wwsn6qBcAuxuJ82DmG9bJXCxoNXm6vMtth+ukscc/C4JQLGClmgoZeIcHO11EYT1G/PPwgxUDGsiHAHMIioH2ZEQ8aKowAgW", "hegUrabKzG6SG5Eth4uPS0xNIJgCDnHevTV9GFPMK1KaZtuDZaXAx8LoY+6XQgEyiDxUF8ZEColFKMuDUol2I/eYvzBmymBv", "Em+qz3V5Hu+RibwndAsKgB/LtNCzGTOjmbYIHi0U3OWtttkKQSFv9i5mMnNXA8G20MHQeBwoZ4ZMm8cfhu3RJTgciCRh8Bxk", "nagTmahSiCkUlMnfQpSNa9dAqJiIIbXzbsdWxSAyWBd/S0DziPGILdkJV7k67fM26C8KHoXYA6jWxl5US2BjPfQ8YvLafVtW", "oIV4WUnHDBNW2CTQoi1aqYCCI+iutfyk1ERopL0TYFVsgCgS4J5laPeXuiXj8/asMOPUIsvhAVILVAmb8gFcrtfuNv1Chowa", "yN9YMT8e5+06Kx4poZBjWeZJWHZRmLCn7IfHX4cIXBw9FC/HpvY4NyFvYTcm9ZkciBPMniw0wjbIfUDi4WNqV0obpbET9WUz", "32dyjidU9pVdikqqjagzVJy7wtNauz/ogoCVLyERyXjR2PPT9YbZfiGKGJa/1nDx5f2TqsxvKHrm2hGl+4YimqNqJ0i+0i+r", "Djwpa6ki3TCb4nr/gFnQzLoFeDSZhNHcL0QOWR43kPaeiDsni0aeQ2eKwmMxCx21YrSjVLxmfHt4rFcqna6xy1w92VQDlAak", "qwQUrwDZ7DorioxDdBJdHdZY5ATqRDnh3TxyQzweaijqzRUkWaBqND8VBOuw9S+sq5p5CRXa6yLlGEmo4o69+uLUkcnp3x89", "lElXaNIe+lmshTEpr4MxquLj/eBm45GjAXg6Idtc7EBVaWBcjK3wq56gX9+o98zzNnVExzlVXDVNrjLU10ow4MgySHvpZZu9", "8pOtFcQKmBnDb6FGmtopcH3mLDJNdFQNsR7h5J5nkdvu12RgdUe00JSj1duvpUCL3oFx0lHJdUCu4qi3rB/gE/qVjcIc5epO", "ZFEj6bDZPhMVCiNVprVAnXuhK9yogM6bouAwNny0KNUI6qOg3+tZGGOajp452tf0Hb4YAlGtXrfHJD5mIe4s5kgg4RVfYvRF", "q7PRbs8MNSoRttw3k4cnONz0uhkrM93uSYsNcEwZCzRy6jZ3K3XXzihj2WtrXlXvI9NWvwPxswYpxlLy27yJhI9GpS9YW1hh", "1ckK5Iz4P9LvK9XIWmQiJxayINWuyE4s3SdsYBZ7ziWY7C7QkDZuAm2GYbTMGS9nMedSvPwogH2Bt2POJcQ1qtryBwGdiwMY", "EEhg3lXn6ExohhuCevNEHTE1doxh3MsLCBsnP2cCIst6qjhhienGXBcNrU3MHydiUmEox3pGRkrYcOsURB7Rh5JabEsLnFGF", "qtAa6UolqSJ1jMTkRGreBIhHdns6qoalY3R1KsBqIG0IDWAzPHpI8QsEhwI78zYFdlrZaCN4N9CcXcL8mPFlYTBZ/XnroNsp", "eW7tkmm1POBCMPOU8U4KoXKwC5YXCGGYPS8PasjMlk5BAnlkBrXw4JhTDSX0b7cPxR+5qG0KBRPw8yjed9wn+NW/RNwd7jPt", "vYFBYLl86vipAGtnRl9kaAuOHVOoj+pAztVFE8F7XT9KC7KOPsYca1GZCMr58dO6wgHfXeB1Rbp5cWTM0fi0iV+25UHtsIlx", "Uc00RRyXaWFIhrjV9o5lQTLK5yfBcYgrLO71KssliAirm3A/ZtF2Xn9LUTSbfrB/kM3E5znVRk6Xx5/tfvT4Z8Auo14Y6ZSF", "n9wgFTBEkp+H+C4ruz0IVNhE1Y5jnP4nu5c4qnqXFd4grgpx3R38nyPDj3/AM3cIVY546of4F0V5N839KBp7D1HlHGNGhDfj", "uvnuFFH+GXX9SNeM7g647wf8FsHzQEwZI7jbHDH+6+4niDw/h7j5Acd6QdnuB44mbyP6exs12rbw/vSmcAzh8OWTB/QWrNIG", "d/8Uj3+AmnLboPKH+daLAhjYlITsBcyormJu+g5meym/bAEMSneMJZzOySnfSrr2vqTXL0q2mlK6Xyutq28VEoDy3VqBS9AR", "8LmcBXnnq/j3V4ziYC0hQlxcVcnfMyrtvo7PsKrUfx6p97JoGfsWA7nOZ3jKHdE+WxdwyKbgCj7A629y3pyxBISrIVmcWwIR", "eSiveQFP0WdRy6h25jbckFOUCo/DGFyUfLoGV+wo5MaGNPKH0hH3FT5HtaEDkFgsgYaCPJKuFzSCQ+P83UEIPM27VYVC+Ukh", "Z65Li+1I79wTUIQCF3lIj4uigbWBf+wgwuQR6ze5pz0janqEHrnqQ1PuyME38cQz7k3dvTakRy7jWbcZoMJifDTAbkqb3BYF", "Lmq6GyKzJZpufPfb3uhlPbsL2JIfIHCFYAwfCyiIRO7oef6m2v+8PN5fZDzbdv6ecSkOVvRQRu+6TJ91kaCyY0xQN+4T6qZ1", "1c5b7joEDuF5sS4zzgpvreMT/kuJwaFiIPx7214nziN5tSmuImXNHLWO1RwbtqpB1IzgmPvm9788dR73ieg0hfmh77hO5AJm", "qH7ELBVdGWpa1lGxiJ9HNI7UJ3cx23XWZqa+x+dahWoO1vG5Gd4Lj92Sv9SGUkIwS/vL3d5cZd+rr75aWUYSH9gjhEEh3PbC", "t2OZTQVEURhhbVL6HEVgbxHW7/Fid3a2qCntmMZvDOQ2IFUvoH/jsUQBpeyloD4E3ECdsuIcjvWyXiqmBHz4ZC3owR8VqlE+", "plI59HYx0zdcAtKSZuvYO4cnocR0Ab0lvuEJ43XTJQ6EiWfUGA9yKnnDRnUyG4/TdFZ82yz27uL9uOeQ8Y3jrs3ACw0iWpKo", "wHanQFQl0bdx4AlbAjuZkkKv1QpLURrktSD1hrEVzPV718qiHeuBON5SwGihp+7Rr8YhqSwdKwnA7CowIyf74xtfypOQIFYH", "r+Ac+cIyn8LAhey9gL8ux5aGDp8JwtU+ZBlOVuRLMkSzKJe4z9aZYETOTIS5GdDz5qCA2UvPAaIlmgjteQFVqS3MRKPebM1T", "XIKQI7mKJAmqR+8q+fHLZtDwJuLgyuHmcLs5QkxyJwSYDVti2WYItdfIGDPOeH0bu+gFr58pRlaLI8aCVW65KheGiaPwBXNg", "aE0HTl17GXD6GVuOtqcGQWHFgCuM6Aag7NkTfoBUHOz+F+b6QKw4VZ4sx+O+RDwMwgUBgY1RLU0m7B5uV9hU5dZB2ZBKmEmo", "kyvEIP8n8ccsDkDOt3Nfnq07a3mqRrPjvCnM4+jmpDFj8zPturpYa9kMSCZF4eKUxZzUCVS7cSDQy/5CuMYP2tVnZ0F0oa9e", "CLHn3MY8rVzwTjHERSFwCazAcYfhEgtNDXXkmeaycHa3rSUDeHIfkdzlUmvGvHMLmUXqkGzs9V3RIq12EAOySTfAGUlc0WZb", "hQTBsly8zpFd9cgMZdIKQMwKr4fJ22Y/7PqL2B90iVMd7U6jfqougiSOBU0Hbr0hB6UpNORmF3s4TpUdc+1FKgZQ3yFyFs6U", "QghsxbTBHBDAEbFZ3EFVPzX0XunYROnU8ZWc0A5WpAZwgGZJBRMmo8/GphrwRQPQdsPyGi45imYAGx5xI/SOObNy2DgX15xZ", "jwZUeXT4hwKRIHXVQ44pmCaYzsB+bIC2YA+IIqBdXt5/6OX9kzzGzD/FkZGxMCIFK6RHUigxbDOs/hjUPYb4WoBZBkYaoZdx", "nu29EvDITpmZNDwCRnu6PW/+yuIQTNFbVtizcB6S83mCglxUpbPvoFwjpKqV2cX2XI4bUm3gl84y3tjCcVQWL+EycYRe26e+", "OEj6zkzN6rsioKy3NI0cw3VYrld46E3a0kjsAa13J4bHA9/yjXzuDi7qCXDOTFsx16vPI/7FIiC0wJGAl+z1HNrCK6yV4xIr", "drx8/qlYTTg0ajmyPqqXv+CjqZWDnvpVrQovqoewMMrpEYhOXVCJHeKtsT43izPJxcS6mfDeitSXfa8v84Tnt6cQP18tNfDZ", "GIggHeiPjSUWDccY5gRTrHKVqJO0QcyAZRs0Bpsw/x7AKsh8VuGnpybBeTF6H5/9WE290912c3jvyFjRYxy3pc7xVs3lHJzp", "riVcbh9/SH8FFeoILiEMFGqOEucdvK9itpLJUI2DzA3OasPK0WnPYvOOejqIAkaJTVjmOCjhOHIPmu1THSIWtQw2ueP1ce+L", "AyPAv2WJNuDkdS4+DuYXE+6jp3alXDdPros4vqIdHUmpYbbb/qWlm0SVwozgfphZMT7uSRqJbmw1RSyC7ZcFnYkgErep1epR", "x3Fey9seBQXSCCXAPj0NOCKgQW4BO1JOnt0pyHdapqthu0F2ewjVVjYj6liwnX+U6KJalthAIgaHQAkIHIJnI/kyHw6BIxJl", "gRy+UqlTob+y1M4BS4fZdJyGUp4M9iW4uV94SfOS9MNamFNsN+n9+IXgH5t1tFk1tUBAh3TnzchVjpcnl8g9MJuwL4jHZFko", "xgchmf7i3OJ/NvJsmHLriyPCh7N75fH27ipmOzYxhxB89vgaZg1WkSOIciP3w9wFIczNOWcxC/BQ8inmepIFcTmEbeIMkuwD", "cOvE5zJWPvzsGmVRzHUBwz6wGH3Kh2xZVp74ep/Q88ITO64dc39iB9rEz5APR/hNMOb3PSqvn+f42o8cKVxT2PEz9NmTW/CZ", "v0Ydm34dbElO3pcxlKoWxi/dZTlWz+rIaEJak/FsCMeaGPvI7IBHFUSyKDqUp/ysYmoxUBhxZ5KsN1JQ7ghOt3D6VVNOinzp", "eTiuKkSYwIzHFfmMcOEMOMjbjZPeKjcsnq1ybP+sCEPF0ylmR9F1H8r1virLUg556GijNx8t01SS4i1d9Cu07erI4OdLwPsJ", "0/F9M5VLXLZVSPm4RFpT88lraPEKwhFyaEEfG7gUheqLpdIffAKPiXYPnqRWSLRIyjNdejq49nRw5+ngO/h5/+zTwZWng388", "W/vm2dqnz9auPVu78mzt+rO1q8/Wvvjvrev/++fntuT8/qr5b0TyYpuSvKAsw9cYt/+QU2Cc6JGsDVdcXpR0m60qDTI4Nj1h", "kwK2CnVDikAHnIWEsy67QlFXO2wri23x7BWVvgkSgh9LEfSO5LC+lMc7J/WkmyrJaKuGbb5yXQp+deJmNSrNvswVppwU0/ms", "oEz7hhTzXuSidW6Tdayf3ZGvNiRBdlmO3JGU31fqdGqfM/jM+sMNqd71q+D5aTdVFvKGyhDZfqezrsuJt6VVzd2/9oRL7S44", "RhMC/kC5EaosLRr28It3J6EHAWQr6jZSf4MGK9xfplb9Yi20gTRdEnH55fmOOtYZs4BeSqyn4qRRuxmzCiR8qJQ/XKmFIQ3a", "1ZTTllvtON2k14bUWdcYfwnmM9iGcjWosu5qi1eqVN7dP1mpTE1PZe+9Mf3Wm9m+8t7M33RJRCbY8DBVlnlc5mnCrRvUSJiG", "Knirp5ziIhm/NY3+O270VDvmB+dS+78saCze0eJdhoLeHIpjUAgg8q/A/Zoll6zxoV8kMlDV5JJZgETPaNYH5k549VFMvamq", "L1WO5teRyzhLmv70BPCXM+sgpCJFpud77XqJusC8eW/RbJT+fa9KbR/Og8743jGqQ1fu0ftq449D+0AGzEjJgXr8hRdS8bR6", "HxTkwyepJZf/5Fuk19VWshnGe8nbtcZTzor2xpvd7GDPOOmdEcW1OEDeRsLy3EFMEPjIPzn8jsc7eUeqMbH28i6xRypMU+IK", "5lO4wiXihwSED9We+tYzO3rs4JuHJ7PiQr80HRAZQPfFMZVJ+B6iMQw70/lVssTGEC7kuu3T5mDa/Eu2c1+p711QubbT7/Ah", "lYSHbGbjmK6AVEsLhor6b5tJVqa6lYMIf03aj4X6iTwes+ZKdjs7UkY8PA/e2IfFE3AMx2tNHHXEr1ORLrO7VauCduqr6dUi", "jlrhQ6k1RFPuJTABOEvSljKOjmAj18vJzUqyWedbx9OvyQpR4WjR4wSHySvlvfuyaX/1twnH59yz+pzuKWbpFSzx8pj2HE+2", "YX94KEuvC89pr2Iz7cTkgAzuJOAQ8fvT3Kim3RPIJye/wLlUjls6mss88wM3wi6Oz+nCwnOas5qy0/Bez2m2GqIzLykLxdaL", "MJhSO8+7fod8HDCK0tahA/oSbeUOIhrtdQRrNhB31XrrlwXtdUXBygY+xu1jxQpD3v1NBVyyiLwdRfCzw9dMuPO0cbmMFFOE", "29oUrNZXqX3Ghr8TuigkT48Q+TXwvXvGjv0foSWBhw==", }, context = { "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+PwABAgMEBQYH", "CAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj8AAQIDBAUGBwgJCgsMDQ4P", "EBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/AAECAwQFBgcICQoLDA0ODxAREhMUFRYX", "GBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAQEBAQICAgIDAwMDBAQEBAUFBQUGBgYGBwcHBwgICAgJCQkJCgoKCgsLCwsMDAwMDQ0NDQ4ODg4PDw8P", "EBAQEBERERESEhISExMTExQUFBQVFRUVFhYWFhcXFxcYGBgYGRkZGRoaGhobGxsbHBwcHB0dHR0eHh4eHx8fHyAgICAhISEh", "IiIiIiMjIyMkJCQkJSUlJSYmJiYnJycnKCgoKCkpKSkqKioqKysrKywsLCwtLS0tLi4uLi8vLy8wMDAwMTExMTIyMjIzMzMz", "NDQ0NDU1NTU2NjY2Nzc3Nzg4ODg5OTk5Ojo6Ojs7Ozs8PDw8PT09PT4+Pj4/Pz8/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAAEAAAAAAAAAAAAAAAAAAAAAAAACAwQDAwUDBAYHAwMIAwkDCwsLCwsLCws", "LCwgIBgoHAwMMDQ0NDA0NDQwNDQ0NDQwNDQ0NDQwNDQ0NDQYDBwMDAw4PDw8ODw8PDg8PDw8PDg8PDw8PDg8PDw8PBgMHAwA", "AAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQIDAgMCAwID", "AgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMAAAAAAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQECAgICAgICAgICAQEBAQEBAQICAgICAgICAgICAgICAgICAgICAgIC", "AgICAQEBAQEBAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMBAQEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICAgICAgIC", "AgICAgICAgICAgICAgICAgICAgICAgICAAgICAgICAgICAgICAgICBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "EBAQEBAQEBAQEBAQEBAQEBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "GBgYGBgYGBggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg", "KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoMDAwMDAwMDAwMDAwMDAwOAABAQEBAQEB", "AQEBAQEBAQECAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDAwMDAwMDAwMDAwMDAwMD", "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUF", "BQUFBQUFBQUFBQUFBQUFBQYGBgYGBgYGBgYGBgYGBgc=", }, prefixSuffix = "ASACLCAIIG9mIHRoZSAEIG9mIAJzIAEuBSBhbmQgBCBpbiABIgQgdG8gAiI+AQoCLiABXQUgZm9yIAMgYSAGIHRoYXQgAScGIHdpdGggBiBmcm9tIAQgYnkgASgGLiBUaGUgBCBvbiAEIGFzIAQgaXMgBGluZyACCgkBOgNlZCACPSIEIGF0IANseSABLAI9JwUuY29tLwcuIFRoaXMgBSBub3QgA2VyIANhbCAEZnVsIARpdmUgBWxlc3MgBGVzdCAEaXplIALCoARvdXMgBSB0aGUgAmUgAA==", prefixSuffixMap = { 0, 2, 5, 14, 19, 22, 24, 30, 35, 37, 42, 45, 47, 50, 52, 58, 62, 69, 71, 78, 85, 90, 92, 99, 104, 109, 114, 119, 122, 124, 128, 131, 136, 140, 142, 145, 151, 159, 165, 169, 173, 178, 183, 189, 194, 199, 202, 207, 213, 216 }, transforms = { 49, 0, 49, 49, 0, 0, 0, 0, 0, 49, 12, 49, 49, 10, 0, 49, 0, 47, 0, 0, 49, 4, 0, 0, 49, 0, 3, 49, 10, 49, 49, 0, 6, 49, 13, 49, 49, 1, 49, 1, 0, 0, 49, 0, 1, 0, 10, 0, 49, 0, 7, 49, 0, 9, 48, 0, 0, 49, 0, 8, 49, 0, 5, 49, 0, 10, 49, 0, 11, 49, 3, 49, 49, 0, 13, 49, 0, 14, 49, 14, 49, 49, 2, 49, 49, 0, 15, 49, 0, 16, 0, 10, 49, 49, 0, 12, 5, 0, 49, 0, 0, 1, 49, 15, 49, 49, 0, 18, 49, 0, 17, 49, 0, 19, 49, 0, 20, 49, 16, 49, 49, 17, 49, 47, 0, 49, 49, 4, 49, 49, 0, 22, 49, 11, 49, 49, 0, 23, 49, 0, 24, 49, 0, 25, 49, 7, 49, 49, 1, 26, 49, 0, 27, 49, 0, 28, 0, 0, 12, 49, 0, 29, 49, 20, 49, 49, 18, 49, 49, 6, 49, 49, 0, 21, 49, 10, 1, 49, 8, 49, 49, 0, 31, 49, 0, 32, 47, 0, 3, 49, 5, 49, 49, 9, 49, 0, 10, 1, 49, 10, 8, 5, 0, 21, 49, 11, 0, 49, 10, 10, 49, 0, 30, 0, 0, 5, 35, 0, 49, 47, 0, 2, 49, 10, 17, 49, 0, 36, 49, 0, 33, 5, 0, 0, 49, 10, 21, 49, 10, 5, 49, 0, 37, 0, 0, 30, 49, 0, 38, 0, 11, 0, 49, 0, 39, 0, 11, 49, 49, 0, 34, 49, 11, 8, 49, 10, 12, 0, 0, 21, 49, 0, 40, 0, 10, 12, 49, 0, 41, 49, 0, 42, 49, 11, 17, 49, 0, 43, 0, 10, 5, 49, 11, 10, 0, 0, 34, 49, 10, 33, 49, 0, 44, 49, 11, 5, 45, 0, 49, 0, 0, 33, 49, 10, 30, 49, 11, 30, 49, 0, 46, 49, 11, 1, 49, 10, 34, 0, 10, 33, 0, 11, 30, 0, 11, 1, 49, 11, 33, 49, 11, 21, 49, 11, 12, 0, 11, 5, 49, 11, 34, 0, 11, 12, 0, 10, 30, 0, 11, 34, 0, 10, 34, }, } end __FILES["codecs/compress/Bzip2"] = function() -- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). -- Written from the format description (no third-party code); randomised blocks (bzip2 0.9.0 and older) are unsupported. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Decode = __include("codecs/compress/Bzip2/Decode") local Bzip2 = {} type Options = { maxBytes: number?, } function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length) if not b then return nil, aerr end local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30 if type(maxBytes) ~= "number" or maxBytes < 0 then return nil, Err.new(Err.ARG, "Bzip2.decompress: bad maxBytes") end local out, nOut, consumed = Decode.decode(b, o, o + l, maxBytes) if not out then return nil, Err.from("bzip2: " .. tostring(nOut), o, consumed) end local res = out if buffer.len(out) ~= nOut then res = buffer.create(nOut) buffer.copy(res, 0, out, 0, nOut) end return res, consumed end function Bzip2.crc(buf: buffer, offset: number?, length: number?): number local CT = Decode.crcTable local o = offset or 0 local e = o + (length or (buffer.len(buf) - o)) local c = 0xFFFFFFFF for i = o, e - 1 do c = bit32.bxor(bit32.lshift(c, 8), CT[bit32.bxor(bit32.rshift(c, 24), buffer.readu8(buf, i)) + 1]) end return bit32.bxor(c, 0xFFFFFFFF) end return Bzip2 end __FILES["codecs/compress/Bzip2/Decode"] = @native function() -- codecs/compress/Bzip2/Decode: bzip2 stream decoder (bzip2 1.0.x sources, Joe Tsai's "bzip2 format specification"). -- Huffman groups, MTF + RUNA/RUNB, inverse BWT, RLE1; block CRC-32/BZIP2 (MSB first) and the combined stream CRC. -- Written from the format description; no third-party code. local Crc32 = __include("core/Crc32") local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len local Decode = {} -- CRC-32/BZIP2 table (polynomial 0x04C11DB7, not reflected: core/Crc32) local CT = Crc32.MSB_TABLE Decode.crcTable = CT local MASK = table.create(33, 0) for i = 0, 32 do MASK[i + 1] = if i == 32 then 0xFFFFFFFF else 2 ^ i - 1 end local PBITS = 10 local PSIZE = 1024 local MAXGROUPS = 6 local MAXALPHA = 258 local MAXLEN = 20 local LOOK = bcreate(MAXGROUPS * PSIZE * 4) local LENS = bcreate(MAXGROUPS * MAXALPHA) local PERM = table.create(MAXGROUPS * MAXALPHA, 0) local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0) local COUNT = table.create(MAXGROUPS * (MAXLEN + 1), 0) local OFFS = table.create(MAXGROUPS * (MAXLEN + 1), 0) local MAXL = table.create(MAXGROUPS, 0) local CFTAB = table.create(257, 0) local MTF = table.create(256, 0) local SEQ = table.create(256, 0) @native local function buildGroup(g: number, n: number): boolean local lbase = g * MAXALPHA local cbase = g * (MAXLEN + 1) for l = 0, MAXLEN do COUNT[cbase + l + 1] = 0 end local maxLen = 0 for s = 0, n - 1 do local l = readu8(LENS, lbase + s) COUNT[cbase + l + 1] += 1 if l > maxLen then maxLen = l end end MAXL[g + 1] = maxLen -- canonical codes: by length, then symbol local code, idx = 0, 0 for l = 1, MAXLEN do FIRST[cbase + l + 1] = code OFFS[cbase + l + 1] = idx local c = COUNT[cbase + l + 1] code += c idx += c if code > 2 ^ l then return false end code *= 2 end local pbase = g * MAXALPHA local tbase = g * PSIZE * 4 bfill(LOOK, tbase, 0, PSIZE * 4) local next = table.create(MAXLEN + 1, 0) for l = 1, MAXLEN do next[l + 1] = OFFS[cbase + l + 1] end for s = 0, n - 1 do local l = readu8(LENS, lbase + s) local k = next[l + 1] next[l + 1] = k + 1 PERM[pbase + k + 1] = s if l <= PBITS then local c = FIRST[cbase + l + 1] + (k - OFFS[cbase + l + 1]) local shift = PBITS - l local from = lshift(c, shift) local entry = s * 32 + l for j = from, from + lshift(1, shift) - 1 do writeu32(LOOK, tbase + j * 4, entry) end end end return true end @native local function grow(out: buffer, op: number, need: number): buffer local nb = bcreate(math.max(blen(out) * 2, need, 65536)) bcopy(nb, 0, out, 0, op) return nb end @native function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buffer?, any, any) local out = bcreate(math.min(math.max(65536, (e - o) * 4), maxBytes + 1)) local op = 0 local p = o local bb, bc = 0, 0 local tt: buffer? = nil local ttSize = 0 local streams = 0 local consumedEnd = o while true do -- stream header (byte aligned) if streams > 0 then if p + 4 > e or readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then break -- trailing data after a stream is ignored, as bzip2 -d does end end if p + 4 > e then return nil, "truncated stream header", "truncated" end if readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then return nil, "bad magic", "corrupt" end local level = readu8(b, p + 3) - 0x30 if level < 1 or level > 9 then return nil, "bad block size", "corrupt" end local maxBlock = level * 100000 if ttSize < maxBlock then tt = bcreate(maxBlock * 4) ttSize = maxBlock end local T = tt :: buffer p += 4 bb, bc = 0, 0 local combined = 0 while true do -- 48-bit magic + 32-bit CRC while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local m1 = band(rshift(bb, bc - 24), 0xFFFFFF) bc -= 24 while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local m2 = band(rshift(bb, bc - 24), 0xFFFFFF) bc -= 24 while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local c1 = band(rshift(bb, bc - 16), 0xFFFF) bc -= 16 while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local storedCrc = band(rshift(bb, bc - 16), 0xFFFF) + c1 * 65536 bc -= 16 if (p - o) * 8 - bc > (e - o) * 8 then return nil, "truncated block header", "truncated" end if m1 == 0x177245 and m2 == 0x385090 then if storedCrc ~= combined then return nil, string.format("stream CRC mismatch (%08x, expected %08x)", combined, storedCrc), "checksum" end -- align to the byte after the stream p -= bc // 8 bb, bc = 0, 0 break end if m1 ~= 0x314159 or m2 ~= 0x265359 then return nil, "bad block magic", "corrupt" end -- randomised bit, origPtr, symbol map while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local rnd = band(rshift(bb, bc - 1), 1) bc -= 1 while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local origPtr = band(rshift(bb, bc - 24), 0xFFFFFF) bc -= 24 if rnd ~= 0 then return nil, "randomised blocks (bzip2 0.9.0 and older) are not supported", "unsupported" end while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local used = band(rshift(bb, bc - 16), 0xFFFF) bc -= 16 local nInUse = 0 for i = 0, 15 do if band(used, lshift(1, 15 - i)) ~= 0 then while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local bits = band(rshift(bb, bc - 16), 0xFFFF) bc -= 16 for j = 0, 15 do if band(bits, lshift(1, 15 - j)) ~= 0 then SEQ[nInUse + 1] = i * 16 + j nInUse += 1 end end end end if nInUse == 0 then return nil, "no symbols in use", "corrupt" end local alphaSize = nInUse + 2 -- groups and selectors while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local nGroups = band(rshift(bb, bc - 3), 7) bc -= 3 local nSelectors = band(rshift(bb, bc - 15), 0x7FFF) bc -= 15 if nGroups < 2 or nGroups > 6 then return nil, "bad number of Huffman groups", "corrupt" end if nSelectors < 1 then return nil, "no selectors", "corrupt" end local selectors = buffer.create(nSelectors) local mtfg0, mtfg1, mtfg2, mtfg3, mtfg4, mtfg5 = 0, 1, 2, 3, 4, 5 for i = 0, nSelectors - 1 do local j = 0 while true do if bc <= 24 then bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end bc -= 1 if band(rshift(bb, bc), 1) == 0 then break end j += 1 if j >= nGroups then return nil, "bad selector", "corrupt" end end -- move-to-front over the group list local v if j == 0 then v = mtfg0 elseif j == 1 then v = mtfg1 mtfg1 = mtfg0 elseif j == 2 then v = mtfg2 mtfg2, mtfg1 = mtfg1, mtfg0 elseif j == 3 then v = mtfg3 mtfg3, mtfg2, mtfg1 = mtfg2, mtfg1, mtfg0 elseif j == 4 then v = mtfg4 mtfg4, mtfg3, mtfg2, mtfg1 = mtfg3, mtfg2, mtfg1, mtfg0 else v = mtfg5 mtfg5, mtfg4, mtfg3, mtfg2, mtfg1 = mtfg4, mtfg3, mtfg2, mtfg1, mtfg0 end mtfg0 = v writeu8(selectors, i, v) end if (p - o) * 8 - bc > (e - o) * 8 then return nil, "truncated selectors", "truncated" end -- code lengths (delta coded) for g = 0, nGroups - 1 do while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local len = band(rshift(bb, bc - 5), 31) bc -= 5 for s = 0, alphaSize - 1 do while true do if len < 1 or len > MAXLEN then return nil, "bad code length", "corrupt" end if bc <= 24 then bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end bc -= 1 if band(rshift(bb, bc), 1) == 0 then break end bc -= 1 if band(rshift(bb, bc), 1) == 0 then len += 1 else len -= 1 end end writeu8(LENS, g * MAXALPHA + s, len) end if not buildGroup(g, alphaSize) then return nil, "over-subscribed Huffman code", "corrupt" end end if (p - o) * 8 - bc > (e - o) * 8 then return nil, "truncated code lengths", "truncated" end -- MTF / RUNA / RUNB symbols -> T low bytes for i = 0, 255 do CFTAB[i + 1] = 0 MTF[i + 1] = i end local eob = alphaSize - 1 local nblock = 0 local selIdx = 0 local left = 0 local g = 0 local tbase, pbase, cbase, gmax = 0, 0, 0, 0 local runLen, runBit = 0, 1 while true do if left == 0 then if selIdx >= nSelectors then return nil, "ran out of selectors", "corrupt" end g = readu8(selectors, selIdx) selIdx += 1 left = 50 tbase = g * PSIZE * 4 pbase = g * MAXALPHA cbase = g * (MAXLEN + 1) gmax = MAXL[g + 1] end left -= 1 while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local ent = readu32(LOOK, tbase + band(rshift(bb, bc - PBITS), PSIZE - 1) * 4) local sym if ent ~= 0 then bc -= band(ent, 31) sym = rshift(ent, 5) else local v = band(rshift(bb, bc - gmax), MASK[gmax + 1]) sym = -1 for l = PBITS + 1, gmax do local c = rshift(v, gmax - l) local f = FIRST[cbase + l + 1] local k = c - f if k >= 0 and k < COUNT[cbase + l + 1] then sym = PERM[pbase + OFFS[cbase + l + 1] + k + 1] bc -= l break end end if sym < 0 then return nil, "bad Huffman code", "corrupt" end end if sym <= 1 then -- RUNA / RUNB: bijective base-2 run length of the front symbol runLen += runBit * (sym + 1) runBit *= 2 if runLen > maxBlock then return nil, "run past the block size", "corrupt" end else if runLen > 0 then if nblock + runLen > maxBlock then return nil, "block larger than its declared size", "corrupt" end local ch = SEQ[MTF[1] + 1] CFTAB[ch + 1] += runLen for k = nblock, nblock + runLen - 1 do writeu32(T, k * 4, ch) end nblock += runLen runLen, runBit = 0, 1 end if sym == eob then break end local idx = sym - 1 if idx >= nInUse then return nil, "bad MTF index", "corrupt" end if nblock >= maxBlock then return nil, "block larger than its declared size", "corrupt" end local v = MTF[idx + 1] for k = idx, 1, -1 do MTF[k + 1] = MTF[k] end MTF[1] = v local ch = SEQ[v + 1] CFTAB[ch + 1] += 1 writeu32(T, nblock * 4, ch) nblock += 1 end if (p - o) * 8 - bc > (e - o) * 8 then return nil, "truncated block data", "truncated" end end if origPtr >= nblock then return nil, "bad BWT origin pointer", "corrupt" end local sum = 0 for i = 0, 255 do local c = CFTAB[i + 1] CFTAB[i + 1] = sum sum += c end for i = 0, nblock - 1 do local ch = band(readu32(T, i * 4), 255) local k = CFTAB[ch + 1] CFTAB[ch + 1] = k + 1 writeu32(T, k * 4, bor(readu32(T, k * 4), lshift(i, 8))) end if op + nblock + 4096 > blen(out) then out = grow(out, op, op + nblock + 4096) end local cap = blen(out) local crc = 0xFFFFFFFF local tPos = rshift(readu32(T, origPtr * 4), 8) local last, run = -1, 0 local i = 0 while i < nblock do local v = readu32(T, tPos * 4) local ch = band(v, 255) tPos = rshift(v, 8) i += 1 if run == 4 then -- ch is a repeat count for the previous byte if ch > 0 then if op + ch > maxBytes then return nil, "output larger than maxBytes", "limit" end if op + ch + 256 > cap then out = grow(out, op, op + ch + nblock - i + 4096) cap = blen(out) end bfill(out, op, last, ch) op += ch for _ = 1, ch do crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), last) + 1]) end end run = 0 last = -1 else if ch == last then run += 1 else run = 1 last = ch end if op + 256 > cap then if op >= maxBytes then return nil, "output larger than maxBytes", "limit" end out = grow(out, op, op + nblock - i + 4096) cap = blen(out) end writeu8(out, op, ch) op += 1 crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), ch) + 1]) end end if op > maxBytes then return nil, "output larger than maxBytes", "limit" end crc = bxor(crc, 0xFFFFFFFF) if crc ~= storedCrc then return nil, string.format("block CRC mismatch (%08x, expected %08x)", crc, storedCrc), "checksum" end combined = bxor(bor(lshift(combined, 1), rshift(combined, 31)), crc) end streams += 1 consumedEnd = p if p >= e then break end end return out, op, consumedEnd end return Decode end __FILES["codecs/compress/Deflate"] = function() -- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with zlib (RFC 1950) and gzip (RFC 1952). -- Absorbed from deflate-luau 1.0.0 (same author; no third-party code); the compressor is new. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Crc32 = __include("core/Crc32") local Adler32 = __include("core/Adler32") local Inflate = __include("codecs/compress/Deflate/Inflate") local Compress = __include("codecs/compress/Deflate/Compress") local Deflate = {} Deflate.version = "1.1.0" local toBuffer = Bytes.toBuffer local args = Bytes.span local function shrink(out: buffer, n: number): buffer if buffer.len(out) == n then return out end local b = buffer.create(n) buffer.copy(b, 0, out, 0, n) return b end local function inflateErr(msg: string, at: number?): Err.Err local code = if string.find(msg, "truncated", 1, true) then Err.TRUNCATED else Err.CORRUPT return Err.new(code, "inflate: " .. msg, at) end function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?, dict: buffer?): (buffer?, any) local b, o, l, aerr = args("Deflate.inflate", buf, offset, length) if not b then return nil, aerr end local exact = expectedSize ~= nil local cap if exact then if type(expectedSize) ~= "number" or expectedSize < 0 or expectedSize % 1 ~= 0 then return nil, Err.new(Err.ARG, "Deflate.inflate: bad expectedSize " .. tostring(expectedSize)) end cap = expectedSize else cap = math.max(1024, l * 4) end if dict ~= nil and type(dict) ~= "buffer" then return nil, Err.new(Err.ARG, "Deflate.inflate: dict must be a buffer") end local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact, false, dict) if not out then return nil, inflateErr(tostring(n), o) end if dict then local d = buffer.len(dict) n -= d local res = buffer.create(n) buffer.copy(res, 0, out, d, n) out = res end if exact and n ~= expectedSize then return nil, Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", n, expectedSize :: number)) end return shrink(out, n), consumed end function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any) local b, o, l, aerr = args("Deflate.zlib", buf, offset, length) if not b then return nil, aerr end if l < 6 then return nil, Err.new(Err.TRUNCATED, "zlib: truncated header", o) end local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1) if cmf % 16 ~= 8 or cmf // 16 > 7 then return nil, Err.new(Err.CORRUPT, "zlib: not a deflate stream (CMF " .. cmf .. ")", o) end if (cmf * 256 + flg) % 31 ~= 0 then return nil, Err.new(Err.CORRUPT, "zlib: header check failed", o) end if bit32.band(flg, 0x20) ~= 0 then return nil, Err.new(Err.UNSUPPORTED, "zlib: preset dictionaries are not supported", o) end local out, consumed = Deflate.inflate(b, o + 2, l - 2, expectedSize) if not out then return nil, consumed end if consumed + 4 > o + l then return nil, Err.new(Err.TRUNCATED, "zlib: missing Adler-32", consumed) end local want = bit32.byteswap(buffer.readu32(b, consumed)) local got = Adler32.raw(out, 0, buffer.len(out)) if got ~= want then return nil, Err.new(Err.CHECKSUM, string.format("zlib: Adler-32 mismatch (%08x, expected %08x)", got, want), consumed) end return out, consumed + 4 end local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?) local flg = buffer.readu8(b, p + 3) if flg >= 0x20 then return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3) end local q = p + 10 if bit32.band(flg, 4) ~= 0 then -- FEXTRA if q + 2 > e then return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) end q += 2 + buffer.readu16(b, q) end for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated if bit32.band(flg, bit) ~= 0 then while q < e and buffer.readu8(b, q) ~= 0 do q += 1 end q += 1 end end if bit32.band(flg, 2) ~= 0 then -- FHCRC q += 2 end if q >= e then return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) end return q, nil end function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length) if not b then return nil, aerr end local e = o + l local parts, total = {}, 0 local p = o repeat if p + 18 > e then if #parts > 0 then break end return nil, Err.new(Err.TRUNCATED, "gzip: truncated member", p) end if buffer.readu8(b, p) ~= 0x1f or buffer.readu8(b, p + 1) ~= 0x8b then if #parts > 0 then break -- trailing garbage after a member: ignored, as gzip -d does end return nil, Err.new(Err.CORRUPT, "gzip: bad magic", p) end if buffer.readu8(b, p + 2) ~= 8 then return nil, Err.new(Err.UNSUPPORTED, "gzip: unknown compression method", p + 2) end local q, herr = gzipBody(b, p, e) if not q then return nil, herr end local out, consumed = Deflate.inflate(b, q, e - q) if not out then return nil, consumed end if consumed + 8 > e then return nil, Err.new(Err.TRUNCATED, "gzip: missing trailer", consumed) end local want, isize = buffer.readu32(b, consumed), buffer.readu32(b, consumed + 4) local got = Crc32.raw(out, 0, buffer.len(out)) if got ~= want then return nil, Err.new(Err.CHECKSUM, string.format("gzip: CRC-32 mismatch (%08x, expected %08x)", got, want), consumed) end if buffer.len(out) % 4294967296 ~= isize then return nil, Err.new(Err.CORRUPT, "gzip: length mismatch", consumed + 4) end table.insert(parts, out) total += buffer.len(out) p = consumed + 8 local z = p while z < e and buffer.readu8(b, z) == 0 do z += 1 end if z == e then break end until p >= e if #parts == 1 then return parts[1], nil end local res = buffer.create(total) local w = 0 for _, part in parts do buffer.copy(res, w, part) w += buffer.len(part) end return res, nil end function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n: number): (buffer?, Err.Err?) local b, o, l, aerr = args("Deflate.peek", buf, offset, length) if not b then return nil, aerr end if type(n) ~= "number" or n < 1 then return nil, Err.new(Err.ARG, "Deflate.peek: bad size " .. tostring(n)) end local e = o + l local q = o if l >= 18 and buffer.readu8(b, o) == 0x1f and buffer.readu8(b, o + 1) == 0x8b and buffer.readu8(b, o + 2) == 8 then local herr q, herr = gzipBody(b, o, e) if not q then return nil, herr end elseif l >= 6 then local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1) if cmf % 16 == 8 and cmf // 16 <= 7 and (cmf * 256 + flg) % 31 == 0 and bit32.band(flg, 0x20) == 0 then q = o + 2 end end local out, k = Inflate.raw(b, q :: number, e, n, true, true) if not out then return nil, inflateErr(tostring(k), q) end return shrink(out, k), nil end type CompressOptions = { level: number?, } local function level(opts: CompressOptions?): number? local lv = if opts and opts.level ~= nil then opts.level else 6 if type(lv) ~= "number" or lv < 0 or lv > 9 or lv % 1 ~= 0 then return nil end return lv end function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) local b = toBuffer(buf) local lv = level(opts) if not b or not lv then return nil, Err.new(Err.ARG, "Deflate.compress: expected a buffer or a string and opts.level 0..9") end return Compress.raw(b, 0, buffer.len(b), lv), nil end function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) local b = toBuffer(buf) local lv = level(opts) if not b or not lv then return nil, Err.new(Err.ARG, "Deflate.zlibCompress: expected a buffer or a string and opts.level 0..9") end local raw = Compress.raw(b, 0, buffer.len(b), lv) local n = buffer.len(raw) local out = buffer.create(n + 6) local flevel = if lv < 2 then 0 elseif lv < 6 then 1 elseif lv == 6 then 2 else 3 local cmf = 0x78 local flg = flevel * 64 flg += 31 - (cmf * 256 + flg) % 31 buffer.writeu8(out, 0, cmf) buffer.writeu8(out, 1, flg) buffer.copy(out, 2, raw, 0, n) buffer.writeu32(out, n + 2, bit32.byteswap(Adler32.raw(b, 0, buffer.len(b)))) return out, nil end function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) local b = toBuffer(buf) local lv = level(opts) if not b or not lv then return nil, Err.new(Err.ARG, "Deflate.gzip: expected a buffer or a string and opts.level 0..9") end local raw = Compress.raw(b, 0, buffer.len(b), lv) local n = buffer.len(raw) local out = buffer.create(n + 18) buffer.writestring(out, 0, "\31\139\8\0\0\0\0\0") buffer.writeu8(out, 8, if lv >= 9 then 2 elseif lv <= 1 then 4 else 0) buffer.writeu8(out, 9, 255) buffer.copy(out, 10, raw, 0, n) buffer.writeu32(out, n + 10, Crc32.raw(b, 0, buffer.len(b))) buffer.writeu32(out, n + 14, buffer.len(b) % 4294967296) return out, nil end -- MSZIP (CAB folders, DirectX .x): each block is "CK" + a raw deflate stream using the previous block's output (up to -- 32 KB) as its dictionary. function Deflate.mszip(buf: buffer, blocks: { { offset: number, length: number, size: number } }): (buffer?, Err.Err?) local total = 0 for _, b in blocks do if b.offset < 0 or b.length < 0 or b.offset + b.length > buffer.len(buf) or b.size < 0 then return nil, Err.new(Err.ARG, "Deflate.mszip: block out of range") end total += b.size end local out = buffer.create(total) local o = 0 for _, b in blocks do if b.length < 2 or buffer.readu16(buf, b.offset) ~= 0x4B43 then return nil, Err.new(Err.CORRUPT, "mszip: block without its CK signature", b.offset) end local dict: buffer? = nil if o > 0 then local d = math.min(o, 32768) dict = buffer.create(d) buffer.copy(dict :: buffer, 0, out, o - d, d) end local part, err = Deflate.inflate(buf, b.offset + 2, b.length - 2, b.size, dict) if not part then return nil, err end buffer.copy(out, o, part, 0, b.size) o += b.size end return out, nil end Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number local b = toBuffer(buf) or buffer.create(0) return Crc32.of(b, offset, length, crc) end Deflate.adler32 = function(buf: buffer | string, offset: number?, length: number?, adler: number?): number local b = toBuffer(buf) or buffer.create(0) return Adler32.of(b, offset, length, adler) end return Deflate end __FILES["codecs/compress/Deflate/Compress"] = @native function() -- codecs/compress/Deflate/Compress: a DEFLATE (RFC 1951) compressor: hash-chain LZ77 over a 32 KB window, then per -- block the cheapest of stored / fixed / dynamic Huffman, as zlib's levels. local Huffman = __include("codecs/entropy/Huffman") local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16 local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local floor = math.floor local WSIZE = 32768 local HSIZE = 65536 local MAXMATCH = 258 local BLOCKSYMS = 16384 -- zlib's configuration_table: GOOD quarters the chain for the lazy search, LAZY = no lazy search after a match this -- long, NICE = stop searching at this length, CHAIN = max chain steps; levels 1-3 are greedy. local GOOD = { 4, 4, 4, 4, 8, 8, 8, 32, 32 } local LAZY = { 0, 0, 0, 4, 16, 16, 32, 128, 258 } local NICE = { 8, 16, 32, 16, 32, 128, 128, 258, 258 } local CHAIN = { 4, 8, 32, 16, 32, 128, 256, 1024, 4096 } -- length 3..258 -> code 257..285 (index len), its extra bits and base local LCODE, LEXTRA, LBASEOF = table.create(259, 0), table.create(259, 0), table.create(259, 0) local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 } local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } for c = 1, 29 do local base = LBASE[c] local top = if c == 29 then 258 elseif c == 28 then 257 else LBASE[c + 1] - 1 for len = base, top do LCODE[len] = 256 + c LEXTRA[len] = LEXT[c] LBASEOF[len] = base end end local DBASE = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, } local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 } -- distance -> code (0..29): direct for 1..256, by (d - 1) // 128 above local DSMALL, DLARGE = table.create(257, 0), table.create(257, 0) for c = 1, 30 do local base = DBASE[c] local top = if c == 30 then 32768 else DBASE[c + 1] - 1 for d = base, math.min(top, 256) do DSMALL[d] = c - 1 end if top > 256 then for k = math.max(base, 257), top, 128 do DLARGE[(k - 1) // 128 + 1] = c - 1 end end end @native local function dcode(d: number): number if d <= 256 then return DSMALL[d] end return DLARGE[(d - 1) // 128 + 1] end local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } local FIXLEN = table.create(288, 0) for i = 1, 288 do FIXLEN[i] = if i <= 144 then 8 elseif i <= 256 then 9 elseif i <= 280 then 7 else 8 end local FIXDLEN = table.create(30, 5) @native local function revCodes(lens: { number }): { number } local codes = Huffman.codes(lens) for i, l in lens do if l > 0 then codes[i] = Huffman.reverse(codes[i], l) end end return codes end local FIXCODE = revCodes(FIXLEN) local FIXDCODE = revCodes(FIXDLEN) local POW = table.create(33, 0) for i = 0, 32 do POW[i + 1] = 2 ^ i end type Out = { buf: buffer, op: number, acc: number, cnt: number } @native local function ensure(o: Out, n: number) if o.op + n > blen(o.buf) then local nb = bcreate(math.max(blen(o.buf) * 2, o.op + n)) bcopy(nb, 0, o.buf, 0, o.op) o.buf = nb end end @native local function put(o: Out, v: number, n: number) local acc = o.acc + v * POW[o.cnt + 1] local cnt = o.cnt + n if cnt >= 8 then ensure(o, 4) local buf, op = o.buf, o.op while cnt >= 8 do local byte = acc % 256 writeu8(buf, op, byte) op += 1 acc = (acc - byte) / 256 cnt -= 8 end o.op = op end o.acc, o.cnt = acc, cnt end @native local function alignOut(o: Out) if o.cnt > 0 then put(o, 0, 8 - o.cnt) end end @native local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean) local p = s repeat local n = math.min(65535, e - p) local last = final and p + n >= e put(o, if last then 1 else 0, 3) alignOut(o) ensure(o, 4 + n) writeu16(o.buf, o.op, n) writeu16(o.buf, o.op + 2, 65535 - n) bcopy(o.buf, o.op + 4, src, p, n) o.op += 4 + n p += n until p >= e end @native local function emitSymbols(o: Out, L: { number }, D: { number }, nsym: number, lcode: { number }, llen: { number }, dcodes: { number }, dlen: { number }) for i = 1, nsym do local l = L[i] if l < 256 then put(o, lcode[l + 1], llen[l + 1]) else local len = l - 256 local c = LCODE[len] put(o, lcode[c + 1], llen[c + 1]) local xb = LEXTRA[len] if xb > 0 then put(o, len - LBASEOF[len], xb) end local d = D[i] local dc = dcode(d) put(o, dcodes[dc + 1], dlen[dc + 1]) xb = DEXT[dc + 1] if xb > 0 then put(o, d - DBASE[dc + 1], xb) end end end put(o, lcode[257], llen[257]) -- end of block end @native local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D: { number }, nsym: number, final: boolean) local lf = table.create(286, 0) local df = table.create(30, 0) local extra = 0 for i = 1, nsym do local l = L[i] if l < 256 then lf[l + 1] += 1 else local len = l - 256 lf[LCODE[len] + 1] += 1 extra += LEXTRA[len] local dc = dcode(D[i]) df[dc + 1] += 1 extra += DEXT[dc + 1] end end lf[257] = 1 local llen = Huffman.lengths(lf, 15) local dlen = Huffman.lengths(df, 15) local hlit = 286 while hlit > 257 and llen[hlit] == 0 do hlit -= 1 end local hdist = 30 while hdist > 1 and dlen[hdist] == 0 do hdist -= 1 end if dlen[1] == 0 and hdist == 1 then dlen[1] = 1 -- at least one distance code (a lone 1-bit code, as zlib writes) end -- code-length symbols: RLE of the hlit + hdist lengths local all = table.create(hlit + hdist, 0) for i = 1, hlit do all[i] = llen[i] end for i = 1, hdist do all[hlit + i] = dlen[i] end local cs, cx = {}, {} local cf = table.create(19, 0) local i = 1 local total = hlit + hdist while i <= total do local v = all[i] local run = 1 while i + run <= total and all[i + run] == v do run += 1 end if v == 0 and run >= 3 then local r = math.min(run, 138) if r >= 11 then table.insert(cs, 18) table.insert(cx, r - 11) cf[19] += 1 else table.insert(cs, 17) table.insert(cx, r - 3) cf[18] += 1 end i += r elseif v ~= 0 and run >= 4 then table.insert(cs, v) table.insert(cx, 0) cf[v + 1] += 1 local r = math.min(run - 1, 6) table.insert(cs, 16) table.insert(cx, r - 3) cf[17] += 1 i += 1 + r else table.insert(cs, v) table.insert(cx, 0) cf[v + 1] += 1 i += 1 end end local clen = Huffman.lengths(cf, 7) local hclen = 19 while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do hclen -= 1 end local dyn = 17 + 3 * hclen + extra for k = 1, 19 do dyn += cf[k] * clen[k] end dyn += cf[17] * 2 + cf[18] * 3 + cf[19] * 7 local fix = 3 + extra for k = 1, 286 do dyn += lf[k] * llen[k] fix += lf[k] * FIXLEN[k] end for k = 1, 30 do dyn += df[k] * dlen[k] fix += df[k] * 5 end local stored = (e - s) * 8 + 40 * (floor((e - s) / 65535) + 1) + 7 if stored <= dyn and stored <= fix then storedBlock(o, src, s, e, final) return end if fix <= dyn then put(o, if final then 3 else 2, 3) emitSymbols(o, L, D, nsym, FIXCODE, FIXLEN, FIXDCODE, FIXDLEN) return end put(o, if final then 5 else 4, 3) put(o, hlit - 257, 5) put(o, hdist - 1, 5) put(o, hclen - 4, 4) for k = 1, hclen do put(o, clen[CLORDER[k] + 1], 3) end local ccode = revCodes(clen) for k = 1, #cs do local c = cs[k] put(o, ccode[c + 1], clen[c + 1]) if c == 16 then put(o, cx[k], 2) elseif c == 17 then put(o, cx[k], 3) elseif c == 18 then put(o, cx[k], 7) end end emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen) end local Compress = {} @native function Compress.raw(src: buffer, off: number, len: number, level: number): buffer local o: Out = { buf = bcreate(math.max(64, len // 2 + 64)), op = 0, acc = 0, cnt = 0 } local e = off + len if level == 0 or len == 0 then if len == 0 then put(o, 3, 3) -- one empty fixed block put(o, 0, 7) else storedBlock(o, src, off, e, true) end alignOut(o) local out = bcreate(o.op) bcopy(out, 0, o.buf, 0, o.op) return out end local maxChain = CHAIN[level] local nice = NICE[level] local good = GOOD[level] local lazyMax = LAZY[level] local head = table.create(HSIZE, -1) local prev = table.create(WSIZE, -1) local L = table.create(BLOCKSYMS, 0) local D = table.create(BLOCKSYMS, 0) local nsym = 0 local blockStart = off @native local function hash(p: number): number return ((readu8(src, p) * 251 + readu8(src, p + 1)) * 251 + readu8(src, p + 2)) % HSIZE end @native local function insert(p: number) local h = hash(p) + 1 prev[p % WSIZE + 1] = head[h] head[h] = p end @native local function find(p: number, steps: number): (number, number) local maxLen = math.min(MAXMATCH, e - p) if maxLen < 3 then return 0, 0 end local best, bestDist = 2, 0 local c = head[hash(p) + 1] local limit = p - WSIZE while c >= 0 and c > limit and steps > 0 do if readu8(src, c + best) == readu8(src, p + best) and readu8(src, c) == readu8(src, p) then local k = 1 while k < maxLen and readu8(src, c + k) == readu8(src, p + k) do k += 1 end if k > best then best, bestDist = k, p - c if k >= nice or k >= maxLen then break end end end local nc = prev[c % WSIZE + 1] if nc >= c then break end c = nc steps -= 1 end if best < 3 then return 0, 0 end return best, bestDist end @native local function flush(upto: number, final: boolean) block(o, src, blockStart, upto, L, D, nsym, final) nsym = 0 blockStart = upto end local p = off local stop3 = e - 3 while p < e do local mlen, mdist = 0, 0 if p <= stop3 then mlen, mdist = find(p, maxChain) insert(p) if mlen >= 3 and mlen < lazyMax and p + 1 <= stop3 then local l2, d2 = find(p + 1, if mlen >= good then maxChain // 4 else maxChain) if l2 > mlen then nsym += 1 L[nsym] = readu8(src, p) D[nsym] = 0 p += 1 insert(p) mlen, mdist = l2, d2 end end end if mlen >= 3 then nsym += 1 L[nsym] = 256 + mlen D[nsym] = mdist local q = p + 1 local qe = math.min(p + mlen, stop3 + 1) while q < qe do insert(q) q += 1 end p += mlen else nsym += 1 L[nsym] = readu8(src, p) D[nsym] = 0 p += 1 end if nsym >= BLOCKSYMS - 2 then flush(p, p >= e) end end if nsym > 0 or blockStart < e then flush(e, true) elseif blockStart == e and o.op == 0 and o.cnt == 0 then put(o, 3, 3) put(o, 0, 7) end alignOut(o) local out = bcreate(o.op) bcopy(out, 0, o.buf, 0, o.op) return out end return Compress end __FILES["codecs/compress/Deflate/Inflate"] = @native function() -- codecs/compress/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks. -- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author). local Huffman = __include("codecs/entropy/Huffman") local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len local LITBITS, DISTBITS, CLBITS = 10, 8, 7 local LITMASK, DISTMASK, CLMASK = 1023, 255, 127 -- RFC 1951 3.2.5: length codes 257..285 and distance codes 0..29: base value, extra bits local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 } local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } local DBASE = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, } local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 } -- RFC 1951 3.2.7: the order the code-length code lengths are sent in local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } local LITCAP = Huffman.capacity(288, LITBITS, 15) local DISTCAP = Huffman.capacity(32, DISTBITS, 15) local CLCAP = Huffman.capacity(19, CLBITS, 7) local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) local FLITS: number, FDISTS: number do local l = bcreate(288) bfill(l, 0, 8, 144) bfill(l, 144, 9, 112) bfill(l, 256, 7, 24) bfill(l, 280, 8, 8) FLITS = Huffman.buildLsb(l, 0, 288, FLIT, LITBITS) local d = bcreate(30) bfill(d, 0, 5, 30) FDISTS = Huffman.buildLsb(d, 0, 30, FDIST, DISTBITS) end local Inflate = {} @native local function grow(out: buffer, op: number, need: number): (buffer, number) local cap = math.max(blen(out) * 2, need, 1024) local nb = bcreate(cap) bcopy(nb, 0, out, 0, op) return nb, cap end @native function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?): (buffer?, any, number?) local op = 0 if dict then op = blen(dict) cap += op end local out = bcreate(cap) if dict then bcopy(out, 0, dict, 0, op) end local pos = start local bitbuf, bitcnt, over = 0, 0, 0 local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer local clt = bcreate(CLCAP * 4) local lens = bcreate(320) local final = 0 repeat -- block header (3 bits); also up to 14 bits of a dynamic header if bitcnt < 17 then if pos + 4 <= endpos then bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) local nb = rshift(32 - bitcnt, 3) pos += nb bitcnt += nb * 8 else while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) pos += 1 else over += 1 if over > 4 then return nil, "truncated input" end end bitcnt += 8 end end end final = band(bitbuf, 1) local btype = band(rshift(bitbuf, 1), 3) bitbuf = rshift(bitbuf, 3) bitcnt -= 3 if btype == 0 then -- stored: skip to the byte boundary, give back the whole bytes still in the bit buffer local k = band(bitcnt, 7) bitcnt -= k local real = rshift(bitcnt, 3) - over if real < 0 then return nil, "truncated input" end pos -= real bitbuf, bitcnt, over = 0, 0, 0 if pos + 4 > endpos then return nil, "truncated input" end local n = readu16(src, pos) if n ~= bxor(readu16(src, pos + 2), 0xFFFF) then return nil, "stored block length mismatch" end pos += 4 if pos + n > endpos then return nil, "truncated input" end if op + n > cap then if exact then if prefix then return out, op, pos end return nil, "output larger than expected" end out, cap = grow(out, op, op + n) end bcopy(out, op, src, pos, n) op += n pos += n continue end local lsub: number, dsub: number if btype == 1 then lt, dt = FLIT, FDIST lsub, dsub = FLITS, FDISTS elseif btype == 2 then if lt == FLIT then lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer end local hlit = band(bitbuf, 31) + 257 local hdist = band(rshift(bitbuf, 5), 31) + 1 local hclen = band(rshift(bitbuf, 10), 15) + 4 bitbuf = rshift(bitbuf, 14) bitcnt -= 14 if hlit > 286 or hdist > 30 then return nil, "too many length or distance symbols" end bfill(lens, 0, 0, 19) for i = 1, hclen do if bitcnt < 3 then if pos + 4 <= endpos then bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) local nb = rshift(32 - bitcnt, 3) pos += nb bitcnt += nb * 8 else while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) pos += 1 else over += 1 if over > 4 then return nil, "truncated input" end end bitcnt += 8 end end end writeu8(lens, CLORDER[i], band(bitbuf, 7)) bitbuf = rshift(bitbuf, 3) bitcnt -= 3 end if Huffman.buildLsb(lens, 0, 19, clt, CLBITS) < 0 then return nil, "invalid code lengths set" end local total = hlit + hdist local i = 0 while i < total do if bitcnt < 14 then if pos + 4 <= endpos then bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) local nb = rshift(32 - bitcnt, 3) pos += nb bitcnt += nb * 8 else while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) pos += 1 else over += 1 if over > 4 then return nil, "truncated input" end end bitcnt += 8 end end end local e = readu32(clt, band(bitbuf, CLMASK) * 4) local l = band(e, 31) if l == 0 then return nil, "invalid code lengths set" end bitbuf = rshift(bitbuf, l) bitcnt -= l local sym = rshift(e, 5) if sym < 16 then writeu8(lens, i, sym) i += 1 else local rep, val if sym == 16 then if i == 0 then return nil, "repeat with no first length" end val = readu8(lens, i - 1) rep = 3 + band(bitbuf, 3) bitbuf = rshift(bitbuf, 2) bitcnt -= 2 elseif sym == 17 then val = 0 rep = 3 + band(bitbuf, 7) bitbuf = rshift(bitbuf, 3) bitcnt -= 3 else val = 0 rep = 11 + band(bitbuf, 127) bitbuf = rshift(bitbuf, 7) bitcnt -= 7 end if i + rep > total then return nil, "too many code lengths" end bfill(lens, i, val, rep) i += rep end end if readu8(lens, 256) == 0 then return nil, "missing end-of-block code" end lsub = Huffman.buildLsb(lens, 0, hlit, lt, LITBITS) dsub = Huffman.buildLsb(lens, hlit, hdist, dt, DISTBITS) if lsub < 0 or dsub < 0 then return nil, "invalid literal/length or distance code set" end else return nil, "invalid block type" end local lsmask = lshift(1, lsub) - 1 local dsmask = lshift(1, dsub) - 1 while true do if bitcnt < 15 then if pos + 4 <= endpos then bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) local nb = rshift(32 - bitcnt, 3) pos += nb bitcnt += nb * 8 else while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) pos += 1 else over += 1 if over > 4 then return nil, "truncated input" end end bitcnt += 8 end end end local e = readu32(lt, band(bitbuf, LITMASK) * 4) local l = band(e, 31) if l == 0 then if e == 0 then return nil, "invalid literal/length code" end e = readu32(lt, (rshift(e, 5) + band(rshift(bitbuf, LITBITS), lsmask)) * 4) l = band(e, 31) if l == 0 then return nil, "invalid literal/length code" end end bitbuf = rshift(bitbuf, l) bitcnt -= l local sym = rshift(e, 5) if sym < 256 then if op >= cap then if exact then if prefix then return out, op, pos end return nil, "output larger than expected" end out, cap = grow(out, op, op + 1) end writeu8(out, op, sym) op += 1 elseif sym == 256 then break else sym -= 256 if sym > 29 then return nil, "invalid literal/length code" end if bitcnt < 20 then if pos + 4 <= endpos then bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) local nb = rshift(32 - bitcnt, 3) pos += nb bitcnt += nb * 8 else while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) pos += 1 else over += 1 if over > 4 then return nil, "truncated input" end end bitcnt += 8 end end end local len = LBASE[sym] local xb = LEXT[sym] if xb > 0 then len += band(bitbuf, lshift(1, xb) - 1) bitbuf = rshift(bitbuf, xb) bitcnt -= xb end e = readu32(dt, band(bitbuf, DISTMASK) * 4) l = band(e, 31) if l == 0 then if e == 0 then return nil, "invalid distance code" end e = readu32(dt, (rshift(e, 5) + band(rshift(bitbuf, DISTBITS), dsmask)) * 4) l = band(e, 31) if l == 0 then return nil, "invalid distance code" end end bitbuf = rshift(bitbuf, l) bitcnt -= l local dsym = rshift(e, 5) + 1 if dsym > 30 then return nil, "invalid distance code" end local dist = DBASE[dsym] xb = DEXT[dsym] if xb > 0 then if bitcnt < 13 then if pos + 4 <= endpos then bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) local nb = rshift(32 - bitcnt, 3) pos += nb bitcnt += nb * 8 else while bitcnt <= 24 do if pos < endpos then bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) pos += 1 else over += 1 if over > 4 then return nil, "truncated input" end end bitcnt += 8 end end end dist += band(bitbuf, lshift(1, xb) - 1) bitbuf = rshift(bitbuf, xb) bitcnt -= xb end if dist > op then return nil, "invalid distance too far back" end if op + len > cap then if exact then if prefix then return out, op, pos end return nil, "output larger than expected" end out, cap = grow(out, op, op + len) end local s = op - dist if dist >= len then if len <= 16 and op + 16 <= cap then -- straight-line 16-byte copy for simple LuaJIT traces; it reads only bytes before op or already copied ones writeu32(out, op, readu32(out, s)) writeu32(out, op + 4, readu32(out, s + 4)) writeu32(out, op + 8, readu32(out, s + 8)) writeu32(out, op + 12, readu32(out, s + 12)) elseif len <= 16 then for k = 0, len - 1 do writeu8(out, op + k, readu8(out, s + k)) end else bcopy(out, op, out, s, len) end op += len elseif dist == 1 then bfill(out, op, readu8(out, s), len) op += len else local rem = len while rem > 0 do local k = math.min(op - s, rem) bcopy(out, op, out, s, k) op += k rem -= k end end end end until final == 1 local consumed = pos + over - rshift(bitcnt, 3) if consumed > endpos then return nil, "truncated input" end return out, op, consumed end return Inflate end __FILES["codecs/compress/Explode"] = @native function() -- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987). -- Code tables and bit order (LSB first, Huffman codes inverted) after Mark Adler's blast.c (zlib licence: -- licenses/blast-LICENSE.txt); the decoder is new code. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local readu8, writeu8 = buffer.readu8, buffer.writeu8 local Explode = {} local MAXBITS = 13 -- blast.c's tables: each byte is (count - 1) << 4 | code length local LITLEN = { 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8, 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5, 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12, 8, 12, 5, 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27, 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, 61, 12, 45, 44, 173 } local LENLEN = { 2, 35, 36, 53, 38, 23 } local DISTLEN = { 2, 20, 53, 230, 247, 151, 248 } local BASE = { 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264 } local EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 } type Code = { count: { number }, symbol: { number } } @native local function construct(rep: { number }): Code local lengths: { number } = {} for _, b in rep do local len = b % 16 for _ = 0, b // 16 do table.insert(lengths, len) end end local count = table.create(MAXBITS + 1, 0) for _, l in lengths do count[l + 1] += 1 end local offs = table.create(MAXBITS + 2, 0) for l = 1, MAXBITS do offs[l + 2] = offs[l + 1] + count[l + 1] end local symbol = table.create(#lengths, 0) for s, l in lengths do if l ~= 0 then offs[l + 1] += 1 symbol[offs[l + 1]] = s - 1 end end return { count = count, symbol = symbol } end local LIT = construct(LITLEN) local LEN = construct(LENLEN) local DIST = construct(DISTLEN) @native function Explode.decompress(buf: buffer | string, offset: number?, length: number?, maxOut: number?): (buffer?, Err.Err?) local b, o, l, aerr = Bytes.span("Explode.decompress", buf, offset, length) if not b then return nil, aerr end local src: buffer = b local p, stop = o, o + l if l < 2 then return nil, Err.new(Err.TRUNCATED, "implode header", 0) end local lit, dict = readu8(src, p), readu8(src, p + 1) p += 2 if lit > 1 then return nil, Err.new(Err.CORRUPT, "bad literal mode " .. lit, 0) end if dict < 4 or dict > 6 then return nil, Err.new(Err.CORRUPT, "bad dictionary size " .. dict, 1) end local limit = maxOut or 2 ^ 30 local cap = math.max(64, math.min(limit, l * 8)) local out = buffer.create(cap) local n = 0 local bitbuf, bitcnt = 0, 0 local truncated = false @native local function bits(need: number): number while bitcnt < need do if p >= stop then truncated = true return 0 end bitbuf += readu8(src, p) * 2 ^ bitcnt p += 1 bitcnt += 8 end local v = bitbuf % 2 ^ need bitbuf = (bitbuf - v) / 2 ^ need bitcnt -= need return v end @native local function decode(h: Code): number local code, first, index = 0, 0, 0 local count, symbol = h.count, h.symbol for len = 1, MAXBITS do local bit = bits(1) if truncated then return -1 end code += 1 - bit local c = count[len + 1] if code < first + c then return symbol[index + code - first + 1] end index += c first = (first + c) * 2 code *= 2 end return -2 end while n < limit do local flag = bits(1) if truncated then break end if flag == 1 then local sym = decode(LEN) if sym < 0 then if truncated then break end return nil, Err.new(Err.CORRUPT, "bad length code", p - o) end local len = BASE[sym + 1] + bits(EXTRA[sym + 1]) if truncated then break end if len == 519 then break end local shift = if len == 2 then 2 else dict local d = decode(DIST) if d < 0 then if truncated then break end return nil, Err.new(Err.CORRUPT, "bad distance code", p - o) end local dist = d * 2 ^ shift + bits(shift) + 1 if truncated then break end if dist > n then return nil, Err.new(Err.CORRUPT, "distance too far back", p - o) end if n + len > limit then len = limit - n end if n + len > cap then cap = math.max(cap * 2, n + len) local grown = buffer.create(cap) buffer.copy(grown, 0, out, 0, n) out = grown end local from = n - dist for k = 0, len - 1 do writeu8(out, n + k, readu8(out, from + k)) end n += len else local sym = if lit == 1 then decode(LIT) else bits(8) if truncated then break end if sym < 0 then return nil, Err.new(Err.CORRUPT, "bad literal code", p - o) end if n >= cap then cap *= 2 local grown = buffer.create(cap) buffer.copy(grown, 0, out, 0, n) out = grown end writeu8(out, n, sym) n += 1 end end if truncated and n < limit and not maxOut then return nil, Err.new(Err.TRUNCATED, "no end code", l) end local res = buffer.create(n) buffer.copy(res, 0, out, 0, n) return res, nil end return Explode end __FILES["codecs/compress/Lz4"] = @native function() -- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md), decode and the reference "fast" encoder. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Lz4 = {} type Options = { maxBytes: number?, } local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32 local bcopy, bcreate, blen = buffer.copy, buffer.create, buffer.len local band, rshift = bit32.band, bit32.rshift local MINMATCH = 4 local LASTLITERALS = 5 -- the last 5 bytes are always literals local MFLIMIT = 12 -- the last match starts at least 12 bytes before the end local MAX_OFFSET = 65535 local HASH_BITS = 13 local HASH_SIZE = 2 ^ HASH_BITS @native function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?) local lo = histStart or d if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then return nil, "corrupt: bad ranges" end if p >= limit then return nil, "truncated: empty block" end while true do if p >= limit then return nil, "truncated" end local token = readu8(src, p) p += 1 local lit = rshift(token, 4) if lit == 15 then local b = 255 while b == 255 do if p >= limit then return nil, "truncated" end b = readu8(src, p) p += 1 lit += b end end if lit > 0 then if p + lit > limit then return nil, "truncated: literals past the end" end if d + lit > dstLimit then return nil, "limit: output larger than expected" end bcopy(dst, d, src, p, lit) p += lit d += lit end if p >= limit then return d, nil -- the last sequence has no match end if p + 2 > limit then return nil, "truncated" end local off = readu16(src, p) p += 2 if off == 0 or d - off < lo then return nil, "corrupt: bad match offset" end local ml = band(token, 15) if ml == 15 then local b = 255 while b == 255 do if p >= limit then return nil, "truncated" end b = readu8(src, p) p += 1 ml += b end end ml += MINMATCH if d + ml > dstLimit then return nil, "limit: output larger than expected" end local s = d - off if off >= ml then bcopy(dst, d, dst, s, ml) d += ml elseif off == 1 then buffer.fill(dst, d, readu8(dst, s), ml) d += ml else local n = ml while n > 0 do local c = d - s if c > n then c = n end bcopy(dst, d, dst, s, c) d += c n -= c end end end end @native function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?) local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length) if not b then return nil, aerr end if outSize ~= nil then if type(outSize) ~= "number" or outSize < 0 or outSize % 1 ~= 0 then return nil, Err.new(Err.ARG, "Lz4.decompress: bad outSize") end local out = bcreate(outSize) local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, outSize) if not e then return nil, Err.from(msg, o) end if e ~= outSize then return nil, Err.new(Err.CORRUPT, string.format("block decodes to %d bytes, expected %d", e, outSize), o) end return out, nil end local max = (opts and opts.maxBytes) or 2 ^ 28 local size = math.min(math.max(l * 4, 256), max) while true do local out = bcreate(size) local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, size) if e then local res = bcreate(e) bcopy(res, 0, out, 0, e) return res, nil end if not (msg and string.sub(msg, 1, 6) == "limit:") then return nil, Err.from(msg, o) end if size >= max then return nil, Err.new(Err.LIMIT, "output over " .. max .. " bytes", o) end size = math.min(size * 4, max) end end @native function Lz4.bound(n: number): number return n + n // 255 + 16 end @native local function extend(dst: buffer, o: number, n: number): number while n >= 255 do writeu8(dst, o, 255) o += 1 n -= 255 end writeu8(dst, o, n) return o + 1 end -- Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles @native local function hash(v: number): number local vl, vh = band(v, 0xFFFF), rshift(v, 16) local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536 return ((vl * 0x79B1 + mid * 65536) % 4294967296) // (2 ^ (32 - HASH_BITS)) + 1 end local hashTable: { number } = table.create(HASH_SIZE, -1e9) @native function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number local op = d local anchor = p local iend = p + n local ht = hashTable for i = 1, HASH_SIZE do ht[i] = -1e9 end if n >= MFLIMIT + 1 then local mflimit = iend - MFLIMIT -- a match starts before this local matchEnd = iend - LASTLITERALS -- and ends at or before this local ip = p local skip = 64 while ip < mflimit do local v = readu32(src, ip) local h = hash(v) local ref = ht[h] ht[h] = ip if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do ip -= 1 ref -= 1 end local a = ip + MINMATCH local bpos = ref + MINMATCH while a + 4 <= matchEnd and readu32(src, a) == readu32(src, bpos) do a += 4 bpos += 4 end while a < matchEnd and readu8(src, a) == readu8(src, bpos) do a += 1 bpos += 1 end local ml = a - ip local lit = ip - anchor local tok = op op += 1 local tl = if lit >= 15 then 15 else lit if lit >= 15 then op = extend(dst, op, lit - 15) end if lit > 0 then bcopy(dst, op, src, anchor, lit) op += lit end writeu16(dst, op, ip - ref) op += 2 local m = ml - MINMATCH local tm = if m >= 15 then 15 else m if m >= 15 then op = extend(dst, op, m - 15) end writeu8(dst, tok, tl * 16 + tm) ip = a anchor = ip skip = 64 if ip - 2 >= p and ip - 2 < mflimit then local w = readu32(src, ip - 2) ht[hash(w)] = ip - 2 end else ip += rshift(skip, 6) -- step up over incompressible data (the reference's acceleration) skip += 1 end end end local lit = iend - anchor local tok = op op += 1 if lit >= 15 then op = extend(dst, op, lit - 15) writeu8(dst, tok, 0xF0) else writeu8(dst, tok, lit * 16) end if lit > 0 then bcopy(dst, op, src, anchor, lit) op += lit end return op - d end @native function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length) if not b then return nil, aerr end local tmp = bcreate(Lz4.bound(l)) local n = Lz4.encodeInto(b, o, l, tmp, 0) local out = bcreate(n) bcopy(out, 0, tmp, 0, n) return out, nil end return Lz4 end __FILES["codecs/compress/Lzh"] = @native function() -- codecs/compress/Lzh: the LHA family of LZSS decoders (lh1, lh4-lh7, lhx, lzs, lz5, ARJ 1-4, Zoo 2). -- Ported from lhasa 0.6.0 (Simon Howard, ISC: licenses/lhasa-LICENSE.txt); ARJ method 4 from the ARJ technical notes. -- Windows start filled as the original tools fill them (spaces; lz5's pattern); offsets before the output read it. local Huffman = __include("codecs/entropy/Huffman") local Lzh = {} local readu8, writeu8, readu32 = buffer.readu8, buffer.writeu8, buffer.readu32 local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local floor = math.floor type Reader = { src: buffer, pos: number, limit: number, acc: number, cnt: number, over: number } @native local function reader(src: buffer, off: number, len: number): Reader return { src = src, pos = off, limit = math.min(off + len, buffer.len(src)), acc = 0, cnt = 0, over = 0 } end @native local function fill(r: Reader) while r.cnt <= 24 do local b = 0 if r.pos < r.limit then b = readu8(r.src, r.pos) r.pos += 1 else r.over += 8 end r.acc = r.acc * 256 + b r.cnt += 8 end end @native local function peek(r: Reader, n: number): number if r.cnt < n then fill(r) end return floor(r.acc / 2 ^ (r.cnt - n)) % 2 ^ n end @native local function skip(r: Reader, n: number) if r.cnt < n then fill(r) end r.cnt -= n r.acc = r.acc % 2 ^ r.cnt end @native local function bits(r: Reader, n: number): number if n == 0 then return 0 end local v = peek(r, n) skip(r, n) return v end type Table = { tab: buffer, P: number, S: number, single: number } @native local function newTable(nsym: number, P: number): Table return { tab = buffer.create(Huffman.capacity(nsym, P, 16) * 4), P = P, S = 0, single = -1 } end @native local function build(t: Table, lens: buffer, n: number): boolean t.single = -1 local S = Huffman.buildMsb(lens, 0, n, t.tab, t.P) if S < 0 then return false end t.S = S return true end @native local function decodeSym(r: Reader, t: Table): number if t.single >= 0 then return t.single end local P, S = t.P, t.S local e = readu32(t.tab, peek(r, P) * 4) local l = band(e, 31) if l == 0 then if e == 0 then return -1 end local idx = peek(r, P + S) e = readu32(t.tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4) l = band(e, 31) if l == 0 then return -1 end end skip(r, l) return rshift(e, 5) end local lens = buffer.create(512) @native local function lengthValue(r: Reader): number local len = bits(r, 3) if len == 7 then while bits(r, 1) == 1 do len += 1 if len > 16 then return 17 end end end return len end -- the temp (code-length code) table and the offset table share this layout; special = 2 for the temp table @native local function readLengths(r: Reader, t: Table, nbits: number, maxN: number, special: number): boolean local n = bits(r, nbits) if n == 0 then t.single = bits(r, nbits) return true end n = math.min(n, maxN) buffer.fill(lens, 0, 0, 512) local i = 0 while i < n do local l = lengthValue(r) if l > 16 then return false end writeu8(lens, i, l) if i == special then local z = bits(r, 2) i += z end i += 1 end return build(t, lens, math.min(i, maxN)) end @native local function readCodes(r: Reader, temp: Table, codes: Table): boolean local n = bits(r, 9) if n == 0 then codes.single = bits(r, 9) return true end n = math.min(n, 510) buffer.fill(lens, 0, 0, 512) local i = 0 while i < n do local c = decodeSym(r, temp) if c < 0 then return false end if c <= 2 then local count = if c == 0 then 1 elseif c == 1 then bits(r, 4) + 3 else bits(r, 9) + 20 i += count else if c - 2 > 16 then return false end writeu8(lens, i, c - 2) i += 1 end end return build(codes, lens, n) end local OFFSET_BITS = { lh4 = 4, lh5 = 4, lh6 = 5, lh7 = 5, lhx = 5 } @native local function decodeNew(src: buffer, off: number, len: number, out: buffer, n: number, method: string): string? local r = reader(src, off, len) local obits = OFFSET_BITS[method] local temp, codes, offs = newTable(19, 8), newTable(510, 10), newTable(32, 8) local o = 0 local remaining = 0 while o < n do if remaining == 0 then remaining = bits(r, 16) if not readLengths(r, temp, 5, 19, 2) or not readCodes(r, temp, codes) or not readLengths(r, offs, obits, lshift(1, obits) - 1, -1) then return if r.over > 0 then "truncated" else "bad Huffman table" end if r.over > 32 then return "truncated" end if remaining == 0 then return "empty block" end end remaining -= 1 local c = decodeSym(r, codes) if c < 0 then return "bad code" end if c < 256 then writeu8(out, o, c) o += 1 else local count = c - 256 + 3 local p = decodeSym(r, offs) if p < 0 then return "bad offset code" end if p > 1 then p = lshift(1, p - 1) + bits(r, p - 1) end local from = o - p - 1 for _ = 1, count do if o >= n then break end writeu8(out, o, if from >= 0 then readu8(out, from) else 0x20) o += 1 from += 1 end end if r.over > 32 then return "truncated" end end return nil end local NUM_CODES = 314 local NUM_NODES = NUM_CODES * 2 - 1 local REORDER = 32 * 1024 local FDIST = { 1, 3, 8, 12, 24, 16 } local offsetLookup = table.create(256, 0) local offsetLength = table.create(64, 0) do local code, offset = 0, 0 for i, count in FDIST do local l = i - 1 + 3 local iter = lshift(1, 8 - l) for _ = 1, count do for k = 0, iter - 1 do offsetLookup[code + k + 1] = offset end offsetLength[offset + 1] = l code += iter offset += 1 end end end @native local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: number): string? local r = reader(src, off, len) local leaf = table.create(NUM_NODES, false) local child = table.create(NUM_NODES, 0) local parent = table.create(NUM_NODES, 0) local freq = table.create(NUM_NODES, 0) local group = table.create(NUM_NODES, 0) local leafNodes = table.create(NUM_CODES, 0) local groups = table.create(NUM_NODES, 0) local leader = table.create(NUM_NODES, 0) local numGroups = 0 @native local function initGroups() for i = 0, NUM_NODES - 1 do groups[i + 1] = i end numGroups = 0 end @native local function allocGroup(): number local g = groups[numGroups + 1] numGroups += 1 return g end @native local function freeGroup(g: number) numGroups -= 1 groups[numGroups + 1] = g end initGroups() do local ni = NUM_NODES - 1 local lg = allocGroup() for i = 0, NUM_CODES - 1 do leaf[ni + 1], child[ni + 1], freq[ni + 1], group[ni + 1] = true, i, 1, lg leader[lg + 1] = ni leafNodes[i + 1] = ni ni -= 1 end local c = NUM_NODES - 1 while ni >= 0 do leaf[ni + 1], child[ni + 1] = false, c parent[c + 1], parent[c] = ni, ni freq[ni + 1] = freq[c + 1] + freq[c] if freq[ni + 1] == freq[ni + 2] then group[ni + 1] = group[ni + 2] else group[ni + 1] = allocGroup() end leader[group[ni + 1] + 1] = ni ni -= 1 c -= 2 end end @native local function makeLeader(ni: number): number local g = group[ni + 1] local li = leader[g + 1] if li == ni then return ni end leaf[li + 1], leaf[ni + 1] = leaf[ni + 1], leaf[li + 1] child[li + 1], child[ni + 1] = child[ni + 1], child[li + 1] for _, x in { ni, li } do if leaf[x + 1] then leafNodes[child[x + 1] + 1] = x else parent[child[x + 1] + 1] = x parent[child[x + 1]] = x end end return li end @native local function incrementNode(ni: number) freq[ni + 1] += 1 if ni < NUM_NODES - 1 and group[ni + 1] == group[ni + 2] then leader[group[ni + 1] + 1] += 1 if freq[ni + 1] == freq[ni] then group[ni + 1] = group[ni] else group[ni + 1] = allocGroup() leader[group[ni + 1] + 1] = ni end elseif freq[ni + 1] == freq[ni] then freeGroup(group[ni + 1]) group[ni + 1] = group[ni] end end @native local function reconstruct() -- leaves to the front, halved local li = 0 for i = 0, NUM_NODES - 1 do if leaf[i + 1] then leaf[li + 1], child[li + 1], freq[li + 1] = true, child[i + 1], (freq[i + 1] + 1) // 2 li += 1 end end local lp = NUM_CODES - 1 local c = NUM_NODES - 1 local i = NUM_NODES - 1 while i >= 0 do while c - i < 2 do leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1] leafNodes[child[i + 1] + 1] = i i -= 1 lp -= 1 end local f = freq[c + 1] + freq[c] while lp >= 0 and f >= freq[lp + 1] do leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1] leafNodes[child[i + 1] + 1] = i i -= 1 lp -= 1 end leaf[i + 1], freq[i + 1], child[i + 1] = false, f, c parent[c + 1], parent[c] = i, i i -= 1 c -= 2 end initGroups() local g = allocGroup() group[1] = g leader[g + 1] = 0 for k = 1, NUM_NODES - 1 do if freq[k + 1] == freq[k] then group[k + 1] = group[k] else g = allocGroup() group[k + 1] = g leader[g + 1] = k end end end local o = 0 while o < n do local ni = 0 local guard = 0 while not leaf[ni + 1] do ni = child[ni + 1] - bits(r, 1) guard += 1 if guard > NUM_NODES or ni < 0 then return "bad tree" end end local code = child[ni + 1] -- lhasa's increment_for_code if freq[1] >= REORDER then reconstruct() end freq[1] += 1 local x = leafNodes[code + 1] while x ~= 0 do x = makeLeader(x) incrementNode(x) x = parent[x + 1] end if code < 256 then writeu8(out, o, code) o += 1 else local future = peek(r, 8) local hi = offsetLookup[future + 1] skip(r, offsetLength[hi + 1]) local offset = hi * 64 + bits(r, 6) local count = code - 256 + 3 local from = o - offset - 1 for _ = 1, count do if o >= n then break end writeu8(out, o, if from >= 0 then readu8(out, from) else 0x20) o += 1 from += 1 end end if r.over > 32 then return "truncated" end end return nil end -- LArc lzs / lz5: a 2 KB / 4 KB ring (absolute ring positions, not distances) @native local function decodeLzs(src: buffer, off: number, len: number, out: buffer, n: number): string? local r = reader(src, off, len) local ring = buffer.create(2048) buffer.fill(ring, 0, 0x20) local rp = 2048 - 17 local o = 0 while o < n do if bits(r, 1) == 1 then local b = bits(r, 8) writeu8(out, o, b) writeu8(ring, rp, b) rp = (rp + 1) % 2048 o += 1 else local pos = bits(r, 11) local l = bits(r, 4) + 2 for k = 0, l - 1 do if o >= n then break end local b = readu8(ring, (pos + k) % 2048) writeu8(out, o, b) writeu8(ring, rp, b) rp = (rp + 1) % 2048 o += 1 end end if r.over > 32 then return "truncated" end end return nil end local LZ5_INIT = buffer.create(4096) do local p = 0 for i = 0, 255 do for _ = 1, 13 do writeu8(LZ5_INIT, p, i) p += 1 end end for i = 0, 255 do writeu8(LZ5_INIT, p, i) p += 1 end for i = 0, 255 do writeu8(LZ5_INIT, p, 255 - i) p += 1 end p += 128 for _ = 1, 110 do writeu8(LZ5_INIT, p, 0x20) p += 1 end end @native local function decodeLz5(src: buffer, off: number, len: number, out: buffer, n: number): string? local ring = buffer.create(4096) buffer.copy(ring, 0, LZ5_INIT) local rp = 4096 - 18 local p = off local limit = math.min(off + len, buffer.len(src)) local o = 0 while o < n do if p >= limit then return "truncated" end local flags = readu8(src, p) p += 1 for bit = 0, 7 do if o >= n then break end if band(flags, lshift(1, bit)) ~= 0 then if p >= limit then return "truncated" end local b = readu8(src, p) p += 1 writeu8(out, o, b) writeu8(ring, rp, b) rp = (rp + 1) % 4096 o += 1 else if p + 2 > limit then return "truncated" end local c0, c1 = readu8(src, p), readu8(src, p + 1) p += 2 local start = lshift(band(c1, 0xF0), 4) + c0 local l = band(c1, 15) + 3 for k = 0, l - 1 do if o >= n then break end local b = readu8(ring, (start + k) % 4096) writeu8(out, o, b) writeu8(ring, rp, b) rp = (rp + 1) % 4096 o += 1 end end end end return nil end @native local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n: number): string? local r = reader(src, off, len) @native local function prefixed(start: number, stop: number): number local plus, pwr = 0, lshift(1, start) local width = start while width < stop do if bits(r, 1) == 0 then break end plus += pwr pwr *= 2 width += 1 end return (if width ~= 0 then bits(r, width) else 0) + plus end local o = 0 while o < n do local c = prefixed(0, 7) if c == 0 then writeu8(out, o, bits(r, 8)) o += 1 else local count = c - 1 + 3 local pos = prefixed(9, 13) local from = o - pos - 1 for _ = 1, count do if o >= n then break end writeu8(out, o, if from >= 0 then readu8(out, from) else 0) o += 1 from += 1 end end if r.over > 32 then return "truncated" end end return nil end Lzh.METHODS = { "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "arj4" } @native function Lzh.decode(src: buffer, off: number, len: number, outSize: number, method: string): (buffer?, string?) if off < 0 or len < 0 or off > buffer.len(src) or outSize < 0 or outSize ~= outSize then return nil, "bad arguments" end local out = buffer.create(outSize) if outSize == 0 then return out, nil end local err: string? if OFFSET_BITS[method] then err = decodeNew(src, off, len, out, outSize, method) elseif method == "lh1" then err = decodeLh1(src, off, len, out, outSize) elseif method == "lzs" then err = decodeLzs(src, off, len, out, outSize) elseif method == "lz5" then err = decodeLz5(src, off, len, out, outSize) elseif method == "arj4" then err = decodeArj4(src, off, len, out, outSize) else return nil, "unsupported: method " .. tostring(method) end if err then return nil, err end return out, nil end return Lzh end __FILES["codecs/compress/Lzma"] = function() -- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. -- From LzmaSpec.cpp (Igor Pavlov) and the xz file format specification 1.2 (Lasse Collin / Igor Pavlov), both public -- domain; the BCJ filters follow xz-embedded (public domain). local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Crc32 = __include("core/Crc32") local Decode = __include("codecs/compress/Lzma/Decode") local Filters = __include("codecs/compress/Lzma/Filters") local Crc64 = __include("codecs/compress/Lzma/Crc64") local readu8, readu32 = buffer.readu8, buffer.readu32 local Lzma = {} local DEFAULT_MAX = 2 ^ 30 type Options = { maxBytes: number?, } type Props = { lc: number, lp: number, pb: number, dictSize: number? } local toBuffer = Bytes.toBuffer local args = Bytes.span local function maxOf(opts: Options?): number local m = opts and opts.maxBytes return if type(m) == "number" and m >= 0 then m else DEFAULT_MAX end local function fail(msg: any, at: number?): Err.Err local s = tostring(msg) local code = Err.CORRUPT if string.sub(s, 1, 5) == "limit" then code = Err.LIMIT elseif string.find(s, "truncated", 1, true) then code = Err.TRUNCATED end return Err.new(code, s, at) end local function propsByte(d: number): (number?, number, number) if d >= 225 then return nil, 0, 0 end return d % 9, (d // 9) % 5, d // 45 end Lzma.propsByte = propsByte local function decodeLzma(st: Decode.State, b: buffer, o: number, e: number, unpackSize: number?): (number?, Err.Err?) local ip, ierr = Decode.rcInit(st, b, o, e) if not ip then return nil, fail(ierr, o) end local target = if unpackSize then st.op + unpackSize else math.huge if unpackSize and target > st.maxBytes then return nil, Err.new(Err.LIMIT, string.format("output of %d bytes is over maxBytes", unpackSize)) end if unpackSize and not Decode.ensure(st, target) then return nil, Err.new(Err.LIMIT, "output over maxBytes") end local status, res = Decode.run(st, b, ip, e, target) if not status then return nil, fail(res, o) end if unpackSize and st.op ~= target then return nil, Err.new(Err.CORRUPT, "end marker before the declared size", o) end return res :: number, nil end function Lzma.lzma(buf: buffer | string, offset: number?, length: number?, props: any, unpackSize: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = args("Lzma.lzma", buf, offset, length) if not b then return nil, aerr end local lc, lp, pb if type(props) == "table" then lc, lp, pb = props.lc, props.lp, props.pb else local pbuf = toBuffer(props) if not pbuf or buffer.len(pbuf) < 1 then return nil, Err.new(Err.ARG, "Lzma.lzma: props must be the 5-byte properties or { lc, lp, pb }") end lc, lp, pb = propsByte(readu8(pbuf, 0)) if not lc then return nil, Err.new(Err.CORRUPT, "bad LZMA properties byte") end end if type(lc) ~= "number" or type(lp) ~= "number" or type(pb) ~= "number" then return nil, Err.new(Err.ARG, "Lzma.lzma: bad props") end if unpackSize ~= nil and (type(unpackSize) ~= "number" or unpackSize < 0 or unpackSize % 1 ~= 0) then return nil, Err.new(Err.ARG, "Lzma.lzma: bad unpackSize") end local max = maxOf(opts) local st = Decode.new(if unpackSize then unpackSize else l * 4, max) local ok, perr = Decode.setProps(st, lc, lp, pb) if not ok then return nil, Err.new(Err.CORRUPT, tostring(perr)) end local consumed, err = decodeLzma(st, b, o, o + l, unpackSize) if not consumed then return nil, err end return Decode.finish(st), consumed end -- .lzma file: props byte, dict size, u64 unpacked size function Lzma.alone(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = args("Lzma.alone", buf, offset, length) if not b then return nil, aerr end if l < 13 then return nil, Err.new(Err.TRUNCATED, "truncated .lzma header", o) end local lo, hi = readu32(b, o + 5), readu32(b, o + 9) local size: number? = nil if not (lo == 0xFFFFFFFF and hi == 0xFFFFFFFF) then if hi >= 2 ^ 21 then return nil, Err.new(Err.CORRUPT, "bad .lzma size", o + 5) end size = hi * 4294967296 + lo end return Lzma.lzma(b, o + 13, l - 13, buffer.fromstring(buffer.readstring(b, o, 1)), size, opts) end local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?) local p = o local needDict, needProps = true, true while true do if p >= e then return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stream", p) end local c = readu8(b, p) if c == 0 then return p + 1, nil end if c == 1 or c == 2 then if p + 3 > e then return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p) end local n = readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1 if c == 1 then Decode.resetDict(st) needDict = false elseif needDict then return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p) end if p + 3 + n > e then return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stored chunk", p) end local ok, cerr = Decode.copy(st, n, b, p + 3) if not ok then return nil, fail(cerr, p) end st.remLen = 0 p += 3 + n elseif c >= 0x80 then if p + 5 > e then return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p) end local usize = (c % 32) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1 local psize = readu8(b, p + 3) * 256 + readu8(b, p + 4) + 1 local mode = (c // 32) % 4 local q = p + 5 if mode == 3 then Decode.resetDict(st) needDict = false elseif needDict then return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p) end if mode >= 2 then if q >= e then return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 properties", q) end local lc, lp, pb = propsByte(readu8(b, q)) if not lc or lc + lp > 4 then return nil, Err.new(Err.CORRUPT, "bad LZMA2 properties", q) end Decode.setProps(st, lc, lp, pb) needProps = false q += 1 elseif needProps then return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without properties", p) elseif mode == 1 then Decode.resetState(st) end if q + psize > e then return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk", q) end local target = st.op + usize if target > st.maxBytes then return nil, Err.new(Err.LIMIT, "output over maxBytes") end Decode.ensure(st, target) local ip, ierr = Decode.rcInit(st, b, q, q + psize) if not ip then return nil, fail(ierr, q) end local status, res = Decode.run(st, b, ip, q + psize, target) if not status then return nil, fail(res, q) end if status ~= "full" or st.op ~= target then return nil, Err.new(Err.CORRUPT, "LZMA2 chunk size mismatch", p) end p = q + psize else return nil, Err.new(Err.CORRUPT, "bad LZMA2 control byte " .. c, p) end end end function Lzma.lzma2(buf: buffer | string, offset: number?, length: number?, _dictSize: number?, unpackSize: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = args("Lzma.lzma2", buf, offset, length) if not b then return nil, aerr end local max = maxOf(opts) local st = Decode.new(if type(unpackSize) == "number" and unpackSize >= 0 then unpackSize else l * 4, max) local consumed, err = decodeLzma2(st, b, o, o + l) if not consumed then return nil, err end if type(unpackSize) == "number" and st.op ~= unpackSize then return nil, Err.new(Err.CORRUPT, string.format("LZMA2 output is %d bytes, expected %d", st.op, unpackSize)) end return Decode.finish(st), consumed end -- filter ids (xz numbering; 7z's method ids map onto these in archive/7z) Lzma.FILTER = table.freeze({ delta = 0x03, x86 = 0x04, powerpc = 0x05, ia64 = 0x06, arm = 0x07, armthumb = 0x08, sparc = 0x09, arm64 = 0x0A, riscv = 0x0B, lzma2 = 0x21, }) local BCJ: { [number]: (buffer, number, number, number) -> () } = { [0x04] = Filters.x86, [0x05] = Filters.powerpc, [0x07] = Filters.arm, [0x08] = Filters.armthumb, [0x09] = Filters.sparc, [0x0A] = Filters.arm64, } -- filter properties: BCJ start offset u32le, delta distance - 1 function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?): (boolean?, Err.Err?) local pb = toBuffer(props) local plen = if pb then buffer.len(pb) else 0 if id == 0x03 then if plen ~= 1 then return nil, Err.new(Err.CORRUPT, "bad delta filter properties") end Filters.delta(b, o, n, readu8(pb :: buffer, 0) + 1) return true, nil end local f = BCJ[id] if not f then return nil, Err.new(Err.UNSUPPORTED, string.format("filter 0x%x is not supported", id)) end local start = 0 if plen == 4 then start = readu32(pb :: buffer, 0) elseif plen ~= 0 then return nil, Err.new(Err.CORRUPT, "bad BCJ filter properties") end f(b, o, n, start) return true, nil end local XZ_MAGIC = "\253" .. "7zXZ\0" local CHECK_SIZE = { [0] = 0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64 } local function vli(b: buffer, p: number, e: number): (number?, number) local v, mul = 0, 1 for i = 0, 8 do if p + i >= e then return nil, p end local c = readu8(b, p + i) v += (c % 128) * mul if c < 128 then if c == 0 and i > 0 then return nil, p -- non-minimal encoding end return v, p + i + 1 end mul *= 128 end return nil, p end Lzma.vli = vli local function crc(b: buffer, o: number, n: number): number return Crc32.raw(b, o, n) end local function xzStream(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?) if o + 12 > e then return nil, Err.new(Err.TRUNCATED, "truncated xz stream header", o) end if buffer.readstring(b, o, 6) ~= XZ_MAGIC then return nil, Err.new(Err.CORRUPT, "bad xz magic", o) end if readu8(b, o + 6) ~= 0 or readu8(b, o + 7) > 15 then return nil, Err.new(Err.UNSUPPORTED, "unknown xz stream flags", o + 6) end if crc(b, o + 6, 2) ~= readu32(b, o + 8) then return nil, Err.new(Err.CHECKSUM, "xz stream header CRC-32 mismatch", o + 8) end local check = readu8(b, o + 7) local csize = CHECK_SIZE[check] local p = o + 12 local records: { { number } } = {} while true do if p >= e then return nil, Err.new(Err.TRUNCATED, "truncated xz block", p) end local hs = readu8(b, p) if hs == 0 then break -- the index end local hsize = (hs + 1) * 4 if p + hsize > e then return nil, Err.new(Err.TRUNCATED, "truncated xz block header", p) end if crc(b, p, hsize - 4) ~= readu32(b, p + hsize - 4) then return nil, Err.new(Err.CHECKSUM, "xz block header CRC-32 mismatch", p) end local flags = readu8(b, p + 1) if flags % 64 >= 4 then return nil, Err.new(Err.UNSUPPORTED, "reserved xz block flags", p + 1) end local nfilters = flags % 4 + 1 local q = p + 2 local he = p + hsize - 4 local csz, usz: number? = nil, nil if flags >= 128 or (flags // 64) % 2 == 1 then if (flags // 64) % 2 == 1 then local v v, q = vli(b, q, he) if not v or v == 0 then return nil, Err.new(Err.CORRUPT, "bad xz compressed size", q) end csz = v end if flags >= 128 then local v v, q = vli(b, q, he) if not v then return nil, Err.new(Err.CORRUPT, "bad xz uncompressed size", q) end usz = v end end local filters: { { id: number, props: buffer } } = {} for _ = 1, nfilters do local id, psz id, q = vli(b, q, he) if not id then return nil, Err.new(Err.CORRUPT, "bad xz filter flags", q) end psz, q = vli(b, q, he) if not psz or q + psz > he then return nil, Err.new(Err.CORRUPT, "bad xz filter properties", q) end local pr = buffer.create(psz) buffer.copy(pr, 0, b, q, psz) q += psz table.insert(filters, { id = id, props = pr }) end for k = q, he - 1 do if readu8(b, k) ~= 0 then return nil, Err.new(Err.CORRUPT, "nonzero xz block header padding", k) end end local last = filters[nfilters] if last.id ~= 0x21 or buffer.len(last.props) ~= 1 or readu8(last.props, 0) > 40 then return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter chain must end in LZMA2 (got 0x%x)", last.id), p) end for k = 1, nfilters - 1 do local id = filters[k].id if id ~= 0x03 and not BCJ[id] then return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter 0x%x is not supported", id), p) end end -- data local dstart = p + hsize local ostart = st.op local dend = if csz then dstart + csz else e if dend > e then return nil, Err.new(Err.TRUNCATED, "truncated xz block data", dstart) end local cend, derr = decodeLzma2(st, b, dstart, dend) if not cend then return nil, derr end if csz and cend ~= dend then return nil, Err.new(Err.CORRUPT, "xz compressed size mismatch", dstart) end local un = st.op - ostart if usz and un ~= usz then return nil, Err.new(Err.CORRUPT, "xz uncompressed size mismatch", dstart) end for k = nfilters - 1, 1, -1 do local ok, ferr = Lzma.filter(filters[k].id, st.out, ostart, un, filters[k].props) if not ok then return nil, ferr end end local unpadded = hsize + (cend - dstart) + csize local pe = cend while (pe - p) % 4 ~= 0 do if pe >= e then return nil, Err.new(Err.TRUNCATED, "truncated xz block padding", pe) end if readu8(b, pe) ~= 0 then return nil, Err.new(Err.CORRUPT, "nonzero xz block padding", pe) end pe += 1 end if pe + csize > e then return nil, Err.new(Err.TRUNCATED, "truncated xz check", pe) end if check == 1 then if crc(st.out, ostart, un) ~= readu32(b, pe) then return nil, Err.new(Err.CHECKSUM, "xz block CRC-32 mismatch", pe) end elseif check == 4 then local hi, lo = Crc64.of(st.out, ostart, un) if lo ~= readu32(b, pe) or hi ~= readu32(b, pe + 4) then return nil, Err.new(Err.CHECKSUM, "xz block CRC-64 mismatch", pe) end end table.insert(records, { unpadded, un }) p = pe + csize end -- index local ip = p local count, q = vli(b, p + 1, e) if not count or count ~= #records then return nil, Err.new(Err.CORRUPT, "xz index record count mismatch", p) end for i = 1, count do local a, u a, q = vli(b, q, e) if not a then return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) end u, q = vli(b, q, e) if not u then return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) end if a ~= records[i][1] or u ~= records[i][2] then return nil, Err.new(Err.CORRUPT, "xz index does not match the blocks", q) end end while (q - ip) % 4 ~= 0 do if q >= e or readu8(b, q) ~= 0 then return nil, Err.new(Err.CORRUPT, "bad xz index padding", q) end q += 1 end if q + 4 > e then return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) end if crc(b, ip, q - ip) ~= readu32(b, q) then return nil, Err.new(Err.CHECKSUM, "xz index CRC-32 mismatch", q) end q += 4 local isize = q - ip -- footer if q + 12 > e then return nil, Err.new(Err.TRUNCATED, "truncated xz stream footer", q) end if crc(b, q + 4, 6) ~= readu32(b, q) then return nil, Err.new(Err.CHECKSUM, "xz stream footer CRC-32 mismatch", q) end if (readu32(b, q + 4) + 1) * 4 ~= isize then return nil, Err.new(Err.CORRUPT, "xz backward size mismatch", q + 4) end if readu8(b, q + 8) ~= 0 or readu8(b, q + 9) ~= check or buffer.readstring(b, q + 10, 2) ~= "YZ" then return nil, Err.new(Err.CORRUPT, "bad xz stream footer", q + 8) end return q + 12, nil end function Lzma.xz(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = args("Lzma.xz", buf, offset, length) if not b then return nil, aerr end local e = o + l local st = Decode.new(l * 4, maxOf(opts)) local p = o local nstreams = 0 while true do local nxt, err = xzStream(st, b, p, e) if not nxt then return nil, err end nstreams += 1 p = nxt -- stream padding: zero bytes in multiples of 4 local z = p while z < e and readu8(b, z) == 0 do z += 1 end if z == e then if (z - p) % 4 ~= 0 then return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p) end p = z break end if (z - p) % 4 ~= 0 then return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p) end p = z end return Decode.finish(st), p end function Lzma.isXz(b: buffer, o: number?): boolean local off = o or 0 return off + 6 <= buffer.len(b) and buffer.readstring(b, off, 6) == XZ_MAGIC end return Lzma end __FILES["codecs/compress/Lzma/Crc64"] = @native function() -- codecs/compress/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), xz check type 4. -- Written from the xz file format specification; the 64-bit value is kept as two u32 halves (hi, lo). local band, bxor, rshift, lshift, bor = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift, bit32.bor local readu8 = buffer.readu8 local THI, TLO = table.create(256, 0), table.create(256, 0) for n = 0, 255 do local hi, lo = 0, n for _ = 1, 8 do local low = band(lo, 1) lo = bor(rshift(lo, 1), lshift(band(hi, 1), 31)) hi = rshift(hi, 1) if low ~= 0 then hi = bxor(hi, 0xC96C5795) lo = bxor(lo, 0xD7870F42) end end THI[n + 1], TLO[n + 1] = hi, lo end local Crc64 = {} @native function Crc64.of(b: buffer, o: number, n: number): (number, number) local hi, lo = 0xFFFFFFFF, 0xFFFFFFFF for i = o, o + n - 1 do local idx = band(bxor(lo, readu8(b, i)), 255) + 1 lo = bxor(TLO[idx], bor(rshift(lo, 8), lshift(band(hi, 255), 24))) hi = bxor(THI[idx], rshift(hi, 8)) end return bxor(hi, 0xFFFFFFFF), bxor(lo, 0xFFFFFFFF) end return Crc64 end __FILES["codecs/compress/Lzma/Decode"] = @native function() -- codecs/compress/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by LZMA (.lzma, 7z) and LZMA2. -- Follows the LZMA specification's reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain): probability layout, -- state transitions, distance / length decoding. local readu8, readu16, writeu8, writeu16 = buffer.readu8, buffer.readu16, buffer.writeu8, buffer.writeu16 local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local rshift, band = bit32.rshift, bit32.band -- probability offsets (u16 entries) local IS_MATCH = 0 -- 12 states x 16 pos states local IS_REP = 192 local IS_REP_G0 = 204 local IS_REP_G1 = 216 local IS_REP_G2 = 228 local IS_REP0_LONG = 240 -- 12 x 16 local POS_SLOT = 432 -- 4 x 64 local SPEC_POS = 688 -- 115 local ALIGN = 803 -- 16 local LEN = 819 -- choice, choice2, low 16 x 8, mid 16 x 8, high 256 local REP_LEN = 1333 local LITERAL = 1847 -- 0x300 << (lc + lp) local TOP = 16777216 -- 2^24 local Decode = {} type State = { out: buffer, cap: number, op: number, dictStart: number, maxBytes: number, probs: buffer, nprobs: number, lc: number, lp: number, pb: number, state: number, rep0: number, rep1: number, rep2: number, rep3: number, remLen: number, range: number, code: number, } @native function Decode.new(cap: number, maxBytes: number): State local c = math.max(64, math.min(cap, maxBytes)) return { out = bcreate(c), cap = c, op = 0, dictStart = 0, maxBytes = maxBytes, probs = bcreate(2), nprobs = 0, lc = 0, lp = 0, pb = 0, state = 0, rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0, remLen = 0, range = 0xFFFFFFFF, code = 0, } end @native function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolean, string?) if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then return false, "bad lc / lp / pb" end st.lc, st.lp, st.pb = lc, lp, pb local n = LITERAL + 0x300 * 2 ^ (lc + lp) if blen(st.probs) < n * 2 then st.probs = bcreate(n * 2) end st.nprobs = n Decode.resetState(st) return true, nil end @native function Decode.resetState(st: State) local p = st.probs for i = 0, st.nprobs - 1 do writeu16(p, i * 2, 1024) end st.state = 0 st.rep0, st.rep1, st.rep2, st.rep3 = 0, 0, 0, 0 st.remLen = 0 end @native function Decode.resetDict(st: State) st.dictStart = st.op st.remLen = 0 end @native function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?, string?) if ip + 5 > iend then return nil, "truncated range coder init" end if readu8(b, ip) ~= 0 then return nil, "bad range coder init byte" end st.code = readu8(b, ip + 1) * 16777216 + readu8(b, ip + 2) * 65536 + readu8(b, ip + 3) * 256 + readu8(b, ip + 4) st.range = 0xFFFFFFFF if st.code == st.range then return nil, "bad range coder init" end return ip + 5, nil end @native local function ensure(st: State, need: number): boolean if need <= st.cap then return true end if need > st.maxBytes then return false end local c = math.min(math.max(st.cap * 2, need, 65536), st.maxBytes) local nb = bcreate(c) bcopy(nb, 0, st.out, 0, st.op) st.out = nb st.cap = c return true end Decode.ensure = ensure @native function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, string?) if not ensure(st, st.op + n) then return false, "limit: output over maxBytes" end bcopy(st.out, st.op, b, ip, n) st.op += n return true, nil end -- module upvalues, so LuaJIT traces stay valid across calls (run() is not re-entrant) local EMPTY = bcreate(2) local probs: buffer = EMPTY local inb: buffer = EMPTY local range, code, ip, iend, over = 0, 0, 0, 0, 0 @native local function bit(i: number): number local p = i * 2 local prob = readu16(probs, p) local bound = rshift(range, 11) * prob local r if code < bound then range = bound writeu16(probs, p, prob + rshift(2048 - prob, 5)) r = 0 else range -= bound code -= bound writeu16(probs, p, prob - rshift(prob, 5)) r = 1 end if range < TOP then range *= 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code *= 256 over += 1 end ip += 1 end return r end @native local function tree(base: number, nbits: number): number local m = 1 for _ = 1, nbits do m = m * 2 + bit(base + m) end return m - 2 ^ nbits end @native local function reverse(base: number, nbits: number): number local m = 1 local sym = 0 for i = 0, nbits - 1 do local b = bit(base + m) m = m * 2 + b sym += b * 2 ^ i end return sym end @native local function direct(nbits: number): number local res = 0 for _ = 1, nbits do range = rshift(range, 1) local b = 0 if code >= range then code -= range b = 1 end res = res * 2 + b if range < TOP then range *= 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code *= 256 over += 1 end ip += 1 end end return res end @native local function length(base: number, posState: number): number if bit(base) == 0 then return tree(base + 2 + posState * 8, 3) end if bit(base + 1) == 0 then return 8 + tree(base + 130 + posState * 8, 3) end return 16 + tree(base + 258, 8) end @native function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: number): (string?, any) probs = st.probs inb = inb0 iend = iend0 local out = st.out local cap = st.cap local op = st.op local dictStart = st.dictStart range, code = st.range, st.code ip = ip0 over = 0 local state = st.state local rep0, rep1, rep2, rep3 = st.rep0, st.rep1, st.rep2, st.rep3 local lc = st.lc local lcShift = 2 ^ (8 - lc) local lpMask = 2 ^ st.lp - 1 local pbMask = 2 ^ st.pb - 1 local lcMul = 2 ^ lc local status: string? = nil local msg: string? = nil local remLen = st.remLen if remLen > 0 then local n = math.min(remLen, outEnd - op) if n > 0 then if op + n > cap then st.op = op if not ensure(st, op + n) then probs, inb = EMPTY, EMPTY return nil, "limit: output over maxBytes" end out, cap = st.out, st.cap end local src = op - rep0 - 1 for k = 0, n - 1 do writeu8(out, op + k, readu8(out, src + k)) end op += n remLen -= n end end while true do if op >= outEnd then status = "full" break end if over > 0 then msg = "truncated" break end if op + 273 > cap then st.op = op if not ensure(st, math.min(op + 273, outEnd)) then msg = "limit: output over maxBytes" break end out, cap = st.out, st.cap end local pos = op - dictStart local posState = band(pos, pbMask) -- is match? (inlined bit) local pidx = (IS_MATCH + state * 16 + posState) * 2 local prob = readu16(probs, pidx) local bound = rshift(range, 11) * prob if code < bound then range = bound writeu16(probs, pidx, prob + rshift(2048 - prob, 5)) if range < TOP then range *= 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code *= 256 over += 1 end ip += 1 end -- literal local prev = if op > dictStart then readu8(out, op - 1) else 0 local base = LITERAL + 0x300 * (band(pos, lpMask) * lcMul + prev // lcShift) local sym = 1 if state >= 7 then local mpos = op - rep0 - 1 local matchByte = if mpos >= dictStart then readu8(out, mpos) else 0 repeat local matchBit = band(rshift(matchByte, 7), 1) matchByte *= 2 local b = bit(base + (1 + matchBit) * 256 + sym) sym = sym * 2 + b if matchBit ~= b then break end until sym >= 256 end while sym < 256 do local p2 = (base + sym) * 2 local pr = readu16(probs, p2) local bd = rshift(range, 11) * pr if code < bd then range = bd writeu16(probs, p2, pr + rshift(2048 - pr, 5)) sym = sym * 2 else range -= bd code -= bd writeu16(probs, p2, pr - rshift(pr, 5)) sym = sym * 2 + 1 end if range < TOP then range *= 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code *= 256 over += 1 end ip += 1 end end writeu8(out, op, sym - 256) op += 1 state = if state < 4 then 0 elseif state < 10 then state - 3 else state - 6 else range -= bound code -= bound writeu16(probs, pidx, prob - rshift(prob, 5)) if range < TOP then range *= 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code *= 256 over += 1 end ip += 1 end local len if bit(IS_REP + state) == 0 then -- simple match len = length(LEN, posState) state = if state < 7 then 7 else 10 rep3, rep2, rep1 = rep2, rep1, rep0 local lenState = if len < 3 then len else 3 local slot = tree(POS_SLOT + lenState * 64, 6) if slot < 4 then rep0 = slot else local nd = slot // 2 - 1 local dist = (2 + slot % 2) * 2 ^ nd if slot < 14 then dist += reverse(SPEC_POS + dist - slot, nd) else dist += direct(nd - 4) * 16 dist += reverse(ALIGN, 4) end rep0 = dist end if rep0 == 0xFFFFFFFF then status = "eos" break end else if bit(IS_REP_G0 + state) == 0 then if bit(IS_REP0_LONG + state * 16 + posState) == 0 then -- short rep: one byte at rep0 if op == dictStart or rep0 >= op - dictStart then msg = "distance past the dictionary start" break end state = if state < 7 then 9 else 11 writeu8(out, op, readu8(out, op - rep0 - 1)) op += 1 continue end else local dist if bit(IS_REP_G1 + state) == 0 then dist = rep1 else if bit(IS_REP_G2 + state) == 0 then dist = rep2 else dist = rep3 rep3 = rep2 end rep2 = rep1 end rep1 = rep0 rep0 = dist end len = length(REP_LEN, posState) state = if state < 7 then 8 else 11 end -- copy len + 2 bytes from rep0 + 1 back if rep0 >= op - dictStart then msg = "distance past the dictionary start" break end local n = len + 2 local room = outEnd - op if n > room then remLen = n - room n = room end local src = op - rep0 - 1 if rep0 + 1 >= n then bcopy(out, op, out, src, n) else for k = 0, n - 1 do writeu8(out, op + k, readu8(out, src + k)) end end op += n end end st.op = op st.range, st.code = range, code st.state = state st.rep0, st.rep1, st.rep2, st.rep3 = rep0, rep1, rep2, rep3 st.remLen = remLen probs, inb = EMPTY, EMPTY if msg then return nil, msg end if over > 0 then return nil, "truncated" end return status, ip end @native function Decode.finish(st: State): buffer if st.cap == st.op then return st.out end local b = bcreate(st.op) bcopy(b, 0, st.out, 0, st.op) return b end return Decode end __FILES["codecs/compress/Lzma/Filters"] = @native function() -- codecs/compress/Lzma/Filters: the xz / 7z branch-call-jump (BCJ) and delta decoding filters, in place. -- From the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin, public domain). local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 local band, bor, bxor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.bxor, bit32.rshift, bit32.lshift, bit32.byteswap local TWO32 = 4294967296 local Filters = {} local MASK_ALLOWED = { [0] = true, true, true, false, true, false, false, false } local MASK_BITNUM = { [0] = 0, 1, 2, 2, 3, 3, 3, 3 } @native local function msbyte(b: number): boolean return b == 0 or b == 0xFF end @native function Filters.x86(b: buffer, o: number, n: number, start: number) if n <= 4 then return end local size = n - 4 local prevPos = -1 local prevMask = 0 local i = 0 while i < size do local c = readu8(b, o + i) if band(c, 0xFE) ~= 0xE8 then i += 1 continue end local d = i - prevPos if d > 3 then prevMask = 0 else prevMask = band(lshift(prevMask, d - 1), 7) if prevMask ~= 0 then local bb = readu8(b, o + i + 4 - MASK_BITNUM[prevMask]) if not MASK_ALLOWED[prevMask] or msbyte(bb) then prevPos = i prevMask = bor(lshift(prevMask, 1), 1) i += 1 continue end end end prevPos = i if msbyte(readu8(b, o + i + 4)) then local src = readu32(b, o + i + 1) local dest while true do dest = (src - (start + i + 5)) % TWO32 if prevMask == 0 then break end local j = MASK_BITNUM[prevMask] * 8 local bb = band(rshift(dest, 24 - j), 0xFF) if not msbyte(bb) then break end src = bxor(dest, 2 ^ (32 - j) - 1) end dest = band(dest, 0x01FFFFFF) if band(dest, 0x01000000) ~= 0 then dest = bor(dest, 0xFF000000) end writeu32(b, o + i + 1, dest) i += 5 else prevMask = bor(lshift(prevMask, 1), 1) i += 1 end end end @native function Filters.arm(b: buffer, o: number, n: number, start: number) local i = 0 while i + 4 <= n do if readu8(b, o + i + 3) == 0xEB then local addr = readu8(b, o + i) + readu8(b, o + i + 1) * 256 + readu8(b, o + i + 2) * 65536 addr = (addr * 4 - (start + i + 8)) % TWO32 addr = rshift(addr, 2) writeu8(b, o + i, band(addr, 255)) writeu8(b, o + i + 1, band(rshift(addr, 8), 255)) writeu8(b, o + i + 2, band(rshift(addr, 16), 255)) end i += 4 end end @native function Filters.armthumb(b: buffer, o: number, n: number, start: number) local i = 0 while i + 4 <= n do local b1, b3 = readu8(b, o + i + 1), readu8(b, o + i + 3) if band(b1, 0xF8) == 0xF0 and band(b3, 0xF8) == 0xF8 then local addr = band(b1, 7) * 524288 + readu8(b, o + i) * 2048 + band(b3, 7) * 256 + readu8(b, o + i + 2) addr = (addr * 2 - (start + i + 4)) % TWO32 addr = rshift(addr, 1) writeu8(b, o + i + 1, bor(0xF0, band(rshift(addr, 19), 7))) writeu8(b, o + i, band(rshift(addr, 11), 255)) writeu8(b, o + i + 3, bor(0xF8, band(rshift(addr, 8), 7))) writeu8(b, o + i + 2, band(addr, 255)) i += 4 else i += 2 end end end @native function Filters.powerpc(b: buffer, o: number, n: number, start: number) local i = 0 while i + 4 <= n do local instr = byteswap(readu32(b, o + i)) if band(instr, 0xFC000003) == 0x48000001 then instr = band(instr, 0x03FFFFFC) instr = band((instr - (start + i)) % TWO32, 0x03FFFFFC) instr = bor(instr, 0x48000001) writeu32(b, o + i, byteswap(instr)) end i += 4 end end @native function Filters.sparc(b: buffer, o: number, n: number, start: number) local i = 0 while i + 4 <= n do local instr = byteswap(readu32(b, o + i)) local top = rshift(instr, 22) if top == 0x100 or top == 0x1FF then instr = (instr * 4) % TWO32 instr = (instr - (start + i)) % TWO32 instr = rshift(instr, 2) instr = bor((0x40000000 - band(instr, 0x400000)) % TWO32, 0x40000000, band(instr, 0x3FFFFF)) writeu32(b, o + i, byteswap(instr)) end i += 4 end end @native function Filters.arm64(b: buffer, o: number, n: number, start: number) local i = 0 while i + 4 <= n do local pc = (start + i) % TWO32 local instr = readu32(b, o + i) if rshift(instr, 26) == 0x25 then local src = instr local p = (TWO32 - rshift(pc, 2)) % TWO32 writeu32(b, o + i, bor(0x94000000, band((src + p) % TWO32, 0x03FFFFFF))) elseif band(instr, 0x9F000000) == 0x90000000 then local src = bor(band(rshift(instr, 29), 3), band(rshift(instr, 3), 0x001FFFFC)) if band(src + 0x00020000, 0x001C0000) == 0 then local p = (TWO32 - rshift(pc, 12)) % TWO32 local dest = (src + p) % TWO32 local v = band(instr, 0x9000001F) v = bor(v, lshift(band(dest, 3), 29)) v = bor(v, lshift(band(dest, 0x0003FFFC), 3)) v = bor(v, band((TWO32 - band(dest, 0x00020000)) % TWO32, 0x00E00000)) writeu32(b, o + i, v) end end i += 4 end end -- delta filter: b[i] += b[i - dist] (1 <= dist <= 256) @native function Filters.delta(b: buffer, o: number, n: number, dist: number) for i = dist, n - 1 do writeu8(b, o + i, band(readu8(b, o + i) + readu8(b, o + i - dist), 255)) end end return Filters end __FILES["codecs/compress/Lzw"] = @native function() -- codecs/compress/Lzw: LZW decoder and encoder, from the GIF89a spec (appendix F) and TIFF 6.0 section 13 (new code). -- gif: LSB-first, clear = 2^min, EOI = clear + 1, width grows when the next code reaches 2^width (max 12, then frozen). -- tiff: MSB-first, clear = 256, EOI = 257, early change (at 2^width - 1). zoo (method 1): gif layout, up to 13 bits. local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16 local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local blen = buffer.len local Lzw = {} local MAX_CODES = 4096 -- 12-bit codes (GIF, TIFF) local TABLE = 8192 -- the tables hold 13-bit codes (Zoo) local prefix = buffer.create(TABLE * 2) local suffix = buffer.create(TABLE) local first = buffer.create(TABLE) local length = buffer.create(TABLE * 2) @native local function emit(out: buffer, o: number, c: number, l: number, lim: number) local p = o + l - 1 if p < lim then while p >= o do writeu8(out, p, readu8(suffix, c)) c = readu16(prefix, c * 2) p -= 1 end else while p >= o do if p < lim then writeu8(out, p, readu8(suffix, c)) end c = readu16(prefix, c * 2) p -= 1 end end end @native function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff: number, maxOut: number, variant: string, minCodeSize: number?): (number, string?) local n = blen(src) if off < 0 or off > n then return 0, "corrupt" end local e = math.min(off + math.max(0, len), n) local lim = math.min(outOff + math.max(0, maxOut), blen(out)) if outOff < 0 then return 0, "corrupt" end local msb = variant == "tiff" local early = 0 local min = minCodeSize or 8 local maxCodes, maxBits = MAX_CODES, 12 if variant == "zoo" then min, maxCodes, maxBits = 8, TABLE, 13 end if msb then min = 8 early = 1 -- old-style TIFF LZW: LSB-first, no early change (libtiff LZWPreDecode's check) if e - off >= 2 and readu8(src, off) == 0 and band(readu8(src, off + 1), 1) == 1 then msb = false early = 0 end end if min < 1 or min > 11 then return 0, "corrupt" end local clear = lshift(1, min) local eoi = clear + 1 for i = 0, clear - 1 do writeu16(prefix, i * 2, 0) writeu8(suffix, i, band(i, 255)) writeu8(first, i, band(i, 255)) writeu16(length, i * 2, 1) end local size = min + 1 local mask = lshift(1, size) - 1 local nextc = clear + 2 local prev = -1 local o = outOff local p = off local acc, nb = 0, 0 while true do while nb < size do if p >= e then return o - outOff, "truncated" end if msb then acc = acc * 256 + readu8(src, p) else acc += lshift(readu8(src, p), nb) end p += 1 nb += 8 end local c if msb then nb -= size c = band(rshift(acc, nb), mask) acc = band(acc, lshift(1, nb) - 1) else c = band(acc, mask) acc = rshift(acc, size) nb -= size end if c == clear then size = min + 1 mask = lshift(1, size) - 1 nextc = clear + 2 prev = -1 elseif c == eoi then return o - outOff, nil else if o >= lim then return o - outOff, nil end if prev < 0 then if c >= clear then return o - outOff, "corrupt" end writeu8(out, o, readu8(suffix, c)) o += 1 prev = c else local l if c < nextc then l = readu16(length, c * 2) emit(out, o, c, l, lim) if nextc < maxCodes then writeu16(prefix, nextc * 2, prev) writeu8(suffix, nextc, readu8(first, c)) writeu8(first, nextc, readu8(first, prev)) writeu16(length, nextc * 2, readu16(length, prev * 2) + 1) nextc += 1 end elseif c == nextc and nextc < maxCodes then -- KwKwK: the new entry is prev + first(prev) local f = readu8(first, prev) writeu16(prefix, nextc * 2, prev) writeu8(suffix, nextc, f) writeu8(first, nextc, f) l = readu16(length, prev * 2) + 1 writeu16(length, nextc * 2, l) nextc += 1 emit(out, o, c, l, lim) else return o - outOff, "corrupt" end o = math.min(o + l, lim) prev = c end if nextc + early >= lshift(1, size) and size < maxBits then size += 1 mask = lshift(1, size) - 1 end end end end local HASH = 8192 local hkey = buffer.create(HASH * 4) local hval = buffer.create(HASH * 2) @native function Lzw.encode(data: buffer, off: number, len: number, variant: string, minCodeSize: number?): buffer local msb = variant == "tiff" local min = if msb then 8 else math.clamp(minCodeSize or 8, 1, 11) local early = if msb then 1 else 0 local symMask = lshift(1, min) - 1 local clear = lshift(1, min) local eoi = clear + 1 local n = blen(data) off = math.clamp(off, 0, n) local e = math.clamp(off + len, off, n) local cap = (e - off) * 2 + 64 local out = buffer.create(cap) local op = 0 local acc, nb = 0, 0 local size = min + 1 @native local function put(code: number) if op + 4 > cap then cap *= 2 local nbuf = buffer.create(cap) buffer.copy(nbuf, 0, out, 0, op) out = nbuf end if msb then acc = acc * lshift(1, size) + code nb += size while nb >= 8 do nb -= 8 writeu8(out, op, rshift(acc, nb)) op += 1 acc = band(acc, lshift(1, nb) - 1) end else acc += lshift(code, nb) nb += size while nb >= 8 do writeu8(out, op, band(acc, 255)) op += 1 acc = rshift(acc, 8) nb -= 8 end end end buffer.fill(hkey, 0, 0, HASH * 4) local nextc = clear + 2 put(clear) if e > off then local cur = band(readu8(data, off), symMask) for i = off + 1, e - 1 do local b = band(readu8(data, i), symMask) local key = cur * 256 + b + 1 local h = band(cur * 31 + b * 4099, HASH - 1) local found = -1 while true do local k = buffer.readi32(hkey, h * 4) if k == 0 then break elseif k == key then found = readu16(hval, h * 2) break end h = band(h + 1, HASH - 1) end if found >= 0 then cur = found else put(cur) if nextc >= MAX_CODES - 2 then put(clear) size = min + 1 nextc = clear + 2 buffer.fill(hkey, 0, 0, HASH * 4) else buffer.writei32(hkey, h * 4, key) writeu16(hval, h * 2, nextc) nextc += 1 if nextc + early > lshift(1, size) and size < 12 then size += 1 end end cur = b end end put(cur) -- the decoder adds an entry for this last code too: its width may grow before EOI if nextc < MAX_CODES then nextc += 1 if nextc + early > lshift(1, size) and size < 12 then size += 1 end end end put(eoi) if nb > 0 then writeu8(out, op, if msb then band(lshift(acc, 8 - nb), 255) else band(acc, 255)) op += 1 end local res = buffer.create(op) buffer.copy(res, 0, out, 0, op) return res end return Lzw end __FILES["codecs/compress/Lzx"] = @native function() -- codecs/compress/Lzx: the LZX decoder for Microsoft Cabinet folders (windows of 2^15 .. 2^21 bytes). -- Written from Microsoft's LZX data format documentation (Cabinet SDK) and [MS-PATCH]; no code from libmspack. -- Frames of 32768 output bytes, 16-bit aligned at their ends; trees, R0..R2 and the window persist across a folder. local Huffman = __include("codecs/entropy/Huffman") local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32 local writeu8, writei32 = buffer.writeu8, buffer.writei32 local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local Lzx = {} local FRAME = 32768 local MAINP, LENP, ALIGNP, PREP = 10, 8, 7, 6 local MAXMAIN = 256 + 8 * 50 local NLEN = 249 local SAFETY = 64 -- pre-tree runs may run past the end of a tree: room for them (as the format's reference decoder) -- position slots: footer bits and base of each formatted offset slot local EXTRA = table.create(51, 0) local BASE = table.create(51, 0) do local b = 0 for i = 0, 50 do local e = if i < 4 then 0 else math.min(i // 2 - 1, 17) EXTRA[i + 1] = e BASE[i + 1] = b b += lshift(1, e) end end local SLOTS: { [number]: number } = { [15] = 30, [16] = 32, [17] = 34, [18] = 36, [19] = 38, [20] = 42, [21] = 50 } -- 16-bit little-endian words, read most significant bit first type State = { src: buffer, pos: number, stop: number, bb: number, cnt: number, over: number } @native local function refill(s: State) while s.cnt <= 16 do local p = s.pos local w = 0 if p + 2 <= s.stop then w = readu16(s.src, p) s.pos = p + 2 elseif p < s.stop then w = readu8(s.src, p) s.pos = p + 1 s.over += 8 else s.over += 16 end s.bb = bor(s.bb, lshift(w, 16 - s.cnt)) s.cnt += 16 end end @native local function bits(s: State, n: number): number if s.cnt < n then refill(s) end local v = rshift(s.bb, 32 - n) s.bb = lshift(s.bb, n) s.cnt -= n return v end @native local function sym(s: State, tab: buffer, P: number, S: number): number if s.cnt < 16 then refill(s) end local e = readu32(tab, rshift(s.bb, 32 - P) * 4) local l = band(e, 31) if l == 0 then if e == 0 then return -1 end e = readu32(tab, (rshift(e, 5) + band(rshift(s.bb, 32 - P - S), lshift(1, S) - 1)) * 4) l = band(e, 31) if l == 0 then return -1 end end s.bb = lshift(s.bb, l) s.cnt -= l return rshift(e, 5) end -- code lengths as deltas of their previous values, through a fresh 20-symbol pre-tree (runs 17 / 18 / 19) @native local function readLens(s: State, lens: buffer, first: number, last: number, pre: buffer, preLens: buffer): boolean for i = 0, 19 do writeu8(preLens, i, bits(s, 4)) end local S = Huffman.buildMsb(preLens, 0, 20, pre, PREP) if S < 0 then return false end local cap = blen(lens) local x = first while x < last do local z = sym(s, pre, PREP, S) if z < 0 then return false end if z == 17 or z == 18 then local run = if z == 17 then bits(s, 4) + 4 else bits(s, 5) + 20 for _ = 1, run do if x < cap then writeu8(lens, x, 0) end x += 1 end elseif z == 19 then local run = bits(s, 1) + 4 local d = sym(s, pre, PREP, S) if d < 0 or d > 16 then return false end local v = (readu8(lens, x) - d + 17) % 17 for _ = 1, run do if x < cap then writeu8(lens, x, v) end x += 1 end else writeu8(lens, x, (readu8(lens, x) - z + 17) % 17) x += 1 end end return true end -- E8 translation, frame by frame: absolute call targets back to relative @native local function translate(out: buffer, n: number, size: number) local base = 0 local frame = 0 while base < n and frame < 32768 do local fs = math.min(FRAME, n - base) if fs > 10 then local i = base local stop = base + fs - 10 while i < stop do if readu8(out, i) == 0xE8 then local abs = readi32(out, i + 1) if abs >= -i and abs < size then writei32(out, i + 1, if abs >= 0 then abs - i else abs + size) end i += 5 else i += 1 end end end base += fs frame += 1 end end @native function Lzx.decode(src: buffer, offset: number, length: number, outSize: number, windowBits: number): (buffer?, string?) local nslots = SLOTS[windowBits] if not nslots then return nil, "unsupported: LZX window 2^" .. tostring(windowBits) end if offset < 0 or length < 0 or offset + length > blen(src) or outSize < 0 or outSize % 1 ~= 0 then return nil, "bad arguments" end local windowSize = lshift(1, windowBits) local mainN = 256 + 8 * nslots local out = bcreate(outSize) local mainLens, lenLens, alignLens, preLens = bcreate(MAXMAIN + SAFETY), bcreate(NLEN + SAFETY), bcreate(8), bcreate(20) local mainTab = bcreate(Huffman.capacity(MAXMAIN, MAINP, 16) * 4) local lenTab = bcreate(Huffman.capacity(NLEN, LENP, 16) * 4) local alignTab = bcreate(Huffman.capacity(8, ALIGNP, 16) * 4) local preTab = bcreate(Huffman.capacity(20, PREP, 16) * 4) local s: State = { src = src, pos = offset, stop = offset + length, bb = 0, cnt = 0, over = 0 } local R0: number, R1: number, R2: number = 1, 1, 1 local intel = 0 local started = false local btype, bremain, bsize = 0, 0, 0 local mainS, lenS, alignS = 0, 0, 0 local op = 0 while op < outSize do local frameEnd = math.min(op + FRAME, outSize) while op < frameEnd do if bremain == 0 then if btype == 3 and band(bsize, 1) == 1 then s.pos += 1 end if not started then started = true if bits(s, 1) == 1 then local hi = bits(s, 16) intel = hi * 65536 + bits(s, 16) end end btype = bits(s, 3) local hi = bits(s, 16) bsize = hi * 256 + bits(s, 8) bremain = bsize if s.over > s.cnt then return nil, "truncated input" end if bsize == 0 then return nil, "empty block" end if btype == 2 then for i = 0, 7 do writeu8(alignLens, i, bits(s, 3)) end alignS = Huffman.buildMsb(alignLens, 0, 8, alignTab, ALIGNP) if alignS < 0 then return nil, "bad aligned offset tree" end end if btype == 1 or btype == 2 then if not readLens(s, mainLens, 0, 256, preTab, preLens) or not readLens(s, mainLens, 256, mainN, preTab, preLens) then return nil, "bad main tree" end mainS = Huffman.buildMsb(mainLens, 0, mainN, mainTab, MAINP) if mainS < 0 then return nil, "bad main tree" end if not readLens(s, lenLens, 0, NLEN, preTab, preLens) then return nil, "bad length tree" end lenS = Huffman.buildMsb(lenLens, 0, NLEN, lenTab, LENP) if lenS < 0 then return nil, "bad length tree" end elseif btype == 3 then -- 1..16 bits of padding to a 16-bit boundary, then R0..R2 and the bytes local k = s.cnt % 16 if k == 0 then k = 16 end local p = s.pos - (s.cnt - k) // 8 s.bb, s.cnt = 0, 0 if s.over > 0 or p + 12 > s.stop then return nil, "truncated uncompressed block" end R0 = readu32(src, p) R1 = readu32(src, p + 4) R2 = readu32(src, p + 8) s.pos = p + 12 else return nil, "bad block type " .. btype end if s.over > s.cnt then return nil, "truncated input" end end local runEnd = op + math.min(bremain, frameEnd - op) if btype == 3 then local n = runEnd - op local p = s.pos if p + n > s.stop then return nil, "truncated uncompressed block" end bcopy(out, op, src, p, n) s.pos = p + n op += n bremain -= n else local bb, cnt, pos, over = s.bb, s.cnt, s.pos, s.over local stop = s.stop local aligned = btype == 2 local start = op while op < runEnd do while cnt <= 16 do local w = 0 if pos + 2 <= stop then w = readu16(src, pos) pos += 2 elseif pos < stop then w = readu8(src, pos) pos += 1 over += 8 else over += 16 end bb = bor(bb, lshift(w, 16 - cnt)) cnt += 16 end local e = readu32(mainTab, rshift(bb, 32 - MAINP) * 4) local l = band(e, 31) if l == 0 then if e == 0 then return nil, "bad main code" end e = readu32(mainTab, (rshift(e, 5) + band(rshift(bb, 32 - MAINP - mainS), lshift(1, mainS) - 1)) * 4) l = band(e, 31) if l == 0 then return nil, "bad main code" end end bb = lshift(bb, l) cnt -= l local m = rshift(e, 5) if m < 256 then writeu8(out, op, m) op += 1 else m -= 256 local len = band(m, 7) if len == 7 then while cnt <= 16 do local w = 0 if pos + 2 <= stop then w = readu16(src, pos) pos += 2 else over += 16 end bb = bor(bb, lshift(w, 16 - cnt)) cnt += 16 end local le = readu32(lenTab, rshift(bb, 32 - LENP) * 4) local ll = band(le, 31) if ll == 0 then if le == 0 then return nil, "bad length code" end le = readu32(lenTab, (rshift(le, 5) + band(rshift(bb, 32 - LENP - lenS), lshift(1, lenS) - 1)) * 4) ll = band(le, 31) if ll == 0 then return nil, "bad length code" end end bb = lshift(bb, ll) cnt -= ll len += rshift(le, 5) end len += 2 local slot = rshift(m, 3) local dist: number if slot == 0 then dist = R0 elseif slot == 1 then dist = R1 R1 = R0 R0 = dist elseif slot == 2 then dist = R2 R2 = R0 R0 = dist else local ex = EXTRA[slot + 1] dist = BASE[slot + 1] - 2 if ex > 0 then while cnt <= 16 do local w = 0 if pos + 2 <= stop then w = readu16(src, pos) pos += 2 else over += 16 end bb = bor(bb, lshift(w, 16 - cnt)) cnt += 16 end if aligned and ex >= 3 then if ex > 3 then dist += lshift(rshift(bb, 35 - ex), 3) bb = lshift(bb, ex - 3) cnt -= ex - 3 while cnt <= 16 do local w = 0 if pos + 2 <= stop then w = readu16(src, pos) pos += 2 else over += 16 end bb = bor(bb, lshift(w, 16 - cnt)) cnt += 16 end end local ae = readu32(alignTab, rshift(bb, 32 - ALIGNP) * 4) local al = band(ae, 31) if al == 0 then return nil, "bad aligned offset code" end bb = lshift(bb, al) cnt -= al dist += rshift(ae, 5) else dist += rshift(bb, 32 - ex) bb = lshift(bb, ex) cnt -= ex end end R2 = R1 R1 = R0 R0 = dist end if dist < 1 or dist > op or dist > windowSize then return nil, "match offset before the start of the data" end if op + len > runEnd then return nil, "match past the end of its block or frame" end local from = op - dist if dist >= len then bcopy(out, op, out, from, len) else for k = 0, len - 1 do writeu8(out, op + k, readu8(out, from + k)) end end op += len end end s.bb, s.cnt, s.pos, s.over = bb, cnt, pos, over bremain -= op - start end end -- the end of a frame: realign to 16 bits local k = s.cnt % 16 s.bb = lshift(s.bb, k) s.cnt -= k if s.over > s.cnt then return nil, "truncated input" end end if intel ~= 0 then translate(out, outSize, intel) end return out, nil end return Lzx end __FILES["codecs/compress/PackBits"] = @native function() -- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD RLE, IFF ByteRun1). -- Header byte n < 128 copies n + 1 literal bytes, n > 128 repeats the next byte 257 - n times, 128 is a no-op. local PackBits = {} local readu8, writeu8 = buffer.readu8, buffer.writeu8 @native function PackBits.decode(src: buffer, p: number, limit: number, dst: buffer, d: number, n: number): (number, number, boolean) local o, lim = d, d + n local clean = true while o < lim do if p >= limit then clean = false break end local h = readu8(src, p) p += 1 if h < 128 then local want = h + 1 local cnt = math.min(want, limit - p, lim - o) if cnt < want then clean = false end if cnt > 0 then buffer.copy(dst, o, src, p, cnt) o += cnt end p += want if p > limit then p = limit break end elseif h > 128 then if p >= limit then clean = false break end local want = 257 - h local cnt = math.min(want, lim - o) if cnt < want then clean = false end buffer.fill(dst, o, readu8(src, p), cnt) p += 1 o += cnt end end return o - d, p, clean end @native function PackBits.encode(src: buffer, off: number, len: number): buffer local out = buffer.create(len + (len + 127) // 128 + 8) local o = 0 local p, e = off, off + len while p < e do local run = 1 local v = readu8(src, p) while p + run < e and run < 128 and readu8(src, p + run) == v do run += 1 end if run >= 3 then writeu8(out, o, 257 - run) writeu8(out, o + 1, v) o += 2 p += run else local s = p local n = 0 while p < e and n < 128 do if p + 2 < e and readu8(src, p) == readu8(src, p + 1) and readu8(src, p) == readu8(src, p + 2) then break end p += 1 n += 1 end writeu8(out, o, n - 1) buffer.copy(out, o + 1, src, s, n) o += n + 1 end end local r = buffer.create(o) buffer.copy(r, 0, out, 0, o) return r end return PackBits end __FILES["codecs/compress/Quantum"] = @native function() -- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 + adaptive arithmetic coder) for Cabinet folders. -- Written from Matthew Russotto's Quantum notes and the cabinet documentation; no code from libmspack. Frequencies grow -- by 8 and rescale above 3800 (halved; every 50th time rebuilt and re-sorted); each CFDATA frame restarts the coder. local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu8, writeu8 = buffer.readu8, buffer.writeu8 local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local floor = math.floor local Quantum = {} -- position slots (offset - 1 = base + footer) and length slots (length - 5 = base + footer) local PBASE = table.create(42, 0) local PEXTRA = table.create(42, 0) do local b = 0 for i = 0, 41 do local e = if i < 4 then 0 else i // 2 - 1 PEXTRA[i + 1] = e PBASE[i + 1] = b b += lshift(1, e) end end local LEXTRA = { 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } local LBASE = table.create(27, 0) do local b = 0 for i = 1, 27 do LBASE[i] = b b += lshift(1, LEXTRA[i]) end end -- model: sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0) type Model = { n: number, sym: { number }, cum: { number }, shifts: number } @native local function model(first: number, n: number): Model local sym = table.create(n, 0) local cum = table.create(n + 1, 0) for i = 1, n do sym[i] = first + i - 1 cum[i] = n - i + 1 end cum[n + 1] = 0 return { n = n, sym = sym, cum = cum, shifts = 4 } end @native local function rescale(m: Model) local n, sym, cum = m.n, m.sym, m.cum m.shifts -= 1 if m.shifts > 0 then for i = n, 1, -1 do local c = rshift(cum[i], 1) if c <= cum[i + 1] then c = cum[i + 1] + 1 end cum[i] = c end return end m.shifts = 50 -- cumulative -> halved frequencies (rounded up: no symbol drops to zero) for i = 1, n do cum[i] = rshift(cum[i] - cum[i + 1] + 1, 1) end -- sort by frequency, decreasing (a selection-style exchange sort: its order of equal frequencies is the format's) for i = 1, n - 1 do for j = i + 1, n do if cum[i] < cum[j] then cum[i], cum[j] = cum[j], cum[i] sym[i], sym[j] = sym[j], sym[i] end end end for i = n, 1, -1 do cum[i] += cum[i + 1] end end type Coder = { src: buffer, pos: number, stop: number, acc: number, cnt: number, over: number, H: number, L: number, C: number, bad: boolean } @native local function bit(c: Coder): number if c.cnt == 0 then local p = c.pos if p < c.stop then c.acc = readu8(c.src, p) c.pos = p + 1 else c.acc = 0 c.over += 1 end c.cnt = 8 end c.cnt -= 1 return band(rshift(c.acc, c.cnt), 1) end @native local function raw(c: Coder, n: number): number local v = 0 for _ = 1, n do v = v * 2 + bit(c) end return v end @native local function symbol(c: Coder, m: Model): number local cum = m.cum local H, L, C = c.H, c.L, c.C local range = H - L + 1 local total = cum[1] if range <= 0 or C < L or C > H then c.bad = true return 0 end local f = band(floor(((C - L + 1) * total - 1) / range), 0xFFFF) local n = m.n local i = 2 while i <= n and cum[i] > f do i += 1 end -- the symbol is sym[i - 1]: its interval is [cum[i], cum[i - 1]) local s = m.sym[i - 1] H = L + floor(cum[i - 1] * range / total) - 1 L = L + floor(cum[i] * range / total) for k = 1, i - 1 do cum[k] += 8 end if cum[1] > 3800 then rescale(m) end while true do if band(bxor(L, H), 0x8000) ~= 0 then if band(L, 0x4000) ~= 0 and band(H, 0x4000) == 0 then -- underflow: L and H straddle the middle C = bxor(C, 0x4000) L = band(L, 0x3FFF) H = bor(H, 0x4000) else break end end L = band(lshift(L, 1), 0xFFFF) H = bor(band(lshift(H, 1), 0xFFFF), 1) C = bor(band(lshift(C, 1), 0xFFFF), bit(c)) end c.H, c.L, c.C = H, L, C return s end @native function Quantum.decode(src: buffer, blocks: { { at: number, len: number, size: number } }, outSize: number, windowBits: number): (buffer?, string?) if type(windowBits) ~= "number" or windowBits < 10 or windowBits > 21 or windowBits % 1 ~= 0 then return nil, "unsupported: Quantum window 2^" .. tostring(windowBits) end if outSize < 0 or outSize % 1 ~= 0 then return nil, "bad output size" end local total = 0 for _, b in blocks do if b.at < 0 or b.len < 0 or b.at + b.len > blen(src) or b.size < 0 then return nil, "bad block range" end total += b.size end if total ~= outSize then return nil, "block sizes do not add up to the output size" end local window = lshift(1, windowBits) local slots = windowBits * 2 local selector = model(0, 7) local lit = { model(0, 64), model(64, 64), model(128, 64), model(192, 64) } local m3 = model(0, math.min(slots, 24)) local m4 = model(0, math.min(slots, 36)) local m5 = model(0, slots) local mlen = model(0, 27) local out = bcreate(outSize) local op = 0 for _, b in blocks do local frameEnd = op + b.size local c: Coder = { src = src, pos = b.at, stop = b.at + b.len, acc = 0, cnt = 0, over = 0, H = 0xFFFF, L = 0, C = 0, bad = false } c.C = raw(c, 16) while op < frameEnd do local sel = symbol(c, selector) if c.bad then return nil, "bad arithmetic code" end if sel < 4 then writeu8(out, op, symbol(c, lit[sel + 1])) op += 1 else local len, slot if sel == 4 then len = 3 slot = symbol(c, m3) elseif sel == 5 then len = 4 slot = symbol(c, m4) elseif sel == 6 then local ls = symbol(c, mlen) len = LBASE[ls + 1] + raw(c, LEXTRA[ls + 1]) + 5 slot = symbol(c, m5) else return nil, "bad selector" end local dist = PBASE[slot + 1] + raw(c, PEXTRA[slot + 1]) + 1 if dist > op or dist > window then return nil, "match offset before the start of the data" end if op + len > frameEnd then return nil, "match past the end of its frame" end local from = op - dist if dist >= len then bcopy(out, op, out, from, len) else for k = 0, len - 1 do writeu8(out, op + k, readu8(out, from + k)) end end op += len end if c.bad then return nil, "bad arithmetic code" end if c.over > 4 then return nil, "truncated frame" end end end return out, nil end return Quantum end __FILES["codecs/compress/UnixCompress"] = @native function() -- codecs/compress/UnixCompress: the LZW of Unix compress (.Z: magic 1F 9D, a flags byte: max width 9..16, block mode). -- From the ncompress sources (public domain: licenses/ncompress-UNLICENSE.txt); the encoder matches ncompress 5.0. -- LSB-first codes from 9 bits; block mode code 256 clears; a width change or CLEAR skips the rest of the 8-code group. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local UnixCompress = {} type DecodeOptions = { maxBytes: number? } type EncodeOptions = { maxBits: number? } local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local MAXCODES = 65536 local CHECK_GAP = 10000 local prefix = bcreate(MAXCODES * 4) local suffix = bcreate(MAXCODES) local first = bcreate(MAXCODES) local length = bcreate(MAXCODES * 4) @native function UnixCompress.decompress(buf: buffer | string, offset: number?, len: number?, opts: DecodeOptions?): (buffer?, Err.Err?) local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len) if not b then return nil, aerr end local maxBytes = (opts and opts.maxBytes) or 2 ^ 30 if n < 3 then return nil, Err.new(Err.TRUNCATED, "header past the end", o) end if readu8(b, o) ~= 0x1F or readu8(b, o + 1) ~= 0x9D then return nil, Err.new(Err.CORRUPT, "bad magic", o) end local flags = readu8(b, o + 2) local maxbits = band(flags, 0x1F) local block = band(flags, 0x80) ~= 0 if maxbits < 9 or maxbits > 16 then return nil, Err.new(Err.UNSUPPORTED, "maximum code width " .. maxbits, o + 2) end if band(flags, 0x60) ~= 0 then return nil, Err.new(Err.UNSUPPORTED, "reserved flag bits set", o + 2) end local maxmax = lshift(1, maxbits) for i = 0, 255 do writeu32(prefix, i * 4, 0) writeu8(suffix, i, i) writeu8(first, i, i) writeu32(length, i * 4, 1) end local cap = math.min(math.max(n * 3, 1024), maxBytes) local out = bcreate(cap) local op = 0 local totalBits = (n - 3) * 8 local base = o + 3 local pos = 0 local gbase = 0 local nbits = 9 local mask = 511 local maxcode = 511 local freeEnt = if block then 257 else 256 local prev = -1 while pos + nbits <= totalBits do if freeEnt > maxcode then local g = nbits * 8 pos = gbase + (pos - gbase + g - 1) // g * g gbase = pos nbits += 1 maxcode = if nbits == maxbits then maxmax else lshift(1, nbits) - 1 mask = lshift(1, nbits) - 1 continue end local q = base + rshift(pos, 3) local acc = readu8(b, q) if q + 1 < o + n then acc = bor(acc, lshift(readu8(b, q + 1), 8)) end if q + 2 < o + n then acc = bor(acc, lshift(readu8(b, q + 2), 16)) end local c = band(rshift(acc, band(pos, 7)), mask) pos += nbits if c == 256 and block then local g = nbits * 8 pos = gbase + (pos - gbase + g - 1) // g * g gbase = pos nbits = 9 mask = 511 maxcode = 511 freeEnt = 257 prev = -1 continue end local l if prev < 0 then if c >= 256 then return nil, Err.new(Err.CORRUPT, "first code is not a literal", base + rshift(pos, 3)) end l = 1 elseif c < freeEnt then l = readu32(length, c * 4) elseif c == freeEnt then l = readu32(length, prev * 4) + 1 else return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3)) end if op + l > cap then if op + l > maxBytes then return nil, Err.new(Err.LIMIT, "output over " .. maxBytes .. " bytes") end local ncap = math.min(math.max(cap * 2, op + l), maxBytes) local nb = bcreate(ncap) bcopy(nb, 0, out, 0, op) out, cap = nb, ncap end -- the new entry (prev + first byte of c's string) before the copy: KwKwK reads it if prev >= 0 and freeEnt < maxmax then local f = if c == freeEnt then readu8(first, prev) else readu8(first, c) writeu32(prefix, freeEnt * 4, prev) writeu8(suffix, freeEnt, f) writeu8(first, freeEnt, readu8(first, prev)) writeu32(length, freeEnt * 4, readu32(length, prev * 4) + 1) freeEnt += 1 elseif prev >= 0 then if c == freeEnt then return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3)) end end local p = op + l - 1 local k = c while p >= op do writeu8(out, p, readu8(suffix, k)) k = readu32(prefix, k * 4) p -= 1 end op += l prev = c end local res = bcreate(op) bcopy(res, 0, out, 0, op) return res, nil end local HSIZE = 1 * 131072 local hkey = bcreate(HSIZE * 4) local hval = bcreate(HSIZE * 4) @native function UnixCompress.compress(buf: buffer | string, offset: number?, len: number?, opts: EncodeOptions?): (buffer?, Err.Err?) local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len) if not b then return nil, aerr end local maxbits = (opts and opts.maxBits) or 16 if type(maxbits) ~= "number" or maxbits < 9 or maxbits > 16 or maxbits % 1 ~= 0 then return nil, Err.new(Err.ARG, "maxBits must be 9..16") end local cap = 3 + n * 2 + 64 local out = bcreate(cap) writeu8(out, 0, 0x1F) writeu8(out, 1, 0x9D) writeu8(out, 2, bor(maxbits, 0x80)) local outbits = 24 local boff = 24 local acc, nb = 0, 0 local nbits = 9 local extcode = 513 local maxmax = lshift(1, maxbits) local stcode = true local freeEnt = 257 local ratio = 0 local checkpoint = CHECK_GAP buffer.fill(hkey, 0, 0, HSIZE * 4) @native local function put(code: number) acc = bor(acc, lshift(code, nb)) nb += nbits outbits += nbits while nb >= 8 do local q = rshift(outbits - nb, 3) if q < cap then writeu8(out, q, band(acc, 255)) end acc = rshift(acc, 8) nb -= 8 end end @native local function align() -- round outbits up to a whole group of nbits-bit codes since boff; the skipped bits are zeros local g = nbits * 8 local nbits2 = boff + (outbits - boff + g - 1) // g * g if nb > 0 then local q = rshift(outbits - nb, 3) if q < cap then writeu8(out, q, band(acc, 255)) end end acc, nb = 0, 0 outbits = nbits2 boff = nbits2 end if n == 0 then local res = bcreate(3) bcopy(res, 0, out, 0, 3) return res, nil end local ent = readu8(b, o) local e = o + n local i = o + 1 -- checks happen with a one-byte current string, right after an output (and at the start) @native local function checks(consumed: number) if freeEnt >= extcode then if nbits < maxbits then align() nbits += 1 extcode = if nbits < maxbits then lshift(1, nbits) + 1 else lshift(1, nbits) else extcode = math.huge stcode = false end end if not stcode and consumed >= checkpoint then checkpoint = consumed + CHECK_GAP local outBytes = rshift(outbits, 3) local rat if consumed > 0x7FFFFF then local d = rshift(outBytes, 8) rat = if d == 0 then 0x7FFFFFFF else consumed // d else rat = (consumed * 256) // outBytes end if rat >= ratio then ratio = rat else ratio = 0 buffer.fill(hkey, 0, 0, HSIZE * 4) put(256) align() nbits = 9 extcode = 513 freeEnt = 257 stcode = true end end end checks(1) while i < e do local c = readu8(b, i) i += 1 local key = ent * 256 + c + 1 local h = band(ent * 4099 + c * 131 + rshift(ent, 5), HSIZE - 1) local found = -1 while true do local k = readu32(hkey, h * 4) if k == 0 then break elseif k == key then found = readu32(hval, h * 4) break end h = band(h + 1, HSIZE - 1) end if found >= 0 then ent = found else put(ent) if stcode then writeu32(hkey, h * 4, key) writeu32(hval, h * 4, freeEnt) freeEnt += 1 end ent = c checks(i - o) end if rshift(outbits, 3) + 8 > cap then local ncap = cap * 2 local nbuf = bcreate(ncap) bcopy(nbuf, 0, out, 0, cap) out, cap = nbuf, ncap end end put(ent) if nb > 0 then local q = rshift(outbits - nb, 3) if q < cap then writeu8(out, q, band(acc, 255)) end end local size = rshift(outbits + 7, 3) local res = bcreate(size) bcopy(res, 0, out, 0, math.min(size, cap)) return res, nil end @native function UnixCompress.isCompress(b: buffer, o: number?): boolean local p = o or 0 return p + 3 <= blen(b) and readu8(b, p) == 0x1F and readu8(b, p + 1) == 0x9D end return UnixCompress end __FILES["codecs/compress/Xxh32"] = @native function() -- codecs/compress/Xxh32: XXH32 for the LZ4 frame checksums, from the xxHash specification (Yann Collet, BSD-2). -- 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double. local Xxh32 = {} local bxor, bor, lshift, rshift = bit32.bxor, bit32.bor, bit32.lshift, bit32.rshift local readu8, readu32 = buffer.readu8, buffer.readu32 local T32 = 4294967296 local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1 @native local function mul(a: number, b: number): number local a0 = a % 65536 local a1 = (a - a0) / 65536 return (a0 * b + ((a1 * b) % 65536) * 65536) % T32 end @native local function rotl(x: number, r: number): number return bor(lshift(x, r), rshift(x, 32 - r)) end @native local function round(acc: number, lane: number): number return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1) end @native function Xxh32.hash(b: buffer, offset: number?, length: number?, seed: number?): number local n0 = buffer.len(b) local o = math.clamp(offset or 0, 0, n0) local n = math.clamp(length or (n0 - o), 0, n0 - o) local s = (seed or 0) % T32 local p = o local e = o + n local h if n >= 16 then local v1 = (s + P1 + P2) % T32 local v2 = (s + P2) % T32 local v3 = s local v4 = (s - P1) % T32 local last = e - 16 while p <= last do v1 = round(v1, readu32(b, p)) v2 = round(v2, readu32(b, p + 4)) v3 = round(v3, readu32(b, p + 8)) v4 = round(v4, readu32(b, p + 12)) p += 16 end h = (rotl(v1, 1) + rotl(v2, 7) + rotl(v3, 12) + rotl(v4, 18)) % T32 else h = (s + P5) % T32 end h = (h + n) % T32 while p + 4 <= e do h = mul(rotl((h + mul(readu32(b, p), P3)) % T32, 17), P4) p += 4 end while p < e do h = mul(rotl((h + readu8(b, p) * P5) % T32, 11), P1) p += 1 end h = mul(bxor(h, rshift(h, 15)), P2) h = mul(bxor(h, rshift(h, 13)), P3) return bxor(h, rshift(h, 16)) end return Xxh32 end __FILES["codecs/compress/Zstd"] = function() -- codecs/compress/Zstd: Zstandard decompression (RFC 8878), written from the specification; no dictionaries. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Decode = __include("codecs/compress/Zstd/Decode") local Zstd = {} type Options = { maxBytes: number?, verify: boolean?, } -- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F) Zstd.MAGIC = "\40\181\47\253" function Zstd.isFrame(buf: buffer, offset: number?): boolean local o = offset or 0 if type(buf) ~= "buffer" or o < 0 or o + 4 > buffer.len(buf) then return false end local m = buffer.readu32(buf, o) return m == 0xFD2FB528 or bit32.band(m, 0xFFFFFFF0) == 0x184D2A50 end -- data after the last frame that is not a frame is an error, as zstd -d does function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = Bytes.span("Zstd.decompress", buf, offset, length) if not b then return nil, aerr end local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30 if type(maxBytes) ~= "number" or maxBytes < 0 then return nil, Err.new(Err.ARG, "Zstd.decompress: bad maxBytes " .. tostring(maxBytes)) end local verify = not (opts and opts.verify == false) local out, len, consumed, at = Decode.decompress(b, o, o + l, maxBytes, verify) if not out then return nil, Err.from(consumed, at, len) end if buffer.len(out) ~= len then local r = buffer.create(len) buffer.copy(r, 0, out, 0, len) out = r end return out, consumed end function Zstd.xxh64(buf: buffer, offset: number?, length: number?): (number, number) local o = math.clamp(offset or 0, 0, buffer.len(buf)) local l = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o) return Decode.hash(buf, o, l) end return Zstd end __FILES["codecs/compress/Zstd/Decode"] = @native function() -- codecs/compress/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no reference code). -- Backward bitstreams: bits [o - n, o) come from one readu32 at byte (o - n) / 8; bits before the stream read as zeros. local Xxh64 = __include("codecs/compress/Zstd/Xxh64") local band, lshift, rshift = bit32.band, bit32.lshift, bit32.rshift local readu8, readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len local MAGIC = 0xFD2FB528 local BLOCK_MAX = 131072 local Decode = {} -- literal length / match length codes: baseline, extra bits (index = code + 1) local LL_BASE = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 28, 32, 40, 48, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 } local LL_BITS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } local ML_BASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 41, 43, 47, 51, 59, 67, 83, 99, 131, 259, 515, 1027, 2051, 4099, 8195, 16387, 32771, 65539, } local ML_BITS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, } local LL_DEFAULT = { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, -1, -1, -1, -1 } local ML_DEFAULT = { 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, } local OF_DEFAULT = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1 } local HB = table.create(2048, 0) do local v = 0 for i = 1, 2048 do if i >= lshift(2, v) then v += 1 end HB[i] = v end end @native local function peek(b: buffer, s: number, o: number, n: number): number if n <= 0 then return 0 end local lo = o - n if lo >= 0 then local byte = s + rshift(lo, 3) local bl = blen(b) if byte + 4 <= bl then return band(rshift(readu32(b, byte), band(lo, 7)), lshift(1, n) - 1) end local v = 0 local m = 1 for k = 0, 3 do if byte + k < bl then v += readu8(b, byte + k) * m end m *= 256 end return band(rshift(v, band(lo, 7)), lshift(1, n) - 1) end if o <= 0 then return 0 end return lshift(peek(b, s, o, o), -lo) end @native local function streamBits(b: buffer, s: number, e: number): number if e <= s then return -1 end local last = readu8(b, e - 1) if last == 0 then return -1 end return (e - 1 - s) * 8 + HB[last] end @native local function getF(b: buffer, p: number, e: number, bp: number, n: number): number local byte = p + rshift(bp, 3) local v = 0 local m = 1 for k = 0, 3 do if byte + k < e then v += readu8(b, byte + k) * m end m *= 256 end return band(rshift(v, band(bp, 7)), lshift(1, n) - 1) end -- FSE decoding table entries (u32): symbol | nbBits << 8 | newStateBase << 16 local symTmp = bcreate(512) -- normalized counts: { [symbol + 1] = count }, -1 = "less than 1" probability @native local function buildFse(norm: { number }, nsym: number, al: number, t: buffer): (boolean?, string?) local size = lshift(1, al) local high = size - 1 local next = table.create(nsym, 0) for s = 0, nsym - 1 do local c = norm[s + 1] if c == -1 then if high < 0 then return nil, "bad FSE distribution" end writeu8(symTmp, high, s) high -= 1 next[s + 1] = 1 else next[s + 1] = c end end local pos = 0 local step = rshift(size, 1) + rshift(size, 3) + 3 local mask = size - 1 for s = 0, nsym - 1 do local c = norm[s + 1] for _ = 1, c do writeu8(symTmp, pos, s) local guard = 0 repeat pos = band(pos + step, mask) guard += 1 until pos <= high or guard > size if guard > size then return nil, "bad FSE distribution" end end end if pos ~= 0 then return nil, "bad FSE distribution" end for u = 0, size - 1 do local s = readu8(symTmp, u) local ns = next[s + 1] if ns < 1 or ns > 2048 then return nil, "bad FSE distribution" end next[s + 1] = ns + 1 local nb = al - HB[ns] if nb < 0 then return nil, "bad FSE distribution" end writeu32(t, u * 4, s + nb * 256 + (lshift(ns, nb) - size) * 65536) end return true, nil end @native local function ncount(b: buffer, p: number, e: number, maxSym: number, maxAL: number, norm: { number }): (number?, any, number?) if p >= e then return nil, "truncated FSE table" end local al = getF(b, p, e, 0, 4) + 5 if al > maxAL then return nil, "FSE accuracy log too large" end local bp = 4 local remaining = lshift(1, al) + 1 local threshold = lshift(1, al) local nbBits = al + 1 local sym = 0 local prev0 = false while remaining > 1 and sym <= maxSym do if prev0 then local n0 = sym while true do local v = getF(b, p, e, bp, 2) bp += 2 if v == 3 then n0 += 3 if n0 > maxSym or bp > (e - p) * 8 then return nil, "bad FSE table" end else n0 += v break end end if n0 > maxSym then return nil, "bad FSE table" end while sym < n0 do norm[sym + 1] = 0 sym += 1 end end local max = 2 * threshold - 1 - remaining local count local low = getF(b, p, e, bp, nbBits - 1) if low < max then count = low bp += nbBits - 1 else count = getF(b, p, e, bp, nbBits) if count >= threshold then count -= max end bp += nbBits end count -= 1 remaining -= if count < 0 then -count else count if remaining < 1 then return nil, "bad FSE table" end norm[sym + 1] = count sym += 1 prev0 = count == 0 while remaining < threshold do nbBits -= 1 threshold = rshift(threshold, 1) end end if remaining ~= 1 then return nil, "bad FSE table" end local used = rshift(bp + 7, 3) if p + used > e then return nil, "truncated FSE table" end for s = sym, maxSym do norm[s + 1] = 0 end return al, used, sym end @native local function predefined(dist: { number }, al: number): buffer local t = bcreate(lshift(1, al) * 4) buildFse(dist, #dist, al, t) return t end local LL_PRE, ML_PRE, OF_PRE = predefined(LL_DEFAULT, 6), predefined(ML_DEFAULT, 6), predefined(OF_DEFAULT, 5) -- Huffman table entry (u16): sym | nbBits << 8 local weights = bcreate(256) local wfse = bcreate(64 * 4) @native local function hufTable(b: buffer, p: number, e: number, st: any): (number?, string?) if p >= e then return nil, "truncated Huffman table" end local hdr = readu8(b, p) local n = 0 local used if hdr >= 128 then n = hdr - 127 used = 1 + rshift(n + 1, 1) if p + used > e then return nil, "truncated Huffman table" end for i = 0, n - 1 do local byte = readu8(b, p + 1 + rshift(i, 1)) writeu8(weights, i, if band(i, 1) == 0 then rshift(byte, 4) else band(byte, 15)) end else used = 1 + hdr if p + used > e then return nil, "truncated Huffman table" end local q, qe = p + 1, p + 1 + hdr local norm = st.norm local al, nb = ncount(b, q, qe, 255, 6, norm) if not al then return nil, nb end local ok, msg = buildFse(norm, 256, al, wfse) if not ok then return nil, msg end local ss = q + nb local off = streamBits(b, ss, qe) if off < 0 then return nil, "bad Huffman weight stream" end local s1 = peek(b, ss, off, al) off -= al local s2 = peek(b, ss, off, al) off -= al while true do if n > 254 then return nil, "too many Huffman weights" end local e1 = readu32(wfse, s1 * 4) writeu8(weights, n, band(e1, 255)) n += 1 local k = band(rshift(e1, 8), 255) s1 = rshift(e1, 16) + peek(b, ss, off, k) off -= k if off < 0 then writeu8(weights, n, band(readu32(wfse, s2 * 4), 255)) n += 1 break end local e2 = readu32(wfse, s2 * 4) writeu8(weights, n, band(e2, 255)) n += 1 k = band(rshift(e2, 8), 255) s2 = rshift(e2, 16) + peek(b, ss, off, k) off -= k if off < 0 then writeu8(weights, n, band(readu32(wfse, s1 * 4), 255)) n += 1 break end end end -- the last weight is implied: the total must reach the next power of two local total = 0 for i = 0, n - 1 do local w = readu8(weights, i) if w > 11 then return nil, "bad Huffman weight" end if w > 0 then total += lshift(1, w - 1) end end if total == 0 or total >= 2048 then return nil, "bad Huffman weights" end local maxBits = HB[total] + 1 local rest = lshift(1, maxBits) - total if band(rest, rest - 1) ~= 0 then return nil, "bad Huffman weights" end writeu8(weights, n, HB[rest] + 1) local nsym = n + 1 -- codes: the longest first, in symbol order within a length local rankCount = table.create(13, 0) for i = 0, nsym - 1 do local w = readu8(weights, i) if w > 0 then local bits = maxBits + 1 - w rankCount[bits + 1] += 1 end end local rankIdx = table.create(13, 0) rankIdx[maxBits + 1] = 0 for i = maxBits, 1, -1 do rankIdx[i] = rankIdx[i + 1] + rankCount[i + 1] * lshift(1, maxBits - i) end if rankIdx[1] ~= lshift(1, maxBits) then return nil, "bad Huffman weights" end local t = st.huf for i = 0, nsym - 1 do local w = readu8(weights, i) if w > 0 then local bits = maxBits + 1 - w local code = rankIdx[bits + 1] local len = lshift(1, maxBits - bits) local v = i + bits * 256 for k = code, code + len - 1 do writeu16(t, k * 2, v) end rankIdx[bits + 1] = code + len end end st.hufBits = maxBits return used, nil end @native local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number, lit: buffer, dp: number, cnt: number): string? local off = streamBits(b, s, e) if off < 0 then return "bad Huffman stream" end local mmask = lshift(1, mb) - 1 local fastEnd = blen(b) - 4 for k = dp, dp + cnt - 1 do local lo = off - mb local idx if lo >= 0 then local byte = s + rshift(lo, 3) if byte <= fastEnd then idx = band(rshift(readu32(b, byte), band(lo, 7)), mmask) else idx = peek(b, s, off, mb) end else idx = peek(b, s, off, mb) end local v = readu16(t, idx * 2) writeu8(lit, k, v) off -= rshift(v, 8) end if off ~= 0 then return "Huffman stream size mismatch" end return nil end @native local function grow(st: any, need: number): boolean if need > st.maxBytes then return false end local cap = math.min(st.maxBytes, math.max(blen(st.out) * 2, need, 65536)) local nb = bcreate(cap) bcopy(nb, 0, st.out, 0, st.op) st.out = nb return true end @native local function block(b: buffer, p: number, e: number, st: any): (string?, string?) -- literals section local b0 = readu8(b, p) local ltype = band(b0, 3) local sf = band(rshift(b0, 2), 3) local regen local litSrc, litPos local lit = st.lit if ltype <= 1 then if sf == 0 or sf == 2 then regen = rshift(b0, 3) p += 1 elseif sf == 1 then if p + 2 > e then return "TRUNCATED", "truncated literals header" end regen = rshift(b0, 4) + readu8(b, p + 1) * 16 p += 2 else if p + 3 > e then return "TRUNCATED", "truncated literals header" end regen = rshift(b0, 4) + readu8(b, p + 1) * 16 + readu8(b, p + 2) * 4096 p += 3 end if regen > BLOCK_MAX then return "CORRUPT", "literals too large" end if ltype == 0 then if p + regen > e then return "TRUNCATED", "truncated raw literals" end litSrc, litPos = b, p p += regen else if p + 1 > e then return "TRUNCATED", "truncated RLE literals" end bfill(lit, 0, readu8(b, p), regen) litSrc, litPos = lit, 0 p += 1 end else local csize if sf <= 1 then if p + 3 > e then return "TRUNCATED", "truncated literals header" end local v = b0 + readu8(b, p + 1) * 256 + readu8(b, p + 2) * 65536 regen = band(rshift(v, 4), 0x3FF) csize = band(rshift(v, 14), 0x3FF) p += 3 elseif sf == 2 then if p + 4 > e then return "TRUNCATED", "truncated literals header" end local v = readu32(b, p) regen = band(rshift(v, 4), 0x3FFF) csize = rshift(v, 18) p += 4 else if p + 5 > e then return "TRUNCATED", "truncated literals header" end local v = readu32(b, p) regen = band(rshift(v, 4), 0x3FFFF) csize = rshift(v, 22) + readu8(b, p + 4) * 1024 p += 5 end if regen > BLOCK_MAX then return "CORRUPT", "literals too large" end if p + csize > e then return "TRUNCATED", "truncated compressed literals" end local hs, he = p, p + csize p = he if ltype == 2 then local used, herr = hufTable(b, hs, he, st) if not used then return "CORRUPT", herr end hs += used elseif not st.hufBits then return "CORRUPT", "treeless literals without a previous Huffman table" end local t, mb = st.huf, st.hufBits if sf == 0 then local herr = hufStream(b, hs, he, t, mb, lit, 0, regen) if herr then return "CORRUPT", herr end else if hs + 6 > he then return "CORRUPT", "truncated jump table" end local l1, l2, l3 = readu16(b, hs), readu16(b, hs + 2), readu16(b, hs + 4) local s1 = hs + 6 local s2 = s1 + l1 local s3 = s2 + l2 local s4 = s3 + l3 if s4 > he then return "CORRUPT", "bad jump table" end local seg = rshift(regen + 3, 2) local last = regen - 3 * seg if last < 0 then return "CORRUPT", "bad 4-stream literals size" end local herr = hufStream(b, s1, s2, t, mb, lit, 0, seg) or hufStream(b, s2, s3, t, mb, lit, seg, seg) or hufStream(b, s3, s4, t, mb, lit, 2 * seg, seg) or hufStream(b, s4, he, t, mb, lit, 3 * seg, last) if herr then return "CORRUPT", herr end end litSrc, litPos = lit, 0 end -- sequences section header if p >= e then return "TRUNCATED", "missing sequences header" end local nbSeq = readu8(b, p) p += 1 if nbSeq >= 128 then if nbSeq == 255 then if p + 2 > e then return "TRUNCATED", "truncated sequences header" end nbSeq = readu16(b, p) + 0x7F00 p += 2 else if p + 1 > e then return "TRUNCATED", "truncated sequences header" end nbSeq = (nbSeq - 128) * 256 + readu8(b, p) p += 1 end end local op = st.op if nbSeq == 0 then if p ~= e then return "CORRUPT", "data after an empty sequences section" end if op + regen > blen(st.out) then if not grow(st, op + regen) then return "LIMIT", "output over the size limit" end end bcopy(st.out, op, litSrc, litPos, regen) st.op = op + regen return nil, nil end if p >= e then return "TRUNCATED", "missing compression modes" end local modes = readu8(b, p) p += 1 if band(modes, 3) ~= 0 then return "CORRUPT", "reserved bits set in compression modes" end -- the three tables, in the order LL, OF, ML local tabs = st.tabs for k = 1, 3 do local mode = band(rshift(modes, 8 - 2 * k), 3) local maxSym = if k == 1 then 35 elseif k == 2 then 31 else 52 local maxAL = if k == 1 then 9 elseif k == 2 then 8 else 9 if mode == 0 then tabs[k] = if k == 1 then LL_PRE elseif k == 2 then OF_PRE else ML_PRE tabs[k + 3] = if k == 2 then 5 else 6 elseif mode == 1 then if p >= e then return "TRUNCATED", "truncated RLE table" end local sym = readu8(b, p) p += 1 if sym > maxSym then return "CORRUPT", "bad RLE symbol" end local t = st.rle[k] writeu32(t, 0, sym) tabs[k] = t tabs[k + 3] = 0 elseif mode == 2 then local norm = st.norm local al, used, nsym = ncount(b, p, e, maxSym, maxAL, norm) if not al then return "CORRUPT", used end p += used local t = st.dyn[k] local ok, msg = buildFse(norm, nsym :: number, al, t) if not ok then return "CORRUPT", msg end tabs[k] = t tabs[k + 3] = al else if not tabs[k] then return "CORRUPT", "repeated table without a previous one" end end end local llT, ofT, mlT = tabs[1] :: buffer, tabs[2] :: buffer, tabs[3] :: buffer local llAL, ofAL, mlAL = tabs[4] :: number, tabs[5] :: number, tabs[6] :: number -- the sequences bitstream local s = p local off = streamBits(b, s, e) if off < 0 then return "CORRUPT", "bad sequences bitstream" end local llS = peek(b, s, off, llAL) off -= llAL local ofS = peek(b, s, off, ofAL) off -= ofAL local mlS = peek(b, s, off, mlAL) off -= mlAL local rep1, rep2, rep3 = st.rep1, st.rep2, st.rep3 local out = st.out local cap = blen(out) local frameStart = st.frameStart local lp, litEnd = litPos, litPos + regen local fastEnd = blen(b) - 4 for i = 1, nbSeq do local ofE, llE, mlE = readu32(ofT, ofS * 4), readu32(llT, llS * 4), readu32(mlT, mlS * 4) local ofCode = band(ofE, 255) local mlCode = band(mlE, 255) + 1 local llCode = band(llE, 255) + 1 -- offset bits, then match length bits, then literal length bits local ofv if ofCode > 24 then local hiN = ofCode - 24 local hi = peek(b, s, off, hiN) off -= hiN ofv = lshift(1, ofCode) + hi * 16777216 + peek(b, s, off, 24) off -= 24 elseif ofCode > 0 then local lo = off - ofCode local v if lo >= 0 and s + rshift(lo, 3) <= fastEnd then v = band(rshift(readu32(b, s + rshift(lo, 3)), band(lo, 7)), lshift(1, ofCode) - 1) else v = peek(b, s, off, ofCode) end off = lo ofv = lshift(1, ofCode) + v else ofv = 1 end local ml = ML_BASE[mlCode] local nb = ML_BITS[mlCode] if nb > 0 then ml += peek(b, s, off, nb) off -= nb end local ll = LL_BASE[llCode] nb = LL_BITS[llCode] if nb > 0 then ll += peek(b, s, off, nb) off -= nb end -- repeat offsets local offset if ofv > 3 then offset = ofv - 3 rep3 = rep2 rep2 = rep1 rep1 = offset else local idx = ofv - 1 if ll == 0 then idx += 1 end if idx == 0 then offset = rep1 else if idx == 1 then offset = rep2 elseif idx == 2 then offset = rep3 else offset = rep1 - 1 end if idx > 1 then rep3 = rep2 end rep2 = rep1 rep1 = offset end end -- state updates (not after the last sequence): LL, ML, OF if i < nbSeq then nb = band(rshift(llE, 8), 255) llS = rshift(llE, 16) + peek(b, s, off, nb) off -= nb nb = band(rshift(mlE, 8), 255) mlS = rshift(mlE, 16) + peek(b, s, off, nb) off -= nb nb = band(rshift(ofE, 8), 255) ofS = rshift(ofE, 16) + peek(b, s, off, nb) off -= nb end -- execute if lp + ll > litEnd then return "CORRUPT", "literal length past the literals" end local need = op + ll + ml if need > cap then st.op = op if not grow(st, need) then return "LIMIT", "output over the size limit" end out = st.out cap = blen(out) end if ll > 0 then bcopy(out, op, litSrc, lp, ll) op += ll lp += ll end if offset > op - frameStart or offset < 1 then return "CORRUPT", "match offset before the frame start" end local from = op - offset if offset >= ml then bcopy(out, op, out, from, ml) op += ml elseif offset == 1 then bfill(out, op, readu8(out, from), ml) op += ml else local left = ml while left > 0 do local n = if left < offset then left else offset bcopy(out, op, out, from, n) op += n from += n left -= n end end end if off ~= 0 then return "CORRUPT", "sequences bitstream size mismatch" end local rest = litEnd - lp if rest > 0 then if op + rest > cap then st.op = op if not grow(st, op + rest) then return "LIMIT", "output over the size limit" end out = st.out end bcopy(out, op, litSrc, lp, rest) op += rest end st.op = op st.rep1, st.rep2, st.rep3 = rep1, rep2, rep3 return nil, nil end @native function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: number, verify: boolean): (buffer?, any, any, any) local st: any = { out = bcreate(math.min(maxBytes, math.max(4096, (stop - start) * 3))), op = 0, maxBytes = maxBytes, lit = bcreate(BLOCK_MAX + 64), huf = bcreate(2048 * 2), hufBits = nil, norm = table.create(256, 0), tabs = {}, rle = { bcreate(4), bcreate(4), bcreate(4) }, dyn = { bcreate(512 * 4), bcreate(256 * 4), bcreate(512 * 4) }, frameStart = 0, rep1 = 1, rep2 = 4, rep3 = 8, } local pos = start local frames = 0 if stop - start < 4 then return nil, "TRUNCATED", "not a zstd stream (too short)", start end while pos < stop do if pos + 4 > stop then return nil, "TRUNCATED", "truncated frame magic", pos end local magic = readu32(b, pos) if band(magic, 0xFFFFFFF0) == 0x184D2A50 then if pos + 8 > stop then return nil, "TRUNCATED", "truncated skippable frame", pos end local size = readu32(b, pos + 4) if pos + 8 + size > stop then return nil, "TRUNCATED", "truncated skippable frame", pos end pos += 8 + size frames += 1 continue end if magic ~= MAGIC then return nil, "CORRUPT", if frames == 0 then "bad magic" else "unknown data after frame " .. frames, pos end pos += 4 if pos + 1 > stop then return nil, "TRUNCATED", "truncated frame header", pos end local fhd = readu8(b, pos) pos += 1 local fcsFlag = rshift(fhd, 6) local single = band(fhd, 0x20) ~= 0 if band(fhd, 8) ~= 0 then return nil, "CORRUPT", "reserved frame header bit set", pos - 1 end local checksum = band(fhd, 4) ~= 0 local didFlag = band(fhd, 3) local didSize = if didFlag == 3 then 4 else didFlag local fcsSize = if fcsFlag == 0 then (if single then 1 else 0) else lshift(1, fcsFlag) local hsize = (if single then 0 else 1) + didSize + fcsSize if pos + hsize > stop then return nil, "TRUNCATED", "truncated frame header", pos end local windowSize = 0 if not single then local wd = readu8(b, pos) pos += 1 local wlog = 10 + rshift(wd, 3) if wlog > 41 then return nil, "CORRUPT", "bad window size", pos - 1 end local base = 2 ^ wlog windowSize = base + base / 8 * band(wd, 7) end local did = 0 if didSize == 1 then did = readu8(b, pos) elseif didSize == 2 then did = readu16(b, pos) elseif didSize == 4 then did = readu32(b, pos) end pos += didSize if did ~= 0 then return nil, "UNSUPPORTED", "dictionaries are not supported (dictionary " .. did .. ")", pos - didSize end local fcs = -1 if fcsSize == 1 then fcs = readu8(b, pos) elseif fcsSize == 2 then fcs = readu16(b, pos) + 256 elseif fcsSize == 4 then fcs = readu32(b, pos) elseif fcsSize == 8 then fcs = readu32(b, pos) + readu32(b, pos + 4) * 4294967296 end pos += fcsSize if single then windowSize = fcs end local blockMax = math.min(windowSize, BLOCK_MAX) local frameStart = st.op if fcs >= 0 then if frameStart + fcs > st.maxBytes then return nil, "LIMIT", string.format("frame content size %d is over the %d byte limit", fcs, st.maxBytes), pos end if frameStart + fcs > blen(st.out) then grow(st, frameStart + fcs) end end st.frameStart = frameStart st.rep1, st.rep2, st.rep3 = 1, 4, 8 st.hufBits = nil table.clear(st.tabs) local last = false repeat if pos + 3 > stop then return nil, "TRUNCATED", "truncated block header", pos end local bh = readu16(b, pos) + readu8(b, pos + 2) * 65536 last = band(bh, 1) ~= 0 local btype = band(rshift(bh, 1), 3) local bsize = rshift(bh, 3) pos += 3 if bsize > blockMax then return nil, "CORRUPT", "block larger than the maximum block size", pos - 3 end if btype == 0 then if pos + bsize > stop then return nil, "TRUNCATED", "truncated raw block", pos end if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then return nil, "LIMIT", "output over the size limit", pos end bcopy(st.out, st.op, b, pos, bsize) st.op += bsize pos += bsize elseif btype == 1 then if pos + 1 > stop then return nil, "TRUNCATED", "truncated RLE block", pos end if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then return nil, "LIMIT", "output over the size limit", pos end bfill(st.out, st.op, readu8(b, pos), bsize) st.op += bsize pos += 1 elseif btype == 2 then if pos + bsize > stop then return nil, "TRUNCATED", "truncated compressed block", pos end if bsize == 0 then return nil, "CORRUPT", "empty compressed block", pos end local code, msg = block(b, pos, pos + bsize, st) if code then return nil, code, msg, pos end pos += bsize else return nil, "CORRUPT", "reserved block type", pos - 3 end until last local size = st.op - frameStart if fcs >= 0 and size ~= fcs then return nil, "CORRUPT", string.format("frame decoded to %d bytes, header says %d", size, fcs), pos end if checksum then if pos + 4 > stop then return nil, "TRUNCATED", "missing content checksum", pos end if verify then local _, lo = Xxh64.hash(st.out, frameStart, size) local want = readu32(b, pos) if lo ~= want then return nil, "CHECKSUM", string.format("content checksum mismatch (%08x, expected %08x)", lo, want), pos end end pos += 4 end frames += 1 end return st.out, st.op, pos end Decode.hash = Xxh64.hash return Decode end __FILES["codecs/compress/Zstd/Xxh64"] = @native function() -- codecs/compress/Zstd/Xxh64: XXH64 (seed 0) on 32-bit halves, from the xxHash specification (Yann Collet, BSD-2). -- 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is exact below 2^53. local bor, bxor, lshift, rshift = bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu8, readu32 = buffer.readu8, buffer.readu32 local T32 = 4294967296 local P1H, P1L = 0x9E3779B1, 0x85EBCA87 local P2H, P2L = 0xC2B2AE3D, 0x27D4EB4F local P3H, P3L = 0x165667B1, 0x9E3779F9 local P4H, P4L = 0x85EBCA77, 0xC2B2AE63 local P5H, P5L = 0x27D4EB2F, 0x165667C5 @native local function mul(ah: number, al: number, bh: number, bl: number): (number, number) local a0 = al % 65536 local a1 = (al - a0) / 65536 local b0 = bl % 65536 local b1 = (bl - b0) / 65536 local mid = a1 * b0 + a0 * b1 local mid0 = mid % 65536 local lo = a0 * b0 + mid0 * 65536 local lo32 = lo % T32 local hi = a1 * b1 + (mid - mid0) / 65536 + (lo - lo32) / T32 hi += (a0 * bh + ((a1 * bh) % 65536) * 65536) + (b0 * ah + ((b1 * ah) % 65536) * 65536) return hi % T32, lo32 end @native local function add(ah: number, al: number, bh: number, bl: number): (number, number) local l = al + bl local h = ah + bh if l >= T32 then l -= T32 h += 1 end return h % T32, l end @native local function rotl(h: number, l: number, r: number): (number, number) return bor(lshift(h, r), rshift(l, 32 - r)), bor(lshift(l, r), rshift(h, 32 - r)) end local P1L0, P1L1 = P1L % 65536, P1L // 65536 local P2L0, P2L1 = P2L % 65536, P2L // 65536 -- round: acc = rotl(acc + input * P2, 31) * P1 @native local function round(ah: number, al: number, ih: number, il: number): (number, number) local a0 = il % 65536 local a1 = (il - a0) / 65536 local mid = a1 * P2L0 + a0 * P2L1 local mid0 = mid % 65536 local lo = a0 * P2L0 + mid0 * 65536 local ml = lo % T32 local mh = a1 * P2L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P2H + ((a1 * P2H) % 65536) * 65536 + P2L0 * ih + ((P2L1 * ih) % 65536) * 65536 local l = al + ml local h = ah + mh if l >= T32 then l -= T32 h += 1 end h %= T32 -- rotl 31 = rotr 1, in arithmetic (cheaper than bit32 calls on LuaJIT) local hb, lb = h % 2, l % 2 local rh, rl = hb * 2147483648 + (l - lb) / 2, lb * 2147483648 + (h - hb) / 2 a0 = rl % 65536 a1 = (rl - a0) / 65536 mid = a1 * P1L0 + a0 * P1L1 mid0 = mid % 65536 lo = a0 * P1L0 + mid0 * 65536 ml = lo % T32 mh = a1 * P1L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P1H + ((a1 * P1H) % 65536) * 65536 + P1L0 * rh + ((P1L1 * rh) % 65536) * 65536 return mh % T32, ml end @native local function merge(hh: number, hl: number, vh: number, vl: number): (number, number) local rh, rl = round(0, 0, vh, vl) hh, hl = bxor(hh, rh), bxor(hl, rl) hh, hl = mul(hh, hl, P1H, P1L) return add(hh, hl, P4H, P4L) end local Xxh64 = {} @native function Xxh64.hash(b: buffer, offset: number, length: number): (number, number) local p = offset local e = offset + length local hh, hl = 0, 0 if length >= 32 then local v1h, v1l = add(P1H, P1L, P2H, P2L) local v2h, v2l = P2H, P2L local v3h, v3l = 0, 0 local v4h, v4l = add(0, 0, (T32 - P1H - 1) % T32, (T32 - P1L) % T32) -- -P1 (two's complement) local limit = e - 32 while p <= limit do v1h, v1l = round(v1h, v1l, readu32(b, p + 4), readu32(b, p)) v2h, v2l = round(v2h, v2l, readu32(b, p + 12), readu32(b, p + 8)) v3h, v3l = round(v3h, v3l, readu32(b, p + 20), readu32(b, p + 16)) v4h, v4l = round(v4h, v4l, readu32(b, p + 28), readu32(b, p + 24)) p += 32 end local ah, al = rotl(v1h, v1l, 1) local bh, bl = rotl(v2h, v2l, 7) hh, hl = add(ah, al, bh, bl) bh, bl = rotl(v3h, v3l, 12) hh, hl = add(hh, hl, bh, bl) bh, bl = rotl(v4h, v4l, 18) hh, hl = add(hh, hl, bh, bl) hh, hl = merge(hh, hl, v1h, v1l) hh, hl = merge(hh, hl, v2h, v2l) hh, hl = merge(hh, hl, v3h, v3l) hh, hl = merge(hh, hl, v4h, v4l) else hh, hl = P5H, P5L end hh, hl = add(hh, hl, math.floor(length / T32) % T32, length % T32) while p + 8 <= e do local kh, kl = round(0, 0, readu32(b, p + 4), readu32(b, p)) hh, hl = bxor(hh, kh), bxor(hl, kl) :: number hh, hl = rotl(hh, hl, 27) hh, hl = mul(hh, hl, P1H, P1L) hh, hl = add(hh, hl, P4H, P4L) p += 8 end if p + 4 <= e then local kh, kl = mul(0, readu32(b, p), P1H, P1L) hh, hl = bxor(hh, kh), bxor(hl, kl) :: number hh, hl = rotl(hh, hl, 23) hh, hl = mul(hh, hl, P2H, P2L) hh, hl = add(hh, hl, P3H, P3L) p += 4 end while p < e do local kh, kl = mul(0, readu8(b, p), P5H, P5L) hh, hl = bxor(hh, kh), bxor(hl, kl) :: number hh, hl = rotl(hh, hl, 11) hh, hl = mul(hh, hl, P1H, P1L) p += 1 end -- avalanche hl = bxor(hl, rshift(hh, 1)) -- h ^= h >> 33 hh, hl = mul(hh, hl, P2H, P2L) hh, hl = bxor(hh, rshift(hh, 29)), bxor(hl, bor(rshift(hl, 29), lshift(hh, 3))) :: number -- h ^= h >> 29 hh, hl = mul(hh, hl, P3H, P3L) hl = bxor(hl, hh) -- h ^= h >> 32 return hh, hl end return Xxh64 end __FILES["codecs/entropy/Huffman"] = @native function() -- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order). -- Decoding table entry (u32, indexed by the next P bits; LSB tables by bit-reversed codes, MSB tables by the code): -- symbol * 32 + length a code of length <= P bits -- offset * 32 a link: index offset + the following S bits (subtable of 2^S entries) -- 0 no code (incomplete code set) local Bits = __include("core/Bits") local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 local bfill = buffer.fill local MAXLEN = 16 local Huffman = {} Huffman.MAXLEN = MAXLEN local REV = table.create(256, 0) for i = 0, 255 do local r, v = 0, i for _ = 1, 8 do r = r * 2 + v % 2 v = v // 2 end REV[i + 1] = r end @native local function reverse(code: number, len: number): number return rshift(bor(lshift(REV[band(code, 255) + 1], 8), REV[band(rshift(code, 8), 255) + 1]), 16 - len) end Huffman.reverse = reverse @native function Huffman.capacity(nsym: number, P: number, maxLen: number): number return 2 ^ P + (if maxLen > P then nsym * 2 ^ (maxLen - P) else 0) end local count = table.create(MAXLEN + 1, 0) local nextc = table.create(MAXLEN + 1, 0) @native local function build(lens: buffer, off: number, n: number, tab: buffer, P: number, msb: boolean): number for i = 1, MAXLEN + 1 do count[i] = 0 end for s = 0, n - 1 do local l = readu8(lens, off + s) if l > MAXLEN then return -1 end count[l + 1] += 1 end count[1] = 0 local left = 1 local maxLen = 0 for l = 1, MAXLEN do left = left * 2 - count[l + 1] if left < 0 then return -1 end if count[l + 1] > 0 then maxLen = l end end local code = 0 for l = 1, MAXLEN do code = (code + count[l]) * 2 nextc[l] = code end local psize = lshift(1, P) bfill(tab, 0, 0, psize * 4) local S = if maxLen > P then maxLen - P else 0 local ssize = lshift(1, S) local nextSub = psize for s = 0, n - 1 do local l = readu8(lens, off + s) if l > 0 then local c = nextc[l] nextc[l] = c + 1 local entry = s * 32 + l if l <= P then if msb then local first = lshift(c, P - l) local last = first + lshift(1, P - l) - 1 for i = first, last do writeu32(tab, i * 4, entry) end else local step = lshift(1, l) local i = reverse(c, l) while i < psize do writeu32(tab, i * 4, entry) i += step end end else local pre, rest if msb then pre = rshift(c, l - P) rest = band(c, lshift(1, l - P) - 1) else local rev = reverse(c, l) pre = band(rev, psize - 1) rest = rshift(rev, P) end local e = readu32(tab, pre * 4) local sub if e == 0 then sub = nextSub nextSub += ssize bfill(tab, sub * 4, 0, ssize * 4) writeu32(tab, pre * 4, sub * 32) else sub = rshift(e, 5) end local k = l - P if msb then local first = lshift(rest, S - k) for i = first, first + lshift(1, S - k) - 1 do writeu32(tab, (sub + i) * 4, entry) end else local step = lshift(1, k) local i = rest while i < ssize do writeu32(tab, (sub + i) * 4, entry) i += step end end end end end return S end @native function Huffman.buildLsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number return build(lens, off, n, tab, P, false) end @native function Huffman.buildMsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number return build(lens, off, n, tab, P, true) end @native function Huffman.decodeLsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number local e = readu32(tab, br:peek(P) * 4) local l = band(e, 31) if l == 0 then if e == 0 then return -1 end local idx = br:peek(P + S) e = readu32(tab, (rshift(e, 5) + rshift(idx, P)) * 4) l = band(e, 31) if l == 0 then return -1 end end br:skip(l) return rshift(e, 5) end @native function Huffman.decodeMsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number local e = readu32(tab, br:peek(P) * 4) local l = band(e, 31) if l == 0 then if e == 0 then return -1 end local idx = br:peek(P + S) e = readu32(tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4) l = band(e, 31) if l == 0 then return -1 end end br:skip(l) return rshift(e, 5) end @native function Huffman.codes(lengths: { number }): { number } local cnt = table.create(MAXLEN + 1, 0) for _, l in lengths do if l > 0 then cnt[l + 1] += 1 end end local nxt = table.create(MAXLEN + 1, 0) local code = 0 for l = 1, MAXLEN do code = (code + cnt[l]) * 2 nxt[l + 1] = code end local out = table.create(#lengths, 0) for i, l in lengths do if l > 0 then out[i] = nxt[l + 1] nxt[l + 1] += 1 end end return out end @native function Huffman.lengths(freqs: { number }, maxLen: number): { number } local n = #freqs local out = table.create(n, 0) local syms = {} for i = 1, n do if freqs[i] > 0 then table.insert(syms, i) end end if #syms == 0 then return out end if #syms == 1 then out[syms[1]] = 1 return out end table.sort(syms, @native function(a: number, b: number): boolean if freqs[a] ~= freqs[b] then return freqs[a] < freqs[b] end return a < b end) local m = #syms local weight = table.create(2 * m, 0) local parent = table.create(2 * m, 0) for i = 1, m do weight[i] = freqs[syms[i]] end local li, ni, nn = 1, m + 1, m + 1 @native local function take(): number if li <= m and (ni >= nn or weight[li] <= weight[ni]) then li += 1 return li - 1 end ni += 1 return ni - 1 end for _ = 1, m - 1 do local a = take() local b = take() weight[nn] = weight[a] + weight[b] parent[a] = nn parent[b] = nn nn += 1 end local depth = table.create(2 * m, 0) for i = nn - 2, 1, -1 do depth[i] = depth[parent[i]] + 1 end -- length limiting: JPEG Annex K.3 (move pairs from the deepest level up) local bl = table.create(m + maxLen + 2, 0) local deepest = 0 for i = 1, m do bl[depth[i]] += 1 deepest = math.max(deepest, depth[i]) end for l = deepest, maxLen + 1, -1 do while bl[l] > 0 do local j = l - 2 while j > 0 and bl[j] == 0 do j -= 1 end bl[l] -= 2 bl[l - 1] += 1 bl[j + 1] += 2 bl[j] -= 1 end end local k = 1 for l = math.min(deepest, maxLen), 1, -1 do for _ = 1, bl[l] do out[syms[k]] = l k += 1 end end return out end return Huffman end __FILES["codecs/entropy/RangeCoder"] = function() -- codecs/entropy/RangeCoder: the RFC 6716 range coder used by Opus, a port of libopus celt/entdec.c + entenc.c. -- BSD: licenses/libopus-BSD.txt. local RangeCoder = { Decoder = __include("codecs/entropy/RangeCoder/Decoder"), Encoder = __include("codecs/entropy/RangeCoder/Encoder"), } return RangeCoder end __FILES["codecs/entropy/RangeCoder/Decoder"] = @native function() -- codecs/entropy/RangeCoder/Decoder: the Opus range decoder (RFC 6716 4.1), a port of libopus celt/entdec.c (BSD: -- licenses/libopus-BSD.txt). Raw bits (ec_dec_bits) are read from the end of the frame backwards. -- All values stay below 2^32, so floor division on plain numbers is exact. local RangeDecoder = {} type Dec = { buf: buffer, base: number, storage: number, offs: number, end_offs: number, end_window: number, nend_bits: number, nbits_total: number, rng: number, val: number, rem: number, ext: number, error: number, } local SYM_BITS = 8 local CODE_BITS = 32 local CODE_TOP = 2147483648 -- 1 << 31 local CODE_BOT = 8388608 -- CODE_TOP >> 8 local CODE_EXTRA = 7 -- (CODE_BITS - 2) % SYM_BITS + 1 local SYM_MAX = 255 local UINT_BITS = 8 local WINDOW_SIZE = 32 local countlz = bit32.countlz local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift local readu8 = buffer.readu8 @native local function ilog(x: number): number return 32 - countlz(x) end RangeDecoder.ilog = ilog @native local function normalize(d: Dec) local rng, val, rem = d.rng, d.val, d.rem while rng <= CODE_BOT do d.nbits_total += SYM_BITS rng = rng * 256 local sym = rem local offs = d.offs if offs < d.storage then rem = readu8(d.buf, d.base + offs) d.offs = offs + 1 else rem = 0 end sym = rshift(bor(lshift(sym, 8), rem), SYM_BITS - CODE_EXTRA) val = band(val * 256 + band(SYM_MAX, bit32.bnot(sym)), CODE_TOP - 1) end d.rng, d.val, d.rem = rng, val, rem end @native function RangeDecoder.new(buf: buffer, base: number, storage: number): Dec local d: Dec = { buf = buf, base = base, storage = storage, offs = 0, end_offs = 0, end_window = 0, nend_bits = 0, nbits_total = CODE_BITS + 1 - ((CODE_BITS - CODE_EXTRA) // SYM_BITS) * SYM_BITS, rng = 128, -- 1 << CODE_EXTRA val = 0, rem = 0, ext = 0, error = 0, } local rem = 0 if storage > 0 then rem = readu8(buf, base) d.offs = 1 end d.rem = rem d.val = d.rng - 1 - rshift(rem, SYM_BITS - CODE_EXTRA) normalize(d) return d end @native function RangeDecoder.decode(d: Dec, ft: number): number local ext = d.rng // ft d.ext = ext local s = d.val // ext return ft - math.min(s + 1, ft) end @native function RangeDecoder.decodeBin(d: Dec, bits: number): number local ext = rshift(d.rng, bits) d.ext = ext local s = d.val // ext local ft = lshift(1, bits) return ft - math.min(s + 1, ft) end @native function RangeDecoder.update(d: Dec, fl: number, fh: number, ft: number) local s = d.ext * (ft - fh) d.val = band(d.val - s, 0xFFFFFFFF) -- uint32 wrap (corrupt streams only) if fl > 0 then d.rng = d.ext * (fh - fl) else d.rng -= s end normalize(d) end @native function RangeDecoder.bitLogp(d: Dec, logp: number): boolean local r = d.rng local v = d.val local s = rshift(r, logp) local ret = v < s if ret then d.rng = s else d.val = v - s d.rng = r - s end normalize(d) return ret end @native function RangeDecoder.icdf(d: Dec, icdf: { number }, off: number, ftb: number): number local s = d.rng local v = d.val local r = rshift(s, ftb) local ret = -1 local t repeat t = s ret += 1 s = r * icdf[off + ret] until v >= s d.val = v - s d.rng = t - s normalize(d) return ret end @native function RangeDecoder.bits(d: Dec, bits: number): number local window = d.end_window local available = d.nend_bits if available < bits then repeat local b = 0 local eo = d.end_offs if eo < d.storage then eo += 1 d.end_offs = eo b = readu8(d.buf, d.base + d.storage - eo) end window = bor(window, lshift(b, available)) available += SYM_BITS until available > WINDOW_SIZE - SYM_BITS end local ret = band(window, lshift(1, bits) - 1) if bits == 32 then ret = window end window = rshift(window, bits) available -= bits d.end_window = window d.nend_bits = available d.nbits_total += bits return ret end @native function RangeDecoder.uint(d: Dec, ft0: number): number local ft = ft0 - 1 local ftb = ilog(ft) if ftb > UINT_BITS then ftb -= UINT_BITS local ft1 = rshift(ft, ftb) + 1 local s = RangeDecoder.decode(d, ft1) RangeDecoder.update(d, s, s + 1, ft1) local t = bor(lshift(s, ftb), RangeDecoder.bits(d, ftb)) if t <= ft then return t end d.error = 1 return ft else local s = RangeDecoder.decode(d, ft0) RangeDecoder.update(d, s, s + 1, ft0) return s end end @native function RangeDecoder.tell(d: Dec): number return d.nbits_total - ilog(d.rng) end local correction = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } @native function RangeDecoder.tellFrac(d: Dec): number local nbits = d.nbits_total * 8 local l = ilog(d.rng) local r = rshift(d.rng, l - 16) local b = rshift(r, 12) - 8 if r > correction[b + 1] then b += 1 end return nbits - (l * 8 + b) end return RangeDecoder end __FILES["codecs/entropy/RangeCoder/Encoder"] = @native function() -- codecs/entropy/RangeCoder/Encoder: the Opus range encoder (RFC 6716 5.1), a port of libopus celt/entenc.c (BSD: -- licenses/libopus-BSD.txt). Range-coded symbols from the front of the frame, raw bits (ec_enc_bits) from the back. local RangeEncoder = {} type Enc = { buf: buffer, storage: number, offs: number, end_offs: number, end_window: number, nend_bits: number, nbits_total: number, rng: number, val: number, rem: number, ext: number, error: number, } local CODE_TOP = 2147483648 -- 1 << 31 local CODE_BOT = 8388608 -- CODE_TOP >> 8 local CODE_SHIFT = 23 local SYM_MAX = 255 local countlz = bit32.countlz local band = bit32.band local readu8, writeu8 = buffer.readu8, buffer.writeu8 local floor = math.floor @native local function ilog(x: number): number return 32 - countlz(x) end RangeEncoder.ilog = ilog @native function RangeEncoder.new(storage: number): Enc return { buf = buffer.create(math.max(storage, 1)), storage = storage, offs = 0, end_offs = 0, end_window = 0, nend_bits = 0, nbits_total = 33, -- EC_CODE_BITS + 1 rng = CODE_TOP, val = 0, rem = -1, ext = 0, error = 0, } end @native local function writeByte(e: Enc, v: number) if e.offs + e.end_offs >= e.storage then e.error = -1 return end writeu8(e.buf, e.offs, band(v, 255)) e.offs += 1 end @native local function writeByteAtEnd(e: Enc, v: number) if e.offs + e.end_offs >= e.storage then e.error = -1 return end e.end_offs += 1 writeu8(e.buf, e.storage - e.end_offs, band(v, 255)) end @native local function carryOut(e: Enc, c: number) if c ~= SYM_MAX then local carry = if c >= 256 then 1 else 0 if e.rem >= 0 then writeByte(e, e.rem + carry) end if e.ext > 0 then local sym = band(SYM_MAX + carry, 255) repeat writeByte(e, sym) e.ext -= 1 until e.ext <= 0 end e.rem = band(c, 255) else e.ext += 1 end end @native local function normalize(e: Enc) while e.rng <= CODE_BOT do carryOut(e, floor(e.val / 8388608)) e.val = (e.val * 256) % CODE_TOP e.rng *= 256 e.nbits_total += 8 end end @native function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number) local r = floor(e.rng / ft) if fl > 0 then e.val += e.rng - r * (ft - fl) e.rng = r * (fh - fl) else e.rng -= r * (ft - fh) end normalize(e) end @native function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number) local ft = 2 ^ bits local r = floor(e.rng / ft) if fl > 0 then e.val += e.rng - r * (ft - fl) e.rng = r * (fh - fl) else e.rng -= r * (ft - fh) end normalize(e) end @native function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number) local r = e.rng local s = floor(r / 2 ^ logp) r -= s if v then e.val += r e.rng = s else e.rng = r end normalize(e) end @native function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number) local r = floor(e.rng / 2 ^ ftb) if s > 0 then e.val += e.rng - r * icdf[s] e.rng = r * (icdf[s] - icdf[s + 1]) else e.rng -= r * icdf[s + 1] end normalize(e) end @native function RangeEncoder.bits(e: Enc, fl: number, n: number) local window = e.end_window local used = e.nend_bits if used + n > 32 then repeat writeByteAtEnd(e, window % 256) window = floor(window / 256) used -= 8 until used < 8 end window += fl * 2 ^ used used += n e.end_window = window e.nend_bits = used e.nbits_total += n end @native function RangeEncoder.uint(e: Enc, fl: number, ft: number) ft -= 1 local ftb = ilog(ft) if ftb > 8 then ftb -= 8 local sh = 2 ^ ftb local ft1 = floor(ft / sh) + 1 local hi = floor(fl / sh) RangeEncoder.encode(e, hi, hi + 1, ft1) RangeEncoder.bits(e, fl - hi * sh, ftb) else RangeEncoder.encode(e, fl, fl + 1, ft + 1) end end @native function RangeEncoder.tell(e: Enc): number return e.nbits_total - ilog(e.rng) end local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } @native function RangeEncoder.tellFrac(e: Enc): number local nbits = e.nbits_total * 8 local l = ilog(e.rng) local r = floor(e.rng / 2 ^ (l - 16)) local b = floor(r / 4096) - 8 if r > CORRECTION[b + 1] then b += 1 end return nbits - (l * 8 + b) end @native function RangeEncoder.done(e: Enc) local l = 32 - ilog(e.rng) local msk = floor((CODE_TOP - 1) / 2 ^ l) local stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) if stop + msk >= e.val + e.rng then l += 1 msk = floor(msk / 2) stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) end while l > 0 do carryOut(e, floor(stop / 8388608)) stop = (stop * 256) % CODE_TOP l -= 8 end if e.rem >= 0 or e.ext > 0 then carryOut(e, 0) end local window = e.end_window local used = e.nend_bits while used >= 8 do writeByteAtEnd(e, window % 256) window = floor(window / 256) used -= 8 end if e.error == 0 then local a, b = e.offs, e.storage - e.end_offs if b > a then buffer.fill(e.buf, a, 0, b - a) end if used > 0 then if e.end_offs >= e.storage then e.error = -1 else l = -l if e.offs + e.end_offs >= e.storage and l < used then window = window % 2 ^ l e.error = -1 end local p = e.storage - e.end_offs - 1 writeu8(e.buf, p, bit32.bor(readu8(e.buf, p), window)) end end end end local _ = CODE_SHIFT return RangeEncoder end __FILES["codecs/font/Bitmap"] = function() -- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT) and their 1-bit rows. -- Bit rows are MSB = left pixel unless lsbFirst; a pixel >= 128 is on. local Err = __include("core/Err") local Types = __include("Types") local Bitmap = {} local readu8, writeu8 = buffer.readu8, buffer.writeu8 function Bitmap.unpack(b: buffer, off: number, w: number, h: number, stride: number, lsbFirst: boolean?): buffer local out = buffer.create(math.max(0, w * h)) local n = buffer.len(b) for y = 0, h - 1 do local row = off + y * stride for x = 0, w - 1 do local p = row + bit32.rshift(x, 3) if p >= 0 and p < n then local byte = readu8(b, p) local bitn = if lsbFirst then bit32.band(x, 7) else 7 - bit32.band(x, 7) if bit32.band(bit32.rshift(byte, bitn), 1) ~= 0 then writeu8(out, y * w + x, 255) end end end end return out end function Bitmap.pack(px: buffer, w: number, h: number, stride: number?, lsbFirst: boolean?): buffer local s = stride or math.ceil(w / 8) local out = buffer.create(math.max(0, s * h)) local n = buffer.len(px) for y = 0, h - 1 do for x = 0, w - 1 do local i = y * w + x if i < n and readu8(px, i) >= 128 then local p = y * s + bit32.rshift(x, 3) local bitn = if lsbFirst then bit32.band(x, 7) else 7 - bit32.band(x, 7) writeu8(out, p, bit32.bor(readu8(out, p), bit32.lshift(1, bitn))) end end end return out end local Face = {} Face.__index = Face function Face.glyphIndex(self: any, cp: number): number return self._index[cp] or 0 end function Face.advance(self: any, g: number): number local gl = self.bitmap.glyphs[g + 1] return if gl then gl.advance else 0 end function Face.kern(_self: any, _a: number, _b: number): number return 0 end function Face.outline(_self: any, _g: number): { any }? return nil end function Face.rasterize(self: any, g: number, px: number?): Types.Image? local gl: Types.BitmapGlyph? = self.bitmap.glyphs[g + 1] if not gl or gl.width < 0 or gl.height < 0 then return nil end local img = Types.Image.new(gl.width, gl.height, "alpha8") local n = math.min(buffer.len(img.pixels), buffer.len(gl.pixels)) if n > 0 then buffer.copy(img.pixels, 0, gl.pixels, 0, n) end img.meta.left = gl.left img.meta.top = gl.top img.meta.advance = gl.advance img.meta.glyph = g img.meta.scale = if type(px) == "number" and self.bitmap.size > 0 then px / self.bitmap.size else 1 return img end function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta: { [string]: any }?): any local index: { [number]: number } = {} for i, gl in strike.glyphs do local cp = gl.codepoint if cp and index[cp] == nil then index[cp] = i - 1 end end if strike.map then for cp, g in strike.map do if index[cp] == nil and g >= 0 and g < #strike.glyphs then index[cp] = g end end end local f = setmetatable({ kind = "font", info = info or {}, unitsPerEm = strike.size, ascent = strike.ascent, descent = -strike.descent, lineGap = 0, numGlyphs = #strike.glyphs, bitmap = strike, meta = meta or {}, _index = index, }, Face) if strike.default then setmetatable(index, { __index = function() return strike.default end }) end return f end type StrikeOptions = { px: number?, chars: (string | { number })?, threshold: number?, } local function codepoints(chars: (string | { number })?): { number } if type(chars) == "table" then return chars end local out = {} if type(chars) == "string" then for _, c in utf8.codes(chars) do table.insert(out, c) end return out end for c = 32, 126 do table.insert(out, c) end return out end function Bitmap.strike(font: any, opts: StrikeOptions?): (Types.BitmapStrike?, Err.Err?) if type(font) ~= "table" or font.kind ~= "font" then return nil, Err.new(Err.ARG, "expected a Font") end if type(font.bitmap) == "table" and type(font.bitmap.glyphs) == "table" then return font.bitmap, nil end if type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then return nil, Err.new(Err.ARG, "font has no glyphs to rasterize") end local o: StrikeOptions = opts or {} local px = o.px or 16 if type(px) ~= "number" or px < 1 or px > 1024 then return nil, Err.new(Err.ARG, "px must be 1..1024") end local threshold = o.threshold or 128 local upm = if type(font.unitsPerEm) == "number" and font.unitsPerEm > 0 then font.unitsPerEm else px local scale = px / upm local ascent = math.ceil((font.ascent or upm) * scale) local descent = math.ceil(math.abs(font.descent or 0) * scale) local glyphs: { Types.BitmapGlyph } = {} local function add(cp: number?, g: number) local ok, img = pcall(font.rasterize, font, g, px) local adv = 0 local aok, a = pcall(font.advance, font, g) if aok and type(a) == "number" then adv = math.floor(a * scale + 0.5) end local gl: Types.BitmapGlyph = { codepoint = cp, width = 0, height = 0, left = 0, top = 0, advance = adv, pixels = buffer.create(0) } if ok and type(img) == "table" and type(img.pixels) == "buffer" and img.format == "alpha8" then local n = img.width * img.height local pxs = buffer.create(n) for i = 0, math.min(n, buffer.len(img.pixels)) - 1 do if readu8(img.pixels, i) >= threshold then writeu8(pxs, i, 255) end end gl.width, gl.height, gl.pixels = img.width, img.height, pxs gl.left = math.floor(img.meta.left or 0) gl.top = math.floor(img.meta.top or 0) if type(img.meta.advance) == "number" then gl.advance = math.floor(img.meta.advance + 0.5) end end table.insert(glyphs, gl) end add(nil, 0) for _, cp in codepoints(o.chars) do local ok, g = pcall(font.glyphIndex, font, cp) if ok and type(g) == "number" and g > 0 then add(cp, g) end end return { size = px, ascent = ascent, descent = descent, glyphs = glyphs, default = 0 }, nil end return Bitmap end __FILES["codecs/font/Cff"] = function() -- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177), the outlines of .otf fonts. -- Charstrings ported from stb_truetype 1.26 (public domain / MIT) via imgui-luau's imstb_truetype.lua, plus -- flex1's last delta, an operation budget, and the TN #5177 4.4 arithmetic / storage operators. local Cff = {} local readu8 = buffer.readu8 local blen = buffer.len local function u8(b: buffer, o: number): number if o < 0 or o + 1 > blen(b) then return 0 end return readu8(b, o) end local function uN(b: buffer, o: number, n: number): number local v = 0 for i = 0, n - 1 do v = v * 256 + u8(b, o + i) end return v end type Index = { count: number, offSize: number, offsets: number, data: number, next: number } type Font = { buf: buffer, base: number, limit: number, charStrings: Index, gsubrs: Index, subrs: Index?, fdSubrs: { Index? }?, fdSelect: number?, numGlyphs: number, cid: boolean, fontMatrix: { number }?, } local function index(b: buffer, p: number, limit: number): Index? if p + 2 > limit then return nil end local count = uN(b, p, 2) if count == 0 then return { count = 0, offSize = 1, offsets = p + 2, data = p + 2, next = p + 2 } end local offSize = u8(b, p + 2) if offSize < 1 or offSize > 4 then return nil end local offsets = p + 3 local data = offsets + (count + 1) * offSize - 1 -- offsets are 1-based if data + 1 > limit then return nil end local last = uN(b, offsets + count * offSize, offSize) if data + last > limit then return nil end return { count = count, offSize = offSize, offsets = offsets, data = data, next = data + last } end local function item(b: buffer, idx: Index, i: number): (number?, number) if i < 0 or i >= idx.count then return nil, 0 end local s = uN(b, idx.offsets + i * idx.offSize, idx.offSize) local e = uN(b, idx.offsets + (i + 1) * idx.offSize, idx.offSize) if s < 1 or e < s or idx.data + e > idx.next then return nil, 0 end return idx.data + s, e - s end Cff.item = item -- DICT operators: two-byte ops (12 x) are keyed 1200 + x local function dict(b: buffer, p: number, n: number): { [number]: { number } } local out: { [number]: { number } } = {} local ops: { number } = {} local e = p + n while p < e do local b0 = u8(b, p) if b0 <= 21 then local op = b0 p += 1 if b0 == 12 then op = 1200 + u8(b, p) p += 1 end out[op] = ops ops = {} elseif b0 == 28 then local v = uN(b, p + 1, 2) table.insert(ops, if v >= 32768 then v - 65536 else v) p += 3 elseif b0 == 29 then local v = uN(b, p + 1, 4) table.insert(ops, if v >= 2147483648 then v - 4294967296 else v) p += 5 elseif b0 == 30 then -- real number: BCD nibbles local s = {} p += 1 local done = false while p < e and not done do local byte = u8(b, p) p += 1 for _, nib in { byte // 16, byte % 16 } do if nib <= 9 then table.insert(s, tostring(nib)) elseif nib == 10 then table.insert(s, ".") elseif nib == 11 then table.insert(s, "E") elseif nib == 12 then table.insert(s, "E-") elseif nib == 14 then table.insert(s, "-") elseif nib == 15 then done = true break end end end table.insert(ops, tonumber(table.concat(s)) or 0) elseif b0 >= 32 and b0 <= 246 then table.insert(ops, b0 - 139) p += 1 elseif b0 >= 247 and b0 <= 250 then table.insert(ops, (b0 - 247) * 256 + u8(b, p + 1) + 108) p += 2 elseif b0 >= 251 and b0 <= 254 then table.insert(ops, -(b0 - 251) * 256 - u8(b, p + 1) - 108) p += 2 else p += 1 -- reserved end if #ops > 48 then return out end end return out end local function privateSubrs(b: buffer, base: number, limit: number, d: { [number]: { number } }): Index? local pr = d[18] if not pr or #pr < 2 then return nil end local size, off = pr[1], pr[2] local ps = base + off if size < 0 or off < 0 or ps + size > limit then return nil end local pd = dict(b, ps, size) local s = pd[19] if not s or #s < 1 then return nil end return index(b, ps + s[1], limit) end function Cff.parse(b: buffer, offset: number, length: number): (Font?, string?) local base, limit = offset, math.min(offset + length, blen(b)) if limit - base < 4 then return nil, "truncated CFF header" end local major, hdrSize = u8(b, base), u8(b, base + 2) if major == 2 then return nil, "unsupported: CFF2 (variable font outlines)" end if major ~= 1 then return nil, "bad CFF version " .. major end local names = index(b, base + hdrSize, limit) if not names then return nil, "bad name INDEX" end local tops = index(b, names.next, limit) if not tops or tops.count < 1 then return nil, "bad Top DICT INDEX" end local strings = index(b, tops.next, limit) if not strings then return nil, "bad String INDEX" end local gsubrs = index(b, strings.next, limit) if not gsubrs then return nil, "bad global subrs INDEX" end local ts, tl = item(b, tops, 0) if not ts then return nil, "bad Top DICT" end local top = dict(b, ts, tl) local cso = top[17] if not cso or #cso < 1 then return nil, "no CharStrings" end local cst = top[1206] if cst and cst[1] ~= 2 then return nil, "unsupported: charstring type " .. tostring(cst[1]) end local charStrings = index(b, base + cso[1], limit) if not charStrings then return nil, "bad CharStrings INDEX" end local f: Font = { buf = b, base = base, limit = limit, charStrings = charStrings, gsubrs = gsubrs, subrs = nil, fdSubrs = nil, fdSelect = nil, numGlyphs = charStrings.count, cid = top[1230] ~= nil, fontMatrix = top[1207], } if f.cid then local fda, fds = top[1236], top[1237] if not fda or not fds then return nil, "CID font without FDArray / FDSelect" end local fdArray = index(b, base + fda[1], limit) if not fdArray then return nil, "bad FDArray" end local list: { Index? } = {} for i = 0, math.min(fdArray.count, 256) - 1 do local s, l = item(b, fdArray, i) list[i + 1] = if s then privateSubrs(b, base, limit, dict(b, s, l)) else nil end f.fdSubrs = list f.fdSelect = base + fds[1] else f.subrs = privateSubrs(b, base, limit, top) end return f, nil end local function bias(count: number): number return if count < 1240 then 107 elseif count < 33900 then 1131 else 32768 end local function localSubrs(f: Font, g: number): Index? if not f.cid then return f.subrs end local b, p = f.buf, f.fdSelect :: number local fmt = u8(b, p) local fd = -1 if fmt == 0 then fd = u8(b, p + 1 + g) elseif fmt == 3 then local n = uN(b, p + 1, 2) local first = uN(b, p + 3, 2) for i = 0, n - 1 do local q = p + 5 + i * 3 local v = u8(b, q) local nxt = uN(b, q + 1, 2) if g >= first and g < nxt then fd = v break end first = nxt end end local list = f.fdSubrs :: { Index? } return list[fd + 1] end local BUDGET = 200000 -- operators per glyph (subroutine bombs) function Cff.outline(f: Font, g: number): ({ any }?, string?) local b = f.buf local p, len = item(b, f.charStrings, g) if not p then return nil, "bad glyph index " .. tostring(g) end local e = p + len local cmds: { any } = {} local s: { number } = table.create(48, 0) local sp = 0 local trans = table.create(32, 0) :: { number } local x, y = 0, 0 local open = false local maskbits = 0 local inHeader = true local stack: { { number } } = {} local subrs: Index? = nil local haveSubrs = false local ops = 0 local seed = 12345 local function moveTo(dx: number, dy: number) if open then table.insert(cmds, { op = "close" }) end x += dx y += dy table.insert(cmds, { op = "moveTo", x, y }) open = true end local function lineTo(dx: number, dy: number) if not open then moveTo(0, 0) end x += dx y += dy table.insert(cmds, { op = "lineTo", x, y }) end local function curveTo(dx1: number, dy1: number, dx2: number, dy2: number, dx3: number, dy3: number) if not open then moveTo(0, 0) end local x1, y1 = x + dx1, y + dy1 local x2, y2 = x1 + dx2, y1 + dy2 x, y = x2 + dx3, y2 + dy3 table.insert(cmds, { op = "cubicTo", x1, y1, x2, y2, x, y }) end local function S(i: number): number return s[i + 1] or 0 end while true do if p >= e then if #stack > 0 then local r = table.remove(stack) :: { number } p, e = r[1], r[2] continue end break end ops += 1 if ops > BUDGET then return nil, "charstring too long (subroutine loop?)" end local b0 = u8(b, p) p += 1 local clear = true local i = 0 if b0 == 19 or b0 == 20 then -- hintmask, cntrmask if inHeader then maskbits += sp // 2 end inHeader = false p += (maskbits + 7) // 8 elseif b0 == 1 or b0 == 3 or b0 == 18 or b0 == 23 then -- hstem vstem hstemhm vstemhm maskbits += sp // 2 elseif b0 == 21 then -- rmoveto inHeader = false if sp < 2 then return nil, "rmoveto stack" end moveTo(S(sp - 2), S(sp - 1)) elseif b0 == 4 then -- vmoveto inHeader = false if sp < 1 then return nil, "vmoveto stack" end moveTo(0, S(sp - 1)) elseif b0 == 22 then -- hmoveto inHeader = false if sp < 1 then return nil, "hmoveto stack" end moveTo(S(sp - 1), 0) elseif b0 == 5 then -- rlineto if sp < 2 then return nil, "rlineto stack" end while i + 1 < sp do lineTo(S(i), S(i + 1)) i += 2 end elseif b0 == 6 or b0 == 7 then -- hlineto / vlineto: alternate if sp < 1 then return nil, "hlineto stack" end local horiz = b0 == 6 while i < sp do if horiz then lineTo(S(i), 0) else lineTo(0, S(i)) end horiz = not horiz i += 1 end elseif b0 == 31 or b0 == 30 then -- hvcurveto / vhcurveto: alternate if sp < 4 then return nil, "hvcurveto stack" end local horiz = b0 == 31 while i + 3 < sp do local last = if sp - i == 5 then S(i + 4) else 0 if horiz then curveTo(S(i), 0, S(i + 1), S(i + 2), last, S(i + 3)) else curveTo(0, S(i), S(i + 1), S(i + 2), S(i + 3), last) end horiz = not horiz i += 4 end elseif b0 == 8 then -- rrcurveto if sp < 6 then return nil, "rrcurveto stack" end while i + 5 < sp do curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) i += 6 end elseif b0 == 24 then -- rcurveline if sp < 8 then return nil, "rcurveline stack" end while i + 5 < sp - 2 do curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) i += 6 end lineTo(S(i), S(i + 1)) elseif b0 == 25 then -- rlinecurve if sp < 8 then return nil, "rlinecurve stack" end while i + 1 < sp - 6 do lineTo(S(i), S(i + 1)) i += 2 end curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) elseif b0 == 26 or b0 == 27 then -- vvcurveto / hhcurveto if sp < 4 then return nil, "vv/hhcurveto stack" end local f0 = 0 if sp % 2 == 1 then f0 = S(0) i = 1 end while i + 3 < sp do if b0 == 27 then curveTo(S(i), f0, S(i + 1), S(i + 2), S(i + 3), 0) else curveTo(f0, S(i), S(i + 1), S(i + 2), 0, S(i + 3)) end f0 = 0 i += 4 end elseif b0 == 10 or b0 == 29 then -- callsubr / callgsubr if b0 == 10 and not haveSubrs then subrs = localSubrs(f, g) haveSubrs = true end if sp < 1 then return nil, "callsubr stack" end local idx = if b0 == 10 then subrs else f.gsubrs if not idx then return nil, "no subroutines" end local n = math.floor(S(sp - 1)) + bias(idx.count) sp -= 1 if #stack >= 10 then return nil, "subroutine recursion limit" end local sp0, sl = item(b, idx, n) if not sp0 then return nil, "subroutine " .. n .. " not found" end table.insert(stack, { p, e }) p, e = sp0, sp0 + sl clear = false elseif b0 == 11 then -- return if #stack == 0 then return nil, "return outside a subroutine" end local r = table.remove(stack) :: { number } p, e = r[1], r[2] clear = false elseif b0 == 14 then -- endchar if open then table.insert(cmds, { op = "close" }) end return cmds, nil elseif b0 == 12 then -- escape local b1 = u8(b, p) p += 1 if b1 == 34 then -- hflex if sp < 7 then return nil, "hflex stack" end curveTo(S(0), 0, S(1), S(2), S(3), 0) curveTo(S(4), 0, S(5), -S(2), S(6), 0) elseif b1 == 35 then -- flex if sp < 13 then return nil, "flex stack" end curveTo(S(0), S(1), S(2), S(3), S(4), S(5)) curveTo(S(6), S(7), S(8), S(9), S(10), S(11)) elseif b1 == 36 then -- hflex1 if sp < 9 then return nil, "hflex1 stack" end curveTo(S(0), S(1), S(2), S(3), S(4), 0) curveTo(S(5), 0, S(6), S(7), S(8), -(S(1) + S(3) + S(7))) elseif b1 == 37 then -- flex1 if sp < 11 then return nil, "flex1 stack" end local dx = S(0) + S(2) + S(4) + S(6) + S(8) local dy = S(1) + S(3) + S(5) + S(7) + S(9) local dx6, dy6 = S(10), S(10) if math.abs(dx) > math.abs(dy) then dy6 = -dy else dx6 = -dx end curveTo(S(0), S(1), S(2), S(3), S(4), S(5)) curveTo(S(6), S(7), S(8), S(9), dx6, dy6) else clear = false local top = sp local a, c = S(top - 2), S(top - 1) local function set(n: number, v: number) sp = math.max(0, sp - n) sp += 1 s[sp] = v end if b1 == 3 then set(2, if a ~= 0 and c ~= 0 then 1 else 0) -- and elseif b1 == 4 then set(2, if a ~= 0 or c ~= 0 then 1 else 0) -- or elseif b1 == 5 then set(1, if c == 0 then 1 else 0) -- not elseif b1 == 9 then set(1, math.abs(c)) elseif b1 == 10 then set(2, a + c) elseif b1 == 11 then set(2, a - c) elseif b1 == 12 then set(2, if c ~= 0 then a / c else 0) elseif b1 == 14 then set(1, -c) elseif b1 == 15 then set(2, if a == c then 1 else 0) elseif b1 == 18 then sp = math.max(0, sp - 1) -- drop elseif b1 == 20 then -- put: val i local k = math.floor(c) if k >= 0 and k < 32 then trans[k + 1] = a end sp = math.max(0, sp - 2) elseif b1 == 21 then -- get local k = math.floor(c) set(1, if k >= 0 and k < 32 then trans[k + 1] else 0) elseif b1 == 22 then -- ifelse: s1 s2 v1 v2 -> v1 <= v2 ? s1 : s2 local s1, s2, v1, v2 = S(top - 4), S(top - 3), S(top - 2), S(top - 1) set(4, if v1 <= v2 then s1 else s2) elseif b1 == 23 then -- random (deterministic) seed = (seed * 1103515245 + 12345) % 2147483648 set(0, (seed % 65535 + 1) / 65536) elseif b1 == 24 then set(2, a * c) elseif b1 == 26 then set(1, math.sqrt(math.max(0, c))) elseif b1 == 27 then set(0, c) -- dup elseif b1 == 28 then -- exch if sp >= 2 then s[sp - 1], s[sp] = s[sp], s[sp - 1] end elseif b1 == 29 then -- index local k = math.floor(c) local v = if k < 0 then S(top - 2) else S(top - 2 - k) set(1, v) elseif b1 == 30 then -- roll: n j local n, j = math.floor(a), math.floor(c) sp = math.max(0, sp - 2) if n > 0 and n <= sp then local base = sp - n local tmp = table.create(n, 0) for k = 0, n - 1 do tmp[((k + j) % n) + 1] = s[base + k + 1] end for k = 0, n - 1 do s[base + k + 1] = tmp[k + 1] end end else return nil, "unknown operator 12 " .. b1 end if sp > 48 then return nil, "stack overflow" end end elseif b0 >= 32 or b0 == 28 then -- operands local v if b0 == 28 then v = uN(b, p, 2) if v >= 32768 then v -= 65536 end p += 2 elseif b0 <= 246 then v = b0 - 139 elseif b0 <= 250 then v = (b0 - 247) * 256 + u8(b, p) + 108 p += 1 elseif b0 <= 254 then v = -(b0 - 251) * 256 - u8(b, p) - 108 p += 1 else -- 255: 16.16 fixed v = uN(b, p, 4) if v >= 2147483648 then v -= 4294967296 end v /= 65536 p += 4 end if sp >= 48 then return nil, "operand stack overflow" end sp += 1 s[sp] = v clear = false else return nil, "reserved operator " .. b0 end if clear then sp = 0 end end return nil, "no endchar" end return Cff end __FILES["codecs/font/GlyphNames"] = function() -- codecs/font/GlyphNames: PostScript glyph names -> Unicode (AGL specification) and Adobe StandardEncoding. -- Data: the Adobe Glyph List For New Fonts (AGLFN 1.7, BSD-3-Clause: licenses/agl-LICENSE.txt; the f-ligatures and -- dotlessj added) and StandardEncoding, generated from fontTools.agl / fontTools.encodings.StandardEncoding. local GlyphNames = {} -- AGLFN: "name hex" pairs local AGL = "" .. "A 41 AE C6 AEacute 1FC Aacute C1 Abreve 102 Acircumflex C2 Adieresis C4 Agrave C0 Alpha 391 " .. "Alphatonos 386 Amacron 100 Aogonek 104 Aring C5 Aringacute 1FA Atilde C3 B 42 Beta 392 C 43 Cacute " .. "106 Ccaron 10C Ccedilla C7 Ccircumflex 108 Cdotaccent 10A Chi 3A7 D 44 Dcaron 10E Dcroat 110 Delta " .. "2206 E 45 Eacute C9 Ebreve 114 Ecaron 11A Ecircumflex CA Edieresis CB Edotaccent 116 Egrave C8 " .. "Emacron 112 Eng 14A Eogonek 118 Epsilon 395 Epsilontonos 388 Eta 397 Etatonos 389 Eth D0 Euro 20AC " .. "F 46 G 47 Gamma 393 Gbreve 11E Gcaron 1E6 Gcircumflex 11C Gdotaccent 120 H 48 H18533 25CF H18543 " .. "25AA H18551 25AB H22073 25A1 Hbar 126 Hcircumflex 124 I 49 IJ 132 Iacute CD Ibreve 12C Icircumflex " .. "CE Idieresis CF Idotaccent 130 Ifraktur 2111 Igrave CC Imacron 12A Iogonek 12E Iota 399 " .. "Iotadieresis 3AA Iotatonos 38A Itilde 128 J 4A Jcircumflex 134 K 4B Kappa 39A L 4C Lacute 139 " .. "Lambda 39B Lcaron 13D Ldot 13F Lslash 141 M 4D Mu 39C N 4E Nacute 143 Ncaron 147 Ntilde D1 Nu 39D O " .. "4F OE 152 Oacute D3 Obreve 14E Ocircumflex D4 Odieresis D6 Ograve D2 Ohorn 1A0 Ohungarumlaut 150 " .. "Omacron 14C Omega 2126 Omegatonos 38F Omicron 39F Omicrontonos 38C Oslash D8 Oslashacute 1FE Otilde " .. "D5 P 50 Phi 3A6 Pi 3A0 Psi 3A8 Q 51 R 52 Racute 154 Rcaron 158 Rfraktur 211C Rho 3A1 S 53 SF010000 " .. "250C SF020000 2514 SF030000 2510 SF040000 2518 SF050000 253C SF060000 252C SF070000 2534 SF080000 " .. "251C SF090000 2524 SF100000 2500 SF110000 2502 SF190000 2561 SF200000 2562 SF210000 2556 SF220000 " .. "2555 SF230000 2563 SF240000 2551 SF250000 2557 SF260000 255D SF270000 255C SF280000 255B SF360000 " .. "255E SF370000 255F SF380000 255A SF390000 2554 SF400000 2569 SF410000 2566 SF420000 2560 SF430000 " .. "2550 SF440000 256C SF450000 2567 SF460000 2568 SF470000 2564 SF480000 2565 SF490000 2559 SF500000 " .. "2558 SF510000 2552 SF520000 2553 SF530000 256B SF540000 256A Sacute 15A Scaron 160 Scedilla 15E " .. "Scircumflex 15C Sigma 3A3 T 54 Tau 3A4 Tbar 166 Tcaron 164 Theta 398 Thorn DE U 55 Uacute DA Ubreve " .. "16C Ucircumflex DB Udieresis DC Ugrave D9 Uhorn 1AF Uhungarumlaut 170 Umacron 16A Uogonek 172 " .. "Upsilon 3A5 Upsilon1 3D2 Upsilondieresis 3AB Upsilontonos 38E Uring 16E Utilde 168 V 56 W 57 Wacute " .. "1E82 Wcircumflex 174 Wdieresis 1E84 Wgrave 1E80 X 58 Xi 39E Y 59 Yacute DD Ycircumflex 176 " .. "Ydieresis 178 Ygrave 1EF2 Z 5A Zacute 179 Zcaron 17D Zdotaccent 17B Zeta 396 a 61 aacute E1 abreve " .. "103 acircumflex E2 acute B4 acutecomb 301 adieresis E4 ae E6 aeacute 1FD agrave E0 aleph 2135 alpha " .. "3B1 alphatonos 3AC amacron 101 ampersand 26 angle 2220 angleleft 2329 angleright 232A anoteleia 387 " .. "aogonek 105 approxequal 2248 aring E5 aringacute 1FB arrowboth 2194 arrowdblboth 21D4 arrowdbldown " .. "21D3 arrowdblleft 21D0 arrowdblright 21D2 arrowdblup 21D1 arrowdown 2193 arrowleft 2190 arrowright " .. "2192 arrowup 2191 arrowupdn 2195 arrowupdnbse 21A8 asciicircum 5E asciitilde 7E asterisk 2A " .. "asteriskmath 2217 at 40 atilde E3 b 62 backslash 5C bar 7C beta 3B2 block 2588 braceleft 7B " .. "braceright 7D bracketleft 5B bracketright 5D breve 2D8 brokenbar A6 bullet 2022 c 63 cacute 107 " .. "caron 2C7 carriagereturn 21B5 ccaron 10D ccedilla E7 ccircumflex 109 cdotaccent 10B cedilla B8 cent " .. "A2 chi 3C7 circle 25CB circlemultiply 2297 circleplus 2295 circumflex 2C6 club 2663 colon 3A " .. "colonmonetary 20A1 comma 2C congruent 2245 copyright A9 currency A4 d 64 dagger 2020 daggerdbl 2021 " .. "dcaron 10F dcroat 111 degree B0 delta 3B4 diamond 2666 dieresis A8 dieresistonos 385 divide F7 " .. "dkshade 2593 dnblock 2584 dollar 24 dong 20AB dotaccent 2D9 dotbelowcomb 323 dotlessi 131 dotlessj " .. "237 dotmath 22C5 e 65 eacute E9 ebreve 115 ecaron 11B ecircumflex EA edieresis EB edotaccent 117 " .. "egrave E8 eight 38 element 2208 ellipsis 2026 emacron 113 emdash 2014 emptyset 2205 endash 2013 eng " .. "14B eogonek 119 epsilon 3B5 epsilontonos 3AD equal 3D equivalence 2261 estimated 212E eta 3B7 " .. "etatonos 3AE eth F0 exclam 21 exclamdbl 203C exclamdown A1 existential 2203 f 66 female 2640 ff " .. "FB00 ffi FB03 ffl FB04 fi FB01 figuredash 2012 filledbox 25A0 filledrect 25AC five 35 fiveeighths " .. "215D fl FB02 florin 192 four 34 fraction 2044 franc 20A3 g 67 gamma 3B3 gbreve 11F gcaron 1E7 " .. "gcircumflex 11D gdotaccent 121 germandbls DF gradient 2207 grave 60 gravecomb 300 greater 3E " .. "greaterequal 2265 guillemotleft AB guillemotright BB guilsinglleft 2039 guilsinglright 203A h 68 " .. "hbar 127 hcircumflex 125 heart 2665 hookabovecomb 309 house 2302 hungarumlaut 2DD hyphen 2D i 69 " .. "iacute ED ibreve 12D icircumflex EE idieresis EF igrave EC ij 133 imacron 12B infinity 221E " .. "integral 222B integralbt 2321 integraltp 2320 intersection 2229 invbullet 25D8 invcircle 25D9 " .. "invsmileface 263B iogonek 12F iota 3B9 iotadieresis 3CA iotadieresistonos 390 iotatonos 3AF itilde " .. "129 j 6A jcircumflex 135 k 6B kappa 3BA kgreenlandic 138 l 6C lacute 13A lambda 3BB lcaron 13E ldot " .. "140 less 3C lessequal 2264 lfblock 258C lira 20A4 logicaland 2227 logicalnot AC logicalor 2228 " .. "longs 17F lozenge 25CA lslash 142 ltshade 2591 m 6D macron AF male 2642 minus 2212 minute 2032 mu " .. "B5 multiply D7 musicalnote 266A musicalnotedbl 266B n 6E nacute 144 napostrophe 149 ncaron 148 nine " .. "39 notelement 2209 notequal 2260 notsubset 2284 ntilde F1 nu 3BD numbersign 23 o 6F oacute F3 " .. "obreve 14F ocircumflex F4 odieresis F6 oe 153 ogonek 2DB ograve F2 ohorn 1A1 ohungarumlaut 151 " .. "omacron 14D omega 3C9 omega1 3D6 omegatonos 3CE omicron 3BF omicrontonos 3CC one 31 onedotenleader " .. "2024 oneeighth 215B onehalf BD onequarter BC onethird 2153 openbullet 25E6 ordfeminine AA " .. "ordmasculine BA orthogonal 221F oslash F8 oslashacute 1FF otilde F5 p 70 paragraph B6 parenleft 28 " .. "parenright 29 partialdiff 2202 percent 25 period 2E periodcentered B7 perpendicular 22A5 " .. "perthousand 2030 peseta 20A7 phi 3C6 phi1 3D5 pi 3C0 plus 2B plusminus B1 prescription 211E product " .. "220F propersubset 2282 propersuperset 2283 proportional 221D psi 3C8 q 71 question 3F questiondown " .. "BF quotedbl 22 quotedblbase 201E quotedblleft 201C quotedblright 201D quoteleft 2018 quotereversed " .. "201B quoteright 2019 quotesinglbase 201A quotesingle 27 r 72 racute 155 radical 221A rcaron 159 " .. "reflexsubset 2286 reflexsuperset 2287 registered AE revlogicalnot 2310 rho 3C1 ring 2DA rtblock " .. "2590 s 73 sacute 15B scaron 161 scedilla 15F scircumflex 15D second 2033 section A7 semicolon 3B " .. "seven 37 seveneighths 215E shade 2592 sigma 3C3 sigma1 3C2 similar 223C six 36 slash 2F smileface " .. "263A space 20 spade 2660 sterling A3 suchthat 220B summation 2211 sun 263C t 74 tau 3C4 tbar 167 " .. "tcaron 165 therefore 2234 theta 3B8 theta1 3D1 thorn FE three 33 threeeighths 215C threequarters BE " .. "tilde 2DC tildecomb 303 tonos 384 trademark 2122 triagdn 25BC triaglf 25C4 triagrt 25BA triagup " .. "25B2 two 32 twodotenleader 2025 twothirds 2154 u 75 uacute FA ubreve 16D ucircumflex FB udieresis " .. "FC ugrave F9 uhorn 1B0 uhungarumlaut 171 umacron 16B underscore 5F underscoredbl 2017 union 222A " .. "universal 2200 uogonek 173 upblock 2580 upsilon 3C5 upsilondieresis 3CB upsilondieresistonos 3B0 " .. "upsilontonos 3CD uring 16F utilde 169 v 76 w 77 wacute 1E83 wcircumflex 175 wdieresis 1E85 " .. "weierstrass 2118 wgrave 1E81 x 78 xi 3BE y 79 yacute FD ycircumflex 177 ydieresis FF yen A5 ygrave " .. "1EF3 z 7A zacute 17A zcaron 17E zdotaccent 17C zero 30 zeta 3B6 " .. "" -- StandardEncoding: 256 names, "-" = .notdef local STD = "" .. "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - space exclam quotedbl numbersign " .. "dollar percent ampersand quoteright parenleft parenright asterisk plus comma hyphen period slash " .. "zero one two three four five six seven eight nine colon semicolon less equal greater question at A " .. "B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash bracketright asciicircum " .. "underscore quoteleft a b c d e f g h i j k l m n o p q r s t u v w x y z braceleft bar braceright " .. "asciitilde - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - exclamdown cent " .. "sterling fraction yen florin section currency quotesingle quotedblleft guillemotleft guilsinglleft " .. "guilsinglright fi fl - endash dagger daggerdbl periodcentered - paragraph bullet quotesinglbase " .. "quotedblbase quotedblright guillemotright ellipsis perthousand - questiondown - grave acute " .. "circumflex tilde macron breve dotaccent dieresis - ring cedilla - hungarumlaut ogonek caron emdash " .. "- - - - - - - - - - - - - - - - AE - ordfeminine - - - - Lslash Oslash OE ordmasculine - - - - - ae " .. "- - - dotlessi - - lslash oslash oe germandbls - - - - " .. "" local byName: { [string]: number }? = nil local function load(): { [string]: number } local t: { [string]: number } = {} for name, hex in string.gmatch(AGL, "(%S+) (%x+)") do t[name] = tonumber(hex, 16) :: number end byName = t return t end local STANDARD: { [number]: string } = {} do local i = 0 for name in string.gmatch(STD, "%S+") do if name ~= "-" then STANDARD[i] = name end i += 1 end end GlyphNames.STANDARD = STANDARD function GlyphNames.unicode(name: string): number? local base = string.match(name, "^([^%.]+)") or name local t = byName or load() local v = t[base] if v then return v end local hex = string.match(base, "^uni(%x%x%x%x)") if hex then local c = tonumber(hex, 16) :: number return if c >= 0xD800 and c < 0xE000 then nil else c end hex = string.match(base, "^u(%x%x%x%x%x?%x?)$") if hex then local c = tonumber(hex, 16) :: number return if c > 0x10FFFF or (c >= 0xD800 and c < 0xE000) then nil else c end local first = string.match(base, "^([^_]+)_") if first then return GlyphNames.unicode(first) end return nil end return GlyphNames end __FILES["codecs/font/TrueType"] = function() -- codecs/font/TrueType: the sfnt container (.ttf, .otf with CFF outlines, .ttc collections) as the standard Font value. -- Ported from stb_truetype 1.26 (public domain / MIT, Sean Barrett et al.) via imgui-luau's imstb_truetype.lua. local Err = __include("core/Err") local Types = __include("Types") local Raster = __include("codecs/image/Raster") local Cff = __include("codecs/font/Cff") local Glyf = __include("codecs/font/TrueType/Glyf") local Tables = __include("codecs/font/TrueType/Tables") local TrueType = {} local u16, i16, u32 = Tables.u16, Tables.i16, Tables.u32 local function tag(b: buffer, o: number): string if o < 0 or o + 4 > buffer.len(b) then return "" end return buffer.readstring(b, o, 4) end function TrueType.count(b: buffer, offset: number?): number local o = offset or 0 local t = tag(b, o) if t == "ttcf" then return u32(b, o + 8) end if t == "\0\1\0\0" or t == "OTTO" or t == "true" or t == "typ1" then return 1 end return 0 end function TrueType.tables(b: buffer, file: number, dir: number, limit: number): ({ [string]: { number } }?, string?) local n = u16(b, dir + 4) if dir + 12 + n * 16 > limit then return nil, "table directory past the end" end local out: { [string]: { number } } = {} for i = 0, n - 1 do local r = dir + 12 + i * 16 local t = tag(b, r) local off, len = u32(b, r + 8), u32(b, r + 12) if file + off + len <= limit then out[t] = { file + off, len } end end return out, nil end local Face = {} Face.__index = Face function Face.glyphIndex(self: any, cp: number): number return Tables.glyph(self._cmap, cp) end function Face.advance(self: any, g: number): number if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then return 0 end local nh = self._numHMetrics if nh == 0 then return 0 end local h = self._hmtx return u16(self._buf, h + 4 * math.min(g, nh - 1)) end function Face.leftSideBearing(self: any, g: number): number if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then return 0 end local nh, h = self._numHMetrics, self._hmtx if g < nh then return i16(self._buf, h + 4 * g + 2) end return i16(self._buf, h + 4 * nh + 2 * (g - nh)) end function Face.kern(self: any, a: number, b: number): number if type(a) ~= "number" or type(b) ~= "number" then return 0 end local key = a * 65536 + b local cache = self._kernCache local v = cache[key] if v then return v end v = 0 if self._gpos then v = Tables.gposKern(self._gpos, a, b) end if v == 0 and self._kern then v = self._kern[key] or 0 end cache[key] = v return v end function Face.kernCodepoints(self: any, a: number, b: number): number return self:kern(self:glyphIndex(a), self:glyphIndex(b)) end function Face.outline(self: any, g: number): { any }? if type(g) ~= "number" or g < 0 or g >= self.numGlyphs or g % 1 ~= 0 then return nil end local ok, cmds, err = pcall(function() if self._cff then return Cff.outline(self._cff, g) end return Glyf.outline(self._glyf, g) end) if not ok then self.meta.lastError = tostring(cmds) return nil end if not cmds then self.meta.lastError = err end return cmds end function Face.bounds(self: any, g: number): (number?, number, number, number) local cmds = self:outline(g) if not cmds then return nil, 0, 0, 0 end local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge for _, c in cmds do for i = 1, #c - 1, 2 do local x, y = c[i], c[i + 1] x0, y0, x1, y1 = math.min(x0, x), math.min(y0, y), math.max(x1, x), math.max(y1, y) end end if x0 > x1 then return nil, 0, 0, 0 end return x0, y0, x1, y1 end function Face.scale(self: any, px: number): number return px / self.unitsPerEm end type RasterOptions = { scaleX: number?, scaleY: number?, shiftX: number?, shiftY: number?, } -- meta.top counts up from the baseline, as FreeType's bitmap_top function Face.rasterize(self: any, g: number, px: number, opts: RasterOptions?): Types.Image? if type(px) ~= "number" or not (px > 0) or px > 4096 then return nil end local cmds = self:outline(g) if not cmds then return nil end local o: RasterOptions = opts or {} local sx = if type(o.scaleX) == "number" then o.scaleX else px / self.unitsPerEm local sy = if type(o.scaleY) == "number" then o.scaleY else sx local tx, ty = o.shiftX or 0, o.shiftY or 0 local m = Raster.mask(cmds, { transform = { sx, 0, 0, -sy, tx, ty }, maxPixels = 2 ^ 24 }) local img if m then img = Types.Image.new(m.width, m.height, "alpha8") buffer.copy(img.pixels, 0, m.coverage) img.meta.left = m.x img.meta.top = -m.y else img = Types.Image.new(0, 0, "alpha8") img.meta.left = 0 img.meta.top = 0 end img.meta.advance = self:advance(g) * sx img.meta.glyph = g return img end type Options = { index: number? } function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Options?): (any, Err.Err?) local b = buf local file = offset or 0 local limit = math.min(buffer.len(b), file + (length or (buffer.len(b) - file))) if limit - file < 12 then return nil, Err.new(Err.TRUNCATED, "too short for an sfnt header", file) end local dir = file local index = (opts and opts.index) or 0 local count = TrueType.count(b, file) if tag(b, file) == "ttcf" then if type(index) ~= "number" or index < 0 or index >= count or index % 1 ~= 0 then return nil, Err.new(Err.ARG, string.format("font index %s out of range (collection of %d)", tostring(index), count)) end dir = file + u32(b, file + 12 + index * 4) if dir + 12 > limit then return nil, Err.new(Err.TRUNCATED, "collection font directory past the end", file) end elseif count == 0 then return nil, Err.new(Err.CORRUPT, "not an sfnt font", file) end local sfntTag = tag(b, dir) if sfntTag == "typ1" then return nil, Err.new(Err.UNSUPPORTED, "PostScript Type 1 sfnt", dir) end local t, terr = TrueType.tables(b, file, dir, limit) if not t then return nil, Err.new(Err.TRUNCATED, terr or "bad table directory", dir) end for _, need in { "head", "hhea", "maxp", "hmtx" } do if not t[need] then return nil, Err.new(Err.CORRUPT, "missing the " .. need .. " table", dir) end end local head, hhea, maxp, hmtx = t.head[1], t.hhea[1], t.maxp[1], t.hmtx[1] if t.head[2] < 54 or t.hhea[2] < 36 or t.maxp[2] < 6 then return nil, Err.new(Err.TRUNCATED, "short head / hhea / maxp table", dir) end local upem = u16(b, head + 18) if upem < 16 or upem > 16384 then return nil, Err.new(Err.CORRUPT, "bad unitsPerEm " .. upem, head + 18) end local numGlyphs = u16(b, maxp + 4) local nh = math.min(u16(b, hhea + 34), numGlyphs) if nh * 4 > t.hmtx[2] then nh = t.hmtx[2] // 4 end local font: any = setmetatable({ kind = "font", info = {}, unitsPerEm = upem, ascent = i16(b, hhea + 4), descent = i16(b, hhea + 6), lineGap = i16(b, hhea + 8), numGlyphs = numGlyphs, bbox = { i16(b, head + 36), i16(b, head + 38), i16(b, head + 40), i16(b, head + 42) }, pages = nil, meta = {}, _buf = b, _hmtx = hmtx, _numHMetrics = nh, _kernCache = {}, }, Face) if t.glyf and t.loca then font._glyf = { buf = b, glyf = t.glyf[1], glyfLen = t.glyf[2], loca = t.loca[1], locaLen = t.loca[2], longLoca = i16(b, head + 50) ~= 0, numGlyphs = numGlyphs, } font.meta.outlines = "truetype" elseif t["CFF "] then local cff, cerr = Cff.parse(b, t["CFF "][1], t["CFF "][2]) if not cff then local code = if cerr and string.find(cerr, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT return nil, Err.new(code, "CFF: " .. tostring(cerr), t["CFF "][1]) end font._cff = cff font.meta.outlines = "cff" elseif t.CFF2 then return nil, Err.new(Err.UNSUPPORTED, "CFF2 outlines (variable OpenType)", dir) else return nil, Err.new(Err.UNSUPPORTED, "no glyf or CFF outlines (bitmap-only font?)", dir) end if t.cmap then font._cmap = Tables.cmap(b, t.cmap[1], t.cmap[2]) end if t.kern then font._kern = Tables.kern(b, t.kern[1], t.kern[2]) end if t.GPOS then font._gpos = Tables.gpos(b, t.GPOS[1], t.GPOS[2]) end if t.name then local names = Tables.names(b, t.name[1], t.name[2]) for k, v in names do font.info[k] = v end font.info.family = names.typographicFamily or names.family font.info.style = names.typographicStyle or names.style end if t["OS/2"] and t["OS/2"][2] >= 10 then font.meta.os2 = Tables.os2(b, t["OS/2"][1], t["OS/2"][2]) end if t.post and t.post[2] >= 16 then local p = t.post[1] font.meta.italicAngle = i16(b, p + 4) + u16(b, p + 6) / 65536 font.meta.underlinePosition = i16(b, p + 8) font.meta.underlineThickness = i16(b, p + 10) font.meta.fixedPitch = u32(b, p + 12) ~= 0 end local tags = {} for k in t do table.insert(tags, k) end table.sort(tags) font.meta.tables = tags font.meta.sfnt = if sfntTag == "OTTO" then "OTTO" else "TrueType" font.meta.collection = if count > 1 or tag(b, file) == "ttcf" then { index = index, count = count } else nil return font, nil end return TrueType end __FILES["codecs/font/TrueType/Glyf"] = function() -- codecs/font/TrueType/Glyf: TrueType glyph outlines from the glyf / loca tables, simple and composite. -- Ported from stb_truetype 1.26 (public domain / MIT, Sean Barrett) via imgui-luau's imstb_truetype.lua; component -- offsets follow FreeType and the spec (stb also scales the offsets of transformed components). local Glyf = {} local readu8, readi8 = buffer.readu8, buffer.readi8 local blen = buffer.len local band = bit32.band local function u8(b: buffer, o: number): number if o < 0 or o + 1 > blen(b) then return 0 end return readu8(b, o) end local function u16(b: buffer, o: number): number if o < 0 or o + 2 > blen(b) then return 0 end return readu8(b, o) * 256 + readu8(b, o + 1) end local function i16(b: buffer, o: number): number local v = u16(b, o) return if v >= 32768 then v - 65536 else v end local function u32(b: buffer, o: number): number return u16(b, o) * 65536 + u16(b, o + 2) end type Face = { buf: buffer, glyf: number, glyfLen: number, loca: number, locaLen: number, longLoca: boolean, numGlyphs: number, [string]: any, } function Glyf.range(f: Face, g: number): (number?, number) if g < 0 or g >= f.numGlyphs or g % 1 ~= 0 then return nil, 0 end local a, z if f.longLoca then if (g + 2) * 4 > f.locaLen then return nil, 0 end a, z = u32(f.buf, f.loca + g * 4), u32(f.buf, f.loca + g * 4 + 4) :: number else if (g + 2) * 2 > f.locaLen then return nil, 0 end a, z = u16(f.buf, f.loca + g * 2) * 2, u16(f.buf, f.loca + g * 2 + 2) * 2 end if z <= a or z > f.glyfLen then return nil, 0 end return f.glyf + a, z - a end function Glyf.bounds(f: Face, g: number): (number?, number, number, number) local o, n = Glyf.range(f, g) if not o or n < 10 then return nil, 0, 0, 0 end local b = f.buf return i16(b, o + 2), i16(b, o + 4), i16(b, o + 6), i16(b, o + 8) end type Contour = { x: { number }, y: { number }, on: { boolean } } local MAX_POINTS = 65536 local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour }?, string?) local e = o + len local ends = table.create(nc) :: { number } local p = o + 10 if p + nc * 2 + 2 > e then return nil, "glyph header past the end" end local last = -1 for i = 1, nc do local v = u16(b, p) if v < last then return nil, "contour end points out of order" end ends[i] = v last = v p += 2 end local n = last + 1 if n > MAX_POINTS then return nil, "too many points" end local ins = u16(b, p) p += 2 + ins if p > e then return nil, "instructions past the end" end local flags = table.create(n, 0) local i = 1 while i <= n do if p >= e then return nil, "flags past the end" end local fl = readu8(b, p) p += 1 flags[i] = fl i += 1 if band(fl, 8) ~= 0 then if p >= e then return nil, "flags past the end" end local rep = readu8(b, p) p += 1 for _ = 1, rep do if i > n then break end flags[i] = fl i += 1 end end end local xs = table.create(n, 0) local x = 0 for k = 1, n do local fl = flags[k] if band(fl, 2) ~= 0 then if p >= e then return nil, "x coordinates past the end" end local d = readu8(b, p) p += 1 x += if band(fl, 16) ~= 0 then d else -d elseif band(fl, 16) == 0 then if p + 2 > e then return nil, "x coordinates past the end" end x += i16(b, p) p += 2 end xs[k] = x end local ys = table.create(n, 0) local y = 0 for k = 1, n do local fl = flags[k] if band(fl, 4) ~= 0 then if p >= e then return nil, "y coordinates past the end" end local d = readu8(b, p) p += 1 y += if band(fl, 32) ~= 0 then d else -d elseif band(fl, 32) == 0 then if p + 2 > e then return nil, "y coordinates past the end" end y += i16(b, p) p += 2 end ys[k] = y end local out = table.create(nc) :: { Contour } local s = 1 for c = 1, nc do local z = ends[c] + 1 local cx, cy, con = {}, {}, {} for k = s, z do table.insert(cx, xs[k]) table.insert(cy, ys[k]) table.insert(con, band(flags[k], 1) ~= 0) end out[c] = { x = cx, y = cy, on = con } s = z + 1 end return out, nil end local contours: (f: Face, g: number, depth: number) -> ({ Contour }?, string?) local function composite(f: Face, o: number, len: number, depth: number): ({ Contour }?, string?) local b = f.buf local e = o + len local p = o + 10 local out: { Contour } = {} local total = 0 while true do if p + 4 > e then return nil, "component past the end" end local flags = u16(b, p) local gi = u16(b, p + 2) p += 4 local a1, a2 if band(flags, 1) ~= 0 then -- ARG_1_AND_2_ARE_WORDS if p + 4 > e then return nil, "component past the end" end if band(flags, 2) ~= 0 then a1, a2 = i16(b, p), i16(b, p + 2) :: number else a1, a2 = u16(b, p), u16(b, p + 2) :: number end p += 4 else if p + 2 > e then return nil, "component past the end" end if band(flags, 2) ~= 0 then a1, a2 = readi8(b, p), readi8(b, p + 1) :: number else a1, a2 = readu8(b, p), readu8(b, p + 1) :: number end p += 2 end local m1, m2, m3, m4 = 1, 0, 0, 1 if band(flags, 8) ~= 0 then -- WE_HAVE_A_SCALE m1 = i16(b, p) / 16384 m4 = m1 p += 2 elseif band(flags, 0x40) ~= 0 then -- WE_HAVE_AN_X_AND_Y_SCALE m1, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384 p += 4 elseif band(flags, 0x80) ~= 0 then -- WE_HAVE_A_TWO_BY_TWO m1, m2, m3, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384, i16(b, p + 4) / 16384, i16(b, p + 6) / 16384 p += 8 end if p > e then return nil, "component past the end" end local child, err = contours(f, gi, depth + 1) if not child then return nil, err end local tc = table.create(#child) :: { Contour } for i, c in child do local nx, ny = table.create(#c.x) :: { number }, table.create(#c.x) :: { number } for k = 1, #c.x do local x, y = c.x[k], c.y[k] nx[k] = m1 * x + m3 * y ny[k] = m2 * x + m4 * y end tc[i] = { x = nx, y = ny, on = c.on } end local dx, dy if band(flags, 2) ~= 0 then -- ARGS_ARE_XY_VALUES dx, dy = a1, a2 if band(flags, 0x800) ~= 0 and band(flags, 0x1000) == 0 then -- SCALED_COMPONENT_OFFSET dx, dy = m1 * a1 + m3 * a2, m2 * a1 + m4 * a2 end else -- point matching: parent point a1 (in what is composed so far) meets child point a2 local function pt(list: { Contour }, idx: number): (number?, number) local k = idx for _, c in list do local n = #c.x if k < n then return c.x[k + 1], c.y[k + 1] end k -= n end return nil, 0 end local px, py = pt(out, a1) local cx, cy = pt(tc, a2) if not px or not cx then return nil, "component point index out of range" end dx, dy = px - cx, py - (cy :: number) end for _, c in tc do for k = 1, #c.x do c.x[k] += dx c.y[k] += dy end total += #c.x table.insert(out, c) end if total > MAX_POINTS then return nil, "too many points" end if band(flags, 0x20) == 0 then -- MORE_COMPONENTS break end end return out, nil end contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?) if depth > 8 then return nil, "composite glyphs nested too deep" end local o, len = Glyf.range(f, g) if not o then return {}, nil end if len < 10 then return nil, "glyph header past the end" end local nc = i16(f.buf, o) if nc >= 0 then return simple(f.buf, o, len, nc) end return composite(f, o, len, depth) end function Glyf.outline(f: Face, g: number): ({ any }?, string?) local cs, err = contours(f, g, 0) if not cs then return nil, err end local cmds = {} for _, c in cs do local n = #c.x if n < 2 then continue end local xs, ys, on = c.x, c.y, c.on -- the start: the first on-curve point, or the midpoint of the first two off-curve points local s = 0 for k = 1, n do if on[k] then s = k break end end local sx, sy if s == 0 then sx, sy = (xs[1] + xs[n]) / 2, (ys[1] + ys[n]) / 2 s = 1 -- all off-curve: start at the implied midpoint between the last and the first, then walk from 1 table.insert(cmds, { op = "moveTo", sx, sy }) local cx, cy = xs[1], ys[1] for k = 2, n do local x, y = xs[k], ys[k] table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 }) cx, cy = x, y end table.insert(cmds, { op = "quadTo", cx, cy, sx, sy }) table.insert(cmds, { op = "close" }) continue end sx, sy = xs[s], ys[s] table.insert(cmds, { op = "moveTo", sx, sy }) local off = false local cx, cy = 0, 0 for i = 1, n do local k = (s + i - 1) % n + 1 local x, y, isOn = xs[k], ys[k], on[k] if i == n then x, y, isOn = sx, sy, true end if isOn then if off then table.insert(cmds, { op = "quadTo", cx, cy, x, y }) elseif i < n then table.insert(cmds, { op = "lineTo", x, y }) end off = false else if off then table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 }) end cx, cy = x, y off = true end end table.insert(cmds, { op = "close" }) end return cmds, nil end function Glyf.counts(f: Face, g: number): (number, number) local cs = contours(f, g, 0) if not cs then return 0, 0 end local n = 0 for _, c in cs do n += #c.x end return n, #cs end return Glyf end __FILES["codecs/font/TrueType/Tables"] = function() -- codecs/font/TrueType/Tables: the sfnt cmap (0, 4, 6, 10, 12, 13), kern, GPOS pair kerning, name and OS/2 tables. -- Written from the OpenType spec; stb_truetype 1.26 (public domain / MIT) was the reference for cmap 4 and GPOS. local Text = __include("codecs/text/Text") local Tables = {} local readu8 = buffer.readu8 local blen = buffer.len local band = bit32.band local function u8(b: buffer, o: number): number if o < 0 or o + 1 > blen(b) then return 0 end return readu8(b, o) end local function u16(b: buffer, o: number): number if o < 0 or o + 2 > blen(b) then return 0 end return readu8(b, o) * 256 + readu8(b, o + 1) end local function i16(b: buffer, o: number): number local v = u16(b, o) return if v >= 32768 then v - 65536 else v end local function u32(b: buffer, o: number): number return u16(b, o) * 65536 + u16(b, o + 2) end Tables.u8, Tables.u16, Tables.i16, Tables.u32 = u8, u16, i16, u32 type Cmap = { buf: buffer, at: number, format: number, symbol: boolean } -- cmap subtable preference: Unicode full repertoire, then BMP, then symbol, then Mac function Tables.cmap(b: buffer, o: number, n: number): Cmap? local count = u16(b, o + 2) local best, bestRank, symbol = -1, 0, false for i = 0, count - 1 do local r = o + 4 + i * 8 if r + 8 > o + n then break end local pid, eid, off = u16(b, r), u16(b, r + 2), u32(b, r + 4) local at = o + off if off >= n then continue end local fmt = u16(b, at) local rank = 0 if pid == 3 and eid == 10 then rank = 6 elseif pid == 0 and (eid == 4 or eid == 6) then rank = 5 elseif pid == 3 and eid == 1 then rank = 4 elseif pid == 0 and fmt ~= 14 then rank = 3 elseif pid == 3 and eid == 0 then rank = 2 elseif pid == 1 and eid == 0 then rank = 1 end if fmt ~= 0 and fmt ~= 4 and fmt ~= 6 and fmt ~= 10 and fmt ~= 12 and fmt ~= 13 then rank = 0 end if rank > bestRank then best, bestRank, symbol = at, rank, pid == 3 and eid == 0 end end if best < 0 then return nil end return { buf = b, at = best, format = u16(b, best), symbol = symbol } end local function lookup(c: Cmap, cp: number): number local b, t, fmt = c.buf, c.at, c.format if fmt == 0 then return if cp < 256 then u8(b, t + 6 + cp) else 0 elseif fmt == 6 then local first, count = u16(b, t + 6), u16(b, t + 8) if cp >= first and cp < first + count then return u16(b, t + 10 + (cp - first) * 2) end return 0 elseif fmt == 10 then local first, count = u32(b, t + 12), u32(b, t + 16) if cp >= first and cp < first + count then return u16(b, t + 20 + (cp - first) * 2) end return 0 elseif fmt == 4 then if cp > 0xFFFF then return 0 end local segX2 = u16(b, t + 6) local segs = segX2 // 2 local ends = t + 14 local lo, hi = 0, segs - 1 while lo < hi do local mid = (lo + hi) // 2 if u16(b, ends + mid * 2) < cp then lo = mid + 1 else hi = mid end end if segs == 0 or u16(b, ends + lo * 2) < cp then return 0 end local starts = ends + segX2 + 2 local start = u16(b, starts + lo * 2) if cp < start then return 0 end local deltaAt = starts + segX2 + lo * 2 local delta = u16(b, deltaAt) local rangeAt = deltaAt + segX2 local ro = u16(b, rangeAt) if ro == 0 then return (cp + delta) % 65536 end local g = u16(b, rangeAt + ro + (cp - start) * 2) if g == 0 then return 0 end return (g + delta) % 65536 elseif fmt == 12 or fmt == 13 then local n = u32(b, t + 12) local lo, hi = 0, n - 1 while lo <= hi do local mid = (lo + hi) // 2 local g = t + 16 + mid * 12 local s, e = u32(b, g), u32(b, g + 4) if cp < s then hi = mid - 1 elseif cp > e then lo = mid + 1 else local gid = u32(b, g + 8) return if fmt == 12 then gid + cp - s else gid end end return 0 end return 0 end function Tables.glyph(c: Cmap?, cp: number): number if not c or type(cp) ~= "number" or cp < 0 or cp > 0x10FFFF or cp % 1 ~= 0 then return 0 end local g = lookup(c, cp) if g == 0 and c.symbol and cp < 256 then g = lookup(c, 0xF000 + cp) -- symbol fonts map U+F020.. to the 8-bit codes end return g end function Tables.kern(b: buffer, o: number, n: number): { [number]: number } local pairs: { [number]: number } = {} local e = o + n local apple = u32(b, o) == 0x00010000 local count = if apple then u32(b, o + 4) else u16(b, o + 2) local p = if apple then o + 8 else o + 4 for _ = 1, math.min(count, 64) do if p + 6 > e then break end local len, fmt, horizontal, cross, minimum, hdr if apple then len = u32(b, p) local cov = u16(b, p + 4) fmt = band(cov, 0xFF) horizontal = band(cov, 0x8000) == 0 cross = band(cov, 0x4000) ~= 0 minimum = band(cov, 0x2000) ~= 0 -- (variation) treated as not applicable hdr = 8 else len = u16(b, p + 2) local cov = u16(b, p + 4) fmt = cov // 256 horizontal = band(cov, 1) ~= 0 minimum = band(cov, 2) ~= 0 cross = band(cov, 4) ~= 0 hdr = 6 end if fmt == 0 and horizontal and not cross and not minimum then local np = u16(b, p + hdr) local q = p + hdr + 8 for k = 0, np - 1 do local r = q + k * 6 if r + 6 > e then break end local key = u16(b, r) * 65536 + u16(b, r + 2) pairs[key] = (pairs[key] or 0) + i16(b, r + 4) end end if len < hdr then break end -- Microsoft subtables often have a wrong 16-bit length for big tables: only the first is reliable then if not apple and len < hdr + 8 then break end p += len end return pairs end local function popcount(v: number): number local c = 0 while v ~= 0 do c += band(v, 1) v = bit32.rshift(v, 1) end return c end local function coverage(b: buffer, t: number, g: number): number local fmt = u16(b, t) if fmt == 1 then local n = u16(b, t + 2) local lo, hi = 0, n - 1 while lo <= hi do local mid = (lo + hi) // 2 local v = u16(b, t + 4 + mid * 2) if g < v then hi = mid - 1 elseif g > v then lo = mid + 1 else return mid end end elseif fmt == 2 then local n = u16(b, t + 2) local lo, hi = 0, n - 1 while lo <= hi do local mid = (lo + hi) // 2 local r = t + 4 + mid * 6 local s, e = u16(b, r), u16(b, r + 2) if g < s then hi = mid - 1 elseif g > e then lo = mid + 1 else return u16(b, r + 4) + g - s end end end return -1 end local function classOf(b: buffer, t: number, g: number): number local fmt = u16(b, t) if fmt == 1 then local s, n = u16(b, t + 2), u16(b, t + 4) if g >= s and g < s + n then return u16(b, t + 6 + (g - s) * 2) end elseif fmt == 2 then local n = u16(b, t + 2) local lo, hi = 0, n - 1 while lo <= hi do local mid = (lo + hi) // 2 local r = t + 4 + mid * 6 local s, e = u16(b, r), u16(b, r + 2) if g < s then hi = mid - 1 elseif g > e then lo = mid + 1 else return u16(b, r + 4) end end end return 0 end local function xAdvance(b: buffer, r: number, vf: number): number if band(vf, 4) == 0 then return 0 end return i16(b, r + 2 * popcount(band(vf, 3))) end local function pairPos(b: buffer, t: number, l: number, r: number): (boolean, number) local fmt = u16(b, t) local ci = coverage(b, t + u16(b, t + 2), l) if ci < 0 then return false, 0 end local vf1, vf2 = u16(b, t + 4), u16(b, t + 6) local s1, s2 = 2 * popcount(band(vf1, 0xFF)), 2 * popcount(band(vf2, 0xFF)) if fmt == 1 then local count = u16(b, t + 8) if ci >= count then return false, 0 end local ps = t + u16(b, t + 10 + ci * 2) local n = u16(b, ps) local rec = 2 + s1 + s2 local lo, hi = 0, n - 1 while lo <= hi do local mid = (lo + hi) // 2 local q = ps + 2 + mid * rec local g = u16(b, q) if r < g then hi = mid - 1 elseif r > g then lo = mid + 1 else return true, xAdvance(b, q + 2, vf1) end end return false, 0 elseif fmt == 2 then local cd1, cd2 = t + u16(b, t + 8), t + u16(b, t + 10) local n1, n2 = u16(b, t + 12), u16(b, t + 14) local c1, c2 = classOf(b, cd1, l), classOf(b, cd2, r) if c1 >= n1 or c2 >= n2 then return false, 0 end local q = t + 16 + (c1 * n2 + c2) * (s1 + s2) return true, xAdvance(b, q, vf1) end return false, 0 end type Gpos = { buf: buffer, subtables: { { number } } } function Tables.gpos(b: buffer, o: number, n: number): Gpos? if n < 10 or u16(b, o) ~= 1 then return nil end local fl, ll = o + u16(b, o + 6), o + u16(b, o + 8) local want: { [number]: boolean } = {} local any = false local nf = u16(b, fl) for i = 0, nf - 1 do local r = fl + 2 + i * 6 if u32(b, r) == 0x6B65726E then -- "kern" local f = fl + u16(b, r + 4) for k = 0, u16(b, f + 2) - 1 do want[u16(b, f + 4 + k * 2)] = true any = true end end end if not any then return nil end local lookups: { { number } } = {} local nl = u16(b, ll) for i = 0, nl - 1 do if want[i] then local lt = ll + u16(b, ll + 2 + i * 2) local ty = u16(b, lt) local subs: { number } = {} for k = 0, math.min(u16(b, lt + 4), 4096) - 1 do local st = lt + u16(b, lt + 6 + k * 2) local sty = ty if ty == 9 and u16(b, st) == 1 then -- extension sty = u16(b, st + 2) st += u32(b, st + 4) end if sty == 2 then table.insert(subs, st) end end if #subs > 0 then table.insert(lookups, subs) end end end if #lookups == 0 then return nil end return { buf = b, subtables = lookups } end function Tables.gposKern(g: Gpos, l: number, r: number): number local total = 0 for _, subs in g.subtables do for _, st in subs do local applies, v = pairPos(g.buf, st, l, r) if applies then total += v break end end end return total end local MAC_ROMAN_HIGH = { 0xC4, 0xC5, 0xC7, 0xC9, 0xD1, 0xD6, 0xDC, 0xE1, 0xE0, 0xE2, 0xE4, 0xE3, 0xE5, 0xE7, 0xE9, 0xE8, 0xEA, 0xEB, 0xED, 0xEC, 0xEE, 0xEF, 0xF1, 0xF3, 0xF2, 0xF4, 0xF6, 0xF5, 0xFA, 0xF9, 0xFB, 0xFC, 0x2020, 0xB0, 0xA2, 0xA3, 0xA7, 0x2022, 0xB6, 0xDF, 0xAE, 0xA9, 0x2122, 0xB4, 0xA8, 0x2260, 0xC6, 0xD8, 0x221E, 0xB1, 0x2264, 0x2265, 0xA5, 0xB5, 0x2202, 0x2211, 0x220F, 0x3C0, 0x222B, 0xAA, 0xBA, 0x3A9, 0xE6, 0xF8, 0xBF, 0xA1, 0xAC, 0x221A, 0x192, 0x2248, 0x2206, 0xAB, 0xBB, 0x2026, 0xA0, 0xC0, 0xC3, 0xD5, 0x152, 0x153, 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0xF7, 0x25CA, 0xFF, 0x178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, 0x2021, 0xB7, 0x201A, 0x201E, 0x2030, 0xC2, 0xCA, 0xC1, 0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0xD3, 0xD4, 0xF8FF, 0xD2, 0xDA, 0xDB, 0xD9, 0x131, 0x2C6, 0x2DC, 0xAF, 0x2D8, 0x2D9, 0x2DA, 0xB8, 0x2DD, 0x2DB, 0x2C7, } local function utf16be(b: buffer, o: number, n: number): string return Text.utf16(b, o, n, true) end local function macRoman(b: buffer, o: number, n: number): string local out = {} for k = 0, n - 1 do local c = u8(b, o + k) table.insert(out, utf8.char(if c < 128 then c else MAC_ROMAN_HIGH[c - 127])) end return table.concat(out) end local NAME_IDS: { [number]: string } = { [0] = "copyright", [1] = "family", [2] = "style", [3] = "uniqueId", [4] = "fullName", [5] = "version", [6] = "postScriptName", [7] = "trademark", [8] = "manufacturer", [9] = "designer", [10] = "description", [11] = "vendorUrl", [12] = "designerUrl", [13] = "license", [14] = "licenseUrl", [16] = "typographicFamily", [17] = "typographicStyle", } function Tables.names(b: buffer, o: number, n: number): { [string]: string } local out: { [string]: string } = {} local rank: { [string]: number } = {} local count, strings = u16(b, o + 2), o + u16(b, o + 4) for i = 0, math.min(count, 4096) - 1 do local r = o + 6 + i * 12 if r + 12 > o + n then break end local pid, eid, lang, nid = u16(b, r), u16(b, r + 2), u16(b, r + 4), u16(b, r + 6) local len, off = u16(b, r + 8), u16(b, r + 10) local key = NAME_IDS[nid] if key and strings + off + len <= o + n then local rk: number, s: string? = 0, nil if pid == 3 and (eid == 1 or eid == 10 or eid == 0) then rk = if lang == 0x409 then 4 else 2 s = utf16be(b, strings + off, len) elseif pid == 0 then rk = 3 s = utf16be(b, strings + off, len) elseif pid == 1 and eid == 0 then rk = if lang == 0 then 1 else 0.5 s = macRoman(b, strings + off, len) end if s and rk > (rank[key] or 0) then out[key] = s rank[key] = rk end end end return out end function Tables.os2(b: buffer, o: number, n: number): { [string]: number } local t: { [string]: number } = { version = u16(b, o), xAvgCharWidth = i16(b, o + 2), weightClass = u16(b, o + 4), widthClass = u16(b, o + 6), fsType = u16(b, o + 8), } if n >= 78 then t.fsSelection = u16(b, o + 62) t.firstChar = u16(b, o + 64) t.lastChar = u16(b, o + 66) t.typoAscender = i16(b, o + 68) t.typoDescender = i16(b, o + 70) t.typoLineGap = i16(b, o + 72) t.winAscent = u16(b, o + 74) t.winDescent = u16(b, o + 76) end if n >= 96 and t.version >= 2 then t.xHeight = i16(b, o + 86) t.capHeight = i16(b, o + 88) end return t end return Tables end __FILES["codecs/image/Bcn"] = @native function() -- codecs/image/Bcn: BC1-BC7 block-compressed textures with the D3D11 rules. -- Decoders ported from Pillow's BcnDecode.c (CC0); encoders new (stb_dxt-style). SNORM is biased by 128 into rgba8. local Decode = __include("codecs/image/Bcn/Decode") local Encode = __include("codecs/image/Bcn/Encode") local Bcn = {} Bcn.BLOCK = table.freeze({ bc1 = 8, bc2 = 16, bc3 = 16, bc4 = 8, bc4s = 8, bc5 = 16, bc5s = 16, bc6h = 16, bc6hs = 16, bc7 = 16 }) :: { [string]: number } Bcn.FLOAT = table.freeze({ bc6h = true, bc6hs = true }) :: { [string]: boolean } local readu32, writeu32 = buffer.readu32, buffer.writeu32 local BLOCKS: { [string]: (buffer, number, buffer) -> () } = { bc1 = Decode.bc1, bc2 = Decode.bc2, bc3 = Decode.bc3, bc4 = Decode.bc4, bc4s = Decode.bc4s, bc5 = Decode.bc5, bc5s = Decode.bc5s, bc7 = Decode.bc7, bc6h = @native function(src: buffer, p: number, blk: buffer) Decode.bc6h(src, p, blk, false) end, bc6hs = @native function(src: buffer, p: number, blk: buffer) Decode.bc6h(src, p, blk, true) end, } @native function Bcn.size(kind: string, w: number, h: number): number? local b = Bcn.BLOCK[kind] if not b then return nil end return ((w + 3) // 4) * ((h + 3) // 4) * b end @native function Bcn.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?): (buffer?, string?) local fn = BLOCKS[kind] if not fn then return nil, "unsupported: unknown block format " .. tostring(kind) end if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then return nil, "bad image size" end local need = Bcn.size(kind, w, h) :: number if offset < 0 or offset + need > buffer.len(src) then return nil, "truncated: block data runs past the end" end local float = Bcn.FLOAT[kind] == true local bpp = if float then 16 else 4 local oo = outOffset or 0 local dst = out or buffer.create(w * h * bpp) if oo + w * h * bpp > buffer.len(dst) then return nil, "output buffer too small" end local bytes = Bcn.BLOCK[kind] local blk = buffer.create(16 * bpp) local bw, bh = (w + 3) // 4, (h + 3) // 4 local p = offset local rowBytes = w * bpp for by = 0, bh - 1 do local rows = math.min(4, h - by * 4) for bx = 0, bw - 1 do fn(src, p, blk) p += bytes local cols = math.min(4, w - bx * 4) local base = oo + (by * 4) * rowBytes + bx * 4 * bpp if cols == 4 and not float then for y = 0, rows - 1 do local d, s = base + y * rowBytes, y * 16 writeu32(dst, d, readu32(blk, s)) writeu32(dst, d + 4, readu32(blk, s + 4)) writeu32(dst, d + 8, readu32(blk, s + 8)) writeu32(dst, d + 12, readu32(blk, s + 12)) end else for y = 0, rows - 1 do buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp) end end end end return dst, nil end type EncodeOptions = { alphaThreshold: number?, } @native function Bcn.encode(kind: string, px: buffer, w: number, h: number, opts: EncodeOptions?): (buffer?, string?) if kind ~= "bc1" and kind ~= "bc3" and kind ~= "bc4" and kind ~= "bc5" then return nil, "unsupported: no encoder for " .. tostring(kind) end if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(px) < w * h * 4 then return nil, "needs w x h rgba8 pixels" end local t = opts and opts.alphaThreshold or 128 return Encode.run(kind, px, w, h, t), nil end return Bcn end __FILES["codecs/image/Bcn/Decode"] = @native function() -- codecs/image/Bcn/Decode: BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC), ported from Pillow's BcnDecode.c -- (CC0, licenses/pillow-bcn-CC0.txt). Follows the D3D11 functional spec where Pillow does not: BC6H rounds -- (a * (64 - w) + b * w + 32) >> 6 and keeps floats, reserved modes decode to zero, SNORM -128 reads as -127. local Half = __include("codecs/image/Half") local Decode = {} local readu8, readu16, readu32, writeu8, writeu32, writef32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32, buffer.writef32 local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift local HALF = Half.TABLE local pal = buffer.create(16) @native local function c565(c: number): (number, number, number) local r = rshift(band(c, 0xF800), 8) local g = rshift(band(c, 0x7E0), 3) local b = lshift(band(c, 0x1F), 3) return bor(r, rshift(r, 5)), bor(g, rshift(g, 6)), bor(b, rshift(b, 5)) end -- BC2 / BC3 colour blocks always use the 4-colour palette @native local function colour(src: buffer, p: number, blk: buffer, fourColour: boolean) local c0, c1 = readu16(src, p), readu16(src, p + 2) local r0, g0, b0 = c565(c0) local r1, g1, b1 = c565(c1) writeu32(pal, 0, r0 + g0 * 256 + b0 * 65536 + 0xFF000000) writeu32(pal, 4, r1 + g1 * 256 + b1 * 65536 + 0xFF000000) if c0 > c1 or fourColour then writeu32(pal, 8, (2 * r0 + r1) // 3 + ((2 * g0 + g1) // 3) * 256 + ((2 * b0 + b1) // 3) * 65536 + 0xFF000000) writeu32(pal, 12, (r0 + 2 * r1) // 3 + ((g0 + 2 * g1) // 3) * 256 + ((b0 + 2 * b1) // 3) * 65536 + 0xFF000000) else writeu32(pal, 8, (r0 + r1) // 2 + ((g0 + g1) // 2) * 256 + ((b0 + b1) // 2) * 65536 + 0xFF000000) writeu32(pal, 12, 0) end local idx = readu32(src, p + 4) for i = 0, 15 do writeu32(blk, i * 4, readu32(pal, band(rshift(idx, i * 2), 3) * 4)) end end local vals = table.create(8, 0) @native local function ramp8(a0: number, a1: number) vals[1], vals[2] = a0, a1 if a0 > a1 then for i = 1, 6 do vals[i + 2] = ((7 - i) * a0 + i * a1) // 7 end else for i = 1, 4 do vals[i + 2] = ((5 - i) * a0 + i * a1) // 5 end vals[7], vals[8] = 0, 255 end end -- signed (SNORM) ramp, values -127..127 rounded to the nearest integer, biased by 128 into 1..255 @native local function ramp8s(u0: number, u1: number) local s0: number = math.max(if u0 >= 128 then u0 - 256 else u0, -127) local s1: number = math.max(if u1 >= 128 then u1 - 256 else u1, -127) vals[1], vals[2] = s0 + 128, s1 + 128 if s0 > s1 then for i = 1, 6 do vals[i + 2] = math.floor(((7 - i) * s0 + i * s1) / 7 + 0.5) + 128 end else for i = 1, 4 do vals[i + 2] = math.floor(((5 - i) * s0 + i * s1) / 5 + 0.5) + 128 end vals[7], vals[8] = 1, 255 end end @native local function single(src: buffer, p: number, blk: buffer, channel: number, signed: boolean, spread: boolean) if signed then ramp8s(readu8(src, p), readu8(src, p + 1)) else ramp8(readu8(src, p), readu8(src, p + 1)) end local lo = readu8(src, p + 2) + readu8(src, p + 3) * 256 + readu8(src, p + 4) * 65536 local hi = readu8(src, p + 5) + readu8(src, p + 6) * 256 + readu8(src, p + 7) * 65536 for i = 0, 15 do local sel = if i < 8 then band(rshift(lo, i * 3), 7) else band(rshift(hi, (i - 8) * 3), 7) local v = vals[sel + 1] local o = i * 4 if spread then writeu32(blk, o, v + v * 256 + v * 65536 + 0xFF000000) else writeu8(blk, o + channel, v) end end end @native function Decode.bc1(src: buffer, p: number, blk: buffer) colour(src, p, blk, false) end @native function Decode.bc2(src: buffer, p: number, blk: buffer) colour(src, p + 8, blk, true) for i = 0, 15 do local a = band(rshift(readu8(src, p + rshift(i, 1)), band(i, 1) * 4), 15) writeu8(blk, i * 4 + 3, a * 17) end end @native function Decode.bc3(src: buffer, p: number, blk: buffer) colour(src, p + 8, blk, true) single(src, p, blk, 3, false, false) end @native function Decode.bc4(src: buffer, p: number, blk: buffer) single(src, p, blk, 0, false, true) end @native function Decode.bc4s(src: buffer, p: number, blk: buffer) single(src, p, blk, 0, true, true) end @native local function bc5(src: buffer, p: number, blk: buffer, signed: boolean) for i = 0, 15 do writeu32(blk, i * 4, 0xFF000000) end single(src, p, blk, 0, signed, false) single(src, p + 8, blk, 1, signed, false) end @native function Decode.bc5(src: buffer, p: number, blk: buffer) bc5(src, p, blk, false) end @native function Decode.bc5s(src: buffer, p: number, blk: buffer) bc5(src, p, blk, true) end -- partition tables (BC7 Table.P2 1 bit per pixel, Table.P3 2 bits per pixel) and the anchor indices local SI2 = { 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000, 0xf710, 0x008e, 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce, 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c, 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, 0x3c3c, 0x55aa, 0x9696, 0xa55a, 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660, 0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, 0x39c6, 0x639c, 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22, } local SI3 = { 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050, 0xaa550000, 0xaa555500, 0xaaaa5500, 0x90909090, 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0, 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, 0xa08585a0, 0xaa821414, 0x50a4a450, 0x6a5a0200, 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50, 0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0, 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, 0xaa444444, 0x54a854a8, 0x95809580, 0x96969600, 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000, 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254, } local AI0 = { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15, } local AI1 = { 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3, } local AI2 = { 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8, 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, } local W2 = { [0] = 0, 21, 43, 64 } local W3 = { [0] = 0, 9, 18, 27, 37, 46, 55, 64 } local W4 = { [0] = 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 } local WEIGHTS = { [2] = W2, [3] = W3, [4] = W4 } Decode.SI2, Decode.SI3, Decode.AI0, Decode.AI1, Decode.AI2, Decode.WEIGHTS = SI2, SI3, AI0, AI1, AI2, WEIGHTS @native local function subset(ns: number, part: number, i: number): number if ns == 2 then return band(rshift(SI2[part + 1], i), 1) elseif ns == 3 then return band(rshift(SI3[part + 1], 2 * i), 3) end return 0 end local w0, w1, w2, w3 = 0, 0, 0, 0 @native local function load(src: buffer, p: number) w0, w1, w2, w3 = readu32(src, p), readu32(src, p + 4), readu32(src, p + 8), readu32(src, p + 12) end @native local function word(i: number): number return if i == 0 then w0 elseif i == 1 then w1 elseif i == 2 then w2 else w3 end @native local function bits(at: number, n: number): number if n == 0 then return 0 end local wi, sh = rshift(at, 5), band(at, 31) local v = rshift(word(wi), sh) if sh + n > 32 and wi < 3 then v = bor(v, lshift(word(wi + 1), 32 - sh)) end return band(v, lshift(1, n) - 1) end -- ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 local MODES7 = { { 3, 4, 0, 0, 4, 0, 1, 0, 3, 0 }, { 2, 6, 0, 0, 6, 0, 0, 1, 3, 0 }, { 3, 6, 0, 0, 5, 0, 0, 0, 2, 0 }, { 2, 6, 0, 0, 7, 0, 1, 0, 2, 0 }, { 1, 0, 2, 1, 5, 6, 0, 0, 2, 3 }, { 1, 0, 2, 0, 7, 8, 0, 0, 2, 2 }, { 1, 0, 0, 0, 7, 7, 1, 0, 4, 0 }, { 2, 6, 0, 0, 5, 5, 1, 0, 2, 0 }, } local er, eg, eb, ea = table.create(6, 0), table.create(6, 0), table.create(6, 0), table.create(6, 0) @native local function expand(v: number, n: number): number v = band(lshift(v, 8 - n), 255) return bor(v, rshift(v, n)) end @native function Decode.bc7(src: buffer, p: number, blk: buffer) local m0 = readu8(src, p) if m0 == 0 then buffer.fill(blk, 0, 0, 64) return end load(src, p) local mode = 0 while band(m0, lshift(1, mode)) == 0 do mode += 1 end local info = MODES7[mode + 1] local ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 = info[1], info[2], info[3], info[4], info[5], info[6], info[7], info[8], info[9], info[10] local bit = mode + 1 local part = bits(bit, pb) bit += pb local rot = bits(bit, rb) bit += rb local sel = bits(bit, isb) bit += isb local nep = ns * 2 for i = 1, nep do er[i] = bits(bit, cb) bit += cb end for i = 1, nep do eg[i] = bits(bit, cb) bit += cb end for i = 1, nep do eb[i] = bits(bit, cb) bit += cb end for i = 1, nep do if ab > 0 then ea[i] = bits(bit, ab) bit += ab else ea[i] = 255 end end if epb == 1 then cb += 1 if ab > 0 then ab += 1 end for i = 1, nep do local v = bits(bit, 1) bit += 1 er[i], eg[i], eb[i] = er[i] * 2 + v, eg[i] * 2 + v, eb[i] * 2 + v if ab > 0 then ea[i] = ea[i] * 2 + v end end end if spb == 1 then cb += 1 if ab > 0 then ab += 1 end for i = 1, nep, 2 do local v = bits(bit, 1) bit += 1 for j = i, i + 1 do er[j], eg[j], eb[j] = er[j] * 2 + v, eg[j] * 2 + v, eb[j] * 2 + v if ab > 0 then ea[j] = ea[j] * 2 + v end end end end for i = 1, nep do er[i], eg[i], eb[i] = expand(er[i], cb), expand(eg[i], cb), expand(eb[i], cb) if ab > 0 then ea[i] = expand(ea[i], ab) end end local cw = WEIGHTS[ib] local aw = if ab > 0 and ib2 > 0 then WEIGHTS[ib2] else cw local cbit = bit local abit = cbit + 16 * ib - ns local a1 = if ns == 2 then AI0[part + 1] elseif ns == 3 then AI1[part + 1] else -1 local a2 = if ns == 3 then AI2[part + 1] else -1 for i = 0, 15 do local s = subset(ns, part, i) * 2 + 1 local n = ib if i == 0 or i == a1 or i == a2 then n -= 1 end local i0 = bits(cbit, n) cbit += n local wc, wa if ab > 0 and ib2 > 0 then local n2 = if i == 0 then ib2 - 1 else ib2 local i1 = bits(abit, n2) abit += n2 if sel == 1 then wc, wa = aw[i1], cw[i0] else wc, wa = cw[i0], aw[i1] end else wc, wa = cw[i0], cw[i0] end local tc, ta = 64 - wc, 64 - wa local r = rshift(tc * er[s] + wc * er[s + 1] + 32, 6) local g = rshift(tc * eg[s] + wc * eg[s + 1] + 32, 6) local b = rshift(tc * eb[s] + wc * eb[s + 1] + 32, 6) local a = rshift(ta * ea[s] + wa * ea[s + 1] + 32, 6) if rot == 1 then r, a = a, r elseif rot == 2 then g, a = a, g elseif rot == 3 then b, a = a, b end writeu32(blk, i * 4, r + g * 256 + b * 65536 + a * 16777216) end end -- ns, transformed, pb, epb, rb, gb, bb local MODES6 = { { 2, 1, 5, 10, 5, 5, 5 }, { 2, 1, 5, 7, 6, 6, 6 }, { 2, 1, 5, 11, 5, 4, 4 }, { 2, 1, 5, 11, 4, 5, 4 }, { 2, 1, 5, 11, 4, 4, 5 }, { 2, 1, 5, 9, 5, 5, 5 }, { 2, 1, 5, 8, 6, 5, 5 }, { 2, 1, 5, 8, 5, 6, 5 }, { 2, 1, 5, 8, 5, 5, 6 }, { 2, 0, 5, 6, 6, 6, 6 }, { 1, 0, 0, 10, 10, 10, 10 }, { 1, 1, 0, 11, 9, 9, 9 }, { 1, 1, 0, 12, 8, 8, 8 }, { 1, 1, 0, 16, 4, 4, 4 }, } -- Table.F: for each endpoint bit in stream order, endpoint * 16 + bit (endpoints r0 g0 b0 r1 g1 b1 r2 ... b3) local PACK6 = { { 116, 132, 180, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, { 117, 164, 165, 0, 1, 2, 3, 4, 5, 6, 176, 177, 132, 16, 17, 18, 19, 20, 21, 22, 133, 178, 116, 32, 33, 34, 35, 36, 37, 38, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 10, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 26, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 176, 178, 144, 145, 146, 147, 116, 179 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 132, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 42, 128, 129, 130, 131, 96, 97, 98, 99, 177, 178, 144, 145, 146, 147, 180, 179 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 132, 16, 17, 18, 19, 20, 21, 22, 23, 24, 116, 32, 33, 34, 35, 36, 37, 38, 39, 40, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, { 0, 1, 2, 3, 4, 5, 6, 7, 164, 132, 16, 17, 18, 19, 20, 21, 22, 23, 178, 116, 32, 33, 34, 35, 36, 37, 38, 39, 179, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, { 0, 1, 2, 3, 4, 5, 6, 7, 176, 132, 16, 17, 18, 19, 20, 21, 22, 23, 117, 116, 32, 33, 34, 35, 36, 37, 38, 39, 165, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, { 0, 1, 2, 3, 4, 5, 6, 7, 177, 132, 16, 17, 18, 19, 20, 21, 22, 23, 133, 116, 32, 33, 34, 35, 36, 37, 38, 39, 181, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, { 0, 1, 2, 3, 4, 5, 164, 176, 177, 132, 16, 17, 18, 19, 20, 21, 117, 133, 178, 116, 32, 33, 34, 35, 36, 37, 165, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 10, 64, 65, 66, 67, 68, 69, 70, 71, 72, 26, 80, 81, 82, 83, 84, 85, 86, 87, 88, 42 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 11, 10, 64, 65, 66, 67, 68, 69, 70, 71, 27, 26, 80, 81, 82, 83, 84, 85, 86, 87, 43, 42 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 15, 14, 13, 12, 11, 10, 64, 65, 66, 67, 31, 30, 29, 28, 27, 26, 80, 81, 82, 83, 47, 46, 45, 44, 43, 42 }, } local ep = table.create(12, 0) local uq = table.create(12, 0) @native local function signExtend(v: number, n: number): number v = band(v, lshift(1, n) - 1) return if v >= lshift(1, n - 1) then v - lshift(1, n) else v end @native local function unquantize(x: number, n: number, signed: boolean): number if not signed then if n >= 15 or x == 0 then return x elseif x == lshift(1, n) - 1 then return 0xFFFF end return rshift(x * 32768 + 0x4000, n - 1) end if n >= 16 then return x end local neg = x < 0 if neg then x = -x end if x ~= 0 then if x >= lshift(1, n - 1) - 1 then x = 0x7FFF else x = rshift(x * 32768 + 0x4000, n - 1) end end return if neg then -x else x end @native local function finish(v: number, signed: boolean): number if signed then if v < 0 then return -HALF[(-v * 31) // 32] end return HALF[(v * 31) // 32] end return HALF[(v * 31) // 64] end @native function Decode.bc6h(src: buffer, p: number, blk: buffer, signed: boolean) load(src, p) local m = band(w0, 31) local mode, bit, epbits, ib local low = band(m, 3) if low < 2 then mode, bit, epbits, ib = low, 2, 75, 3 elseif low == 2 then mode, bit, epbits, ib = 2 + rshift(m, 2), 5, 72, 3 else mode, bit, epbits, ib = 10 + rshift(m, 2), 5, 60, 4 end if mode >= 14 then for i = 0, 15 do local o = i * 16 writef32(blk, o, 0) writef32(blk, o + 4, 0) writef32(blk, o + 8, 0) writef32(blk, o + 12, 1) end return end local info = MODES6[mode + 1] local ns, tr, pb, epb, rbits, gbits, bbits = info[1], info[2], info[3], info[4], info[5], info[6], info[7] local nep = if ns == 2 then 12 else 6 for i = 1, 12 do ep[i] = 0 end local pack = PACK6[mode + 1] for i = 1, epbits do local d = pack[i] local e = rshift(d, 4) + 1 ep[e] = bor(ep[e], lshift(bits(bit + i - 1, 1), band(d, 15))) end bit += epbits local part = bits(bit, pb) bit += pb local mask = lshift(1, epb) - 1 if signed then ep[1], ep[2], ep[3] = signExtend(ep[1], epb), signExtend(ep[2], epb), signExtend(ep[3], epb) end if signed or tr == 1 then for i = 4, nep, 3 do ep[i], ep[i + 1], ep[i + 2] = signExtend(ep[i], rbits), signExtend(ep[i + 1], gbits), signExtend(ep[i + 2], bbits) end end if tr == 1 then for i = 4, nep, 3 do for c = 0, 2 do local v = band(ep[i + c] + ep[1 + c], mask) ep[i + c] = if signed then signExtend(v, epb) else v end end end for i = 1, nep do uq[i] = unquantize(ep[i], epb, signed) end local w = WEIGHTS[ib] local a1 = if ns == 2 then AI0[part + 1] else -1 for i = 0, 15 do local s = subset(ns, part, i) * 6 + 1 local n = if i == 0 or i == a1 then ib - 1 else ib local wt = w[bits(bit, n)] bit += n local t = 64 - wt local o = i * 16 -- floor((a * t + b * w + 32) / 64): the products may be negative (signed) - // floors like >> would writef32(blk, o, finish((uq[s] * t + uq[s + 3] * wt + 32) // 64, signed)) writef32(blk, o + 4, finish((uq[s + 1] * t + uq[s + 4] * wt + 32) // 64, signed)) writef32(blk, o + 8, finish((uq[s + 2] * t + uq[s + 5] * wt + 32) // 64, signed)) writef32(blk, o + 12, 1) end end return Decode end __FILES["codecs/image/Bcn/Encode"] = @native function() -- codecs/image/Bcn/Encode: BC1 / BC3 / BC4 / BC5 block encoders, new in rosetta; the approach follows stb_dxt (Fabian -- Giesen / Sean Barrett, public domain): principal axis endpoints, least-squares refinement, exact single-colour tables. local Encode = {} local readu8, writeu8, writeu16, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu16, buffer.writeu32 local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift @native local function exp5(v: number): number return bor(lshift(v, 3), rshift(v, 2)) end @native local function exp6(v: number): number return bor(lshift(v, 2), rshift(v, 4)) end -- OM[k][v + 1] = e0 * 256 + e1 (quantized) whose colour-2 value (4-colour: (2 e0 + e1) // 3; 3-colour: (e0 + e1) -- // 2) is closest to v; k = 1 / 2 for 5-bit (4 / 3 colour), 3 / 4 for 6-bit local OM: { { number } }? = nil @native local function singleTables(): { { number } } local om = OM if om then return om end local t: { { number } } = {} for k = 1, 4 do local bitsN = if k <= 2 then 5 else 6 local maxq = lshift(1, bitsN) - 1 local exp: (number) -> number = if bitsN == 5 then exp5 else exp6 local best = table.create(256, 1e9) local pick = table.create(256, 0) for a = 0, maxq do local ea = exp(a) for b = 0, maxq do local eb = exp(b) local v: number = if k % 2 == 1 then (2 * ea + eb) // 3 else (ea + eb) // 2 -- prefer endpoints close to each other (less error if the colour shifts) local e = math.abs(ea - eb) * 0.01 for target = math.max(0, v - 8), math.min(255, v + 8) do local err = (target - v) ^ 2 + e if err < best[target + 1] then best[target + 1] = err pick[target + 1] = a * 256 + b end end end end t[k] = pick end OM = t return t end local R, G, B, A = table.create(16, 0), table.create(16, 0), table.create(16, 0), table.create(16, 0) local USE = table.create(16, true) local PR, PG, PB = table.create(4, 0), table.create(4, 0), table.create(4, 0) local IDX = table.create(16, 0) local BEST = table.create(16, 0) @native local function palette(c0: number, c1: number, four: boolean) local r0, g0, b0 = exp5(rshift(c0, 11)), exp6(band(rshift(c0, 5), 63)), exp5(band(c0, 31)) local r1, g1, b1 = exp5(rshift(c1, 11)), exp6(band(rshift(c1, 5), 63)), exp5(band(c1, 31)) PR[1], PG[1], PB[1] = r0, g0, b0 PR[2], PG[2], PB[2] = r1, g1, b1 if four then PR[3], PG[3], PB[3] = (2 * r0 + r1) // 3, (2 * g0 + g1) // 3, (2 * b0 + b1) // 3 PR[4], PG[4], PB[4] = (r0 + 2 * r1) // 3, (g0 + 2 * g1) // 3, (b0 + 2 * b1) // 3 else PR[3], PG[3], PB[3] = (r0 + r1) // 2, (g0 + g1) // 2, (b0 + b1) // 2 PR[4], PG[4], PB[4] = 0, 0, 0 end end @native local function assign(four: boolean): number local n = if four then 4 else 3 local total = 0 for i = 1, 16 do if USE[i] then local r, g, b = R[i], G[i], B[i] local bi, be = 0, math.huge for k = 1, n do local dr, dg, db = r - PR[k], g - PG[k], b - PB[k] local e = dr * dr + dg * dg + db * db if e < be then be, bi = e, k - 1 end end IDX[i] = bi total += be else IDX[i] = 3 end end return total end @native local function q565(r: number, g: number, b: number): number local qr = math.clamp(math.floor(r * 31 / 255 + 0.5), 0, 31) local qg = math.clamp(math.floor(g * 63 / 255 + 0.5), 0, 63) local qb = math.clamp(math.floor(b * 31 / 255 + 0.5), 0, 31) return qr * 2048 + qg * 32 + qb end local W4 = { 1, 0, 2 / 3, 1 / 3 } local W3 = { 1, 0, 0.5, 0 } @native local function refine(four: boolean): (number?, number?) local W = if four then W4 else W3 local aa, bb, ab = 0, 0, 0 local ar, ag, ab_, br, bg, bb_ = 0, 0, 0, 0, 0, 0 for i = 1, 16 do if USE[i] then local w = W[IDX[i] + 1] local v = 1 - w aa += w * w bb += v * v ab += w * v ar += w * R[i] ag += w * G[i] ab_ += w * B[i] br += v * R[i] bg += v * G[i] bb_ += v * B[i] end end local det = aa * bb - ab * ab if math.abs(det) < 1e-9 then return nil, nil end local f = 1 / det local r0, g0, b0 = (ar * bb - br * ab) * f, (ag * bb - bg * ab) * f, (ab_ * bb - bb_ * ab) * f local r1, g1, b1 = (br * aa - ar * ab) * f, (bg * aa - ag * ab) * f, (bb_ * aa - ab_ * ab) * f return q565(r0, g0, b0), q565(r1, g1, b1) end @native local function colourBlock(out: buffer, o: number, four: boolean) local n, mr, mg, mb = 0, 0, 0, 0 for i = 1, 16 do if USE[i] then n += 1 mr += R[i] mg += G[i] mb += B[i] end end if n == 0 then writeu16(out, o, 0) writeu16(out, o + 2, 0) writeu32(out, o + 4, 0xFFFFFFFF) return end mr, mg, mb = mr / n, mg / n, mb / n local crr, cgg, cbb, crg, crb, cgb = 0, 0, 0, 0, 0, 0 local same = true local fr, fg, fb = -1, -1, -1 for i = 1, 16 do if USE[i] then if fr < 0 then fr, fg, fb = R[i], G[i], B[i] elseif R[i] ~= fr or G[i] ~= fg or B[i] ~= fb then same = false end local dr, dg, db = R[i] - mr, G[i] - mg, B[i] - mb crr += dr * dr cgg += dg * dg cbb += db * db crg += dr * dg crb += dr * db cgb += dg * db end end local c0, c1 if same then local t = singleTables() local k = if four then 0 else 1 local pr, pg, pb = t[1 + k][fr + 1], t[3 + k][fg + 1], t[1 + k][fb + 1] c0 = rshift(pr, 8) * 2048 + rshift(pg, 8) * 32 + rshift(pb, 8) c1 = band(pr, 255) * 2048 + band(pg, 255) * 32 + band(pb, 255) local i2 = 2 if c0 == c1 then i2 = 0 end -- index 2 everywhere (or 0 for an exact endpoint); order fixed below for i = 1, 16 do IDX[i] = if USE[i] then i2 else 3 end else -- principal axis local vr, vg, vb = 1, 1, 1 for _ = 1, 8 do local nr = crr * vr + crg * vg + crb * vb local ng = crg * vr + cgg * vg + cgb * vb local nb = crb * vr + cgb * vg + cbb * vb local m = math.max(math.abs(nr), math.abs(ng), math.abs(nb)) if m < 1e-9 then break end vr, vg, vb = nr / m, ng / m, nb / m end local lo, hi, li, hi_ = math.huge, -math.huge, 1, 1 for i = 1, 16 do if USE[i] then local d = R[i] * vr + G[i] * vg + B[i] * vb if d < lo then lo, li = d, i end if d > hi then hi, hi_ = d, i end end end c0 = q565(R[hi_], G[hi_], B[hi_]) c1 = q565(R[li], G[li], B[li]) palette(c0, c1, four) local err = assign(four) for i = 1, 16 do BEST[i] = IDX[i] end for _ = 1, 2 do local n0, n1 = refine(four) if not n0 or not n1 then break end palette(n0, n1, four) local e2 = assign(four) if e2 < err then err, c0, c1 = e2, n0, n1 for i = 1, 16 do BEST[i] = IDX[i] end else break end end for i = 1, 16 do IDX[i] = BEST[i] end end -- the mode is set by the endpoint order: 4-colour c0 > c1, 3-colour c0 <= c1 if four then if c0 < c1 then c0, c1 = c1, c0 for i = 1, 16 do local v = IDX[i] IDX[i] = if v == 0 then 1 elseif v == 1 then 0 elseif v == 2 then 3 else 2 end elseif c0 == c1 then for i = 1, 16 do IDX[i] = 0 end end elseif c0 > c1 then c0, c1 = c1, c0 for i = 1, 16 do local v = IDX[i] IDX[i] = if v == 0 then 1 elseif v == 1 then 0 else v end end writeu16(out, o, c0) writeu16(out, o + 2, c1) local bitsv = 0 for i = 16, 1, -1 do bitsv = bitsv * 4 + IDX[i] end writeu32(out, o + 4, bitsv) end local V = table.create(16, 0) local RAMP = table.create(8, 0) local SEL = table.create(16, 0) local SELB = table.create(16, 0) @native local function ramp(a0: number, a1: number) RAMP[1], RAMP[2] = a0, a1 if a0 > a1 then for i = 1, 6 do RAMP[i + 2] = ((7 - i) * a0 + i * a1) // 7 end else for i = 1, 4 do RAMP[i + 2] = ((5 - i) * a0 + i * a1) // 5 end RAMP[7], RAMP[8] = 0, 255 end end @native local function pick(): number local total = 0 for i = 1, 16 do local v = V[i] local bi, be = 0, math.huge for k = 1, 8 do local d = v - RAMP[k] local e = d * d if e < be then be, bi = e, k - 1 end end SEL[i] = bi total += be end return total end @native local function channelBlock(out: buffer, o: number) local lo, hi = 255, 0 local lo2, hi2 = 255, 0 for i = 1, 16 do local v = V[i] lo, hi = math.min(lo, v), math.max(hi, v) if v > 0 and v < 255 then lo2, hi2 = math.min(lo2, v), math.max(hi2, v) end end local a0, a1 if lo == hi then a0, a1 = lo, lo ramp(a0, a1) pick() else -- 8-value ramp, then a few nudged endpoints local bestErr, b0, b1 = math.huge, hi, lo for d0 = 0, 1 do for d1 = 0, 1 do local x0, x1 = hi - d0, lo + d1 if x0 > x1 then ramp(x0, x1) local e = pick() if e < bestErr then bestErr, b0, b1 = e, x0, x1 for i = 1, 16 do SELB[i] = SEL[i] end end end end end -- 6-value ramp with the 0 / 255 extremes if lo2 > hi2 then lo2, hi2 = lo, lo end ramp(lo2, hi2) local e = pick() if e < bestErr then bestErr, b0, b1 = e, lo2, hi2 for i = 1, 16 do SELB[i] = SEL[i] end end a0, a1 = b0, b1 for i = 1, 16 do SEL[i] = SELB[i] end end writeu8(out, o, a0) writeu8(out, o + 1, a1) local lo24, hi24 = 0, 0 for i = 8, 1, -1 do lo24 = lo24 * 8 + SEL[i] hi24 = hi24 * 8 + SEL[i + 8] end writeu8(out, o + 2, band(lo24, 255)) writeu8(out, o + 3, band(rshift(lo24, 8), 255)) writeu8(out, o + 4, rshift(lo24, 16)) writeu8(out, o + 5, band(hi24, 255)) writeu8(out, o + 6, band(rshift(hi24, 8), 255)) writeu8(out, o + 7, rshift(hi24, 16)) end @native local function gather(px: buffer, w: number, h: number, bx: number, by: number) for y = 0, 3 do local sy = math.min(by * 4 + y, h - 1) for x = 0, 3 do local sx = math.min(bx * 4 + x, w - 1) local s = (sy * w + sx) * 4 local i = y * 4 + x + 1 R[i], G[i], B[i], A[i] = readu8(px, s), readu8(px, s + 1), readu8(px, s + 2), readu8(px, s + 3) end end end @native function Encode.run(kind: string, px: buffer, w: number, h: number, threshold: number): buffer local bw, bh = (w + 3) // 4, (h + 3) // 4 local bytes = if kind == "bc1" or kind == "bc4" then 8 else 16 local out = buffer.create(bw * bh * bytes) local o = 0 for by = 0, bh - 1 do for bx = 0, bw - 1 do gather(px, w, h, bx, by) if kind == "bc1" then local any = false for i = 1, 16 do local u = A[i] >= threshold USE[i] = u any = any or not u end colourBlock(out, o, not any) elseif kind == "bc3" then for i = 1, 16 do USE[i] = true V[i] = A[i] end channelBlock(out, o) colourBlock(out, o + 8, true) elseif kind == "bc4" then for i = 1, 16 do V[i] = R[i] end channelBlock(out, o) else for i = 1, 16 do V[i] = R[i] end channelBlock(out, o) for i = 1, 16 do V[i] = G[i] end channelBlock(out, o + 8) end o += bytes end end return out end return Encode end __FILES["codecs/image/Blend"] = @native function() -- codecs/image/Blend: rgba8 layer compositing (straight alpha) with the W3C Compositing and Blending Level 1 modes. -- Clipping is source-atop (the backdrop keeps its alpha); unknown mode names composite as normal. local Blend = {} local readu8, writeu8, readu32, writeu32, blen = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32, buffer.len local min, max, floor, sqrt, abs = math.min, math.max, math.floor, math.sqrt, math.abs local IDS: { [string]: number } = { normal = 0, dissolve = 1, darken = 2, multiply = 3, colorBurn = 4, linearBurn = 5, darkerColor = 6, lighten = 7, screen = 8, colorDodge = 9, linearDodge = 10, add = 10, lighterColor = 11, overlay = 12, softLight = 13, hardLight = 14, vividLight = 15, linearLight = 16, pinLight = 17, hardMix = 18, difference = 19, exclusion = 20, subtract = 21, divide = 22, hue = 23, saturation = 24, color = 25, luminosity = 26, } local MODES: { [string]: boolean } = {} for k in IDS do MODES[k] = true end Blend.MODES = table.freeze(MODES) @native local function burn(cb: number, cs: number): number if cb >= 1 then return 1 elseif cs <= 0 then return 0 end return 1 - min(1, (1 - cb) / cs) end @native local function dodge(cb: number, cs: number): number if cb <= 0 then return 0 elseif cs >= 1 then return 1 end return min(1, cb / (1 - cs)) end -- B(cb, cs) of a separable mode @native local function sep(m: number, cb: number, cs: number): number if m == 3 then return cb * cs elseif m == 8 then return cb + cs - cb * cs elseif m == 2 then return min(cb, cs) elseif m == 7 then return max(cb, cs) elseif m == 12 then -- overlay = hardLight(cs, cb) if cb <= 0.5 then return 2 * cb * cs end local c = 2 * cb - 1 return cs + c - cs * c elseif m == 14 then if cs <= 0.5 then return 2 * cb * cs end local c = 2 * cs - 1 return cb + c - cb * c elseif m == 13 then if cs <= 0.5 then return cb - (1 - 2 * cs) * cb * (1 - cb) end local d = if cb <= 0.25 then ((16 * cb - 12) * cb + 4) * cb else sqrt(cb) return cb + (2 * cs - 1) * (d - cb) elseif m == 9 then return dodge(cb, cs) elseif m == 4 then return burn(cb, cs) elseif m == 5 then return max(0, cb + cs - 1) elseif m == 10 then return min(1, cb + cs) elseif m == 15 then if cs <= 0.5 then return burn(cb, 2 * cs) end return dodge(cb, 2 * cs - 1) elseif m == 16 then return max(0, min(1, cb + 2 * cs - 1)) elseif m == 17 then if cs <= 0.5 then return min(cb, 2 * cs) end return max(cb, 2 * cs - 1) elseif m == 18 then return if cb + cs >= 1 then 1 else 0 elseif m == 19 then return abs(cb - cs) elseif m == 20 then return cb + cs - 2 * cb * cs elseif m == 21 then return max(0, cb - cs) elseif m == 22 then if cs <= 0 then return if cb <= 0 then 0 else 1 end return min(1, cb / cs) end return cs end -- non-separable helpers (W3C): lum, clip, setLum, sat, setSat @native local function lum(r: number, g: number, b: number): number return 0.3 * r + 0.59 * g + 0.11 * b end @native local function clipColor(r: number, g: number, b: number): (number, number, number) local l = lum(r, g, b) local n = min(r, g, b) local x = max(r, g, b) if n < 0 and l - n > 1e-12 then r, g, b = l + (r - l) * l / (l - n), l + (g - l) * l / (l - n), l + (b - l) * l / (l - n) end if x > 1 and x - l > 1e-12 then r, g, b = l + (r - l) * (1 - l) / (x - l), l + (g - l) * (1 - l) / (x - l), l + (b - l) * (1 - l) / (x - l) end return r, g, b end @native local function setLum(r: number, g: number, b: number, l: number): (number, number, number) local d = l - lum(r, g, b) return clipColor(r + d, g + d, b + d) end @native local function setSat(r: number, g: number, b: number, s: number): (number, number, number) local mx = max(r, g, b) local mn = min(r, g, b) if mx - mn <= 1e-12 then return 0, 0, 0 end local k = s / (mx - mn) return (r - mn) * k, (g - mn) * k, (b - mn) * k end @native local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: number, sh: number, x: number, y: number, opacity: number, mode: string?, opts: { clip: boolean?, mask: any? }?) x, y = floor(x), floor(y) if opacity <= 0 or dw <= 0 or dh <= 0 or sw <= 0 or sh <= 0 then return end if blen(dst) < dw * dh * 4 or blen(src) < sw * sh * 4 then return end local op = min(1, opacity) local m = IDS[mode or "normal"] or 0 local clip = opts ~= nil and opts.clip == true local mask = if opts ~= nil then opts.mask else nil local mbuf: buffer? = nil local mx0, my0, mw, mh, mdef = 0, 0, 0, 0, 1 if type(mask) == "table" and type(mask.pixels) == "buffer" and type(mask.width) == "number" and type(mask.height) == "number" then mw, mh = floor(mask.width), floor(mask.height) :: number if mw > 0 and mh > 0 and blen(mask.pixels) >= mw * mh then mbuf = mask.pixels end mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0) :: number mdef = (tonumber(mask.default) or 255) / 255 elseif type(mask) == "table" then mdef = (tonumber(mask.default) or 255) / 255 end local x0, y0 = max(0, x), max(0, y) local x1, y1 = min(dw, x + sw), min(dh, y + sh) for py = y0, y1 - 1 do local so = ((py - y) * sw + (x0 - x)) * 4 local do_ = (py * dw + x0) * 4 for px = x0, x1 - 1 do local sa8 = readu8(src, so + 3) if sa8 ~= 0 then local sa = sa8 / 255 * op if mbuf ~= nil or mdef ~= 1 then local mv = mdef local mxx, myy = px - mx0, py - my0 if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then mv = readu8(mbuf, myy * mw + mxx) / 255 end sa *= mv end if m == 1 then -- dissolve: a hash threshold per pixel, full alpha where it shows local h = (px * 73856093 + py * 19349663) % 65536 / 65536 sa = if h < sa then 1 else 0 end local ba8 = readu8(dst, do_ + 3) if sa > 0 and not (clip and ba8 == 0) then local sr, sg, sb = readu8(src, so) / 255, readu8(src, so + 1) / 255, readu8(src, so + 2) / 255 if ba8 == 0 then writeu32(dst, do_, readu32(src, so)) writeu8(dst, do_ + 3, floor(sa * 255 + 0.5)) else local ba = ba8 / 255 local br, bg, bb = readu8(dst, do_) / 255, readu8(dst, do_ + 1) / 255, readu8(dst, do_ + 2) / 255 local mr, mg, mb = sr, sg, sb if m >= 2 and m ~= 6 and m ~= 11 and m < 23 then mr, mg, mb = sep(m, br, sr), sep(m, bg, sg), sep(m, bb, sb) :: number elseif m == 6 then if lum(sr, sg, sb) >= lum(br, bg, bb) then mr, mg, mb = br, bg, bb end elseif m == 11 then if lum(sr, sg, sb) < lum(br, bg, bb) then mr, mg, mb = br, bg, bb end elseif m == 23 then local s = max(br, bg, bb) - min(br, bg, bb) local r1, g1, b1 = setSat(sr, sg, sb, s) mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb)) elseif m == 24 then local s = max(sr, sg, sb) - min(sr, sg, sb) local r1, g1, b1 = setSat(br, bg, bb, s) mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb)) elseif m == 25 then mr, mg, mb = setLum(sr, sg, sb, lum(br, bg, bb)) elseif m == 26 then mr, mg, mb = setLum(br, bg, bb, lum(sr, sg, sb)) end local orr, og, ob, oa if clip then -- source-atop: the backdrop's alpha; the mixed colour where the backdrop is opaque orr = sa * mr + (1 - sa) * br og = sa * mg + (1 - sa) * bg ob = sa * mb + (1 - sa) * bb oa = ba else oa = sa + ba * (1 - sa) local ws, wm, wb = sa * (1 - ba), sa * ba, (1 - sa) * ba orr = (ws * sr + wm * mr + wb * br) / oa og = (ws * sg + wm * mg + wb * bg) / oa ob = (ws * sb + wm * mb + wb * bb) / oa end writeu8(dst, do_, floor(max(0, min(1, orr)) * 255 + 0.5)) writeu8(dst, do_ + 1, floor(max(0, min(1, og)) * 255 + 0.5)) writeu8(dst, do_ + 2, floor(max(0, min(1, ob)) * 255 + 0.5)) writeu8(dst, do_ + 3, floor(max(0, min(1, oa)) * 255 + 0.5)) end end end so += 4 do_ += 4 end end end @native local function lerp(dst: buffer, from: buffer, t: number, n: number, w: number?, mask: any?) if blen(dst) < n * 4 or blen(from) < n * 4 then return end if mask == nil or w == nil or w <= 0 then for i = 0, n * 4 - 1 do local a = readu8(from, i) writeu8(dst, i, floor(a + (readu8(dst, i) - a) * t + 0.5)) end return end local mbuf: buffer? = mask.pixels local mw, mh = floor(tonumber(mask.width) or 0), floor(tonumber(mask.height) or 0) local mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0) local mdef = (tonumber(mask.default) or 255) / 255 if type(mbuf) ~= "buffer" or mw <= 0 or mh <= 0 or blen(mbuf) < mw * mh then mbuf = nil end for p = 0, n - 1 do local px, py = p % w, p // w local mv = mdef local mxx, myy = px - mx0, py - my0 if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then mv = readu8(mbuf, myy * mw + mxx) / 255 end local tt = t * mv local o = p * 4 for k = o, o + 3 do local a = readu8(from, k) writeu8(dst, k, floor(a + (readu8(dst, k) - a) * tt + 0.5)) end end end Blend.composite = composite Blend.lerp = lerp @native local function isImage(v: any): boolean return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and buffer.len(v.pixels) >= v.width * v.height * 4 end @native local function maskOf(l: any): any local m = l.mask if type(m) ~= "table" or m.disabled or type(m.image) ~= "table" or type(m.image.pixels) ~= "buffer" then return nil end local img = m.image local px = img.pixels if img.format == "rgba8" then local n = img.width * img.height local g = buffer.create(n) for i = 0, n - 1 do buffer.writeu8(g, i, buffer.readu8(px, i * 4)) end px = g end return { pixels = px, width = img.width, height = img.height, x = m.x or 0, y = m.y or 0, default = m.default or 255 } end @native local function compose(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) local i = 1 while i <= #layers do local l = layers[i] i += 1 if type(l) ~= "table" or (l.visible == false and not hidden) then -- clipped layers above a hidden base are hidden too while i <= #layers and type(layers[i]) == "table" and layers[i].clip do i += 1 end continue end local opacity = (tonumber(l.opacity) or 1) * (tonumber(l.fillOpacity) or 1) local mode = if type(l.blend) == "string" then l.blend else "normal" local src: buffer? = nil if type(l.children) == "table" then if mode == "passThrough" then local before = buffer.create(w * h * 4) buffer.copy(before, 0, canvas, 0, w * h * 4) compose(l.children, canvas, w, h, hidden) -- the group's opacity and mask limit how much of its effect reaches the canvas (as in Photoshop) local gm = maskOf(l) if opacity < 1 or gm ~= nil then lerp(canvas, before, opacity, w * h, w, gm) end continue end src = buffer.create(w * h * 4) compose(l.children, src :: buffer, w, h, hidden) elseif isImage(l.image) then if l.image.width > 0 and l.image.height > 0 then local b = buffer.create(w * h * 4) composite(b, w, h, l.image.pixels, l.image.width, l.image.height, tonumber(l.x) or 0, tonumber(l.y) or 0, 1, "normal") src = b end end -- clipping layers above this one: composited onto it with their alpha limited to it while i <= #layers and type(layers[i]) == "table" and layers[i].clip do local c = layers[i] i += 1 if src and (c.visible ~= false or hidden) and isImage(c.image) then composite(src :: buffer, w, h, c.image.pixels, c.image.width, c.image.height, tonumber(c.x) or 0, tonumber(c.y) or 0, (tonumber(c.opacity) or 1) * (tonumber(c.fillOpacity) or 1), c.blend, { clip = true, mask = maskOf(c) }) end end if src then composite(canvas, w, h, src :: buffer, w, h, 0, 0, opacity, mode, { mask = maskOf(l) }) end end end @native function Blend.flatten(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) if blen(canvas) >= w * h * 4 then compose(layers, canvas, w, h, hidden) end end return Blend end __FILES["codecs/image/Dct"] = @native function() -- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). -- libjpeg's islow (jidctint.c / jfdctint.c), the reduced IDCTs (jidctred.c) and jcdctmgr.c's rounding quantiser, bit-exact -- with libjpeg-turbo. From jpeg-luau 1.0 (same author); IJG code: licenses/libjpeg-turbo-LICENSE.md. local readi16, readu16, writeu16, readu8, writei16 = buffer.readi16, buffer.readu16, buffer.writeu16, buffer.readu8, buffer.writei16 local clamp = math.clamp local Dct = {} local ws = table.create(64, 0) @native local function idct8(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) local s1 = 2 ^ (13 - p1) local h1 = s1 / 2 local s2 = 2 ^ (16 + p1) local h2 = s2 / 2 + center * s2 local dcm = 2 ^ p1 for c = 0, 7 do local o = off + c * 2 local qo = c * 2 local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48) local c4, c5, c6, c7 = readi16(coef, o + 64), readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112) if c1 == 0 and c2 == 0 and c3 == 0 and c4 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then local dc = readi16(coef, o) * readu16(q, qo) * dcm ws[c + 1] = dc ws[c + 9] = dc ws[c + 17] = dc ws[c + 25] = dc ws[c + 33] = dc ws[c + 41] = dc ws[c + 49] = dc ws[c + 57] = dc else -- even part local z2 = c2 * readu16(q, qo + 32) local z3 = c6 * readu16(q, qo + 96) local z1 = (z2 + z3) * 4433 local tmp2 = z1 - z3 * 15137 local tmp3 = z1 + z2 * 6270 z2 = readi16(coef, o) * readu16(q, qo) z3 = c4 * readu16(q, qo + 64) local tmp0 = (z2 + z3) * 8192 local tmp1 = (z2 - z3) * 8192 local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 -- odd part local t0 = c7 * readu16(q, qo + 112) local t1 = c5 * readu16(q, qo + 80) local t2 = c3 * readu16(q, qo + 48) local t3 = c1 * readu16(q, qo + 16) z1 = t0 + t3 z2 = t1 + t2 z3 = t0 + t2 local z4 = t1 + t3 local z5 = (z3 + z4) * 9633 t0 *= 2446 t1 *= 16819 t2 *= 25172 t3 *= 12299 z1 *= -7373 z2 *= -20995 z3 = z3 * -16069 + z5 z4 = z4 * -3196 + z5 t0 += z1 + z3 t1 += z2 + z4 t2 += z2 + z3 t3 += z1 + z4 ws[c + 1] = (tmp10 + t3 + h1) // s1 ws[c + 57] = (tmp10 - t3 + h1) // s1 ws[c + 9] = (tmp11 + t2 + h1) // s1 ws[c + 49] = (tmp11 - t2 + h1) // s1 ws[c + 17] = (tmp12 + t1 + h1) // s1 ws[c + 41] = (tmp12 - t1 + h1) // s1 ws[c + 25] = (tmp13 + t0 + h1) // s1 ws[c + 33] = (tmp13 - t0 + h1) // s1 end end local sd = 2 ^ (p1 + 3) local hd = sd / 2 + center * sd for r = 0, 7 do local b = r * 8 local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4] local w4, w5, w6, w7 = ws[b + 5], ws[b + 6], ws[b + 7], ws[b + 8] local o = (out + r * stride) * 2 if w1 == 0 and w2 == 0 and w3 == 0 and w4 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then local v = clamp((w0 + hd) // sd, 0, maxv) for i = 0, 14, 2 do writeu16(plane, o + i, v) end else local z1 = (w2 + w6) * 4433 local tmp2 = z1 - w6 * 15137 local tmp3 = z1 + w2 * 6270 local tmp0 = (w0 + w4) * 8192 local tmp1 = (w0 - w4) * 8192 local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 local t0, t1, t2, t3 = w7, w5, w3, w1 z1 = t0 + t3 local z2 = t1 + t2 local z3 = t0 + t2 local z4 = t1 + t3 local z5 = (z3 + z4) * 9633 t0 *= 2446 t1 *= 16819 t2 *= 25172 t3 *= 12299 z1 *= -7373 z2 *= -20995 z3 = z3 * -16069 + z5 z4 = z4 * -3196 + z5 t0 += z1 + z3 t1 += z2 + z4 t2 += z2 + z3 t3 += z1 + z4 writeu16(plane, o, clamp((tmp10 + t3 + h2) // s2, 0, maxv)) writeu16(plane, o + 14, clamp((tmp10 - t3 + h2) // s2, 0, maxv)) writeu16(plane, o + 2, clamp((tmp11 + t2 + h2) // s2, 0, maxv)) writeu16(plane, o + 12, clamp((tmp11 - t2 + h2) // s2, 0, maxv)) writeu16(plane, o + 4, clamp((tmp12 + t1 + h2) // s2, 0, maxv)) writeu16(plane, o + 10, clamp((tmp12 - t1 + h2) // s2, 0, maxv)) writeu16(plane, o + 6, clamp((tmp13 + t0 + h2) // s2, 0, maxv)) writeu16(plane, o + 8, clamp((tmp13 - t0 + h2) // s2, 0, maxv)) end end end @native local function idct4(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) local s1 = 2 ^ (14 - p1) local h1 = s1 / 2 local dcm = 2 ^ p1 for c = 0, 7 do if c ~= 4 then local o = off + c * 2 local qo = c * 2 local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48) local c5, c6, c7 = readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112) if c1 == 0 and c2 == 0 and c3 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then local dc = readi16(coef, o) * readu16(q, qo) * dcm ws[c + 1] = dc ws[c + 9] = dc ws[c + 17] = dc ws[c + 25] = dc else local tmp0 = readi16(coef, o) * readu16(q, qo) * 16384 local tmp2 = c2 * readu16(q, qo + 32) * 15137 - c6 * readu16(q, qo + 96) * 6270 local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2 local z1 = c7 * readu16(q, qo + 112) local z2 = c5 * readu16(q, qo + 80) local z3 = c3 * readu16(q, qo + 48) local z4 = c1 * readu16(q, qo + 16) tmp0 = z1 * -1730 + z2 * 11893 + z3 * -17799 + z4 * 8697 tmp2 = z1 * -4176 + z2 * -4926 + z3 * 7373 + z4 * 20995 ws[c + 1] = (tmp10 + tmp2 + h1) // s1 ws[c + 25] = (tmp10 - tmp2 + h1) // s1 ws[c + 9] = (tmp12 + tmp0 + h1) // s1 ws[c + 17] = (tmp12 - tmp0 + h1) // s1 end end end local s2 = 2 ^ (17 + p1) local h2 = s2 / 2 + center * s2 local sd = 2 ^ (p1 + 3) local hd = sd / 2 + center * sd for r = 0, 3 do local b = r * 8 local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4] local w5, w6, w7 = ws[b + 6], ws[b + 7], ws[b + 8] local o = (out + r * stride) * 2 if w1 == 0 and w2 == 0 and w3 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then local v = clamp((w0 + hd) // sd, 0, maxv) writeu16(plane, o, v) writeu16(plane, o + 2, v) writeu16(plane, o + 4, v) writeu16(plane, o + 6, v) else local tmp0 = w0 * 16384 local tmp2 = w2 * 15137 - w6 * 6270 local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2 tmp0 = w7 * -1730 + w5 * 11893 + w3 * -17799 + w1 * 8697 tmp2 = w7 * -4176 + w5 * -4926 + w3 * 7373 + w1 * 20995 writeu16(plane, o, clamp((tmp10 + tmp2 + h2) // s2, 0, maxv)) writeu16(plane, o + 6, clamp((tmp10 - tmp2 + h2) // s2, 0, maxv)) writeu16(plane, o + 2, clamp((tmp12 + tmp0 + h2) // s2, 0, maxv)) writeu16(plane, o + 4, clamp((tmp12 - tmp0 + h2) // s2, 0, maxv)) end end end @native local function idct2(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) local s1 = 2 ^ (15 - p1) local h1 = s1 / 2 local dcm = 2 ^ p1 for c = 0, 7 do if c ~= 2 and c ~= 4 and c ~= 6 then local o = off + c * 2 local qo = c * 2 local c1, c3 = readi16(coef, o + 16), readi16(coef, o + 48) local c5, c7 = readi16(coef, o + 80), readi16(coef, o + 112) if c1 == 0 and c3 == 0 and c5 == 0 and c7 == 0 then local dc = readi16(coef, o) * readu16(q, qo) * dcm ws[c + 1] = dc ws[c + 9] = dc else local tmp10 = readi16(coef, o) * readu16(q, qo) * 32768 local tmp0 = c7 * readu16(q, qo + 112) * -5906 + c5 * readu16(q, qo + 80) * 6967 + c3 * readu16(q, qo + 48) * -10426 + c1 * readu16(q, qo + 16) * 29692 ws[c + 1] = (tmp10 + tmp0 + h1) // s1 ws[c + 9] = (tmp10 - tmp0 + h1) // s1 end end end local s2 = 2 ^ (18 + p1) local h2 = s2 / 2 + center * s2 local sd = 2 ^ (p1 + 3) local hd = sd / 2 + center * sd for r = 0, 1 do local b = r * 8 local w0, w1, w3, w5, w7 = ws[b + 1], ws[b + 2], ws[b + 4], ws[b + 6], ws[b + 8] local o = (out + r * stride) * 2 if w1 == 0 and w3 == 0 and w5 == 0 and w7 == 0 then local v = clamp((w0 + hd) // sd, 0, maxv) writeu16(plane, o, v) writeu16(plane, o + 2, v) else local tmp10 = w0 * 32768 local tmp0 = w7 * -5906 + w5 * 6967 + w3 * -10426 + w1 * 29692 writeu16(plane, o, clamp((tmp10 + tmp0 + h2) // s2, 0, maxv)) writeu16(plane, o + 2, clamp((tmp10 - tmp0 + h2) // s2, 0, maxv)) end end end -- p1 = PASS1_BITS (2 for 8-bit, 1 for 12-bit) @native function Dct.idctComponent(coef: buffer, q: buffer, bpl: number, bpc: number, size: number, plane: buffer, p1: number, center: number, maxv: number, hook: (() -> ())?) local stride = bpl * size for by = 0, bpc - 1 do if hook and by > 0 then pcall(hook) end for bx = 0, bpl - 1 do local off = (by * bpl + bx) * 128 local out = by * size * stride + bx * size if size == 8 then idct8(coef, off, q, plane, out, stride, p1, center, maxv) elseif size == 4 then idct4(coef, off, q, plane, out, stride, p1, center, maxv) elseif size == 2 then idct2(coef, off, q, plane, out, stride, p1, center, maxv) else local v = (readi16(coef, off) * readu16(q, 0) + 4) // 8 + center writeu16(plane, out * 2, clamp(v, 0, maxv)) end end end end @native function Dct.idctBlock(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) idct8(coef, off, q, plane, out, stride, p1, center, maxv) end local fw = table.create(64, 0) @native local function quant(coef: buffer, off: number, div: buffer, v: number, i: number) local qv = readu16(div, i * 2) * 8 local h = qv // 2 if v < 0 then writei16(coef, off + i * 2, -((h - v) // qv)) else writei16(coef, off + i * 2, (v + h) // qv) end end -- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored @native function Dct.fdctQuantize(src: buffer, stride: number, x: number, y: number, w: number, h: number, div: buffer, coef: buffer, off: number) local lastX, lastY = w - 1, h - 1 for r = 0, 7 do local row = math.min(y + r, lastY) * stride local d0: number, d1: number, d2: number, d3: number, d4: number, d5: number, d6: number, d7: number if x + 7 <= lastX then local p = row + x d0, d1, d2, d3 = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3) :: number d4, d5, d6, d7 = readu8(src, p + 4), readu8(src, p + 5), readu8(src, p + 6), readu8(src, p + 7) :: number else d0 = readu8(src, row + math.min(x, lastX)) d1 = readu8(src, row + math.min(x + 1, lastX)) d2 = readu8(src, row + math.min(x + 2, lastX)) d3 = readu8(src, row + math.min(x + 3, lastX)) d4 = readu8(src, row + math.min(x + 4, lastX)) d5 = readu8(src, row + math.min(x + 5, lastX)) d6 = readu8(src, row + math.min(x + 6, lastX)) d7 = readu8(src, row + math.min(x + 7, lastX)) end d0 -= 128 d1 -= 128 d2 -= 128 d3 -= 128 d4 -= 128 d5 -= 128 d6 -= 128 d7 -= 128 local tmp0, tmp7 = d0 + d7, d0 - d7 local tmp1, tmp6 = d1 + d6, d1 - d6 local tmp2, tmp5 = d2 + d5, d2 - d5 local tmp3, tmp4 = d3 + d4, d3 - d4 local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 local b = r * 8 + 1 fw[b] = (tmp10 + tmp11) * 4 fw[b + 4] = (tmp10 - tmp11) * 4 local z1 = (tmp12 + tmp13) * 4433 fw[b + 2] = (z1 + tmp13 * 6270 + 1024) // 2048 fw[b + 6] = (z1 - tmp12 * 15137 + 1024) // 2048 z1 = tmp4 + tmp7 local z2 = tmp5 + tmp6 local z3 = tmp4 + tmp6 local z4 = tmp5 + tmp7 local z5 = (z3 + z4) * 9633 tmp4 *= 2446 tmp5 *= 16819 tmp6 *= 25172 tmp7 *= 12299 z1 *= -7373 z2 *= -20995 z3 = z3 * -16069 + z5 z4 = z4 * -3196 + z5 fw[b + 7] = (tmp4 + z1 + z3 + 1024) // 2048 fw[b + 5] = (tmp5 + z2 + z4 + 1024) // 2048 fw[b + 3] = (tmp6 + z2 + z3 + 1024) // 2048 fw[b + 1] = (tmp7 + z1 + z4 + 1024) // 2048 end for c = 1, 8 do local d0, d1, d2, d3 = fw[c], fw[c + 8], fw[c + 16], fw[c + 24] local d4, d5, d6, d7 = fw[c + 32], fw[c + 40], fw[c + 48], fw[c + 56] local tmp0, tmp7 = d0 + d7, d0 - d7 local tmp1, tmp6 = d1 + d6, d1 - d6 local tmp2, tmp5 = d2 + d5, d2 - d5 local tmp3, tmp4 = d3 + d4, d3 - d4 local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 local o0 = (tmp10 + tmp11 + 2) // 4 local o4 = (tmp10 - tmp11 + 2) // 4 local z1 = (tmp12 + tmp13) * 4433 local o2 = (z1 + tmp13 * 6270 + 16384) // 32768 local o6 = (z1 - tmp12 * 15137 + 16384) // 32768 z1 = tmp4 + tmp7 local z2 = tmp5 + tmp6 local z3 = tmp4 + tmp6 local z4 = tmp5 + tmp7 local z5 = (z3 + z4) * 9633 tmp4 *= 2446 tmp5 *= 16819 tmp6 *= 25172 tmp7 *= 12299 z1 *= -7373 z2 *= -20995 z3 = z3 * -16069 + z5 z4 = z4 * -3196 + z5 local o7 = (tmp4 + z1 + z3 + 16384) // 32768 local o5 = (tmp5 + z2 + z4 + 16384) // 32768 local o3 = (tmp6 + z2 + z3 + 16384) // 32768 local o1 = (tmp7 + z1 + z4 + 16384) // 32768 local cc = c - 1 quant(coef, off, div, o0, cc) quant(coef, off, div, o1, cc + 8) quant(coef, off, div, o2, cc + 16) quant(coef, off, div, o3, cc + 24) quant(coef, off, div, o4, cc + 32) quant(coef, off, div, o5, cc + 40) quant(coef, off, div, o6, cc + 48) quant(coef, off, div, o7, cc + 56) end end return Dct end __FILES["codecs/image/Etc"] = @native function() -- codecs/image/Etc: ETC1 / ETC2 / EAC block texture decoding (Khronos Data Format Specification 1.3, section 21). -- New in rosetta. Signed EAC values are biased into rgba8 (-1 -> 1, 0 -> 128, +1 -> 255). local Etc = {} Etc.BLOCK = table.freeze({ etc1 = 8, etc2_rgb = 8, etc2_rgba = 16, etc2_rgba1 = 8, eac_r11 = 8, eac_r11s = 8, eac_rg11 = 16, eac_rg11s = 16 }) :: { [string]: number } local readu8, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap local MOD = { -- the ETC1 intensity modifiers per table: index (msb * 2 + lsb) -> a, b, -a, -b { 2, 8, -2, -8 }, { 5, 17, -5, -17 }, { 9, 29, -9, -29 }, { 13, 42, -13, -42 }, { 18, 60, -18, -60 }, { 24, 80, -24, -80 }, { 33, 106, -33, -106 }, { 47, 183, -47, -183 }, } local DIST = { 3, 6, 11, 16, 23, 32, 41, 64 } -- T / H mode distances local EAC = { { -3, -6, -9, -15, 2, 5, 8, 14 }, { -3, -7, -10, -13, 2, 6, 9, 12 }, { -2, -5, -8, -13, 1, 4, 7, 12 }, { -2, -4, -6, -13, 1, 3, 5, 12 }, { -3, -6, -8, -12, 2, 5, 7, 11 }, { -3, -7, -9, -11, 2, 6, 8, 10 }, { -4, -7, -8, -11, 3, 6, 7, 10 }, { -3, -5, -8, -11, 2, 4, 7, 10 }, { -2, -6, -8, -10, 1, 5, 7, 9 }, { -2, -5, -8, -10, 1, 4, 7, 9 }, { -2, -4, -8, -10, 1, 3, 7, 9 }, { -2, -5, -7, -10, 1, 4, 6, 9 }, { -3, -4, -7, -10, 2, 3, 6, 9 }, { -1, -2, -3, -10, 0, 1, 2, 9 }, { -4, -6, -8, -9, 3, 5, 7, 8 }, { -3, -5, -7, -9, 2, 4, 6, 8 }, } @native local function clamp8(v: number): number return if v < 0 then 0 elseif v > 255 then 255 else v end @native local function rgb(r: number, g: number, b: number): number return clamp8(r) + clamp8(g) * 256 + clamp8(b) * 65536 + 0xFF000000 end -- blk: 16 u32 rgba8 pixels in raster order (y * 4 + x) local P = table.create(4, 0) @native local function be32(src: buffer, p: number): number return byteswap(readu32(src, p)) end -- the 2-bit pixel index of pixel i (column-major: i = x * 4 + y) @native local function pix(lo: number, i: number): number return band(rshift(lo, i + 15), 2) + band(rshift(lo, i), 1) end -- ETC1 / ETC2 colour block; the RGB A1 variant: bit 33 = opaque @native local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch: boolean) local hi, lo = be32(src, p), be32(src, p + 4) local diffBit = band(rshift(hi, 1), 1) local flip = band(hi, 1) local opaque = not punch or diffBit == 1 local r1, g1, b1, r2, g2, b2 if not punch and diffBit == 0 then r1, r2 = band(rshift(hi, 28), 15) * 17, band(rshift(hi, 24), 15) * 17 g1, g2 = band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17 b1, b2 = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17 else local R, G, B = band(rshift(hi, 27), 31), band(rshift(hi, 19), 31), band(rshift(hi, 11), 31) local dR, dG, dB = band(rshift(hi, 24), 7), band(rshift(hi, 16), 7), band(rshift(hi, 8), 7) if dR >= 4 then dR -= 8 end if dG >= 4 then dG -= 8 end if dB >= 4 then dB -= 8 end local R2, G2, B2 = R + dR, G + dG, B + dB if etc2 and (R2 < 0 or R2 > 31) then -- T mode local ra = band(rshift(hi, 27), 3) * 4 + band(rshift(hi, 24), 3) local c1r, c1g, c1b = ra * 17, band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17 local c2r, c2g, c2b = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17, band(rshift(hi, 4), 15) * 17 local d = DIST[band(rshift(hi, 2), 3) * 2 + band(hi, 1) + 1] P[1] = rgb(c1r, c1g, c1b) P[2] = rgb(c2r + d, c2g + d, c2b + d) P[3] = rgb(c2r, c2g, c2b) P[4] = rgb(c2r - d, c2g - d, c2b - d) elseif etc2 and (G2 < 0 or G2 > 31) then -- H mode local q1r = band(rshift(hi, 27), 15) local q1g = band(rshift(hi, 24), 7) * 2 + band(rshift(hi, 20), 1) local q1b = band(rshift(hi, 19), 1) * 8 + band(rshift(hi, 15), 7) local q2r, q2g, q2b = band(rshift(hi, 11), 15), band(rshift(hi, 7), 15), band(rshift(hi, 3), 15) local order = if q1r * 256 + q1g * 16 + q1b >= q2r * 256 + q2g * 16 + q2b then 1 else 0 local d = DIST[band(rshift(hi, 2), 1) * 4 + band(hi, 1) * 2 + order + 1] local c1r, c1g, c1b, c2r, c2g, c2b = q1r * 17, q1g * 17, q1b * 17, q2r * 17, q2g * 17, q2b * 17 P[1] = rgb(c1r + d, c1g + d, c1b + d) P[2] = rgb(c1r - d, c1g - d, c1b - d) P[3] = rgb(c2r + d, c2g + d, c2b + d) P[4] = rgb(c2r - d, c2g - d, c2b - d) elseif etc2 and (B2 < 0 or B2 > 31) then -- planar (always opaque) local ro = band(rshift(hi, 25), 63) local go = band(rshift(hi, 24), 1) * 64 + band(rshift(hi, 17), 63) local bo = band(rshift(hi, 16), 1) * 32 + band(rshift(hi, 11), 3) * 8 + band(rshift(hi, 7), 7) local rh = band(rshift(hi, 2), 31) * 2 + band(hi, 1) local gh, bh = band(rshift(lo, 25), 127), band(rshift(lo, 19), 63) local rv, gv, bv = band(rshift(lo, 13), 63), band(rshift(lo, 6), 127), band(lo, 63) ro, rh, rv = ro * 4 + rshift(ro, 4), rh * 4 + rshift(rh, 4), rv * 4 + rshift(rv, 4) go, gh, gv = go * 2 + rshift(go, 6), gh * 2 + rshift(gh, 6), gv * 2 + rshift(gv, 6) bo, bh, bv = bo * 4 + rshift(bo, 4), bh * 4 + rshift(bh, 4), bv * 4 + rshift(bv, 4) for y = 0, 3 do for x = 0, 3 do local r = (x * (rh - ro) + y * (rv - ro) + 4 * ro + 2) // 4 local g = (x * (gh - go) + y * (gv - go) + 4 * go + 2) // 4 local b = (x * (bh - bo) + y * (bv - bo) + 4 * bo + 2) // 4 writeu32(blk, (y * 4 + x) * 4, rgb(r, g, b)) end end return else r1, g1, b1 = R * 8 + rshift(R, 2), G * 8 + rshift(G, 2), B * 8 + rshift(B, 2) r2, g2, b2 = R2 * 8 + rshift(R2, 2), G2 * 8 + rshift(G2, 2), B2 * 8 + rshift(B2, 2) end if not r1 then for i = 0, 15 do local x, y = rshift(i, 2), band(i, 3) local idx = pix(lo, i) local c = if not opaque and idx == 2 then 0 else P[idx + 1] writeu32(blk, (y * 4 + x) * 4, c) end return end end local t1, t2 = MOD[band(rshift(hi, 5), 7) + 1], MOD[band(rshift(hi, 2), 7) + 1] for i = 0, 15 do local x, y = rshift(i, 2), band(i, 3) local second = if flip == 0 then x >= 2 else y >= 2 local idx = pix(lo, i) local c if not opaque and idx == 2 then c = 0 else local m = if second then t2[idx + 1] else t1[idx + 1] if not opaque and idx == 0 then m = 0 end if second then c = rgb((r2 :: number) + m, (g2 :: number) + m, (b2 :: number) + m) else c = rgb((r1 :: number) + m, (g1 :: number) + m, (b1 :: number) + m) end end writeu32(blk, (y * 4 + x) * 4, c) end end local VALS = table.create(16, 0) @native local function eac(src: buffer, p: number, mode: string) local base = readu8(src, p) local b1 = readu8(src, p + 1) local mult, tab = rshift(b1, 4), EAC[band(b1, 15) + 1] -- 48 index bits, pixel 0 (column-major) first: bytes 2..7 big-endian, as 24 + 24 bits local hiIdx = readu8(src, p + 2) * 65536 + readu8(src, p + 3) * 256 + readu8(src, p + 4) local loIdx = readu8(src, p + 5) * 65536 + readu8(src, p + 6) * 256 + readu8(src, p + 7) if mode == "s11" then if base >= 128 then base -= 256 end if base == -128 then base = -127 end end for i = 0, 15 do local idx = if i < 8 then band(rshift(hiIdx, 21 - i * 3), 7) else band(rshift(loIdx, 21 - (i - 8) * 3), 7) local m = tab[idx + 1] local v if mode == "alpha" then v = clamp8(base + m * mult) elseif mode == "u11" then v = if mult == 0 then base * 8 + 4 + m else base * 8 + 4 + m * mult * 8 v = if v < 0 then 0 elseif v > 2047 then 2047 else v else v = if mult == 0 then base * 8 + m else base * 8 + m * mult * 8 v = if v < -1023 then -1023 elseif v > 1023 then 1023 else v end VALS[band(i, 3) * 4 + rshift(i, 2) + 1] = v end end @native local function to8(v: number, signed: boolean): number if signed then return math.floor(v * 127 / 1023 + 0.5) + 128 end return math.floor(v * 255 / 2047 + 0.5) end @native local function to16(v: number, signed: boolean): number if signed then return math.floor((v + 1023) * 65535 / 2046 + 0.5) end return v * 32 + rshift(v, 6) end @native function Etc.size(kind: string, w: number, h: number): number? local b = Etc.BLOCK[kind] return if b then ((w + 3) // 4) * ((h + 3) // 4) * b else nil end @native function Etc.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?, wide: boolean?): (buffer?, string?) local bytes = Etc.BLOCK[kind] if not bytes then return nil, "unsupported: unknown block format " .. tostring(kind) end if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then return nil, "bad image size" end local need = Etc.size(kind, w, h) :: number if offset < 0 or offset + need > buffer.len(src) then return nil, "truncated: block data runs past the end" end local isEac = string.sub(kind, 1, 3) == "eac" local w16 = isEac and wide == true local bpp = if w16 then 8 else 4 local oo = outOffset or 0 local dst = out or buffer.create(w * h * bpp) if oo + w * h * bpp > buffer.len(dst) then return nil, "output buffer too small" end local signed = kind == "eac_r11s" or kind == "eac_rg11s" local two = kind == "eac_rg11" or kind == "eac_rg11s" local mode11 = if signed then "s11" else "u11" local etc2 = kind ~= "etc1" local punch = kind == "etc2_rgba1" local blk = buffer.create(16 * bpp) local bw, bh = (w + 3) // 4, (h + 3) // 4 local p = offset local rowBytes = w * bpp for by = 0, bh - 1 do local rows = math.min(4, h - by * 4) for bx = 0, bw - 1 do if isEac then eac(src, p, mode11) for i = 0, 15 do local v = VALS[i + 1] if w16 then local q = to16(v, signed) writeu16(blk, i * 8, q) writeu16(blk, i * 8 + 2, if two then 0 else q) writeu16(blk, i * 8 + 4, if two then 0 else q) writeu16(blk, i * 8 + 6, 65535) else local q = to8(v, signed) writeu32(blk, i * 4, if two then q + 0xFF000000 else q + q * 256 + q * 65536 + 0xFF000000) end end if two then eac(src, p + 8, mode11) for i = 0, 15 do local v = VALS[i + 1] if w16 then writeu16(blk, i * 8 + 2, to16(v, signed)) else writeu8(blk, i * 4 + 1, to8(v, signed)) end end end elseif kind == "etc2_rgba" then colour(src, p + 8, blk, true, false) eac(src, p, "alpha") for i = 0, 15 do writeu8(blk, i * 4 + 3, VALS[i + 1]) end else colour(src, p, blk, etc2, punch) end p += bytes local cols = math.min(4, w - bx * 4) local base = oo + (by * 4) * rowBytes + bx * 4 * bpp for y = 0, rows - 1 do buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp) end end end return dst, nil end return Etc end __FILES["codecs/image/Half"] = @native function() -- codecs/image/Half: IEEE 754 binary16 <-> number (round to nearest even, overflow to infinity). New in rosetta. local Half = {} local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift @native local function toFloat(h: number): number local s = if h >= 32768 then -1 else 1 local e = band(rshift(h, 10), 31) local m = band(h, 1023) if e == 0 then return s * m * 2 ^ -24 elseif e == 31 then return if m == 0 then s * math.huge else 0 / 0 end return s * (1024 + m) * 2 ^ (e - 25) end Half.toFloat = toFloat local TABLE: { [number]: number } = table.create(65536, 0) for h = 0, 65535 do TABLE[h] = toFloat(h) end Half.TABLE = TABLE local scratch = buffer.create(4) @native function Half.fromFloat(f: number): number if f ~= f then return 0x7E00 end buffer.writef32(scratch, 0, f) local x = buffer.readu32(scratch, 0) local sign = band(rshift(x, 16), 0x8000) local e = band(rshift(x, 23), 0xFF) local m = band(x, 0x7FFFFF) if e == 255 then return bor(sign, 0x7C00) end local ne = e - 112 if ne >= 31 then return bor(sign, 0x7C00) elseif ne <= 0 then if ne < -10 then return sign end m = bor(m, 0x800000) local shift = 14 - ne local hm = rshift(m, shift) local rem = band(m, lshift(1, shift) - 1) local halfway = lshift(1, shift - 1) if rem > halfway or (rem == halfway and band(hm, 1) == 1) then hm += 1 end return sign + hm end local hm = rshift(m, 13) local rem = band(m, 0x1FFF) if rem > 0x1000 or (rem == 0x1000 and band(hm, 1) == 1) then hm += 1 -- a carry out of the mantissa bumps the exponent (up to infinity), as it should end return sign + ne * 1024 + hm end return Half end __FILES["codecs/image/Jpeg"] = function() -- codecs/image/Jpeg: the JPEG codec (ITU T.81), bit-exact with libjpeg-turbo's djpeg and byte-identical with cjpeg. -- From jpeg-luau 1.0 (same author); IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md. Motion-JPEG: frames without -- DHT use the T.81 annex K tables; AVI1 fields are woven top field first, as ffmpeg does (it ignores the polarity). local Err = __include("core/Err") local Types = __include("Types") local Decode = __include("codecs/image/Jpeg/Decode") local Encode = __include("codecs/image/Jpeg/Encode") local Yuv = __include("codecs/image/Jpeg/Yuv") local Jpeg = {} type DecodeOptions = { scale: number?, orient: boolean?, native: boolean?, yuv: boolean?, fields: boolean?, raw: boolean?, maxPixels: number?, yield: (() -> ())?, } type EncodeOptions = { quality: number?, subsampling: ("420" | "422" | "444")?, progressive: boolean?, optimize: boolean?, gray: boolean?, restart: number?, jfif: boolean?, density: { unit: number, x: number, y: number }?, segments: { { marker: number, data: buffer } }?, } type Info = { width: number, height: number, components: number, progressive: boolean, arithmetic: boolean, precision: number, colorSpace: string, sampling: { { number } }, orientation: number, adobe: number?, jfif: boolean, avi1: number?, } local function range(buf: buffer, off: number?, len: number?): (number, number) local n = buffer.len(buf) local o = math.clamp(math.floor(tonumber(off) or 0), 0, n) return o, math.clamp(math.floor(tonumber(len) or (n - o)), 0, n - o) end local function parse(buf: buffer, o: number, l: number, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?) local ok, st, code, msg = pcall(Decode.parse, buf, o, o + l, opts, headerOnly) if not ok then return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st)) end if not st then return nil, Err.from(msg or "decode failed", o, code) end return st, nil end local function samplingOf(f: any): { { number } } local sampling = {} for _, c in f.comps do table.insert(sampling, { c.h, c.v }) end return sampling end function Jpeg.info(buf: buffer, off: number?, len: number?): (Info?, Err.Err?) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "expected a buffer") end local o, l = range(buf, off, len) local st, err = parse(buf, o, l, nil, true) if not st then return nil, err end local f = st.frame return { width = f.width, height = f.height, components = #f.comps, progressive = f.progressive, arithmetic = f.arithmetic, precision = f.precision, colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif), sampling = samplingOf(f), orientation = st.orientation, adobe = st.adobe, jfif = st.jfif, avi1 = st.avi1, }, nil end local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number) if o <= 1 or o > 8 then return px, w, h end local swap = o >= 5 local ow, oh = if swap then h else w, if swap then w else h local out = buffer.create(ow * oh * 4) local readu32, writeu32 = buffer.readu32, buffer.writeu32 for y = 0, oh - 1 do for x = 0, ow - 1 do local col, row if o == 2 then col, row = w - 1 - x, y elseif o == 3 then col, row = w - 1 - x, h - 1 - y elseif o == 4 then col, row = x, h - 1 - y elseif o == 5 then col, row = y, x elseif o == 6 then col, row = y, h - 1 - x elseif o == 7 then col, row = w - 1 - y, h - 1 - x else col, row = w - 1 - y, x end writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4)) end end return out, ow, oh end local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions?): (Types.Image?, any) local st, err = parse(buf, o, l, opts, false) if not st then return nil, err end local s = st :: Decode.State local img = Types.Image.new(0, 0) local space, mode = nil, nil if opts and opts.yuv then local ok, w, h, px, m = pcall(Decode.outputYuv, s) if not ok then return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) end if w then img.width, img.height, img.pixels, img.format = w, h :: number, px :: buffer, "yuv420p" mode = m space = Decode.colorSpaceOf(s.frame, s.adobe, s.jfif) end end if not mode then local ok, w, h, px, sp = pcall(Decode.output, s) if not ok then return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) end if not w then return nil, Err.from(px, o, h) end space = sp if opts and opts.orient then px, w, h = orient(px, w, h, s.orientation) end img.width, img.height, img.pixels = w, h, px if opts and opts.native and space == "gray" then local g = buffer.create(w * h) for i = 0, w * h - 1 do buffer.writeu8(g, i, buffer.readu8(px, i * 4)) end img.pixels, img.format = g, "gray8" end end local f = s.frame local meta = img.meta meta.orientation = s.orientation meta.oriented = (opts and opts.orient and not mode) or false meta.exif = s.exif meta.icc = s.icc if #s.comments > 0 then meta.text = { comment = table.concat(s.comments, "\n") } end if s.density and s.density.unit > 0 and s.density.x > 0 and s.density.y > 0 then local k = if s.density.unit == 2 then 2.54 else 1 meta.dpi = { x = s.density.x * k, y = s.density.y * k } end meta.truncated = s.truncated meta.source = { format = "jpeg", bitDepth = f.precision, colorType = space, components = #f.comps, progressive = f.progressive, arithmetic = f.arithmetic, sampling = samplingOf(f), scale = s.scale, adobe = s.adobe, jfif = s.jfif, avi1 = s.avi1, yuv = mode, range = if mode then "full" else nil, fields = 1, } return img, s end -- the start of a second JPEG: FF D8 FF local function nextSoi(buf: buffer, p: number, e: number): number local readu8 = buffer.readu8 while p + 3 <= e do if readu8(buf, p) == 0xFF and readu8(buf, p + 1) == 0xD8 and readu8(buf, p + 2) == 0xFF then return p end p += 1 end return -1 end local function weave(a: Types.Image, b: Types.Image): Types.Image local w, hf = a.width, a.height local h = hf * 2 local out = Types.Image.new(w, h, a.format) local dst = out.pixels if a.format == "yuv420p" then local cw, chf = (w + 1) // 2, (hf + 1) // 2 local ch = (h + 1) // 2 Yuv.weave(a.pixels, 0, b.pixels, 0, w, h, dst, 0) for k = 0, 1 do Yuv.weave(a.pixels, w * hf + k * cw * chf, b.pixels, w * hf + k * cw * chf, cw, ch, dst, w * h + k * cw * ch) end else local bpp = Types.Image.bpp(a.format) or 4 Yuv.weave(a.pixels, 0, b.pixels, 0, w * bpp, h, dst, 0) end out.meta = a.meta return out end function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOptions?): (Types.Image?, Err.Err?) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "expected a buffer") end if opts ~= nil and type(opts) ~= "table" then return nil, Err.new(Err.ARG, "options must be a table") end local o, l = range(buf, off, len) local img, st = decodeOne(buf, o, l, opts) if not img then return nil, st end local s = st :: Decode.State local wantFields = if opts and opts.fields ~= nil then opts.fields else (s.avi1 == 1 or s.avi1 == 2) if wantFields and not (opts and opts.orient) then local e = o + l local p = nextSoi(buf, s.endPos, e) if p >= 0 then local o2 = table.clone(opts or {}) :: any if o2.maxPixels then o2.maxPixels = math.max(0, o2.maxPixels - img.width * img.height) end local b = decodeOne(buf, p, e - p, o2) if b and b.width == img.width and b.height == img.height and b.format == img.format then local truncated = img.meta.truncated or b.meta.truncated img = weave(img, b) img.meta.truncated = truncated local source: any = img.meta.source source.fields = 2 end end end return img, nil end local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, yuv420p = 0 } function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then return nil, Err.new(Err.ARG, "needs an Image") end local bpp = BPP[img.format] if not bpp then return nil, Err.new(Err.ARG, "needs an rgba8, rgb8, gray8 or yuv420p Image (got " .. tostring(img.format) .. ")") end local w, h = img.width, img.height local need = if bpp == 0 then w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) else w * h * bpp if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < need then return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)") end if opts ~= nil and type(opts) ~= "table" then return nil, Err.new(Err.ARG, "options must be a table") end local o: any = opts or {} local quality = o.quality or 90 if type(quality) ~= "number" or quality < 1 or quality > 100 then return nil, Err.new(Err.ARG, "quality must be 1..100") end local sub = o.subsampling or "420" if sub ~= "420" and sub ~= "422" and sub ~= "444" then return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"") end if bpp == 0 then sub = "420" end local restart = o.restart or 0 if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs") end local gray = o.gray if gray == nil then gray = img.format == "gray8" end local segments = {} if o.segments ~= nil then if type(o.segments) ~= "table" then return nil, Err.new(Err.ARG, "segments must be a list of { marker, data }") end for _, sg in o.segments do if type(sg) ~= "table" or type(sg.data) ~= "buffer" or buffer.len(sg.data) > 65533 or type(sg.marker) ~= "number" then return nil, Err.new(Err.ARG, "bad segment (marker 0xE0..0xEF / 0xFE, at most 65533 bytes)") end if not ((sg.marker >= 0xE0 and sg.marker <= 0xEF) or sg.marker == 0xFE) then return nil, Err.new(Err.ARG, "bad segment marker (0xE0..0xEF / 0xFE)") end table.insert(segments, sg) end end local density = o.density if density ~= nil then if type(density) ~= "table" or type(density.unit) ~= "number" or type(density.x) ~= "number" or type(density.y) ~= "number" then return nil, Err.new(Err.ARG, "bad density") end density = { unit = math.clamp(math.floor(density.unit), 0, 2), x = math.clamp(math.floor(density.x), 1, 65535), y = math.clamp(math.floor(density.y), 1, 65535), } end local out = Encode.run(img.pixels, w, h, bpp, { quality = quality, sampling = sub, progressive = o.progressive == true, optimize = o.optimize == true, gray = gray, restart = restart, segments = segments, jfif = o.jfif ~= false, density = density, }) return out, nil end return Jpeg end __FILES["codecs/image/Jpeg/Arith"] = @native function() -- codecs/image/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive). -- A Luau translation of libjpeg-turbo's jdarith.c / jaricom.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md); past the -- end of a restart segment it reads zero bytes, as libjpeg does. Bins: DC [t * 64], AC [256 + t * 256], fixed 0.5 [1280]. local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16 local band, bxor = bit32.band, bit32.bxor local Arith = {} -- jaricom.c: Qe << 16 | Next_Index_MPS << 8 | Switch_MPS << 7 | Next_Index_LPS local TAB = buffer.create(114 * 4) do local raw = { { 0x5a1d, 1, 1, 1 }, { 0x2586, 14, 2, 0 }, { 0x1114, 16, 3, 0 }, { 0x080b, 18, 4, 0 }, { 0x03d8, 20, 5, 0 }, { 0x01da, 23, 6, 0 }, { 0x00e5, 25, 7, 0 }, { 0x006f, 28, 8, 0 }, { 0x0036, 30, 9, 0 }, { 0x001a, 33, 10, 0 }, { 0x000d, 35, 11, 0 }, { 0x0006, 9, 12, 0 }, { 0x0003, 10, 13, 0 }, { 0x0001, 12, 13, 0 }, { 0x5a7f, 15, 15, 1 }, { 0x3f25, 36, 16, 0 }, { 0x2cf2, 38, 17, 0 }, { 0x207c, 39, 18, 0 }, { 0x17b9, 40, 19, 0 }, { 0x1182, 42, 20, 0 }, { 0x0cef, 43, 21, 0 }, { 0x09a1, 45, 22, 0 }, { 0x072f, 46, 23, 0 }, { 0x055c, 48, 24, 0 }, { 0x0406, 49, 25, 0 }, { 0x0303, 51, 26, 0 }, { 0x0240, 52, 27, 0 }, { 0x01b1, 54, 28, 0 }, { 0x0144, 56, 29, 0 }, { 0x00f5, 57, 30, 0 }, { 0x00b7, 59, 31, 0 }, { 0x008a, 60, 32, 0 }, { 0x0068, 62, 33, 0 }, { 0x004e, 63, 34, 0 }, { 0x003b, 32, 35, 0 }, { 0x002c, 33, 9, 0 }, { 0x5ae1, 37, 37, 1 }, { 0x484c, 64, 38, 0 }, { 0x3a0d, 65, 39, 0 }, { 0x2ef1, 67, 40, 0 }, { 0x261f, 68, 41, 0 }, { 0x1f33, 69, 42, 0 }, { 0x19a8, 70, 43, 0 }, { 0x1518, 72, 44, 0 }, { 0x1177, 73, 45, 0 }, { 0x0e74, 74, 46, 0 }, { 0x0bfb, 75, 47, 0 }, { 0x09f8, 77, 48, 0 }, { 0x0861, 78, 49, 0 }, { 0x0706, 79, 50, 0 }, { 0x05cd, 48, 51, 0 }, { 0x04de, 50, 52, 0 }, { 0x040f, 50, 53, 0 }, { 0x0363, 51, 54, 0 }, { 0x02d4, 52, 55, 0 }, { 0x025c, 53, 56, 0 }, { 0x01f8, 54, 57, 0 }, { 0x01a4, 55, 58, 0 }, { 0x0160, 56, 59, 0 }, { 0x0125, 57, 60, 0 }, { 0x00f6, 58, 61, 0 }, { 0x00cb, 59, 62, 0 }, { 0x00ab, 61, 63, 0 }, { 0x008f, 61, 32, 0 }, { 0x5b12, 65, 65, 1 }, { 0x4d04, 80, 66, 0 }, { 0x412c, 81, 67, 0 }, { 0x37d8, 82, 68, 0 }, { 0x2fe8, 83, 69, 0 }, { 0x293c, 84, 70, 0 }, { 0x2379, 86, 71, 0 }, { 0x1edf, 87, 72, 0 }, { 0x1aa9, 87, 73, 0 }, { 0x174e, 72, 74, 0 }, { 0x1424, 72, 75, 0 }, { 0x119c, 74, 76, 0 }, { 0x0f6b, 74, 77, 0 }, { 0x0d51, 75, 78, 0 }, { 0x0bb6, 77, 79, 0 }, { 0x0a40, 77, 48, 0 }, { 0x5832, 80, 81, 1 }, { 0x4d1c, 88, 82, 0 }, { 0x438e, 89, 83, 0 }, { 0x3bdd, 90, 84, 0 }, { 0x34ee, 91, 85, 0 }, { 0x2eae, 92, 86, 0 }, { 0x299a, 93, 87, 0 }, { 0x2516, 86, 71, 0 }, { 0x5570, 88, 89, 1 }, { 0x4ca9, 95, 90, 0 }, { 0x44d9, 96, 91, 0 }, { 0x3e22, 97, 92, 0 }, { 0x3824, 99, 93, 0 }, { 0x32b4, 99, 94, 0 }, { 0x2e17, 93, 86, 0 }, { 0x56a8, 95, 96, 1 }, { 0x4f46, 101, 97, 0 }, { 0x47e5, 102, 98, 0 }, { 0x41cf, 103, 99, 0 }, { 0x3c3d, 104, 100, 0 }, { 0x375e, 99, 93, 0 }, { 0x5231, 105, 102, 0 }, { 0x4c0f, 106, 103, 0 }, { 0x4639, 107, 104, 0 }, { 0x415e, 103, 99, 0 }, { 0x5627, 105, 106, 1 }, { 0x50e7, 108, 107, 0 }, { 0x4b85, 109, 103, 0 }, { 0x5597, 110, 109, 0 }, { 0x504f, 111, 107, 0 }, { 0x5a10, 110, 111, 1 }, { 0x5522, 112, 109, 0 }, { 0x59eb, 112, 111, 1 }, { 0x5a1d, 113, 113, 0 }, } for i, e in raw do buffer.writeu16(TAB, (i - 1) * 4, e[1]) -- Qe writeu8(TAB, (i - 1) * 4 + 2, e[4] * 128 + e[2]) -- Switch_MPS << 7 | Next_Index_LPS writeu8(TAB, (i - 1) * 4 + 3, e[3]) -- Next_Index_MPS end end local ZZ: buffer = buffer.create(80) local STATS = 1281 local POW2 = buffer.create(8) for i = 0, 7 do writeu8(POW2, i, 2 ^ i) end local FIXED = 1280 local D: buffer = buffer.create(0) local P = 0 local SEGEND = 0 local OVER = 0 local C, A, CT = 0, 0, -16 local st: buffer = buffer.create(STATS) @native local function decode(s: number): number while A < 0x8000 do CT -= 1 if CT < 0 then local data = 0 if P < SEGEND then data = readu8(D, P) P += 1 else OVER += 1 end C = C * 256 + data CT += 8 if CT < 0 then CT += 1 if CT == 0 then A = 0x8000 end end end A *= 2 end local sv = readu8(st, s) local t = band(sv, 0x7F) * 4 local qe = buffer.readu16(TAB, t) local nl = readu8(TAB, t + 2) local nm = readu8(TAB, t + 3) local temp = A - qe A = temp temp *= readu8(POW2, CT) if C >= temp then C -= temp if A < qe then A = qe writeu8(st, s, bxor(band(sv, 0x80), nm)) else A = qe writeu8(st, s, bxor(band(sv, 0x80), nl)) sv = bxor(sv, 0x80) end elseif A < 0x8000 then if A < qe then writeu8(st, s, bxor(band(sv, 0x80), nl)) sv = bxor(sv, 0x80) else writeu8(st, s, bxor(band(sv, 0x80), nm)) end end return if sv >= 0x80 then 1 else 0 end @native local function i16(v: number): number v = band(v, 0xFFFF) return if v >= 0x8000 then v - 0x10000 else v end type ArithComp = { coef: buffer, bpl: number, h: number, v: number, bw: number, bh: number, dcTbl: number, acTbl: number, pred: number, ctx: number, } type ArithParams = { comps: { ArithComp }, mcusX: number, mcusY: number, ri: number, mode: number, ss: number, se: number, al: number, dcL: { number }, dcU: { number }, acK: { number }, } -- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24) @native local function dcDiff(c: ArithComp, L: number, U: number): number? local base = c.dcTbl * 64 local s = base + c.ctx if decode(s) == 0 then c.ctx = 0 return c.pred end local sign = decode(s + 1) s = s + 2 + sign local m = decode(s) if m ~= 0 then s = base + 20 while decode(s) ~= 0 do m *= 2 if m == 0x8000 then return nil end s += 1 end end if m < 2 ^ L // 2 then c.ctx = 0 elseif m > 2 ^ U // 2 then c.ctx = 12 + sign * 4 else c.ctx = 4 + sign * 4 end local v = m s += 14 m = m // 2 while m > 0 do if decode(s) ~= 0 then v += m end m = m // 2 end v += 1 if sign ~= 0 then v = -v end return band(c.pred + v, 0xFFFF) end -- AC coefficients k = ss..se of one block (figure F.20) @native local function acFirst(coef: buffer, off: number, tbl: number, ss: number, se: number, K: number, mul: number): boolean local base = 256 + tbl * 256 local k = ss while k <= se do local s = base + 3 * (k - 1) if decode(s) ~= 0 then break -- EOB end while decode(s + 1) == 0 do s += 3 k += 1 if k > se then return false end end local sign = decode(FIXED) s += 2 local m = decode(s) if m ~= 0 then if decode(s) ~= 0 then m *= 2 s = base + (if k <= K then 189 else 217) while decode(s) ~= 0 do m *= 2 if m == 0x8000 then return false end s += 1 end end end local v = m s += 14 m = m // 2 while m > 0 do if decode(s) ~= 0 then v += m end m = m // 2 end v += 1 if sign ~= 0 then v = -v end writei16(coef, off + readu8(ZZ, k) * 2, i16(v * mul)) k += 1 end return true end @native local function acRefine(coef: buffer, off: number, tbl: number, ss: number, se: number, al: number): boolean local base = 256 + tbl * 256 local p1 = 2 ^ al local m1 = -p1 local kex = se while kex > 0 do if readi16(coef, off + readu8(ZZ, kex) * 2) ~= 0 then break end kex -= 1 end local k = ss while k <= se do local s = base + 3 * (k - 1) if k > kex then if decode(s) ~= 0 then break end end while true do local o = off + readu8(ZZ, k) * 2 local cv = readi16(coef, o) if cv ~= 0 then if decode(s + 2) ~= 0 then writei16(coef, o, i16(if cv < 0 then cv + m1 else cv + p1)) end break end if decode(s + 1) ~= 0 then writei16(coef, o, i16(if decode(FIXED) ~= 0 then m1 else p1)) break end s += 3 k += 1 if k > se then return false end end k += 1 end return true end @native function Arith.init(zigzag: buffer) ZZ = zigzag end @native function Arith.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, Pm: ArithParams): boolean local comps = Pm.comps local nc = #comps local mode, ss, se, al, ri = Pm.mode, Pm.ss, Pm.se, Pm.al, Pm.ri local units, ux if nc == 1 then ux = comps[1].bw units = ux * comps[1].bh else ux = Pm.mcusX units = ux * Pm.mcusY end local resetDc = mode == 0 or mode == 1 local resetAc = mode == 0 or mode == 3 or mode == 4 @native local function reset() for i = 1, nc do local c = comps[i] if resetDc then buffer.fill(st, c.dcTbl * 64, 0, 64) c.pred = 0 c.ctx = 0 end if resetAc then buffer.fill(st, 256 + c.acTbl * 256, 0, 256) end end C, A, CT = 0, 0, -16 end D = d P = 0 SEGEND = if nrst >= 1 then math.min(rst[1], cleanLen) else cleanLen OVER = 0 writeu8(st, FIXED, 113) reset() local rstIdx = 0 local bad = false local truncated = false local mul = 2 ^ al for u = 0, units - 1 do if ri > 0 and u > 0 and u % ri == 0 then rstIdx += 1 if rstIdx <= nrst then P = math.min(rst[rstIdx], cleanLen) SEGEND = if rstIdx + 1 <= nrst then math.min(rst[rstIdx + 1], cleanLen) else cleanLen bad = false else truncated = true break end reset() end if not bad then local my, mx = u // ux, u % ux for ci = 1, nc do local c = comps[ci] local bh, bw, by0, bx0 if nc == 1 then bh, bw, by0, bx0 = 1, 1, my, mx else bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h end local coef, bpl = c.coef, c.bpl for by = by0, by0 + bh - 1 do for bx = bx0, bx0 + bw - 1 do local off = (by * bpl + bx) * 128 if mode == 0 then local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1]) if not pred then bad = true else c.pred = pred writei16(coef, off, i16(pred)) if not acFirst(coef, off, c.acTbl, 1, 63, Pm.acK[c.acTbl + 1], 1) then bad = true end end elseif mode == 1 then local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1]) if not pred then bad = true else c.pred = pred writei16(coef, off, i16(pred * mul)) end elseif mode == 2 then if decode(FIXED) ~= 0 then local cv = readi16(coef, off) if band(cv, mul) == 0 then writei16(coef, off, i16(cv + mul)) end end elseif mode == 3 then if not acFirst(coef, off, c.acTbl, ss, se, Pm.acK[c.acTbl + 1], mul) then bad = true end else if not acRefine(coef, off, c.acTbl, ss, se, al) then bad = true end end if bad then break end end if bad then break end end if bad then break end end end end D = buffer.create(0) return truncated end return Arith end __FILES["codecs/image/Jpeg/Color"] = @native function() -- codecs/image/Jpeg/Color: chroma upsampling (libjpeg-turbo jdsample.c: fancy H2V1 / H2V2 / H1V2, else replicate) and -- colour conversion (jdcolor.c; YCCK = Adobe inverted CMYK), matching djpeg's defaults. From jpeg-luau 1.0, a Luau -- translation of libjpeg-turbo (IJG licence: licenses/libjpeg-turbo-LICENSE.md). local readu16, readi32, readu8, writeu16, writeu32 = buffer.readu16, buffer.readi32, buffer.readu8, buffer.writeu16, buffer.writeu32 local clamp, min, max = math.clamp, math.min, math.max local Color = {} Color.FULL = 0 Color.REPLICATE = 1 Color.H2V1 = 2 Color.H2V2 = 3 Color.H1V2 = 4 Color.GRAY = 0 Color.YCC = 1 Color.RGB = 2 Color.CMYK = 3 Color.YCCK = 4 Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted Color.RAW = 6 type Comp = { plane: buffer, stride: number, rows: number, downW: number, downH: number, method: number, hIn: number, hOut: number, vIn: number, vOut: number, row: buffer, } type Params = { comps: { Comp }, space: number, outW: number, outH: number, maxv: number, pixels: buffer, crr: buffer, cbb: buffer, crg: buffer, cbg: buffer, toByte: buffer?, hook: (() -> ())?, } -- jdcolor.c build_ycc_rgb_table @native function Color.tables(maxv: number): (buffer, buffer, buffer, buffer) local n = maxv + 1 local center = n // 2 local crr, cbb, crg, cbg = buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4) @native local function fix(x: number): number return math.floor(x * 65536 + 0.5) end for i = 0, maxv do local x = i - center buffer.writei32(crr, i * 4, (fix(1.40200) * x + 32768) // 65536) buffer.writei32(cbb, i * 4, (fix(1.77200) * x + 32768) // 65536) buffer.writei32(crg, i * 4, -fix(0.71414) * x) buffer.writei32(cbg, i * 4, -fix(0.34414) * x + 32768) end return crr, cbb, crg, cbg end @native local function fetch(c: Comp, y: number, outW: number): (buffer, number) local method = c.method local plane, stride, row = c.plane, c.stride, c.row if method == 0 then return plane, min(y, c.rows - 1) * stride * 2 elseif method == 2 then local w = c.downW local b = min(y, c.rows - 1) * stride * 2 local cur = readu16(plane, b) writeu16(row, 0, cur) local nxt = readu16(plane, b + 2) writeu16(row, 2, (cur * 3 + nxt + 2) // 4) local prev = cur cur = nxt for i = 1, w - 2 do nxt = readu16(plane, b + (i + 1) * 2) local v3 = cur * 3 writeu16(row, i * 4, (v3 + prev + 1) // 4) writeu16(row, i * 4 + 2, (v3 + nxt + 2) // 4) prev = cur cur = nxt end writeu16(row, (w - 1) * 4, (cur * 3 + prev + 1) // 4) writeu16(row, (w - 1) * 4 + 2, cur) return row, 0 elseif method == 3 then local w = c.downW local iy = min(y // 2, c.downH - 1) local oy = if y % 2 == 0 then max(iy - 1, 0) else min(iy + 1, c.downH - 1) local b0, b1 = iy * stride * 2, oy * stride * 2 local this = readu16(plane, b0) * 3 + readu16(plane, b1) local nxt = readu16(plane, b0 + 2) * 3 + readu16(plane, b1 + 2) writeu16(row, 0, (this * 4 + 8) // 16) writeu16(row, 2, (this * 3 + nxt + 7) // 16) local last = this this = nxt for i = 1, w - 2 do nxt = readu16(plane, b0 + (i + 1) * 2) * 3 + readu16(plane, b1 + (i + 1) * 2) local t3 = this * 3 writeu16(row, i * 4, (t3 + last + 8) // 16) writeu16(row, i * 4 + 2, (t3 + nxt + 7) // 16) last = this this = nxt end writeu16(row, (w - 1) * 4, (this * 3 + last + 8) // 16) writeu16(row, (w - 1) * 4 + 2, (this * 4 + 7) // 16) return row, 0 elseif method == 4 then local iy = min(y // 2, c.downH - 1) local oy, bias if y % 2 == 0 then oy, bias = max(iy - 1, 0), 1 else oy, bias = min(iy + 1, c.downH - 1), 2 end local b0, b1 = iy * stride * 2, oy * stride * 2 for x = 0, outW - 1 do writeu16(row, x * 2, (readu16(plane, b0 + x * 2) * 3 + readu16(plane, b1 + x * 2) + bias) // 4) end return row, 0 else local hIn, hOut = c.hIn, c.hOut local iy = min((y * c.vIn) // c.vOut, c.rows - 1) local b = iy * stride * 2 local last = stride - 1 for x = 0, outW - 1 do writeu16(row, x * 2, readu16(plane, b + min((x * hIn) // hOut, last) * 2)) end return row, 0 end end @native function Color.run(P: Params) local comps = P.comps local nc = #comps local space, outW, outH, maxv, out = P.space, P.outW, P.outH, P.maxv, P.pixels local crr, cbb, crg, cbg = P.crr, P.cbb, P.crg, P.cbg local toByte = P.toByte local o = 0 local hook = P.hook for y = 0, outH - 1 do if hook and y > 0 and y % 8 == 0 then pcall(hook) end local s0, b0 = fetch(comps[1], y, outW) if space == 0 or nc < 3 then for x = 0, outW - 1 do local v = readu16(s0, b0 + x * 2) if toByte then v = readu8(toByte, v) end writeu32(out, o, 0xFF000000 + v * 0x10101) o += 4 end else local s1, b1 = fetch(comps[2], y, outW) local s2, b2 = fetch(comps[3], y, outW) local s3, b3 = s0, b0 if nc >= 4 then s3, b3 = fetch(comps[4], y, outW) end if space == 6 then for x = 0, outW - 1 do local i = x * 2 local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) local c3 = if nc >= 4 then readu16(s3, b3 + i) else maxv if toByte then c0, c1, c2, c3 = readu8(toByte, c0), readu8(toByte, c1), readu8(toByte, c2), readu8(toByte, c3) end writeu32(out, o, c0 + c1 * 256 + c2 * 65536 + c3 * 16777216) o += 4 end continue end if space == 1 and not toByte then for x = 0, outW - 1 do local i = x * 2 local yv, cb, cr = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) local r = clamp(yv + readi32(crr, cr * 4), 0, 255) local g = clamp(yv + (readi32(cbg, cb * 4) + readi32(crg, cr * 4)) // 65536, 0, 255) local b = clamp(yv + readi32(cbb, cb * 4), 0, 255) writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536) o += 4 end continue end for x = 0, outW - 1 do local i = x * 2 local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) local r, g, b if space == 2 then r, g, b = c0, c1, c2 elseif space == 3 or space == 5 then local k = readu16(s3, b3 + i) if space == 5 then c0, c1, c2, k = maxv - c0, maxv - c1, maxv - c2, maxv - k end r = (c0 * k + maxv // 2) // maxv g = (c1 * k + maxv // 2) // maxv b = (c2 * k + maxv // 2) // maxv else r = clamp(c0 + readi32(crr, c2 * 4), 0, maxv) g = clamp(c0 + (readi32(cbg, c1 * 4) + readi32(crg, c2 * 4)) // 65536, 0, maxv) b = clamp(c0 + readi32(cbb, c1 * 4), 0, maxv) if space == 4 then -- YCCK: the YCC part decodes to inverted C, M, Y (libjpeg ycck_cmyk_convert), K as stored local k = readu16(s3, b3 + i) r = ((maxv - r) * k + maxv // 2) // maxv g = ((maxv - g) * k + maxv // 2) // maxv b = ((maxv - b) * k + maxv // 2) // maxv end end if toByte then r, g, b = readu8(toByte, r), readu8(toByte, g), readu8(toByte, b) end writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536) o += 4 end end end end return Color end __FILES["codecs/image/Jpeg/Decode"] = function() -- codecs/image/Jpeg/Decode: the JPEG marker parser and output stage (it validates everything the native loops index). -- From jpeg-luau 1.0 (same author), extended with SOF9 / SOF10 / DAC, EXIF / ICC / AVI1 segments and yuv420p output; -- the IDCT size choice for scaled decodes follows libjpeg-turbo's jdmaster.c. local Scan = __include("codecs/image/Jpeg/Scan") local Arith = __include("codecs/image/Jpeg/Arith") local Color = __include("codecs/image/Jpeg/Color") local Tables = __include("codecs/image/Jpeg/Tables") local Yuv = __include("codecs/image/Jpeg/Yuv") local Dct = __include("codecs/image/Dct") local readu8 = buffer.readu8 local band, rshift = bit32.band, bit32.rshift local Decode = {} Arith.init(Scan.ZIGZAG) local function be16(b: buffer, p: number): number return readu8(b, p) * 256 + readu8(b, p + 1) end local stdBuilt: { [string]: buffer } = {} local function stdTable(class: string, slot: number): buffer? local key = class .. slot if not stdBuilt[key] then local def = (if class == "dc" then Tables.DC else Tables.AC)[slot + 1] if not def then return nil end stdBuilt[key] = Scan.buildTable(def.counts, def.symbols) end return stdBuilt[key] end -- the EXIF TIFF block (after "Exif\0\0") and its orientation tag local function exif(b: buffer, p: number, e: number): (number?, number?) if e - p < 14 or buffer.readstring(b, p, 6) ~= "Exif\0\0" then return nil, nil end local t = p + 6 local le local bo = buffer.readstring(b, t, 2) if bo == "II" then le = true elseif bo == "MM" then le = false else return nil, nil end local function r16(at: number): number if le then return readu8(b, at) + readu8(b, at + 1) * 256 end return readu8(b, at) * 256 + readu8(b, at + 1) end local function r32(at: number): number if le then return r16(at) + r16(at + 2) * 65536 end return r16(at) * 65536 + r16(at + 2) end local ifd = t + r32(t + 4) if ifd + 2 > e then return t, nil end local count = r16(ifd) for i = 0, count - 1 do local en = ifd + 2 + i * 12 if en + 12 > e then return t, nil end if r16(en) == 0x0112 then local v = r16(en + 8) return t, if v >= 1 and v <= 8 then v else nil end end return t, nil end type Comp = { id: number, h: number, v: number, tq: number, bpl: number, bpc: number, bw: number, bh: number, coef: buffer?, quant: buffer?, dct: buffer?, act: buffer?, dcTbl: number, acTbl: number, pred: number, ctx: number, } type Frame = { width: number, height: number, precision: number, progressive: boolean, arithmetic: boolean, comps: { Comp }, hmax: number, vmax: number, mcusX: number, mcusY: number, } local SOF_REFUSED = { [0xC3] = "lossless", [0xC5] = "hierarchical", [0xC6] = "hierarchical", [0xC7] = "hierarchical", [0xCB] = "lossless arithmetic-coded", [0xCD] = "hierarchical arithmetic-coded", [0xCE] = "hierarchical arithmetic-coded", [0xCF] = "hierarchical arithmetic-coded", } local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, string?, string?) if e - p < 6 then return nil, "corrupt", "short SOF" end local prec = readu8(b, p) local height, width, nf = be16(b, p + 1), be16(b, p + 3), readu8(b, p + 5) if prec ~= 8 and prec ~= 12 then return nil, "unsupported", "sample precision " .. prec end if width == 0 or height == 0 then if height == 0 and width > 0 then return nil, "unsupported", "DNL (height 0 in the frame header)" end return nil, "corrupt", "bad size " .. width .. "x" .. height end if nf ~= 1 and nf ~= 3 and nf ~= 4 then return nil, "unsupported", "component count " .. nf end if e - p < 6 + nf * 3 then return nil, "corrupt", "short SOF" end local comps: { Comp } = {} local hmax, vmax = 1, 1 for i = 0, nf - 1 do local q = p + 6 + i * 3 local hv = readu8(b, q + 1) local h, v, tq = rshift(hv, 4), band(hv, 15), readu8(b, q + 2) :: number if h < 1 or h > 4 or v < 1 or v > 4 then return nil, "corrupt", "bad sampling factors " .. h .. "x" .. v end if tq > 3 then return nil, "corrupt", "bad quantisation table selector " .. tq end local id = readu8(b, q) for _, c in comps do if c.id == id then return nil, "corrupt", "duplicate component id " .. id end end hmax, vmax = math.max(hmax, h), math.max(vmax, v) :: number table.insert(comps, { id = id, h = h, v = v, tq = tq, bpl = 0, bpc = 0, bw = 0, bh = 0, dcTbl = 0, acTbl = 0, pred = 0, ctx = 0 } :: Comp) end local mcusX = math.ceil(width / (8 * hmax)) local mcusY = math.ceil(height / (8 * vmax)) for _, c in comps do c.bpl = mcusX * c.h c.bpc = mcusY * c.v c.bw = math.ceil(math.ceil(width * c.h / hmax) / 8) c.bh = math.ceil(math.ceil(height * c.v / vmax) / 8) end return { width = width, height = height, precision = prec, progressive = m == 0xC2 or m == 0xCA, arithmetic = m == 0xC9 or m == 0xCA, comps = comps, hmax = hmax, vmax = vmax, mcusX = mcusX, mcusY = mcusY, }, nil, nil end local function colorSpaceOf(frame: Frame, adobe: number?, jfif: boolean): string local n = #frame.comps if n == 1 then return "gray" elseif n == 3 then if adobe ~= nil then return if adobe == 0 then "rgb" else "ycbcr" end local c = frame.comps if not jfif and c[1].id == 82 and c[2].id == 71 and c[3].id == 66 then return "rgb" end return "ycbcr" end return if adobe == 2 then "ycck" else "cmyk" end Decode.colorSpaceOf = colorSpaceOf -- The IDCT size (8, 4, 2 or 1) for a component at a scale. libjpeg-turbo scales chroma up through a bigger IDCT -- instead of upsampling it, when the sampling ratios allow (jdmaster.c jpeg_calc_output_dimensions). local function idctSize(f: Frame, c: Comp, scale: number): number local minSize = 8 // scale local ssize = minSize while ssize < 8 and (f.hmax * minSize) % (c.h * ssize * 2) == 0 and (f.vmax * minSize) % (c.v * ssize * 2) == 0 do ssize *= 2 end return ssize end type State = { frame: any, adobe: number?, jfif: boolean, density: { unit: number, x: number, y: number }?, orientation: number, exif: buffer?, icc: buffer?, comments: { string }, truncated: boolean, raw: boolean, scale: number, avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back) endPos: number, hook: (() -> ())?, } function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: boolean): (State?, string?, string?) if n - base < 4 or readu8(b, base) ~= 0xFF or readu8(b, base + 1) ~= 0xD8 then return nil, "corrupt", "not a JPEG file (no SOI marker)" end local scale = (opts and opts.scale) or 1 if scale ~= 1 and scale ~= 2 and scale ~= 4 and scale ~= 8 then return nil, "arg", "scale must be 1, 2, 4 or 8" end local maxPixels: number = (opts and opts.maxPixels) or 2 ^ 26 local quant: { [number]: buffer } = {} local dcT: { [number]: buffer } = {} local acT: { [number]: buffer } = {} local dcL, dcU, acK = { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 5, 5, 5, 5 } local frame: Frame? = nil local st: State = { frame = nil, adobe = nil, jfif = false, density = nil, orientation = 1, exif = nil, icc = nil, comments = {}, truncated = false, raw = opts ~= nil and opts.raw == true, scale = scale, avi1 = nil, endPos = n, hook = if opts and type(opts.yield) == "function" then opts.yield else nil, } local iccChunks: { buffer } = {} local ri = 0 local scans = 0 local clean: buffer? = nil local rst = {} local pos = base + 2 while pos < n do -- find the next marker (tolerate garbage and fill bytes) if readu8(b, pos) ~= 0xFF then pos += 1 continue end while pos < n and readu8(b, pos) == 0xFF do pos += 1 end if pos >= n then break end local m = readu8(b, pos) pos += 1 if m == 0xD9 then st.endPos = pos break -- EOI elseif m == 0 or m == 0x01 or m == 0xD8 or (m >= 0xD0 and m <= 0xD7) then continue -- standalone markers (or stray stuffing) end if pos + 2 > n then st.truncated = true break end local len = be16(b, pos) if len < 2 then return nil, "corrupt", string.format("bad segment length for marker %02X", m) end local p, e = pos + 2, pos + len if e > n then if m == 0xDA and frame and not headerOnly then e = n -- a truncated SOS header still fails below else st.truncated = true break end end pos = e if m == 0xE0 then if e - p >= 12 and buffer.readstring(b, p, 5) == "JFIF\0" then st.jfif = true st.density = { unit = readu8(b, p + 7), x = be16(b, p + 8), y = be16(b, p + 10) } elseif e - p >= 5 and buffer.readstring(b, p, 4) == "AVI1" then st.avi1 = readu8(b, p + 4) end elseif m == 0xE1 then local t, o = exif(b, p, e) if t and not st.exif then local x = buffer.create(e - t) buffer.copy(x, 0, b, t, e - t) st.exif = x end if o then st.orientation = o end elseif m == 0xE2 then -- ICC_PROFILE\0, sequence number, count, data if e - p >= 14 and buffer.readstring(b, p, 12) == "ICC_PROFILE\0" then local seq = readu8(b, p + 12) local x = buffer.create(e - p - 14) buffer.copy(x, 0, b, p + 14, e - p - 14) if seq >= 1 then iccChunks[seq] = x end end elseif m == 0xEE then if e - p >= 12 and buffer.readstring(b, p, 5) == "Adobe" then st.adobe = readu8(b, p + 11) end elseif m == 0xFE then table.insert(st.comments, buffer.readstring(b, p, e - p)) elseif m == 0xDB then -- DQT while p < e do local pt = readu8(b, p) local pq, tq = rshift(pt, 4), band(pt, 15) local size = if pq == 0 then 64 else 128 if tq > 3 or pq > 1 or p + 1 + size > e then return nil, "corrupt", "bad DQT segment" end local q = buffer.create(128) for k = 0, 63 do local v = if pq == 0 then readu8(b, p + 1 + k) else be16(b, p + 1 + k * 2) buffer.writeu16(q, readu8(Scan.ZIGZAG, k) * 2, v) end quant[tq] = q p += 1 + size end elseif m == 0xC4 then -- DHT while p < e do if p + 17 > e then return nil, "corrupt", "bad DHT segment" end local tc = readu8(b, p) local class, slot = rshift(tc, 4), band(tc, 15) if class > 1 or slot > 3 then return nil, "corrupt", "bad DHT table class / slot" end local counts, total = {}, 0 for l = 1, 16 do counts[l] = readu8(b, p + l) total += counts[l] end if total > 256 or p + 17 + total > e then return nil, "corrupt", "bad DHT segment" end local syms = {} for i = 1, total do syms[i] = readu8(b, p + 16 + i) end local t = Scan.buildTable(counts, syms) if class == 0 then dcT[slot] = t else acT[slot] = t end p += 17 + total end elseif m == 0xCC then -- DAC: arithmetic conditioning while p + 2 <= e do local tc, v = readu8(b, p), readu8(b, p + 1) local class, slot = rshift(tc, 4), band(tc, 15) if class > 1 or slot > 3 then return nil, "corrupt", "bad DAC segment" end if class == 0 then local L, U = band(v, 15), rshift(v, 4) if L > U then return nil, "corrupt", "bad DAC value" end dcL[slot + 1], dcU[slot + 1] = L, U else if v < 1 or v > 63 then return nil, "corrupt", "bad DAC value" end acK[slot + 1] = v end p += 2 end elseif m == 0xDD then if e - p < 2 then return nil, "corrupt", "bad DRI segment" end ri = be16(b, p) elseif m == 0xC0 or m == 0xC1 or m == 0xC2 or m == 0xC9 or m == 0xCA then if frame then return nil, "corrupt", "more than one frame header" end local f, code, err = parseSof(b, p, e, m) if not f then return nil, code, err end if f.width * f.height > maxPixels then return nil, "limit", string.format("%d x %d is over the %d pixel limit", f.width, f.height, maxPixels) end frame = f st.frame = f if headerOnly then return st, nil, nil end elseif SOF_REFUSED[m] then return nil, "unsupported", SOF_REFUSED[m] .. " JPEG" elseif m == 0xDA then if headerOnly then break end if not frame then return nil, "corrupt", "scan before the frame header" end local f = frame :: Frame local ns = if p < e then readu8(b, p) else 0 if ns < 1 or ns > 4 or e - p < 4 + ns * 2 then return nil, "corrupt", "bad SOS segment" end local sc: { Comp } = {} local blocks = 0 for i = 0, ns - 1 do local id, t = readu8(b, p + 1 + i * 2), readu8(b, p + 2 + i * 2) local comp = nil for _, c in f.comps do if c.id == id then comp = c end end if not comp or table.find(sc, comp) then return nil, "corrupt", "scan names an unknown component " .. id end local td, ta = rshift(t, 4), band(t, 15) if td > 3 or ta > 3 then return nil, "corrupt", "bad entropy table selector" end comp.dcTbl, comp.acTbl = td, ta if not f.arithmetic then comp.dct = dcT[td] or stdTable("dc", td) comp.act = acT[ta] or stdTable("ac", ta) end blocks += comp.h * comp.v table.insert(sc, comp) end local q = p + 1 + ns * 2 local ss, se, a = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2) local ah, al = rshift(a, 4), band(a, 15) if ns > 1 and blocks > 10 then return nil, "corrupt", "more than 10 blocks per MCU" end local mode if not f.progressive then mode = 0 ss, se, ah, al = 0, 63, 0, 0 else if se > 63 or ss > se or ah > 13 or al > 13 or (ss == 0 and se ~= 0) or (ss > 0 and ns ~= 1) then return nil, "corrupt", "bad progressive scan parameters" end if ss == 0 then mode = if ah == 0 then 1 else 2 else mode = if ah == 0 then 3 else 4 end end for _, c in sc do if not f.arithmetic then if (mode == 0 or mode == 1) and not c.dct then return nil, "corrupt", "missing DC Huffman table" end if (mode == 0 or mode == 3 or mode == 4) and not c.act then return nil, "corrupt", "missing AC Huffman table" end end if not c.coef then c.coef = buffer.create(c.bpl * c.bpc * 128) end if not c.quant then c.quant = quant[c.tq] end end if not clean then clean = buffer.create(n - base + Scan.PAD) end local cb = clean :: buffer local nextPos, cleanLen, nrst = Scan.destuff(b, pos, n, cb, rst) if nextPos >= n then st.truncated = true -- no EOI end -- a component decoded through the 1x1 IDCT only needs its DC coefficient: skip its AC scans if not (mode >= 3 and idctSize(f, sc[1], scale) == 1) then local params = { comps = sc :: any, mcusX = f.mcusX, mcusY = f.mcusY, ri = ri, mode = mode, ss = ss, se = se, al = al, hook = st.hook, dcL = dcL, dcU = dcU, acK = acK, } local short if f.arithmetic then short = Arith.run(cb, cleanLen, rst, nrst, params) else local _ _, short = Scan.run(cb, cleanLen, rst, nrst, params) end st.truncated = st.truncated or short end scans += 1 pos = nextPos end end if not frame then return nil, if st.truncated then "truncated" else "corrupt", "no frame header" end if #iccChunks > 0 then local total = 0 for _, c in iccChunks do total += buffer.len(c) end local icc = buffer.create(total) local o = 0 for _, c in iccChunks do buffer.copy(icc, o, c) o += buffer.len(c) end st.icc = icc end if headerOnly then return st, nil, nil end if scans == 0 then return nil, "truncated", "no image data" end return st, nil, nil end local SPACE_IDS = { gray = Color.GRAY, ycbcr = Color.YCC, rgb = Color.RGB, cmyk = Color.CMYK, ycck = Color.YCCK } local tableCache: { [number]: { buffer } } = {} local function yccTables(maxv: number): { buffer } local t = tableCache[maxv] if not t then local a, b, c, d = Color.tables(maxv) t = { a, b, c, d } tableCache[maxv] = t end return t end local toByte12: buffer? = nil function Decode.output(st: State): (number?, any, any, string?) local f: Frame = st.frame local scale = st.scale local minSize = 8 // scale local maxv = if f.precision == 12 then 4095 else 255 local center = (maxv + 1) // 2 local p1 = if f.precision == 12 then 1 else 2 local outW = math.ceil(f.width * minSize / 8) local outH = math.ceil(f.height * minSize / 8) local fancy = minSize > 1 local ccomps = {} local zeroQ = buffer.create(128) for _, c in f.comps do local ssize = idctSize(f, c, scale) local stride, rows = c.bpl * ssize, c.bpc * ssize local plane = buffer.create(stride * rows * 2) local coef = c.coef or buffer.create(c.bpl * c.bpc * 128) local q = c.quant if not q then if c.coef then return nil, "corrupt", "missing quantisation table " .. c.tq end q = zeroQ -- the component never appeared in a scan: mid grey end Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, ssize, plane, p1, center, maxv, st.hook) local hIn, hOut = c.h * ssize // minSize, f.hmax local vIn, vOut = c.v * ssize // minSize, f.vmax local downW = math.ceil(f.width * c.h * ssize / (f.hmax * 8)) local downH = math.ceil(f.height * c.v * ssize / (f.vmax * 8)) local method if hIn == hOut and vIn == vOut then method = Color.FULL elseif hIn * 2 == hOut and vIn * 2 == vOut and fancy and downW > 2 then method = Color.H2V2 elseif hIn * 2 == hOut and vIn == vOut and fancy and downW > 2 then method = Color.H2V1 elseif hIn == hOut and vIn * 2 == vOut and fancy then method = Color.H1V2 else method = Color.REPLICATE end table.insert(ccomps, { plane = plane, stride = stride, rows = rows, downW = downW, downH = downH, method = method, hIn = hIn, hOut = hOut, vIn = vIn, vOut = vOut, row = buffer.create((math.max(outW, 2 * stride) + 8) * 2), }) c.coef = nil end local space = colorSpaceOf(f, st.adobe, st.jfif) local spaceId = SPACE_IDS[space] if space == "cmyk" and st.adobe == nil then spaceId = Color.CMYK_PLAIN end if st.raw then spaceId = Color.RAW end local t = yccTables(maxv) local tb = nil if maxv == 4095 then if not toByte12 then local tbuf = buffer.create(4096) for v = 0, 4095 do buffer.writeu8(tbuf, v, (v * 255 + 2047) // 4095) end toByte12 = tbuf end tb = toByte12 end local pixels = buffer.create(outW * outH * 4) Color.run({ comps = ccomps, space = spaceId, outW = outW, outH = outH, maxv = maxv, pixels = pixels, crr = t[1], cbb = t[2], crg = t[3], cbg = t[4], toByte = tb, hook = st.hook, }) return outW, outH, pixels, space end -- outputYuv: 4:2:0, 4:2:2 (chroma row pairs averaged, rounding up), 4:4:4 (2 x 2 averaged, rounding to nearest) or grey -- (chroma 128) straight from the IDCT planes; full scale only local scratch: buffer? = nil local function scratchPlane(n: number): buffer local sc = scratch if sc and buffer.len(sc) >= n then return sc end local b = buffer.create(n) if n <= 4 * 1024 * 1024 then scratch = b end return b end function Decode.outputYuv(st: State): (number?, number?, buffer?, string?) local f: Frame = st.frame if st.scale ~= 1 or f.precision ~= 8 then return nil, nil, nil, nil end local comps = f.comps local space = colorSpaceOf(f, st.adobe, st.jfif) local mode = nil if space == "gray" then mode = "gray" elseif space == "ycbcr" then -- the ratios of luma to chroma sampling (ffmpeg writes 4:2:2 as 2x2 / 1x2 and 4:4:4 as 1x2 everywhere) local l, cb, cr = comps[1], comps[2], comps[3] if l.h == f.hmax and l.v == f.vmax and cb.h == cr.h and cb.v == cr.v then local rh, rv = f.hmax // cb.h, f.vmax // cb.v if rh * cb.h ~= f.hmax or rv * cb.v ~= f.vmax then mode = nil elseif rh == 2 and rv == 2 then mode = "420" elseif rh == 2 and rv == 1 then mode = "422" elseif rh == 1 and rv == 1 then mode = "444" end end end if not mode then return nil, nil, nil, nil end for _, c in comps do if c.coef and not c.quant then return nil, nil, nil, nil end end local w, h = f.width, f.height local cw, ch = (w + 1) // 2, (h + 1) // 2 local out = buffer.create(w * h + 2 * cw * ch) local zeroQ: buffer? = nil for i, c in comps do local stride, rows = c.bpl * 8, c.bpc * 8 local plane = scratchPlane(stride * rows * 2) local coef = c.coef or buffer.create(c.bpl * c.bpc * 128) local q = c.quant if not q then zeroQ = zeroQ or buffer.create(128) -- the component never appeared in a scan: mid grey q = zeroQ end Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, 8, plane, 2, 128, 255, st.hook) if i == 1 then Yuv.crop(plane, stride, w, h, out, 0) elseif mode == "420" then Yuv.crop(plane, stride, cw, ch, out, w * h + (i - 2) * cw * ch) elseif mode == "422" then Yuv.rows(plane, stride, cw, h, out, w * h + (i - 2) * cw * ch) else Yuv.box(plane, stride, w, h, out, w * h + (i - 2) * cw * ch) end c.coef = nil end if mode == "gray" then buffer.fill(out, w * h, 128, 2 * cw * ch) end return w, h, out, mode end return Decode end __FILES["codecs/image/Jpeg/Encode"] = @native function() -- codecs/image/Jpeg/Encode: the JPEG encoder, baseline (SOF0) and progressive (SOF2, jpeg_simple_progression). -- Follows libjpeg-turbo step for step (jccolor.c, jcsample.c, jccoefct.c, jfdctint.c / jcdctmgr.c, jchuff.c, jcphuff.c) -- so its output is byte-identical to cjpeg's; Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md. local Dct = __include("codecs/image/Dct") local Tables = __include("codecs/image/Jpeg/Tables") local readu8, writeu8, readi16, writei16, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16, buffer.readu16, buffer.writeu16 local band, countlz = bit32.band, bit32.countlz local Encode = {} -- natural order index of zigzag position k local ZZ = buffer.create(64) do local i = 0 for s = 0, 14 do local lo, hi = math.max(0, s - 7), math.min(s, 7) if s % 2 == 0 then for r = hi, lo, -1 do writeu8(ZZ, i, r * 8 + (s - r)) i += 1 end else for r = lo, hi do writeu8(ZZ, i, r * 8 + (s - r)) i += 1 end end end end Encode.ZIGZAG = ZZ local OUT = buffer.create(0) local OP = 0 local CAP = 0 local ACC, NB = 0, 0 local GATHER = false @native local function grow(n: number) if OP + n > CAP then local c = math.max(CAP * 2, OP + n + 1024) local nb = buffer.create(c) buffer.copy(nb, 0, OUT, 0, OP) OUT = nb CAP = c end end @native local function byte(v: number) grow(1) writeu8(OUT, OP, v) OP += 1 end @native local function u16be(v: number) byte(v // 256) byte(v % 256) end -- n bits of v (n <= 16), MSB first, with 0xFF stuffing @native local function bits(v: number, n: number) if GATHER or n == 0 then return end local p = 2 ^ n ACC = ACC * p + band(v, p - 1) NB += n while NB >= 8 do NB -= 8 local d = 2 ^ NB local b = ACC // d ACC -= b * d grow(2) writeu8(OUT, OP, b) OP += 1 if b == 0xFF then writeu8(OUT, OP, 0) OP += 1 end end end @native local function flushBits() if NB > 0 then bits(0x7F, 8 - NB) -- pad with ones end ACC, NB = 0, 0 end @native local function nbits(v: number): number return if v == 0 then 0 else 32 - countlz(v) end -- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl) type Derived = { code: buffer, size: buffer } @native local function derive(counts: { number }, symbols: { number }): Derived local code, size = buffer.create(512), buffer.create(256) local c, k = 0, 1 for l = 1, 16 do for _ = 1, counts[l] or 0 do local s = symbols[k] if s then writeu16(code, s * 2, c) writeu8(size, s, l) end k += 1 c += 1 end c *= 2 end return { code = code, size = size } end -- jchuff.c jpeg_gen_optimal_table: freq (0..256, 1-based +1) -> counts, symbols @native local function optimal(freqIn: { number }): ({ number }, { number }) local freq = table.create(257, 0) local bitsT = table.create(34, 0) local codesize = table.create(257, 0) local others = table.create(257, -1) local nz = table.create(257, 0) local n = 0 for i = 0, 256 do local f = if i == 256 then 1 else freqIn[i + 1] if f > 0 then n += 1 nz[n] = i freq[n] = f end end while true do local c1, c2 = -1, -1 local v, v2 = 1e9, 1e9 for i = 1, n do local f = freq[i] if f <= v2 then if f <= v then c2 = c1 v2 = v v = f c1 = i else v2 = f c2 = i end end end if c2 < 0 then break end freq[c1] += freq[c2] freq[c2] = 1000000001 codesize[c1] += 1 while others[c1] >= 0 do c1 = others[c1] codesize[c1] += 1 end others[c1] = c2 codesize[c2] += 1 while others[c2] >= 0 do c2 = others[c2] codesize[c2] += 1 end end for i = 1, n do local cs = math.min(codesize[i], 32) bitsT[cs + 1] += 1 end local bitPos = table.create(34, 0) local p = 0 for i = 1, 32 do bitPos[i + 1] = p p += bitsT[i + 1] end local i = 32 while i > 16 do while bitsT[i + 1] > 0 do local j = i - 2 while bitsT[j + 1] == 0 do j -= 1 end bitsT[i + 1] -= 2 bitsT[i] += 1 bitsT[j + 2] += 2 bitsT[j + 1] -= 1 end i -= 1 end while bitsT[i + 1] == 0 do i -= 1 end bitsT[i + 1] -= 1 local counts = table.create(16, 0) for l = 1, 16 do counts[l] = bitsT[l + 1] end local symbols = table.create(n, 0) for k = 1, n - 1 do local cs = math.min(codesize[k], 32) symbols[bitPos[cs + 1] + 1] = nz[k] bitPos[cs + 1] += 1 end local total = 0 for l = 1, 16 do total += counts[l] end local out = table.create(total, 0) for k = 1, total do out[k] = symbols[k] end return counts, out end Encode.optimal = optimal local dcTab: { Derived } = {} local acTab: { Derived } = {} local dcFreq: { { number } } = {} local acFreq: { { number } } = {} @native local function symbol(t: Derived, freq: { number }, s: number) if GATHER then freq[s + 1] += 1 else bits(readu16(t.code, s * 2), readu8(t.size, s)) end end type Comp = { id: number, h: number, v: number, tq: number, td: number, ta: number, bw: number, bh: number, bpl: number, bpc: number, coef: buffer, last: number, } @native local function dcDiff(c: Comp, diff: number) local t = diff local t2 = diff if t < 0 then t = -t t2 -= 1 end local n = nbits(t) symbol(dcTab[c.td + 1], dcFreq[c.td + 1], n) if n > 0 then bits(t2, n) end end -- jchuff.c encode_one_block @native local function blockSeq(c: Comp, off: number) local coef = c.coef local dc = readi16(coef, off) dcDiff(c, dc - c.last) c.last = dc local at, af = acTab[c.ta + 1], acFreq[c.ta + 1] local r = 0 for k = 1, 63 do local v = readi16(coef, off + readu8(ZZ, k) * 2) if v == 0 then r += 1 else while r > 15 do symbol(at, af, 0xF0) r -= 16 end local t, t2 = v, v if t < 0 then t = -t t2 -= 1 end local n = nbits(t) symbol(at, af, r * 16 + n) bits(t2, n) r = 0 end end if r > 0 then symbol(at, af, 0) end end -- progressive state (jcphuff.c) local EOBRUN = 0 local BE = 0 local CORR = table.create(1000, 0) :: { number } local curAc: Derived = { code = buffer.create(512), size = buffer.create(256) } local curAcFreq: { number } = {} @native local function emitEobrun() if EOBRUN > 0 then local n = nbits(EOBRUN) - 1 symbol(curAc, curAcFreq, n * 16) if n > 0 then bits(EOBRUN, n) end EOBRUN = 0 if not GATHER then for i = 1, BE do bits(CORR[i], 1) end end BE = 0 end end @native local function blockDcFirst(c: Comp, off: number, al: number) local t2 = readi16(c.coef, off) // 2 ^ al dcDiff(c, t2 - c.last) c.last = t2 end @native local function blockAcFirst(c: Comp, off: number, ss: number, se: number, al: number) local coef = c.coef local d = 2 ^ al local r = 0 for k = ss, se do local v = readi16(coef, off + readu8(ZZ, k) * 2) local t, t2 if v < 0 then t = (-v) // d t2 = -t - 1 -- ~t else t = v // d t2 = t end if t == 0 then r += 1 else emitEobrun() while r > 15 do symbol(curAc, curAcFreq, 0xF0) r -= 16 end local n = nbits(t) symbol(curAc, curAcFreq, r * 16 + n) bits(t2, n) r = 0 end end if r > 0 then EOBRUN += 1 if EOBRUN == 0x7FFF then emitEobrun() end end end local absv = table.create(64, 0) @native local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: number) local coef = c.coef local d = 2 ^ al local eob = 0 for k = ss, se do local v = readi16(coef, off + readu8(ZZ, k) * 2) local t = (if v < 0 then -v else v) // d absv[k + 1] = t if t == 1 then eob = k end end local r = 0 local br = 0 local brStart = BE for k = ss, se do local t = absv[k + 1] if t == 0 then r += 1 continue end while r > 15 and k <= eob do emitEobrun() symbol(curAc, curAcFreq, 0xF0) r -= 16 if not GATHER then for i = 1, br do bits(CORR[brStart + i], 1) end end brStart = 0 br = 0 end if t > 1 then br += 1 CORR[brStart + br] = t % 2 continue end emitEobrun() symbol(curAc, curAcFreq, r * 16 + 1) bits(if readi16(coef, off + readu8(ZZ, k) * 2) < 0 then 0 else 1, 1) if not GATHER then for i = 1, br do bits(CORR[brStart + i], 1) end end brStart = 0 br = 0 r = 0 end if r > 0 or br > 0 then EOBRUN += 1 BE += br if EOBRUN == 0x7FFF or BE > 1000 - 64 + 1 then emitEobrun() end end end type ScanSpec = { comps: { number }, ss: number, se: number, ah: number, al: number } @native local function walk(comps: { Comp }, mcusX: number, mcusY: number, ri: number, onRestart: (number) -> (), fn: (Comp, number) -> ()) local nc = #comps local units, ux if nc == 1 then ux = comps[1].bw units = ux * comps[1].bh else ux = mcusX units = ux * mcusY end local rn = 0 for u = 0, units - 1 do if ri > 0 and u > 0 and u % ri == 0 then onRestart(rn) rn = (rn + 1) % 8 end local my, mx = u // ux, u % ux for ci = 1, nc do local c = comps[ci] if nc == 1 then fn(c, (my * c.bpl + mx) * 128) else for by = my * c.v, my * c.v + c.v - 1 do for bx = mx * c.h, mx * c.h + c.h - 1 do fn(c, (by * c.bpl + bx) * 128) end end end end end end @native local function dht(class: number, slot: number, counts: { number }, symbols: { number }) byte(0xFF) byte(0xC4) u16be(2 + 17 + #symbols) byte(class * 16 + slot) for l = 1, 16 do byte(counts[l]) end for _, s in symbols do byte(s) end end @native local function sos(comps: { Comp }, ss: number, se: number, ah: number, al: number, dcOnly: boolean, acOnly: boolean) byte(0xFF) byte(0xDA) u16be(6 + 2 * #comps) byte(#comps) for _, c in comps do byte(c.id) local td = if acOnly then 0 else c.td local ta = if dcOnly then 0 else c.ta byte(td * 16 + ta) end byte(ss) byte(se) byte(ah * 16 + al) end -- jccolor.c rgb_ycc_start tables (16-bit fixed point) @native local function fix(x: number): number return math.floor(x * 65536 + 0.5) end local YR, YG, YB = fix(0.29900), fix(0.58700), fix(0.11400) local CBR, CBG, HALF = fix(0.16874), fix(0.33126), fix(0.5) local CRG, CRB = fix(0.41869), fix(0.08131) local OFF = 128 * 65536 + 32768 - 1 @native local function planes(px: buffer, w: number, h: number, bpp: number, gray: boolean): (buffer, buffer?, buffer?) local n = w * h local Y = buffer.create(n) if bpp == 1 then buffer.copy(Y, 0, px, 0, n) if gray then return Y, nil, nil end local Cb = buffer.create(n) buffer.fill(Cb, 0, 128, n) local Cr = buffer.create(n) buffer.fill(Cr, 0, 128, n) return Y, Cb, Cr end if gray then for i = 0, n - 1 do local o = i * bpp local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2) writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536) end return Y, nil, nil end local Cb, Cr = buffer.create(n), buffer.create(n) for i = 0, n - 1 do local o = i * bpp local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2) writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536) writeu8(Cb, i, (-CBR * r - CBG * g + HALF * b + OFF) // 65536) writeu8(Cr, i, (HALF * r - CRG * g - CRB * b + OFF) // 65536) end return Y, Cb, Cr end -- jcsample.c downsampling: columns past w - 1 repeat the last one, rows past h - 1 the last row @native local function downsample(src: buffer, w: number, h: number, hf: number, vf: number, outW: number, outH: number): buffer local out = buffer.create(outW * outH) for oy = 0, outH - 1 do local r0 = math.min(oy * vf, h - 1) * w local r1 = math.min(oy * vf + vf - 1, h - 1) * w local bias = if hf == 2 and vf == 2 then 1 elseif hf == 2 then 0 else (if vf == 2 then 1 else 0) for ox = 0, outW - 1 do local x0 = math.min(ox * hf, w - 1) local x1 = math.min(ox * hf + hf - 1, w - 1) local v if hf == 2 and vf == 2 then v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + readu8(src, r1 + x0) + readu8(src, r1 + x1) + bias) // 4 bias = 3 - bias elseif hf == 2 then v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + bias) // 2 bias = 1 - bias else v = (readu8(src, r0 + x0) + readu8(src, r1 + x0) + bias) // 2 bias = 1 - bias end writeu8(out, oy * outW + ox, v) end end return out end type Options = { quality: number, sampling: string, progressive: boolean, optimize: boolean, gray: boolean, restart: number, segments: { { marker: number, data: buffer } }, jfif: boolean, density: { unit: number, x: number, y: number }?, } @native function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): buffer OUT = buffer.create(math.max(1024, w * h // 2)) CAP = buffer.len(OUT) OP = 0 ACC, NB = 0, 0 GATHER = false EOBRUN, BE = 0, 0 local yuv = bpp == 0 local Y, Cb, Cr if yuv then local n, cn = w * h, ((w + 1) // 2) * ((h + 1) // 2) Y = px if not o.gray then Cb, Cr = buffer.create(cn), buffer.create(cn) buffer.copy(Cb :: buffer, 0, px, n, cn) buffer.copy(Cr :: buffer, 0, px, n + cn, cn) end else Y, Cb, Cr = planes(px, w, h, bpp, o.gray) end local hs, vs = 1, 1 if not o.gray then if o.sampling == "420" then hs, vs = 2, 2 elseif o.sampling == "422" then hs, vs = 2, 1 end end local mcusX = math.ceil(w / (8 * hs)) local mcusY = math.ceil(h / (8 * vs)) local qt = { Tables.quant(Tables.LUMA, o.quality), Tables.quant(Tables.CHROMA, o.quality) } local qdiv = {} for t = 1, 2 do local b = buffer.create(128) for i = 1, 64 do writeu16(b, (i - 1) * 2, qt[t][i]) end qdiv[t] = b end local comps: { Comp } = {} local srcs = if o.gray then { Y } else { Y, Cb :: buffer, Cr :: buffer } for i, src in srcs do local ch, cv = if i == 1 then hs else 1, if i == 1 then vs else 1 local cw = math.ceil(w * ch / hs) local chh = math.ceil(h * cv / vs) local bw, bh = math.ceil(cw / 8), math.ceil(chh / 8) local bpl, bpc = mcusX * ch, mcusY * cv local plane, pw, ph = src, w, h if yuv and i > 1 then pw, ph = (w + 1) // 2, (h + 1) // 2 -- already 4:2:0: fdctQuantize repeats the edges as jcsample.c does elseif ch < hs or cv < vs then pw, ph = bw * 8, chh plane = downsample(src, w, h, hs // ch, vs // cv, pw, ph) end local coef = buffer.create(bpl * bpc * 128) local c: Comp = { id = i, h = ch, v = cv, tq = if i == 1 then 0 else 1, td = if i == 1 then 0 else 1, ta = if i == 1 then 0 else 1, bw = bw, bh = bh, bpl = bpl, bpc = bpc, coef = coef, last = 0, } local div = qdiv[c.tq + 1] for by = 0, bpc - 1 do for bx = 0, bpl - 1 do local off = (by * bpl + bx) * 128 if by < bh and bx < bw then Dct.fdctQuantize(plane, pw, bx * 8, by * 8, pw, ph, div, coef, off) elseif by < bh then writei16(coef, off, readi16(coef, off - 128)) -- right edge: the previous block's DC else -- bottom: the DC of the MCU's last block in the row above local lb = (bx // ch) * ch + ch - 1 writei16(coef, off, readi16(coef, ((by - 1) * bpl + lb) * 128)) end end end comps[i] = c end byte(0xFF) byte(0xD8) if o.jfif then local d = o.density or { unit = 0, x = 1, y = 1 } byte(0xFF) byte(0xE0) u16be(16) for _, ch in { 0x4A, 0x46, 0x49, 0x46, 0 } do byte(ch) end byte(1) byte(1) byte(d.unit) u16be(d.x) u16be(d.y) byte(0) byte(0) end for _, s in o.segments do local n = buffer.len(s.data) byte(0xFF) byte(s.marker) u16be(n + 2) grow(n) buffer.copy(OUT, OP, s.data, 0, n) OP += n end for t = 1, (if o.gray then 1 else 2) do byte(0xFF) byte(0xDB) u16be(67) byte(t - 1) for k = 0, 63 do byte(qt[t][readu8(ZZ, k) + 1]) end end byte(0xFF) byte(if o.progressive then 0xC2 else 0xC0) u16be(8 + 3 * #comps) byte(8) u16be(h) u16be(w) byte(#comps) for _, c in comps do byte(c.id) byte(c.h * 16 + c.v) byte(c.tq) end local ntab = if o.gray then 1 else 2 @native local function restartMarker(n: number) flushBits() byte(0xFF) byte(0xD0 + n) end if not o.progressive then if o.optimize then GATHER = true for t = 1, ntab do dcFreq[t] = table.create(257, 0) acFreq[t] = table.create(257, 0) end for _, c in comps do c.last = 0 end walk(comps, mcusX, mcusY, o.restart, @native function() for _, c in comps do c.last = 0 end end, blockSeq) GATHER = false end for t = 1, ntab do local dcC, dcS, acC, acS if o.optimize then dcC, dcS = optimal(dcFreq[t]) acC, acS = optimal(acFreq[t]) else local d, a = Tables.DC[t], Tables.AC[t] dcC, dcS, acC, acS = d.counts, d.symbols, a.counts, a.symbols end dcTab[t] = derive(dcC, dcS) acTab[t] = derive(acC, acS) dcFreq[t] = table.create(257, 0) acFreq[t] = table.create(257, 0) -- libjpeg emits each table before the scan in component order: DC0, AC0, DC1, AC1 dht(0, t - 1, dcC, dcS) dht(1, t - 1, acC, acS) end if o.restart > 0 then byte(0xFF) byte(0xDD) u16be(4) u16be(o.restart) end sos(comps, 0, 63, 0, 0, false, false) for _, c in comps do c.last = 0 end walk(comps, mcusX, mcusY, o.restart, @native function(n: number) restartMarker(n) for _, c in comps do c.last = 0 end end, blockSeq) flushBits() else local script: { ScanSpec } if o.gray then script = { { comps = { 1 }, ss = 0, se = 0, ah = 0, al = 1 }, { comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 }, { comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 }, { comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 }, { comps = { 1 }, ss = 0, se = 0, ah = 1, al = 0 }, { comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 }, } else script = { { comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 0, al = 1 }, { comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 }, { comps = { 3 }, ss = 1, se = 63, ah = 0, al = 1 }, { comps = { 2 }, ss = 1, se = 63, ah = 0, al = 1 }, { comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 }, { comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 }, { comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 1, al = 0 }, { comps = { 3 }, ss = 1, se = 63, ah = 1, al = 0 }, { comps = { 2 }, ss = 1, se = 63, ah = 1, al = 0 }, { comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 }, } end local driSent = false for _, sc in script do local sComps: { Comp } = {} for _, ci in sc.comps do table.insert(sComps, comps[ci]) end local ss, se, ah, al = sc.ss, sc.se, sc.ah, sc.al local isDc = ss == 0 local blockFn: (Comp, number) -> () if isDc and ah == 0 then blockFn = @native function(c: Comp, off: number) blockDcFirst(c, off, al) end elseif isDc then blockFn = @native function(c: Comp, off: number) bits(band(readi16(c.coef, off) // 2 ^ al, 1), 1) end elseif ah == 0 then blockFn = @native function(c: Comp, off: number) blockAcFirst(c, off, ss, se, al) end else blockFn = @native function(c: Comp, off: number) blockAcRefine(c, off, ss, se, al) end end @native local function onRestart(n: number) emitEobrun() if not GATHER then restartMarker(n) end for _, c in sComps do c.last = 0 end EOBRUN, BE = 0, 0 end @native local function pass() for _, c in sComps do c.last = 0 end EOBRUN, BE = 0, 0 walk(sComps, mcusX, mcusY, o.restart, onRestart, blockFn) emitEobrun() end if not (isDc and ah > 0) then GATHER = true for t = 1, ntab do dcFreq[t] = table.create(257, 0) acFreq[t] = table.create(257, 0) end if not isDc then curAcFreq = acFreq[sComps[1].ta + 1] end pass() GATHER = false local sent = {} for _, c in sComps do local slot = if isDc then c.td else c.ta if not sent[slot] then sent[slot] = true local counts, syms = optimal(if isDc then dcFreq[slot + 1] else acFreq[slot + 1]) dht(if isDc then 0 else 1, slot, counts, syms) if isDc then dcTab[slot + 1] = derive(counts, syms) else acTab[slot + 1] = derive(counts, syms) end end end if not isDc then curAc = acTab[sComps[1].ta + 1] end end if o.restart > 0 and not driSent then driSent = true byte(0xFF) byte(0xDD) u16be(4) u16be(o.restart) end sos(sComps, ss, se, ah, al, isDc, not isDc or ah > 0) -- DC refinement uses no table: td = 0 (as libjpeg) pass() flushBits() end end byte(0xFF) byte(0xD9) local res = buffer.create(OP) buffer.copy(res, 0, OUT, 0, OP) OUT = buffer.create(0) CAP = 0 return res end return Encode end __FILES["codecs/image/Jpeg/Scan"] = @native function() -- codecs/image/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients. From jpeg-luau 1.0 (same author). -- The clean scan data is followed by PAD zero bytes, so the 32-bit big-endian bit reader needs no bounds check. -- Huffman tables (built by `buildTable`) are buffers: -- [0, 1024) fast lookup by the next 9 bits: u16 (length << 8) | symbol, 0 = longer code -- [1024, 1096) maxcode[l], l = 0..17: u32, one past the last code of length l, left-aligned to 16 bits -- [1096, 1168) delta[l]: i32, symbol index = code + delta[l] -- [1168, 1424) symbols -- [1424, 1426) symbol count -- [1428, 3476) fast AC lookup by the next 9 bits: i32 value * 256 + run * 16 + total length, when the code -- and its extra bits fit in 9 bits (0 otherwise) local readu8, readu16, readu32, readi32, readi16 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readi16 local writeu8, writeu16, writeu32, writei32, writei16 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei32, buffer.writei16 local band, bor, lshift, rshift, byteswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.byteswap local Scan = {} Scan.PAD = 4096 Scan.TABLE_SIZE = 3476 local T_MAX = 1024 local T_DELTA = 1096 local T_VAL = 1168 local T_COUNT = 1424 local T_FASTAC = 1428 -- zigzag index -> natural (row-major) index, padded with 63s so a run past the end stays in range local ZZ = buffer.create(80) do local i = 0 for s = 0, 14 do local lo, hi = math.max(0, s - 7), math.min(s, 7) if s % 2 == 0 then for r = hi, lo, -1 do writeu8(ZZ, i, r * 8 + (s - r)) i += 1 end else for r = lo, hi do writeu8(ZZ, i, r * 8 + (s - r)) i += 1 end end end for j = 64, 79 do writeu8(ZZ, j, 63) end end Scan.ZIGZAG = ZZ -- an over-subscribed table keeps the codes that fit; the rest decode as invalid @native function Scan.buildTable(counts: { number }, symbols: { number }): buffer local t = buffer.create(Scan.TABLE_SIZE) local code, k = 0, 0 local nsym = #symbols local codes, sizes = {}, {} local broken = false for l = 1, 16 do writei32(t, T_DELTA + l * 4, k - code) local n = counts[l] or 0 for _ = 1, n do if broken or code >= lshift(1, l) or k >= nsym or k >= 256 then broken = true break end k += 1 codes[k] = code sizes[k] = l code += 1 end writeu32(t, T_MAX + l * 4, if broken then 0 else lshift(code, 16 - l)) code *= 2 end writeu32(t, T_MAX + 17 * 4, 0xFFFFFFFF) for i = 1, k do writeu8(t, T_VAL + i - 1, symbols[i]) end writeu16(t, T_COUNT, k) for i = 1, k do local l = sizes[i] if l <= 9 then local sym = symbols[i] local base = lshift(codes[i], 9 - l) for j = 0, lshift(1, 9 - l) - 1 do local idx = base + j writeu16(t, idx * 2, l * 256 + sym) local r, s = rshift(sym, 4), band(sym, 15) if s ~= 0 and l + s <= 9 then local v = band(rshift(idx, 9 - l - s), lshift(1, s) - 1) if v < lshift(1, s - 1) then v = v - lshift(1, s) + 1 end writei32(t, T_FASTAC + idx * 4, v * 256 + r * 16 + l + s) end end end end return t end @native function Scan.destuff(src: buffer, pos: number, n: number, dst: buffer, rst: { number }): (number, number, number) local o, nr = 0, 0 while pos < n do local b = readu8(src, pos) if b ~= 0xFF then writeu8(dst, o, b) o += 1 pos += 1 else local q = pos + 1 while q < n and readu8(src, q) == 0xFF do q += 1 end if q >= n then pos = n break end local m = readu8(src, q) if m == 0 then writeu8(dst, o, 0xFF) o += 1 pos = q + 1 elseif m >= 0xD0 and m <= 0xD7 then nr += 1 rst[nr] = o pos = q + 1 else pos = q - 1 break end end end buffer.fill(dst, o, 0, Scan.PAD) return pos, o, nr end @native local function huff(d: buffer, pos: number, t: buffer): (number, number) local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) local f = readu16(t, rshift(w, 23) * 2) if f ~= 0 then return band(f, 255), pos + rshift(f, 8) end local c = rshift(w, 16) local l = 10 while c >= readu32(t, T_MAX + l * 4) do l += 1 end if l > 16 then return 0, pos + 16 -- invalid code end local idx = rshift(c, 16 - l) + readi32(t, T_DELTA + l * 4) if idx < 0 or idx >= readu16(t, T_COUNT) then return 0, pos + l end return readu8(t, T_VAL + idx), pos + l end @native local function bits(d: buffer, pos: number, s: number): number return rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 32 - s) end @native local function extend(v: number, s: number): number if v < lshift(1, s - 1) then return v - lshift(1, s) + 1 end return v end @native local function blockSeq(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, act: buffer, pred: number): (number, number) local s s, pos = huff(d, pos, dct) if s ~= 0 then if s > 16 then s = 16 end pred += extend(bits(d, pos, s), s) pos += s end writei16(coef, off, pred) local k = 1 while k < 64 do local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4) if fa ~= 0 then local low = fa % 256 k += low // 16 pos += low % 16 if k > 63 then break end writei16(coef, off + readu8(ZZ, k) * 2, fa // 256) k += 1 else local rs rs, pos = huff(d, pos, act) local r, sz = rshift(rs, 4), band(rs, 15) if sz == 0 then if r ~= 15 then break end k += 16 else k += r if k > 63 then break end writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, sz), sz)) pos += sz k += 1 end end end return pos, pred end @native local function blockDcFirst(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, pred: number, al: number): (number, number) local s s, pos = huff(d, pos, dct) if s ~= 0 then if s > 16 then s = 16 end pred += extend(bits(d, pos, s), s) pos += s end writei16(coef, off, pred * lshift(1, al)) return pos, pred end @native local function blockAcFirst(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number) if eobrun > 0 then return pos, eobrun - 1 end local mul = lshift(1, al) local k = ss while k <= se do local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4) if fa ~= 0 then local low = fa % 256 k += low // 16 pos += low % 16 if k > se then break end writei16(coef, off + readu8(ZZ, k) * 2, (fa // 256) * mul) k += 1 else local rs rs, pos = huff(d, pos, act) local r, s = rshift(rs, 4), band(rs, 15) if s == 0 then if r < 15 then eobrun = lshift(1, r) - 1 if r > 0 then eobrun += bits(d, pos, r) pos += r end break end k += 16 else k += r if k > se then break end writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, s), s) * mul) pos += s k += 1 end end end return pos, eobrun end -- successive-approximation refinement of AC coefficients ss..se (as stb_image / libjpeg decode_mcu_AC_refine) @native local function blockAcRefine(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number) local bit = lshift(1, al) if eobrun > 0 then for k = ss, se do local o = off + readu8(ZZ, k) * 2 local p = readi16(coef, o) if p ~= 0 then local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) pos += 1 if b ~= 0 and band(p, bit) == 0 then writei16(coef, o, if p > 0 then p + bit else p - bit) end end end return pos, eobrun - 1 end local k = ss while k <= se do local rs rs, pos = huff(d, pos, act) local s, r = band(rs, 15), rshift(rs, 4) local val = 0 if s == 0 then if r < 15 then eobrun = lshift(1, r) - 1 if r > 0 then eobrun += bits(d, pos, r) pos += r end r = 64 -- the rest of the block only refines end else -- s must be 1; anything else is corrupt and treated as 1 local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) pos += 1 val = if b ~= 0 then bit else -bit end while k <= se do local o = off + readu8(ZZ, k) * 2 k += 1 local p = readi16(coef, o) if p ~= 0 then local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) pos += 1 if b ~= 0 and band(p, bit) == 0 then writei16(coef, o, if p > 0 then p + bit else p - bit) end else if r == 0 then if val ~= 0 then writei16(coef, o, val) end break end r -= 1 end end end -- an EOB run that started in this block counts it already (eobrun = run length - 1) return pos, eobrun end type ScanComp = { coef: buffer, bpl: number, h: number, v: number, bw: number, bh: number, dct: buffer?, act: buffer?, pred: number, } type ScanParams = { comps: { ScanComp }, mcusX: number, mcusY: number, ri: number, mode: number, ss: number, se: number, al: number, hook: (() -> ())?, } @native function Scan.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, P: ScanParams): (number, boolean) local comps = P.comps local nc = #comps local mode, ss, se, al, ri = P.mode, P.ss, P.se, P.al, P.ri local endBits = cleanLen * 8 local units, ux if nc == 1 then ux = comps[1].bw units = ux * comps[1].bh else ux = P.mcusX units = ux * P.mcusY end for i = 1, nc do comps[i].pred = 0 end local pos, eobrun, rstIdx = 0, 0, 0 local truncated, skipping = false, false local bit = lshift(1, al) local hook = P.hook for u = 0, units - 1 do if hook and u > 0 and u % ux == 0 then pcall(hook) end if ri > 0 and u > 0 and u % ri == 0 then rstIdx += 1 if rstIdx <= nrst then pos = rst[rstIdx] * 8 skipping = false end for i = 1, nc do comps[i].pred = 0 end eobrun = 0 end if pos > endBits then truncated = true if ri == 0 or rstIdx >= nrst then break end skipping = true end if not skipping then local my, mx = u // ux, u % ux for ci = 1, nc do local c = comps[ci] local bh, bw, by0, bx0 if nc == 1 then bh, bw, by0, bx0 = 1, 1, my, mx else bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h end local coef, bpl = c.coef, c.bpl for by = by0, by0 + bh - 1 do for bx = bx0, bx0 + bw - 1 do local off = (by * bpl + bx) * 128 if mode == 0 then pos, c.pred = blockSeq(d, pos, coef, off, c.dct :: buffer, c.act :: buffer, c.pred) elseif mode == 1 then pos, c.pred = blockDcFirst(d, pos, coef, off, c.dct :: buffer, c.pred, al) elseif mode == 2 then local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) pos += 1 if b ~= 0 then writei16(coef, off, bor(readi16(coef, off), bit)) end elseif mode == 3 then pos, eobrun = blockAcFirst(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun) else pos, eobrun = blockAcRefine(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun) end end end end end end return pos, truncated end return Scan end __FILES["codecs/image/Jpeg/Tables"] = function() -- codecs/image/Jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline -- encoder without optimisation writes and Motion-JPEG frames leave out) and the luminance / chrominance quantisation -- tables (K.1) with libjpeg's quality scaling (jcparam.c jpeg_quality_scaling / jpeg_add_quant_table). local Tables = {} local function range(t: { number }, a: number, b: number) for v = a, b do table.insert(t, v) end end -- { counts (16 code-length counts), symbols } per table: dc[1] luma, dc[2] chroma, ac[1], ac[2] local dcl = { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 } local dcc = { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 } local dcv = {} range(dcv, 0, 11) local acl = { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d } local aclv = { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, } range(aclv, 0x34, 0x3a) for hi = 4, 8 do range(aclv, hi * 16 + 3, hi * 16 + 10) end for hi = 9, 13 do range(aclv, hi * 16 + 2, hi * 16 + 10) end range(aclv, 0xe1, 0xea) range(aclv, 0xf1, 0xfa) local acc = { 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 } local accv = { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, } range(accv, 0x35, 0x3a) for hi = 4, 7 do range(accv, hi * 16 + 3, hi * 16 + 10) end for hi = 8, 14 do range(accv, hi * 16 + 2, hi * 16 + 10) end range(accv, 0xf2, 0xfa) type Spec = { counts: { number }, symbols: { number } } Tables.DC = { { counts = dcl, symbols = dcv }, { counts = dcc, symbols = dcv } } :: { Spec } Tables.AC = { { counts = acl, symbols = aclv }, { counts = acc, symbols = accv } } :: { Spec } -- K.1, natural (row-major) order Tables.LUMA = { 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99, } Tables.CHROMA = { 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, } function Tables.quant(base: { number }, quality: number): { number } local q = math.clamp(math.floor(quality), 1, 100) local scale = if q < 50 then 5000 // q else 200 - q * 2 local out = table.create(64, 1) for i = 1, 64 do out[i] = math.clamp((base[i] * scale + 50) // 100, 1, 255) end return out end return Tables end __FILES["codecs/image/Jpeg/Yuv"] = @native function() -- codecs/image/Jpeg/Yuv: the JPEG decoder's u16 IDCT planes -> u8 yuv420p; 4:2:2 / 4:4:4 chroma averaged to 4:2:0, -- the two fields of AVI1 interlaced Motion-JPEG woven. local readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buffer.readu32, buffer.writeu32 local Yuv = {} @native function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) local quads = w // 4 local rest = w - quads * 4 for y = 0, h - 1 do local s = y * stride * 2 local d = doff + y * w for _ = 1, quads do local a, b = readu32(src, s), readu32(src, s + 4) writeu32(dst, d, a % 65536 + (a // 65536) * 256 + (b % 65536) * 65536 + (b // 65536) * 16777216) s += 8 d += 4 end for k = 0, rest - 1 do writeu8(dst, d + k, readu16(src, s + k * 2)) end end end @native function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) local oh = (h + 1) // 2 for y = 0, oh - 1 do local a = 2 * y * stride * 2 local b = if 2 * y + 1 < h then a + stride * 2 else a local d = doff + y * w for x = 0, w - 1 do writeu8(dst, d + x, (readu16(src, a + x * 2) + readu16(src, b + x * 2) + 1) // 2) end end end @native function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) local ow, oh = (w + 1) // 2, (h + 1) // 2 for y = 0, oh - 1 do local a = 2 * y * stride * 2 local b = if 2 * y + 1 < h then a + stride * 2 else a local d = doff + y * ow for x = 0, ow - 1 do local x0 = 2 * x * 2 local x1 = if 2 * x + 1 < w then x0 + 2 else x0 writeu8(dst, d + x, (readu16(src, a + x0) + readu16(src, a + x1) + readu16(src, b + x0) + readu16(src, b + x1) + 2) // 4) end end end @native function Yuv.weave(top: buffer, toff: number, bottom: buffer, boff: number, rowBytes: number, rows: number, dst: buffer, doff: number) for y = 0, rows - 1 do local k = y // 2 if y % 2 == 0 then buffer.copy(dst, doff + y * rowBytes, top, toff + k * rowBytes, rowBytes) else buffer.copy(dst, doff + y * rowBytes, bottom, boff + k * rowBytes, rowBytes) end end end return Yuv end __FILES["codecs/image/Miptex"] = function() -- 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 type Header = { name: string, width: number, height: number, offsets: { number } } type Lump = { name: string, offset: number, disksize: number, size: number, type: number, compression: number } type DecodeOptions = { palette: buffer?, -- 1024-byte rgba8 palette (Pixels.palette) when the texture has none of its own goldsrc: boolean?, -- read the palette stored after mip 3 mip: number?, -- 0..3, default 0 keyed: boolean?, -- index 255 transparent; default: names starting with '{' maxPixels: number?, -- default 2^24 } -- 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: buffer, at: number, n: number): string return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string end function Miptex.header(b: buffer, at: number, size: number): (Header?, string?) 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: buffer, at: number, size: number, hd: Header): buffer? local w, h = hd.width, hd.height local p = hd.offsets[4] + (w // 8) * (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: buffer, at: number, size: number, opts: DecodeOptions?): (Types.Image?, string?) 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 = hd.width // (2 ^ mip), 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 = if opts and opts.goldsrc then Miptex.ownPalette(b, at, size, hd) else nil local pal = own or (opts and opts.palette) or Pixels.grey() local keyed = if opts and opts.keyed ~= nil then opts.keyed else string.sub(hd.name, 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: buffer, w: number, h: number): (buffer, number, number) local w2, h2 = math.max(1, w // 2), math.max(1, 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 += readu8(px, (sy * w + sx) * 4 + c) end end buffer.writeu8(out, (y * w2 + x) * 4 + c, (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: Types.Image, name: string, palette: buffer?, goldsrc: boolean?): (buffer?, string?) 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 local colors: { { number } } if palette then colors = Pixels.colorList(palette) elseif goldsrc then colors = Quantize.palette(img.pixels, w, h, 256) else return nil, "a Quake miptex needs a palette" end local keyed = string.sub(name, 1, 1) == "{" local levels: { buffer } = {} 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 idx = Quantize.map(px, lw, lh, colors, { transparentIndex = if keyed then 255 else nil }) if keyed then for k = 0, lw * lh - 1 do if readu8(px, k * 4 + 3) < 128 then buffer.writeu8(idx, k, 255) end end end levels[m + 1] = idx end local total = 40 for _, l in levels do total += buffer.len(l) end local palAt = total if goldsrc then 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 levels do buffer.writeu32(out, 24 + (m - 1) * 4, o) buffer.copy(out, o, l) 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: buffer, base: number, size: number, maxLumps: number?): ({ Lump }?, string?, string?) 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: { Lump } = {} 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: { Lump }, name: string): Lump? local want = string.lower(name) local best: Lump? = nil for _, l in lumps do if string.lower(l.name) == want then best = l end end return best end return Miptex end __FILES["codecs/image/Pixels"] = @native function() -- 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 = {} @native function Pixels.palette(src: buffer, base: number, n: number, bgr: boolean?): buffer local pal = buffer.create(1024) local m = if base >= 0 then math.clamp(math.min(n, (buffer.len(src) - base) // 3), 0, 256) else 0 for i = 0, 255 do local v = 0xFF000000 if i < m then local o = base + i * 3 local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) if bgr then r, b = b, r end v = bor(0xFF000000, lshift(b, 16), lshift(g, 8), r) end writeu32(pal, i * 4, v) end return pal end @native function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, topDown: boolean, pal: buffer) local mask = lshift(1, bpp) - 1 for r = 0, h - 1 do local so = base + r * stride local d = (if topDown then r else h - 1 - r) * w * 4 if bpp == 8 then for x = 0, w - 1 do writeu32(dst, d + x * 4, readu32(pal, readu8(src, so + x) * 4)) end elseif bpp == 4 then for x = 0, w - 1 do local b = readu8(src, so + rshift(x, 1)) local i = if band(x, 1) == 0 then rshift(b, 4) else band(b, 15) writeu32(dst, d + x * 4, readu32(pal, i * 4)) end else for x = 0, w - 1 do local bit = x * bpp local b = readu8(src, so + rshift(bit, 3)) local i = band(rshift(b, 8 - bpp - band(bit, 7)), mask) writeu32(dst, d + x * 4, readu32(pal, i * 4)) end end end end -- 16 bpp X-R-G-B 1-5-5-5 (BI_RGB 16-bit), opaque; 5-bit channels scaled to 8 bits with rounding @native function Pixels.rgb555(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean) for r = 0, h - 1 do local so = base + r * stride local d = (if topDown then r else h - 1 - r) * w * 4 for x = 0, w - 1 do local s = readu16(src, so + x * 2) local cr, cg, cb = band(rshift(s, 10), 31), band(rshift(s, 5), 31), band(s, 31) writeu32(dst, d + x * 4, (cr * 255 + 15) // 31 + ((cg * 255 + 15) // 31) * 256 + ((cb * 255 + 15) // 31) * 65536 + 0xFF000000) end end end -- 24 bpp BI_RGB: B, G, R @native function Pixels.bgr24(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean) for r = 0, h - 1 do local so = base + r * stride local d = (if topDown then r else h - 1 - r) * w * 4 for x = 0, w - 1 do local s = so + x * 3 writeu32(dst, d + x * 4, bor(readu8(src, s + 2), lshift(readu8(src, s + 1), 8), lshift(readu8(src, s), 16), 0xFF000000)) end end end -- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks) @native function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean): number local aor = 0 for r = 0, h - 1 do local so = base + r * stride local d = (if topDown then r else h - 1 - r) * w * 4 for x = 0, w - 1 do local p = readu32(src, so + x * 4) writeu32(dst, d + x * 4, bor(band(p, 0xFF00FF00), band(rshift(p, 16), 0xFF), lshift(band(p, 0xFF), 16))) aor = bor(aor, p) end end return rshift(aor, 24) end @native function Pixels.masked(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, topDown: boolean, shr: number, mr: number, tr: buffer, shg: number, mg: number, tg: buffer, shb: number, mb: number, tb: buffer, sha: number, ma: number, ta: buffer): number local bytes = rshift(bpp, 3) local aor = 0 for r = 0, h - 1 do local so = base + r * stride local d = (if topDown then r else h - 1 - r) * w * 4 for x = 0, w - 1 do local s = so + x * bytes local p if bytes == 2 then p = readu16(src, s) elseif bytes == 4 then p = readu32(src, s) else p = bor(readu16(src, s), lshift(readu8(src, s + 2), 16)) end local a = band(rshift(p, sha), ma) aor = bor(aor, a) local o = d + x * 4 writeu8(dst, o, readu8(tr, band(rshift(p, shr), mr))) writeu8(dst, o + 1, readu8(tg, band(rshift(p, shg), mg))) writeu8(dst, o + 2, readu8(tb, band(rshift(p, shb), mb))) writeu8(dst, o + 3, readu8(ta, a)) end end return aor end -- 32-bit images whose alpha channel is all zero are opaque @native function Pixels.opaque(dst: buffer, n: number) for i = 0, n - 1 do writeu8(dst, i * 4 + 3, 255) end end -- RLE8 / RLE4: pixels skipped by a delta or an early end of line / bitmap stay transparent @native function Pixels.rle(src: buffer, pos: number, stop: number, rle4: boolean, dst: buffer, w: number, h: number, topDown: boolean, pal: buffer): number local x, y = 0, 0 local written = 0 local row = (if topDown then 0 else h - 1) * w * 4 local rowStep = if topDown then w * 4 else -w * 4 while y < h and pos + 1 < stop do local n = readu8(src, pos) local v = readu8(src, pos + 1) pos += 2 if n > 0 then -- encoded run: n pixels of index v (RLE4: alternating high / low nibble) local e = math.min(x + n, w) if rle4 then local hi, lo = readu32(pal, rshift(v, 4) * 4), readu32(pal, band(v, 15) * 4) for i = x, e - 1 do writeu32(dst, row + i * 4, if band(i - x, 1) == 0 then hi else lo) end else local c = readu32(pal, v * 4) for i = x, e - 1 do writeu32(dst, row + i * 4, c) end end if e > x then written += e - x end x += n elseif v == 0 then -- end of line x = 0 y += 1 row += rowStep elseif v == 1 then break -- end of bitmap elseif v == 2 then -- delta: right dx, up (in file rows) dy if pos + 1 >= stop then break end local dx, dy = readu8(src, pos), readu8(src, pos + 1) pos += 2 x += dx y += dy row += rowStep * dy else -- absolute run of v pixels, padded to a 16-bit boundary local nb = if rle4 then rshift(v + 1, 1) else v if pos + nb > stop then break end local e = math.min(x + v, w) for i = x, e - 1 do local k = i - x local idx if rle4 then local b = readu8(src, pos + rshift(k, 1)) idx = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) else idx = readu8(src, pos + k) end writeu32(dst, row + i * 4, readu32(pal, idx * 4)) end if e > x then written += e - x end x += v pos += nb + band(nb, 1) end end return written end @native function Pixels.encode24(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number) for y = 0, h - 1 do local s = y * w * 4 local d = base + (h - 1 - y) * stride for x = 0, w - 1 do local v = readu32(src, s + x * 4) writeu8(dst, d, band(rshift(v, 16), 255)) writeu8(dst, d + 1, band(rshift(v, 8), 255)) writeu8(dst, d + 2, band(v, 255)) d += 3 end end end @native function Pixels.encode32(src: buffer, w: number, h: number, dst: buffer, base: number) for y = 0, h - 1 do local s = y * w * 4 local d = base + (h - 1 - y) * w * 4 for x = 0, w - 1 do local v = readu32(src, s + x * 4) writeu32(dst, d + x * 4, bor(band(v, 0xFF00FF00), band(rshift(v, 16), 255), lshift(band(v, 255), 16))) end end end @native function Pixels.encode8(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number, idx: { [number]: number }) for y = 0, h - 1 do local s = y * w * 4 local d = base + (h - 1 - y) * stride for x = 0, w - 1 do writeu8(dst, d + x, idx[band(readu32(src, s + x * 4), 0xFFFFFF)] or 0) end end end @native function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boolean) local seen: { [number]: boolean } = {} local list: { number } = {} local alpha = false for i = 0, n - 1 do local v = readu32(src, i * 4) if v < 0xFF000000 then alpha = true end local c = band(v, 0xFFFFFF) if #list <= max and not seen[c] then seen[c] = true list[#list + 1] = c end end return list, alpha end -- a 256-entry rgba8 palette (u32 LE per entry) with entry i = { i, i, i, 255 } @native function Pixels.grey(): buffer 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 fully transparent (Quake / GoldSrc: index 255 of sprites, qpics and -- '{' textures) @native function Pixels.keyed(pal: buffer, index: number): buffer local out = buffer.create(1024) buffer.copy(out, 0, pal, 0, math.min(buffer.len(pal), 1024)) if index >= 0 and index < 256 then writeu32(out, index * 4, 0) end return out end -- palette (1024 bytes) -> { { r, g, b, a } } for codecs/image/Quantize @native function Pixels.colorList(pal: buffer, n: number?): { { number } } local out: { { number } } = {} for i = 0, math.clamp(n or 256, 0, 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 @native function Pixels.colormap(pal: buffer, cmap: buffer, base: number, row: number): buffer? 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) @native function Pixels.paletteBytes(pal: buffer, n: number?): buffer 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"] = @native function() -- codecs/image/Quantize: palette quantization of rgba8 pixels (median cut or octree, Floyd-Steinberg dithering). -- New in rosetta: Heckbert's median cut and the Gervautz-Purgathofer octree over a 5-bit-per-channel histogram; -- deterministic on every runtime (no table iteration order is relied on). local readu8, writeu8 = buffer.readu8, buffer.writeu8 local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64 local floor = math.floor local blen = buffer.len local Quantize = {} type Color = { number } type PaletteOptions = { method: ("mediancut" | "octree")?, } type MapOptions = { dither: boolean?, transparentIndex: number?, } local BINS = 32768 -- 5 bits per channel @native local function count(pixels: buffer, n: number): (buffer, buffer) -- per bin: u32 count; f64 sums of r, g, b local cnt = buffer.create(BINS * 4) local sums = buffer.create(BINS * 24) for i = 0, n - 1 do local o = i * 4 if readu8(pixels, o + 3) >= 128 then local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2) local bin = (r // 8) * 1024 + (g // 8) * 32 + b // 8 writeu32(cnt, bin * 4, readu32(cnt, bin * 4) + 1) local s = bin * 24 writef64(sums, s, readf64(sums, s) + r) writef64(sums, s + 8, readf64(sums, s + 8) + g) writef64(sums, s + 16, readf64(sums, s + 16) + b) end end return cnt, sums end @native local function mean(cnt: buffer, sums: buffer, bins: { number }, lo: number, hi: number): Color local n, r, g, b = 0, 0, 0, 0 for i = lo, hi do local bin = bins[i] n += readu32(cnt, bin * 4) r += readf64(sums, bin * 24) g += readf64(sums, bin * 24 + 8) b += readf64(sums, bin * 24 + 16) end if n == 0 then return { 0, 0, 0, 255 } end return { floor(r / n + 0.5), floor(g / n + 0.5), floor(b / n + 0.5), 255 } end @native local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color } local bins: { number } = {} for bin = 0, BINS - 1 do if readu32(cnt, bin * 4) > 0 then table.insert(bins, bin) end end if #bins == 0 then return {} end local boxes: { { number } } = {} @native local function channel(bin: number, c: number): number if c == 0 then return bin // 1024 elseif c == 1 then return (bin // 32) % 32 end return bin % 32 end @native local function stats(box: { number }): (number, number, number) local mins, maxs = { 31, 31, 31 }, { 0, 0, 0 } local n = 0 for i = box[1], box[2] do local bin = bins[i] n += readu32(cnt, bin * 4) for c = 0, 2 do local v = channel(bin, c) if v < mins[c + 1] then mins[c + 1] = v end if v > maxs[c + 1] then maxs[c + 1] = v end end end local best, range = 0, -1 for c = 0, 2 do local rg = maxs[c + 1] - mins[c + 1] if rg > range then best, range = c, rg end end return best, range, n end @native local function scored(lo: number, hi: number): { number } local c, range, n = stats({ lo, hi }) return { lo, hi, c, if hi > lo then range * math.sqrt(n) else 0 } end boxes[1] = scored(1, #bins) while #boxes < maxColors do -- split the box with the largest range * sqrt(count) score (ties: the first) local pick, pickScore = 0, 0 for i, box in boxes do if box[4] > pickScore then pick, pickScore = i, box[4] end end if pick == 0 then break end local box = boxes[pick] local lo, hi, c = box[1], box[2], box[3] -- sort the range by the channel, ties by bin number: unique numeric keys, no comparator local keys = table.create(hi - lo + 1) :: { number } for i = lo, hi do keys[i - lo + 1] = channel(bins[i], c) * BINS + bins[i] end table.sort(keys) local total = 0 for i = 1, #keys do local bin = keys[i] % BINS bins[lo + i - 1] = bin total += readu32(cnt, bin * 4) end -- the weighted median, keeping both halves non-empty local acc, cut = 0, lo for i = lo, hi - 1 do acc += readu32(cnt, bins[i] * 4) cut = i if acc * 2 >= total then break end end boxes[pick] = scored(lo, cut) table.insert(boxes, scored(cut + 1, hi)) end local pal = table.create(#boxes) :: { Color } for i, box in boxes do pal[i] = mean(cnt, sums, bins, box[1], box[2]) end return pal end -- octree over the histogram bins: 5 levels, one bit of each channel per level @native local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color } local child: { number } = {} -- node * 8 + k -> node (0 = none) local n: { number } = {} local sr: { number }, sg: { number }, sb: { number } = {}, {}, {} local leaf: { boolean } = {} local level: { number } = {} local nodes = 1 n[1], sr[1], sg[1], sb[1], leaf[1], level[1] = 0, 0, 0, 0, false, 0 for k = 1, 8 do child[k] = 0 end local byLevel: { { number } } = { {}, {}, {}, {}, {} } table.insert(byLevel[1], 1) local leaves = 0 for bin = 0, BINS - 1 do local c = readu32(cnt, bin * 4) if c > 0 then local r5, g5, b5 = bin // 1024, (bin // 32) % 32, bin % 32 local node = 1 for lv = 0, 4 do local sh = 4 - lv local k = ((r5 // 2 ^ sh) % 2) * 4 + ((g5 // 2 ^ sh) % 2) * 2 + (b5 // 2 ^ sh) % 2 local slot = (node - 1) * 8 + k + 1 local nx = child[slot] if nx == 0 then nodes += 1 nx = nodes child[slot] = nx for j = 1, 8 do child[(nx - 1) * 8 + j] = 0 end n[nx], sr[nx], sg[nx], sb[nx], level[nx] = 0, 0, 0, 0, lv + 1 leaf[nx] = lv == 4 if lv == 4 then leaves += 1 else table.insert(byLevel[lv + 2], nx) end end node = nx end n[node] += c sr[node] += readf64(sums, bin * 24) sg[node] += readf64(sums, bin * 24 + 8) sb[node] += readf64(sums, bin * 24 + 16) end end -- fold the deepest inner nodes (fewest pixels first, ties by creation order) until few enough leaves remain @native local function fold(node: number): number local merged = 0 for k = 1, 8 do local slot = (node - 1) * 8 + k local ch = child[slot] if ch ~= 0 then n[node] += n[ch] sr[node] += sr[ch] sg[node] += sg[ch] sb[node] += sb[ch] child[slot] = 0 merged += 1 end end leaf[node] = true return merged - 1 end @native local function subtotal(node: number): number local s = 0 for k = 1, 8 do local ch = child[(node - 1) * 8 + k] if ch ~= 0 then s += n[ch] end end return s end for lv = 5, 1, -1 do if leaves <= maxColors then break end local list = byLevel[lv] local order = table.create(#list) :: { { any } } for i, node in list do order[i] = { node, subtotal(node), i } end table.sort(order, @native function(a: { number }, b: { number }): boolean if a[2] ~= b[2] then return a[2] < b[2] end return a[3] < b[3] end) for _, e in order do if leaves <= maxColors then break end leaves -= fold(e[1]) end end local pal: { Color } = {} @native local function walk(node: number) if leaf[node] then local c = n[node] if c > 0 then table.insert(pal, { floor(sr[node] / c + 0.5), floor(sg[node] / c + 0.5), floor(sb[node] / c + 0.5), 255 }) end return end for k = 1, 8 do local ch = child[(node - 1) * 8 + k] if ch ~= 0 then walk(ch) end end end walk(1) -- the root itself can end up a leaf with everything (maxColors 1) while #pal > maxColors do table.remove(pal) end return pal end @native function Quantize.palette(pixels: buffer, w: number, h: number, maxColors: number, opts: PaletteOptions?): ({ Color }, boolean) if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 then return {}, false end local maxc = math.clamp(floor(tonumber(maxColors) or 256), 1, 65536) local npx = w * h local seen: { [number]: boolean } = {} local exact: { Color } = {} local over = false for i = 0, npx - 1 do local o = i * 4 if readu8(pixels, o + 3) >= 128 then local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2) local key = r * 65536 + g * 256 + b if not seen[key] then if #exact >= maxc then over = true break end seen[key] = true table.insert(exact, { r, g, b, 255 }) end end end if not over then return exact, true end local cnt, sums = count(pixels, npx) local method = opts and opts.method or "mediancut" if method == "octree" and maxc >= 8 then -- below 8 the octree can only fold to a single colour return octree(cnt, sums, maxc), false end return medianCut(cnt, sums, maxc), false end @native function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, opts: MapOptions?): buffer if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 or type(palette) ~= "table" then return buffer.create(0) end local npx = w * h local out = buffer.create(npx) local dither = opts and opts.dither or false local tidx = opts and opts.transparentIndex local pr: { number }, pg: { number }, pb: { number }, pi: { number } = {}, {}, {}, {} for i, c in palette do if tidx == nil or i - 1 ~= tidx then table.insert(pr, c[1] or 0) table.insert(pg, c[2] or 0) table.insert(pb, c[3] or 0) table.insert(pi, i - 1) end end local np = #pr -- sorted by green (the heaviest weight), so the search can stop once 4 * dg^2 alone is worse than the best do local order = table.create(np) :: { number } for k = 1, np do order[k] = pg[k] * 65536 + k end table.sort(order) local r2, g2, b2, i2 = table.create(np) :: { number }, table.create(np) :: { number }, table.create(np) :: { number }, table.create(np) :: { number } for k = 1, np do local j = order[k] % 65536 r2[k], g2[k], b2[k], i2[k] = pr[j], pg[j], pb[j], pi[j] end pr, pg, pb, pi = r2, g2, b2, i2 end local startAt = table.create(256, np) do local k = 1 for g = 0, 255 do while k <= np and pg[k] < g do k += 1 end startAt[g + 1] = k end end if np == 0 then if tidx then buffer.fill(out, 0, math.clamp(tidx, 0, 255), npx) end return out end local cache: { [number]: number } = {} @native local function nearest(r: number, g: number, b: number): number local key = r * 65536 + g * 256 + b local hit = cache[key] if hit then return hit end local best, bd = 1, math.huge local up = startAt[math.clamp(g, 0, 255) + 1] local down = up - 1 while up <= np or down >= 1 do if up <= np then local dg = pg[up] - g if dg * dg * 4 >= bd then up = np + 1 else local dr, db = r - pr[up], b - pb[up] local d = dr * dr * 2 + dg * dg * 4 + db * db * 3 if d < bd then best, bd = up, d end up += 1 end end if down >= 1 then local dg = g - pg[down] if dg * dg * 4 >= bd then down = 0 else local dr, db = r - pr[down], b - pb[down] local d = dr * dr * 2 + dg * dg * 4 + db * db * 3 if d < bd then best, bd = down, d end down -= 1 end end end cache[key] = best return best end local tbyte = if tidx then math.clamp(tidx, 0, 255) else 0 if not dither then for i = 0, npx - 1 do local o = i * 4 if tidx and readu8(pixels, o + 3) < 128 then writeu8(out, i, tbyte) else writeu8(out, i, pi[nearest(readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2))]) end end return out end local rowLen = (w + 2) * 24 local cur, nxt = buffer.create(rowLen), buffer.create(rowLen) for y = 0, h - 1 do buffer.fill(nxt, 0, 0, rowLen) for x = 0, w - 1 do local i = y * w + x local o = i * 4 if tidx and readu8(pixels, o + 3) < 128 then writeu8(out, i, tbyte) else local e = (x + 1) * 24 local r = math.clamp(floor(readu8(pixels, o) + readf64(cur, e) + 0.5), 0, 255) local g = math.clamp(floor(readu8(pixels, o + 1) + readf64(cur, e + 8) + 0.5), 0, 255) local b = math.clamp(floor(readu8(pixels, o + 2) + readf64(cur, e + 16) + 0.5), 0, 255) local k = nearest(r, g, b) writeu8(out, i, pi[k]) local er, eg, eb = r - pr[k], g - pg[k], b - pb[k] -- 7/16 right, 3/16 down-left, 5/16 down, 1/16 down-right writef64(cur, e + 24, readf64(cur, e + 24) + er * 0.4375) writef64(cur, e + 32, readf64(cur, e + 32) + eg * 0.4375) writef64(cur, e + 40, readf64(cur, e + 40) + eb * 0.4375) writef64(nxt, e - 24, readf64(nxt, e - 24) + er * 0.1875) writef64(nxt, e - 16, readf64(nxt, e - 16) + eg * 0.1875) writef64(nxt, e - 8, readf64(nxt, e - 8) + eb * 0.1875) writef64(nxt, e, readf64(nxt, e) + er * 0.3125) writef64(nxt, e + 8, readf64(nxt, e + 8) + eg * 0.3125) writef64(nxt, e + 16, readf64(nxt, e + 16) + eb * 0.3125) writef64(nxt, e + 24, readf64(nxt, e + 24) + er * 0.0625) writef64(nxt, e + 32, readf64(nxt, e + 32) + eg * 0.0625) writef64(nxt, e + 40, readf64(nxt, e + 40) + eb * 0.0625) end end cur, nxt = nxt, cur end return out end @native function Quantize.quantize(pixels: buffer, w: number, h: number, maxColors: number, opts: any?): (buffer, { Color }, boolean) local pal, exact = Quantize.palette(pixels, w, h, maxColors, opts) local mo = opts if exact and opts and opts.dither then mo = table.clone(opts) mo.dither = false end return Quantize.map(pixels, w, h, pal, mo), pal, exact end return Quantize end __FILES["codecs/image/Raster"] = @native function() -- codecs/image/Raster: an antialiased scanline rasterizer (nonzero / even-odd) for line and Bézier paths, plus a stroker. -- New code; the signed-area accumulation follows font-rs (Raph Levien, Apache-2.0 / MIT; algorithm only) and stb_truetype -- v2, and the summed coverage a maps as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2. local Raster = {} local floor, ceil, min, max, abs, sqrt = math.floor, math.ceil, math.min, math.max, math.abs, math.sqrt local readf32, writef32, readu8, writeu8 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8 local bcreate = buffer.create type Cmd = { op: string, [number]: number } type Path = { Cmd } type Transform = { number } type Mask = { x: number, y: number, width: number, height: number, coverage: buffer } type Options = { transform: Transform?, rule: ("nonzero" | "evenodd")?, clip: { number }?, tolerance: number?, maxPixels: number?, opacity: number?, } local LIMIT = 1e7 -- coordinates beyond this (device pixels) are treated as broken -- transforms { a, b, c, d, e, f } in SVG matrix order: x' = a x + c y + e, y' = b x + d y + f Raster.IDENTITY = table.freeze({ 1, 0, 0, 1, 0, 0 }) @native function Raster.multiply(m: Transform, n: Transform): Transform return { m[1] * n[1] + m[3] * n[2], m[2] * n[1] + m[4] * n[2], m[1] * n[3] + m[3] * n[4], m[2] * n[3] + m[4] * n[4], m[1] * n[5] + m[3] * n[6] + m[5], m[2] * n[5] + m[4] * n[6] + m[6], } end @native function Raster.translate(tx: number, ty: number): Transform return { 1, 0, 0, 1, tx, ty } end @native function Raster.scale(sx: number, sy: number?): Transform return { sx, 0, 0, sy or sx, 0, 0 } end @native function Raster.rotate(radians: number): Transform local c, s = math.cos(radians), math.sin(radians) return { c, s, -s, c, 0, 0 } end @native function Raster.invert(m: Transform): Transform? local det = m[1] * m[4] - m[2] * m[3] if det == 0 or det ~= det then return nil end local id = 1 / det local a, b, c, d = m[4] * id, -m[2] * id, -m[3] * id, m[1] * id return { a, b, c, d, -(a * m[5] + c * m[6]), -(b * m[5] + d * m[6]) } end @native function Raster.apply(m: Transform, x: number, y: number): (number, number) return m[1] * x + m[3] * y + m[5], m[2] * x + m[4] * y + m[6] end local Builder = {} Builder.__index = Builder type Builder = typeof(setmetatable({} :: { cmds: Path }, Builder)) @native function Raster.path(): Builder return setmetatable({ cmds = {} :: Path }, Builder) end @native function Builder.moveTo(self: Builder, x: number, y: number): Builder table.insert(self.cmds, { op = "moveTo", x, y }) return self end @native function Builder.lineTo(self: Builder, x: number, y: number): Builder table.insert(self.cmds, { op = "lineTo", x, y }) return self end @native function Builder.quadTo(self: Builder, cx: number, cy: number, x: number, y: number): Builder table.insert(self.cmds, { op = "quadTo", cx, cy, x, y }) return self end @native function Builder.cubicTo(self: Builder, c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): Builder table.insert(self.cmds, { op = "cubicTo", c1x, c1y, c2x, c2y, x, y }) return self end @native function Builder.close(self: Builder): Builder table.insert(self.cmds, { op = "close" } :: Cmd) return self end @native function Builder.rect(self: Builder, x: number, y: number, w: number, h: number): Builder return self:moveTo(x, y):lineTo(x + w, y):lineTo(x + w, y + h):lineTo(x, y + h):close() end @native function Builder.ellipse(self: Builder, cx: number, cy: number, rx: number, ry: number): Builder local k = 0.5522847498307936 -- 4/3 (sqrt 2 - 1): cubic quarter circle self:moveTo(cx + rx, cy) self:cubicTo(cx + rx, cy + ry * k, cx + rx * k, cy + ry, cx, cy + ry) self:cubicTo(cx - rx * k, cy + ry, cx - rx, cy + ry * k, cx - rx, cy) self:cubicTo(cx - rx, cy - ry * k, cx - rx * k, cy - ry, cx, cy - ry) self:cubicTo(cx + rx * k, cy - ry, cx + rx, cy - ry * k, cx + rx, cy) return self:close() end @native local function commands(path: any): Path? if type(path) ~= "table" then return nil end if type(path.cmds) == "table" then return path.cmds end return path end @native local function operands(c: any, n: number): boolean if type(c) ~= "table" then return false end for i = 1, n do local v = c[i] if type(v) ~= "number" or v ~= v or abs(v) > 1e15 then return false end end return true end @native local function flatten(path: any, transform: Transform?, tolerance: number?, minLen: number): ({ { number } }, number?, number?, number?, number?) local cmds = commands(path) local polys: { { number } } = {} if not cmds then return polys, nil, nil, nil, nil end local m = transform or Raster.IDENTITY local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6] if type(a) ~= "number" or type(b) ~= "number" or type(c) ~= "number" or type(d) ~= "number" or type(e) ~= "number" or type(f) ~= "number" then return polys, nil, nil, nil, nil end local tol = tolerance or 0.1 if type(tol) ~= "number" or not (tol > 0.001) then tol = 0.1 end local cur: { number }? = nil local px, py = 0, 0 local sx, sy = 0, 0 local bx0, by0, bx1, by1 = math.huge, math.huge, -math.huge, -math.huge @native local function point(x: number, y: number) local poly = cur :: { number } local n = #poly poly[n + 1] = x poly[n + 2] = y if x < bx0 then bx0 = x end if x > bx1 then bx1 = x end if y < by0 then by0 = y end if y > by1 then by1 = y end end @native local function start(x: number, y: number) if cur and #cur >= minLen then table.insert(polys, cur) end cur = {} point(x, y) sx, sy = x, y px, py = x, y end for _, cmd in cmds do local op = if type(cmd) == "table" then cmd.op else nil if op == "moveTo" then if operands(cmd, 2) then start(a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f) end elseif op == "lineTo" then if operands(cmd, 2) then if not cur then start(px, py) end px, py = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f point(px, py) end elseif op == "quadTo" then if operands(cmd, 4) then if not cur then start(px, py) end local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f local ddx, ddy = px - 2 * x1 + x2, py - 2 * y1 + y2 local n = ceil(sqrt(sqrt(ddx * ddx + ddy * ddy) * 0.25 / tol)) n = if n ~= n then 1 else max(1, min(n, 500)) local x0, y0 = px, py for i = 1, n - 1 do local t = i / n local u = 1 - t point(u * u * x0 + 2 * u * t * x1 + t * t * x2, u * u * y0 + 2 * u * t * y1 + t * t * y2) end point(x2, y2) px, py = x2, y2 end elseif op == "cubicTo" then if operands(cmd, 6) then if not cur then start(px, py) end local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f local x3, y3 = a * cmd[5] + c * cmd[6] + e, b * cmd[5] + d * cmd[6] + f local ax, ay = px - 2 * x1 + x2, py - 2 * y1 + y2 local bxx, byy = x1 - 2 * x2 + x3, y1 - 2 * y2 + y3 local dd = max(sqrt(ax * ax + ay * ay), sqrt(bxx * bxx + byy * byy)) local n = ceil(sqrt(dd * 0.75 / tol)) n = if n ~= n then 1 else max(1, min(n, 500)) local x0, y0 = px, py for i = 1, n - 1 do local t = i / n local u = 1 - t local w0, w1, w2, w3 = u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t point(w0 * x0 + w1 * x1 + w2 * x2 + w3 * x3, w0 * y0 + w1 * y1 + w2 * y2 + w3 * y3) end point(x3, y3) px, py = x3, y3 end elseif op == "close" then if cur then if #cur >= minLen then table.insert(polys, cur) end cur = nil px, py = sx, sy end end end if cur and #cur >= minLen then table.insert(polys, cur) end if #polys == 0 or bx0 ~= bx0 or by0 ~= by0 or bx1 ~= bx1 or by1 ~= by1 then return polys, nil, nil, nil, nil end return polys, bx0, by0, bx1, by1 end @native function Raster.flatten(path: any, transform: Transform?, tolerance: number?): ({ { number } }, number?, number?, number?, number?) return flatten(path, transform, tolerance, 6) end -- the signed area each pixel gains from one edge (font-rs draw_line) @native local function line(acc: buffer, S: number, H: number, x0: number, y0: number, x1: number, y1: number) if y0 == y1 then return end local W = S - 2 local xl, xr = 0, W -- x stays in [0, W] (rounding in the splits and in x + dxdy * dy must never index outside) local dir = 1 if y0 > y1 then dir = -1 x0, x1 = x1, x0 y0, y1 = y1, y0 end if y1 <= 0 or y0 >= H then return end local dxdy = (x1 - x0) / (y1 - y0) local x = x0 if y0 < 0 then x -= y0 * dxdy end local ystart = max(0, floor(y0)) local yend = min(H, ceil(y1)) - 1 for y = ystart, yend do local ls = y * S local dy = min(y + 1, y1) - max(y, y0) local xnext = x + dxdy * dy if xnext < xl then xnext = xl elseif xnext > xr then xnext = xr end if x < xl then x = xl elseif x > xr then x = xr end local dd = dy * dir local xa, xb = x, xnext if xa > xb then xa, xb = xb, xa end local xaf = floor(xa) local xai = xaf local xbc = ceil(xb) local xbi = xbc if xbi <= xai + 1 then local xmf = 0.5 * (x + xnext) - xaf local o = (ls + xai) * 4 writef32(acc, o, readf32(acc, o) + dd - dd * xmf) writef32(acc, o + 4, readf32(acc, o + 4) + dd * xmf) else local s = 1 / (xb - xa) local x0f = xa - xaf local a0 = 0.5 * s * (1 - x0f) * (1 - x0f) local x1f = xb - xbc + 1 local am = 0.5 * s * x1f * x1f local o = (ls + xai) * 4 writef32(acc, o, readf32(acc, o) + dd * a0) if xbi == xai + 2 then writef32(acc, o + 4, readf32(acc, o + 4) + dd * (1 - a0 - am)) else local a1 = s * (1.5 - x0f) writef32(acc, o + 4, readf32(acc, o + 4) + dd * (a1 - a0)) local ds = dd * s for xi = xai + 2, xbi - 2 do local q = (ls + xi) * 4 writef32(acc, q, readf32(acc, q) + ds) end local a2 = a1 + (xbi - xai - 3) * s local q = (ls + xbi - 1) * 4 writef32(acc, q, readf32(acc, q) + dd * (1 - a2 - am)) end local q = (ls + xbi) * 4 writef32(acc, q, readf32(acc, q) + dd * am) end x = xnext end end -- edges split at x = 0 / x = W: the parts outside go onto the border, whose cover still applies to the row @native local function clampx(x: number, W: number): number return if x < 0 then 0 elseif x > W then W else x end @native local function edge(acc: buffer, S: number, W: number, H: number, x0: number, y0: number, x1: number, y1: number) if y0 == y1 or not (abs(x0) < LIMIT and abs(y0) < LIMIT and abs(x1) < LIMIT and abs(y1) < LIMIT) then return -- horizontal, or non-finite (NaN fails every comparison) end if (y0 <= 0 and y1 <= 0) or (y0 >= H and y1 >= H) then return end local dx = x1 - x0 local ta, tb = 2, 2 if dx ~= 0 then local t0 = (0 - x0) / dx local tw = (W - x0) / dx if t0 > 0 and t0 < 1 then ta = t0 end if tw > 0 and tw < 1 then tb = tw end if ta > tb then ta, tb = tb, ta end end local dy = y1 - y0 local px, py = x0, y0 if ta < 1 then local qx, qy = x0 + dx * ta, y0 + dy * ta line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy) px, py = qx, qy end if tb < 1 then local qx, qy = x0 + dx * tb, y0 + dy * tb line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy) px, py = qx, qy end line(acc, S, H, clampx(px, W), py, clampx(x1, W), y1) end @native function Raster.mask(path: any, opts: Options?): (Mask?, string?) local o: Options = opts or {} local polys, bx0, by0, bx1, by1 = Raster.flatten(path, o.transform, o.tolerance) if not bx0 then return nil, nil end if abs(bx0 :: number) > LIMIT or abs(by0 :: number) > LIMIT or abs(bx1 :: number) > LIMIT or abs(by1 :: number) > LIMIT then return nil, "coordinates out of range" end local X0, Y0, X1, Y1 = floor(bx0 :: number), floor(by0 :: number), ceil(bx1 :: number), ceil(by1 :: number) local clip = o.clip if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then Y0 = max(Y0, floor(clip[2])) Y1 = min(Y1, ceil(clip[4])) X1 = min(X1, ceil(clip[3])) local cx0 = floor(clip[1]) X0 = max(X0, cx0) end local W, H = X1 - X0, Y1 - Y0 if W <= 0 or H <= 0 then return nil, nil end local maxPixels = if type(o.maxPixels) == "number" then o.maxPixels else 2 ^ 26 if W * H > maxPixels then return nil, "limit" end local S = W + 2 local acc = bcreate(S * H * 4) for _, poly in polys do local n = #poly local lx, ly = poly[n - 1] - X0, poly[n] - Y0 for i = 1, n - 1, 2 do local x, y = poly[i] - X0, poly[i + 1] - Y0 edge(acc, S, W, H, lx, ly, x, y) lx, ly = x, y end end local cov = bcreate(W * H) local evenodd = o.rule == "evenodd" for y = 0, H - 1 do local sum = 0 local ls = y * S local os = y * W for x = 0, W - 1 do sum += readf32(acc, (ls + x) * 4) local v = abs(sum) if evenodd then v = v % 2 if v > 1 then v = 2 - v end elseif v > 1 then v = 1 end writeu8(cov, os + x, floor(v * 255 + 0.5)) end end return { x = X0, y = Y0, width = W, height = H, coverage = cov }, nil end @native function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean, string?) if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then return false, "fill: expected an rgba8 image" end local iw, ih = img.width, img.height local px = img.pixels if buffer.len(px) < iw * ih * 4 then return false, "fill: image pixels too short" end local o: Options = table.clone(opts or {} :: Options) local clip = o.clip if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then o.clip = { max(0, clip[1]), max(0, clip[2]), min(iw, clip[3]), min(ih, clip[4]) } else o.clip = { 0, 0, iw, ih } end local m, why = Raster.mask(path, o) if not m then return why == nil, why end local opacity = if type(o.opacity) == "number" then math.clamp(o.opacity, 0, 1) else 1 local fn: any = nil local cr, cg, cb, ca = 0, 0, 0, 255 if type(paint) == "function" then fn = paint elseif type(paint) == "table" then cr, cg, cb = tonumber(paint[1]) or 0, tonumber(paint[2]) or 0, tonumber(paint[3]) or 0 ca = tonumber(paint[4]) or 255 else return false, "fill: paint must be a colour or a function" end local cov = m.coverage local mw = m.width for y = 0, m.height - 1 do local iy = m.y + y for x = 0, mw - 1 do local cv = readu8(cov, y * mw + x) if cv > 0 then local ix = m.x + x local r, g, b, a = cr, cg, cb, ca if fn then local ok, r2, g2, b2, a2 = pcall(fn, ix + 0.5, iy + 0.5) if not ok then return false, "fill: paint function failed" end r, g, b, a = tonumber(r2) or 0, tonumber(g2) or 0, tonumber(b2) or 0, tonumber(a2) or 255 end local sa = math.clamp(a, 0, 255) / 255 * cv / 255 * opacity if sa > 0 then local p = (iy * iw + ix) * 4 local da = readu8(px, p + 3) / 255 local oa = sa + da * (1 - sa) local k = da * (1 - sa) writeu8(px, p, floor((math.clamp(r, 0, 255) * sa + readu8(px, p) * k) / oa + 0.5)) writeu8(px, p + 1, floor((math.clamp(g, 0, 255) * sa + readu8(px, p + 1) * k) / oa + 0.5)) writeu8(px, p + 2, floor((math.clamp(b, 0, 255) * sa + readu8(px, p + 2) * k) / oa + 0.5)) writeu8(px, p + 3, floor(oa * 255 + 0.5)) end end end end return true, nil end type StrokeOptions = { width: number?, join: ("miter" | "round" | "bevel")?, cap: ("butt" | "round" | "square")?, miterLimit: number?, tolerance: number?, closed: boolean?, } -- push a polygon (flat x, y list) as a closed subpath with positive orientation, so overlapping pieces add up -- under the nonzero rule @native local function polygon(out: Path, pts: { number }) local n = #pts if n < 6 then return end local area = 0 for i = 1, n - 1, 2 do local j = if i + 2 > n then 1 else i + 2 area += pts[i] * pts[j + 1] - pts[j] * pts[i + 1] end if area == 0 then return end if area > 0 then table.insert(out, { op = "moveTo", pts[1], pts[2] }) for i = 3, n - 1, 2 do table.insert(out, { op = "lineTo", pts[i], pts[i + 1] }) end else table.insert(out, { op = "moveTo", pts[n - 1], pts[n] }) for i = n - 3, 1, -2 do table.insert(out, { op = "lineTo", pts[i], pts[i + 1] }) end end table.insert(out, { op = "close" } :: Cmd) end @native local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: number, tol: number, pts: { number }) local da = a1 - a0 local step = 2 * math.acos(math.clamp(1 - tol / max(r, 1e-9), -1, 1)) local n = max(1, min(256, ceil(abs(da) / max(step, 0.01)))) for i = 0, n do local t = a0 + da * i / n table.insert(pts, cx + r * math.cos(t)) table.insert(pts, cy + r * math.sin(t)) end end @native function Raster.stroke(path: any, opts: StrokeOptions?): Path local o: StrokeOptions = opts or {} local hw = (if type(o.width) == "number" and o.width > 0 then o.width else 1) / 2 local join = o.join or "miter" local cap = o.cap or "butt" local miterLimit = if type(o.miterLimit) == "number" and o.miterLimit >= 1 then o.miterLimit else 4 local tol = if type(o.tolerance) == "number" and o.tolerance > 0.0005 then o.tolerance else 0.1 local out: Path = {} local cmds = commands(path) if not cmds then return out end -- subpaths with their closed flag (flatten loses it, so split here) local subs: { { cmds: Path, closed: boolean } } = {} local cur: Path? = nil local lx, ly = 0, 0 for _, c in cmds do local op = if type(c) == "table" then c.op else nil if op == "moveTo" and operands(c, 2) then cur = { c } table.insert(subs, { cmds = cur :: Path, closed = o.closed == true }) lx, ly = c[1], c[2] elseif op == "close" then if cur then subs[#subs].closed = true cur = nil end elseif op == "lineTo" or op == "quadTo" or op == "cubicTo" then if not cur then cur = { { op = "moveTo", lx, ly } } table.insert(subs, { cmds = cur :: Path, closed = o.closed == true }) end table.insert(cur :: Path, c) end end for _, sub in subs do local polys = flatten(sub.cmds, nil, tol, 4) local pts = polys[1] if not pts then -- a degenerate subpath (a single point): round / square caps draw a dot local m = sub.cmds[1] if #sub.cmds >= 1 and operands(m, 2) and cap ~= "butt" then local d = {} if cap == "round" then arcPoints(m[1], m[2], hw, 0, 2 * math.pi, tol, d) else d = { m[1] - hw, m[2] - hw, m[1] + hw, m[2] - hw, m[1] + hw, m[2] + hw, m[1] - hw, m[2] + hw } end polygon(out, d) end continue end local p: { number } = { pts[1], pts[2] } for i = 3, #pts - 1, 2 do if abs(pts[i] - p[#p - 1]) > 1e-9 or abs(pts[i + 1] - p[#p]) > 1e-9 then table.insert(p, pts[i]) table.insert(p, pts[i + 1]) end end local closed = sub.closed if closed and #p >= 4 and abs(p[1] - p[#p - 1]) < 1e-9 and abs(p[2] - p[#p]) < 1e-9 then table.remove(p) table.remove(p) end local n = #p // 2 if n < 2 then continue end local segs = if closed then n else n - 1 local dirs: { number } = {} for s = 0, segs - 1 do local i, j = s, (s + 1) % n local x0, y0, x1, y1 = p[2 * i + 1], p[2 * i + 2], p[2 * j + 1], p[2 * j + 2] local dx, dy = x1 - x0, y1 - y0 local len = sqrt(dx * dx + dy * dy) local ux, uy = dx / len, dy / len dirs[2 * s + 1], dirs[2 * s + 2] = ux, uy local nx, ny = -uy * hw, ux * hw polygon(out, { x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny }) end @native local function joinAt(k: number, s0: number, s1: number) local x, y = p[2 * k + 1], p[2 * k + 2] local ax, ay = dirs[2 * s0 + 1], dirs[2 * s0 + 2] local bx, by = dirs[2 * s1 + 1], dirs[2 * s1 + 2] local cross = ax * by - ay * bx if abs(cross) < 1e-12 and ax * bx + ay * by > 0 then return end -- the outer side: left normals when turning right (cross < 0) local sgn = if cross < 0 then 1 else -1 local n0x, n0y = -ay * hw * sgn, ax * hw * sgn local n1x, n1y = -by * hw * sgn, bx * hw * sgn if join == "round" then local d = { x, y } local a0 = math.atan2(n0y, n0x) local a1 = math.atan2(n1y, n1x) local da = a1 - a0 while da > math.pi do da -= 2 * math.pi end while da < -math.pi do da += 2 * math.pi end arcPoints(x, y, hw, a0, a0 + da, tol, d) polygon(out, d) else local cosT = ax * bx + ay * by local miter = if join == "miter" then 1 / sqrt(max(1e-12, (1 + cosT) / 2)) else math.huge if join == "miter" and miter <= miterLimit then local mx, my = n0x + n1x, n0y + n1y local ml = sqrt(mx * mx + my * my) if ml > 1e-12 then local scale = hw * miter / ml polygon(out, { x, y, x + n0x, y + n0y, x + mx * scale, y + my * scale, x + n1x, y + n1y }) return end end polygon(out, { x, y, x + n0x, y + n0y, x + n1x, y + n1y }) end end if closed then for k = 0, n - 1 do joinAt(k, (k - 1) % n, k) end else for k = 1, n - 2 do joinAt(k, k - 1, k) end if cap ~= "butt" then for _, endInfo in { { 0, 0, -1 }, { n - 1, segs - 1, 1 } } do local k, s, sgn = endInfo[1], endInfo[2], endInfo[3] local x, y = p[2 * k + 1], p[2 * k + 2] local ux, uy = dirs[2 * s + 1] * sgn, dirs[2 * s + 2] * sgn local nx, ny = -uy * hw, ux * hw if cap == "square" then polygon(out, { x + nx, y + ny, x + nx + ux * hw, y + ny + uy * hw, x - nx + ux * hw, y - ny + uy * hw, x - nx, y - ny }) else local d = {} local a0 = math.atan2(ny, nx) arcPoints(x, y, hw, a0, a0 - math.pi, tol, d) polygon(out, d) end end end end end return out end return Raster end __FILES["codecs/image/Texel"] = @native function() -- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats. New in rosetta. -- Names list channels from the lowest address / bit up (DXGI order); snorm -> rgba8 is biased (8-bit: s + 128). local Half = __include("codecs/image/Half") local Texel = {} type Channel = { c: string, shift: number, bits: number } type Desc = { bytes: number, kind: "array" | "packed" | "r11g11b10f" | "rgb9e5" | "pair" | "ayuv", size: number?, type: string?, order: string?, channels: { Channel }?, } local readu8, readu16, readu32, readi8, readi16, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readf32 local writeu8, writeu16, writeu32, writef32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writef32 local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local HALF = Half.TABLE local FORMATS: { [string]: Desc } = {} @native local function array(name: string, size: number, typ: string, order: string) FORMATS[name] = { bytes = size * #order, kind = "array", size = size, type = typ, order = order } end for _, o in { "r", "rg", "rgb", "rgba" } do array(o .. "8", 1, "unorm", o) array(o .. "8s", 1, "snorm", o) array(o .. "8ui", 1, "uint", o) array(o .. "8i", 1, "sint", o) array(o .. "16", 2, "unorm", o) array(o .. "16s", 2, "snorm", o) array(o .. "16ui", 2, "uint", o) array(o .. "16i", 2, "sint", o) array(o .. "16f", 2, "float", o) array(o .. "32ui", 4, "uint", o) array(o .. "32i", 4, "sint", o) array(o .. "32f", 4, "float", o) end array("bgr8", 1, "unorm", "bgr") array("bgra8", 1, "unorm", "bgra") array("bgrx8", 1, "unorm", "bgrx") array("rgbx8", 1, "unorm", "rgbx") array("a8", 1, "unorm", "a") array("l8", 1, "unorm", "l") array("la8", 1, "unorm", "la") array("l16", 2, "unorm", "l") array("la16", 2, "unorm", "la") array("a16", 2, "unorm", "a") @native local function packed(name: string, bytes: number, spec: { any }) local ch: { Channel } = {} for i = 1, #spec, 3 do table.insert(ch, { c = spec[i], shift = spec[i + 1], bits = spec[i + 2] }) end FORMATS[name] = { bytes = bytes, kind = "packed", channels = ch } end packed("b5g6r5", 2, { "b", 0, 5, "g", 5, 6, "r", 11, 5 }) packed("r5g6b5", 2, { "r", 0, 5, "g", 5, 6, "b", 11, 5 }) packed("b5g5r5a1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5, "a", 15, 1 }) packed("b5g5r5x1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5 }) packed("a1b5g5r5", 2, { "a", 0, 1, "b", 1, 5, "g", 6, 5, "r", 11, 5 }) packed("a1r5g5b5", 2, { "a", 0, 1, "r", 1, 5, "g", 6, 5, "b", 11, 5 }) packed("b4g4r4a4", 2, { "b", 0, 4, "g", 4, 4, "r", 8, 4, "a", 12, 4 }) packed("r4g4b4a4", 2, { "r", 0, 4, "g", 4, 4, "b", 8, 4, "a", 12, 4 }) packed("a4b4g4r4", 2, { "a", 0, 4, "b", 4, 4, "g", 8, 4, "r", 12, 4 }) packed("a4r4g4b4", 2, { "a", 0, 4, "r", 4, 4, "g", 8, 4, "b", 12, 4 }) packed("rgb10a2", 4, { "r", 0, 10, "g", 10, 10, "b", 20, 10, "a", 30, 2 }) packed("bgr10a2", 4, { "b", 0, 10, "g", 10, 10, "r", 20, 10, "a", 30, 2 }) packed("r3g3b2", 1, { "b", 0, 2, "g", 2, 3, "r", 5, 3 }) FORMATS.r11g11b10f = { bytes = 4, kind = "r11g11b10f" } FORMATS.rgb9e5 = { bytes = 4, kind = "rgb9e5" } -- 4:2:2 pairs (2 pixels in 4 bytes; bytes = per pixel) and 4:4:4 AYUV (bytes V U Y A); Y'CbCr is BT.601 limited range FORMATS.yuy2 = { bytes = 2, kind = "pair", order = "yuyv" } FORMATS.uyvy = { bytes = 2, kind = "pair", order = "uyvy" } FORMATS.rgbg = { bytes = 2, kind = "pair", order = "rgbg" } FORMATS.grgb = { bytes = 2, kind = "pair", order = "grgb" } FORMATS.ayuv = { bytes = 4, kind = "ayuv" } Texel.FORMATS = FORMATS @native function Texel.masked(bytes: number, r: number, g: number, b: number, a: number, luminance: boolean?): Desc? if bytes < 1 or bytes > 4 then return nil end local ch: { Channel } = {} for i, m in { r, g, b, a } do if m ~= 0 then local shift = 0 while band(m, lshift(1, shift)) == 0 and shift < 31 do shift += 1 end local bits = 0 while shift + bits < 32 and band(m, lshift(1, shift + bits)) ~= 0 do bits += 1 end local name = if i == 1 then (if luminance then "l" else "r") elseif i == 2 then "g" elseif i == 3 then "b" else "a" table.insert(ch, { c = name, shift = shift, bits = bits }) end end if #ch == 0 then return nil end return { bytes = bytes, kind = "packed", channels = ch } end @native function Texel.size(fmt: string | Desc, w: number, h: number): number? local d = if type(fmt) == "string" then FORMATS[fmt] else fmt if not d then return nil end return if d.kind == "pair" then ((w + 1) // 2) * 4 * h else d.bytes * w * h end @native local function nativeOf(d: Desc): string if d.kind == "array" then local t, s = d.type, d.size :: number if t == "float" or t == "snorm" or t == "sint" or (t == "uint" and s > 1) then return "rgbaf32" end return if s == 1 then "rgba8" else "rgba16" elseif d.kind == "packed" then local wide = false for _, c in d.channels :: { Channel } do wide = wide or c.bits > 8 end return if wide then "rgba16" else "rgba8" end return "rgbaf32" end Texel.nativeOf = nativeOf @native local function uf11(v: number): number local e, m = rshift(v, 6), band(v, 63) if e == 0 then return m / 64 * 2 ^ -14 elseif e == 31 then return if m == 0 then math.huge else 0 / 0 end return (1 + m / 64) * 2 ^ (e - 15) end @native local function uf10(v: number): number local e, m = rshift(v, 5), band(v, 31) if e == 0 then return m / 32 * 2 ^ -14 elseif e == 31 then return if m == 0 then math.huge else 0 / 0 end return (1 + m / 32) * 2 ^ (e - 15) end @native local function component(src: buffer, q: number, size: number, typ: string): (number, number) if typ == "unorm" then if size == 1 then local v = readu8(src, q) return v / 255, v elseif size == 2 then local v = readu16(src, q) return v / 65535, (v * 255 + 32767) // 65535 end local v = readu32(src, q) return v / 4294967295, math.floor(v / 4294967295 * 255 + 0.5) elseif typ == "snorm" then if size == 1 then local v = math.max(readi8(src, q), -127) return v / 127, v + 128 elseif size == 2 then local v = math.max(readi16(src, q), -32767) return v / 32767, math.floor(v * 127 / 32767 + 0.5) + 128 end local v = math.max(readi32(src, q), -2147483647) return v / 2147483647, math.floor(v * 127 / 2147483647 + 0.5) + 128 elseif typ == "float" then local f = if size == 2 then HALF[readu16(src, q)] else readf32(src, q) local c = if f ~= f then 0 elseif f < 0 then 0 elseif f > 1 then 1 else f return f, math.floor(c * 255 + 0.5) elseif typ == "uint" then local v = if size == 1 then readu8(src, q) elseif size == 2 then readu16(src, q) else readu32(src, q) return v, math.min(v, 255) end local v = if size == 1 then readi8(src, q) elseif size == 2 then readi16(src, q) else readi32(src, q) return v, math.clamp(v, 0, 255) end @native local function ycc(y: number, u: number, v: number, a: number): number local c, d, e = 1.164 * (y - 16), u - 128, v - 128 local r = math.clamp(math.floor(c + 1.596 * e + 0.5), 0, 255) local g = math.clamp(math.floor(c - 0.392 * d - 0.813 * e + 0.5), 0, 255) local b = math.clamp(math.floor(c + 2.017 * d + 0.5), 0, 255) return r + g * 256 + b * 65536 + a * 16777216 end @native local function yuv(d: Desc, src: buffer, offset: number, w: number, h: number, pitch: number, dst: buffer): buffer local n = 0 local order = d.order or "" for y = 0, h - 1 do local s = offset + y * pitch for x = 0, w - 1 do if d.kind == "ayuv" then local q = s + x * 4 writeu32(dst, n, ycc(readu8(src, q + 2), readu8(src, q + 1), readu8(src, q), readu8(src, q + 3))) else local q = s + (x // 2) * 4 local b0, b1, b2, b3 = readu8(src, q), readu8(src, q + 1), readu8(src, q + 2), readu8(src, q + 3) local odd = x % 2 == 1 if order == "yuyv" then writeu32(dst, n, ycc(if odd then b2 else b0, b1, b3, 255)) elseif order == "uyvy" then writeu32(dst, n, ycc(if odd then b3 else b1, b0, b2, 255)) elseif order == "rgbg" then writeu32(dst, n, b0 + (if odd then b3 else b1) * 256 + b2 * 65536 + 0xFF000000) else writeu32(dst, n, b1 + (if odd then b2 else b0) * 256 + b3 * 65536 + 0xFF000000) end end n += 4 end end return dst end @native function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number, h: number, native: boolean?, rowPitch: number?): (buffer?, string) local d = if type(fmt) == "string" then FORMATS[fmt] else fmt if not d then return nil, "unsupported: unknown texel format " .. tostring(fmt) end local tb = d.bytes local rowBytes = if d.kind == "pair" then ((w + 1) // 2) * 4 else tb * w local pitch = rowPitch or rowBytes if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or pitch < rowBytes then return nil, "bad image size" end if offset < 0 or offset + pitch * (h - 1) + rowBytes > buffer.len(src) then return nil, "truncated: texel data runs past the end" end local out = if native and d.kind ~= "pair" and d.kind ~= "ayuv" then nativeOf(d) else "rgba8" local bpp = if out == "rgba8" then 4 elseif out == "rgba16" then 8 else 16 local dst = buffer.create(w * h * bpp) local n = 0 if d.kind == "array" then local order, size, typ = d.order :: string, d.size :: number, d.type :: string if size == 1 and typ == "unorm" and out == "rgba8" and (order == "rgba" or order == "bgra" or order == "bgrx" or order == "rgbx") then local swap = order == "bgra" or order == "bgrx" local opaque = order == "bgrx" or order == "rgbx" for y = 0, h - 1 do local s = offset + y * pitch for x = 0, w - 1 do local v = readu32(src, s + x * 4) if swap then v = band(v, 0xFF00FF00) + band(rshift(v, 16), 0xFF) + lshift(band(v, 0xFF), 16) end if opaque then v = band(v, 0xFFFFFF) + 0xFF000000 end writeu32(dst, n, v) n += 4 end end return dst, out end local nc = #order local map = table.create(nc, 0) for i = 1, nc do local c = string.sub(order, i, i) map[i] = if c == "r" then (if nc == 1 then 4 else 0) elseif c == "g" then 1 elseif c == "b" then 2 elseif c == "a" then 3 elseif c == "l" then 4 else -1 end local f = table.create(4, 0) local q8 = table.create(4, 0) for y = 0, h - 1 do local s = offset + y * pitch for _ = 0, w - 1 do f[1], f[2], f[3], f[4] = 0, 0, 0, 1 q8[1], q8[2], q8[3], q8[4] = 0, 0, 0, 255 for i = 1, nc do local m = map[i] if m >= 0 then local fv, bv = component(src, s, size, typ) if m == 4 then f[1], f[2], f[3] = fv, fv, fv q8[1], q8[2], q8[3] = bv, bv, bv else f[m + 1], q8[m + 1] = fv, bv end end s += size end if out == "rgba8" then writeu32(dst, n, q8[1] + q8[2] * 256 + q8[3] * 65536 + q8[4] * 16777216) elseif out == "rgba16" then for c = 0, 3 do writeu16(dst, n + c * 2, math.floor(math.clamp(f[c + 1], 0, 1) * 65535 + 0.5)) end else for c = 0, 3 do writef32(dst, n + c * 4, f[c + 1]) end end n += bpp end end return dst, out elseif d.kind == "packed" then local chs = d.channels :: { Channel } for y = 0, h - 1 do local s = offset + y * pitch for _ = 0, w - 1 do local v = if tb == 1 then readu8(src, s) elseif tb == 2 then readu16(src, s) elseif tb == 3 then readu16(src, s) + readu8(src, s + 2) * 65536 else readu32(src, s) s += tb local r, g, b, a = 0, 0, 0, 1 for _, c in chs do local maxv = lshift(1, c.bits) - 1 local x = band(rshift(v, c.shift), maxv) / (if c.bits >= 32 then 4294967295 else maxv) local k = c.c if k == "r" then r = x elseif k == "g" then g = x elseif k == "b" then b = x elseif k == "a" then a = x else r, g, b = x, x, x end end if out == "rgba8" then writeu32(dst, n, math.floor(r * 255 + 0.5) + math.floor(g * 255 + 0.5) * 256 + math.floor(b * 255 + 0.5) * 65536 + math.floor(a * 255 + 0.5) * 16777216) else writeu16(dst, n, math.floor(r * 65535 + 0.5)) writeu16(dst, n + 2, math.floor(g * 65535 + 0.5)) writeu16(dst, n + 4, math.floor(b * 65535 + 0.5)) writeu16(dst, n + 6, math.floor(a * 65535 + 0.5)) end n += bpp end end return dst, out end if d.kind == "pair" or d.kind == "ayuv" then return yuv(d, src, offset, w, h, pitch, dst), out end local nine = d.kind == "rgb9e5" for y = 0, h - 1 do local s = offset + y * pitch for _ = 0, w - 1 do local v = readu32(src, s) s += 4 local sc = if nine then 2 ^ (rshift(v, 27) - 24) else 0 local r: number = if nine then band(v, 511) * sc else uf11(band(v, 2047)) local g: number = if nine then band(rshift(v, 9), 511) * sc else uf11(band(rshift(v, 11), 2047)) local b: number = if nine then band(rshift(v, 18), 511) * sc else uf10(rshift(v, 22)) if out == "rgba8" then @native local function q(x: number): number return if x ~= x or x <= 0 then 0 elseif x >= 1 then 255 else math.floor(x * 255 + 0.5) end writeu32(dst, n, q(r) + q(g) * 256 + q(b) * 65536 + 0xFF000000) else writef32(dst, n, r) writef32(dst, n + 4, g) writef32(dst, n + 8, b) writef32(dst, n + 12, 1) end n += bpp end end return dst, out end return Texel end __FILES["codecs/image/Texture"] = function() -- codecs/image/Texture: one entry point over the texture pixel codecs (Bcn, Etc, Texel). New in rosetta. local Types = __include("Types") local Bcn = __include("codecs/image/Bcn") local Etc = __include("codecs/image/Etc") local Texel = __include("codecs/image/Texel") local Half = __include("codecs/image/Half") local Texture = {} function Texture.known(name: string): string? if Bcn.BLOCK[name] then return "bcn" elseif Etc.BLOCK[name] then return "etc" elseif Texel.FORMATS[name] then return "texel" end return nil end function Texture.size(name: string, w: number, h: number): number? return Bcn.size(name, w, h) or Etc.size(name, w, h) or Texel.size(name, w, h) end function Texture.block(name: string): (number?, number?, number?) local b = Bcn.BLOCK[name] or Etc.BLOCK[name] if b then return 4, 4, b end local d = Texel.FORMATS[name] if d then return 1, 1, d.bytes end return nil, nil, nil end function Texture.decode(name: string, src: buffer, offset: number, w: number, h: number, native: boolean?): (buffer?, string) if Bcn.BLOCK[name] then local px, err = Bcn.decode(name, src, offset, w, h) if not px then return nil, err or "bad block data" end if Bcn.FLOAT[name] then if native then return px, "rgbaf32" end local out = buffer.create(w * h * 4) for i = 0, w * h - 1 do for c = 0, 3 do local v = buffer.readf32(px, i * 16 + c * 4) buffer.writeu8(out, i * 4 + c, if v ~= v or v <= 0 then 0 elseif v >= 1 then 255 else math.floor(v * 255 + 0.5)) end end return out, "rgba8" end return px, "rgba8" elseif Etc.BLOCK[name] then local wide = native == true and string.sub(name, 1, 3) == "eac" local px, err = Etc.decode(name, src, offset, w, h, nil, 0, wide) if not px then return nil, err or "bad block data" end return px, if wide then "rgba16" else "rgba8" end return Texel.decode(name, src, offset, w, h, native) end function Texture.image(px: buffer, pf: string, w: number, h: number): Types.Image local img = Types.Image.new(0, 0, pf :: any) img.width, img.height, img.pixels = w, h, px return img end type Surface = { level: number, layer: number, face: number, slice: number, image: Types.Image } function Texture.assemble(list: { Surface }, layout: string): Types.Image? local first: Types.Image? = nil local frames: { Types.Frame } = {} local mips: { Types.Image } = {} for _, s in list do if s.level == 0 then first = first or s.image local fr: Types.Frame = { image = s.image, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } table.insert(frames, fr) elseif s.layer == 0 and s.face == 0 and s.slice == 0 then mips[s.level] = s.image end end if not first then return nil end local img = Texture.image(first.pixels, first.format, first.width, first.height) if #frames > 1 then img.frames = frames end if #mips > 0 then img.meta.mipmaps = mips end img.meta.layout = layout return img end function Texture.halve(img: Types.Image): Types.Image local w, h = img.width, img.height local nw, nh = math.max(1, w // 2), math.max(1, h // 2) local fmt = img.format local out = Types.Image.new(nw, nh, fmt) local src, dst = img.pixels, out.pixels local cs = if fmt == "rgba8" then 1 elseif fmt == "rgba16" then 2 else 4 local function get(x: number, y: number, c: number): number local o = ((math.min(y, h - 1) * w + math.min(x, w - 1)) * 4 + c) * cs return if cs == 1 then buffer.readu8(src, o) elseif cs == 2 then buffer.readu16(src, o) else buffer.readf32(src, o) end for y = 0, nh - 1 do for x = 0, nw - 1 do for c = 0, 3 do local x0, y0 = x * 2, y * 2 local v = (get(x0, y0, c) + get(x0 + 1, y0, c) + get(x0, y0 + 1, c) + get(x0 + 1, y0 + 1, c)) / 4 local o = ((y * nw + x) * 4 + c) * cs if cs == 1 then buffer.writeu8(dst, o, math.floor(v + 0.5)) elseif cs == 2 then buffer.writeu16(dst, o, math.floor(v + 0.5)) else buffer.writef32(dst, o, v) end end end end return out end function Texture.toHalf(px: buffer, n: number): buffer local out = buffer.create(n * 8) local from = Half.fromFloat for i = 0, n * 4 - 1 do buffer.writeu16(out, i * 2, from(buffer.readf32(px, i * 4))) end return out end return Texture end __FILES["codecs/image/Vp8"] = function() -- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. -- Key frames ported from libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), inter frames after libvpx 1.17 -- (BSD-3-Clause, licenses/libvpx-LICENSE.txt); bit-exact with both. Scale bits are ignored, as libwebp and ffmpeg do. local Err = __include("core/Err") local Types = __include("Types") local Decode = __include("codecs/image/Vp8/Decode") local Yuv = __include("codecs/image/Vp8/Yuv") local Vp8 = {} local DEFAULT_MAX_PIXELS = 2 ^ 28 type Options = { maxPixels: number?, } local function fail(msg: string?, offset: number?): Err.Err local m = msg or "bad data" if string.sub(m, 1, 11) == "truncated: " then return Err.new(Err.TRUNCATED, string.sub(m, 12), offset) elseif string.sub(m, 1, 7) == "limit: " then return Err.new(Err.LIMIT, string.sub(m, 8), offset) elseif string.sub(m, 1, 13) == "unsupported: " then return Err.new(Err.UNSUPPORTED, string.sub(m, 14), offset) end return Err.new(Err.CORRUPT, m, offset) end local function range(buf: buffer, off: number?, len: number?): (number, number) local n = buffer.len(buf) local o = math.clamp(off or 0, 0, n) return o, math.clamp(len or (n - o), 0, n - o) end function Vp8.info(buf: buffer, off: number?, len: number?): (any, Err.Err?) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "info: expected a buffer") end local o, l = range(buf, off, len) local h, err = Decode.header(buf, o, l) if not h then return nil, fail(err, o) end return h, nil end local DecoderMeta = {} DecoderMeta.__index = DecoderMeta type Decoder = typeof(setmetatable({} :: { state: Decode.State }, DecoderMeta)) function Vp8.newDecoder(): Decoder return setmetatable({ state = Decode.new() }, DecoderMeta) end function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer") end local o, l = range(buf, off, len) local f, err = Decode.decodeFrame(self.state, buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS) if not f then return nil, fail(err, o) end local img = Types.Image.new(f.width, f.height, "yuv420p") local ny = f.width * f.height local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2) Decode.cropTo(f, img.pixels, 0, img.pixels, ny, img.pixels, ny + nc) local h = f.header img.meta.source = { format = "vp8", keyFrame = h.keyFrame, show = h.show, profile = h.profile, width = f.width, height = f.height } return img, nil end function DecoderMeta.reset(self: Decoder) Decode.reset(self.state) end function Vp8.decodeFrame(buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?) return Vp8.newDecoder():decodeFrame(buf, off, len, opts) end function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options?): (buffer?, any, buffer?, number?, number?) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "decodePlanes: expected a buffer") end local o, l = range(buf, off, len) local f, err = Decode.decodeFrame(Decode.new(), buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS) if not f then return nil, fail(err, o) end local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2) local y, u, v = buffer.create(f.width * f.height), buffer.create(nc), buffer.create(nc) Decode.cropTo(f, y, 0, u, 0, v, 0) return y, u, v, f.width, f.height end function Vp8.planes(img: Types.Image): (number, number, number, number, number) local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2 local ny = img.width * img.height return 0, ny, ny + cw * ch, cw, ch end function Vp8.toRgba(img: Types.Image, fancy: boolean?): (Types.Image?, Err.Err?) if type(img) ~= "table" or img.format ~= "yuv420p" then return nil, Err.new(Err.ARG, "toRgba: needs a yuv420p Image") end local w, h = img.width, img.height local _, uo, vo, cw, ch = Vp8.planes(img) local y = buffer.create(w * h) local u = buffer.create(cw * ch) local v = buffer.create(cw * ch) buffer.copy(y, 0, img.pixels, 0, w * h) buffer.copy(u, 0, img.pixels, uo, cw * ch) buffer.copy(v, 0, img.pixels, vo, cw * ch) local out = Types.Image.new(w, h, "rgba8") Yuv.toRgba(y, u, v, w, h, fancy ~= false, out.pixels) out.meta.source = img.meta.source return out, nil end function Vp8.yuvToRgba(y: buffer, u: buffer, v: buffer, w: number, h: number, fancy: boolean?): buffer return Yuv.toRgba(y, u, v, w, h, fancy ~= false) end Vp8.setAlpha = Yuv.setAlpha return Vp8 end __FILES["codecs/image/Vp8/Decode"] = @native function() -- codecs/image/Vp8/Decode: the VP8 frame decoder (RFC 6386), key frames a port of libwebp 1.6 src/dec + src/dsp/dec.c -- (BSD-3-Clause, licenses/libwebp-LICENSE.txt), inter frames after libvpx 1.17 vp8/decoder + vp8/common (BSD-3-Clause, -- licenses/libvpx-LICENSE.txt). Where libvpx and ffmpeg disagree on streams no encoder writes, this follows ffmpeg. local Tables = __include("codecs/image/Vp8/Tables") local Predict = __include("codecs/image/Vp8/Predict") local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16 local readu32, writeu32 = buffer.readu32, buffer.writeu32 local bfill, bcopy, bcreate = buffer.fill, buffer.copy, buffer.create local abs = math.abs local COEFF_PROBA0 = Tables.COEFF_PROBA0 local COEFF_UPDATE_PROBA = Tables.COEFF_UPDATE_PROBA local BMODES_PROBA = Tables.BMODES_PROBA local DC_TABLE, AC_TABLE = Tables.DC_TABLE, Tables.AC_TABLE local BANDS, ZIGZAG = Tables.BANDS, Tables.ZIGZAG local CAT = { Tables.CAT3, Tables.CAT4, Tables.CAT5, Tables.CAT6 } local Decode = {} -- libwebp's VP8BitReader: `range` is the range minus one (127..254), `value` holds the unread bits, `bits` is the -- position of the 8-bit window in `value` (< 0: load more). Bytes past the end read as zero once and set eof. type Br = { buf: buffer, pos: number, limit: number, value: number, bits: number, range: number, eof: boolean } -- SHIFT[r + 1]: the normalisation shift of a range r (1..255) = 7 - floor(log2 r) local SHIFT = table.create(256, 0) for r = 1, 255 do local s, v = 0, r while v < 128 do v *= 2 s += 1 end SHIFT[r + 1] = s end @native local function load(br: Br) local p = br.pos if p + 3 <= br.limit then local b = br.buf br.value = br.value * 16777216 + readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) br.pos = p + 3 br.bits += 24 elseif p < br.limit then br.value = br.value * 256 + readu8(br.buf, p) br.pos = p + 1 br.bits += 8 elseif not br.eof then br.value *= 256 br.bits += 8 br.eof = true else br.bits = 0 end end @native local function newBr(buf: buffer, off: number, len: number): Br local br = { buf = buf, pos = off, limit = off + len, value = 0, bits = -8, range = 254, eof = false } load(br) return br end -- branchless getBit: bit = value >> bits > split; range = bit ? range - split : split + 1; -- value -= bit * (split + 1) << bits @native local function getBit(br: Br, prob: number): number if br.bits < 0 then load(br) end local range = br.range local pos = br.bits local split = rshift(range * prob, 8) local bit = rshift(split - rshift(br.value, pos), 31) local r = split + 1 + bit * (range - split - split - 1) br.value -= bit * lshift(split + 1, pos) local shift = SHIFT[r + 1] br.range = lshift(r, shift) - 1 br.bits = pos - shift return bit end @native local function getValue(br: Br, n: number): number local v = 0 for i = n - 1, 0, -1 do v += getBit(br, 0x80) * 2 ^ i end return v end @native local function getSignedValue(br: Br, n: number): number local v = getValue(br, n) return if getBit(br, 0x80) == 1 then -v else v end type Quant = { y1dc: number, y1ac: number, y2dc: number, y2ac: number, uvdc: number, uvac: number } type Ref = Predict.Planes & { extended: boolean } type State = { -- the frame context (saved and restored around frames that do not refresh it) proba: { number }, -- 4 * 8 * 3 * 11 token probabilities ymodeProb: { number }, -- 4 uvmodeProb: { number }, -- 3 mvProb: { number }, -- 2 * 19 -- persistent between frames (reset by key frames) segProba: { number }, -- 3 useSegment: boolean, updateMap: boolean, absoluteDelta: boolean, segQuant: { number }, -- 4 segFilter: { number }, -- 4 refLfDelta: { number }, -- 4: intra, last, golden, altref modeLfDelta: { number }, -- 4: B_PRED, zero, nearest / near / new, split signBias: { number }, -- 4 (by reference frame + 1) segMap: { number }, width: number, height: number, mbw: number, mbh: number, hasKey: boolean, last: Ref?, golden: Ref?, alt: Ref?, pool: { Ref }, -- the mode info of the current inter frame, (mbw + 1) x (mbh + 1) with a zero top row and left column miRef: { number }, miMode: { number }, miMvR: { number }, miMvC: { number }, miSubR: { number }, -- 16 per macroblock miSubC: { number }, miN: number, pred: buffer?, } @native function Decode.new(): State return { proba = table.clone(COEFF_PROBA0), ymodeProb = table.clone(Tables.YMODE_PROB), uvmodeProb = table.clone(Tables.UVMODE_PROB), mvProb = table.clone(Tables.MV_DEFAULT), segProba = { 255, 255, 255 }, useSegment = false, updateMap = false, absoluteDelta = false, segQuant = { 0, 0, 0, 0 }, segFilter = { 0, 0, 0, 0 }, refLfDelta = { 0, 0, 0, 0 }, modeLfDelta = { 0, 0, 0, 0 }, signBias = { 0, 0, 0, 0 }, segMap = {}, width = 0, height = 0, mbw = 0, mbh = 0, hasKey = false, last = nil, golden = nil, alt = nil, pool = {}, miRef = {}, miMode = {}, miMvR = {}, miMvC = {}, miSubR = {}, miSubC = {}, miN = 0, pred = nil, } end @native function Decode.reset(st: State) st.hasKey = false st.last, st.golden, st.alt = nil, nil, nil end @native function Decode.header(buf: buffer, off: number, len: number): (any, string?) if len < 3 then return nil, "truncated: frame tag" end local bits = readu8(buf, off) + readu8(buf, off + 1) * 256 + readu8(buf, off + 2) * 65536 local h = { keyFrame = band(bits, 1) == 0, profile = band(rshift(bits, 1), 7), show = band(rshift(bits, 4), 1) == 1, partitionLength = rshift(bits, 5), width = 0, height = 0, xscale = 0, yscale = 0, } if h.profile > 3 then return nil, "bad profile " .. h.profile end if h.keyFrame then if len < 10 then return nil, "truncated: key frame header" end if readu8(buf, off + 3) ~= 0x9d or readu8(buf, off + 4) ~= 0x01 or readu8(buf, off + 5) ~= 0x2a then return nil, "bad VP8 start code" end local w = readu8(buf, off + 6) + readu8(buf, off + 7) * 256 local ht = readu8(buf, off + 8) + readu8(buf, off + 9) * 256 h.width, h.xscale = band(w, 0x3fff), rshift(w, 14) h.height, h.yscale = band(ht, 0x3fff), rshift(ht, 14) end return h, nil end @native local function getLargeValue(br: Br, P: { number }, p: number): number local v if getBit(br, P[p + 4]) == 0 then if getBit(br, P[p + 5]) == 0 then v = 2 else v = 3 + getBit(br, P[p + 6]) end else if getBit(br, P[p + 7]) == 0 then if getBit(br, P[p + 8]) == 0 then v = 5 + getBit(br, 159) else v = 7 + 2 * getBit(br, 165) v += getBit(br, 145) end else local bit1 = getBit(br, P[p + 9]) local bit0 = getBit(br, P[p + 10 + bit1]) local cat = 2 * bit1 + bit0 v = 0 for _, pr in CAT[cat + 1] do v = v + v + getBit(br, pr) end v += 3 + lshift(8, cat) end end return v end -- coefficients are dequantized to int16 as libwebp stores them, in raster order @native local function getCoeffs(br: Br, P: { number }, t: number, ctx: number, dqDc: number, dqAc: number, n: number, out: buffer, o: number): number local tb = t * 8 local p = ((tb + BANDS[n + 1]) * 3 + ctx) * 11 local buf, limit = br.buf, br.limit local value, bits, range, pos = br.value, br.bits, br.range, br.pos while n < 16 do do if bits < 0 then if pos + 3 <= limit then value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) pos += 3 bits += 24 else br.value, br.bits, br.pos = value, bits, pos load(br) value, bits, pos = br.value, br.bits, br.pos end end local split = rshift(range * P[p + 1], 8) local more = rshift(value, bits) > split if more then range -= split value -= lshift(split + 1, bits) else range = split + 1 end local sh = SHIFT[range + 1] range = lshift(range, sh) - 1 bits -= sh if not more then br.value, br.bits, br.range, br.pos = value, bits, range, pos return n end end while true do if bits < 0 then if pos + 3 <= limit then value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) pos += 3 bits += 24 else br.value, br.bits, br.pos = value, bits, pos load(br) value, bits, pos = br.value, br.bits, br.pos end end local split = rshift(range * P[p + 2], 8) local nonzero = rshift(value, bits) > split if nonzero then range -= split value -= lshift(split + 1, bits) else range = split + 1 end local sh = SHIFT[range + 1] range = lshift(range, sh) - 1 bits -= sh if nonzero then break end n += 1 if n == 16 then br.value, br.bits, br.range, br.pos = value, bits, range, pos return 16 end p = (tb + BANDS[n + 1]) * 33 end local nb = (tb + BANDS[n + 2]) * 3 local v do if bits < 0 then if pos + 3 <= limit then value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) pos += 3 bits += 24 else br.value, br.bits, br.pos = value, bits, pos load(br) value, bits, pos = br.value, br.bits, br.pos end end local split = rshift(range * P[p + 3], 8) local large = rshift(value, bits) > split if large then range -= split value -= lshift(split + 1, bits) else range = split + 1 end local sh = SHIFT[range + 1] range = lshift(range, sh) - 1 bits -= sh if not large then v = 1 p = (nb + 1) * 11 else br.value, br.bits, br.range, br.pos = value, bits, range, pos v = getLargeValue(br, P, p) value, bits, range, pos = br.value, br.bits, br.range, br.pos p = (nb + 2) * 11 end end do if bits < 0 then if pos + 3 <= limit then value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) pos += 3 bits += 24 else br.value, br.bits, br.pos = value, bits, pos load(br) value, bits, pos = br.value, br.bits, br.pos end end local split = rshift(range * 0x80, 8) local neg = rshift(value, bits) > split if neg then range -= split value -= lshift(split + 1, bits) else range = split + 1 end local sh = SHIFT[range + 1] range = lshift(range, sh) - 1 bits -= sh if neg then v = -v end end if n > 0 then writei16(out, o + ZIGZAG[n + 1] * 2, v * dqAc) else writei16(out, o + ZIGZAG[n + 1] * 2, v * dqDc) end n += 1 end br.value, br.bits, br.range, br.pos = value, bits, range, pos return 16 end @native local function nzCode(acc: number, nz: number, dcNz: number): number return acc * 4 + (if nz > 3 then 3 elseif nz > 1 then 2 else dcNz) end -- the inverse Walsh-Hadamard transform of the 16 Y2 coefficients into the DC of the 16 luma blocks local whtTmp = table.create(16, 0) @native local function transformWHT(inp: buffer, out: buffer, o: number) for i = 0, 3 do local i0, i4, i8, i12 = readi16(inp, i * 2), readi16(inp, (4 + i) * 2), readi16(inp, (8 + i) * 2), readi16(inp, (12 + i) * 2) local a0 = i0 + i12 local a1 = i4 + i8 local a2 = i4 - i8 local a3 = i0 - i12 whtTmp[1 + i] = a0 + a1 whtTmp[9 + i] = a0 - a1 whtTmp[5 + i] = a3 + a2 whtTmp[13 + i] = a3 - a2 end for i = 0, 3 do local dc = whtTmp[1 + i * 4] + 3 local a0 = dc + whtTmp[4 + i * 4] local a1 = whtTmp[2 + i * 4] + whtTmp[3 + i * 4] local a2 = whtTmp[2 + i * 4] - whtTmp[3 + i * 4] local a3 = dc - whtTmp[4 + i * 4] local base = o + i * 128 writei16(out, base, (a0 + a1) // 8) writei16(out, base + 32, (a3 + a2) // 8) writei16(out, base + 64, (a0 - a1) // 8) writei16(out, base + 96, (a3 - a2) // 8) end end -- the work buffer of libwebp (yuv_b): BPS = 32, Y at row 1 column 8, U and V below it side by side local BPS = 32 local Y_OFF = BPS + 8 local U_OFF = Y_OFF + BPS * 16 + BPS local V_OFF = U_OFF + 16 local YUV_SIZE = BPS * 17 + BPS * 9 @native local function clip8(v: number): number return if v < 0 then 0 elseif v > 255 then 255 else v end -- the inverse DCT of one block (libwebp TransformOne) added to dst local C1, C2 = 20091, 35468 local idctTmp = table.create(16, 0) @native local function mul1(a: number): number return ((a * C1) // 65536) + a end @native local function mul2(a: number): number return (a * C2) // 65536 end @native local function transformOne(c: buffer, o: number, b: buffer, dst: number) for i = 0, 3 do local i0, i4, i8, i12 = readi16(c, o + i * 2), readi16(c, o + (4 + i) * 2), readi16(c, o + (8 + i) * 2), readi16(c, o + (12 + i) * 2) local a = i0 + i8 local bb = i0 - i8 local cc = mul2(i4) - mul1(i12) local d = mul1(i4) + mul2(i12) idctTmp[i * 4 + 1] = a + d idctTmp[i * 4 + 2] = bb + cc idctTmp[i * 4 + 3] = bb - cc idctTmp[i * 4 + 4] = a - d end for i = 0, 3 do local dc = idctTmp[i + 1] + 4 local a = dc + idctTmp[i + 9] local bb = dc - idctTmp[i + 9] local cc = mul2(idctTmp[i + 5]) - mul1(idctTmp[i + 13]) local d = mul1(idctTmp[i + 5]) + mul2(idctTmp[i + 13]) local row = dst + i * BPS writeu8(b, row, clip8(readu8(b, row) + (a + d) // 8)) writeu8(b, row + 1, clip8(readu8(b, row + 1) + (bb + cc) // 8)) writeu8(b, row + 2, clip8(readu8(b, row + 2) + (bb - cc) // 8)) writeu8(b, row + 3, clip8(readu8(b, row + 3) + (a - d) // 8)) end end @native local function transformDC(c: buffer, o: number, b: buffer, dst: number) local dc = (readi16(c, o) + 4) // 8 for j = 0, 3 do local row = dst + j * BPS for i = row, row + 3 do writeu8(b, i, clip8(readu8(b, i) + dc)) end end end -- code: 3 = full transform, 2 = only the first three coefficients (the same result as the full one), 1 = DC only @native local function doTransform(code: number, c: buffer, o: number, b: buffer, dst: number) if code >= 2 then transformOne(c, o, b, dst) elseif code == 1 then transformDC(c, o, b, dst) end end @native local function doUVTransform(bits: number, c: buffer, o: number, b: buffer, dst: number) if band(bits, 0xff) ~= 0 then if band(bits, 0xaa) ~= 0 then transformOne(c, o, b, dst) transformOne(c, o + 32, b, dst + 4) transformOne(c, o + 64, b, dst + 4 * BPS) transformOne(c, o + 96, b, dst + 4 * BPS + 4) else if readi16(c, o) ~= 0 then transformDC(c, o, b, dst) end if readi16(c, o + 32) ~= 0 then transformDC(c, o + 32, b, dst + 4) end if readi16(c, o + 64) ~= 0 then transformDC(c, o + 64, b, dst + 4 * BPS) end if readi16(c, o + 96) ~= 0 then transformDC(c, o + 96, b, dst + 4 * BPS + 4) end end end end -- prediction: modes 0 DC, 1 TM, 2 VE, 3 HE; 4 DC no top, 5 DC no left, 6 DC no top-left (16x16 and chroma) @native local function fill(b: buffer, dst: number, size: number, v: number) for j = 0, size - 1 do local o = dst + j * BPS for i = o, o + size - 4, 4 do writeu32(b, i, v * 0x01010101) end end end @native local function trueMotion(b: buffer, dst: number, size: number) local tl = readu8(b, dst - BPS - 1) for y = 0, size - 1 do local row = dst + y * BPS local l = readu8(b, row - 1) - tl for x = 0, size - 1 do writeu8(b, row + x, clip8(readu8(b, dst - BPS + x) + l)) end end end @native local function predictBlock(b: buffer, dst: number, size: number, mode: number) local shift = if size == 16 then 5 else 4 if mode == 0 then local dc = size for j = 0, size - 1 do dc += readu8(b, dst - 1 + j * BPS) + readu8(b, dst + j - BPS) end fill(b, dst, size, rshift(dc, shift)) elseif mode == 1 then trueMotion(b, dst, size) elseif mode == 2 then for j = 0, size - 1 do local o = dst + j * BPS for i = 0, size - 4, 4 do writeu32(b, o + i, readu32(b, dst - BPS + i)) end end elseif mode == 3 then for j = 0, size - 1 do local o = dst + j * BPS local v = readu8(b, o - 1) * 0x01010101 for i = o, o + size - 4, 4 do writeu32(b, i, v) end end elseif mode == 4 then -- no top: left samples local dc = size // 2 for j = 0, size - 1 do dc += readu8(b, dst - 1 + j * BPS) end fill(b, dst, size, rshift(dc, shift - 1)) elseif mode == 5 then -- no left: top samples local dc = size // 2 for j = 0, size - 1 do dc += readu8(b, dst + j - BPS) end fill(b, dst, size, rshift(dc, shift - 1)) else fill(b, dst, size, 0x80) end end @native local function avg3(a: number, b: number, c: number): number return rshift(a + 2 * b + c + 2, 2) end @native local function avg2(a: number, b: number): number return rshift(a + b + 1, 1) end -- 4x4 prediction (libwebp VP8PredLuma4): 0 DC, 1 TM, 2 VE, 3 HE, 4 RD, 5 VR, 6 LD, 7 VL, 8 HD, 9 HU @native local function predict4(b: buffer, dst: number, mode: number) if mode == 0 then local dc = 4 for i = 0, 3 do dc += readu8(b, dst + i - BPS) + readu8(b, dst - 1 + i * BPS) end fill(b, dst, 4, rshift(dc, 3)) elseif mode == 1 then trueMotion(b, dst, 4) elseif mode == 2 then local t = dst - BPS local x, a, bb, c, d, e = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3), readu8(b, t + 4) local v0, v1, v2, v3 = avg3(x, a, bb), avg3(a, bb, c), avg3(bb, c, d), avg3(c, d, e) for j = 0, 3 do writeu8(b, dst + j * BPS + 0, v0) writeu8(b, dst + j * BPS + 1, v1) writeu8(b, dst + j * BPS + 2, v2) writeu8(b, dst + j * BPS + 3, v3) end elseif mode == 3 then local A, B, C, D = readu8(b, dst - 1 - BPS), readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS) local E = readu8(b, dst - 1 + 3 * BPS) writeu32(b, dst, avg3(A, B, C) * 0x01010101) writeu32(b, dst + BPS, avg3(B, C, D) * 0x01010101) writeu32(b, dst + 2 * BPS, avg3(C, D, E) * 0x01010101) writeu32(b, dst + 3 * BPS, avg3(D, E, E) * 0x01010101) else local I, J, K, L = readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS), readu8(b, dst - 1 + 3 * BPS) local t = dst - BPS local X, A, B, C, D = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3) local E, F, G, H = readu8(b, t + 4), readu8(b, t + 5), readu8(b, t + 6), readu8(b, t + 7) if mode == 4 then -- RD writeu8(b, dst + 96, avg3(J, K, L)) local v = avg3(I, J, K) writeu8(b, dst + 97, v) writeu8(b, dst + 64, v) v = avg3(X, I, J) writeu8(b, dst + 98, v) writeu8(b, dst + 65, v) writeu8(b, dst + 32, v) v = avg3(A, X, I) writeu8(b, dst + 99, v) writeu8(b, dst + 66, v) writeu8(b, dst + 33, v) writeu8(b, dst + 0, v) v = avg3(B, A, X) writeu8(b, dst + 67, v) writeu8(b, dst + 34, v) writeu8(b, dst + 1, v) v = avg3(C, B, A) writeu8(b, dst + 35, v) writeu8(b, dst + 2, v) writeu8(b, dst + 3, avg3(D, C, B)) elseif mode == 5 then -- VR local v = avg2(X, A) writeu8(b, dst + 0, v) writeu8(b, dst + 65, v) v = avg2(A, B) writeu8(b, dst + 1, v) writeu8(b, dst + 66, v) v = avg2(B, C) writeu8(b, dst + 2, v) writeu8(b, dst + 67, v) writeu8(b, dst + 3, avg2(C, D)) writeu8(b, dst + 96, avg3(K, J, I)) writeu8(b, dst + 64, avg3(J, I, X)) v = avg3(I, X, A) writeu8(b, dst + 32, v) writeu8(b, dst + 97, v) v = avg3(X, A, B) writeu8(b, dst + 33, v) writeu8(b, dst + 98, v) v = avg3(A, B, C) writeu8(b, dst + 34, v) writeu8(b, dst + 99, v) writeu8(b, dst + 35, avg3(B, C, D)) elseif mode == 6 then -- LD writeu8(b, dst + 0, avg3(A, B, C)) local v = avg3(B, C, D) writeu8(b, dst + 1, v) writeu8(b, dst + 32, v) v = avg3(C, D, E) writeu8(b, dst + 2, v) writeu8(b, dst + 33, v) writeu8(b, dst + 64, v) v = avg3(D, E, F) writeu8(b, dst + 3, v) writeu8(b, dst + 34, v) writeu8(b, dst + 65, v) writeu8(b, dst + 96, v) v = avg3(E, F, G) writeu8(b, dst + 35, v) writeu8(b, dst + 66, v) writeu8(b, dst + 97, v) v = avg3(F, G, H) writeu8(b, dst + 67, v) writeu8(b, dst + 98, v) writeu8(b, dst + 99, avg3(G, H, H)) elseif mode == 7 then -- VL writeu8(b, dst + 0, avg2(A, B)) local v = avg2(B, C) writeu8(b, dst + 1, v) writeu8(b, dst + 64, v) v = avg2(C, D) writeu8(b, dst + 2, v) writeu8(b, dst + 65, v) v = avg2(D, E) writeu8(b, dst + 3, v) writeu8(b, dst + 66, v) writeu8(b, dst + 32, avg3(A, B, C)) v = avg3(B, C, D) writeu8(b, dst + 33, v) writeu8(b, dst + 96, v) v = avg3(C, D, E) writeu8(b, dst + 34, v) writeu8(b, dst + 97, v) v = avg3(D, E, F) writeu8(b, dst + 35, v) writeu8(b, dst + 98, v) writeu8(b, dst + 67, avg3(E, F, G)) writeu8(b, dst + 99, avg3(F, G, H)) elseif mode == 8 then -- HD local v = avg2(I, X) writeu8(b, dst + 0, v) writeu8(b, dst + 34, v) v = avg2(J, I) writeu8(b, dst + 32, v) writeu8(b, dst + 66, v) v = avg2(K, J) writeu8(b, dst + 64, v) writeu8(b, dst + 98, v) writeu8(b, dst + 96, avg2(L, K)) writeu8(b, dst + 3, avg3(A, B, C)) writeu8(b, dst + 2, avg3(X, A, B)) v = avg3(I, X, A) writeu8(b, dst + 1, v) writeu8(b, dst + 35, v) v = avg3(J, I, X) writeu8(b, dst + 33, v) writeu8(b, dst + 67, v) v = avg3(K, J, I) writeu8(b, dst + 65, v) writeu8(b, dst + 99, v) writeu8(b, dst + 97, avg3(L, K, J)) else -- HU writeu8(b, dst + 0, avg2(I, J)) local v = avg2(J, K) writeu8(b, dst + 2, v) writeu8(b, dst + 32, v) v = avg2(K, L) writeu8(b, dst + 34, v) writeu8(b, dst + 64, v) writeu8(b, dst + 1, avg3(I, J, K)) v = avg3(J, K, L) writeu8(b, dst + 3, v) writeu8(b, dst + 33, v) v = avg3(K, L, L) writeu8(b, dst + 35, v) writeu8(b, dst + 65, v) writeu8(b, dst + 67, L) writeu8(b, dst + 66, L) writeu8(b, dst + 96, L) writeu8(b, dst + 97, L) writeu8(b, dst + 98, L) writeu8(b, dst + 99, L) end end end @native local function checkMode(mbx: number, mby: number, mode: number): number if mode == 0 then if mbx == 0 then return if mby == 0 then 6 else 5 end return if mby == 0 then 4 else 0 end return mode end -- the filters are libwebp's DoFilter2 / DoFilter4 / DoFilter6 inlined into their loops (VP8ksclip1 clamps to -- [-128, 127], VP8ksclip2 to [-16, 15], VP8kclip1 to [0, 255]). Arithmetic shifts of small signed values are -- logical shifts of the value plus a bias: (a + 4) >> 3 = rshift(a + 4 + 1024, 3) - 128 for a >= -1024. -- SimpleVFilter16 / SimpleHFilter16; a position whose filter value a is 0 changes nothing (skipped before the mask) @native local function simpleFilter(b: buffer, p: number, step: number, along: number, thresh: number) local t2 = 2 * thresh + 1 for _ = 1, 16 do local p1, p0, q0, q1 = readu8(b, p - 2 * step), readu8(b, p - step), readu8(b, p), readu8(b, p + step) local w = p1 - q1 local a = 3 * (q0 - p0) + (if w < -128 then -128 elseif w > 127 then 127 else w) if a ~= 0 and 4 * abs(p0 - q0) + abs(w) <= t2 then local a1 = rshift(a + 1028, 3) - 128 if a1 < -16 then a1 = -16 elseif a1 > 15 then a1 = 15 end local a2 = rshift(a + 1027, 3) - 128 if a2 < -16 then a2 = -16 elseif a2 > 15 then a2 = 15 end local v = p0 + a2 writeu8(b, p - step, if v < 0 then 0 elseif v > 255 then 255 else v) v = q0 - a1 writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) end p += along end end -- the macroblock edge filter (FilterLoop26) @native local function filterEdge(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number) local t2 = 2 * thresh + 1 for _ = 1, size do local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs) local w = p1 - q1 local a = 3 * (q0 - p0) + (if w < -128 then -128 elseif w > 127 then 127 else w) if a ~= 0 then local dp, dq = abs(p1 - p0), abs(q1 - q0) if 4 * abs(p0 - q0) + abs(w) <= t2 and dp <= it and dq <= it then local p3, p2 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs) local q2, q3 = readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) if abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it then if dp > hevT or dq > hevT then local a1 = rshift(a + 1028, 3) - 128 if a1 < -16 then a1 = -16 elseif a1 > 15 then a1 = 15 end local a2 = rshift(a + 1027, 3) - 128 if a2 < -16 then a2 = -16 elseif a2 > 15 then a2 = 15 end local v = p0 + a2 writeu8(b, p - hs, if v < 0 then 0 elseif v > 255 then 255 else v) v = q0 - a1 writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) else if a < -128 then a = -128 elseif a > 127 then a = 127 end local a1 = rshift(27 * a + 4159, 7) - 32 local a2 = rshift(18 * a + 4159, 7) - 32 local a3 = rshift(9 * a + 4159, 7) - 32 local v = p2 + a3 writeu8(b, p - 3 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) v = p1 + a2 writeu8(b, p - 2 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) v = p0 + a1 writeu8(b, p - hs, if v < 0 then 0 elseif v > 255 then 255 else v) v = q0 - a1 writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) v = q1 - a2 writeu8(b, p + hs, if v < 0 then 0 elseif v > 255 then 255 else v) v = q2 - a3 writeu8(b, p + 2 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) end end end end p += vs end end -- the inner edge filter (FilterLoop24); nothing changes when q0 == p0 and p1 == q1 @native local function filterInner(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number) local t2 = 2 * thresh + 1 for _ = 1, size do local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs) local w = p1 - q1 if q0 ~= p0 or w ~= 0 then local dp, dq = abs(p1 - p0), abs(q1 - q0) if 4 * abs(p0 - q0) + abs(w) <= t2 and dp <= it and dq <= it then local p3, p2 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs) local q2, q3 = readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) if abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it then local hev = dp > hevT or dq > hevT local a = 3 * (q0 - p0) if hev then a += if w < -128 then -128 elseif w > 127 then 127 else w end local a1 = rshift(a + 1028, 3) - 128 if a1 < -16 then a1 = -16 elseif a1 > 15 then a1 = 15 end local a2 = rshift(a + 1027, 3) - 128 if a2 < -16 then a2 = -16 elseif a2 > 15 then a2 = 15 end local v = p0 + a2 writeu8(b, p - hs, if v < 0 then 0 elseif v > 255 then 255 else v) v = q0 - a1 writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) if not hev then local a3 = rshift(a1 + 17, 1) - 8 v = p1 + a3 writeu8(b, p - 2 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) v = q1 - a3 writeu8(b, p + hs, if v < 0 then 0 elseif v > 255 then 255 else v) end end end end p += vs end end local MODE_CTX = Tables.MODE_CONTEXTS local SUB_MV_REF_PROB = Tables.SUB_MV_REF_PROB local SPLIT_OFFSET, SPLIT_FILL, SPLIT_COUNT = Tables.SPLIT_OFFSET, Tables.SPLIT_FILL, Tables.SPLIT_COUNT local BMODE_PROB = Tables.BMODE_PROB local MV_UPDATE = Tables.MV_UPDATE -- macroblock modes (the row arrays and miMode): 0 DC, 1 TM, 2 V, 3 H (16x16 intra, libwebp's numbering), 4 B_PRED, -- 5 ZEROMV, 6 NEARESTMV, 7 NEARMV, 8 NEWMV, 9 SPLITMV. Their loop filter mode delta index: local MODE_LF = { 1, 1, 1, 1, 0, 1, 2, 2, 2, 3 } -- a 4x4 intra mode with the fixed probabilities P[o + 1 .. o + 9] (libvpx vp8_bmode_tree, libwebp's numbering) @native local function readBMode(br: Br, P: { number }, o: number): number if getBit(br, P[o + 1]) == 0 then return 0 elseif getBit(br, P[o + 2]) == 0 then return 1 elseif getBit(br, P[o + 3]) == 0 then return 2 elseif getBit(br, P[o + 4]) == 0 then if getBit(br, P[o + 5]) == 0 then return 3 end return if getBit(br, P[o + 6]) == 0 then 4 else 5 elseif getBit(br, P[o + 7]) == 0 then return 6 elseif getBit(br, P[o + 8]) == 0 then return 7 end return if getBit(br, P[o + 9]) == 0 then 8 else 9 end -- one motion vector component (libvpx read_mvcomponent) with the probabilities P[o + 1 .. o + 19], in quarter pixels @native local function readMvComponent(br: Br, P: { number }, o: number): number local x if getBit(br, P[o + 1]) == 1 then -- long: bits 0-2, then 9-4, then bit 3 (implicit when nothing above it is set) x = getBit(br, P[o + 10]) + 2 * getBit(br, P[o + 11]) + 4 * getBit(br, P[o + 12]) for i = 9, 4, -1 do x += getBit(br, P[o + 10 + i]) * lshift(1, i) end if x < 16 or getBit(br, P[o + 13]) == 1 then x += 8 end elseif getBit(br, P[o + 3]) == 0 then -- short tree if getBit(br, P[o + 4]) == 0 then x = getBit(br, P[o + 5]) else x = 2 + getBit(br, P[o + 6]) end elseif getBit(br, P[o + 7]) == 0 then x = 4 + getBit(br, P[o + 8]) else x = 6 + getBit(br, P[o + 9]) end if x ~= 0 and getBit(br, P[o + 2]) == 1 then x = -x end return x end type Rows = { i4: { boolean }, -- no Y2 block (B_PRED or SPLITMV) modes: { number }, uv: { number }, ref: { number }, -- 0 intra, 1 last, 2 golden, 3 altref mode: { number }, part: { number }, -- SPLITMV partitioning (0 16x8, 1 8x16, 2 8x8, 3 4x4) or -1 } local nr, nc, cnt = table.create(4, 0), table.create(4, 0), table.create(4, 0) -- libvpx read_mb_modes_mv with vp8_find_near_mvs @native local function readInterMb(st: State, br: Br, probIntra: number, probLast: number, probGf: number, mi: number, mbx: number, mby: number, rows: Rows) local miRef, miMode, miMvR, miMvC = st.miRef, st.miMode, st.miMvR, st.miMvC local x1 = mbx + 1 if getBit(br, probIntra) == 0 then local P = st.ymodeProb local ymode if getBit(br, P[1]) == 0 then ymode = 0 elseif getBit(br, P[2]) == 0 then ymode = if getBit(br, P[3]) == 0 then 2 else 3 else ymode = if getBit(br, P[4]) == 0 then 1 else 4 end local modes = rows.modes if ymode == 4 then for k = mbx * 16 + 1, mbx * 16 + 16 do modes[k] = readBMode(br, BMODE_PROB, 0) end else modes[mbx * 16 + 1] = ymode end local U = st.uvmodeProb if getBit(br, U[1]) == 0 then rows.uv[x1] = 0 elseif getBit(br, U[2]) == 0 then rows.uv[x1] = 2 else rows.uv[x1] = if getBit(br, U[3]) == 0 then 3 else 1 end rows.i4[x1] = ymode == 4 rows.ref[x1] = 0 rows.mode[x1] = ymode rows.part[x1] = -1 miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = 0, ymode, 0, 0 return end local ref = 1 if getBit(br, probLast) == 1 then ref = 2 + getBit(br, probGf) end -- the near motion vectors of the above, left and above-left macroblocks, sign corrected local bias = st.signBias local sb = bias[ref + 1] local a = mi - (st.mbw + 1) local l = mi - 1 local al = a - 1 for k = 1, 4 do nr[k], nc[k], cnt[k] = 0, 0, 0 end local n = 1 local rf = miRef[a] if rf ~= 0 then local r, c = miMvR[a], miMvC[a] if r ~= 0 or c ~= 0 then if bias[rf + 1] ~= sb then r, c = -r, -c end n = 2 nr[2], nc[2] = r, c end cnt[n] += 2 end rf = miRef[l] if rf ~= 0 then local r, c = miMvR[l], miMvC[l] if r ~= 0 or c ~= 0 then if bias[rf + 1] ~= sb then r, c = -r, -c end if r ~= nr[n] or c ~= nc[n] then n += 1 nr[n], nc[n] = r, c end cnt[n] += 2 else cnt[1] += 2 end end rf = miRef[al] if rf ~= 0 then local r, c = miMvR[al], miMvC[al] if r ~= 0 or c ~= 0 then if bias[rf + 1] ~= sb then r, c = -r, -c end if r ~= nr[n] or c ~= nc[n] then n += 1 nr[n], nc[n] = r, c end cnt[n] += 1 else cnt[1] += 1 end end -- clamping bounds (vp8_clamp_mv2), in eighth pixels local mbw, mbh = st.mbw, st.mbh local toL, toR = -mbx * 128 - 128, (mbw - 1 - mbx) * 128 + 128 local toT, toB = -mby * 128 - 128, (mbh - 1 - mby) * 128 + 128 local mode, mvr, mvc, part = 5, 0, 0, -1 if getBit(br, MODE_CTX[cnt[1] * 4 + 1]) == 1 then if cnt[4] > 0 and nr[n] == nr[2] and nc[n] == nc[2] then cnt[2] += 1 end if cnt[3] > cnt[2] then cnt[2], cnt[3] = cnt[3], cnt[2] nr[2], nr[3] = nr[3], nr[2] nc[2], nc[3] = nc[3], nc[2] end local k if getBit(br, MODE_CTX[cnt[2] * 4 + 2]) == 0 then mode, k = 6, 2 elseif getBit(br, MODE_CTX[cnt[3] * 4 + 3]) == 0 then mode, k = 7, 3 else k = if cnt[2] >= cnt[1] then 2 else 1 end mvr, mvc = nr[k], nc[k] if mvc < toL then mvc = toL elseif mvc > toR then mvc = toR end if mvr < toT then mvr = toT elseif mvr > toB then mvr = toB end if mode == 5 then -- mvr, mvc: the best vector; new or split local P = st.mvProb local sc = (if miMode[a] == 9 then 2 else 0) + (if miMode[l] == 9 then 2 else 0) + (if miMode[al] == 9 then 1 else 0) if getBit(br, MODE_CTX[sc * 4 + 4]) == 0 then mode = 8 mvr += readMvComponent(br, P, 0) * 2 mvc += readMvComponent(br, P, 19) * 2 else mode = 9 local bestR, bestC = mvr, mvc local s, nump if getBit(br, 110) == 1 then if getBit(br, 111) == 1 then s, nump = getBit(br, 150), 2 else s, nump = 2, 4 end else s, nump = 3, 16 end part = s local subR, subC = st.miSubR, st.miSubC local sb0 = (mi - 1) * 16 local lb, ab = (l - 1) * 16, (a - 1) * 16 local splitL, splitA = miMode[l] == 9, miMode[a] == 9 local count = SPLIT_COUNT[s + 1] for j = 0, nump - 1 do local b = SPLIT_OFFSET[s * 16 + j + 1] local lr, lc, ar, ac if b % 4 ~= 0 then lr, lc = subR[sb0 + b], subC[sb0 + b] elseif splitL then lr, lc = subR[lb + b + 4], subC[lb + b + 4] else lr, lc = miMvR[l], miMvC[l] end if b >= 4 then ar, ac = subR[sb0 + b - 3], subC[sb0 + b - 3] elseif splitA then ar, ac = subR[ab + b + 13], subC[ab + b + 13] else ar, ac = miMvR[a], miMvC[a] end local pi = ((if ar == 0 and ac == 0 then 4 else 0) + (if lr == 0 and lc == 0 then 2 else 0) + (if lr == ar and lc == ac then 1 else 0)) * 3 local r, c if getBit(br, SUB_MV_REF_PROB[pi + 1]) == 0 then r, c = lr, lc elseif getBit(br, SUB_MV_REF_PROB[pi + 2]) == 0 then r, c = ar, ac elseif getBit(br, SUB_MV_REF_PROB[pi + 3]) == 0 then r, c = 0, 0 else r = bestR + readMvComponent(br, P, 0) * 2 c = bestC + readMvComponent(br, P, 19) * 2 end local fo = s * 16 + j * count for i = fo + 1, fo + count do local q = sb0 + SPLIT_FILL[i] + 1 subR[q], subC[q] = r, c end end mvr, mvc = subR[sb0 + 16], subC[sb0 + 16] end end end rows.i4[x1] = mode == 9 rows.ref[x1] = ref rows.mode[x1] = mode rows.part[x1] = part miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = ref, mode, mvr, mvc end type Frame = { width: number, height: number, ref: Ref, header: any, } local BORDER = Predict.BORDER @native local function newRef(mbw: number, mbh: number): Ref local ys, uvs = mbw * 16 + 2 * BORDER, mbw * 8 + 2 * BORDER return { Y = bcreate(ys * (mbh * 16 + 2 * BORDER)), U = bcreate(uvs * (mbh * 8 + 2 * BORDER)), V = bcreate(uvs * (mbh * 8 + 2 * BORDER)), ys = ys, uvs = uvs, yb = BORDER * ys + BORDER, uvb = BORDER * uvs + BORDER, mbw = mbw, mbh = mbh, extended = false, } end @native local function freeRef(st: State): Ref for _, r in st.pool do if r ~= st.last and r ~= st.golden and r ~= st.alt then return r end end local r = newRef(st.mbw, st.mbh) table.insert(st.pool, r) return r end @native function Decode.cropTo(f: Frame, dy: buffer, oy: number, du: buffer, ou: number, dv: buffer, ov: number) local r = f.ref local w, h = f.width, f.height local cw, chh = (w + 1) // 2, (h + 1) // 2 local Y, U, V, ys, uvs, yb, uvb = r.Y, r.U, r.V, r.ys, r.uvs, r.yb, r.uvb for j = 0, h - 1 do bcopy(dy, oy + j * w, Y, yb + j * ys, w) end for j = 0, chh - 1 do bcopy(du, ou + j * cw, U, uvb + j * uvs, cw) bcopy(dv, ov + j * cw, V, uvb + j * uvs, cw) end end @native function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, maxPixels: number): (Frame?, string?) local hdr, herr = Decode.header(buf, off, len) if not hdr then return nil, herr end local key = hdr.keyFrame local width, height, p, left if key then width, height = hdr.width, hdr.height if width == 0 or height == 0 then return nil, "zero frame size" end if width * height > maxPixels then return nil, "limit: " .. width .. " x " .. height .. " is over maxPixels" end p, left = off + 10, len - 10 else if not st.hasKey then return nil, "inter frame without a key frame" end width, height = st.width, st.height p, left = off + 3, len - 3 end if hdr.partitionLength > left then return nil, "truncated: first partition" end local mbw, mbh = (width + 15) // 16, (height + 15) // 16 if key then st.hasKey = false if width ~= st.width or height ~= st.height then st.width, st.height, st.mbw, st.mbh = width, height, mbw, mbh st.last, st.golden, st.alt, st.pool = nil, nil, nil, {} st.miN, st.pred = 0, nil st.segMap = table.create(mbw * mbh, 0) end -- key frames reset the frame context, the segment and loop filter deltas st.proba = table.clone(COEFF_PROBA0) st.ymodeProb = table.clone(Tables.YMODE_PROB) st.uvmodeProb = table.clone(Tables.UVMODE_PROB) st.mvProb = table.clone(Tables.MV_DEFAULT) st.segProba = { 255, 255, 255 } st.useSegment, st.updateMap, st.absoluteDelta = false, false, false st.segQuant = { 0, 0, 0, 0 } st.segFilter = { 0, 0, 0, 0 } st.refLfDelta = { 0, 0, 0, 0 } st.modeLfDelta = { 0, 0, 0, 0 } st.signBias = { 0, 0, 0, 0 } end local br = newBr(buf, p, hdr.partitionLength) p += hdr.partitionLength left -= hdr.partitionLength if key then getValue(br, 1) -- colour space getValue(br, 1) -- clamping type end -- segment header st.useSegment = getValue(br, 1) == 1 if st.useSegment then st.updateMap = getValue(br, 1) == 1 if getValue(br, 1) == 1 then st.absoluteDelta = getValue(br, 1) == 1 for s = 1, 4 do st.segQuant[s] = if getValue(br, 1) == 1 then getSignedValue(br, 7) else 0 end for s = 1, 4 do st.segFilter[s] = if getValue(br, 1) == 1 then getSignedValue(br, 6) else 0 end end if st.updateMap then for s = 1, 3 do st.segProba[s] = if getValue(br, 1) == 1 then getValue(br, 8) else 255 end end else st.updateMap = false end if br.eof then return nil, "truncated: segment header" end -- filter header local simple = getValue(br, 1) == 1 local level = getValue(br, 6) local sharpness = getValue(br, 3) local useLfDelta = getValue(br, 1) == 1 if useLfDelta then if getValue(br, 1) == 1 then for i = 1, 4 do if getValue(br, 1) == 1 then st.refLfDelta[i] = getSignedValue(br, 6) end end for i = 1, 4 do if getValue(br, 1) == 1 then st.modeLfDelta[i] = getSignedValue(br, 6) end end end end local filterType = if level == 0 then 0 elseif simple then 1 else 2 if br.eof then return nil, "truncated: filter header" end -- partitions local numParts = lshift(1, getValue(br, 2)) local lastPart = numParts - 1 if left < 3 * lastPart then return nil, "truncated: partition sizes" end local parts: { Br } = {} local partStart = p + lastPart * 3 local sizeLeft = left - lastPart * 3 for k = 0, lastPart - 1 do local q = p + k * 3 local psize = readu8(buf, q) + readu8(buf, q + 1) * 256 + readu8(buf, q + 2) * 65536 if psize > sizeLeft then psize = sizeLeft end parts[k + 1] = newBr(buf, partStart, psize) partStart += psize sizeLeft -= psize end parts[numParts] = newBr(buf, partStart, sizeLeft) if partStart >= off + len then return nil, "truncated: partitions" end -- quantizers local baseQ = getValue(br, 7) local dqy1dc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 local dqy2dc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 local dqy2ac = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 local dquvdc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 local dquvac = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 local quants: { Quant } = {} for s = 1, 4 do local q if st.useSegment then q = st.segQuant[s] if not st.absoluteDelta then q += baseQ end else q = baseQ end @native local function cq(v: number, m: number): number return if v < 0 then 0 elseif v > m then m else v end local y2ac = (AC_TABLE[cq(q + dqy2ac, 127) + 1] * 101581) // 65536 if y2ac < 8 then y2ac = 8 end quants[s] = { y1dc = DC_TABLE[cq(q + dqy1dc, 127) + 1], y1ac = AC_TABLE[cq(q, 127) + 1], y2dc = DC_TABLE[cq(q + dqy2dc, 127) + 1] * 2, y2ac = y2ac, uvdc = DC_TABLE[cq(q + dquvdc, 117) + 1], uvac = AC_TABLE[cq(q + dquvac, 127) + 1], } end -- reference updates (inter frames) local refreshGolden, refreshAlt, copyToGolden, copyToAlt = true, true, 0, 0 if not key then refreshGolden = getValue(br, 1) == 1 refreshAlt = getValue(br, 1) == 1 copyToGolden = if refreshGolden then 0 else getValue(br, 2) copyToAlt = if refreshAlt then 0 else getValue(br, 2) st.signBias[3] = getValue(br, 1) st.signBias[4] = getValue(br, 1) end -- a frame that does not refresh the context decodes with the updates below, then the context comes back local saved: { { number } }? = nil if getValue(br, 1) == 0 then saved = { table.clone(st.proba), table.clone(st.ymodeProb), table.clone(st.uvmodeProb), table.clone(st.mvProb) } end local refreshLast = key or getValue(br, 1) == 1 -- token probabilities local P = st.proba for i = 1, 1056 do if getBit(br, COEFF_UPDATE_PROBA[i]) == 1 then P[i] = getValue(br, 8) end end local useSkip = getValue(br, 1) == 1 local skipP = if useSkip then getValue(br, 8) else 0 local probIntra, probLast, probGf = 0, 0, 0 if not key then probIntra = getValue(br, 8) probLast = getValue(br, 8) probGf = getValue(br, 8) if getValue(br, 1) == 1 then for i = 1, 4 do st.ymodeProb[i] = getValue(br, 8) end end if getValue(br, 1) == 1 then for i = 1, 3 do st.uvmodeProb[i] = getValue(br, 8) end end local M = st.mvProb for i = 1, 38 do if getBit(br, MV_UPDATE[i]) == 1 then local x = getValue(br, 7) M[i] = if x == 0 then 1 else x * 2 end end end @native local function fail(msg: string): (Frame?, string?) if saved then st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4] end return nil, msg end if br.eof then return fail("truncated: frame header") end -- loop filter levels [segment][reference][mode delta index] and, per level, the interior limit and hev threshold local lvlTab = table.create(64, 0) local ilTab, hevTab = table.create(64, 0), table.create(64, 0) if filterType > 0 then for s = 0, 3 do local base if st.useSegment then base = st.segFilter[s + 1] if not st.absoluteDelta then base += level end else base = level end for rf = 0, 3 do for m = 0, 3 do local lv = base if useLfDelta then lv += st.refLfDelta[rf + 1] if rf > 0 or m == 0 then lv += st.modeLfDelta[m + 1] end end lvlTab[s * 16 + rf * 4 + m + 1] = if lv < 0 then 0 elseif lv > 63 then 63 else lv end end end for lv = 1, 63 do local il = lv if sharpness > 0 then il = rshift(il, if sharpness > 4 then 2 else 1) if il > 9 - sharpness then il = 9 - sharpness end end ilTab[lv] = if il < 1 then 1 else il if key then hevTab[lv] = if lv >= 40 then 2 elseif lv >= 15 then 1 else 0 else hevTab[lv] = if lv >= 40 then 3 elseif lv >= 20 then 2 elseif lv >= 15 then 1 else 0 end end end local cur = freeRef(st) cur.extended = false local Y, U, V, ys, uvs, yb, uvb = cur.Y, cur.U, cur.V, cur.ys, cur.uvs, cur.yb, cur.uvb local refs: { Ref } = {} local bil, full = hdr.profile > 0, hdr.profile == 3 if not key then local rl, rg, ra = st.last :: Ref, st.golden :: Ref, st.alt :: Ref refs[1], refs[2], refs[3] = rl, rg, ra for k = 1, 3 do local r = refs[k] if not r.extended then Predict.extend(r) r.extended = true end end end local topY, topU, topV = bcreate(mbw * 16), bcreate(mbw * 8), bcreate(mbw * 8) local yuv = bcreate(YUV_SIZE) local pred = yuv if not key then local nmi = (mbw + 1) * (mbh + 1) if st.miN ~= nmi then -- zero top row and left column: never written, they read as intra macroblocks without motion st.miRef, st.miMode = table.create(nmi, 0), table.create(nmi, 0) st.miMvR, st.miMvC = table.create(nmi, 0), table.create(nmi, 0) st.miSubR, st.miSubC = table.create(nmi * 16, 0), table.create(nmi * 16, 0) st.miN = nmi st.pred = bcreate(YUV_SIZE * mbw) end pred = st.pred :: buffer end local coeffs = bcreate(mbw * 768) local dcb = bcreate(32) local intraT = table.create(mbw * 4, 0) local intraL = table.create(4, 0) local topNz = table.create(mbw, 0) local topNzDc = table.create(mbw, 0) local rows: Rows = { i4 = table.create(mbw, false), modes = table.create(mbw * 16, 0), uv = table.create(mbw, 0), ref = table.create(mbw, 0), mode = table.create(mbw, 0), part = table.create(mbw, -1), } local mbI4, mbModes, mbUv, mbRef, mbMode, mbPart = rows.i4, rows.modes, rows.uv, rows.ref, rows.mode, rows.part local mbSeg = table.create(mbw, 0) local mbSkip = table.create(mbw, 0) local mbNzY = table.create(mbw, 0) local mbNzUv = table.create(mbw, 0) local fLimit = table.create(mbw * mbh, 0) local fIlevel = table.create(mbw * mbh, 0) local fInner = table.create(mbw * mbh, 0) local fHev = table.create(mbw * mbh, 0) local segProba = st.segProba local segMap = st.segMap local updateMap = st.updateMap local miMvR, miMvC, miSubR, miSubC = st.miMvR, st.miMvC, st.miSubR, st.miSubC for mby = 0, mbh - 1 do local tbr = parts[band(mby, lastPart) + 1] -- modes of the row (first partition) for k = 1, 4 do intraL[k] = 0 end for mbx = 0, mbw - 1 do local x1 = mbx + 1 local si = mby * mbw + x1 local seg if updateMap then if getBit(br, segProba[1]) == 0 then seg = getBit(br, segProba[2]) else seg = getBit(br, segProba[3]) + 2 end segMap[si] = seg elseif key then seg = 0 segMap[si] = 0 else seg = segMap[si] end mbSeg[x1] = seg mbSkip[x1] = 0 if useSkip then mbSkip[x1] = getBit(br, skipP) end if not key then readInterMb(st, br, probIntra, probLast, probGf, (mby + 1) * (mbw + 1) + x1 + 1, mbx, mby, rows) continue end mbRef[x1] = 0 mbPart[x1] = -1 local i4 = getBit(br, 145) == 0 mbI4[x1] = i4 local t0 = mbx * 4 if not i4 then local ymode if getBit(br, 156) == 1 then ymode = if getBit(br, 128) == 1 then 1 else 3 else ymode = if getBit(br, 163) == 1 then 2 else 0 end mbModes[mbx * 16 + 1] = ymode mbMode[x1] = ymode for k = 1, 4 do intraT[t0 + k] = ymode intraL[k] = ymode end else mbMode[x1] = 4 for y = 0, 3 do local ymode = intraL[y + 1] for x = 0, 3 do local pr = (intraT[t0 + x + 1] * 10 + ymode) * 9 if getBit(br, BMODES_PROBA[pr + 1]) == 0 then ymode = 0 elseif getBit(br, BMODES_PROBA[pr + 2]) == 0 then ymode = 1 elseif getBit(br, BMODES_PROBA[pr + 3]) == 0 then ymode = 2 elseif getBit(br, BMODES_PROBA[pr + 4]) == 0 then if getBit(br, BMODES_PROBA[pr + 5]) == 0 then ymode = 3 elseif getBit(br, BMODES_PROBA[pr + 6]) == 0 then ymode = 4 else ymode = 5 end elseif getBit(br, BMODES_PROBA[pr + 7]) == 0 then ymode = 6 elseif getBit(br, BMODES_PROBA[pr + 8]) == 0 then ymode = 7 elseif getBit(br, BMODES_PROBA[pr + 9]) == 0 then ymode = 8 else ymode = 9 end intraT[t0 + x + 1] = ymode mbModes[mbx * 16 + y * 4 + x + 1] = ymode end intraL[y + 1] = ymode end end if getBit(br, 142) == 0 then mbUv[x1] = 0 elseif getBit(br, 114) == 0 then mbUv[x1] = 2 else mbUv[x1] = if getBit(br, 183) == 1 then 1 else 3 end end if br.eof then return fail("truncated: first partition (modes)") end -- residuals (token partition) local leftNz, leftNzDc = 0, 0 for mbx = 0, mbw - 1 do local x1 = mbx + 1 local q = quants[mbSeg[x1] + 1] local skip = mbSkip[x1] local i4 = mbI4[x1] if skip == 0 then local co = mbx * 768 bfill(coeffs, co, 0, 768) local first, acType local dcNz = 0 if not i4 then bfill(dcb, 0, 0, 32) local ctx = topNzDc[x1] + leftNzDc local nz = getCoeffs(tbr, P, 1, ctx, q.y2dc, q.y2ac, 0, dcb, 0) dcNz = if nz > 0 then 1 else 0 topNzDc[x1] = dcNz leftNzDc = dcNz if nz > 1 then transformWHT(dcb, coeffs, co) else local dc0 = (readi16(dcb, 0) + 3) // 8 for i = 0, 15 do writei16(coeffs, co + i * 32, dc0) end end first, acType = 1, 0 else first, acType = 0, 3 end local tnz = band(topNz[x1], 0x0f) local lnz = band(leftNz, 0x0f) local nzY = 0 local dst = co for _ = 0, 3 do local l = band(lnz, 1) local acc = 0 for _ = 0, 3 do local ctx = l + band(tnz, 1) local nz = getCoeffs(tbr, P, acType, ctx, q.y1dc, q.y1ac, first, coeffs, dst) l = if nz > first then 1 else 0 tnz = bor(rshift(tnz, 1), l * 128) acc = nzCode(acc, nz, if readi16(coeffs, dst) ~= 0 then 1 else 0) dst += 32 end tnz = rshift(tnz, 4) lnz = bor(rshift(lnz, 1), l * 128) nzY = nzY * 256 + acc end local outT = tnz local outL = rshift(lnz, 4) local nzUv = 0 for ch = 0, 2, 2 do local acc = 0 tnz = band(rshift(topNz[x1], 4 + ch), 255) lnz = band(rshift(leftNz, 4 + ch), 255) for _ = 0, 1 do local l = band(lnz, 1) for _ = 0, 1 do local ctx = l + band(tnz, 1) local nz = getCoeffs(tbr, P, 2, ctx, q.uvdc, q.uvac, 0, coeffs, dst) l = if nz > 0 then 1 else 0 tnz = bor(rshift(tnz, 1), l * 8) acc = nzCode(acc, nz, if readi16(coeffs, dst) ~= 0 then 1 else 0) dst += 32 end tnz = rshift(tnz, 2) lnz = bor(rshift(lnz, 1), l * 32) end nzUv = bor(nzUv, lshift(acc, 4 * ch)) outT = bor(outT, lshift(lshift(tnz, 4), ch)) outL = bor(outL, lshift(band(lnz, 0xf0), ch)) end topNz[x1] = band(outT, 255) leftNz = band(outL, 255) mbNzY[x1] = nzY mbNzUv[x1] = nzUv -- no coefficient at all (libvpx: eobtotal == 0) skips the inner edges of the loop filter skip = if nzY == 0 and nzUv == 0 and dcNz == 0 then 1 else 0 else topNz[x1] = 0 leftNz = 0 if not i4 then topNzDc[x1] = 0 leftNzDc = 0 end mbNzY[x1] = 0 mbNzUv[x1] = 0 end if filterType > 0 then local lv = lvlTab[mbSeg[x1] * 16 + mbRef[x1] * 4 + MODE_LF[mbMode[x1] + 1] + 1] local fi = mby * mbw + x1 if lv > 0 then local il = ilTab[lv] fLimit[fi] = 2 * lv + il fIlevel[fi] = il fHev[fi] = hevTab[lv] else fLimit[fi] = 0 end fInner[fi] = if i4 or skip == 0 then 1 else 0 end if tbr.eof then return fail("truncated: token partition") end end -- reconstruct the row (libwebp ReconstructRow; inter macroblocks predict from the references) if not key then Predict.row(refs :: any, mby, mbw, mbRef, mbPart, miMvR, miMvC, miSubR, miSubC, (mby + 1) * (mbw + 1) + 1, pred, YUV_SIZE, Y_OFF, U_OFF, V_OFF, bil, full) end for j = 0, 15 do writeu8(yuv, Y_OFF + j * BPS - 1, 129) end for j = 0, 7 do writeu8(yuv, U_OFF + j * BPS - 1, 129) writeu8(yuv, V_OFF + j * BPS - 1, 129) end if mby > 0 then writeu8(yuv, Y_OFF - 1 - BPS, 129) writeu8(yuv, U_OFF - 1 - BPS, 129) writeu8(yuv, V_OFF - 1 - BPS, 129) else bfill(yuv, Y_OFF - BPS - 1, 127, 16 + 4 + 1) bfill(yuv, U_OFF - BPS - 1, 127, 8 + 1) bfill(yuv, V_OFF - BPS - 1, 127, 8 + 1) end for mbx = 0, mbw - 1 do local x1 = mbx + 1 local co = mbx * 768 local bits = mbNzY[x1] local rf = mbRef[x1] if rf == 0 and mbx > 0 then -- the left context of an intra macroblock: the previous macroblock's last columns for j = -1, 15 do writeu32(yuv, Y_OFF + j * BPS - 4, readu32(yuv, Y_OFF + j * BPS + 12)) end for j = -1, 7 do writeu32(yuv, U_OFF + j * BPS - 4, readu32(yuv, U_OFF + j * BPS + 4)) writeu32(yuv, V_OFF + j * BPS - 4, readu32(yuv, V_OFF + j * BPS + 4)) end end if mby > 0 then local t = mbx * 16 writeu32(yuv, Y_OFF - BPS, readu32(topY, t)) writeu32(yuv, Y_OFF - BPS + 4, readu32(topY, t + 4)) writeu32(yuv, Y_OFF - BPS + 8, readu32(topY, t + 8)) writeu32(yuv, Y_OFF - BPS + 12, readu32(topY, t + 12)) t = mbx * 8 writeu32(yuv, U_OFF - BPS, readu32(topU, t)) writeu32(yuv, U_OFF - BPS + 4, readu32(topU, t + 4)) writeu32(yuv, V_OFF - BPS, readu32(topV, t)) writeu32(yuv, V_OFF - BPS + 4, readu32(topV, t + 4)) end if rf > 0 then -- the prediction (Predict.row): luma rows 0..15, then the chroma rows (U and V side by side) local o = mbx * YUV_SIZE bcopy(yuv, Y_OFF, pred, o + Y_OFF, 15 * BPS + 16) bcopy(yuv, U_OFF, pred, o + U_OFF, 7 * BPS + 24) if bits ~= 0 then for n = 0, 15 do local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) end end else if mbI4[x1] then local tr = Y_OFF - BPS + 16 if mby > 0 then if mbx >= mbw - 1 then writeu32(yuv, tr, readu8(topY, mbx * 16 + 15) * 0x01010101) else writeu32(yuv, tr, readu32(topY, mbx * 16 + 16)) end end local trv = readu32(yuv, tr) writeu32(yuv, tr + 4 * BPS, trv) writeu32(yuv, tr + 8 * BPS, trv) writeu32(yuv, tr + 12 * BPS, trv) for n = 0, 15 do local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS predict4(yuv, dst, mbModes[mbx * 16 + n + 1]) doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) end else predictBlock(yuv, Y_OFF, 16, checkMode(mbx, mby, mbModes[mbx * 16 + 1])) if bits ~= 0 then for n = 0, 15 do local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) end end end local uvm = checkMode(mbx, mby, mbUv[x1]) predictBlock(yuv, U_OFF, 8, uvm) predictBlock(yuv, V_OFF, 8, uvm) end local buv = mbNzUv[x1] doUVTransform(buv, coeffs, co + 16 * 32, yuv, U_OFF) doUVTransform(rshift(buv, 8), coeffs, co + 20 * 32, yuv, V_OFF) if mby < mbh - 1 then local t = mbx * 16 local r = Y_OFF + 15 * BPS writeu32(topY, t, readu32(yuv, r)) writeu32(topY, t + 4, readu32(yuv, r + 4)) writeu32(topY, t + 8, readu32(yuv, r + 8)) writeu32(topY, t + 12, readu32(yuv, r + 12)) t = mbx * 8 r = U_OFF + 7 * BPS writeu32(topU, t, readu32(yuv, r)) writeu32(topU, t + 4, readu32(yuv, r + 4)) writeu32(topV, t, readu32(yuv, r + 16)) writeu32(topV, t + 4, readu32(yuv, r + 20)) end local yo = yb + mby * 16 * ys + mbx * 16 for j = 0, 15 do local d, r = yo + j * ys, Y_OFF + j * BPS writeu32(Y, d, readu32(yuv, r)) writeu32(Y, d + 4, readu32(yuv, r + 4)) writeu32(Y, d + 8, readu32(yuv, r + 8)) writeu32(Y, d + 12, readu32(yuv, r + 12)) end local uo = uvb + mby * 8 * uvs + mbx * 8 for j = 0, 7 do local d, r = uo + j * uvs, U_OFF + j * BPS writeu32(U, d, readu32(yuv, r)) writeu32(U, d + 4, readu32(yuv, r + 4)) writeu32(V, d, readu32(yuv, r + 16)) writeu32(V, d + 4, readu32(yuv, r + 20)) end end end -- loop filter over the whole frame, macroblocks in raster order (libwebp DoFilter) if filterType > 0 then for mby = 0, mbh - 1 do for mbx = 0, mbw - 1 do local fi = mby * mbw + mbx + 1 local limit = fLimit[fi] if limit ~= 0 then local inner = fInner[fi] == 1 local yp = yb + mby * 16 * ys + mbx * 16 if filterType == 1 then if mbx > 0 then simpleFilter(Y, yp, 1, ys, limit + 4) end if inner then for k = 1, 3 do simpleFilter(Y, yp + 4 * k, 1, ys, limit) end end if mby > 0 then simpleFilter(Y, yp, ys, 1, limit + 4) end if inner then for k = 1, 3 do simpleFilter(Y, yp + 4 * k * ys, ys, 1, limit) end end else local il, hev = fIlevel[fi], fHev[fi] local up = uvb + mby * 8 * uvs + mbx * 8 if mbx > 0 then filterEdge(Y, yp, 1, ys, 16, limit + 4, il, hev) filterEdge(U, up, 1, uvs, 8, limit + 4, il, hev) filterEdge(V, up, 1, uvs, 8, limit + 4, il, hev) end if inner then for k = 1, 3 do filterInner(Y, yp + 4 * k, 1, ys, 16, limit, il, hev) end filterInner(U, up + 4, 1, uvs, 8, limit, il, hev) filterInner(V, up + 4, 1, uvs, 8, limit, il, hev) end if mby > 0 then filterEdge(Y, yp, ys, 1, 16, limit + 4, il, hev) filterEdge(U, up, uvs, 1, 8, limit + 4, il, hev) filterEdge(V, up, uvs, 1, 8, limit + 4, il, hev) end if inner then for k = 1, 3 do filterInner(Y, yp + 4 * k * ys, ys, 1, 16, limit, il, hev) end filterInner(U, up + 4 * uvs, uvs, 1, 8, limit, il, hev) filterInner(V, up + 4 * uvs, uvs, 1, 8, limit, il, hev) end end end end end end -- the references (libvpx swap_frame_buffers; copies read the references of the previous frame, as ffmpeg does) if key then st.last, st.golden, st.alt = cur, cur, cur st.hasKey = true else local oldLast, oldGolden, oldAlt = st.last, st.golden, st.alt if refreshGolden then st.golden = cur elseif copyToGolden == 1 then st.golden = oldLast elseif copyToGolden == 2 then st.golden = oldAlt end if refreshAlt then st.alt = cur elseif copyToAlt == 1 then st.alt = oldLast elseif copyToAlt == 2 then st.alt = oldGolden end if refreshLast then st.last = cur end end if saved then st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4] end return { width = width, height = height, ref = cur, header = hdr }, nil end return Decode end __FILES["codecs/image/Vp8/Predict"] = @native function() -- codecs/image/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18), after libvpx 1.17 vp8/common/reconinter.c and -- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the edge pixels extended forever, -- which equals libvpx's 32 pixel border plus its motion vector clamping. local Tables = __include("codecs/image/Vp8/Tables") local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill local readu32, writeu32 = buffer.readu32, buffer.writeu32 local rshift, band = bit32.rshift, bit32.band local SIX, BIL = Tables.SIXTAP, Tables.BILINEAR local Predict = {} local BORDER = 32 Predict.BORDER = BORDER local BPS = 32 local emu = bcreate(32 * 32) local tmp = bcreate(32 * 32) -- six-tap along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7) @native local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) local k = f * 6 local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] for _ = 1, h do for i = so - 2, so + w - 3 do local v = readu8(src, i) * t0 + readu8(src, i + 1) * t1 + readu8(src, i + 2) * t2 + readu8(src, i + 3) * t3 + readu8(src, i + 4) * t4 + readu8(src, i + 5) * t5 + 64 writeu8(dst, d + i - so + 2, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7)) end so += ss d += ds end end @native local function sixV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) local k = f * 6 local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] local s1, s2, s3 = ss, 2 * ss, 3 * ss for _ = 1, h do local p = so - s2 for i = 0, w - 1 do local q = p + i local v = readu8(src, q) * t0 + readu8(src, q + s1) * t1 + readu8(src, q + s2) * t2 + readu8(src, q + s3) * t3 + readu8(src, q + s2 + s2) * t4 + readu8(src, q + s2 + s3) * t5 + 64 writeu8(dst, d + i, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7)) end so += ss d += ds end end -- the bilinear filters: dst[i] = (src[i] * t0 + src[i + 1] * t1 + 64) >> 7 @native local function bilH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] for _ = 1, h do for i = 0, w - 1 do writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + i + 1) * t1 + 64, 7)) end so += ss d += ds end end @native local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] for _ = 1, h do for i = 0, w - 1 do writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + ss + i) * t1 + 64, 7)) end so += ss d += ds end end @native local function block(src: buffer, stride: number, base: number, wmax: number, hmax: number, x: number, y: number, mvx: number, mvy: number, w: number, h: number, dst: buffer, d: number, bil: boolean) local fx, fy = band(mvx, 7), band(mvy, 7) local px, py = x + (mvx - fx) // 8, y + (mvy - fy) // 8 local sb, so, ss = src, 0, stride if px >= 2 - BORDER and py >= 2 - BORDER and px + w + 3 <= wmax + 1 + BORDER and py + h + 3 <= hmax + 1 + BORDER then so = base + py * stride + px else for r = 0, h + 4 do local sy = py - 2 + r if sy < 0 then sy = 0 elseif sy > hmax then sy = hmax end local row = base + sy * stride local o = r * 32 for c = 0, w + 4 do local sx = px - 2 + c if sx < 0 then sx = 0 elseif sx > wmax then sx = wmax end writeu8(emu, o + c, readu8(src, row + sx)) end end sb, so, ss = emu, 66, 32 end if fx == 0 then if fy == 0 then for _ = 1, h do for i = 0, w - 4, 4 do writeu32(dst, d + i, readu32(sb, so + i)) end so += ss d += BPS end elseif bil then bilV(sb, so, ss, dst, d, BPS, w, h, fy) else sixV(sb, so, ss, dst, d, BPS, w, h, fy) end elseif fy == 0 then if bil then bilH(sb, so, ss, dst, d, BPS, w, h, fx) else sixH(sb, so, ss, dst, d, BPS, w, h, fx) end elseif bil then bilH(sb, so, ss, tmp, 0, 32, w, h + 1, fx) bilV(tmp, 0, 32, dst, d, BPS, w, h, fy) else sixH(sb, so - 2 * ss, ss, tmp, 0, 32, w, h + 5, fx) sixV(tmp, 64, 32, dst, d, BPS, w, h, fy) end end @native local function chroma16(v: number): number -- the chroma vector of a whole macroblock: half the luma one, rounded away from zero if v < 0 then return -((1 - v) // 2) end return (v + 1) // 2 end @native local function chroma4(s: number): number -- the chroma vector of a 2x2 group of luma blocks: the sum of their 4 vectors / 8, rounded half away from zero if s < 0 then return -((4 - s) // 8) end return (s + 4) // 8 end type Planes = { Y: buffer, U: buffer, V: buffer, ys: number, uvs: number, yb: number, uvb: number, mbw: number, mbh: number, } @native function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: number, part: number, subR: { number }, subC: { number }, sb: number, dst: buffer, yo: number, uo: number, vo: number, bil: boolean, full: boolean) local Y, U, V, ys, uvs, yb, uvb = ref.Y, ref.U, ref.V, ref.ys, ref.uvs, ref.yb, ref.uvb local wl, hl = ref.mbw * 16 - 1, ref.mbh * 16 - 1 local wc, hc = ref.mbw * 8 - 1, ref.mbh * 8 - 1 local x, y = mbx * 16, mby * 16 local cx, cy = mbx * 8, mby * 8 if part < 0 then block(Y, ys, yb, wl, hl, x, y, mvc, mvr, 16, 16, dst, yo, bil) local cr, cc = chroma16(mvr), chroma16(mvc) if full then cr -= band(cr, 7) cc -= band(cc, 7) end block(U, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, uo, bil) block(V, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, vo, bil) return end if part < 3 then for q = 0, 3 do local bx, by = (q % 2) * 8, (q // 2) * 8 local k = sb + by + bx // 4 + 1 block(Y, ys, yb, wl, hl, x + bx, y + by, subC[k], subR[k], 8, 8, dst, yo + by * BPS + bx, bil) end else for b = 0, 15, 2 do local k = sb + b + 1 local bx, by = (b % 4) * 4, (b // 4) * 4 local r0, c0 = subR[k], subC[k] if r0 == subR[k + 1] and c0 == subC[k + 1] then block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 8, 4, dst, yo + by * BPS + bx, bil) else block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 4, 4, dst, yo + by * BPS + bx, bil) block(Y, ys, yb, wl, hl, x + bx + 4, y + by, subC[k + 1], subR[k + 1], 4, 4, dst, yo + by * BPS + bx + 4, bil) end end end for i = 0, 1 do local rr, rc = 0, 0 for j = 0, 1 do local k = sb + i * 8 + j * 2 + 1 local cr = chroma4(subR[k] + subR[k + 1] + subR[k + 4] + subR[k + 5]) local cc = chroma4(subC[k] + subC[k + 1] + subC[k + 4] + subC[k + 5]) if full then cr -= band(cr, 7) cc -= band(cc, 7) end if j == 0 then rr, rc = cr, cc elseif cr == rr and cc == rc then -- both 4x4 chroma blocks of the row share one vector: one 8x4 block block(U, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, uo + i * 4 * BPS, bil) block(V, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, vo + i * 4 * BPS, bil) else block(U, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, uo + i * 4 * BPS, bil) block(V, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, vo + i * 4 * BPS, bil) block(U, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, uo + i * 4 * BPS + 4, bil) block(V, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, vo + i * 4 * BPS + 4, bil) end end end end @native function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number }, part: { number }, miMvR: { number }, miMvC: { number }, miSubR: { number }, miSubC: { number }, mi0: number, pred: buffer, chunk: number, yo: number, uo: number, vo: number, bil: boolean, full: boolean) for mbx = 0, mbw - 1 do local rf = ref[mbx + 1] if rf > 0 then local mi = mi0 + mbx + 1 local o = mbx * chunk Predict.mb(refs[rf], mbx, mby, miMvR[mi], miMvC[mi], part[mbx + 1], miSubR, miSubC, (mi - 1) * 16, pred, o + yo, o + uo, o + vo, bil, full) end end end @native local function extend(P: buffer, stride: number, base: number, w: number, h: number) for r = 0, h - 1 do local o = base + r * stride bfill(P, o - BORDER, readu8(P, o), BORDER) bfill(P, o + w, readu8(P, o + w - 1), BORDER) end local top = base - BORDER local bottom = base + (h - 1) * stride - BORDER for r = 1, BORDER do bcopy(P, top - r * stride, P, top, stride) bcopy(P, bottom + r * stride, P, bottom, stride) end end @native function Predict.extend(ref: Planes) extend(ref.Y, ref.ys, ref.yb, ref.mbw * 16, ref.mbh * 16) extend(ref.U, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) extend(ref.V, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) end return Predict end __FILES["codecs/image/Vp8/Tables"] = function() -- codecs/image/Vp8/Tables: the VP8 tables of RFC 6386 (sections 11.5, 13.4, 13.5, 14.1, 16-18), from libwebp 1.6 src/dec -- (BSD-3-Clause, licenses/libwebp-LICENSE.txt) and libvpx 1.17 vp8/common (BSD-3-Clause, licenses/libvpx-LICENSE.txt). -- Flat 1-based arrays. local Tables = {} -- default token probabilities [type 4][band 8][ctx 3][proba 11]: index ((t * 8 + b) * 3 + c) * 11 + p + 1 Tables.COEFF_PROBA0 = { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128, 189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128, 106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128, 1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128, 181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128, 78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128, 1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128, 184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128, 77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128, 1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128, 170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128, 37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128, 1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128, 207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128, 102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128, 1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128, 177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128, 80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62, 131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1, 68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128, 1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128, 184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128, 81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128, 1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128, 99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128, 23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128, 1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128, 109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128, 44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128, 1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128, 94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128, 22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128, 1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128, 124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128, 35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128, 1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128, 121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128, 45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128, 1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128, 203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128, 137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128, 253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128, 175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128, 73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128, 1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128, 239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128, 155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128, 1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128, 201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128, 69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128, 1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128, 223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128, 141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128, 1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128, 190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128, 149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128, 247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128, 240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128, 1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128, 213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128, 55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255, 126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128, 61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128, 1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128, 166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128, 39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128, 1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128, 124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128, 24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128, 1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128, 149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128, 28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128, 1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128, 123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128, 20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128, 1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128, 168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128, 47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128, 1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128, 141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128, 42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, } -- token probability update probabilities, same layout Tables.COEFF_UPDATE_PROBA = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255, 223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255, 249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255, 234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255, 239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255, 250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255, 234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255, 234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255, 251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255, 248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, 246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255, 248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255, 245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, } -- 4x4 intra mode probabilities [top 10][left 10][9]: index (top * 10 + left) * 9 + i + 1 Tables.BMODES_PROBA = { 231, 120, 48, 89, 115, 113, 120, 152, 112, 152, 179, 64, 126, 170, 118, 46, 70, 95, 175, 69, 143, 80, 85, 82, 72, 155, 103, 56, 58, 10, 171, 218, 189, 17, 13, 152, 114, 26, 17, 163, 44, 195, 21, 10, 173, 121, 24, 80, 195, 26, 62, 44, 64, 85, 144, 71, 10, 38, 171, 213, 144, 34, 26, 170, 46, 55, 19, 136, 160, 33, 206, 71, 63, 20, 8, 114, 114, 208, 12, 9, 226, 81, 40, 11, 96, 182, 84, 29, 16, 36, 134, 183, 89, 137, 98, 101, 106, 165, 148, 72, 187, 100, 130, 157, 111, 32, 75, 80, 66, 102, 167, 99, 74, 62, 40, 234, 128, 41, 53, 9, 178, 241, 141, 26, 8, 107, 74, 43, 26, 146, 73, 166, 49, 23, 157, 65, 38, 105, 160, 51, 52, 31, 115, 128, 104, 79, 12, 27, 217, 255, 87, 17, 7, 87, 68, 71, 44, 114, 51, 15, 186, 23, 47, 41, 14, 110, 182, 183, 21, 17, 194, 66, 45, 25, 102, 197, 189, 23, 18, 22, 88, 88, 147, 150, 42, 46, 45, 196, 205, 43, 97, 183, 117, 85, 38, 35, 179, 61, 39, 53, 200, 87, 26, 21, 43, 232, 171, 56, 34, 51, 104, 114, 102, 29, 93, 77, 39, 28, 85, 171, 58, 165, 90, 98, 64, 34, 22, 116, 206, 23, 34, 43, 166, 73, 107, 54, 32, 26, 51, 1, 81, 43, 31, 68, 25, 106, 22, 64, 171, 36, 225, 114, 34, 19, 21, 102, 132, 188, 16, 76, 124, 62, 18, 78, 95, 85, 57, 50, 48, 51, 193, 101, 35, 159, 215, 111, 89, 46, 111, 60, 148, 31, 172, 219, 228, 21, 18, 111, 112, 113, 77, 85, 179, 255, 38, 120, 114, 40, 42, 1, 196, 245, 209, 10, 25, 109, 88, 43, 29, 140, 166, 213, 37, 43, 154, 61, 63, 30, 155, 67, 45, 68, 1, 209, 100, 80, 8, 43, 154, 1, 51, 26, 71, 142, 78, 78, 16, 255, 128, 34, 197, 171, 41, 40, 5, 102, 211, 183, 4, 1, 221, 51, 50, 17, 168, 209, 192, 23, 25, 82, 138, 31, 36, 171, 27, 166, 38, 44, 229, 67, 87, 58, 169, 82, 115, 26, 59, 179, 63, 59, 90, 180, 59, 166, 93, 73, 154, 40, 40, 21, 116, 143, 209, 34, 39, 175, 47, 15, 16, 183, 34, 223, 49, 45, 183, 46, 17, 33, 183, 6, 98, 15, 32, 183, 57, 46, 22, 24, 128, 1, 54, 17, 37, 65, 32, 73, 115, 28, 128, 23, 128, 205, 40, 3, 9, 115, 51, 192, 18, 6, 223, 87, 37, 9, 115, 59, 77, 64, 21, 47, 104, 55, 44, 218, 9, 54, 53, 130, 226, 64, 90, 70, 205, 40, 41, 23, 26, 57, 54, 57, 112, 184, 5, 41, 38, 166, 213, 30, 34, 26, 133, 152, 116, 10, 32, 134, 39, 19, 53, 221, 26, 114, 32, 73, 255, 31, 9, 65, 234, 2, 15, 1, 118, 73, 75, 32, 12, 51, 192, 255, 160, 43, 51, 88, 31, 35, 67, 102, 85, 55, 186, 85, 56, 21, 23, 111, 59, 205, 45, 37, 192, 55, 38, 70, 124, 73, 102, 1, 34, 98, 125, 98, 42, 88, 104, 85, 117, 175, 82, 95, 84, 53, 89, 128, 100, 113, 101, 45, 75, 79, 123, 47, 51, 128, 81, 171, 1, 57, 17, 5, 71, 102, 57, 53, 41, 49, 38, 33, 13, 121, 57, 73, 26, 1, 85, 41, 10, 67, 138, 77, 110, 90, 47, 114, 115, 21, 2, 10, 102, 255, 166, 23, 6, 101, 29, 16, 10, 85, 128, 101, 196, 26, 57, 18, 10, 102, 102, 213, 34, 20, 43, 117, 20, 15, 36, 163, 128, 68, 1, 26, 102, 61, 71, 37, 34, 53, 31, 243, 192, 69, 60, 71, 38, 73, 119, 28, 222, 37, 68, 45, 128, 34, 1, 47, 11, 245, 171, 62, 17, 19, 70, 146, 85, 55, 62, 70, 37, 43, 37, 154, 100, 163, 85, 160, 1, 63, 9, 92, 136, 28, 64, 32, 201, 85, 75, 15, 9, 9, 64, 255, 184, 119, 16, 86, 6, 28, 5, 64, 255, 25, 248, 1, 56, 8, 17, 132, 137, 255, 55, 116, 128, 58, 15, 20, 82, 135, 57, 26, 121, 40, 164, 50, 31, 137, 154, 133, 25, 35, 218, 51, 103, 44, 131, 131, 123, 31, 6, 158, 86, 40, 64, 135, 148, 224, 45, 183, 128, 22, 26, 17, 131, 240, 154, 14, 1, 209, 45, 16, 21, 91, 64, 222, 7, 1, 197, 56, 21, 39, 155, 60, 138, 23, 102, 213, 83, 12, 13, 54, 192, 255, 68, 47, 28, 85, 26, 85, 85, 128, 128, 32, 146, 171, 18, 11, 7, 63, 144, 171, 4, 4, 246, 35, 27, 10, 146, 174, 171, 12, 26, 128, 190, 80, 35, 99, 180, 80, 126, 54, 45, 85, 126, 47, 87, 176, 51, 41, 20, 32, 101, 75, 128, 139, 118, 146, 116, 128, 85, 56, 41, 15, 176, 236, 85, 37, 9, 62, 71, 30, 17, 119, 118, 255, 17, 18, 138, 101, 38, 60, 138, 55, 70, 43, 26, 142, 146, 36, 19, 30, 171, 255, 97, 27, 20, 138, 45, 61, 62, 219, 1, 81, 188, 64, 32, 41, 20, 117, 151, 142, 20, 21, 163, 112, 19, 12, 61, 195, 128, 48, 4, 24, } -- DC dequantization factors, index q + 1 (q 0..127) Tables.DC_TABLE = { 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157, } -- AC dequantization factors, index q + 1 Tables.AC_TABLE = { 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205, 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284, } -- coefficient band of each position (with a sentinel for position 16) Tables.BANDS = { 0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0 } -- zigzag scan: coefficient n goes to position ZIGZAG[n + 1] Tables.ZIGZAG = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 } -- extra bits probabilities for the DCT_CAT3..6 tokens Tables.CAT3 = { 173, 148, 140 } Tables.CAT4 = { 176, 155, 140, 135 } Tables.CAT5 = { 180, 157, 141, 134, 130 } Tables.CAT6 = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 } -- inter frames: default intra mode probabilities (16x16 / chroma, kept in the frame context) and the fixed 4x4 ones Tables.YMODE_PROB = { 112, 86, 140, 37 } Tables.UVMODE_PROB = { 162, 101, 204 } Tables.BMODE_PROB = { 120, 90, 79, 133, 87, 85, 80, 111, 151 } -- motion vector probabilities, row then column (19 each): is short, sign, short tree (7), long bits (10) Tables.MV_DEFAULT = { 162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254, 164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, 254, } Tables.MV_UPDATE = { 237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254, 231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254, } -- mode contexts [count 0..5][tree node 0..3]: index count * 4 + node + 1 Tables.MODE_CONTEXTS = { 7, 1, 1, 143, 14, 18, 14, 107, 135, 64, 57, 68, 60, 56, 128, 65, 159, 134, 128, 34, 234, 188, 128, 28, } -- sub-block motion vector reference probabilities [(above zero << 2) | (left zero << 1) | (left == above)][3] Tables.SUB_MV_REF_PROB = { 147, 136, 18, 223, 1, 34, 106, 145, 1, 208, 1, 1, 179, 121, 1, 223, 1, 34, 179, 121, 1, 208, 1, 1, } -- split partitions (16x8, 8x16, 8x8, 4x4): the first block of each partition [s * 16 + j + 1], the blocks of each -- partition in order [s * 16 + j * count + i + 1], and the number of blocks per partition Tables.SPLIT_OFFSET = { 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, } Tables.SPLIT_FILL = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15, 0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, } Tables.SPLIT_COUNT = { 8, 8, 4, 1 } -- the six-tap sub-pixel filters [fraction 0..7][tap 0..5] and the bilinear ones [fraction][2] (versions 1-3) Tables.SIXTAP = { 0, 0, 128, 0, 0, 0, 0, -6, 123, 12, -1, 0, 2, -11, 108, 36, -8, 1, 0, -9, 93, 50, -6, 0, 3, -16, 77, 77, -16, 3, 0, -6, 50, 93, -9, 0, 1, -8, 36, 108, -11, 2, 0, -1, 12, 123, -6, 0, } Tables.BILINEAR = { 128, 0, 112, 16, 96, 32, 80, 48, 64, 64, 48, 80, 32, 96, 16, 112 } return Tables end __FILES["codecs/image/Vp8/Yuv"] = @native function() -- codecs/image/Vp8/Yuv: 4:2:0 BT.601 limited-range Y'CbCr -> rgba8, bit-exact with libwebp (src/dsp/yuv.h VP8YuvToRgb; -- src/dsp/upsampling.c "fancy" 9-3-3-1 upsampler, or point sampling as dwebp -nofancy). A port of libwebp 1.6 -- (BSD-3-Clause, licenses/libwebp-LICENSE.txt). local rshift = bit32.rshift local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 local bcreate = buffer.create local Yuv = {} @native local function clip(v: number): number -- VP8Clip8: v in 14-bit fixed point if v >= 0 and v < 16384 then return rshift(v, 6) end return if v < 0 then 0 else 255 end @native local function mulHi(v: number, c: number): number return rshift(v * c, 8) end @native local function rgba(y: number, u: number, v: number): number local yy = mulHi(y, 19077) local r = clip(yy + mulHi(v, 26149) - 14234) local g = clip(yy - mulHi(u, 6419) - mulHi(v, 13320) + 8708) local b = clip(yy + mulHi(u, 33050) - 17685) return r + g * 256 + b * 65536 + 0xff000000 end Yuv.rgba = rgba -- libwebp UPSAMPLE_FUNC for one or two output rows (by < 0: no bottom row) @native local function upsamplePair(Y: buffer, U: buffer, V: buffer, ty: number, by: number, tu: number, cu: number, out: buffer, dt: number, db: number, len: number) local last = rshift(len - 1, 1) local tlu, tlv = readu8(U, tu), readu8(V, tu) local lu, lv = readu8(U, cu), readu8(V, cu) do local u0 = rshift(3 * tlu + lu + 2, 2) local v0 = rshift(3 * tlv + lv + 2, 2) writeu32(out, dt, rgba(readu8(Y, ty), u0, v0)) end if by >= 0 then local u0 = rshift(3 * lu + tlu + 2, 2) local v0 = rshift(3 * lv + tlv + 2, 2) writeu32(out, db, rgba(readu8(Y, by), u0, v0)) end for x = 1, last do local tu1, tv1 = readu8(U, tu + x), readu8(V, tu + x) local u1, v1 = readu8(U, cu + x), readu8(V, cu + x) local avgU = tlu + tu1 + lu + u1 + 8 local avgV = tlv + tv1 + lv + v1 + 8 local d12u = rshift(avgU + 2 * (tu1 + lu), 3) local d03u = rshift(avgU + 2 * (tlu + u1), 3) local d12v = rshift(avgV + 2 * (tv1 + lv), 3) local d03v = rshift(avgV + 2 * (tlv + v1), 3) local px = 2 * x writeu32(out, dt + (px - 1) * 4, rgba(readu8(Y, ty + px - 1), rshift(d12u + tlu, 1), rshift(d12v + tlv, 1))) writeu32(out, dt + px * 4, rgba(readu8(Y, ty + px), rshift(d03u + tu1, 1), rshift(d03v + tv1, 1))) if by >= 0 then writeu32(out, db + (px - 1) * 4, rgba(readu8(Y, by + px - 1), rshift(d03u + lu, 1), rshift(d03v + lv, 1))) writeu32(out, db + px * 4, rgba(readu8(Y, by + px), rshift(d12u + u1, 1), rshift(d12v + v1, 1))) end tlu, tlv, lu, lv = tu1, tv1, u1, v1 end if len % 2 == 0 then local u0 = rshift(3 * tlu + lu + 2, 2) local v0 = rshift(3 * tlv + lv + 2, 2) writeu32(out, dt + (len - 1) * 4, rgba(readu8(Y, ty + len - 1), u0, v0)) if by >= 0 then u0 = rshift(3 * lu + tlu + 2, 2) v0 = rshift(3 * lv + tlv + 2, 2) writeu32(out, db + (len - 1) * 4, rgba(readu8(Y, by + len - 1), u0, v0)) end end end @native function Yuv.toRgba(Y: buffer, U: buffer, V: buffer, w: number, h: number, fancy: boolean, out: buffer?): buffer local o = out or bcreate(w * h * 4) local cw = (w + 1) // 2 local stride = w * 4 if fancy then -- libwebp EmitFancyRGB over the whole picture: row 0 alone (chroma mirrored), then pairs of rows between two -- chroma rows, then the last row of an even height alone upsamplePair(Y, U, V, 0, -1, 0, 0, o, 0, -1, w) local y = 1 local cu = 0 while y + 1 < h do upsamplePair(Y, U, V, y * w, (y + 1) * w, cu, cu + cw, o, y * stride, (y + 1) * stride, w) cu += cw y += 2 end if h % 2 == 0 and h > 1 then upsamplePair(Y, U, V, (h - 1) * w, -1, cu, cu, o, (h - 1) * stride, -1, w) end else for y = 0, h - 1 do local cu = (y // 2) * cw local yo = y * w local oo = y * stride for x = 0, w - 1 do local c = cu + x // 2 writeu32(o, oo + x * 4, rgba(readu8(Y, yo + x), readu8(U, c), readu8(V, c))) end end end return o end @native function Yuv.setAlpha(o: buffer, a: buffer, n: number) for i = 0, n - 1 do writeu8(o, i * 4 + 3, readu8(a, i)) end end return Yuv end __FILES["codecs/image/Vp8L"] = function() -- codecs/image/Vp8L: WebP lossless (VP8L, RFC 9649 section 3). -- Decoder ported from libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it; encoder new. local Err = __include("core/Err") local Decode = __include("codecs/image/Vp8L/Decode") local Encode = __include("codecs/image/Vp8L/Encode") local Vp8L = {} local DEFAULT_MAX_PIXELS = 2 ^ 28 local function fail(msg: string?, offset: number?): Err.Err local m = msg or "bad data" if string.sub(m, 1, 11) == "truncated: " then return Err.new(Err.TRUNCATED, string.sub(m, 12), offset) elseif string.sub(m, 1, 7) == "limit: " then return Err.new(Err.LIMIT, string.sub(m, 8), offset) end return Err.new(Err.CORRUPT, m, offset) end Vp8L.fail = fail local function range(buf: buffer, off: number?, len: number?): (number, number) local n = buffer.len(buf) local o = math.clamp(off or 0, 0, n) return o, math.clamp(len or (n - o), 0, n - o) end function Vp8L.info(buf: buffer, off: number?, len: number?): ({ width: number, height: number, alpha: boolean }?, Err.Err?) local o, l = range(buf, off, len) local w, h, alpha, err = Decode.header(buf, o, l) if not w then return nil, fail(err, o) end return { width = w, height = h, alpha = alpha }, nil end function Vp8L.decodeArgb(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?) local o, l = range(buf, off, len) local px, w, h, alpha, err = Decode.argb(buf, o, l, maxPixels or DEFAULT_MAX_PIXELS) if not px then return nil, fail(err, o) end return px, w, h, alpha end function Vp8L.decode(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?) local px, w, h, alpha = Vp8L.decodeArgb(buf, off, len, maxPixels) if not px then return nil, w end return Decode.toRgba(px, w * (h :: number)), w, h, alpha end function Vp8L.decodeAlpha(buf: buffer, off: number?, len: number?, width: number, height: number): (buffer?, Err.Err?) local o, l = range(buf, off, len) local px, err = Decode.stream(buf, o, l, width, height) if not px then return nil, fail(err, o) end return Decode.green(px, width * height), nil end Vp8L.toRgba = Decode.toRgba type EncodeOptions = { effort: number?, exact: boolean?, alphaHint: boolean?, } function Vp8L.encode(rgba: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?) if type(rgba) ~= "buffer" or type(width) ~= "number" or type(height) ~= "number" then return nil, Err.new(Err.ARG, "encode: needs rgba8 pixels, width, height") end if width < 1 or height < 1 or width > 16384 or height > 16384 or width % 1 ~= 0 or height % 1 ~= 0 then return nil, Err.new(Err.ARG, "encode: size must be 1..16384") end if buffer.len(rgba) < width * height * 4 then return nil, Err.new(Err.ARG, "encode: pixel buffer too small") end local o: EncodeOptions = opts or {} :: EncodeOptions local effort = o.effort or 5 if type(effort) ~= "number" or effort < 0 or effort > 9 then return nil, Err.new(Err.ARG, "encode: effort must be 0..9") end return Encode.encode(rgba, width, height, effort, o.exact == true, o.alphaHint, false), nil end function Vp8L.encodeAlpha(a8: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?) if type(a8) ~= "buffer" or buffer.len(a8) < width * height then return nil, Err.new(Err.ARG, "encodeAlpha: plane too small") end local rgba = buffer.create(width * height * 4) for i = 0, width * height - 1 do buffer.writeu32(rgba, i * 4, 0xff000000 + buffer.readu8(a8, i) * 256) end local effort = opts and opts.effort or 5 return Encode.encode(rgba, width, height, effort, true, false, true), nil end return Vp8L end __FILES["codecs/image/Vp8L/Decode"] = @native function() -- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder, a port of libwebp 1.6 src/dec/vp8l_dec.c, -- src/utils/huffman_utils.c and src/dsp/lossless.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); bit-exact with it. -- Pixels are ARGB u32 values (0xAARRGGBB). local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local Decode = {} local ROOT_BITS = 8 local MAX_LEN = 15 local NUM_LITERAL = 256 local NUM_LENGTH = 24 local NUM_DISTANCE = 40 local MAX_CACHE_BITS = 11 local ARGB_BLACK = 0xff000000 local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } local CODE_TO_PLANE = { 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, 0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, 0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, 0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, 0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52, 0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61, 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70, } -- distance map (x offset 8 - (v & 15), y offset v >> 4) as a plain distance for a row width: done per image Decode.CODE_TO_PLANE = CODE_TO_PLANE -- LSB-first; bytes past the end read as zero and count in `over`: the stream is overrun when bitcnt < over * 8 type State = { buf: buffer, pos: number, limit: number, bitbuf: number, bitcnt: number, over: number, -- prefix code tables (u32 entries value * 32 + bits), shared by every group of every level tab: buffer, tabUsed: number, maxPixels: number, } @native local function fill(d: State) local bitbuf, bitcnt = d.bitbuf, d.bitcnt while bitcnt <= 24 do local p = d.pos local b = 0 if p < d.limit then b = readu8(d.buf, p) d.pos = p + 1 else d.over += 1 end bitbuf += lshift(b, bitcnt) bitcnt += 8 end d.bitbuf, d.bitcnt = bitbuf, bitcnt end @native local function readBits(d: State, n: number): number if d.bitcnt < n then fill(d) end local v = band(d.bitbuf, lshift(1, n) - 1) d.bitbuf = rshift(d.bitbuf, n) d.bitcnt -= n return v end @native local function eos(d: State): boolean return d.bitcnt < d.over * 8 end local count = table.create(MAX_LEN + 1, 0) local offset = table.create(MAX_LEN + 2, 0) @native local function ensure(d: State, n: number) local cap = blen(d.tab) // 4 if d.tabUsed + n > cap then local nb = bcreate(math.max(cap * 2, d.tabUsed + n) * 4) bcopy(nb, 0, d.tab, 0, d.tabUsed * 4) d.tab = nb end end @native local function replicate(tab: buffer, at: number, step: number, size: number, entry: number) local e = size repeat e -= step writeu32(tab, (at + e) * 4, entry) until e <= 0 end @native local function nextKey(key: number, len: number): number local step = lshift(1, len - 1) while band(key, step) ~= 0 do step = rshift(step, 1) end return if step ~= 0 then band(key, step - 1) + step else key end -- libwebp BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits; -1 when invalid local sorted = table.create(2400, 0) @native local function build(d: State, lens: { number }, n: number): number for l = 0, MAX_LEN do count[l + 1] = 0 end for s = 0, n - 1 do local l = lens[s + 1] if l > MAX_LEN then return -1 end count[l + 1] += 1 end if count[1] == n then return -1 end offset[2] = 0 for len = 1, MAX_LEN - 1 do if count[len + 1] > lshift(1, len) then return -1 end offset[len + 2] = offset[len + 1] + count[len + 1] end for s = 0, n - 1 do local l = lens[s + 1] if l > 0 then sorted[offset[l + 1] + 1] = s offset[l + 1] += 1 end end local long = 0 for len = ROOT_BITS + 1, MAX_LEN do long += count[len + 1] end ensure(d, lshift(1, ROOT_BITS) + long * lshift(1, MAX_LEN - ROOT_BITS)) local tab = d.tab local root = d.tabUsed local totalSize = lshift(1, ROOT_BITS) if offset[MAX_LEN + 1] == 1 then replicate(tab, root, 1, totalSize, sorted[1] * 32) d.tabUsed = root + totalSize return root end local key = 0 local numNodes, numOpen = 1, 1 local tableBits = ROOT_BITS local tableSize = lshift(1, tableBits) local tableAt = root local low = -1 local mask = totalSize - 1 local symbol = 1 local step = 2 for len = 1, ROOT_BITS do numOpen *= 2 numNodes += numOpen numOpen -= count[len + 1] if numOpen < 0 then return -1 end while count[len + 1] > 0 do replicate(tab, root + key, step, tableSize, sorted[symbol] * 32 + len) symbol += 1 key = nextKey(key, len) count[len + 1] -= 1 end step *= 2 end step = 2 for len = ROOT_BITS + 1, MAX_LEN do numOpen *= 2 numNodes += numOpen numOpen -= count[len + 1] if numOpen < 0 then return -1 end while count[len + 1] > 0 do if band(key, mask) ~= low then tableAt += tableSize -- NextTableBitSize local l2 = len local left = lshift(1, l2 - ROOT_BITS) while l2 < MAX_LEN do left -= count[l2 + 1] if left <= 0 then break end l2 += 1 left *= 2 end tableBits = l2 - ROOT_BITS tableSize = lshift(1, tableBits) totalSize += tableSize low = band(key, mask) writeu32(tab, (root + low) * 4, (tableAt - root - low) * 32 + tableBits + ROOT_BITS) end replicate(tab, tableAt + rshift(key, ROOT_BITS), step, tableSize, sorted[symbol] * 32 + len - ROOT_BITS) symbol += 1 key = nextKey(key, len) count[len + 1] -= 1 end step *= 2 end if numNodes ~= 2 * offset[MAX_LEN + 1] - 1 then return -1 end d.tabUsed = root + totalSize return root end @native local function readSymbol(d: State, at: number): number if d.bitcnt < MAX_LEN then fill(d) end local tab = d.tab local bitbuf = d.bitbuf local idx = at + band(bitbuf, 255) local e = readu32(tab, idx * 4) local nb = band(e, 31) if nb > ROOT_BITS then bitbuf = rshift(bitbuf, ROOT_BITS) d.bitcnt -= ROOT_BITS e = readu32(tab, (idx + rshift(e, 5) + band(bitbuf, lshift(1, nb - ROOT_BITS) - 1)) * 4) nb = band(e, 31) end d.bitbuf = rshift(bitbuf, nb) d.bitcnt -= nb return rshift(e, 5) end local codeLengths = table.create(2400, 0) local clLens = table.create(19, 0) @native local function readCode(d: State, size: number): number for i = 1, size do codeLengths[i] = 0 end if readBits(d, 1) == 1 then local numSymbols = readBits(d, 1) + 1 local first = readBits(d, 1) local s = readBits(d, if first == 0 then 1 else 8) if s < size then codeLengths[s + 1] = 1 end if numSymbols == 2 then s = readBits(d, 8) if s < size then codeLengths[s + 1] = 1 end end else for i = 1, 19 do clLens[i] = 0 end local numCodes = readBits(d, 4) + 4 for i = 1, numCodes do clLens[CODE_LENGTH_ORDER[i] + 1] = readBits(d, 3) end local mark = d.tabUsed local clt = build(d, clLens, 19) if clt < 0 then return -1 end local maxSymbol = size if readBits(d, 1) == 1 then local nbits = 2 + 2 * readBits(d, 3) maxSymbol = 2 + readBits(d, nbits) if maxSymbol > size then return -1 end end local prev = 8 local s = 0 while s < size do if maxSymbol == 0 then break end maxSymbol -= 1 local cl = readSymbol(d, clt) if cl < 16 then codeLengths[s + 1] = cl s += 1 if cl ~= 0 then prev = cl end else local rep, len if cl == 16 then rep, len = readBits(d, 2) + 3, prev elseif cl == 17 then rep, len = readBits(d, 3) + 3, 0 else rep, len = readBits(d, 7) + 11, 0 end if s + rep > size then return -1 end for k = s + 1, s + rep do codeLengths[k] = len end s += rep end end d.tabUsed = mark -- the code length table is temporary end if eos(d) then return -1 end return build(d, codeLengths, size) end @native local function subSample(size: number, bits: number): number return rshift(size + lshift(1, bits) - 1, bits) end Decode.subSample = subSample @native local function cacheKey(argb: number, shift: number): number -- (0x1e35a7bd * argb) mod 2^32 >> shift, exact in doubles local lo = argb % 65536 local hi = (argb - lo) / 65536 local m = (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 return rshift(m, shift) end Decode.cacheKey = cacheKey @native local function decodeData(d: State, data: buffer, w: number, h: number, cacheBits: number, groups: { number }, himg: buffer?, hbits: number, hxs: number): (boolean, string?) local total = w * h local cache: buffer? = if cacheBits > 0 then bcreate(lshift(1, cacheBits) * 4) else nil local cshift = 32 - cacheBits local lenLimit = NUM_LITERAL + NUM_LENGTH local cacheLimit = lenLimit + (if cacheBits > 0 then lshift(1, cacheBits) else 0) local hmask = if himg then lshift(1, hbits) - 1 else -1 local i, col, row = 0, 0, 0 local gG, gR, gB, gA, gD = groups[1], groups[2], groups[3], groups[4], groups[5] @native local function setGroup() if himg then local g = readu32(himg, (hxs * rshift(row, hbits) + rshift(col, hbits)) * 4) * 5 gG, gR, gB, gA, gD = groups[g + 1], groups[g + 2], groups[g + 3], groups[g + 4], groups[g + 5] end end while i < total do if band(col, hmask) == 0 then setGroup() end local code = readSymbol(d, gG) if code < NUM_LITERAL then local r = readSymbol(d, gR) local b = readSymbol(d, gB) local a = readSymbol(d, gA) if d.bitcnt < d.over * 8 then break end local argb = a * 16777216 + r * 65536 + code * 256 + b writeu32(data, i * 4, argb) if cache then writeu32(cache, cacheKey(argb, cshift) * 4, argb) end i += 1 col += 1 if col >= w then col = 0 row += 1 end elseif code < lenLimit then local ls = code - NUM_LITERAL local length if ls < 4 then length = ls + 1 else local eb = rshift(ls - 2, 1) length = lshift(2 + band(ls, 1), eb) + readBits(d, eb) + 1 end local ds = readSymbol(d, gD) local dc if ds < 4 then dc = ds + 1 else local eb = rshift(ds - 2, 1) dc = lshift(2 + band(ds, 1), eb) + readBits(d, eb) + 1 end local dist if dc > 120 then dist = dc - 120 else local v = CODE_TO_PLANE[dc] dist = rshift(v, 4) * w + 8 - band(v, 15) if dist < 1 then dist = 1 end end if d.bitcnt < d.over * 8 then break end if i < dist or total - i < length then return false, "bad backward reference" end if dist >= length then bcopy(data, i * 4, data, (i - dist) * 4, length * 4) else for k = i, i + length - 1 do writeu32(data, k * 4, readu32(data, (k - dist) * 4)) end end if cache then for k = i, i + length - 1 do local argb = readu32(data, k * 4) writeu32(cache, cacheKey(argb, cshift) * 4, argb) end end i += length col += length while col >= w do col -= w row += 1 end if band(col, hmask) ~= 0 then setGroup() end elseif code < cacheLimit and cache then if d.bitcnt < d.over * 8 then break end local argb = readu32(cache, (code - lenLimit) * 4) writeu32(data, i * 4, argb) writeu32(cache, cacheKey(argb, cshift) * 4, argb) i += 1 col += 1 if col >= w then col = 0 row += 1 end else return false, "bad symbol" end end if eos(d) then return false, "truncated: pixel data" end return true, nil end @native local function addPixels(a: number, b: number): number return band(band(a, 0xff00ff00) + band(b, 0xff00ff00), 0xff00ff00) + band(band(a, 0x00ff00ff) + band(b, 0x00ff00ff), 0x00ff00ff) end Decode.addPixels = addPixels @native local function average2(a: number, b: number): number return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b) end Decode.average2 = average2 @native local function clip255(v: number): number return if v < 0 then 0 elseif v > 255 then 255 else v end @native local function sub3(a: number, b: number, c: number): number local pb, pa = b - c, a - c return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa) end -- select(T, L, TL) @native local function select3(a: number, b: number, c: number): number local s = sub3(rshift(a, 24), rshift(b, 24), rshift(c, 24)) + sub3(band(rshift(a, 16), 255), band(rshift(b, 16), 255), band(rshift(c, 16), 255)) + sub3(band(rshift(a, 8), 255), band(rshift(b, 8), 255), band(rshift(c, 8), 255)) + sub3(band(a, 255), band(b, 255), band(c, 255)) return if s <= 0 then a else b end @native local function clampedFull(c0: number, c1: number, c2: number): number local a = clip255(rshift(c0, 24) + rshift(c1, 24) - rshift(c2, 24)) local r = clip255(band(rshift(c0, 16), 255) + band(rshift(c1, 16), 255) - band(rshift(c2, 16), 255)) local g = clip255(band(rshift(c0, 8), 255) + band(rshift(c1, 8), 255) - band(rshift(c2, 8), 255)) local b = clip255(band(c0, 255) + band(c1, 255) - band(c2, 255)) return a * 16777216 + r * 65536 + g * 256 + b end @native local function half(a: number, b: number): number local dd = a - b -- C division truncates toward zero local q = if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1) return clip255(a + q) end @native local function clampedHalf(c0: number, c1: number, c2: number): number local ave = average2(c0, c1) local a = half(rshift(ave, 24), rshift(c2, 24)) local r = half(band(rshift(ave, 16), 255), band(rshift(c2, 16), 255)) local g = half(band(rshift(ave, 8), 255), band(rshift(c2, 8), 255)) local b = half(band(ave, 255), band(c2, 255)) return a * 16777216 + r * 65536 + g * 256 + b end -- libwebp VP8LPredictors; modes 14 and 15 are black @native local function predict(mode: number, L: number, T: number, TR: number, TL: number): number if mode == 0 then return ARGB_BLACK elseif mode == 1 then return L elseif mode == 2 then return T elseif mode == 3 then return TR elseif mode == 4 then return TL elseif mode == 5 then return average2(average2(L, TR), T) elseif mode == 6 then return average2(L, TL) elseif mode == 7 then return average2(L, T) elseif mode == 8 then return average2(TL, T) elseif mode == 9 then return average2(T, TR) elseif mode == 10 then return average2(average2(L, TL), average2(T, TR)) elseif mode == 11 then return select3(T, L, TL) elseif mode == 12 then return clampedFull(L, T, TL) elseif mode == 13 then return clampedHalf(L, T, TL) end return ARGB_BLACK end Decode.predict = predict @native local function inversePredictor(data: buffer, w: number, h: number, bits: number, sub: buffer) local tw = subSample(w, bits) -- first row: black, then L writeu32(data, 0, addPixels(readu32(data, 0), ARGB_BLACK)) for x = 1, w - 1 do writeu32(data, x * 4, addPixels(readu32(data, x * 4), readu32(data, (x - 1) * 4))) end for y = 1, h - 1 do local row = y * w local up = row - w writeu32(data, row * 4, addPixels(readu32(data, row * 4), readu32(data, up * 4))) local trow = rshift(y, bits) * tw local x = 1 while x < w do local mode = band(rshift(readu32(sub, (trow + rshift(x, bits)) * 4), 8), 15) local xe = math.min(w, lshift(rshift(x, bits) + 1, bits)) local L = readu32(data, (row + x - 1) * 4) if mode == 1 then for k = x, xe - 1 do L = addPixels(readu32(data, (row + k) * 4), L) writeu32(data, (row + k) * 4, L) end elseif mode == 2 then for k = x, xe - 1 do writeu32(data, (row + k) * 4, addPixels(readu32(data, (row + k) * 4), readu32(data, (up + k) * 4))) end else for k = x, xe - 1 do local p = predict(mode, L, readu32(data, (up + k) * 4), readu32(data, (up + k + 1) * 4), readu32(data, (up + k - 1) * 4)) L = addPixels(readu32(data, (row + k) * 4), p) writeu32(data, (row + k) * 4, L) end end x = xe end end end @native local function sint8(v: number): number return if v >= 128 then v - 256 else v end @native local function inverseCrossColor(data: buffer, w: number, h: number, bits: number, sub: buffer) local tw = subSample(w, bits) for y = 0, h - 1 do local trow = rshift(y, bits) * tw local x = 0 while x < w do local m = readu32(sub, (trow + rshift(x, bits)) * 4) local g2r = sint8(band(m, 255)) local g2b = sint8(band(rshift(m, 8), 255)) local r2b = sint8(band(rshift(m, 16), 255)) local xe = math.min(w, lshift(rshift(x, bits) + 1, bits)) for k = y * w + x, y * w + xe - 1 do local argb = readu32(data, k * 4) local g = sint8(band(rshift(argb, 8), 255)) local r = band(band(rshift(argb, 16), 255) + ((g2r * g) // 32), 255) local b = band(band(argb, 255) + ((g2b * g) // 32) + ((r2b * sint8(r)) // 32), 255) writeu32(data, k * 4, band(argb, 0xff00ff00) + r * 65536 + b) end x = xe end end end @native local function inverseSubtractGreen(data: buffer, n: number) for k = 0, n - 1 do local argb = readu32(data, k * 4) local g = band(rshift(argb, 8), 255) writeu32(data, k * 4, band(argb, 0xff00ff00) + band(band(argb, 0x00ff00ff) + g * 65537, 0x00ff00ff)) end end @native local function inverseColorIndexing(src: buffer, sw: number, w: number, h: number, bits: number, map: buffer): buffer local out = bcreate(w * h * 4) if bits == 0 then for k = 0, w * h - 1 do writeu32(out, k * 4, readu32(map, band(rshift(readu32(src, k * 4), 8), 255) * 4)) end return out end local bpp = rshift(8, bits) local cmask = lshift(1, bits) - 1 local vmask = lshift(1, bpp) - 1 for y = 0, h - 1 do local packed = 0 local s = y * sw local o = y * w for x = 0, w - 1 do if band(x, cmask) == 0 then packed = band(rshift(readu32(src, s * 4), 8), 255) s += 1 end writeu32(out, (o + x) * 4, readu32(map, band(packed, vmask) * 4)) packed = rshift(packed, bpp) end end return out end type Transform = { kind: number, xsize: number, bits: number, data: buffer? } local decodeStream: (d: State, xs: number, ys: number, level0: boolean) -> (buffer?, string?) @native local function readCodes(d: State, xs: number, ys: number, cacheBits: number, level0: boolean): ({ number }?, buffer?, number, number, string?) local himg: buffer? = nil local hbits, hxs = 0, 0 local numGroups = 1 local mapping: { number }? = nil local numMax = 1 if level0 and readBits(d, 1) == 1 then hbits = readBits(d, 3) + 2 hxs = subSample(xs, hbits) local hys = subSample(ys, hbits) local img, err = decodeStream(d, hxs, hys, false) if not img then return nil, nil, 0, 0, err end local n = hxs * hys for k = 0, n - 1 do local g = band(rshift(readu32(img, k * 4), 8), 0xffff) writeu32(img, k * 4, g) if g >= numMax then numMax = g + 1 end end if numMax > 1000 or numMax > xs * ys then -- remap the used groups to [0, numGroups); unused ones are read and checked but not kept local map = table.create(numMax, -1) :: { number } numGroups = 0 for k = 0, n - 1 do local g = readu32(img, k * 4) if map[g + 1] == -1 then map[g + 1] = numGroups numGroups += 1 end writeu32(img, k * 4, map[g + 1]) end mapping = map else numGroups = numMax end himg = img end if eos(d) then return nil, nil, 0, 0, "truncated: meta codes" end local groups = table.create(numGroups * 5, 0) :: { number } local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0 for i = 0, numMax - 1 do local slot = if mapping then mapping[i + 1] else i local mark = d.tabUsed for j = 0, 4 do local size = if j == 0 then NUM_LITERAL + NUM_LENGTH + cacheSize elseif j == 4 then NUM_DISTANCE else NUM_LITERAL local at = readCode(d, size) if at < 0 then return nil, nil, 0, 0, if eos(d) then "truncated: prefix code" else "bad prefix code" end if slot >= 0 then groups[slot * 5 + j + 1] = at end end if slot < 0 then d.tabUsed = mark end end return groups, himg, hbits, hxs, nil end decodeStream = @native function(d: State, xs: number, ys: number, level0: boolean): (buffer?, string?) local transforms: { Transform } = {} local seen = 0 local txs = xs if level0 then while readBits(d, 1) == 1 do local kind = readBits(d, 2) if band(seen, lshift(1, kind)) ~= 0 then return nil, "repeated transform" end seen = bor(seen, lshift(1, kind)) local t: Transform = { kind = kind, xsize = txs, bits = 0, data = nil } if kind == 0 or kind == 1 then t.bits = readBits(d, 3) + 2 local sub, err = decodeStream(d, subSample(txs, t.bits), subSample(ys, t.bits), false) if not sub then return nil, err end t.data = sub elseif kind == 3 then local num = readBits(d, 8) + 1 local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3 t.bits = bits local pal, err = decodeStream(d, num, 1, false) if not pal then return nil, err end local final = lshift(1, rshift(8, bits)) local map = bcreate(final * 4) local prev = 0 for k = 0, num - 1 do prev = addPixels(readu32(pal, k * 4), prev) writeu32(map, k * 4, prev) end t.data = map txs = subSample(txs, bits) end table.insert(transforms, t) if eos(d) then return nil, "truncated: transforms" end end end local cacheBits = 0 if readBits(d, 1) == 1 then cacheBits = readBits(d, 4) if cacheBits < 1 or cacheBits > MAX_CACHE_BITS then return nil, "bad colour cache size" end end local mark = d.tabUsed local groups, himg, hbits, hxs, err = readCodes(d, txs, ys, cacheBits, level0) if not groups then return nil, err end local data = bcreate(txs * ys * 4) local ok, derr = decodeData(d, data, txs, ys, cacheBits, groups, himg, hbits, hxs) if not ok then return nil, derr end d.tabUsed = mark -- inverse transforms, last read first for k = #transforms, 1, -1 do local t = transforms[k] if t.kind == 0 then inversePredictor(data, t.xsize, ys, t.bits, t.data :: buffer) elseif t.kind == 1 then inverseCrossColor(data, t.xsize, ys, t.bits, t.data :: buffer) elseif t.kind == 2 then inverseSubtractGreen(data, t.xsize * ys) else data = inverseColorIndexing(data, subSample(t.xsize, t.bits), t.xsize, ys, t.bits, t.data :: buffer) end end return data, nil end @native local function newState(buf: buffer, off: number, len: number, maxPixels: number): State return { buf = buf, pos = off, limit = off + len, bitbuf = 0, bitcnt = 0, over = 0, tab = bcreate(4096 * 4), tabUsed = 0, maxPixels = maxPixels, } end @native function Decode.header(buf: buffer, off: number, len: number): (number?, number, boolean, string?) if len < 5 then return nil, 0, false, "truncated: header" end if readu8(buf, off) ~= 0x2f then return nil, 0, false, "bad VP8L signature" end local v = readu32(buf, off + 1) local w = band(v, 0x3fff) + 1 local h = band(rshift(v, 14), 0x3fff) + 1 local alpha = band(rshift(v, 28), 1) == 1 if rshift(v, 29) ~= 0 then return nil, 0, false, "bad VP8L version" end return w, h, alpha, nil end @native function Decode.argb(buf: buffer, off: number, len: number, maxPixels: number): (buffer?, number, number, boolean, string?) local w, h, alpha, err = Decode.header(buf, off, len) if not w then return nil, 0, 0, false, err end if w * h > maxPixels then return nil, w, h, alpha, "limit: " .. w .. " x " .. h .. " is over maxPixels" end local d = newState(buf, off + 5, len - 5, maxPixels) local data, derr = decodeStream(d, w, h, true) if not data then return nil, w, h, alpha, derr end return data, w, h, alpha, nil end @native function Decode.stream(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, string?) local d = newState(buf, off, len, w * h) return decodeStream(d, w, h, true) end @native function Decode.toRgba(argb: buffer, n: number, out: buffer?, outOff: number?): buffer local o = out or bcreate(n * 4) local base = outOff or 0 for k = 0, n - 1 do local v = readu32(argb, k * 4) -- 0xAARRGGBB (bytes B G R A) -> bytes R G B A writeu32(o, base + k * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536) end return o end @native function Decode.green(argb: buffer, n: number): buffer local o = bcreate(n) for k = 0, n - 1 do writeu8(o, k, band(rshift(readu32(argb, k * 4), 8), 255)) end return o end return Decode end __FILES["codecs/image/Vp8L/Encode"] = @native function() -- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from RFC 9649 section 3. local Huffman = __include("codecs/entropy/Huffman") local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu32, writeu8, writeu32 = buffer.readu32, buffer.writeu8, buffer.writeu32 local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local log = math.log local Encode = {} local NUM_LITERAL = 256 local NUM_LENGTH = 24 local NUM_DISTANCE = 40 local MAX_LENGTH = 4096 local WINDOW = 1048576 - 120 local ARGB_BLACK = 0xff000000 local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } local CODE_TO_PLANE = { 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, 0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, 0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, 0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, 0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52, 0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61, 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70, } -- PLANE_TO_CODE[v + 1] = the distance code (1..120) of the plane offset v = yoffset * 16 + 8 - xoffset local PLANE_TO_CODE = table.create(128, 0) for i, v in CODE_TO_PLANE do PLANE_TO_CODE[v + 1] = i end type W = { buf: buffer, pos: number, acc: number, cnt: number } @native local function newWriter(cap: number): W return { buf = bcreate(math.max(64, cap)), pos = 0, acc = 0, cnt = 0 } end -- the n <= 24 low bits of v, LSB first @native local function put(w: W, v: number, n: number) local acc = w.acc + v * 2 ^ w.cnt local cnt = w.cnt + n if cnt >= 8 then local pos = w.pos local buf = w.buf if pos + 8 > blen(buf) then local nb = bcreate(blen(buf) * 2) bcopy(nb, 0, buf, 0, pos) buf = nb w.buf = nb end repeat local byte = acc % 256 writeu8(buf, pos, byte) pos += 1 acc = (acc - byte) / 256 cnt -= 8 until cnt < 8 w.pos = pos end w.acc, w.cnt = acc, cnt end @native local function finish(w: W): buffer if w.cnt > 0 then put(w, 0, 8 - w.cnt) end local out = bcreate(w.pos) bcopy(out, 0, w.buf, 0, w.pos) return out end @native local function subSample(size: number, bits: number): number return rshift(size + lshift(1, bits) - 1, bits) end -- (0x1e35a7bd * v) mod 2^32: the colour cache hash before its shift @native local function mulHash(v: number): number local lo = v % 65536 local hi = (v - lo) / 65536 return (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 end @native local function prefix(v: number): (number, number, number) local d = v - 1 if d < 4 then return d, 0, 0 end local hb = 0 local t = d while t >= 2 do t = rshift(t, 1) hb += 1 end local second = band(rshift(d, hb - 1), 1) local eb = hb - 1 return 2 * hb + second, eb, band(d, lshift(1, eb) - 1) end -- distance code value: 1..120 for the 2-D plane offsets, else dist + 120 @native local function distCode(xs: number, dist: number): number local yo = dist // xs local xo = dist - yo * xs if xo <= 8 and yo < 8 then return PLANE_TO_CODE[yo * 16 + 8 - xo + 1] elseif xo > xs - 8 and yo < 7 then return PLANE_TO_CODE[(yo + 1) * 16 + 8 + (xs - xo) + 1] end return dist + 120 end @native local function subPixels(a: number, b: number): number return band(bor(a, 0x00ff00ff) - band(b, 0xff00ff00), 0xff00ff00) + band(bor(a, 0xff00ff00) - band(b, 0x00ff00ff), 0x00ff00ff) end @native local function average2(a: number, b: number): number return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b) end @native local function clip255(v: number): number return if v < 0 then 0 elseif v > 255 then 255 else v end @native local function sub3(a: number, b: number, c: number): number local pb, pa = b - c, a - c return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa) end @native local function half(x: number, y: number): number local dd = x - y return clip255(x + (if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1))) end @native local function predict(mode: number, L: number, T: number, TR: number, TL: number): number if mode == 1 then return L elseif mode == 2 then return T elseif mode == 3 then return TR elseif mode == 4 then return TL elseif mode == 5 then return average2(average2(L, TR), T) elseif mode == 6 then return average2(L, TL) elseif mode == 7 then return average2(L, T) elseif mode == 8 then return average2(TL, T) elseif mode == 9 then return average2(T, TR) elseif mode == 10 then return average2(average2(L, TL), average2(T, TR)) elseif mode == 11 then local s = sub3(rshift(T, 24), rshift(L, 24), rshift(TL, 24)) + sub3(band(rshift(T, 16), 255), band(rshift(L, 16), 255), band(rshift(TL, 16), 255)) + sub3(band(rshift(T, 8), 255), band(rshift(L, 8), 255), band(rshift(TL, 8), 255)) + sub3(band(T, 255), band(L, 255), band(TL, 255)) return if s <= 0 then T else L elseif mode == 12 then local a = clip255(rshift(L, 24) + rshift(T, 24) - rshift(TL, 24)) local r = clip255(band(rshift(L, 16), 255) + band(rshift(T, 16), 255) - band(rshift(TL, 16), 255)) local g = clip255(band(rshift(L, 8), 255) + band(rshift(T, 8), 255) - band(rshift(TL, 8), 255)) local b = clip255(band(L, 255) + band(T, 255) - band(TL, 255)) return a * 16777216 + r * 65536 + g * 256 + b elseif mode == 13 then local ave = average2(L, T) local a = half(rshift(ave, 24), rshift(TL, 24)) local r = half(band(rshift(ave, 16), 255), band(rshift(TL, 16), 255)) local g = half(band(rshift(ave, 8), 255), band(rshift(TL, 8), 255)) local b = half(band(ave, 255), band(TL, 255)) return a * 16777216 + r * 65536 + g * 256 + b end return ARGB_BLACK end local COST = table.create(256, 0) for v = 0, 255 do local m = math.min(v, 256 - v) COST[v + 1] = log(1 + m) / log(2) end @native local function residualCost(r: number): number return COST[band(r, 255) + 1] + COST[band(rshift(r, 8), 255) + 1] + COST[band(rshift(r, 16), 255) + 1] + COST[rshift(r, 24) + 1] end local MODES_FAST = { 1, 2, 11 } local MODES_MID = { 0, 1, 2, 4, 5, 7, 10, 11, 12, 13 } local MODES_ALL = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 } @native local function predictorTransform(px: buffer, w: number, h: number, bits: number, effort: number): buffer local tw, th = subSample(w, bits), subSample(h, bits) local modesImg = bcreate(tw * th * 4) local modes = if effort <= 2 then MODES_FAST elseif effort <= 6 then MODES_MID else MODES_ALL local ts = lshift(1, bits) for ty = 0, th - 1 do for tx = 0, tw - 1 do local x0, y0 = tx * ts, ty * ts local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts) local best, bestCost = 1, math.huge for _, m in modes do local cost = 0 for y = math.max(y0, 1), y1 - 1 do local row = y * w for x = math.max(x0, 1), x1 - 1 do local i = row + x local up = i - w local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4)) cost += residualCost(subPixels(readu32(px, i * 4), p)) end if cost >= bestCost then break end end if cost < bestCost then best, bestCost = m, cost end end writeu32(modesImg, (ty * tw + tx) * 4, ARGB_BLACK + best * 256) end end -- residuals with the chosen modes (and the decoder's fixed first row and column) local res = bcreate(w * h * 4) writeu32(res, 0, subPixels(readu32(px, 0), ARGB_BLACK)) for x = 1, w - 1 do writeu32(res, x * 4, subPixels(readu32(px, x * 4), readu32(px, (x - 1) * 4))) end for y = 1, h - 1 do local row = y * w writeu32(res, row * 4, subPixels(readu32(px, row * 4), readu32(px, (row - w) * 4))) local trow = rshift(y, bits) * tw for x = 1, w - 1 do local m = band(rshift(readu32(modesImg, (trow + rshift(x, bits)) * 4), 8), 15) local i = row + x local up = i - w local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4)) writeu32(res, i * 4, subPixels(readu32(px, i * 4), p)) end end bcopy(px, 0, res, 0, w * h * 4) return modesImg end @native local function sint8(v: number): number return if v >= 128 then v - 256 else v end @native local function clampM(v: number): number local m = math.floor(v + 0.5) return if m < -128 then -128 elseif m > 127 then 127 else m end -- cross colour per tile: least-squares r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32, kept when they lower the cost @native local function crossColorTransform(px: buffer, w: number, h: number, bits: number): buffer local tw, th = subSample(w, bits), subSample(h, bits) local img = bcreate(tw * th * 4) local ts = lshift(1, bits) @native local function tileCost(x0: number, y0: number, x1: number, y1: number, g2r: number, g2b: number, r2b: number): number local c = 0 for y = y0, y1 - 1 do for x = x0, x1 - 1 do local argb = readu32(px, (y * w + x) * 4) local g = sint8(band(rshift(argb, 8), 255)) local r = band(rshift(argb, 16), 255) local b = band(argb, 255) local nr = band(r - ((g2r * g) // 32), 255) local nb = band(b - ((g2b * g) // 32) - ((r2b * sint8(r)) // 32), 255) c += COST[nr + 1] + COST[nb + 1] end end return c end for ty = 0, th - 1 do for tx = 0, tw - 1 do local x0, y0 = tx * ts, ty * ts local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts) local sgg, sgr, sgb, srr, srb = 0, 0, 0, 0, 0 for y = y0, y1 - 1 do for x = x0, x1 - 1 do local argb = readu32(px, (y * w + x) * 4) local g = sint8(band(rshift(argb, 8), 255)) local r = sint8(band(rshift(argb, 16), 255)) local b = sint8(band(argb, 255)) sgg += g * g sgr += g * r sgb += g * b srr += r * r srb += r * b end end local g2r, g2b, r2b = 0, 0, 0 if sgg > 0 then g2r = clampM(32 * sgr / sgg) local det = sgg * srr - sgr * sgr if det > 0 then g2b = clampM(32 * (sgb * srr - srb * sgr) / det) r2b = clampM(32 * (srb * sgg - sgb * sgr) / det) else g2b = clampM(32 * sgb / sgg) end end if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then if tileCost(x0, y0, x1, y1, g2r, g2b, r2b) >= tileCost(x0, y0, x1, y1, 0, 0, 0) then g2r, g2b, r2b = 0, 0, 0 end end writeu32(img, (ty * tw + tx) * 4, ARGB_BLACK + band(r2b, 255) * 65536 + band(g2b, 255) * 256 + band(g2r, 255)) if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then for y = y0, y1 - 1 do for x = x0, x1 - 1 do local k = (y * w + x) * 4 local argb = readu32(px, k) local g = sint8(band(rshift(argb, 8), 255)) local r = band(rshift(argb, 16), 255) local b = band(argb, 255) local nr = band(r - ((g2r * g) // 32), 255) local nb = band(b - ((g2b * g) // 32) - ((r2b * sint8(r)) // 32), 255) writeu32(px, k, band(argb, 0xff00ff00) + nr * 65536 + nb) end end end end end return img end -- tokens: L[i] >= 0 is a literal ARGB pixel; L[i] < 0 is a copy of -L[i] pixels with the distance code value D[i] local HASH_BITS = 16 @native local function hash2(a: number, b: number): number return rshift(mulHash(bxor(a, (b * 31) % 4294967296)), 32 - HASH_BITS) end @native local function matchLen(px: buffer, i: number, j: number, max: number): number local n = 0 while n < max and readu32(px, (i + n) * 4) == readu32(px, (j + n) * 4) do n += 1 end return n end @native local function lz77(px: buffer, xs: number, n: number, effort: number): ({ number }, { number }) local L: { number } = {} local D: { number } = {} if effort == 0 then for i = 0, n - 1 do L[i + 1] = readu32(px, i * 4) D[i + 1] = 0 end return L, D end local head = table.create(lshift(1, HASH_BITS), -1) local prev = table.create(n, -1) local maxIter = if effort <= 2 then 4 elseif effort <= 5 then 16 elseif effort <= 7 then 48 else 128 @native local function insert(i: number) if i + 1 < n then local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1 prev[i + 1] = head[h] head[h] = i end end @native local function best(i: number): (number, number) local max = math.min(MAX_LENGTH, n - i) if max < 2 then return 0, 0 end local bl, bd, bc = 0, 0, math.huge @native local function try(j: number) local d = i - j if d < 1 or d > WINDOW then return end local l = matchLen(px, i, j, max) if l >= 2 then local c = distCode(xs, d) if l > bl or (l == bl and c < bc) then bl, bd, bc = l, d, c end end end if i >= 1 then try(i - 1) end if i >= xs then try(i - xs) end if bl < max then local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1 local j = head[h] local it = 0 while j >= 0 and it < maxIter and i - j <= WINDOW do if j ~= i - 1 and j ~= i - xs then try(j) if bl >= max then break end end j = prev[j + 1] it += 1 end end -- a 2-pixel copy only pays with a short 2-D distance code if bl == 2 and bc > 120 then return 0, 0 end return bl, bd end local i = 0 local k = 0 local lazy = effort >= 4 local nl, nd = 0, 0 local haveNext = false while i < n do local l, d if haveNext then l, d = nl, nd haveNext = false else l, d = best(i) end if l >= 2 and lazy and l < 64 and i + 1 < n then insert(i) nl, nd = best(i + 1) if nl > l + 1 then -- a literal now, the longer match next k += 1 L[k] = readu32(px, i * 4) D[k] = 0 i += 1 haveNext = true else k += 1 L[k] = -l D[k] = distCode(xs, d) for t = i + 1, i + l - 1 do insert(t) end i += l end elseif l >= 2 then k += 1 L[k] = -l D[k] = distCode(xs, d) local stop = i + l if effort <= 2 and l > 16 then insert(i) insert(stop - 1) else for t = i, stop - 1 do insert(t) end end i = stop else insert(i) k += 1 L[k] = readu32(px, i * 4) D[k] = 0 i += 1 end end return L, D end @native local function entropy(h: { number }): number local total = 0 for _, c in h do total += c end if total == 0 then return 0 end local bits = 0 local lt = log(total) for _, c in h do if c > 0 then bits += c * (lt - log(c)) end end return bits / log(2) end @native local function chooseCache(px: buffer, L: { number }, effort: number): number if effort < 2 then return 0 end local cands = if effort < 5 then { 0, 4, 7, 10 } else { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } local caches: { { number } } = {} local hg: { { number } } = {} local hr: { { number } } = {} local hb: { { number } } = {} local ha: { { number } } = {} for c, bits in cands do caches[c] = table.create(lshift(1, bits), -1) hg[c] = table.create(256 + lshift(1, bits), 0) hr[c] = table.create(256, 0) hb[c] = table.create(256, 0) ha[c] = table.create(256, 0) end local pos = 0 for _, t in L do if t >= 0 then local hsh = mulHash(t) for c, bits in cands do local cache = caches[c] local key = if bits > 0 then rshift(hsh, 32 - bits) else 0 if bits > 0 and cache[key + 1] == t then hg[c][257 + key] += 1 else hg[c][band(rshift(t, 8), 255) + 1] += 1 hr[c][band(rshift(t, 16), 255) + 1] += 1 hb[c][band(t, 255) + 1] += 1 ha[c][rshift(t, 24) + 1] += 1 end if bits > 0 then cache[key + 1] = t end end pos += 1 else for p = pos, pos - t - 1 do local v = readu32(px, p * 4) local hsh = mulHash(v) for c, bits in cands do if bits > 0 then caches[c][rshift(hsh, 32 - bits) + 1] = v end end end pos -= t end end local bestBits, bestCost = 0, math.huge for c, bits in cands do -- + a rough price for the longer green code lengths local cost = entropy(hg[c]) + entropy(hr[c]) + entropy(hb[c]) + entropy(ha[c]) + lshift(1, bits) * 0.5 if cost < bestCost then bestBits, bestCost = bits, cost end end return bestBits end type Code = { lens: { number }, codes: { number }, single: boolean } @native local function buildCode(freqs: { number }, maxLen: number): Code local lens = Huffman.lengths(freqs, maxLen) local used = 0 for _, l in lens do if l > 0 then used += 1 end end local codes = Huffman.codes(lens) for i, l in lens do if l > 0 then codes[i] = Huffman.reverse(codes[i], l) end end return { lens = lens, codes = codes, single = used <= 1 } end @native local function emit(w: W, c: Code, sym: number) if not c.single then put(w, c.codes[sym + 1], c.lens[sym + 1]) end end @native local function zeroRun(tok: { number }, ext: { number }, run: number) local r = run while r > 0 do if r >= 11 then local k = math.min(r, 138) table.insert(tok, 18) table.insert(ext, k - 11) r -= k elseif r >= 3 then table.insert(tok, 17) table.insert(ext, r - 3) r = 0 else table.insert(tok, 0) table.insert(ext, 0) r -= 1 end end end @native local function writeCode(w: W, c: Code, size: number) local syms: { number } = {} for s = 0, size - 1 do if (c.lens[s + 1] or 0) > 0 then table.insert(syms, s) if #syms > 2 then break end end end if #syms == 0 then -- an unused alphabet: the simple code of symbol 0 put(w, 1, 1) put(w, 0, 1) put(w, 0, 1) put(w, 0, 1) return end if #syms <= 2 and syms[#syms] < 256 then put(w, 1, 1) put(w, #syms - 1, 1) if syms[1] <= 1 then put(w, 0, 1) put(w, syms[1], 1) else put(w, 1, 1) put(w, syms[1], 8) end if #syms == 2 then put(w, syms[2], 8) end return end -- run-length tokens of every length: 0..15 literal, 16 repeats the previous non-zero length (3..6 times; the -- decoder's "previous" starts at 8), 17 zeros (3..10), 18 zeros (11..138) local tok: { number } = {} local ext: { number } = {} local keep = 0 local prev = 8 local s = 1 while s <= size do local l = c.lens[s] or 0 local run = 1 while s + run <= size and (c.lens[s + run] or 0) == l do run += 1 end if l == 0 then zeroRun(tok, ext, run) else local r = run if l ~= prev then table.insert(tok, l) table.insert(ext, 0) r -= 1 prev = l end while r > 0 do if r >= 3 then local k = math.min(r, 6) table.insert(tok, 16) table.insert(ext, k - 3) r -= k else table.insert(tok, l) table.insert(ext, 0) r -= 1 end end keep = #tok end s += run end local ntok = #tok local trim = keep < ntok and keep >= 2 if trim then ntok = keep end local hist = table.create(19, 0) for i = 1, ntok do hist[tok[i] + 1] += 1 end local cl = buildCode(hist, 7) local nc = 19 while nc > 4 and (cl.lens[CODE_LENGTH_ORDER[nc] + 1] or 0) == 0 do nc -= 1 end put(w, 0, 1) put(w, nc - 4, 4) for i = 1, nc do put(w, cl.lens[CODE_LENGTH_ORDER[i] + 1] or 0, 3) end if trim then put(w, 1, 1) local v = ntok - 2 local nbits = 0 while lshift(1, nbits) <= v do nbits += 1 end local pairs = math.max(1, (nbits + 1) // 2) put(w, pairs - 1, 3) put(w, v, pairs * 2) else put(w, 0, 1) end for i = 1, ntok do local t = tok[i] emit(w, cl, t) if t == 16 then put(w, ext[i], 2) elseif t == 17 then put(w, ext[i], 3) elseif t == 18 then put(w, ext[i], 7) end end end -- colour cache bits, [the meta-code bit], the five codes, the pixels @native local function writeImage(w: W, px: buffer, xs: number, n: number, effort: number, level0: boolean) local L, D = lz77(px, xs, n, effort) local cacheBits = if level0 then chooseCache(px, L, effort) else 0 if cacheBits > 0 then put(w, 1, 1) put(w, cacheBits, 4) else put(w, 0, 1) end if level0 then put(w, 0, 1) -- no meta prefix codes end local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0 local cshift = 32 - cacheBits local hg = table.create(NUM_LITERAL + NUM_LENGTH + cacheSize, 0) local hr = table.create(256, 0) local hb = table.create(256, 0) local ha = table.create(256, 0) local hd = table.create(NUM_DISTANCE, 0) -- token kinds after the cache: 0 literal, 1 cache hit, 2 copy local cache: { number }? = if cacheBits > 0 then table.create(cacheSize, -1) else nil local K = table.create(#L, 0) local pos = 0 for i, t in L do if t >= 0 then local hit = false if cache then local key = rshift(mulHash(t), cshift) if cache[key + 1] == t then hit = true hg[NUM_LITERAL + NUM_LENGTH + key + 1] += 1 end cache[key + 1] = t end if hit then K[i] = 1 else hg[band(rshift(t, 8), 255) + 1] += 1 hr[band(rshift(t, 16), 255) + 1] += 1 hb[band(t, 255) + 1] += 1 ha[rshift(t, 24) + 1] += 1 end pos += 1 else K[i] = 2 hg[NUM_LITERAL + prefix(-t) + 1] += 1 hd[prefix(D[i]) + 1] += 1 if cache then for p = pos, pos - t - 1 do local v = readu32(px, p * 4) cache[rshift(mulHash(v), cshift) + 1] = v end end pos -= t end end local cg, cr, cb, ca, cd = buildCode(hg, 15), buildCode(hr, 15), buildCode(hb, 15), buildCode(ha, 15), buildCode(hd, 15) writeCode(w, cg, NUM_LITERAL + NUM_LENGTH + cacheSize) writeCode(w, cr, 256) writeCode(w, cb, 256) writeCode(w, ca, 256) writeCode(w, cd, NUM_DISTANCE) for i, t in L do local k = K[i] if k == 0 then emit(w, cg, band(rshift(t, 8), 255)) emit(w, cr, band(rshift(t, 16), 255)) emit(w, cb, band(t, 255)) emit(w, ca, rshift(t, 24)) elseif k == 1 then emit(w, cg, NUM_LITERAL + NUM_LENGTH + rshift(mulHash(t), cshift)) else local lc, leb, lev = prefix(-t) emit(w, cg, NUM_LITERAL + lc) if leb > 0 then put(w, lev, leb) end local dc, deb, dev = prefix(D[i]) emit(w, cd, dc) if deb > 0 then put(w, dev, deb) end end end end @native local function toArgb(rgba: buffer, n: number, exact: boolean): (buffer, boolean) local px = bcreate(n * 4) local alpha = false for i = 0, n - 1 do local v = readu32(rgba, i * 4) local a = rshift(v, 24) if a ~= 255 then alpha = true end if a == 0 and not exact then v = 0 end -- bytes R G B A (0xAABBGGRR) -> 0xAARRGGBB writeu32(px, i * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536) end return px, alpha end @native local function palette(px: buffer, n: number): { number }? local seen: { [number]: boolean } = {} local list: { number } = {} for i = 0, n - 1 do local v = readu32(px, i * 4) if not seen[v] then if #list == 256 then return nil end seen[v] = true table.insert(list, v) end end table.sort(list) return list end type Config = { palette: { number }?, pbits: number, cc: boolean, ccbits: number } @native local function stream(px: buffer, w: number, h: number, effort: number, cfg: Config, bw: W) local n = w * h local xs = w local sub = math.min(effort, 3) local pal = cfg.palette if pal then local num = #pal local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3 put(bw, 1, 1) put(bw, 3, 2) put(bw, num - 1, 8) local pimg = bcreate(num * 4) local prevc = 0 local index: { [number]: number } = {} for i, c in pal do writeu32(pimg, (i - 1) * 4, subPixels(c, prevc)) prevc = c index[c] = i - 1 end writeImage(bw, pimg, num, num, sub, false) xs = subSample(w, bits) local packed = bcreate(xs * h * 4) local bpp = rshift(8, bits) local cmask = lshift(1, bits) - 1 for y = 0, h - 1 do local acc = 0 local o = y * xs for x = 0, w - 1 do local sh = band(x, cmask) acc += index[readu32(px, (y * w + x) * 4)] * 2 ^ (bpp * sh) if sh == cmask or x == w - 1 then writeu32(packed, (o + rshift(x, bits)) * 4, ARGB_BLACK + acc * 256) acc = 0 end end end px = packed elseif cfg.pbits > 0 then -- subtract green put(bw, 1, 1) put(bw, 2, 2) for i = 0, n - 1 do local v = readu32(px, i * 4) local g = band(rshift(v, 8), 255) writeu32(px, i * 4, band(v, 0xff00ff00) + band(band(v, 0x00ff00ff) + 0x01000100 - g * 65537, 0x00ff00ff)) end -- predictor local pbits = cfg.pbits local modes = predictorTransform(px, w, h, pbits, effort) put(bw, 1, 1) put(bw, 0, 2) put(bw, pbits - 2, 3) writeImage(bw, modes, subSample(w, pbits), subSample(w, pbits) * subSample(h, pbits), sub, false) -- cross colour if cfg.cc then local cbits = cfg.ccbits local cimg = crossColorTransform(px, w, h, cbits) put(bw, 1, 1) put(bw, 1, 2) put(bw, cbits - 2, 3) writeImage(bw, cimg, subSample(w, cbits), subSample(w, cbits) * subSample(h, cbits), sub, false) end end put(bw, 0, 1) -- no more transforms writeImage(bw, px, xs, xs * h, effort, true) end @native function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact: boolean, alphaHint: boolean?, headerless: boolean): buffer local n = w * h local px, usesAlpha = toArgb(rgba, n, exact) local pal = if effort > 0 then palette(px, n) else nil local configs: { Config } = {} if effort == 0 then table.insert(configs, { palette = nil, pbits = 0, cc = false, ccbits = 0 }) else local pbits = if effort >= 5 then 4 else 5 local plain: Config = { palette = nil, pbits = pbits, cc = effort >= 3, ccbits = if effort >= 6 then 4 else 5 } if pal then table.insert(configs, { palette = pal, pbits = 0, cc = false, ccbits = 0 }) if effort >= 6 then table.insert(configs, plain) end else table.insert(configs, plain) end if effort >= 9 then table.insert(configs, { palette = nil, pbits = 3, cc = true, ccbits = 3 }) table.insert(configs, { palette = nil, pbits = 5, cc = false, ccbits = 0 }) end end local best: buffer? = nil for k, cfg in configs do local bw = newWriter(n + 256) if not headerless then put(bw, 0x2f, 8) put(bw, w - 1, 14) put(bw, h - 1, 14) local hint = if alphaHint == nil then usesAlpha else alphaHint put(bw, if hint then 1 else 0, 1) put(bw, 0, 3) end local work = px if k < #configs then work = bcreate(n * 4) bcopy(work, 0, px, 0, n * 4) end stream(work, w, h, effort, cfg, bw) local out = finish(bw) if not best or blen(out) < blen(best) then best = out end end return best :: buffer end return Encode end __FILES["codecs/image/Yuv"] = @native function() -- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8, BT.601 / BT.709, limited or full range. -- yuv -> rgb: nearest chroma, swscale's default 16-bit coefficients (within about one level of ffmpeg -pix_fmt rgba); -- rgb -> yuv: each 2x2 block averaged for the chroma. local Types = __include("Types") local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 local bcreate = buffer.create local floor = math.floor local Yuv = {} -- coefficients (x 65536): r = y' + crv * v; g = y' - cgu * u - cgv * v; b = y' + cbu * u -- limited: y' = (y - 16) * 255 / 219, chroma scaled by 255 / 224 local MATRIX: { [string]: { kr: number, kb: number } } = { bt601 = { kr = 0.299, kb = 0.114 }, bt709 = { kr = 0.2126, kb = 0.0722 }, } type Coeffs = { ys: number, yo: number, crv: number, cgu: number, cgv: number, cbu: number, cs: number } local cache: { [string]: Coeffs } = {} @native local function coeffs(range: string?, matrix: string?): Coeffs local key = (range or "limited") .. (matrix or "bt601") local c = cache[key] if c then return c end local m = MATRIX[matrix or "bt601"] or MATRIX.bt601 local kr, kb = m.kr, m.kb local kg = 1 - kr - kb local full = range == "full" local ys = if full then 1 else 255 / 219 local cs = if full then 1 else 255 / 224 c = { ys = floor(ys * 65536 + 0.5), yo = if full then 0 else 16, crv = floor(2 * (1 - kr) * cs * 65536 + 0.5), cbu = floor(2 * (1 - kb) * cs * 65536 + 0.5), cgu = floor(2 * (1 - kb) * kb / kg * cs * 65536 + 0.5), cgv = floor(2 * (1 - kr) * kr / kg * cs * 65536 + 0.5), cs = cs, } cache[key] = c return c end local CLIP = bcreate(2304) for i = 0, 2303 do writeu8(CLIP, i, math.clamp(i - 1024, 0, 255)) end @native function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?): buffer local dst = out or bcreate(w * h * 4) local c = coeffs(range, matrix) local ys, yo, crv, cgu, cgv, cbu = c.ys, c.yo, c.crv, c.cgu, c.cgv, c.cbu local ch = (h + 1) // 2 if buffer.len(src) < vo + cw * ch or buffer.len(dst) < w * h * 4 or uo + cw * ch > buffer.len(src) then return dst end for y = 0, h - 1 do local yrow = y * w local crow = (y // 2) * cw local o = yrow * 4 for x = 0, w - 1, 2 do local ci = crow + (x // 2) local u = readu8(src, uo + ci) - 128 local v = readu8(src, vo + ci) - 128 local rv = (crv * v + 32768) // 65536 local gv = (cgu * u + cgv * v + 32768) // 65536 local bu = (cbu * u + 32768) // 65536 local yy = (ys * (readu8(src, yrow + x) - yo) + 32768) // 65536 + 1024 writeu32(dst, o, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000) if x + 1 < w then yy = (ys * (readu8(src, yrow + x + 1) - yo) + 32768) // 65536 + 1024 writeu32(dst, o + 4, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000) end o += 8 end end return dst end @native function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: string?, out: buffer?): buffer local cw, ch = (w + 1) // 2, (h + 1) // 2 local uo, vo = w * h, w * h + cw * ch local dst = out or bcreate(w * h + 2 * cw * ch) if buffer.len(src) < w * h * 4 or buffer.len(dst) < w * h + 2 * cw * ch then return dst end local m = MATRIX[matrix or "bt601"] or MATRIX.bt601 local kr, kb = m.kr, m.kb local kg = 1 - kr - kb local full = range == "full" local ysc = if full then 1 else 219 / 255 local csc = if full then 1 else 224 / 255 local yof = if full then 0.5 else 16.5 local yr, yg, yb = floor(kr * ysc * 65536 + 0.5), floor(kg * ysc * 65536 + 0.5), floor(kb * ysc * 65536 + 0.5) local yoff = floor(yof * 65536) local ur = floor(-kr / (2 * (1 - kb)) * csc * 65536 + 0.5) local ug = floor(-kg / (2 * (1 - kb)) * csc * 65536 + 0.5) local ub = floor(0.5 * csc * 65536 + 0.5) local vr = ub local vg = floor(-kg / (2 * (1 - kr)) * csc * 65536 + 0.5) local vb = floor(-kb / (2 * (1 - kr)) * csc * 65536 + 0.5) local coff4 = floor(128.5 * 65536) * 4 for i = 0, w * h - 1 do local o = i * 4 local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) writeu8(dst, i, readu8(CLIP, (yr * r + yg * g + yb * b + yoff) // 65536 + 1024)) end for cy = 0, ch - 1 do local y0 = cy * 2 local y1 = if y0 + 1 < h then y0 + 1 else y0 for cx = 0, cw - 1 do local x0 = cx * 2 local x1 = if x0 + 1 < w then x0 + 1 else x0 local a, b2, c2, d = (y0 * w + x0) * 4, (y0 * w + x1) * 4, (y1 * w + x0) * 4, (y1 * w + x1) * 4 local r = readu8(src, a) + readu8(src, b2) + readu8(src, c2) + readu8(src, d) local g = readu8(src, a + 1) + readu8(src, b2 + 1) + readu8(src, c2 + 1) + readu8(src, d + 1) local b = readu8(src, a + 2) + readu8(src, b2 + 2) + readu8(src, c2 + 2) + readu8(src, d + 2) local i = cy * cw + cx writeu8(dst, uo + i, readu8(CLIP, (ur * r + ug * g + ub * b + coff4) // 262144 + 1024)) writeu8(dst, vo + i, readu8(CLIP, (vr * r + vg * g + vb * b + coff4) // 262144 + 1024)) end end return dst end @native local function info(img: Types.Image): (string, string) local m = img.meta local y = m and m.yuv if type(y) == "table" then return y.range or "limited", y.matrix or "bt601" end local src = m and m.source if type(src) == "table" and src.range == "full" then return "full", "bt601" end return "limited", "bt601" end Yuv.info = info @native function Yuv.planes(w: number, h: number): (number, number, number, number) local cw, ch = (w + 1) // 2, (h + 1) // 2 return w * h, w * h + cw * ch, cw, ch end local FULL_Y = bcreate(256) local FULL_C = bcreate(256) for v = 0, 255 do writeu8(FULL_Y, v, math.clamp(floor((v - 16) * 255 / 219 + 0.5), 0, 255)) writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255)) end @native function Yuv.toFullRange(img: Types.Image): Types.Image if img.format ~= "yuv420p" or info(img) == "full" then return img end local w, h = img.width, img.height local out = Types.Image.new(w, h, "yuv420p") local src, dst = img.pixels, out.pixels local ny = w * h local n = math.min(buffer.len(src), buffer.len(dst)) for i = 0, math.min(ny, n) - 1 do writeu8(dst, i, readu8(FULL_Y, readu8(src, i))) end for i = ny, n - 1 do writeu8(dst, i, readu8(FULL_C, readu8(src, i))) end out.meta.yuv = { range = "full", matrix = select(2, info(img)) } out.meta.source = img.meta.source return out end @native function Yuv.imageToRgba(img: Types.Image): Types.Image? if img.format == "rgba8" then return img end if img.format ~= "yuv420p" then return nil end local w, h = img.width, img.height local uo, vo, cw = Yuv.planes(w, h) local range, matrix = info(img) local out = Types.Image.new(w, h, "rgba8") Yuv.toRgba(img.pixels, w, h, uo, vo, cw, range, matrix, out.pixels) out.meta.source = img.meta.source return out end @native function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image? if img.format == "yuv420p" then return img end if img.format ~= "rgba8" then return nil end local out = Types.Image.new(img.width, img.height, "yuv420p") Yuv.fromRgba(img.pixels, img.width, img.height, range, matrix, out.pixels) out.meta.yuv = { range = range or "limited", matrix = matrix or "bt601" } out.meta.source = img.meta.source return out end @native local function scalePlane(src: buffer, so: number, sw: number, sh: number, dst: buffer, d0: number, dw: number, dh: number) local fx, fy = sw / dw, sh / dh for y = 0, dh - 1 do local sy = (y + 0.5) * fy - 0.5 if sy < 0 then sy = 0 end local y0 = floor(sy) if y0 > sh - 1 then y0 = sh - 1 end local y1 = if y0 < sh - 1 then y0 + 1 else y0 local wy = floor((sy - y0) * 256) local r0, r1 = so + y0 * sw, so + y1 * sw local o = d0 + y * dw for x = 0, dw - 1 do local sx = (x + 0.5) * fx - 0.5 if sx < 0 then sx = 0 end local x0 = floor(sx) if x0 > sw - 1 then x0 = sw - 1 end local x1 = if x0 < sw - 1 then x0 + 1 else x0 local wx = floor((sx - x0) * 256) local a = readu8(src, r0 + x0) * (256 - wx) + readu8(src, r0 + x1) * wx local b = readu8(src, r1 + x0) * (256 - wx) + readu8(src, r1 + x1) * wx writeu8(dst, o + x, (a * (256 - wy) + b * wy + 32768) // 65536) end end end @native function Yuv.scale(src: buffer, w: number, h: number, width: number, height: number, out: buffer?): buffer local dw: number = math.max(1, floor(width)) local dh: number = math.max(1, floor(height)) local cw: number = (w + 1) // 2 local ch: number = (h + 1) // 2 local dcw: number = (dw + 1) // 2 local dch: number = (dh + 1) // 2 local size = dw * dh + 2 * dcw * dch local dst = if out and buffer.len(out) >= size then out else bcreate(size) if w < 1 or h < 1 or buffer.len(src) < w * h + 2 * cw * ch then return dst end scalePlane(src, 0, w, h, dst, 0, dw, dh) scalePlane(src, w * h, cw, ch, dst, dw * dh, dcw, dch) scalePlane(src, w * h + cw * ch, cw, ch, dst, dw * dh + dcw * dch, dcw, dch) return dst end @native function Yuv.imageScale(img: Types.Image, dw: number, dh: number): Types.Image local out = Types.Image.new(math.max(1, floor(dw)), math.max(1, floor(dh)), "yuv420p") Yuv.scale(img.pixels, img.width, img.height, out.width, out.height, out.pixels) out.meta = table.clone(img.meta or {}) return out end return Yuv end __FILES["codecs/model/Brush"] = @native function() -- 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 type Plane = { number } -- nx, ny, nz, d (unit normal pointing out of the brush) type Face = { plane: Plane, texture: string?, vecs: { { number } }?, -- 2 x 4: s = p . vecs[1].xyz + vecs[1][4] in texels (Quake standard / Valve 220) bp: { { number } }?, -- 2 x 3 brush-primitive matrix: s = bp[1] . (p . texS, p . texT, 1) in texture widths [string]: any, } type Polygon = { brush: number, face: number, points: { number }, -- x, y, z per corner, counter-clockwise seen from the front normal: { number }, } type Options = { epsilon: number?, -- plane side tolerance, default 1e-3 size: number?, -- half size of the starting winding, default 2^17 merge: boolean?, -- merge coplanar faces with the same texture projection, default false hull: boolean?, -- drop face parts inside / touching other brushes, default false maxPolygons: number?, -- default 2^20 } type Built = { texture: string, primitive: Types.Primitive } -- 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 }, } @native local function snap(x: number): number local r = floor(x + 0.5) return if abs(x - r) < 1e-6 then r else x end -- qbsp PlaneFromPoints: normal = (p1 - p2) x (p3 - p2), the brush lies behind it; nil when the points are colinear @native function Brush.planeFromPoints(a: { number }, b: { number }, c: { number }): Plane? 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) @native function Brush.baseAxis(n: { number }): number 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) @native function Brush.quakeVecs(n: { number }, xoff: number, yoff: number, rot: number, xscale: number, yscale: number): { { number } } 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 = if vecs[1][1] ~= 0 then 1 elseif vecs[1][2] ~= 0 then 2 else 3 local tv = if vecs[2][1] ~= 0 then 1 elseif vecs[2][2] ~= 0 then 2 else 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 = { if xscale == 0 then 1 else xscale, if yscale == 0 then 1 else 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 @native function Brush.valveVecs(u: { number }, v: { number }, xscale: number, yscale: number): { { number } } local su, sv = if xscale == 0 then 1 else xscale, if yscale == 0 then 1 else 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 @native function Brush.axisBase(normal: { number }): ({ number }, { number }) local nx, ny, nz = normal[1], normal[2], normal[3] nx = if abs(nx) < 1e-6 then 0 else nx ny = if abs(ny) < 1e-6 then 0 else ny nz = if abs(nz) < 1e-6 then 0 else 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) @native function Brush.bpVecs(normal: { number }, m: { { number } }, w: number, h: number): { { number } } local tx, ty = Brush.axisBase(normal) local out = {} for i, size in { 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) @native function Brush.vecsToBp(normal: { number }, vecs: { { number } }, w: number, h: number): { { number } } local tx, ty = Brush.axisBase(normal) local out = {} for i, size in { 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) @native function Brush.uv(face: Face, x: number, y: number, z: number, w: number, h: number): (number, number) 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 @native function Brush.baseWinding(p: Plane, size: number): { number } 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 @native function Brush.split(pts: { number }, p: Plane, eps: number): ({ number }?, { number }?, boolean) local n = #pts // 3 local nx, ny, nz, d = p[1], p[2], p[3], p[4] local dist = table.create(n, 0) :: { number } local side = table.create(n, 0) :: { number } 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 += 1 elseif v < -eps then side[i + 1] = -1 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: { number }, b: { number } = {}, {} 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 (if #f >= 9 then f else nil), (if #b >= 9 then b else nil), false end -- removes repeated and colinear corners; nil when fewer than 3 remain @native local function clean(pts: { number }, eps: number): { number }? local out: { number } = {} local n = #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 = #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 if #out >= 9 then out else nil end @native local function samePlane(a: Plane, b: Plane, eps: number): boolean 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 @native local function oppositePlane(a: Plane, b: Plane, eps: number): boolean 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) @native function Brush.windings(planes: { Plane }, opts: Options?): { { number }? } local eps = opts and opts.epsilon or 1e-3 local size = opts and opts.size or 2 ^ 17 local out: { { number }? } = {} for i, p in planes do local w: { number }? = Brush.baseWinding(p, size) for j, q in 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 = if on then nil else back end end end out[i] = if w then clean(w, eps) else nil end return out end @native local function bounds(polys: { Polygon }): { number } local b = { math.huge, math.huge, math.huge, -math.huge, -math.huge, -math.huge } for _, p in polys do local pts = p.points for k = 0, #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 @native local function outside(pts: { number }, own: Plane, a: number, b: number, planes: { Plane }, eps: number): { { number } } local kept: { { number } } = {} local inside: { number }? = pts for _, q in 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 @native local function faceKey(f: Face): string local parts = { f.texture or "" } for _, m in { f.vecs, f.bp } do if m then for _, row in m do for _, v in row do table.insert(parts, string.format("%.6g", v)) end end end end return table.concat(parts, " ") end @native local function convex(pts: { number }, n: { number }, eps: number): boolean local k = #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 @native local function tryMerge(f1: { number }, f2: { number }, n: { number }, eps: number): { number }? local n1, n2 = #f1 // 3, #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: { number } = {} 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 @native local function mergeAll(polys: { Polygon }, faces: { [number]: { Face } }, eps: number): { Polygon } local groups: { [string]: { Polygon } } = {} local order: { string } = {} for _, p in 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: { Polygon } = {} for _, key in 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 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 @native function Brush.polygons(brushes: { { Face } }, opts: Options?): ({ Polygon }?, string?) local eps = opts and opts.epsilon or 1e-3 local limit = opts and opts.maxPolygons or 2 ^ 20 local per: { { Polygon } } = {} local planesOf: { { Plane } } = {} local count = 0 for bi, faces in brushes do local planes: { Plane } = {} for fi, f in faces do planes[fi] = f.plane end planesOf[bi] = planes local list: { Polygon } = {} 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 += #list if count > limit then return nil, "limit: too many brush faces" end end local all: { Polygon } = {} if opts and opts.hull then local boxes: { { number } } = {} for bi = 1, #brushes do boxes[bi] = bounds(per[bi]) end for bi = 1, #brushes do for _, p in per[bi] do local frags: { { number } } = { 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: { { number } } = {} for _, fr in frags do for _, kept in 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 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 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) @native function Brush.area(pts: { number }): number local n = #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 += uy * vz - uz * vy ay += uz * vx - ux * vz 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) @native function Brush.primitives(polys: { Polygon }, brushes: { { Face } }, size: (name: string) -> (number, number)): { Built } type Acc = { texture: string, pos: { number }, nrm: { number }, uv: { number }, idx: { number } } local byTex: { [string]: Acc } = {} local order: { Acc } = {} local sizes: { [string]: { number } } = {} for _, p in 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 = acc local pts = p.points local n = #pts // 3 local base = #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: { Built } = {} for _, a in order do local nv, ni = #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" :: "triangles", }, }) end return out end return Brush end __FILES["codecs/model/DoomMap"] = function() -- codecs/model/DoomMap: Doom / Heretic / Hexen binary map lumps (Hexen when BEHAVIOR is present) and UDMF TEXTMAP to -- tables and a Scene, with vanilla texture alignment (offsets, unpegged) and the sky hack; z up, map units. From the -- Unofficial Doom Specs, the Hexen specs and UDMF 1.1; no code taken. Not supported: UDMF slopes / per-part offsets. local Types = __include("Types") local Polygon = __include("codecs/model/Polygon") local Udmf = __include("codecs/model/DoomMap/Udmf") local Map = {} local Scene = Types.Scene local readu8, readi16, readu16 = buffer.readu8, buffer.readi16, buffer.readu16 local writef32, writeu32 = buffer.writef32, buffer.writeu32 type Lump = { buf: buffer, at: number, size: number } type Fields = { [string]: any } -- UDMF: the block's fields as written (lower-case keys) type Thing = { x: number, y: number, z: number?, angle: number, type: number, flags: number, tid: number?, special: number?, args: { number }?, fields: Fields? } type Linedef = { v1: number, v2: number, flags: number, special: number, tag: number?, args: { number }?, front: number?, back: number?, fields: Fields? } type Sidedef = { xoff: number, yoff: number, upper: string, lower: string, middle: string, sector: number, fields: Fields? } type Sector = { floor: number, ceiling: number, floorFlat: string, ceilingFlat: string, light: number, special: number, tag: number, fields: Fields? } type MapData = { format: "doom" | "hexen" | "udmf", namespace: string?, -- UDMF globals: Fields?, -- UDMF global assignments blocks: { Udmf.Block }?, -- UDMF blocks other than vertex / linedef / sidedef / sector / thing things: { Thing }, linedefs: { Linedef }, sidedefs: { Sidedef }, vertices: { number }, -- x1, y1, x2, y2, ... sectors: { Sector }, } type Textures = { size: (kind: string, name: string) -> (number?, number?), image: ((kind: string, name: string) -> Types.Image?)?, } -- ------------------------------------------------------------------------------------------------ parse local function name8(b: buffer, at: number): string local s = buffer.readstring(b, at, 8) local z = string.find(s, "\0", 1, true) return string.upper(if z then string.sub(s, 1, z - 1) else s) end local function side(v: number): number? return if v == 0xFFFF then nil else v + 1 end function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string?) for _, k in { "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" } do if not lumps[k] then return nil, "map has no " .. k end end local m: MapData = { format = if hexen then "hexen" else "doom", things = {}, linedefs = {}, sidedefs = {}, vertices = {}, sectors = {} } local v = lumps.VERTEXES for i = 0, v.size // 4 - 1 do table.insert(m.vertices, readi16(v.buf, v.at + i * 4)) table.insert(m.vertices, readi16(v.buf, v.at + i * 4 + 2)) end local s = lumps.SECTORS for i = 0, s.size // 26 - 1 do local o = s.at + i * 26 table.insert(m.sectors, { floor = readi16(s.buf, o), ceiling = readi16(s.buf, o + 2), floorFlat = name8(s.buf, o + 4), ceilingFlat = name8(s.buf, o + 12), light = readi16(s.buf, o + 20), special = readu16(s.buf, o + 22), tag = readu16(s.buf, o + 24), }) end local sd = lumps.SIDEDEFS for i = 0, sd.size // 30 - 1 do local o = sd.at + i * 30 table.insert(m.sidedefs, { xoff = readi16(sd.buf, o), yoff = readi16(sd.buf, o + 2), upper = name8(sd.buf, o + 4), lower = name8(sd.buf, o + 12), middle = name8(sd.buf, o + 20), sector = readu16(sd.buf, o + 28) + 1, }) end local l = lumps.LINEDEFS local ls = if hexen then 16 else 14 for i = 0, l.size // ls - 1 do local o = l.at + i * ls local b = l.buf if hexen then table.insert(m.linedefs, { v1 = readu16(b, o) + 1, v2 = readu16(b, o + 2) + 1, flags = readu16(b, o + 4), special = readu8(b, o + 6), args = { readu8(b, o + 7), readu8(b, o + 8), readu8(b, o + 9), readu8(b, o + 10), readu8(b, o + 11) }, front = side(readu16(b, o + 12)), back = side(readu16(b, o + 14)), }) else table.insert(m.linedefs, { v1 = readu16(b, o) + 1, v2 = readu16(b, o + 2) + 1, flags = readu16(b, o + 4), special = readu16(b, o + 6), tag = readu16(b, o + 8), front = side(readu16(b, o + 10)), back = side(readu16(b, o + 12)), }) end end local t = lumps.THINGS if t then local ts = if hexen then 20 else 10 for i = 0, t.size // ts - 1 do local o = t.at + i * ts local b = t.buf if hexen then table.insert(m.things, { tid = readi16(b, o), x = readi16(b, o + 2), y = readi16(b, o + 4), z = readi16(b, o + 6), angle = readi16(b, o + 8), type = readu16(b, o + 10), flags = readu16(b, o + 12), special = readu8(b, o + 14), args = { readu8(b, o + 15), readu8(b, o + 16), readu8(b, o + 17), readu8(b, o + 18), readu8(b, o + 19) }, }) else table.insert(m.things, { x = readi16(b, o), y = readi16(b, o + 2), angle = readi16(b, o + 4), type = readu16(b, o + 6), flags = readu16(b, o + 8), }) end end end return m, nil end function Map.udmf(text: string, maxBlocks: number?): (MapData?, string?) local doc, err = Udmf.parse(text, maxBlocks) if not doc then return nil, err end return Udmf.map(doc) end Map.parseUdmf = Udmf.parse -- ------------------------------------------------------------------------------------------------ sector outlines -- sector loops: front sides v1 -> v2, back sides v2 -> v1, lines with the sector on both sides left out; the sharpest -- right turn at forks; unclosed chains dropped local function loops(m: MapData): { [number]: { { number } } } local edges: { [number]: { { number } } } = {} local nv = #m.vertices // 2 local function add(sec: number, a: number, b: number) local e = edges[sec] or {} edges[sec] = e table.insert(e, { a, b }) end for _, ld in m.linedefs do if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then local fs = ld.front and m.sidedefs[ld.front] local bs = ld.back and m.sidedefs[ld.back] local f = fs and fs.sector local b = bs and bs.sector if f ~= b then if f and m.sectors[f] then add(f, ld.v1, ld.v2) end if b and m.sectors[b] then add(b, ld.v2, ld.v1) end end end end local V = m.vertices local out: { [number]: { { number } } } = {} for sec, list in edges do local from: { [number]: { number } } = {} for i, e in list do local l = from[e[1]] or {} from[e[1]] = l table.insert(l, i) end local used: { [number]: boolean } = {} local res: { { number } } = {} for start = 1, #list do if not used[start] then used[start] = true local loop = { list[start][1] } local cur = start local closed = false for _ = 1, #list do local e = list[cur] local at = e[2] if at == loop[1] then closed = true break end table.insert(loop, at) local cands = from[at] local best, bestT = nil :: number?, math.huge if cands then local ix, iy = V[at * 2 - 1] - V[e[1] * 2 - 1], V[at * 2] - V[e[1] * 2] for _, c in cands do if not used[c] then local n2 = list[c][2] local ox, oy = V[n2 * 2 - 1] - V[at * 2 - 1], V[n2 * 2] - V[at * 2] local t = math.atan2(ix * oy - iy * ox, ix * ox + iy * oy) if t < bestT then best, bestT = c, t end end end end if not best then break end used[best] = true cur = best end if closed and #loop >= 3 then table.insert(res, loop) end end end out[sec] = res end return out end local function insideLoop(V: { number }, loop: { number }, x: number, y: number): boolean local c = false local n = #loop local j = n for i = 1, n do local ax, ay = V[loop[i] * 2 - 1], V[loop[i] * 2] local bx, by = V[loop[j] * 2 - 1], V[loop[j] * 2] if (ay > y) ~= (by > y) and x < (bx - ax) * (y - ay) / (by - ay) + ax then c = not c end j = i end return c end -- ------------------------------------------------------------------------------------------------ scene type Batch = { kind: string, name: string, pos: { number }, nrm: { number }, uv: { number } } local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4 function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene local batches: { [string]: Batch } = {} local order: { string } = {} local function batch(kind: string, tname: string): Batch local key = kind .. ":" .. tname local b = batches[key] if not b then b = { kind = kind, name = tname, pos = {}, nrm = {}, uv = {} } batches[key] = b table.insert(order, key) end return b end local function vert(b: Batch, x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number) local p, n, t = b.pos, b.nrm, b.uv p[#p + 1], p[#p + 2], p[#p + 3] = x, y, z n[#n + 1], n[#n + 2], n[#n + 3] = nx, ny, nz t[#t + 1], t[#t + 2] = u, v end local V = m.vertices local nv = #V // 2 local secLoops = loops(m) for sec, ls in secLoops do local s = m.sectors[sec] local flat: { { number } } = {} for li, loop in ls do local f: { number } = {} for _, vi in loop do table.insert(f, V[vi * 2 - 1]) table.insert(f, V[vi * 2]) end flat[li] = f end local tris = Polygon.triangulate(flat) for pass = 1, 2 do local tname = if pass == 1 then s.floorFlat else s.ceilingFlat local fw, fh = tex.size("flat", tname) local w, h = fw or 64, fh or 64 local z = if pass == 1 then s.floor else s.ceiling local b = batch("flat", tname) local nz = if pass == 1 then 1 else -1 for k = 1, #tris, 6 do for c = 0, 2 do local cc = if pass == 1 then c else 2 - c local loop = ls[tris[k + cc * 2]] local vi = loop[tris[k + cc * 2 + 1]] local x, y = V[vi * 2 - 1], V[vi * 2] vert(b, x, y, z, 0, 0, nz, x / w, -y / h) end end end end local function quad(tname: string, x1: number, y1: number, x2: number, y2: number, zb: number, zt: number, xoff: number, len: number, texTop: number, yoff: number) if tname == "-" or tname == "" or zt <= zb then return end local tw, th = tex.size("texture", tname) local w, h = tw or 64, th or 128 local b = batch("texture", tname) local dx, dy = x2 - x1, y2 - y1 local l = math.sqrt(dx * dx + dy * dy) local nx, ny = dy / l, -dx / l local u0, u1 = xoff / w, (xoff + len) / w local vb, vt = (texTop - zb + yoff) / h, (texTop - zt + yoff) / h vert(b, x1, y1, zb, nx, ny, 0, u0, vb) vert(b, x2, y2, zb, nx, ny, 0, u1, vb) vert(b, x2, y2, zt, nx, ny, 0, u1, vt) vert(b, x1, y1, zb, nx, ny, 0, u0, vb) vert(b, x2, y2, zt, nx, ny, 0, u1, vt) vert(b, x1, y1, zt, nx, ny, 0, u0, vt) end for _, ld in m.linedefs do if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then local ax, ay, bx, by = V[ld.v1 * 2 - 1], V[ld.v1 * 2], V[ld.v2 * 2 - 1], V[ld.v2 * 2] local len = math.sqrt((bx - ax) ^ 2 + (by - ay) ^ 2) for sideN = 1, 2 do local sdi = if sideN == 1 then ld.front else ld.back local odi = if sideN == 1 then ld.back else ld.front local sd = sdi and m.sidedefs[sdi] local me = sd and m.sectors[sd.sector] if sd and me then local x1, y1, x2, y2 = ax, ay, bx, by if sideN == 2 then x1, y1, x2, y2 = bx, by, ax, ay end local od = odi and m.sidedefs[odi] local other = od and m.sectors[od.sector] if not other then local th = select(2, tex.size("texture", sd.middle)) or 128 local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.floor + th else me.ceiling quad(sd.middle, x1, y1, x2, y2, me.floor, me.ceiling, sd.xoff, len, top, sd.yoff) else if other.floor > me.floor then local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.ceiling else other.floor quad(sd.lower, x1, y1, x2, y2, me.floor, other.floor, sd.xoff, len, top, sd.yoff) end local sky = string.sub(me.ceilingFlat, 1, 5) == "F_SKY" and string.sub(other.ceilingFlat, 1, 5) == "F_SKY" if other.ceiling < me.ceiling and not sky then local th = select(2, tex.size("texture", sd.upper)) or 128 local top = if bit32.band(ld.flags, UPPER_UNPEGGED) ~= 0 then me.ceiling else other.ceiling + th quad(sd.upper, x1, y1, x2, y2, other.ceiling, me.ceiling, sd.xoff, len, top, sd.yoff) end if sd.middle ~= "-" and sd.middle ~= "" and bit32.band(ld.flags, TWO_SIDED) ~= 0 then local th = select(2, tex.size("texture", sd.middle)) or 128 local lo, hi = math.max(me.floor, other.floor), math.min(me.ceiling, other.ceiling) local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then lo + th else hi quad(sd.middle, x1, y1, x2, y2, math.max(lo, top + sd.yoff - th), math.min(hi, top + sd.yoff), sd.xoff, len, top, sd.yoff) end end end end end end local scene = Scene.new() scene.meta.up = "z" local mesh: Types.Mesh = { name = name, primitives = {} } local texIndex: { [string]: number } = {} for _, key in order do local b = batches[key] local n = #b.pos // 3 if n > 0 then local pb, nb, ub, ib = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) for i = 1, n * 3 do writef32(pb, (i - 1) * 4, b.pos[i]) writef32(nb, (i - 1) * 4, b.nrm[i]) end for i = 1, n * 2 do writef32(ub, (i - 1) * 4, b.uv[i]) end for i = 0, n - 1 do writeu32(ib, i * 4, i) end local ti = texIndex[key] if not ti then table.insert(scene.textures, { name = b.name, uri = b.name, image = if tex.image then tex.image(b.kind, b.name) else nil, extras = { wad = { kind = b.kind } } }) ti = #scene.textures texIndex[key] = ti end local mat = Scene.material(b.name) mat.metallic = 0 mat.baseColorTexture = { texture = ti } mat.extras = { wad = { kind = b.kind } } table.insert(scene.materials, mat) table.insert(mesh.primitives, { attributes = { POSITION = Scene.accessor(pb, "f32", 3, n), NORMAL = Scene.accessor(nb, "f32", 3, n), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, n), }, indices = Scene.accessor(ib, "u32", 1, n), mode = "triangles" :: any, material = #scene.materials, extras = { wad = { kind = b.kind, texture = b.name } }, }) end end table.insert(scene.meshes, mesh) scene.nodes[1] = { name = name, children = {}, mesh = 1 } scene.roots[1] = 1 for i, th in m.things do local z = th.z or 0 for sec, ls in secLoops do local inside = false for _, loop in ls do if insideLoop(V, loop, th.x, th.y) then inside = not inside end end if inside then z += m.sectors[sec].floor break end end local a = math.rad(th.angle) / 2 table.insert(scene.nodes, { name = "thing " .. i, children = {}, translation = { th.x, th.y, z }, rotation = { 0, 0, math.sin(a), math.cos(a) }, extras = { thing = { type = th.type, angle = th.angle, flags = th.flags, tid = th.tid, special = th.special, args = th.args } }, }) table.insert(scene.nodes[1].children, #scene.nodes) end return scene end return Map end __FILES["codecs/model/DoomMap/Udmf"] = function() -- codecs/model/DoomMap/Udmf: UDMF 1.1 TEXTMAP text (zdoom.org specs/udmf.txt; no code taken) to the DoomMap tables. -- Every block keeps its fields (lower-case keys, namespace and user_ keys included); unknown blocks and global -- assignments are kept as data. Flags are rebuilt in the binary layout of the namespace (Doom or Hexen bits). local Lexer = __include("codecs/text/Lexer") local Udmf = {} type Block = { type: string, fields: { [string]: any } } type Document = { namespace: string?, globals: { [string]: any }, blocks: { Block } } -- ------------------------------------------------------------------------------------------------ parse local function value(L: Lexer.Lexer): (any, string?) local k, v = L:next() if k == "number" then local raw = L.raw :: string -- integer := ... | 0[0-9]+ (octal) | 0x[0-9A-Fa-f]+ if string.match(raw, "^[+-]?0[0-7]+$") then local neg = string.sub(raw, 1, 1) == "-" local o = tonumber((string.gsub(raw, "^[+-]?0", "")), 8) :: number return if neg then -o else o, nil end return v, nil elseif k == "string" then return v, nil elseif k == "word" then local w = string.lower(v) if w == "true" then return true, nil elseif w == "false" then return false, nil end return v, nil end return nil, L.err or "expected a value" end function Udmf.parse(text: string, maxBlocks: number?): (Document?, string?) local L = Lexer.new(text) local doc: Document = { namespace = nil, globals = {}, blocks = {} } local limit = maxBlocks or 2 ^ 22 while true do local k, id = L:next() if k == nil then if L.err then return nil, L.err .. " at line " .. L:line() end break end if k ~= "word" then return nil, "expected an identifier at line " .. L:line() end local name = string.lower(id) local pk, pv = L:next() if pk == "punct" and pv == "=" then local v, err = value(L) if err then return nil, err .. " at line " .. L:line() end local sk, sv = L:next() if sk ~= "punct" or sv ~= ";" then return nil, "expected ; at line " .. L:line() end doc.globals[name] = v if name == "namespace" and type(v) == "string" then doc.namespace = v end elseif pk == "punct" and pv == "{" then if #doc.blocks >= limit then return nil, "limit: more than " .. limit .. " blocks" end local fields: { [string]: any } = {} while true do local fk, fv = L:next() if fk == "punct" and fv == "}" then break end if fk ~= "word" then return nil, (L.err or "expected a field name") .. " at line " .. L:line() end local ek, ev = L:next() if ek ~= "punct" or ev ~= "=" then return nil, "expected = at line " .. L:line() end local v, err = value(L) if err then return nil, err .. " at line " .. L:line() end local sk, sv = L:next() if sk ~= "punct" or sv ~= ";" then return nil, "expected ; at line " .. L:line() end fields[string.lower(fv)] = v end table.insert(doc.blocks, { type = name, fields = fields }) else return nil, "expected = or { at line " .. L:line() end end return doc, nil end -- ------------------------------------------------------------------------------------------------ map local LINE_FLAGS: { [string]: number } = { blocking = 1, blockmonsters = 2, twosided = 4, dontpegtop = 8, dontpegbottom = 16, secret = 32, blocksound = 64, dontdraw = 128, mapped = 256 } -- Hexen SPAC activation (bits 10..12) and repeat (bit 9) local SPAC: { [string]: number } = { playercross = 0, playeruse = 1, monstercross = 2, impact = 3, playerpush = 4, missilecross = 5 } local function num(f: { [string]: any }, k: string, default: number): number local v = f[k] return if type(v) == "number" then v else default end local function flag(f: { [string]: any }, k: string): boolean return f[k] == true end local function tex(f: { [string]: any }, k: string, default: string): string local v = f[k] return if type(v) == "string" then string.upper(v) else default end local function args(f: { [string]: any }): { number } return { num(f, "arg0", 0), num(f, "arg1", 0), num(f, "arg2", 0), num(f, "arg3", 0), num(f, "arg4", 0) } end local function index(f: { [string]: any }, k: string): number? local v = f[k] return if type(v) == "number" and v >= 0 and v % 1 == 0 then v + 1 else nil end function Udmf.map(doc: Document): (any, string?) local ns = string.lower(doc.namespace or "") local hexenBits = ns ~= "doom" and ns ~= "heretic" and ns ~= "strife" local m = { format = "udmf", namespace = doc.namespace, globals = doc.globals, things = {}, linedefs = {}, sidedefs = {}, vertices = {}, sectors = {}, blocks = {} } for _, b in doc.blocks do local f = b.fields if b.type == "vertex" then local x, y = f.x, f.y if type(x) ~= "number" or type(y) ~= "number" then return nil, "vertex " .. (#m.vertices // 2) .. " has no x / y" end table.insert(m.vertices, x) table.insert(m.vertices, y) elseif b.type == "linedef" then local flags = 0 for k, bit in LINE_FLAGS do if flag(f, k) then flags += bit end end if hexenBits then if flag(f, "repeatspecial") then flags += 512 end for k, a in SPAC do if flag(f, k) then flags = bit32.bor(bit32.band(flags, bit32.bnot(0x1C00)), a * 1024) end end end local v1, v2 = index(f, "v1"), index(f, "v2") if not v1 or not v2 then return nil, "linedef " .. #m.linedefs .. " has no v1 / v2" end local a = args(f) table.insert(m.linedefs, { v1 = v1, v2 = v2, flags = flags, special = num(f, "special", 0), tag = if hexenBits then num(f, "id", -1) else a[1], args = a, front = index(f, "sidefront"), back = index(f, "sideback"), fields = f, }) elseif b.type == "sidedef" then local s = index(f, "sector") if not s then return nil, "sidedef " .. #m.sidedefs .. " has no sector" end table.insert(m.sidedefs, { xoff = num(f, "offsetx", 0), yoff = num(f, "offsety", 0), upper = tex(f, "texturetop", "-"), lower = tex(f, "texturebottom", "-"), middle = tex(f, "texturemiddle", "-"), sector = s, fields = f, }) elseif b.type == "sector" then table.insert(m.sectors, { floor = num(f, "heightfloor", 0), ceiling = num(f, "heightceiling", 0), floorFlat = tex(f, "texturefloor", "-"), ceilingFlat = tex(f, "textureceiling", "-"), light = num(f, "lightlevel", 160), special = num(f, "special", 0), tag = num(f, "id", 0), fields = f, }) elseif b.type == "thing" then local x, y = f.x, f.y if type(x) ~= "number" or type(y) ~= "number" then return nil, "thing " .. #m.things .. " has no x / y" end local fl = 0 if flag(f, "skill1") or flag(f, "skill2") then fl += 1 end if flag(f, "skill3") then fl += 2 end if flag(f, "skill4") or flag(f, "skill5") then fl += 4 end if flag(f, "ambush") then fl += 8 end if hexenBits then fl += (if flag(f, "dormant") then 16 else 0) + (if flag(f, "class1") then 32 else 0) + (if flag(f, "class2") then 64 else 0) + (if flag(f, "class3") then 128 else 0) + (if flag(f, "single") then 256 else 0) + (if flag(f, "coop") then 512 else 0) + (if flag(f, "dm") then 1024 else 0) else -- Doom / Boom / MBF: 16 not in single player, 32 not in deathmatch, 64 not in coop, 128 friend fl += (if flag(f, "single") then 0 else 16) + (if flag(f, "dm") then 0 else 32) + (if flag(f, "coop") then 0 else 64) + (if flag(f, "friend") then 128 else 0) end table.insert(m.things, { x = x, y = y, z = num(f, "height", 0), angle = num(f, "angle", 0), type = num(f, "type", 0), flags = fl, tid = num(f, "id", 0), special = num(f, "special", 0), args = args(f), fields = f, }) else table.insert(m.blocks, b) end end return m, nil end return Udmf end __FILES["codecs/model/Draco"] = function() -- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). -- Port of Draco 1.5.7's decoder (Apache-2.0, licenses/draco-LICENSE.txt): bitstreams 1.0 - 2.2 meshes, 2.3 kd-tree -- point clouds; values match draco_decoder bit for bit (f32 rounding at every dequantization step). local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Reader = __include("codecs/model/Draco/Reader") local Connectivity = __include("codecs/model/Draco/Connectivity") local Attributes = __include("codecs/model/Draco/Attributes") local Draco = {} local NAMES = { [0] = "POSITION", "NORMAL", "COLOR", "TEX_COORD", "GENERIC", "TANGENT", "MATERIAL", "JOINTS", "WEIGHTS" } local TYPES = { "i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "f32", "f64", "bool" } Draco.ATTRIBUTE_NAMES = NAMES Draco.DATA_TYPES = TYPES type Attribute = { name: string, typeId: number, uniqueId: number, components: number, type: string, normalized: boolean, data: buffer, } type Metadata = { entries: { [string]: buffer }, children: { [string]: Metadata }, attributes: { [number]: Metadata }? } type Geometry = { kind: "mesh" | "points", version: string, method: string, numPoints: number, numFaces: number, indices: buffer?, attributes: { Attribute }, metadata: Metadata?, } type Header = { major: number, minor: number, kind: "mesh" | "points", method: number, flags: number } function Draco.sniff(buf: buffer, off: number?): boolean local o = off or 0 return buffer.len(buf) >= o + 5 and buffer.readstring(buf, o, 5) == "DRACO" end local function header(d: Reader.D): (Header?, string?) if Reader.remaining(d) < 11 then return nil, "truncated header" end if buffer.readstring(d.b, d.pos, 5) ~= "DRACO" then return nil, "not Draco data" end d.pos += 5 local major, minor, kind, method = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d) local flags = Reader.u16(d) if kind > 1 then return nil, "unsupported: geometry type " .. kind end return { major = major, minor = minor, kind = if kind == 0 then "points" else "mesh", method = method, flags = flags }, nil end function Draco.info(src: buffer | string, off: number?, len: number?): (Header?, Err.Err?) local buf, o, l, aerr = Bytes.span("draco", src, off, len) if not buf then return nil, aerr end local d = Reader.new(buf, o, o + l, 0) local h, err = header(d) if not h then return nil, Err.from(err, 0) end return h, nil end local function metadataElement(d: Reader.D, depth: number): Metadata? if depth > 1000 then return nil end local m: Metadata = { entries = {}, children = {} } local n = Reader.varint(d) if d.bad or n > Reader.remaining(d) then return nil end for _ = 1, n do local nameLen = Reader.u8(d) if d.bad or Reader.remaining(d) < nameLen then return nil end local name = buffer.readstring(d.b, d.pos, nameLen) d.pos += nameLen local size = Reader.varint(d) if d.bad or size == 0 or size > Reader.remaining(d) then return nil end local v = buffer.create(size) buffer.copy(v, 0, d.b, d.pos, size) d.pos += size m.entries[name] = v end local subs = Reader.varint(d) if d.bad or subs > Reader.remaining(d) then return nil end for _ = 1, subs do local nameLen = Reader.u8(d) if d.bad or Reader.remaining(d) < nameLen then return nil end local name = buffer.readstring(d.b, d.pos, nameLen) d.pos += nameLen local child = metadataElement(d, depth + 1) if not child then return nil end m.children[name] = child end return m end local function metadata(d: Reader.D): Metadata? local n = Reader.varint(d) if d.bad or n > Reader.remaining(d) then return nil end local atts: { [number]: Metadata } = {} for _ = 1, n do local id = Reader.varint(d) local m = metadataElement(d, 0) if not m then return nil end atts[id] = m end local m = metadataElement(d, 0) if not m then return nil end m.attributes = atts return m end local WRITE: { [number]: (buffer, number, number) -> () } = { [1] = buffer.writei8, [2] = buffer.writeu8, [3] = buffer.writei16, [4] = buffer.writeu16, [5] = buffer.writei32, [6] = buffer.writeu32, [9] = buffer.writef32, [11] = buffer.writeu8, } local function expand(a: Attributes.Attr, numPoints: number): (buffer?, string?) local size = Attributes.DT_LENGTH[a.dataType] local comps = a.comps local stride = size * comps local out = buffer.create(numPoints * stride) local map = a.map local n = a.numValues if a.raw then local raw = a.raw :: buffer for p = 0, numPoints - 1 do local e = if map then map[p + 1] else p if e >= n then return nil, "attribute value out of range" end buffer.copy(out, p * stride, raw, e * stride, stride) end return out, nil end local vals = a.values :: { number } local w = WRITE[a.dataType] if not w then return nil, "unsupported: data type " .. a.dataType end for p = 0, numPoints - 1 do local e = if map then map[p + 1] else p if e >= n then return nil, "attribute value out of range" end local o = p * stride local k = e * comps for c = 1, comps do w(out, o, vals[k + c]) o += size end end return out, nil end local function decode(buf: buffer, o: number, l: number, opts: any): (Geometry?, string?, string?) local d = Reader.new(buf, o, o + l, 0) local h, herr = header(d) if not h then return nil, herr, nil end local ver = h.major * 256 + h.minor local maxVer = if h.kind == "points" then 0x0203 else 0x0202 if h.major < 1 or ver > maxVer then return nil, string.format("unsupported: bitstream version %d.%d", h.major, h.minor), nil end d.ver = ver local maxPoints = (opts and opts.maxPoints) or 2 ^ 24 local maxFaces = (opts and opts.maxFaces) or 2 ^ 24 local meta: Metadata? = nil if ver >= 0x0103 and bit32.band(h.flags, 0x8000) ~= 0 then meta = metadata(d) if not meta then return nil, d.bad or "bad metadata", nil end end local mesh: Connectivity.Mesh? = nil local numPoints = 0 local method if h.kind == "mesh" then if h.method == 0 then method = "sequential" local m, err = Connectivity.sequential(d) if not m then return nil, err, nil end mesh = m elseif h.method == 1 then method = "edgebreaker" local kind = Reader.u8(d) if d.bad then return nil, d.bad, nil end if kind > 2 then return nil, "unknown edgebreaker traversal " .. kind, nil end local m, err = Connectivity.edgebreaker(d, kind) if not m then return nil, err, nil end mesh = m else return nil, "unsupported: mesh encoding method " .. h.method, nil end local m = mesh :: Connectivity.Mesh if m.numFaces > maxFaces then return nil, "too many faces", "limit" end numPoints = m.numPoints else if h.method > 1 then return nil, "unsupported: point cloud encoding method " .. h.method, nil end method = if h.method == 1 then "kdtree" else "sequential" numPoints = Reader.i32(d) if d.bad then return nil, d.bad, nil end if numPoints < 0 then return nil, "bad point count", nil end end if numPoints > maxPoints then return nil, "too many points", "limit" end local attrs, aerr = Attributes.decode(d, { numPoints = numPoints, mesh = mesh, edgebreaker = method == "edgebreaker", kdTree = method == "kdtree" }) if not attrs then return nil, aerr, nil end local g: Geometry = { kind = h.kind, version = h.major .. "." .. h.minor, method = method, numPoints = numPoints, numFaces = 0, indices = nil, attributes = {}, metadata = meta, } if mesh then local nf = mesh.numFaces local idx = buffer.create(nf * 12) local faces = mesh.faces for i = 1, nf * 3 do local v = faces[i] if v < 0 or v >= numPoints then return nil, "face index out of range", nil end buffer.writeu32(idx, (i - 1) * 4, v) end g.numFaces = nf g.indices = idx end for _, a in attrs do local data, err = expand(a, numPoints) if not data then return nil, err, nil end table.insert(g.attributes, { name = NAMES[a.type] or "GENERIC", typeId = a.type, uniqueId = a.uniqueId, components = a.comps, type = TYPES[a.dataType], normalized = a.normalized, data = data, }) end return g, nil, nil end function Draco.decode(src: buffer | string, off: number?, len: number?, opts: any?): (Geometry?, Err.Err?) local buf, o, l, aerr = Bytes.span("draco", src, off, len) if not buf then return nil, aerr end local ok, g, msg, kind = pcall(decode, buf, o, l, opts) if not ok then return nil, Err.new(Err.CORRUPT, "draco: internal error: " .. tostring(g)) end if not g then return nil, Err.from("draco: " .. tostring(msg), nil, kind or (if string.find(tostring(msg), "^unsupported") then "unsupported" elseif string.find(tostring(msg), "truncated") then "truncated" else nil)) end return g, nil end function Draco.attribute(g: Geometry, uniqueId: number): Attribute? for _, a in g.attributes do if a.uniqueId == uniqueId then return a end end return nil end return Draco end __FILES["codecs/model/Draco/Attributes"] = function() -- codecs/model/Draco/Attributes: Draco attribute decoders and sequential attribute decoding (bitstreams 1.0 - 2.2). -- Port of Draco 1.5.7 compression/attributes/*, point_cloud_decoder.cc, attribute_quantization_transform.cc and -- attribute_octahedron_transform.cc (Apache-2.0, licenses/draco-LICENSE.txt). local Reader = __include("codecs/model/Draco/Reader") local Connectivity = __include("codecs/model/Draco/Connectivity") local Predict = __include("codecs/model/Draco/Predict") local KdTree = __include("codecs/model/Draco/KdTree") local Attributes = {} type D = Reader.D -- data type ids (draco::DataType) -> byte length local DT_LENGTH = { [1] = 1, [2] = 1, [3] = 2, [4] = 2, [5] = 4, [6] = 4, [7] = 8, [8] = 8, [9] = 4, [10] = 8, [11] = 1 } Attributes.DT_LENGTH = DT_LENGTH type Attr = { id: number, type: number, -- GeometryAttribute::Type (0 POSITION, 1 NORMAL, 2 COLOR, 3 TEX_COORD, 4 GENERIC, 5.. transcoder types) dataType: number, comps: number, normalized: boolean, uniqueId: number, seqType: number, -- 0 generic, 1 integer, 2 quantization, 3 normals map: { number }?, numValues: number, portable: { number }?, values: { number }?, raw: buffer?, quant: { min: { number }, range: number, bits: number }?, octBits: number?, scheme: Predict.Scheme?, } type Decoder = { attrs: { Attr }, traversal: { ct: Connectivity.CT, enc: Connectivity.Enc, method: number }?, md: Predict.MeshData?, points: { number }?, } type Geom = { numPoints: number, mesh: Connectivity.Mesh?, edgebreaker: boolean, kdTree: boolean } local function zigzag(v: number): number if v % 2 == 1 then return -(v // 2) - 1 end return v // 2 end -- parent getter: portable integers from 2.0 on, the final values before (truncated unless the scheme uses floats) local function parentGetter(ver: number, pos: Attr, floats: boolean): Predict.Parent? local old = ver < 0x0200 local vals = if old then pos.values else pos.portable if not vals or pos.comps ~= 3 or (not old and pos.seqType == 3) then return nil end local map = pos.map local trunc = old and not floats return function(point: number): (number, number, number) local e = if map then (map[point + 1] or 0) else point local o = e * 3 local x, y, z = vals[o + 1] or 0, vals[o + 2] or 0, vals[o + 3] or 0 if trunc then x = if x < 0 then math.ceil(x) else math.floor(x) y = if y < 0 then math.ceil(y) else math.floor(y) z = if z < 0 then math.ceil(z) else math.floor(z) end return x, y, z end end local function decodeIntegerValues(d: D, a: Attr, points: { number }, scheme: Predict.Scheme?): (boolean, string?) local comps = if a.seqType == 3 then 2 else a.comps local n = #points local numValues = n * comps if n == 0 then return false, "no values" end local compressed = Reader.u8(d) if d.bad then return false, d.bad end local vals: { number } if compressed > 0 then local s = Reader.symbols(d, numValues, comps) if not s then return false, d.bad or "bad values" end vals = s else local nb = Reader.u8(d) if d.bad then return false, d.bad end if nb < 1 or nb > 4 then return false, "bad value byte count" end if Reader.remaining(d) < nb * numValues then return false, "truncated values" end vals = table.create(numValues, 0) local b, p = d.b, d.pos if nb == 4 then for i = 1, numValues do vals[i] = buffer.readu32(b, p) p += 4 end elseif nb == 1 then for i = 1, numValues do vals[i] = buffer.readu8(b, p) p += 1 end elseif nb == 2 then for i = 1, numValues do vals[i] = buffer.readu16(b, p) p += 2 end else for i = 1, numValues do vals[i] = buffer.readu16(b, p) + buffer.readu8(b, p + 2) * 65536 p += 3 end end d.pos = p end if not scheme or not scheme.tr.positive then for i = 1, numValues do vals[i] = zigzag(vals[i]) end else local i32 = Predict.i32 for i = 1, numValues do vals[i] = i32(vals[i]) end end if scheme then if not Predict.decodeData(scheme, d) then return false, d.bad or "bad prediction data" end local ok, err = Predict.compute(scheme, vals, n, comps, points) if not ok then return false, err end end a.portable = vals a.numValues = n return true, nil end local function decodeQuantInfo(d: D, a: Attr): boolean local mins = table.create(a.comps, 0) for c = 1, a.comps do mins[c] = Reader.f32(d) end local range = Reader.f32(d) local bits = Reader.u8(d) if d.bad or bits < 1 or bits > 30 then return false end a.quant = { min = mins, range = range, bits = bits } return true end -- StoreValues: integer -> the data type; quantized -> f32; octahedral -> unit vectors local function storeValues(a: Attr): (boolean, string?) local src = a.portable :: { number } local n = a.numValues local fround = Predict.fround if a.seqType == 1 then local dt = a.dataType local out = table.create(n * a.comps, 0) for i = 1, n * a.comps do local v = src[i] if dt == 1 then v = (v + 128) % 256 - 128 elseif dt == 2 or dt == 11 then v %= 256 elseif dt == 3 then v = (v + 32768) % 65536 - 32768 elseif dt == 4 then v %= 65536 elseif dt == 6 then v %= 4294967296 elseif dt ~= 5 then return false, "unsupported: integer attribute of data type " .. dt end out[i] = v end a.values = out elseif a.seqType == 2 then local q = a.quant if not q then return false, "no quantization data" end local maxQ = 2 ^ q.bits - 1 local delta = fround(q.range / fround(maxQ)) local comps = a.comps local mins = q.min local out = table.create(n * comps, 0) local k = 1 for _ = 1, n do for c = 1, comps do out[k] = fround(fround(fround(src[k]) * delta) + mins[c]) k += 1 end end a.values = out elseif a.seqType == 3 then local o = Predict.octahedron(a.octBits or 0) if not o then return false, "bad normal quantization" end local out = table.create(n * 3, 0) for i = 0, n - 1 do local x, y, z = Predict.octToVector(o, src[i * 2 + 1], src[i * 2 + 2]) out[i * 3 + 1], out[i * 3 + 2], out[i * 3 + 3] = x, y, z end a.values = out end return true, nil end function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) local ver = d.ver local numDecoders = Reader.u8(d) if d.bad then return nil, d.bad end local mesh = g.mesh local decoders: { Decoder } = {} for i = 0, numDecoders - 1 do local dec: Decoder = { attrs = {}, traversal = nil, md = nil, points = nil } if g.edgebreaker and mesh then local attDataId = Reader.i8(d) local decoderType = Reader.u8(d) if d.bad then return nil, d.bad end local ad = nil if attDataId >= 0 then ad = mesh.attrData[attDataId + 1] if not ad or ad.decoderId >= 0 then return nil, "bad attribute data id" end ad.decoderId = i else if mesh.posDecoderId >= 0 then return nil, "two position decoders" end mesh.posDecoderId = i end local method = 0 if ver >= 0x0102 then method = Reader.u8(d) if d.bad or method >= 2 then return nil, "bad traversal method" end end local ct = mesh.ct :: Connectivity.CT local enc if decoderType == 0 then if ad then enc = ad.enc ad.used = false else enc = mesh.posEnc :: Connectivity.Enc end dec.traversal = { ct = ct, enc = enc, method = method } else if method ~= 0 or not ad then return nil, "bad corner attribute decoder" end local cad = ad :: Connectivity.AttrData enc = cad.enc dec.traversal = { ct = cad.ct :: Connectivity.CT, enc = enc, method = 0 } end local pct = if ad and ad.used then ad.ct :: Connectivity.CT else ct dec.md = { ct = pct, e2c = enc.e2c, v2e = enc.v2e } end decoders[i + 1] = dec end local all: { Attr } = {} for _, dec in decoders do local n = Reader.count(d, 0x0200) if d.bad then return nil, d.bad end if n == 0 or n > 5 * Reader.remaining(d) then return nil, "bad attribute count" end for _ = 1, n do local attType, dataType, comps, normalized = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d) if d.bad then return nil, d.bad end if attType >= 9 or dataType == 0 or dataType >= 12 or comps == 0 then return nil, "bad attribute descriptor" end local uniqueId = if ver < 0x0103 then Reader.u16(d) else Reader.varint(d) local a: Attr = { id = #all, type = attType, dataType = dataType, comps = comps, normalized = normalized > 0, uniqueId = uniqueId, seqType = 0, map = nil, numValues = 0, } table.insert(all, a) table.insert(dec.attrs, a) end for _, a in (if g.kdTree then {} else dec.attrs) do local t = Reader.u8(d) if d.bad then return nil, d.bad end if t > 3 then return nil, "unknown attribute decoder " .. t end if (t == 2 or t == 3) and a.dataType ~= 9 then return nil, "quantized attribute is not f32" end if t == 3 and a.comps ~= 3 then return nil, "normal attribute without 3 components" end a.seqType = t end end if d.bad then return nil, d.bad end local function named(t: number): Attr? for _, a in all do if a.type == t then return a end end return nil end for _, dec in decoders do if g.kdTree then local ok, err = KdTree.decode(d, dec.attrs, g.numPoints) if not ok then return nil, err end continue end local points: { number } local trav = dec.traversal if trav then local faces = (mesh :: Connectivity.Mesh).faces local p = Connectivity.traverse(trav.ct, faces, trav.enc, trav.method) if not p then return nil, "bad attribute traversal" end points = p local numPoints = (mesh :: Connectivity.Mesh).numPoints for _, a in dec.attrs do local m = Connectivity.mapping(trav.ct, faces, trav.enc, numPoints) if not m then return nil, "bad attribute mapping" end a.map = m end else points = table.create(g.numPoints, 0) for i = 1, g.numPoints do points[i] = i - 1 end end dec.points = points for _, a in dec.attrs do if a.seqType == 0 then local stride = DT_LENGTH[a.dataType] * a.comps local size = #points * stride if Reader.remaining(d) < size then return nil, "truncated attribute values" end local raw = buffer.create(size) buffer.copy(raw, 0, d.b, d.pos, size) d.pos += size a.raw = raw a.numValues = #points continue end local psm = Reader.i8(d) if d.bad then return nil, d.bad end if psm < -2 or psm >= 7 then return nil, "bad prediction scheme" end local scheme: Predict.Scheme? = nil if psm ~= -2 then local ptt = Reader.i8(d) if d.bad then return nil, d.bad end if ptt < -1 or ptt >= 4 then return nil, "bad prediction transform" end if a.seqType == 3 then if ptt == 2 or ptt == 3 then scheme = Predict.new(psm, Predict.transform(ptt), dec.md) end elseif ptt == 1 then scheme = Predict.new(psm, Predict.transform(1), dec.md) end end if scheme and Predict.needsParent(scheme) then local pos = named(0) local getter = pos and parentGetter(ver, pos, scheme.method == 3) if not getter then return nil, "prediction needs the decoded positions" end scheme.parent = getter end if ver < 0x0200 then if a.seqType == 2 and not decodeQuantInfo(d, a) then return nil, d.bad or "bad quantization data" elseif a.seqType == 3 then a.octBits = Reader.u8(d) end end local ok, err = decodeIntegerValues(d, a, points, scheme) if not ok then return nil, err end a.scheme = scheme if ver < 0x0200 then local ok2, err2 = storeValues(a) if not ok2 then return nil, err2 end end end if ver >= 0x0200 then for _, a in dec.attrs do if a.seqType == 2 then if not decodeQuantInfo(d, a) then return nil, d.bad or "bad quantization data" end elseif a.seqType == 3 then a.octBits = Reader.u8(d) end end if d.bad then return nil, d.bad end for _, a in dec.attrs do if a.seqType ~= 0 then local ok, err = storeValues(a) if not ok then return nil, err end end end end end return all, nil end return Attributes end __FILES["codecs/model/Draco/Connectivity"] = function() -- codecs/model/Draco/Connectivity: Draco mesh connectivity (sequential and Edgebreaker) and traversal sequencers. -- Port of Draco 1.5.7 mesh_sequential_decoder.cc, mesh_edgebreaker_decoder_impl.cc, mesh_edgebreaker_traversal_*, -- corner_table, mesh_attribute_corner_table, traverser/* (Apache-2.0, licenses/draco-LICENSE.txt). local Reader = __include("codecs/model/Draco/Reader") local Connectivity = {} type D = Reader.D type CT = { c2v: { number }, opp: { number }, lmc: { number }, nv: number, nf: number } type Enc = { v2e: { number }, e2c: { number }, numValues: number } type AttrData = { decoderId: number, used: boolean, seams: { number }, ct: CT?, enc: Enc } type Mesh = { faces: { number }, numFaces: number, numPoints: number, ct: CT?, attrData: { AttrData }, posEnc: Enc?, posDecoderId: number, } local TOPOLOGY_C, TOPOLOGY_S, TOPOLOGY_L, TOPOLOGY_R, TOPOLOGY_E = 0, 1, 3, 5, 7 local SYMBOL_TO_TOPOLOGY = { [0] = TOPOLOGY_C, TOPOLOGY_S, TOPOLOGY_L, TOPOLOGY_R, TOPOLOGY_E } local function nextC(c: number): number if c < 0 then return -1 end return if c % 3 == 2 then c - 2 else c + 1 end local function prevC(c: number): number if c < 0 then return -1 end return if c % 3 == 0 then c + 2 else c - 1 end Connectivity.next = nextC Connectivity.prev = prevC local function newEnc(nv: number): Enc return { v2e = table.create(nv, 0), e2c = {}, numValues = 0 } end function Connectivity.sequential(d: D): (Mesh?, string?) local numFaces, numPoints if d.ver < 0x0202 then numFaces, numPoints = Reader.u32(d), Reader.u32(d) else numFaces, numPoints = Reader.varint(d), Reader.varint(d) end if d.bad then return nil, d.bad end if numFaces > 0xffffffff // 3 or numFaces > Reader.remaining(d) // 3 then return nil, "too many faces" end local method = Reader.u8(d) local n = numFaces * 3 local faces = table.create(n, 0) if method == 0 then local sym = Reader.symbols(d, n, 1) if not sym then return nil, d.bad or "bad indices" end local last = 0 for i = 1, n do local e = sym[i] local diff = e // 2 if e % 2 == 1 then if diff > last then return nil, "bad index delta" end diff = -diff elseif diff > 0x7fffffff - last then return nil, "bad index delta" end last += diff faces[i] = last end else local b = d.b if numPoints < 256 then if d.pos + n > d.limit then return nil, "truncated indices" end for i = 1, n do faces[i] = buffer.readu8(b, d.pos + i - 1) end d.pos += n elseif numPoints < 65536 then if d.pos + n * 2 > d.limit then return nil, "truncated indices" end for i = 1, n do faces[i] = buffer.readu16(b, d.pos + (i - 1) * 2) end d.pos += n * 2 elseif numPoints < 2 ^ 21 and d.ver >= 0x0202 then for i = 1, n do faces[i] = Reader.varint(d) end else if d.pos + n * 4 > d.limit then return nil, "truncated indices" end for i = 1, n do faces[i] = buffer.readu32(b, d.pos + (i - 1) * 4) end d.pos += n * 4 end end if d.bad then return nil, d.bad end return { faces = faces, numFaces = numFaces, numPoints = numPoints, ct = nil, attrData = {}, posEnc = nil, posDecoderId = -1 }, nil end type Trav = { decodeSymbol: () -> number, newActiveCorner: (corner: number) -> (), mergeVertices: (dest: number, src: number) -> (), startFace: () -> boolean, seam: (i: number) -> boolean, } -- MeshEdgebreakerTraversalDecoder::Start local function standardStart(buf: D, numAttributeData: number, withSymbols: boolean): (any?, D) local st: any = {} if withSymbols then local sym = Reader.copy(buf) local size = Reader.startBits(sym, true) if sym.bad then buf.bad = sym.bad return nil, buf end buf = Reader.copy(sym) buf.bitMode = false if size > Reader.remaining(buf) then Reader.fail(buf, "traversal symbols past the end") return nil, buf end buf.pos += size st.sym = sym end if buf.ver < 0x0202 then local sf = Reader.copy(buf) local size = Reader.startBits(sf, true) if sf.bad then buf.bad = sf.bad return nil, buf end buf = Reader.copy(sf) buf.bitMode = false if size > Reader.remaining(buf) then Reader.fail(buf, "start faces past the end") return nil, buf end buf.pos += size st.startBuf = sf else local bd = Reader.bitDecoder(buf) if not bd then return nil, buf end st.startDec = bd end st.seams = {} for i = 1, numAttributeData do local bd = Reader.bitDecoder(buf) if not bd then return nil, buf end st.seams[i] = bd end return st, buf end local function standardSymbol(sym: D): number local s = Reader.bits(sym, 1) if s == TOPOLOGY_C then return s end return s + Reader.bits(sym, 2) * 2 end -- traversal decoder kind: 0 standard, 1 predictive, 2 valence local function makeTraversal(kind: number, buf: D, numAttributeData: number, numVertices: number, numFaces: number, ct: CT): (Trav?, D) local ver = buf.ver local st, out = standardStart(buf, numAttributeData, kind ~= 2 or ver < 0x0202) if not st then return nil, out end local function startFace(): boolean if st.startBuf then return Reader.bits(st.startBuf, 1) == 1 end return Reader.bit(st.startDec) end local function seam(i: number): boolean return Reader.bit(st.seams[i + 1]) end local valences = table.create(numVertices, 0) local c2v = ct.c2v local function vtx(c: number): number return if c < 0 then -1 else (c2v[c + 1] or -1) end local function addValence(v: number, k: number) if v >= 0 and v < numVertices then valences[v + 1] += k end end local function mergeVertices(dest: number, src: number) if dest >= 0 and dest < numVertices and src >= 0 and src < numVertices then valences[dest + 1] += valences[src + 1] end end local lastSymbol = -1 local function updateValences(corner: number) local nx, pv = nextC(corner), prevC(corner) if lastSymbol == TOPOLOGY_C or lastSymbol == TOPOLOGY_S then addValence(vtx(nx), 1) addValence(vtx(pv), 1) elseif lastSymbol == TOPOLOGY_R then addValence(vtx(corner), 1) addValence(vtx(nx), 1) addValence(vtx(pv), 2) elseif lastSymbol == TOPOLOGY_L then addValence(vtx(corner), 1) addValence(vtx(nx), 2) addValence(vtx(pv), 1) elseif lastSymbol == TOPOLOGY_E then addValence(vtx(corner), 2) addValence(vtx(nx), 2) addValence(vtx(pv), 2) end end if kind == 0 then local sym = st.sym return { decodeSymbol = function(): number return standardSymbol(sym) end, newActiveCorner = function(_c: number) end, mergeVertices = function(_a: number, _b: number) end, startFace = startFace, seam = seam, }, out elseif kind == 1 then -- predictive (deprecated): a bit says whether the predicted symbol (from the pivot's valence) is right local n = Reader.i32(out) if out.bad or n < 0 or n >= numVertices then Reader.fail(out, "bad split symbol count") return nil, out end local pred = Reader.bitDecoder(out) if not pred then return nil, out end local sym = st.sym local predicted = -1 return { decodeSymbol = function(): number if predicted ~= -1 and Reader.bit(pred) then lastSymbol = predicted return predicted end lastSymbol = standardSymbol(sym) return lastSymbol end, newActiveCorner = function(corner: number) updateValences(corner) if lastSymbol == TOPOLOGY_C or lastSymbol == TOPOLOGY_R then local pivot = vtx(nextC(corner)) local val = if pivot >= 0 and pivot < numVertices then valences[pivot + 1] else 0 predicted = if val < 6 then TOPOLOGY_R else TOPOLOGY_C else predicted = -1 end end, mergeVertices = mergeVertices, startFace = startFace, seam = seam, }, out end -- valence: per-context symbol streams chosen by the valence of the next vertex local minValence, maxValence = 2, 7 if ver < 0x0202 then local nSplit = Reader.count(out, 0x0200) if out.bad or nSplit >= numVertices then Reader.fail(out, "bad split symbol count") return nil, out end local mode = Reader.i8(out) if out.bad or mode ~= 0 then Reader.fail(out, "unsupported valence mode") return nil, out end end local contexts: { { number } } = {} local counters: { number } = {} for i = 1, maxValence - minValence + 1 do local n = Reader.varint(out) if out.bad then return nil, out end if n > numFaces then Reader.fail(out, "too many context symbols") return nil, out end counters[i] = n contexts[i] = {} if n > 0 then -- C++ ignores a failure here (the symbols stay zero) local save = out.bad local syms = Reader.symbols(out, n, 1) if syms then contexts[i] = syms else out.bad = save end end end local active = -1 local sym = st.sym return { decodeSymbol = function(): number if active ~= -1 then local k = counters[active + 1] - 1 counters[active + 1] = k if k < 0 then return -1 end local id = contexts[active + 1][k + 1] or 0 if id > 4 then return -1 end lastSymbol = SYMBOL_TO_TOPOLOGY[id] elseif ver < 0x0202 then lastSymbol = standardSymbol(sym) else lastSymbol = TOPOLOGY_E end return lastSymbol end, newActiveCorner = function(corner: number) updateValences(corner) local v = vtx(nextC(corner)) local val = if v >= 0 and v < numVertices then valences[v + 1] else 0 if val < minValence then val = minValence elseif val > maxValence then val = maxValence end active = val - minValence end, mergeVertices = mergeVertices, startFace = startFace, seam = seam, }, out end local function splitEvents(eb: D, numFaces: number): { any }? local ver = eb.ver local n = Reader.count(eb, 0x0200) if eb.bad then return nil end local splits = {} if n > 0 then if n > numFaces then Reader.fail(eb, "too many topology splits") return nil end if ver < 0x0102 then for i = 1, n do local split = Reader.u32(eb) local source = Reader.u32(eb) local edge = Reader.u8(eb) % 2 splits[i] = { source = source, split = split, edge = edge } end else local last = 0 for i = 1, n do local source = Reader.varint(eb) + last local delta = Reader.varint(eb) if eb.bad then return nil end if delta > source then Reader.fail(eb, "bad topology split") return nil end splits[i] = { source = source, split = source - delta, edge = 0 } last = source end Reader.startBits(eb, false) for i = 1, n do local e = Reader.bits(eb, if ver < 0x0202 then 2 else 1) splits[i].edge = e % 2 end Reader.endBits(eb) end end -- hole events (before 2.1): read and ignored local holes = 0 if ver < 0x0200 then holes = Reader.u32(eb) elseif ver < 0x0201 then holes = Reader.varint(eb) end if eb.bad then return nil end if holes > Reader.remaining(eb) then Reader.fail(eb, "too many hole events") return nil end for _ = 1, holes do if ver < 0x0102 then Reader.i32(eb) else Reader.varint(eb) end end if eb.bad then return nil end return splits end -- MeshAttributeCornerTable from the seam corners (InitEmpty, AddSeamEdge, RecomputeVertices) local function attributeTable(ct: CT, seams: { number }): CT? local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc local nc = ct.nf * 3 local function V(c: number): number return if c < 0 then -1 else (c2v[c + 1] or -1) end local edgeSeam: { [number]: boolean } = {} local vertSeam: { [number]: boolean } = {} for _, c in seams do edgeSeam[c] = true vertSeam[V(nextC(c))] = true vertSeam[V(prevC(c))] = true local o = if c < 0 then -1 else (opp[c + 1] or -1) if o ~= -1 then edgeSeam[o] = true vertSeam[V(nextC(o))] = true vertSeam[V(prevC(o))] = true end end local aopp = table.create(nc, -1) for c = 0, nc - 1 do aopp[c + 1] = if edgeSeam[c] then -1 else (opp[c + 1] or -1) end local ac2v = table.create(nc, -1) local almc: { number } = {} local num = 0 local function swingLeftA(c: number): number local n = nextC(c) local o = if n < 0 then -1 else aopp[n + 1] return nextC(o) end local function swingRight(c: number): number local p = prevC(c) local o = if p < 0 then -1 else (opp[p + 1] or -1) return prevC(o) end for v = 0, ct.nv - 1 do local c = lmc[v + 1] or -1 if c ~= -1 then local id = num num += 1 local first = c if vertSeam[v] then local act = swingLeftA(first) while act ~= -1 do first = act act = swingLeftA(act) if act == c then return nil end end end ac2v[first + 1] = id table.insert(almc, first) local act = swingRight(first) local guard = 0 while act ~= -1 and act ~= first do if edgeSeam[nextC(act)] then id = num num += 1 table.insert(almc, act) end ac2v[act + 1] = id act = swingRight(act) guard += 1 if guard > nc then return nil end end end end return { c2v = ac2v, opp = aopp, lmc = almc, nv = num, nf = ct.nf, vertSeam = vertSeam } :: any end -- MeshEdgebreakerDecoderImpl::DecodeConnectivity (+ the traversal start, seams, AssignPointsToCorners) function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?) local ver = d.ver if ver < 0x0202 then Reader.count(d, 0x0200) -- num_new_vertices (unused) end local numEncodedVertices = Reader.count(d, 0x0200) local numFaces = Reader.count(d, 0x0200) if d.bad then return nil, d.bad end if numFaces > 0xffffffff // 3 then return nil, "too many faces" end if numEncodedVertices > numFaces * 3 then return nil, "more vertices than corners" end local minEdges = (3 * numFaces) // 2 local maxEdges = numEncodedVertices * (numEncodedVertices - 1) / 2 if numEncodedVertices == 0 then maxEdges = 0 end if maxEdges < minEdges then return nil, "too few vertices for the faces" end local numAttributeData = Reader.u8(d) local numSymbols = Reader.count(d, 0x0200) if d.bad then return nil, d.bad end if numFaces < numSymbols or numFaces > numSymbols + numSymbols // 3 then return nil, "bad symbol count" end local numSplitSymbols = Reader.count(d, 0x0200) if d.bad then return nil, d.bad end if numSplitSymbols > numSymbols then return nil, "bad split symbol count" end local maxVertices = numEncodedVertices + numSplitSymbols local c2v: { number } = {} local opp: { number } = {} local lmc: { number } = {} local nv = 0 local ct: CT = { c2v = c2v, opp = opp, lmc = lmc, nv = 0, nf = numFaces } local notHole: { [number]: boolean } = {} local splits: { any }? local splitBytes = 0 if ver < 0x0202 then local size = Reader.count(d, 0x0200) if d.bad then return nil, d.bad end if size == 0 or size > Reader.remaining(d) then return nil, "bad connectivity size" end local eb = Reader.new(d.b, d.pos + size, d.limit, ver) splits = splitEvents(eb, numFaces) if not splits then return nil, eb.bad or "bad split events" end splitBytes = eb.pos - (d.pos + size) else splits = splitEvents(d, numFaces) if not splits then return nil, d.bad or "bad split events" end end local splitData = splits :: { any } local trav, after = makeTraversal(traversalKind, Reader.copy(d), numAttributeData, maxVertices, numFaces, ct) if not trav then return nil, after.bad or "bad traversal data" end local function V(c: number): number return if c < 0 then -1 else (c2v[c + 1] or -1) end local function O(c: number): number return if c < 0 then -1 else (opp[c + 1] or -1) end local function setOpp(a: number, b: number) if a >= 0 then opp[a + 1] = b end if b >= 0 then opp[b + 1] = a end end local function setLmc(v: number, c: number) if v >= 0 then lmc[v + 1] = c end end local function LMC(v: number): number return if v < 0 then -1 else (lmc[v + 1] or -1) end local function addVertex(): number nv += 1 lmc[nv] = -1 return nv - 1 end local function swingLeft(c: number): number return nextC(O(nextC(c))) end local function swingRight(c: number): number return prevC(O(prevC(c))) end local stack: { number } = {} local sp = 0 local splitActive: { [number]: number } = {} local invalidVerts: { number } = {} local removeInvalid = numAttributeData == 0 local nf = 0 for symbolId = 0, numSymbols - 1 do local face = nf nf += 1 local checkSplit = false local symbol = trav.decodeSymbol() local corner = 3 * face if symbol == TOPOLOGY_C then if sp == 0 then return nil, "bad traversal (C)" end local a = stack[sp] local vx = V(nextC(a)) local b = nextC(LMC(vx)) if a == b or O(a) ~= -1 or O(b) ~= -1 then return nil, "bad traversal (C)" end setOpp(a, corner + 1) setOpp(b, corner + 2) local vap, vbn = V(prevC(a)), V(nextC(b)) if vx == vap or vx == vbn then return nil, "bad traversal (C)" end c2v[corner + 1] = vx c2v[corner + 2] = vbn c2v[corner + 3] = vap setLmc(vap, corner + 2) notHole[vx] = true stack[sp] = corner elseif symbol == TOPOLOGY_R or symbol == TOPOLOGY_L then if sp == 0 then return nil, "bad traversal (R / L)" end local a = stack[sp] if O(a) ~= -1 then return nil, "bad traversal (R / L)" end local oc, cl, cr if symbol == TOPOLOGY_R then oc, cl, cr = corner + 2, corner + 1, corner else oc, cl, cr = corner + 1, corner, corner + 2 end setOpp(oc, a) local nvx = addVertex() if nv > maxVertices then return nil, "too many vertices" end c2v[oc + 1] = nvx setLmc(nvx, oc) local vr = V(prevC(a)) c2v[cr + 1] = vr setLmc(vr, cr) c2v[cl + 1] = V(nextC(a)) stack[sp] = corner checkSplit = true elseif symbol == TOPOLOGY_S then if sp == 0 then return nil, "bad traversal (S)" end local b = stack[sp] stack[sp] = nil sp -= 1 local pushed = splitActive[symbolId] if pushed then sp += 1 stack[sp] = pushed end if sp == 0 then return nil, "bad traversal (S)" end local a = stack[sp] if a == b or O(a) ~= -1 or O(b) ~= -1 then return nil, "bad traversal (S)" end setOpp(a, corner + 2) setOpp(b, corner + 1) local vp = V(prevC(a)) c2v[corner + 1] = vp c2v[corner + 2] = V(nextC(a)) local vbp = V(prevC(b)) c2v[corner + 3] = vbp setLmc(vbp, corner + 2) local cn = nextC(b) local vn = V(cn) trav.mergeVertices(vp, vn) setLmc(vp, LMC(vn)) local first = cn while cn ~= -1 do c2v[cn + 1] = vp cn = swingLeft(cn) if cn == first then return nil, "bad traversal (S loop)" end end setLmc(vn, -1) if removeInvalid then table.insert(invalidVerts, vn) end stack[sp] = corner elseif symbol == TOPOLOGY_E then local v0 = addVertex() c2v[corner + 1] = v0 c2v[corner + 2] = addVertex() c2v[corner + 3] = addVertex() if nv > maxVertices then return nil, "too many vertices" end setLmc(v0, corner) setLmc(v0 + 1, corner + 1) setLmc(v0 + 2, corner + 2) sp += 1 stack[sp] = corner checkSplit = true else return nil, "bad traversal symbol" end ct.nv = nv trav.newActiveCorner(stack[sp]) if checkSplit then local encId = numSymbols - symbolId - 1 while true do local top = splitData[#splitData] if not top then break end if top.source > encId then return nil, "bad split symbol id" end if top.source ~= encId then break end splitData[#splitData] = nil local act = stack[sp] local newActive = if top.edge == 1 then nextC(act) else prevC(act) splitActive[numSymbols - top.split - 1] = newActive end end end if nv > maxVertices then return nil, "too many vertices" end -- start faces: interior faces that close the remaining holes local initFaces = {} while sp > 0 do local corner = stack[sp] stack[sp] = nil sp -= 1 if trav.startFace() then if nf >= numFaces then return nil, "too many faces" end local vn = V(nextC(corner)) local b = nextC(LMC(vn)) local vx = V(nextC(b)) local c = nextC(LMC(vx)) if corner == b or corner == c or b == c or O(corner) ~= -1 or O(b) ~= -1 or O(c) ~= -1 then return nil, "bad start face" end local vp = V(nextC(c)) local nc = 3 * nf nf += 1 setOpp(nc, corner) setOpp(nc + 1, b) setOpp(nc + 2, c) c2v[nc + 1] = vx c2v[nc + 2] = vp c2v[nc + 3] = vn for k = 0, 2 do notHole[V(nc + k)] = true end table.insert(initFaces, nc) end end if nf ~= numFaces then return nil, "face count mismatch" end -- compact the vertices removed by S symbols (no attribute data only) local numVertices = nv for _, inv in invalidVerts do local src = numVertices - 1 while src >= 0 and LMC(src) == -1 do numVertices -= 1 src = numVertices - 1 end if src >= inv then -- every corner of src (VertexCornersIterator: left, then right) local start = LMC(src) local corners = {} local cc = start local left = true local guard = 0 while cc ~= -1 do table.insert(corners, cc) guard += 1 if guard > numFaces * 3 + 3 then return nil, "bad vertex fan" end if left then cc = swingLeft(cc) if cc == -1 then cc = swingRight(start) left = false elseif cc == start then cc = -1 end else cc = swingRight(cc) end end for _, cid in corners do if V(cid) ~= src then return nil, "bad vertex fan" end c2v[cid + 1] = inv end setLmc(inv, LMC(src)) setLmc(src, -1) notHole[inv] = notHole[src] notHole[src] = true numVertices -= 1 end end -- continue after the traversal data (and the split events before 2.2) d.pos = after.pos d.bad = after.bad if ver < 0x0202 then d.pos += splitBytes end local attrData: { AttrData } = {} for i = 1, numAttributeData do attrData[i] = { decoderId = -1, used = true, seams = {}, ct = nil, enc = newEnc(0) } end if numAttributeData > 0 then for f = 0, numFaces - 1 do local base = 3 * f for k = 0, 2 do local c = if k == 0 then base elseif k == 1 then base + 1 else base + 2 local o = O(c) if o == -1 then for i = 1, numAttributeData do table.insert(attrData[i].seams, c) end elseif ver < 0x0201 or o // 3 >= f then for i = 1, numAttributeData do if trav.seam(i - 1) then table.insert(attrData[i].seams, c) end end end end end end ct.nv = nv for i = 1, numAttributeData do local act = attributeTable(ct, attrData[i].seams) if not act then return nil, "bad attribute seams" end attrData[i].ct = act attrData[i].enc = newEnc(math.max(act.nv, nv)) end local posEnc = newEnc(nv) -- AssignPointsToCorners local faces = table.create(numFaces * 3, 0) local numPoints if numAttributeData == 0 then for c = 0, numFaces * 3 - 1 do faces[c + 1] = V(c) end numPoints = numVertices else numPoints = 0 for v = 0, nv - 1 do local c = LMC(v) if c ~= -1 then local first = c if notHole[v] then for i = 1, numAttributeData do local act = attrData[i].ct :: any if act.vertSeam[V(c)] then local vid = act.c2v[c + 1] local a = swingRight(c) local found = false while a ~= c do if a == -1 then return nil, "bad seam fan" end if act.c2v[a + 1] ~= vid then first = a found = true break end a = swingRight(a) end if found then break end end end end c = first faces[c + 1] = numPoints numPoints += 1 local pc = c c = swingRight(c) local guard = 0 while c ~= -1 and c ~= first do local seam = false for i = 1, numAttributeData do local ac2v = (attrData[i].ct :: CT).c2v if ac2v[c + 1] ~= ac2v[pc + 1] then seam = true break end end if seam then faces[c + 1] = numPoints numPoints += 1 else faces[c + 1] = faces[pc + 1] end pc = c c = swingRight(c) guard += 1 if guard > numFaces * 3 then return nil, "bad vertex fan" end end end end end for k = 1, nv do if not lmc[k] then lmc[k] = -1 end end return { faces = faces, numFaces = numFaces, numPoints = numPoints, ct = ct, attrData = attrData, posEnc = posEnc, posDecoderId = -1, }, nil end -- MeshTraversalSequencer::GenerateSequence: method 0 depth first, 1 max prediction degree function Connectivity.traverse(ct: CT, faces: { number }, enc: Enc, method: number): { number }? local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc local nf, nvt = ct.nf, ct.nv local faceVisited = table.create(nf, false) local vertVisited = table.create(nvt, false) local points: { number } = {} local v2e, e2c = enc.v2e, enc.e2c local function V(c: number): number return if c < 0 then -1 else (c2v[c + 1] or -1) end local function O(c: number): number return if c < 0 then -1 else (opp[c + 1] or -1) end local function faceSeen(c: number): boolean if c < 0 then return true end return faceVisited[c // 3 + 1] == true end local function visit(v: number, c: number): boolean if v < 0 or v >= nvt then return false end vertVisited[v + 1] = true table.insert(points, faces[c + 1]) table.insert(e2c, c) v2e[v + 1] = enc.numValues enc.numValues += 1 return true end local function onBoundary(v: number): boolean local c = if v < 0 then -1 else (lmc[v + 1] or -1) return nextC(O(nextC(c))) == -1 end if method == 0 then local stack: { number } = {} for f = 0, nf - 1 do local start = 3 * f if not faceSeen(start) then stack[1] = start for k = #stack, 2, -1 do stack[k] = nil end local nx, pv = V(nextC(start)), V(prevC(start)) if nx == -1 or pv == -1 then return nil end if not vertVisited[nx + 1] and not visit(nx, nextC(start)) then return nil end if not vertVisited[pv + 1] and not visit(pv, prevC(start)) then return nil end while #stack > 0 do local c = stack[#stack] if c == -1 or faceSeen(c) then stack[#stack] = nil continue end while true do faceVisited[c // 3 + 1] = true local v = V(c) if v == -1 then return nil end if not vertVisited[v + 1] then local boundary = onBoundary(v) if not visit(v, c) then return nil end if not boundary then c = O(nextC(c)) if c == -1 then -- C++ would index face -1 here; treat as done stack[#stack] = nil break end continue end end local rc, lc = O(nextC(c)), O(prevC(c)) if faceSeen(rc) then if faceSeen(lc) then stack[#stack] = nil break end c = lc elseif faceSeen(lc) then c = rc else stack[#stack] = lc table.insert(stack, rc) break end end end end end return points end if nvt == 0 then return points end local degree = table.create(nvt, 0) local stacks: { { number } } = { {}, {}, {} } local best = 0 local function priority(c: number): number local v = V(c) if v < 0 or v >= nvt then return 0 end local p = 0 if not vertVisited[v + 1] then degree[v + 1] += 1 p = if degree[v + 1] > 1 then 1 else 2 end return p end for f = 0, nf - 1 do local start = 3 * f table.insert(stacks[1], start) best = 0 local nx, pv, tip = V(nextC(start)), V(prevC(start)), V(start) for _, pair in { { nx, nextC(start) }, { pv, prevC(start) }, { tip, start } } do local v = pair[1] if v < 0 or v >= nvt then return nil end if not vertVisited[v + 1] then visit(v, pair[2]) end end while true do local c = -1 for i = best, 2 do local s = stacks[i + 1] if #s > 0 then c = s[#s] s[#s] = nil best = i break end end if c == -1 then break end if not faceSeen(c) then while true do faceVisited[c // 3 + 1] = true local v = V(c) if v < 0 or v >= nvt then return nil end if not vertVisited[v + 1] then visit(v, c) end local rc, lc = O(nextC(c)), O(prevC(c)) local rSeen, lSeen = faceSeen(rc), faceSeen(lc) if not lSeen then local p = priority(lc) if rSeen and p <= best then c = lc continue end table.insert(stacks[p + 1], lc) if p < best then best = p end end if not rSeen then local p = priority(rc) if p <= best then c = rc continue end table.insert(stacks[p + 1], rc) if p < best then best = p end end break end end end end return points end -- MeshTraversalSequencer::UpdatePointToAttributeIndexMapping function Connectivity.mapping(ct: CT, faces: { number }, enc: Enc, numPoints: number): { number }? local map = table.create(numPoints, 0) local c2v, v2e = ct.c2v, enc.v2e for c = 0, ct.nf * 3 - 1 do local p = faces[c + 1] local v = c2v[c + 1] or -1 if v == -1 then return nil end local e = v2e[v + 1] or 0 if p >= numPoints or e >= numPoints then return nil end map[p + 1] = e end return map end return Connectivity end __FILES["codecs/model/Draco/Int64"] = function() -- codecs/model/Draco/Int64: wrap-around int64 / uint64 for Draco's portable tex coord predictor. -- Values are (hi, lo) 32-bit halves, two's complement (hi >= 2^31 is negative). local Int64 = {} local P32 = 4294967296 local P31 = 2147483648 function Int64.from(n: number): (number, number) if n >= 0 then return (n // P32) % P32, n % P32 end local h, l = Int64.from(-n) return Int64.neg(h, l) end function Int64.neg(h: number, l: number): (number, number) if l == 0 then return (P32 - h) % P32, 0 end return P32 - 1 - h, P32 - l end function Int64.add(ah: number, al: number, bh: number, bl: number): (number, number) local l = al + bl local c = 0 if l >= P32 then l -= P32 c = 1 end return (ah + bh + c) % P32, l end function Int64.sub(ah: number, al: number, bh: number, bl: number): (number, number) local nh, nl = Int64.neg(bh, bl) return Int64.add(ah, al, nh, nl) end function Int64.mul(ah: number, al: number, bh: number, bl: number): (number, number) local a0, a1, a2, a3 = al % 65536, al // 65536, ah % 65536, ah // 65536 local b0, b1, b2, b3 = bl % 65536, bl // 65536, bh % 65536, bh // 65536 local c0 = a0 * b0 local c1 = a1 * b0 + a0 * b1 local c2 = a2 * b0 + a1 * b1 + a0 * b2 local c3 = a3 * b0 + a2 * b1 + a1 * b2 + a0 * b3 local lo = c0 + (c1 % 65536) * 65536 local carry = lo // P32 lo %= P32 local hi = (c1 // 65536 + c2 + (c3 % 65536) * 65536 + carry) % P32 return hi, lo end function Int64.isNeg(h: number): boolean return h >= P31 end function Int64.signed(h: number, l: number): number if h >= P31 then return (h - P32) * P32 + l end return h * P32 + l end function Int64.unsigned(h: number, l: number): number return h * P32 + l end function Int64.ucmp(ah: number, al: number, bh: number, bl: number): number if ah ~= bh then return if ah < bh then -1 else 1 end if al ~= bl then return if al < bl then -1 else 1 end return 0 end function Int64.cmp(ah: number, al: number, bh: number, bl: number): number local sa = if ah >= P31 then ah - P32 else ah local sb = if bh >= P31 then bh - P32 else bh if sa ~= sb then return if sa < sb then -1 else 1 end return Int64.ucmp(0, al, 0, bl) end function Int64.udivmod(ah: number, al: number, bh: number, bl: number): (number, number, number, number) if ah == 0 and bh == 0 then return 0, al // bl, 0, al % bl end local qh, ql, rh, rl = 0, 0, 0, 0 for i = 63, 0, -1 do local bit = if i >= 32 then (ah // 2 ^ (i - 32)) % 2 else (al // 2 ^ i) % 2 local over = rh >= P31 rh = (rh * 2 + rl // P31) % P32 rl = (rl * 2) % P32 + bit if over or Int64.ucmp(rh, rl, bh, bl) >= 0 then rh, rl = Int64.sub(rh, rl, bh, bl) if i >= 32 then qh += 2 ^ (i - 32) else ql += 2 ^ i end end end return qh, ql, rh, rl end function Int64.div(ah: number, al: number, bh: number, bl: number): (number, number) local na, nb = ah >= P31, bh >= P31 if na then ah, al = Int64.neg(ah, al) end if nb then bh, bl = Int64.neg(bh, bl) end local qh, ql = Int64.udivmod(ah, al, bh, bl) if na ~= nb then return Int64.neg(qh, ql) end return qh, ql end -- IntSqrt (draco/core/math_utils.h) on a uint64, step for step (wrap-around included) function Int64.isqrt(h: number, l: number): (number, number) if h == 0 and l == 0 then return 0, 0 end local acth, actl = h, l local sh, sl = 0, 1 while Int64.ucmp(acth, actl, 0, 2) >= 0 do sh, sl = Int64.add(sh, sl, sh, sl) acth, actl = Int64.udivmod(acth, actl, 0, 4) end repeat local qh, ql = Int64.udivmod(h, l, sh, sl) local th, tl = Int64.add(sh, sl, qh, ql) sh, sl = Int64.udivmod(th, tl, 0, 2) if sh == 0 and sl == 0 then return 0, 0 end local pph, ppl = Int64.mul(sh, sl, sh, sl) until Int64.ucmp(pph, ppl, h, l) <= 0 return sh, sl end return Int64 end __FILES["codecs/model/Draco/KdTree"] = function() -- codecs/model/Draco/KdTree: kd-tree coded point cloud attributes (bitstream 2.3, compression levels 0 - 6). -- Port of Draco 1.5.7 kd_tree_attributes_decoder.cc, dynamic_integer_points_kd_tree_decoder.h and the direct / -- folded_integer bit decoders (Apache-2.0, licenses/draco-LICENSE.txt). Pre-2.3 kd-tree layouts are not supported. local Reader = __include("codecs/model/Draco/Reader") local Predict = __include("codecs/model/Draco/Predict") local KdTree = {} type D = Reader.D -- bits(n) reads MSB first type Src = { next: () -> number, bits: (n: number) -> number? } local function direct(d: D): Src? local size = Reader.u32(d) if d.bad or size == 0 or size % 4 ~= 0 or size > Reader.remaining(d) then Reader.fail(d, "kd-tree: bad direct bits") return nil end local b, base, words = d.b, d.pos, size // 4 d.pos += size local pos, used = 0, 0 return { next = function(): number if pos >= words then return 0 end local w = buffer.readu32(b, base + pos * 4) local bit = bit32.extract(w, 31 - used) used += 1 if used == 32 then pos += 1 used = 0 end return bit end, bits = function(n: number): number? local remaining = 32 - used if n <= remaining then if pos >= words then return nil end local w = buffer.readu32(b, base + pos * 4) local v = bit32.extract(w, 32 - used - n, n) used += n if used == 32 then pos += 1 used = 0 end return v end if pos + 1 >= words then return nil end local hiBits = bit32.extract(buffer.readu32(b, base + pos * 4), 0, remaining) local lo = n - remaining pos += 1 used = lo local loBits = bit32.extract(buffer.readu32(b, base + pos * 4), 32 - lo, lo) return hiBits * 2 ^ lo + loBits end, } end local function rans(d: D): Src? local bd = Reader.bitDecoder(d) if not bd then return nil end local function nextBit(): number return if Reader.bit(bd) then 1 else 0 end return { next = nextBit, bits = function(n: number): number? local v = 0 for _ = 1, n do v = v * 2 + nextBit() end return v end, } end local function folded(d: D): Src? local parts: { Reader.Bits } = {} for i = 1, 32 do local bd = Reader.bitDecoder(d) if not bd then return nil end parts[i] = bd end local main = Reader.bitDecoder(d) if not main then return nil end return { next = function(): number return if Reader.bit(main :: Reader.Bits) then 1 else 0 end, bits = function(n: number): number? local v = 0 for i = 1, n do v = v * 2 + (if Reader.bit(parts[i]) then 1 else 0) end return v end, } end local function msb(n: number): number local k = -1 while n >= 1 do n = n // 2 k += 1 end return k end -- DynamicIntegerPointsKdTreeDecoder::DecodePoints local function decodePoints(d: D, level: number, dim: number, expected: number): ({ { number } }?, string?) local bitLength = Reader.u32(d) local numPoints = Reader.u32(d) if d.bad then return nil, d.bad end if bitLength > 32 then return nil, "kd-tree: bad bit length" end if numPoints ~= expected then return nil, "kd-tree: point count mismatch" end local out: { { number } } = {} if numPoints == 0 then return out, nil end local numbers = if level >= 4 then folded(d) elseif level >= 2 then rans(d) else direct(d) local remainingBits = numbers and direct(d) local axisDec = remainingBits and direct(d) local half = axisDec and direct(d) if not numbers or not remainingBits or not axisDec or not half then return nil, d.bad or "kd-tree: bad bit decoders" end local selectAxis = level >= 6 local zero = table.create(dim, 0) local baseStack: { { number } } = { table.clone(zero) } local levelStack: { { number } } = { table.clone(zero) } local stack = { { numPoints, 0, 0 } } local decoded = 0 local p = table.create(dim, 0) while #stack > 0 do local st = stack[#stack] stack[#stack] = nil local n, lastAxis, sp = st[1], st[2], st[3] local oldBase, levels = baseStack[sp + 1], levelStack[sp + 1] if n > numPoints then return nil, "kd-tree: bad point count" end local axis if not selectAxis then axis = if lastAxis == dim - 1 then 0 else lastAxis + 1 elseif n < 64 then axis = 0 for a = 1, dim - 1 do if levels[axis + 1] > levels[a + 1] then axis = a end end else axis = (axisDec :: Src).bits(4) or 0 end if axis >= dim then return nil, "kd-tree: bad axis" end local lvl = levels[axis + 1] if bitLength - lvl == 0 then for _ = 1, n do table.insert(out, table.clone(oldBase)) decoded += 1 end if decoded > numPoints then return nil, "kd-tree: too many points" end continue end if n <= 2 then for _ = 1, n do local a = axis for _ = 1, dim do local rb = bitLength - levels[a + 1] local v = 0 if rb > 0 then local got = remainingBits.bits(rb) if got == nil then return nil, "kd-tree: remaining bits run out" end v = got end p[a + 1] = bit32.bor(oldBase[a + 1], v) a = if a == dim - 1 then 0 else a + 1 end table.insert(out, table.clone(p)) decoded += 1 end if decoded > numPoints then return nil, "kd-tree: too many points" end continue end if decoded > numPoints then return nil, "kd-tree: too many points" end local rbits = bitLength - lvl local modifier = 2 ^ (rbits - 1) local nb = table.clone(oldBase) nb[axis + 1] = (nb[axis + 1] + modifier) % 4294967296 baseStack[sp + 2] = nb local number = numbers.bits(msb(n)) or 0 local first = n // 2 if first < number then return nil, "kd-tree: bad split" end first -= number local second = n - first if first ~= second and half.next() == 0 then first, second = second, first end levels[axis + 1] += 1 levelStack[sp + 2] = table.clone(levels) if sp + 2 > 32 * dim + 1 then return nil, "kd-tree: too deep" end if first > 0 then table.insert(stack, { first, axis, sp }) end if second > 0 then table.insert(stack, { second, axis, sp + 1 }) end end if decoded ~= expected then return nil, "kd-tree: point count mismatch" end return out, nil end local SIGNED = { [1] = 8, [3] = 16, [5] = 32 } function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, string?) if d.ver < 0x0203 then return false, "unsupported: kd-tree point clouds before bitstream 2.3" end local level = Reader.u8(d) if d.bad then return false, d.bad end if level > 6 then return false, "kd-tree: bad compression level" end local dim = 0 for _, a in attrs do local dt = a.dataType if dt ~= 2 and dt ~= 4 and dt ~= 6 and dt ~= 1 and dt ~= 3 and dt ~= 5 and dt ~= 9 then return false, "unsupported: kd-tree attribute of data type " .. dt end dim += a.comps end local points, err = decodePoints(d, level, dim, numPoints) if not points then return false, err end -- the portable values per attribute: the low bytes of each u32 for 8 / 16-bit types local off = 0 for _, a in attrs do local comps = a.comps local vals = table.create(numPoints * comps, 0) local mod = if a.dataType == 1 or a.dataType == 2 then 256 elseif a.dataType == 3 or a.dataType == 4 then 65536 else 4294967296 local raw = a.dataType == 9 for i, pt in points do for c = 1, comps do local v = pt[off + c] vals[(i - 1) * comps + c] = if raw then v else v % mod end end a.portable = vals a.values = vals a.numValues = numPoints a.map = nil off += comps end for _, a in attrs do if a.dataType == 9 then local mins = table.create(a.comps, 0) for c = 1, a.comps do mins[c] = Reader.f32(d) end local range = Reader.f32(d) local bits = Reader.u8(d) if d.bad or bits < 1 or bits > 30 then return false, d.bad or "kd-tree: bad quantization" end a.quant = { min = mins, range = range, bits = bits } end end for _, a in attrs do if SIGNED[a.dataType] then local mins = table.create(a.comps, 0) for c = 1, a.comps do local v = Reader.varint(d) mins[c] = if v % 2 == 1 then -(v // 2) - 1 else v // 2 end if d.bad then return false, d.bad end a.signedMin = mins end end local fround = Predict.fround for _, a in attrs do local vals = a.portable :: { number } local comps = a.comps if a.dataType == 9 then local q = a.quant local delta = fround(q.range / fround(2 ^ q.bits - 1)) local out = table.create(#vals, 0) for i = 1, #vals do local c = (i - 1) % comps + 1 local v = vals[i] if v >= 2147483648 then v -= 4294967296 end out[i] = fround(fround(fround(v) * delta) + q.min[c]) end a.values = out elseif SIGNED[a.dataType] then -- the C++ reads the stored (already narrowed) unsigned values back local bits = SIGNED[a.dataType] local mins = a.signedMin local out = table.create(#vals, 0) for i = 1, #vals do local c = (i - 1) % comps + 1 local u = vals[i] if u > 2147483647 then return false, "kd-tree: signed value out of range" end local s = Predict.i32(u + mins[c]) local m = 2 ^ bits out[i] = (s + m / 2) % m - m / 2 end a.values = out end end return true, nil end return KdTree end __FILES["codecs/model/Draco/Predict"] = function() -- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms. -- C++ integer semantics (int32 wrap, truncating division, exact 64-bit products) and f32 rounding at every step. -- Port of Draco 1.5.7 prediction_schemes/*, normal_compression_utils.h (Apache-2.0, licenses/draco-LICENSE.txt). local Reader = __include("codecs/model/Draco/Reader") local Connectivity = __include("codecs/model/Draco/Connectivity") local Int64 = __include("codecs/model/Draco/Int64") local Predict = {} type D = Reader.D type CT = Connectivity.CT local nextC, prevC = Connectivity.next, Connectivity.prev local F32 = buffer.create(4) local function fround(x: number): number buffer.writef32(F32, 0, x) return buffer.readf32(F32, 0) end Predict.fround = fround local function i32(x: number): number return (x + 2147483648) % 4294967296 - 2147483648 end Predict.i32 = i32 local function tdiv(a: number, b: number): number local q = a / b return if q < 0 then math.ceil(q) else math.floor(q) end -- static_cast of a float with the decoder's NaN / range guard (INT_MIN) local function truncInt(x: number): number if x ~= x or x > 2147483647 or x < -2147483648 then return -2147483648 end return tdiv(x, 1) end -- exact a * b = p + e (Dekker), for integers below 2^53 local SPLIT = 134217729 local function twoProd(a: number, b: number): (number, number) local p = a * b local t = SPLIT * a local ah = t - (t - a) local al = a - ah t = SPLIT * b local bh = t - (t - b) local bl = b - bh return p, ((ah * bh - p) + ah * bl + al * bh) + al * bl end -- trunc(a * b / c) for integers, exact while the true product is below 2^106 (c > 0) local function mulDiv(a: number, b: number, c: number): number local neg = (a < 0) ~= (b < 0) a, b = math.abs(a), math.abs(b) local p = a * b local q if p < 9007199254740992 then q = p // c else q = math.floor(p / c) local ph, pl = twoProd(a, b) local qh, ql = twoProd(q, c) local r = (ph - qh) + (pl - ql) while r < 0 do q -= 1 r += c end while r >= c do q += 1 r -= c end end return if neg then -q else q end -- floor(sqrt(a * b)) (IntSqrt of a 64-bit product), exact for a, b < 2^53 local function isqrtProd(a: number, b: number): number if a == 0 or b == 0 then return 0 end local s = math.floor(math.sqrt(a) * math.sqrt(b)) local ph, pl = twoProd(a, b) local function le(x: number): boolean local xh, xl = twoProd(x, x) if xh ~= ph then return xh < ph end return xl <= pl end while s > 0 and not le(s) do s -= 1 end while le(s + 1) do s += 1 end return s end type Oct = { bits: number, maxQ: number, maxV: number, center: number, scale: number } function Predict.octahedron(bits: number): Oct? if bits < 2 or bits > 30 then return nil end local maxQ = 2 ^ bits - 1 local maxV = maxQ - 1 return { bits = bits, maxQ = maxQ, maxV = maxV, center = maxV // 2, scale = fround(2 / fround(maxV)) } end local function canonicalizeCoords(o: Oct, s: number, t: number): (number, number) local maxV, center = o.maxV, o.center if (s == 0 and t == 0) or (s == 0 and t == maxV) or (s == maxV and t == 0) then return maxV, maxV elseif s == 0 and t > center then t = center - (t - center) elseif s == maxV and t < center then t = center + (center - t) elseif t == maxV and s < center then s = center + (center - s) elseif t == 0 and s > center then s = center - (s - center) end return s, t end local function intVectorToOct(o: Oct, x: number, y: number, z: number): (number, number) local s, t local center, maxV = o.center, o.maxV if x >= 0 then s, t = y + center, z + center else s = if y < 0 then math.abs(z) else maxV - math.abs(z) t = if z < 0 then math.abs(y) else maxV - math.abs(y) end return canonicalizeCoords(o, s, t) end local function canonicalizeVector(o: Oct, x: number, y: number, z: number): (number, number, number) local sum = math.abs(x) + math.abs(y) + math.abs(z) local center = o.center if sum == 0 then return center, y, z end x = mulDiv(x, center, sum) y = mulDiv(y, center, sum) if z >= 0 then z = center - math.abs(x) - math.abs(y) else z = -(center - math.abs(x) - math.abs(y)) end return x, y, z end local function invertDiamond(o: Oct, s: number, t: number): (number, number) local signS, signT if s >= 0 and t >= 0 then signS, signT = 1, 1 elseif s <= 0 and t <= 0 then signS, signT = -1, -1 else signS = if s > 0 then 1 else -1 signT = if t > 0 then 1 else -1 end local cs, ctv = signS * o.center, signT * o.center local us, ut = s + s - cs, t + t - ctv if signS * signT >= 0 then us, ut = -ut, -us else us, ut = ut, us end return tdiv(i32(us + cs), 2), tdiv(i32(ut + ctv), 2) end local function modMax(o: Oct, x: number): number if x > o.center then return x - o.maxQ elseif x < -o.center then return x + o.maxQ end return x end -- quantized octahedral (s, t) -> unit vector, in f32 like the C++ function Predict.octToVector(o: Oct, s: number, t: number): (number, number, number) local y = fround(fround(fround(s) * o.scale) - 1) local z = fround(fround(fround(t) * o.scale) - 1) local x = fround(fround(1 - math.abs(y)) - math.abs(z)) local xo = -x if xo < 0 then xo = 0 end y = fround(if y < 0 then y + xo else y - xo) z = fround(if z < 0 then z + xo else z - xo) local n2 = fround(fround(fround(x * x) + fround(y * y)) + fround(z * z)) if n2 < 1e-6 then return 0, 0, 0 end local dd = fround(1 / fround(math.sqrt(n2))) return fround(x * dd), fround(y * dd), fround(z * dd) end type Transform = { kind: number, -- 1 wrap, 2 octahedron, 3 octahedron canonicalized positive: boolean, -- corrections are stored without the zig-zag sign mapping min: number, max: number, maxDif: number, oct: Oct?, } function Predict.transform(kind: number): Transform return { kind = kind, positive = kind ~= 1, min = 0, max = 0, maxDif = 0, oct = nil } end function Predict.decodeTransform(tr: Transform, d: D): boolean if tr.kind == 1 then local mn, mx = Reader.i32(d), Reader.i32(d) if d.bad or mn > mx then return false end local dif = mx - mn if dif >= 2147483647 then return false end tr.min, tr.max, tr.maxDif = mn, mx, dif + 1 return true end local maxQ = Reader.i32(d) if tr.kind == 3 or d.ver < 0x0202 then Reader.i32(d) -- center value (unused) end if d.bad or maxQ <= 0 or maxQ % 2 == 0 then return false end local bits = 0 while 2 ^ bits <= maxQ do bits += 1 end local o = Predict.octahedron(bits) if not o then return false end tr.oct = o return true end local function apply(tr: Transform, pred: { number }, data: { number }, off: number, comps: number) if tr.kind == 1 then local mn, mx, dif = tr.min, tr.max, tr.maxDif for c = 1, comps do local p = pred[c] if p > mx then p = mx elseif p < mn then p = mn end local v = i32(p + data[off + c]) if v > mx then v -= dif elseif v < mn then v += dif end data[off + c] = v end return end local o = tr.oct :: Oct local center = o.center local ps, pt = pred[1] - center, pred[2] - center local cs, ct = data[off + 1], data[off + 2] local inDiamond = math.abs(ps) + math.abs(pt) <= center if not inDiamond then ps, pt = invertDiamond(o, ps, pt) end local os_: number, ot: number = 0, 0 if tr.kind == 2 then os_ = modMax(o, i32(ps + cs)) ot = modMax(o, i32(pt + ct)) else local bottomLeft = (ps == 0 and pt == 0) or (ps < 0 and pt <= 0) local rot = 0 if ps == 0 then rot = if pt == 0 then 0 elseif pt > 0 then 3 else 1 elseif ps > 0 then rot = if pt >= 0 then 2 else 1 else rot = if pt <= 0 then 0 else 3 end local function rotate(x: number, y: number, r: number): (number, number) if r == 1 then return y, -x elseif r == 2 then return -x, -y elseif r == 3 then return -y, x end return x, y end if not bottomLeft then ps, pt = rotate(ps, pt, rot) end os_ = modMax(o, i32(ps + cs)) ot = modMax(o, i32(pt + ct)) if not bottomLeft then os_, ot = rotate(os_, ot, (4 - rot) % 4) end end if not inDiamond then os_, ot = invertDiamond(o, os_, ot) end data[off + 1] = os_ + center data[off + 2] = ot + center end Predict.apply = apply type MeshData = { ct: CT, e2c: { number }, v2e: { number } } type Parent = (point: number) -> (number, number, number) type Scheme = { method: number, tr: Transform, md: MeshData?, parent: Parent?, crease: { { boolean } }?, orient: { boolean }?, flips: Reader.Bits?, areaMode: boolean, ver: number, } local DELTA, PARALLELOGRAM, MULTI, TEXDEP, CONSTRAINED, TEXPORT, GEONORMAL = 0, 1, 2, 3, 4, 5, 6 Predict.GEOMETRIC_NORMAL = GEONORMAL function Predict.needsParent(s: Scheme): boolean return s.md ~= nil and (s.method == TEXDEP or s.method == TEXPORT or s.method == GEONORMAL) end -- CreatePredictionSchemeForDecoder: md = nil (no corner table: sequential connectivity, point clouds) gives delta function Predict.new(method: number, tr: Transform, md: MeshData?): Scheme local m = method if not md then m = DELTA elseif tr.kind ~= 1 then if m ~= GEONORMAL then m = DELTA md = nil end elseif m < PARALLELOGRAM or m > GEONORMAL then m = DELTA md = nil end return { method = m, tr = tr, md = if m == DELTA then nil else md, parent = nil, areaMode = true, ver = 0x0202 } end -- DecodePredictionData function Predict.decodeData(s: Scheme, d: D): boolean local m = s.method s.ver = d.ver if m == CONSTRAINED then if d.ver < 0x0202 then local mode = Reader.u8(d) if d.bad or mode ~= 0 then return false end end local md = s.md :: MeshData local crease = {} for i = 1, 4 do local n = Reader.varint(d) if d.bad or n > md.ct.nf * 3 then return false end local flags = table.create(n, false) if n > 0 then local bd = Reader.bitDecoder(d) if not bd then return false end for j = 1, n do flags[j] = Reader.bit(bd) end end crease[i] = flags end s.crease = crease elseif m == TEXPORT then local n = Reader.i32(d) if d.bad or n < 0 or n > (s.md :: MeshData).ct.nf * 3 then return false end local bd = Reader.bitDecoder(d) if not bd then return false end local orient = table.create(n, false) local last = true for i = 1, n do if not Reader.bit(bd) then last = not last end orient[i] = last end s.orient = orient elseif m == TEXDEP then local n = Reader.count(d, 0x0202) local md = s.md :: MeshData if d.bad or n == 0 or n > md.ct.nf * 3 then return false end local bd = Reader.bitDecoder(d) if not bd then return false end local orient = table.create(n, false) local last = true for i = 1, n do if not Reader.bit(bd) then last = not last end orient[i] = last end s.orient = orient elseif m == GEONORMAL then if not Predict.decodeTransform(s.tr, d) then return false end if d.ver < 0x0202 then local mode = Reader.u8(d) if d.bad or mode > 1 then return false end s.areaMode = mode == 1 end local bd = Reader.bitDecoder(d) if not bd then return false end s.flips = bd return true end return Predict.decodeTransform(s.tr, d) end local function parallelogram(md: MeshData, p: number, ci: number, data: { number }, comps: number, out: { number }): boolean local ct = md.ct local oci = if ci < 0 then -1 else (ct.opp[ci + 1] or -1) if oci == -1 then return false end local c2v, v2e = ct.c2v, md.v2e local vo, vn, vp = c2v[oci + 1] or -1, c2v[nextC(oci) + 1] or -1, c2v[prevC(oci) + 1] or -1 if vo < 0 or vn < 0 or vp < 0 then return false end local eo, en, ep = v2e[vo + 1] or 0, v2e[vn + 1] or 0, v2e[vp + 1] or 0 if eo < p and en < p and ep < p then for c = 1, comps do out[c] = i32((data[en * comps + c] + data[ep * comps + c]) - data[eo * comps + c]) end return true end return false end local function swingRight(ct: CT, c: number): number local p = prevC(c) local o = if p < 0 then -1 else (ct.opp[p + 1] or -1) return prevC(o) end local function swingLeft(ct: CT, c: number): number local n = nextC(c) local o = if n < 0 then -1 else (ct.opp[n + 1] or -1) return nextC(o) end -- MeshPredictionSchemeTexCoordsPortablePredictor::ComputePredictedValue in int64 / uint64 like the C++ local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: number, ty: number, tz: number, nx: number, ny: number, nz: number, qx: number, qy: number, qz: number, pop: () -> boolean?): (string, any, any) local pnx, pny, pnz = qx - nx, qy - ny, qz - nz local cnx, cny, cnz = tx - nx, ty - ny, tz - nz local pnu, pnv = pu - nu, pv - nv local B = 67108864 -- 2^26: below it every product and sum stays exact in a double local small = math.abs(pnx) < B and math.abs(pny) < B and math.abs(pnz) < B and math.abs(cnx) < B and math.abs(cny) < B and math.abs(cnz) < B if small then local pn2 = pnx * pnx + pny * pny + pnz * pnz local dot = pnx * cnx + pny * cny + pnz * cnz if pn2 < B and math.abs(dot) < B and math.abs(nu) < B and math.abs(nv) < B and math.abs(pnu) < B and math.abs(pnv) < B then if pn2 == 0 then return "fallback" end local xu, xv = nu * pn2 + dot * pnu, nv * pn2 + dot * pnv local dx = tx - (nx + tdiv(dot * pnx, pn2)) local dy = ty - (ny + tdiv(dot * pny, pn2)) local dz = tz - (nz + tdiv(dot * pnz, pn2)) local cx2 = dx * dx + dy * dy + dz * dz if cx2 < B then local norm = isqrtProd(cx2, pn2) local cxu, cxv = pnv * norm, -pnu * norm local o = pop() if o == nil then return "fail", "prediction: orientations run out" end if o then return "ok", i32(tdiv(xu + cxu, pn2)), i32(tdiv(xv + cxv, pn2)) end return "ok", i32(tdiv(xu - cxu, pn2)), i32(tdiv(xv - cxv, pn2)) end end end local from, add, sub, mul, div = Int64.from, Int64.add, Int64.sub, Int64.mul, Int64.div local function dot3(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number) local xh, xl = from(ax) local yh, yl = from(ay) local zh, zl = from(az) local uh, ul = from(bx) local vh, vl = from(by) local wh, wl = from(bz) local h1, l1 = mul(xh, xl, uh, ul) local h2, l2 = mul(yh, yl, vh, vl) local h3, l3 = mul(zh, zl, wh, wl) h1, l1 = add(h1, l1, h2, l2) return add(h1, l1, h3, l3) end local p2h, p2l = dot3(pnx, pny, pnz, pnx, pny, pnz) if p2h == 0 and p2l == 0 then return "fallback" end local dh, dl = dot3(pnx, pny, pnz, cnx, cny, cnz) local MAXH, MAXL = 2147483647, 4294967295 -- INT64_MAX local function absmax(...: number): (number, number) local m = 0 for _, x in { ... } do m = math.max(m, math.abs(x)) end return from(m) end local function absI(h: number, l: number): (number, number) if Int64.isNeg(h) then return Int64.neg(h, l) end return h, l end -- the overflow guards (unsigned divisions as in the C++) local nmh, nml = absmax(nu, nv) local lh, ll = Int64.udivmod(MAXH, MAXL, p2h, p2l) if Int64.ucmp(nmh, nml, lh, ll) > 0 then return "fail", "prediction: tex coord overflow" end local adh, adl = absI(dh, dl) local pmh, pml = absmax(pnu, pnv) lh, ll = Int64.div(MAXH, MAXL, pmh, pml) if Int64.cmp(adh, adl, lh, ll) > 0 then return "fail", "prediction: tex coord overflow" end local nuh, nul = from(nu) local nvh, nvl = from(nv) local puh, pul = from(pnu) local pvh, pvl = from(pnv) local xuh, xul do local ah, al = mul(nuh, nul, p2h, p2l) local bh, bl = mul(dh, dl, puh, pul) xuh, xul = add(ah, al, bh, bl) end local xvh, xvl do local ah, al = mul(nvh, nvl, p2h, p2l) local bh, bl = mul(dh, dl, pvh, pvl) xvh, xvl = add(ah, al, bh, bl) end local pam = math.max(math.abs(pnx), math.abs(pny), math.abs(pnz)) local pah, pal = from(pam) lh, ll = Int64.div(MAXH, MAXL, pah, pal) if Int64.cmp(adh, adl, lh, ll) > 0 then return "fail", "prediction: tex coord overflow" end -- x_pos = next + (dot * pn) / pn2; cx = tip - x_pos local function proj(n: number, pc: number, t: number): (number, number) local ph, pl = from(pc) local mh, ml = mul(dh, dl, ph, pl) local qh, ql = div(mh, ml, p2h, p2l) local nh, nl = from(n) local xh, xl = add(nh, nl, qh, ql) local th, tl = from(t) return sub(th, tl, xh, xl) end local ax, axl = proj(nx, pnx, tx) local ay, ayl = proj(ny, pny, ty) local az, azl = proj(nz, pnz, tz) local c2h, c2l = mul(ax, axl, ax, axl) do local h, l = mul(ay, ayl, ay, ayl) c2h, c2l = add(c2h, c2l, h, l) h, l = mul(az, azl, az, azl) c2h, c2l = add(c2h, c2l, h, l) end local prh, prl = mul(c2h, c2l, p2h, p2l) local sh, sl = Int64.isqrt(prh, prl) -- cx_uv = (pn_uv.v, -pn_uv.u) * norm local cuh, cul = mul(pvh, pvl, sh, sl) local nh, nl = Int64.neg(puh, pul) local cvh, cvl = mul(nh, nl, sh, sl) local o = pop() if o == nil then return "fail", "prediction: orientations run out" end local uh, ul, vh, vl if o then uh, ul = add(xuh, xul, cuh, cul) vh, vl = add(xvh, xvl, cvh, cvl) else uh, ul = sub(xuh, xul, cuh, cul) vh, vl = sub(xvh, xvl, cvh, cvl) end uh, ul = div(uh, ul, p2h, p2l) vh, vl = div(vh, vl, p2h, p2l) -- static_cast: the low 32 bits return "ok", i32(ul), i32(vl) end -- ComputeOriginalValues (in place); points = the entry -> point map function Predict.compute(s: Scheme, data: { number }, numEntries: number, comps: number, points: { number }): (boolean, string?) local tr = s.tr local m = s.method local pred = table.create(math.max(comps, 3), 0) if m == DELTA then if numEntries == 0 then return true, nil end apply(tr, pred, data, 0, comps) for e = 1, numEntries - 1 do local off = e * comps for c = 1, comps do pred[c] = data[off - comps + c] end apply(tr, pred, data, off, comps) end return true, nil end local md = s.md :: MeshData local e2c = md.e2c local n = #e2c if n ~= numEntries then return false, "prediction: value count mismatch" end local ct = md.ct local function previous(p: number) local off = (p - 1) * comps for c = 1, comps do pred[c] = data[off + c] end end if m == PARALLELOGRAM or m == MULTI or m == CONSTRAINED then if n == 0 then return true, nil end apply(tr, pred, data, 0, comps) local para = table.create(comps, 0) local preds: { { number } } = { table.create(comps, 0), table.create(comps, 0), table.create(comps, 0), table.create(comps, 0) } local creasePos = { 0, 0, 0, 0 } local nc = ct.nf * 3 for p = 1, n - 1 do local start = e2c[p + 1] local off = p * comps if m == PARALLELOGRAM then if parallelogram(md, p, start, data, comps, pred) then apply(tr, pred, data, off, comps) else previous(p) apply(tr, pred, data, off, comps) end elseif m == MULTI then for c = 1, comps do pred[c] = 0 end local count = 0 local ci = start local guard = 0 while ci ~= -1 do if parallelogram(md, p, ci, data, comps, para) then for c = 1, comps do pred[c] = i32(pred[c] + para[c]) end count += 1 end ci = swingRight(ct, ci) if ci == start then ci = -1 end guard += 1 if guard > nc then return false, "prediction: bad vertex fan" end end if count == 0 then previous(p) else for c = 1, comps do pred[c] = tdiv(pred[c], count) end end apply(tr, pred, data, off, comps) else local count = 0 local ci = start local first = true local guard = 0 while ci ~= -1 do if parallelogram(md, p, ci, data, comps, preds[count + 1]) then count += 1 if count == 4 then break end end if first then ci = swingLeft(ct, ci) else ci = swingRight(ct, ci) end if ci == start then break end if ci == -1 and first then first = false ci = swingRight(ct, start) end guard += 1 if guard > nc then return false, "prediction: bad vertex fan" end end local used = 0 if count > 0 then for c = 1, comps do pred[c] = 0 end local crease = s.crease :: { { boolean } } for i = 1, count do local pos = creasePos[count] + 1 creasePos[count] = pos local flag = crease[count][pos] if flag == nil then return false, "prediction: crease flags run out" end if not flag then used += 1 for c = 1, comps do pred[c] = i32(pred[c] + preds[i][c]) end end end end if used == 0 then previous(p) else for c = 1, comps do pred[c] = tdiv(pred[c], used) end end apply(tr, pred, data, off, comps) end end return true, nil end local parent = s.parent if not parent then return false, "prediction: no position attribute" end local c2v, v2e = ct.c2v, md.v2e local function entryOf(c: number): number local v = if c < 0 then -1 else (c2v[c + 1] or -1) if v < 0 then return math.huge end return v2e[v + 1] or 0 end local function posOf(e: number): (number, number, number) local pt = points[e + 1] if pt == nil then return 0, 0, 0 end return parent(pt) end if m == TEXPORT or m == TEXDEP then if comps ~= 2 then return false, "prediction: tex coords need 2 components" end local orient = s.orient :: { boolean } local no = #orient for p = 0, n - 1 do local ci = e2c[p + 1] local ne, pe = entryOf(nextC(ci)), entryOf(prevC(ci)) local done = false if pe < p and ne < p then local nu, nv = data[ne * 2 + 1], data[ne * 2 + 2] local pu, pv = data[pe * 2 + 1], data[pe * 2 + 2] if m == TEXPORT then if pu == nu and pv == nv then pred[1], pred[2] = pu, pv done = true else local tx, ty, tz = posOf(p) local nx, ny, nz = posOf(ne) local qx, qy, qz = posOf(pe) local status, u, v = texPortable(nu, nv, pu, pv, tx, ty, tz, nx, ny, nz, qx, qy, qz, function(): boolean? if no == 0 then return nil end local o = orient[no] orient[no] = nil no -= 1 return o end) if status == "fail" then return false, u :: any elseif status == "ok" then pred[1], pred[2] = u, v done = true end end else local fnu, fnv, fpu, fpv = fround(nu), fround(nv), fround(pu), fround(pv) if fpu == fnu and fpv == fnv then pred[1], pred[2] = truncInt(fpu), truncInt(fpv) done = true else local tx: number, ty: number, tz: number = posOf(p) local nx: number, ny: number, nz: number = posOf(ne) local qx: number, qy: number, qz: number = posOf(pe) tx, ty, tz, nx, ny, nz = fround(tx), fround(ty), fround(tz), fround(nx), fround(ny), fround(nz) qx, qy, qz = fround(qx), fround(qy), fround(qz) local pnx, pny, pnz = fround(qx - nx), fround(qy - ny), fround(qz - nz) local cnx, cny, cnz = fround(tx - nx), fround(ty - ny), fround(tz - nz) local pn2 = fround(fround(fround(pnx * pnx) + fround(pny * pny)) + fround(pnz * pnz)) local sv, tv = 0, 0 if s.ver < 0x0102 or pn2 > 0 then local dot = fround(fround(fround(pnx * cnx) + fround(pny * cny)) + fround(pnz * cnz)) sv = fround(dot / pn2) local ex, ey, ez = fround(cnx - fround(pnx * sv)), fround(cny - fround(pny * sv)), fround(cnz - fround(pnz * sv)) local e2 = fround(fround(fround(ex * ex) + fround(ey * ey)) + fround(ez * ez)) tv = fround(math.sqrt(fround(e2 / pn2))) end local pnu, pnv = fround(fpu - fnu), fround(fpv - fnv) local pnus = fround(fround(pnu * sv) + fnu) local pnut = fround(pnu * tv) local pnvs = fround(fround(pnv * sv) + fnv) local pnvt = fround(pnv * tv) if no == 0 then return false, "prediction: orientations run out" end local o = orient[no] orient[no] = nil no -= 1 local u: number, v: number = 0, 0 if o then u = fround(pnus - pnvt) v = fround(pnvs + pnut) else u = fround(pnus + pnvt) v = fround(pnvs - pnut) end local function toInt(x: number): number local r = math.floor(x + 0.5) if r ~= r or r > 2147483647 or r < -2147483648 then return -2147483648 end return r end pred[1] = toInt(u) pred[2] = toInt(v) done = true end end end if not done then local off = -1 if pe < p then off = pe * 2 end if ne < p then off = ne * 2 elseif p > 0 then off = (p - 1) * 2 else off = -1 end if off < 0 then pred[1], pred[2] = 0, 0 else pred[1], pred[2] = data[off + 1], data[off + 2] end end apply(tr, pred, data, p * 2, 2) end return true, nil end local o = tr.oct local flips = s.flips if not o or not flips or comps ~= 2 then return false, "prediction: bad geometric normal setup" end local nc = ct.nf * 3 for p = 0, n - 1 do local ci = e2c[p + 1] local cx, cy, cz = posOf(entryOf(ci)) local sx, sy, sz = 0, 0, 0 -- VertexCornersIterator from ci: swing left, then right from the start local c = ci local left = true local guard = 0 while c ~= -1 do local cn, cp if s.areaMode then cn, cp = nextC(c), prevC(c) else cn, cp = nextC(ci), prevC(ci) end local ax, ay, az = posOf(entryOf(cn)) local bx, by, bz = posOf(entryOf(cp)) ax, ay, az = ax - cx, ay - cy, az - cz bx, by, bz = bx - cx, by - cy, bz - cz sx += ay * bz - az * by sy += az * bx - ax * bz sz += ax * by - ay * bx if left then c = swingLeft(ct, c) if c == -1 then c = swingRight(ct, ci) left = false elseif c == ci then c = -1 end else c = swingRight(ct, c) end guard += 1 if guard > nc then return false, "prediction: bad vertex fan" end end local upper = 2 ^ 29 local sum = math.abs(sx) + math.abs(sy) + math.abs(sz) if sum > upper then local q = sum // upper sx, sy, sz = tdiv(sx, q), tdiv(sy, q), tdiv(sz, q) end sx, sy, sz = i32(sx), i32(sy), i32(sz) sx, sy, sz = canonicalizeVector(o, sx, sy, sz) if Reader.bit(flips) then sx, sy, sz = -sx, -sy, -sz end pred[1], pred[2] = intVectorToOct(o, sx, sy, sz) apply(tr, pred, data, p * 2, 2) end return true, nil end return Predict end __FILES["codecs/model/Draco/Reader"] = function() -- codecs/model/Draco/Reader: Draco's decoder buffer (LE fields, LEB128, LSB-first bit runs) and rANS / rABS decoders. -- Port of Draco 1.5.7 core/decoder_buffer, core/varint_decoding, entropy/ans.h, rans_symbol_decoder.h, symbol_decoding.cc -- and rans_bit_decoder.cc (Apache-2.0, licenses/draco-LICENSE.txt). local Reader = {} local readu8, readu16, readu32, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readf32 local band, rshift = bit32.band, bit32.rshift type D = { b: buffer, pos: number, limit: number, ver: number, -- major * 256 + minor bad: string?, bitMode: boolean, bitStart: number, bitOff: number, } function Reader.new(b: buffer, pos: number, limit: number, ver: number): D return { b = b, pos = pos, limit = limit, ver = ver, bad = nil, bitMode = false, bitStart = pos, bitOff = 0 } end -- a copy (C++ DecoderBuffer is copied by value: positions are independent afterwards) function Reader.copy(d: D): D return { b = d.b, pos = d.pos, limit = d.limit, ver = d.ver, bad = d.bad, bitMode = d.bitMode, bitStart = d.bitStart, bitOff = d.bitOff } end function Reader.fail(d: D, msg: string): number if not d.bad then d.bad = msg end return 0 end function Reader.remaining(d: D): number return d.limit - d.pos end function Reader.u8(d: D): number local p = d.pos if p + 1 > d.limit then return Reader.fail(d, "truncated") end d.pos = p + 1 return readu8(d.b, p) end function Reader.i8(d: D): number local v = Reader.u8(d) return if v >= 128 then v - 256 else v end function Reader.u16(d: D): number local p = d.pos if p + 2 > d.limit then return Reader.fail(d, "truncated") end d.pos = p + 2 return readu16(d.b, p) end function Reader.u32(d: D): number local p = d.pos if p + 4 > d.limit then return Reader.fail(d, "truncated") end d.pos = p + 4 return readu32(d.b, p) end function Reader.i32(d: D): number local p = d.pos if p + 4 > d.limit then return Reader.fail(d, "truncated") end d.pos = p + 4 return readi32(d.b, p) end function Reader.u64(d: D): number local p = d.pos if p + 8 > d.limit then return Reader.fail(d, "truncated") end d.pos = p + 8 return readu32(d.b, p) + readu32(d.b, p + 4) * 4294967296 end function Reader.f32(d: D): number local p = d.pos if p + 4 > d.limit then return Reader.fail(d, "truncated") end d.pos = p + 4 return readf32(d.b, p) end -- LEB128 (at most 5 bytes for 32-bit values, 10 for 64-bit); 32-bit values wrap like the C++ shifts function Reader.varint(d: D, wide: boolean?): number local maxBytes = if wide then 10 else 5 local v, mul = 0, 1 for _ = 1, maxBytes do local p = d.pos if p + 1 > d.limit then return Reader.fail(d, "truncated varint") end local c = readu8(d.b, p) d.pos = p + 1 v += band(c, 127) * mul if c < 128 then if not wide then v %= 4294967296 end return v end mul *= 128 end return Reader.fail(d, "varint too long") end -- a count stored as u32 before `fixedBefore` (a version number) and as a varint from then on function Reader.count(d: D, fixedBefore: number): number if d.ver < fixedBefore then return Reader.u32(d) end return Reader.varint(d) end -- StartBitDecoding(decodeSize): an optional size (u64 before 2.2, varint64 after), then LSB-first bits up to the end -- of the buffer; EndBitDecoding moves pos past the whole bytes consumed. function Reader.startBits(d: D, decodeSize: boolean): number local size = 0 if decodeSize then if d.ver < 0x0202 then size = Reader.u64(d) else size = Reader.varint(d, true) end end d.bitMode = true d.bitStart = d.pos d.bitOff = 0 return size end function Reader.bits(d: D, n: number): number if not d.bitMode then return Reader.fail(d, "bit decoder not active") end if n > 32 then return Reader.fail(d, "bit run over 32 bits") end local b, start, limit = d.b, d.bitStart, d.limit local off = d.bitOff local v, mul = 0, 1 for _ = 1, n do local byte = start + rshift(off, 3) if byte < limit then if band(rshift(readu8(b, byte), band(off, 7)), 1) == 1 then v += mul end off += 1 end mul *= 2 end d.bitOff = off return v end function Reader.endBits(d: D) d.bitMode = false d.pos = d.bitStart + (d.bitOff + 7) // 8 end -- the precision for a symbol alphabet of `bitLength`-bit symbols: (3 * bits) / 2 clamped to 12..20 local function precisionBits(bitLength: number): number local p = (3 * bitLength) // 2 return if p < 12 then 12 elseif p > 20 then 20 else p end type Rans = { b: buffer, base: number, off: number, state: number, lBase: number, precBits: number, lut: { number }, prob: { number }, cum: { number }, numSymbols: number, } -- RAnsSymbolDecoder::Create: the probability table local function ransCreate(d: D, precBits: number): Rans? local numSymbols = Reader.count(d, 0x0200) if d.bad then return nil end if numSymbols // 64 > Reader.remaining(d) then Reader.fail(d, "rans: too many symbols") return nil end local prec = 2 ^ precBits local prob = table.create(numSymbols, 0) local i = 0 while i < numSymbols do local data = Reader.u8(d) if d.bad then return nil end local token = band(data, 3) if token == 3 then local offset = rshift(data, 2) if i + offset >= numSymbols then Reader.fail(d, "rans: bad zero run") return nil end for j = 0, offset do prob[i + j + 1] = 0 end i += offset + 1 else local p = rshift(data, 2) for k = 1, token do p += Reader.u8(d) * 2 ^ (8 * k - 2) end if d.bad then return nil end prob[i + 1] = p i += 1 end end local lut: { number } = {} local cum = table.create(numSymbols, 0) if numSymbols > 0 then lut = table.create(prec, 0) local c, act = 0, 0 for s = 1, numSymbols do cum[s] = c c += prob[s] if c > prec then Reader.fail(d, "rans: probabilities over the precision") return nil end for j = act + 1, c do lut[j] = s end act = c end if c ~= prec then Reader.fail(d, "rans: probabilities do not sum to the precision") return nil end end return { b = d.b, base = 0, off = 0, state = 0, lBase = prec * 4, precBits = precBits, lut = lut, prob = prob, cum = cum, numSymbols = numSymbols, } end -- read_init over [base, base + size): the final state is stored in the last 1-4 bytes local function ansInit(b: buffer, base: number, size: number, lBase: number, allow4: boolean): (number?, number?) if size < 1 then return nil, nil end local x = rshift(readu8(b, base + size - 1), 6) local off: number, state: number = 0, 0 if x == 0 then off = size - 1 state = band(readu8(b, base + size - 1), 0x3F) elseif x == 1 then if size < 2 then return nil, nil end off = size - 2 state = band(readu16(b, base + size - 2), 0x3FFF) elseif x == 2 then if size < 3 then return nil, nil end off = size - 3 state = readu16(b, base + size - 3) + band(readu8(b, base + size - 1), 0x3F) * 65536 else if not allow4 or size < 4 then return nil, nil end off = size - 4 state = band(readu32(b, base + size - 4), 0x3FFFFFFF) end state += lBase if state >= lBase * 256 then return nil, nil end return off, state end -- RAnsSymbolDecoder::StartDecoding: the coded size, then the bytes local function ransStart(d: D, r: Rans): boolean local size if d.ver < 0x0200 then size = Reader.u64(d) else size = Reader.varint(d, true) end if d.bad then return false end if size > Reader.remaining(d) then Reader.fail(d, "rans: data past the end") return false end local off, state = ansInit(d.b, d.pos, size, r.lBase, true) if not off then Reader.fail(d, "rans: bad initial state") return false end r.base, r.off, r.state = d.pos, off, state :: number d.pos += size return true end local function ransRead(r: Rans, n: number, out: { number }, first: number) local b, base, off, state = r.b, r.base, r.off, r.state local lBase, bits = r.lBase, r.precBits local mask = 2 ^ bits - 1 local lut, prob, cum = r.lut, r.prob, r.cum for i = first, first + n - 1 do while state < lBase and off > 0 do off -= 1 state = state * 256 + readu8(b, base + off) end local quo, rem = rshift(state, bits), band(state, mask) local s = lut[rem + 1] state = quo * prob[s] + rem - cum[s] out[i] = s - 1 end r.off, r.state = off, state end local function decodeTagged(d: D, n: number, comps: number, out: { number }): boolean local tag = ransCreate(d, precisionBits(5)) if not tag or not ransStart(d, tag) then return false end if n > 0 and tag.numSymbols == 0 then Reader.fail(d, "rans: no symbols") return false end Reader.startBits(d, false) local len = { 0 } local k = 1 local i = 0 while i < n do ransRead(tag, 1, len, 1) local bitLength = len[1] for _ = 1, comps do if k > n then break end out[k] = Reader.bits(d, bitLength) k += 1 end if d.bad then return false end i += comps end Reader.endBits(d) return true end local function decodeRaw(d: D, n: number, out: { number }): boolean local maxBitLength = Reader.u8(d) if d.bad then return false end if maxBitLength < 1 or maxBitLength > 18 then Reader.fail(d, "rans: bad symbol bit length") return false end local r = ransCreate(d, precisionBits(maxBitLength)) if not r then return false end if n > 0 and r.numSymbols == 0 then Reader.fail(d, "rans: no symbols") return false end if not ransStart(d, r) then return false end ransRead(r, n, out, 1) return true end -- DecodeSymbols function Reader.symbols(d: D, n: number, comps: number): { number }? local out = table.create(n, 0) if n == 0 then return out end local scheme = Reader.u8(d) if d.bad then return nil end local ok if scheme == 0 then ok = decodeTagged(d, n, math.max(comps, 1), out) elseif scheme == 1 then ok = decodeRaw(d, n, out) else Reader.fail(d, "rans: unknown symbol coding scheme") ok = false end return if ok then out else nil end type Bits = { b: buffer, base: number, off: number, state: number, p0: number, p: number } -- RAnsBitDecoder::StartDecoding: prob_zero, the size (u32 before 2.2), the bytes function Reader.bitDecoder(d: D): Bits? local p0 = Reader.u8(d) local size = Reader.count(d, 0x0202) if d.bad then return nil end if size > Reader.remaining(d) then Reader.fail(d, "rabs: data past the end") return nil end local off, state = ansInit(d.b, d.pos, size, 4096, false) if not off then Reader.fail(d, "rabs: bad initial state") return nil end local bd = { b = d.b, base = d.pos, off = off, state = state :: number, p0 = p0, p = 256 - p0 } d.pos += size return bd end -- rabs_desc_read: one bit (true / false) function Reader.bit(bd: Bits): boolean local state, off = bd.state, bd.off if state < 4096 and off > 0 then off -= 1 state = state * 256 + readu8(bd.b, bd.base + off) bd.off = off end local quot, rem = rshift(state, 8), band(state, 255) local p = bd.p local xn = quot * p if rem < p then bd.state = xn + rem return true end bd.state = state - xn - p return false end return Reader end __FILES["codecs/model/Mat4"] = function() -- codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers. local Types = __include("Types") local Mat4 = {} type M4 = { number } local sqrt, abs, sin, cos, rad = math.sqrt, math.abs, math.sin, math.cos, math.rad function Mat4.identity(): M4 return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } end Mat4.mul = Types.Scene.mul function Mat4.translation(x: number, y: number, z: number): M4 return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } end function Mat4.scaling(x: number, y: number, z: number): M4 return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } end function Mat4.rotation(axis: number, degrees: number): M4 local a = rad(degrees) local c, s = cos(a), sin(a) if axis == 1 then return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 } elseif axis == 2 then return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 } end return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } end local AXIS = { x = 1, y = 2, z = 3 } function Mat4.euler(x: number, y: number, z: number, order: string?): M4 local o = order or "xyz" local deg = { x = x, y = y, z = z } local m = Mat4.identity() for i = 1, 3 do local a = string.sub(o, i, i) m = Mat4.mul(Mat4.rotation(AXIS[a] or i, deg[a] or 0), m) end return m end function Mat4.axisAngle(x: number, y: number, z: number, degrees: number): { number } local l = sqrt(x * x + y * y + z * z) if l < 1e-12 then return { 0, 0, 0, 1 } end local h = rad(degrees) / 2 local s = sin(h) / l return { x * s, y * s, z * s, cos(h) } end function Mat4.fromQuat(q: { number }): M4 local x, y, z, w = q[1], q[2], q[3], q[4] local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z return { 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0, 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0, 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0, 0, 0, 0, 1, } end function Mat4.quat(m: M4): { number } local m00, m01, m02 = m[1], m[5], m[9] local m10, m11, m12 = m[2], m[6], m[10] local m20, m21, m22 = m[3], m[7], m[11] local tr = m00 + m11 + m22 local x, y, z, w if tr > 0 then local s = sqrt(tr + 1) * 2 w, x, y, z = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s elseif m00 > m11 and m00 > m22 then local s = sqrt(math.max(1 + m00 - m11 - m22, 1e-30)) * 2 w, x, y, z = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s elseif m11 > m22 then local s = sqrt(math.max(1 + m11 - m00 - m22, 1e-30)) * 2 w, x, y, z = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s else local s = sqrt(math.max(1 + m22 - m00 - m11, 1e-30)) * 2 w, x, y, z = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4 end local n = sqrt(x * x + y * y + z * z + w * w) if n == 0 or n ~= n then return { 0, 0, 0, 1 } end return { x / n, y / n, z / n, w / n } end function Mat4.eulerXYZ(q: { number }): { number } local m = Mat4.fromQuat(q) local sy = math.clamp(-m[3], -1, 1) -- m[3] = r20 = -sin(y) local y = math.asin(sy) local x, z if abs(sy) < 0.9999999 then x = math.atan2(m[7], m[11]) z = math.atan2(m[2], m[1]) else x = math.atan2(-m[10], m[6]) z = 0 end return { math.deg(x), math.deg(y), math.deg(z) } end -- T * R * S (glTF 2.0 node transform) function Mat4.compose(t: { number }?, r: { number }?, s: { number }?): M4 local m = if r then Mat4.fromQuat(r) else Mat4.identity() if s then for k = 0, 2 do m[k * 4 + 1] *= s[k + 1] m[k * 4 + 2] *= s[k + 1] m[k * 4 + 3] *= s[k + 1] end end if t then m[13], m[14], m[15] = t[1], t[2], t[3] end return m end local function det3(m: M4): number return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) end local function split(m: M4, strict: boolean): ({ number }?, { number }?, { number }?) if strict and (abs(m[4]) > 1e-6 or abs(m[8]) > 1e-6 or abs(m[12]) > 1e-6 or abs(m[16] - 1) > 1e-6) then return nil, nil, nil end local sx = sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3]) local sy = sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7]) local sz = sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) if strict and (sx < 1e-12 or sy < 1e-12 or sz < 1e-12) then return nil, nil, nil end if det3(m) < 0 then sx = -sx end local ix = if sx ~= 0 then 1 / sx else 0 local iy = if sy ~= 0 then 1 / sy else 0 local iz = if sz ~= 0 then 1 / sz else 0 local r = { m[1] * ix, m[2] * ix, m[3] * ix, 0, m[5] * iy, m[6] * iy, m[7] * iy, 0, m[9] * iz, m[10] * iz, m[11] * iz, 0, 0, 0, 0, 1 } if strict then local dxy = r[1] * r[5] + r[2] * r[6] + r[3] * r[7] local dxz = r[1] * r[9] + r[2] * r[10] + r[3] * r[11] local dyz = r[5] * r[9] + r[6] * r[10] + r[7] * r[11] if abs(dxy) > 1e-4 or abs(dxz) > 1e-4 or abs(dyz) > 1e-4 then return nil, nil, nil end end return { m[13], m[14], m[15] }, Mat4.quat(r), { sx, sy, sz } end -- a negative determinant flips the x scale; shear is lost function Mat4.decompose(m: M4): ({ number }, { number }, { number }) local t, r, s = split(m, false) return t :: { number }, r :: { number }, s :: { number } end function Mat4.decomposeStrict(m: M4): ({ number }?, { number }?, { number }?) return split(m, true) end function Mat4.inverse(m: M4): M4? local a, b, c = m[1], m[5], m[9] local d, e, f = m[2], m[6], m[10] local g, h, i = m[3], m[7], m[11] local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g local det = a * A + b * B + c * C if det == 0 or det ~= det then return nil end local k = 1 / det local r = { A * k, B * k, C * k, 0, -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0, (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0, 0, 0, 0, 1, } local tx, ty, tz = m[13], m[14], m[15] r[13] = -(r[1] * tx + r[5] * ty + r[9] * tz) r[14] = -(r[2] * tx + r[6] * ty + r[10] * tz) r[15] = -(r[3] * tx + r[7] * ty + r[11] * tz) return r end function Mat4.inverseFull(m: M4): M4? local a = m local inv = table.create(16, 0) inv[1] = a[6] * a[11] * a[16] - a[6] * a[12] * a[15] - a[10] * a[7] * a[16] + a[10] * a[8] * a[15] + a[14] * a[7] * a[12] - a[14] * a[8] * a[11] inv[5] = -a[5] * a[11] * a[16] + a[5] * a[12] * a[15] + a[9] * a[7] * a[16] - a[9] * a[8] * a[15] - a[13] * a[7] * a[12] + a[13] * a[8] * a[11] inv[9] = a[5] * a[10] * a[16] - a[5] * a[12] * a[14] - a[9] * a[6] * a[16] + a[9] * a[8] * a[14] + a[13] * a[6] * a[12] - a[13] * a[8] * a[10] inv[13] = -a[5] * a[10] * a[15] + a[5] * a[11] * a[14] + a[9] * a[6] * a[15] - a[9] * a[7] * a[14] - a[13] * a[6] * a[11] + a[13] * a[7] * a[10] inv[2] = -a[2] * a[11] * a[16] + a[2] * a[12] * a[15] + a[10] * a[3] * a[16] - a[10] * a[4] * a[15] - a[14] * a[3] * a[12] + a[14] * a[4] * a[11] inv[6] = a[1] * a[11] * a[16] - a[1] * a[12] * a[15] - a[9] * a[3] * a[16] + a[9] * a[4] * a[15] + a[13] * a[3] * a[12] - a[13] * a[4] * a[11] inv[10] = -a[1] * a[10] * a[16] + a[1] * a[12] * a[14] + a[9] * a[2] * a[16] - a[9] * a[4] * a[14] - a[13] * a[2] * a[12] + a[13] * a[4] * a[10] inv[14] = a[1] * a[10] * a[15] - a[1] * a[11] * a[14] - a[9] * a[2] * a[15] + a[9] * a[3] * a[14] + a[13] * a[2] * a[11] - a[13] * a[3] * a[10] inv[3] = a[2] * a[7] * a[16] - a[2] * a[8] * a[15] - a[6] * a[3] * a[16] + a[6] * a[4] * a[15] + a[14] * a[3] * a[8] - a[14] * a[4] * a[7] inv[7] = -a[1] * a[7] * a[16] + a[1] * a[8] * a[15] + a[5] * a[3] * a[16] - a[5] * a[4] * a[15] - a[13] * a[3] * a[8] + a[13] * a[4] * a[7] inv[11] = a[1] * a[6] * a[16] - a[1] * a[8] * a[14] - a[5] * a[2] * a[16] + a[5] * a[4] * a[14] + a[13] * a[2] * a[8] - a[13] * a[4] * a[6] inv[15] = -a[1] * a[6] * a[15] + a[1] * a[7] * a[14] + a[5] * a[2] * a[15] - a[5] * a[3] * a[14] - a[13] * a[2] * a[7] + a[13] * a[3] * a[6] inv[4] = -a[2] * a[7] * a[12] + a[2] * a[8] * a[11] + a[6] * a[3] * a[12] - a[6] * a[4] * a[11] - a[10] * a[3] * a[8] + a[10] * a[4] * a[7] inv[8] = a[1] * a[7] * a[12] - a[1] * a[8] * a[11] - a[5] * a[3] * a[12] + a[5] * a[4] * a[11] + a[9] * a[3] * a[8] - a[9] * a[4] * a[7] inv[12] = -a[1] * a[6] * a[12] + a[1] * a[8] * a[10] + a[5] * a[2] * a[12] - a[5] * a[4] * a[10] - a[9] * a[2] * a[8] + a[9] * a[4] * a[6] inv[16] = a[1] * a[6] * a[11] - a[1] * a[7] * a[10] - a[5] * a[2] * a[11] + a[5] * a[3] * a[10] + a[9] * a[2] * a[7] - a[9] * a[3] * a[6] local det = a[1] * inv[1] + a[2] * inv[5] + a[3] * inv[9] + a[4] * inv[13] if det == 0 or det ~= det then return nil end for k = 1, 16 do inv[k] /= det end return inv end function Mat4.transpose3(m: M4): M4 return { m[1], m[5], m[9], 0, m[2], m[6], m[10], 0, m[3], m[7], m[11], 0, 0, 0, 0, 1 } end function Mat4.fromRows(v: { number }, at: number?): M4 local o = (at or 1) - 1 local m = table.create(16, 0) for r = 0, 3 do for c = 0, 3 do m[c * 4 + r + 1] = v[o + r * 4 + c + 1] or (if r == c then 1 else 0) end end return m end function Mat4.toRows(m: M4): { number } local v = table.create(16, 0) for r = 0, 3 do for c = 0, 3 do v[r * 4 + c + 1] = m[c * 4 + r + 1] end end return v end function Mat4.point(m: M4, x: number, y: number, z: number): (number, number, number) return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] end function Mat4.normalMatrix(m: M4): M4 local inv = Mat4.inverse({ m[1], m[2], m[3], 0, m[5], m[6], m[7], 0, m[9], m[10], m[11], 0, 0, 0, 0, 1 }) if not inv then return Mat4.identity() end return Mat4.transpose3(inv) end return Mat4 end __FILES["codecs/model/MeshFlatten"] = function() -- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). local Types = __include("Types") local Flatten = {} local readf32, readf64 = buffer.readf32, buffer.readf64 local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 local readi8, readi16, readi32 = buffer.readi8, buffer.readi16, buffer.readi32 local SIZE = Types.COMPONENT_SIZE -- normalized integer types: their scale (raw / scale = the normalized value) local NORM: { [string]: number } = { unorm8 = 255, unorm16 = 65535, snorm8 = 127, snorm16 = 32767 } type Attr = { type: string, components: number, raw: boolean, values: { number }, } type PartInfo = { prim: Types.Primitive, mesh: Types.Mesh?, node: Types.Node?, firstVertex: number, vertexCount: number, firstFace: number, faceCount: number, identity: boolean, } type Merged = { count: number, attrs: { [string]: Attr }, sizes: { number }?, corners: { number }, parts: { PartInfo }, } function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?) if type(acc) ~= "table" or type(acc.data) ~= "buffer" then return nil, "accessor without a data buffer" end local t, comps, count = acc.type, acc.components, acc.count local size = SIZE[t] if size == nil then return nil, "unknown accessor type " .. tostring(t) end if type(comps) ~= "number" or type(count) ~= "number" or comps < 1 or comps > 16 or count < 0 or comps % 1 ~= 0 or count % 1 ~= 0 then return nil, "bad accessor components / count" end local n = count * comps local d: buffer = acc.data if buffer.len(d) < n * size then return nil, "accessor data shorter than count * components" end local out = table.create(n) :: { number } if t == "f32" then for i = 0, n - 1 do out[i + 1] = readf32(d, i * 4) end elseif t == "f64" then for i = 0, n - 1 do out[i + 1] = readf64(d, i * 8) end elseif t == "u8" or t == "unorm8" then for i = 0, n - 1 do out[i + 1] = readu8(d, i) end elseif t == "u16" or t == "unorm16" then for i = 0, n - 1 do out[i + 1] = readu16(d, i * 2) end elseif t == "u32" then for i = 0, n - 1 do out[i + 1] = readu32(d, i * 4) end elseif t == "i8" or t == "snorm8" then for i = 0, n - 1 do out[i + 1] = readi8(d, i) end elseif t == "i16" or t == "snorm16" then for i = 0, n - 1 do out[i + 1] = readi16(d, i * 2) end else -- i32 for i = 0, n - 1 do out[i + 1] = readi32(d, i * 4) end end local scale = NORM[t] if scale and not raw then local signed = t == "snorm8" or t == "snorm16" for i = 1, n do local v = out[i] / scale out[i] = if signed and v < -1 then -1 else v end end return out, nil end local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } local mul = Types.Scene.mul local function numList(v: any, n: number): boolean if type(v) ~= "table" then return false end for i = 1, n do if type(v[i]) ~= "number" then return false end end return true end local function localMatrix(node: any): ({ number }?, string?) if node.matrix ~= nil then if not numList(node.matrix, 16) then return nil, "node matrix is not 16 numbers" end local m = table.create(16) :: { number } for i = 1, 16 do m[i] = node.matrix[i] end return m, nil end local t, q, s = node.translation, node.rotation, node.scale if t == nil and q == nil and s == nil then return nil, nil end if (t ~= nil and not numList(t, 3)) or (q ~= nil and not numList(q, 4)) or (s ~= nil and not numList(s, 3)) then return nil, "bad node translation / rotation / scale" end local x, y, z, w = 0, 0, 0, 1 if q then x, y, z, w = q[1], q[2], q[3], q[4] end local sx, sy, sz = 1, 1, 1 if s then sx, sy, sz = s[1], s[2], s[3] end local tx, ty, tz = 0, 0, 0 if t then tx, ty, tz = t[1], t[2], t[3] end return { (1 - 2 * (y * y + z * z)) * sx, (2 * (x * y + z * w)) * sx, (2 * (x * z - y * w)) * sx, 0, (2 * (x * y - z * w)) * sy, (1 - 2 * (x * x + z * z)) * sy, (2 * (y * z + x * w)) * sy, 0, (2 * (x * z + y * w)) * sz, (2 * (y * z - x * w)) * sz, (1 - 2 * (x * x + y * y)) * sz, 0, tx, ty, tz, 1, }, nil end local function isIdentity(m: { number }): boolean for i = 1, 16 do if m[i] ~= IDENTITY[i] then return false end end return true end type Instance = { prim: Types.Primitive, mesh: Types.Mesh?, node: Types.Node?, matrix: { number }? } local function instances(scene: any): ({ Instance }?, string?) local out: { Instance } = {} local nodes, meshes = scene.nodes, scene.meshes if type(nodes) ~= "table" or type(meshes) ~= "table" then return nil, "scene without nodes / meshes tables" end local function addMesh(mi: any, node: Types.Node?, m: { number }?): string? local mesh = meshes[mi] if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then return "node refers to a missing mesh " .. tostring(mi) end for _, prim in mesh.primitives do if type(prim) ~= "table" or type(prim.attributes) ~= "table" then return "bad primitive" end table.insert(out, { prim = prim, mesh = mesh, node = node, matrix = m }) end return nil end local visiting: { [number]: boolean } = {} local function visit(ni: any, parent: { number }?, depth: number): string? local node = nodes[ni] if type(node) ~= "table" then return "missing node " .. tostring(ni) end if depth > 256 or visiting[ni] then return "node hierarchy is cyclic or too deep" end visiting[ni] = true local m, merr = localMatrix(node) if merr then return merr end local world = if m and parent then mul(parent, m) elseif m then m else parent if node.mesh ~= nil then local e = addMesh(node.mesh, node, world) if e then return e end end if type(node.children) == "table" then for _, c in node.children do local e = visit(c, world, depth + 1) if e then return e end end end visiting[ni] = nil return nil end local roots = scene.roots if type(roots) == "table" and #roots > 0 then for _, ri in roots do local e = visit(ri, nil, 0) if e then return nil, e end end elseif #nodes > 0 then local isChild: { [number]: boolean } = {} for _, n in nodes do if type(n) == "table" and type(n.children) == "table" then for _, c in n.children do isChild[c] = true end end end for i = 1, #nodes do if not isChild[i] then local e = visit(i, nil, 0) if e then return nil, e end end end else for i = 1, #meshes do local e = addMesh(i, nil, nil) if e then return nil, e end end end return out, nil end local function faces(prim: any, nv: number): (any, any, string?) local mode = prim.mode or "triangles" if mode == "points" then return "points", nil, nil elseif mode == "lines" or mode == "line_strip" or mode == "line_loop" then return "skip", nil, nil end local idx: { number } if prim.indices ~= nil then local v, err = Flatten.numbers(prim.indices, true) if not v then return nil, nil, "indices: " .. tostring(err) end idx = v else idx = table.create(nv) :: { number } for i = 1, nv do idx[i] = i - 1 end end for i = 1, #idx do local v = idx[i] if v < 0 or v >= nv or v % 1 ~= 0 then return nil, nil, string.format("index %s out of range (%d vertices)", tostring(v), nv) end end if mode == "triangles" then local n = #idx - #idx % 3 if n ~= #idx then local c = table.create(n) :: { number } table.move(idx, 1, n, 1, c) idx = c end return false, idx, nil elseif mode == "polygons" then if prim.faces == nil then return nil, nil, "polygons primitive without faces" end local sizes, err = Flatten.numbers(prim.faces, true) if not sizes then return nil, nil, "faces: " .. tostring(err) end local total = 0 for i = 1, #sizes do local s = sizes[i] if s < 0 or s % 1 ~= 0 then return nil, nil, "bad face size" end total += s end if total ~= #idx then return nil, nil, "face sizes do not add up to the index count" end return sizes, idx, nil elseif mode == "triangle_strip" or mode == "triangle_fan" then local c = {} for i = 3, #idx do if mode == "triangle_fan" then table.insert(c, idx[1]) table.insert(c, idx[i - 1]) table.insert(c, idx[i]) elseif i % 2 == 1 then table.insert(c, idx[i - 2]) table.insert(c, idx[i - 1]) table.insert(c, idx[i]) else table.insert(c, idx[i - 1]) table.insert(c, idx[i - 2]) table.insert(c, idx[i]) end end return false, c, nil end return nil, nil, "unknown primitive mode " .. tostring(mode) end -- the fill value of a missing attribute component: colours default to opaque white, everything else to 0 local function fill(name: string, t: string, raw: boolean): number if string.sub(name, 1, 6) ~= "COLOR_" then return 0 end return if raw and NORM[t] then NORM[t] else 1 end local function f32(v: number): number local b = buffer.create(4) buffer.writef32(b, 0, v) return buffer.readf32(b, 0) end function Flatten.merge(scene: any, keep: (string) -> boolean, opts: { triangulate: boolean? }?): (Merged?, string?) if type(scene) ~= "table" then return nil, "not a scene" end local list, lerr = instances(scene) if not list then return nil, lerr end local triangulate = opts and opts.triangulate or false local types: { [string]: string } = {} local comps: { [string]: number } = {} local used: { Instance } = {} for _, inst in list do local mode = inst.prim.mode or "triangles" if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" then local pos = inst.prim.attributes.POSITION if type(pos) ~= "table" then return nil, "primitive without POSITION" end table.insert(used, inst) for name, acc in inst.prim.attributes do if type(name) == "string" and (name == "POSITION" or keep(name)) and type(acc) == "table" then local t = acc.type if types[name] == nil then types[name] = t elseif types[name] ~= t then types[name] = "f32" end comps[name] = math.max(comps[name] or 0, tonumber(acc.components) or 0) end end end end if (comps.POSITION or 3) < 3 then return nil, "POSITION needs 3 components" end local attrs: { [string]: Attr } = {} for name, t in types do local raw = NORM[t] ~= nil if name == "POSITION" or name == "NORMAL" then raw = false end attrs[name] = { type = if name == "POSITION" or name == "NORMAL" then "f32" else t, components = if name == "POSITION" or name == "NORMAL" then 3 else comps[name], raw = raw, values = {} } end local merged: Merged = { count = 0, attrs = attrs, sizes = nil, corners = {}, parts = {} } local sizes: { number } = {} local anyFaces = false local corners = merged.corners for _, inst in used do local prim: any = inst.prim local posAcc = prim.attributes.POSITION local nv = tonumber(posAcc.count) or 0 local m = inst.matrix local identity = m == nil or isIdentity(m :: { number }) local info: PartInfo = { prim = prim, mesh = inst.mesh, node = inst.node, firstVertex = merged.count, vertexCount = nv, firstFace = #sizes, faceCount = 0, identity = identity } for name, a in attrs do local acc = prim.attributes[name] local dst = a.values local n0 = #dst local ac = a.components if acc == nil then local f = fill(name, a.type, a.raw) for i = 1, nv * ac do dst[n0 + i] = f end else if acc.count ~= nv then return nil, name .. " count differs from POSITION" end local vals, err = Flatten.numbers(acc, a.raw and acc.type == a.type) if not vals then return nil, name .. ": " .. tostring(err) end local sc = acc.components if a.raw and acc.type ~= a.type then return nil, name .. ": mixed accessor types" end local f = fill(name, a.type, a.raw) if name == "POSITION" and not identity then local mm = m :: { number } for i = 0, nv - 1 do local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3] dst[n0 + i * 3 + 1] = f32(mm[1] * x + mm[5] * y + mm[9] * z + mm[13]) dst[n0 + i * 3 + 2] = f32(mm[2] * x + mm[6] * y + mm[10] * z + mm[14]) dst[n0 + i * 3 + 3] = f32(mm[3] * x + mm[7] * y + mm[11] * z + mm[15]) end elseif name == "NORMAL" and not identity and sc >= 3 then local mm = m :: { number } -- the cofactor matrix of the upper 3x3 = det * inverse transpose; the sign of det keeps the direction local a1, a2, a3, b1, b2, b3, c1, c2, c3 = mm[1], mm[2], mm[3], mm[5], mm[6], mm[7], mm[9], mm[10], mm[11] local n11, n12, n13 = b2 * c3 - b3 * c2, b3 * c1 - b1 * c3, b1 * c2 - b2 * c1 local n21, n22, n23 = c2 * a3 - c3 * a2, c3 * a1 - c1 * a3, c1 * a2 - c2 * a1 local n31, n32, n33 = a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1 local sgn = if a1 * n11 + a2 * n12 + a3 * n13 < 0 then -1 else 1 for i = 0, nv - 1 do local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3] -- column j of the cofactor matrix multiplies component j: (inverse transpose) * n local nx = n11 * x + n21 * y + n31 * z local ny = n12 * x + n22 * y + n32 * z local nz = n13 * x + n23 * y + n33 * z local l = math.sqrt(nx * nx + ny * ny + nz * nz) if l > 0 then nx, ny, nz = sgn * nx / l, sgn * ny / l, sgn * nz / l end dst[n0 + i * 3 + 1] = f32(nx) dst[n0 + i * 3 + 2] = f32(ny) dst[n0 + i * 3 + 3] = f32(nz) end else for i = 0, nv - 1 do for c = 1, ac do dst[n0 + i * ac + c] = if c <= sc then vals[i * sc + c] else f end end end end end local fs, cs, ferr = faces(prim, nv) if ferr then return nil, ferr end local flip = false if not identity then local mm = m :: { number } local det = mm[1] * (mm[6] * mm[11] - mm[7] * mm[10]) - mm[5] * (mm[2] * mm[11] - mm[3] * mm[10]) + mm[9] * (mm[2] * mm[7] - mm[3] * mm[6]) flip = det < 0 end if fs ~= "points" and fs ~= "skip" then anyFaces = true local base = merged.count local cl: { number } = cs local p = 0 local nf = if fs then #fs else #cl // 3 for f = 1, nf do local s = if fs then fs[f] else 3 if triangulate then for k = 2, s - 1 do table.insert(sizes, 3) local a, b, c = cl[p + 1], cl[p + k], cl[p + k + 1] if flip then b, c = c, b end table.insert(corners, base + a) table.insert(corners, base + b) table.insert(corners, base + c) end else table.insert(sizes, s) if flip then table.insert(corners, base + cl[p + 1]) for k = s, 2, -1 do table.insert(corners, base + cl[p + k]) end else for k = 1, s do table.insert(corners, base + cl[p + k]) end end end p += s end end info.faceCount = #sizes - info.firstFace merged.count += nv table.insert(merged.parts, info) end merged.sizes = if anyFaces then sizes else nil return merged, nil end return Flatten end __FILES["codecs/model/Minecraft"] = function() -- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. local Types = __include("Types") local Nbt = __include("codecs/text/Nbt") local Colors = __include("codecs/model/Minecraft/Colors") local Legacy = __include("codecs/model/Minecraft/Legacy") local Packed = __include("codecs/model/Minecraft/Packed") local Minecraft = {} Minecraft.Packed = Packed Minecraft.Legacy = Legacy function Minecraft.parseState(s: string): (string, { { string } }) local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$") local n = name or "" if n ~= "" and not string.find(n, ":", 1, true) then n = "minecraft:" .. n end local props = {} local body = rest and string.match(rest :: string, "^%[(.*)%]%s*$") if body then for pair in string.gmatch(body, "[^,]+") do local k, v = string.match(pair, "^%s*([^=%s]+)%s*=%s*(.-)%s*$") if k then table.insert(props, { k, v :: string }) end end end return n, props end function Minecraft.stateString(name: string, props: { any }?): string if not props or next(props) == nil then return name end local parts = {} if props[1] ~= nil then for _, kv in props do table.insert(parts, kv[1] .. "=" .. tostring(kv[2])) end else for _, k in Types.keys(props) do table.insert(parts, tostring(k) .. "=" .. tostring((props :: any)[k])) end end return name .. "[" .. table.concat(parts, ",") .. "]" end function Minecraft.stateFromNbt(c: any): string? if type(c) ~= "table" or type(c.Name) ~= "string" then return nil end local props = {} if type(c.Properties) == "table" then for _, k in Types.keys(c.Properties) do local v = c.Properties[k] table.insert(props, { k, if type(v) == "string" then v else tostring(Nbt.number(v) or v) }) end end return Minecraft.stateString(c.Name, props) end function Minecraft.stateToNbt(s: string): { [string]: any } local name, props = Minecraft.parseState(s) local c = Types.object({ Name = name }, { "Name" }) if #props > 0 then local p, keys = {}, {} for _, kv in props do p[kv[1]] = kv[2] table.insert(keys, kv[1]) end Types.set(c, "Properties", Types.object(p, keys)) end return c end function Minecraft.baseName(s: string): string local name = string.match(s, "^%s*([^%[%s]*)") or "" return string.match(name, ":(.*)$") or name end local AIR = { air = true, cave_air = true, void_air = true, structure_void = true, light = true, barrier = true, moving_piston = true } function Minecraft.isAir(s: string): boolean return AIR[Minecraft.baseName(s)] == true end local function hex(h: string): { number } local c = { tonumber(string.sub(h, 1, 2), 16) or 0, tonumber(string.sub(h, 3, 4), 16) or 0, tonumber(string.sub(h, 5, 6), 16) or 0, 255 } if #h >= 8 then c[4] = tonumber(string.sub(h, 7, 8), 16) or 255 end return c end local function list(s: string): { { number } } local out = {} for h in string.gmatch(s, "%x+") do table.insert(out, hex(h)) end return out end local EXACT: { [string]: { number } } = {} for name, h in string.gmatch(Colors.BLOCKS, "([%w_]+)=(%x+)") do EXACT[name :: string] = hex(h :: string) end local WOOL, CONCRETE, TERRACOTTA = list(Colors.WOOL), list(Colors.CONCRETE), list(Colors.TERRACOTTA) local PLANKS, BARK, LEAVES = list(Colors.PLANKS), list(Colors.BARK), list(Colors.LEAVES) -- longest prefixes first, so light_blue wins over blue and dark_oak over oak local function byLength(names: { string }): { { any } } local out: { { any } } = {} for i, n in names do table.insert(out, { n, i }) end table.sort(out, function(a: { any }, b: { any }): boolean return #(a[1] :: string) > #(b[1] :: string) end) return out end local DYES, WOODS = byLength(Colors.DYES), byLength(Colors.WOODS) local SUFFIXES = { "_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign", "_fence_gate", "_fence", "_pressure_plate", "_button", "_trapdoor", "_door", "_stairs", "_slab", "_wall", "_pane", "_carpet", "_wall_banner", "_banner", "_bars", } local PREFIXES = { "waxed_", "potted_", "flowing_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" } local CORAL: { [string]: { number } } = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") } local FALLBACK = hex("909090") local function mix(c: { number }, w: { number }, t: number): { number } return { math.floor(c[1] + (w[1] - c[1]) * t + 0.5), math.floor(c[2] + (w[2] - c[2]) * t + 0.5), math.floor(c[3] + (w[3] - c[3]) * t + 0.5), c[4] } end local resolve: (string, number) -> { number }? local function family(n: string): { number }? for _, d in DYES do local pre = d[1] .. "_" if string.sub(n, 1, #pre) == pre then local rest = string.sub(n, #pre + 1) local i = d[2] if rest == "concrete" then return CONCRETE[i] elseif rest == "concrete_powder" then return mix(CONCRETE[i], { 255, 255, 255, 255 }, 0.2) elseif rest == "terracotta" then return TERRACOTTA[i] elseif string.find(rest, "glass", 1, true) then local c = table.clone(WOOL[i]) c[4] = 0x80 return c end return WOOL[i] end end local stripped = string.match(n, "^stripped_(.*)$") for _, w in WOODS do local pre = w[1] .. "_" local m = stripped or n if string.sub(m, 1, #pre) == pre then local rest = string.sub(m, #pre + 1) local i = w[2] if stripped then return PLANKS[i] elseif rest == "log" or rest == "wood" or rest == "stem" or rest == "hyphae" then return BARK[i] elseif rest == "leaves" or rest == "sapling" or rest == "propagule" then return LEAVES[i] elseif rest == "block" and w[1] == "bamboo" then return EXACT.bamboo_block end return PLANKS[i] end end return nil end local function keywords(n: string): { number }? if string.find(n, "copper", 1, true) then return if string.find(n, "oxidized", 1, true) then EXACT.oxidized_copper elseif string.find(n, "weathered", 1, true) then EXACT.weathered_copper elseif string.find(n, "exposed", 1, true) then EXACT.exposed_copper else EXACT.copper_block elseif string.find(n, "coral", 1, true) then if string.find(n, "dead", 1, true) then return hex("857e79") end for k, c in CORAL do if string.find(n, k, 1, true) then return c end end elseif string.find(n, "_ore$") then return if string.find(n, "deepslate", 1, true) then EXACT.deepslate elseif string.find(n, "nether", 1, true) then EXACT.netherrack else EXACT.stone end for _, k in { "deepslate", "blackstone", "sandstone", "prismarine", "purpur", "quartz", "glass", "ice", "stone", "brick", "nether", "end", "mushroom", "grass", "candle", "head", "skull", "rail", "sign", "tulip", "orchid" } do if string.find(n, k, 1, true) then local alias = ({ glass = "glass", ice = "ice", stone = "stone", brick = "bricks", nether = "nether_bricks", ["end"] = "end_stone", mushroom = "mushroom_stem", grass = "short_grass", candle = "white_wool", head = "polished_andesite", skull = "bone_block", rail = "rail", sign = "oak_planks", tulip = "red_tulip", orchid = "blue_orchid", deepslate = "deepslate", blackstone = "blackstone", sandstone = "sandstone", prismarine = "prismarine", purpur = "purpur_block", quartz = "quartz_block" } :: any)[k] return EXACT[alias] end end return nil end resolve = function(n: string, depth: number): { number }? if depth > 4 then return nil end local c = EXACT[n] if c then return c end local renamed = Legacy.RENAMED[n] if renamed then return resolve(renamed, depth + 1) end for _, p in PREFIXES do if string.sub(n, 1, #p) == p then return resolve(string.sub(n, #p + 1), depth + 1) end end c = family(n) if c then return c end for _, sfx in SUFFIXES do if #n > #sfx and string.sub(n, -#sfx) == sfx then local base = string.sub(n, 1, #n - #sfx) for _, form in { base, base .. "s", base .. "_block", base .. "_planks" } do local fc = EXACT[form] or family(form) if fc then return fc end end return resolve(base, depth + 1) end end return keywords(n) end local cache: { [string]: { number } | false } = {} function Minecraft.color(s: string): { number }? local hit = cache[s] if hit ~= nil then return hit or nil end local name, props = Minecraft.parseState(s) local n = string.match(name, ":(.*)$") or name local res: { number }? = nil if not AIR[n] then local variants = Legacy.VARIANTS[n] or (if n == "double_wooden_slab" then Legacy.VARIANTS.planks else nil) if variants then local data = 0 for _, kv in props do if kv[1] == "data" then data = tonumber(kv[2]) or 0 end end local v = variants[data % (Legacy.MASK[n] or 16) + 1] or variants[1] res = resolve(v, 0) end res = res or resolve(n, 0) or FALLBACK end cache[s] = res or false return res end local REVERSE: { [string]: { number } }? = nil local function reverse(): { [string]: { number } } if REVERSE then return REVERSE end local r: { [string]: { number } } = {} local byName: { [string]: number } = {} for i, n in Legacy.NAMES do if n ~= "-" then byName[n] = i - 1 end end for legacy, modern in Legacy.RENAMED do r[modern] = { byName[legacy], 0 } end for legacy, variants in Legacy.VARIANTS do for d, v in variants do if r[v] == nil then r[v] = { byName[legacy], d - 1 } end end end for n, id in byName do if r[n] == nil then r[n] = { id, 0 } end end REVERSE = r return r end -- the rest of the data value stays as [data=N], so legacyId gives it back exactly function Minecraft.legacyState(id: number, data: number): string local n = Legacy.NAMES[id + 1] if n == nil or n == "-" then return "minecraft:legacy_" .. id .. (if data ~= 0 then "[data=" .. data .. "]" else "") end local variants = Legacy.VARIANTS[n] if variants then local idx = data % (Legacy.MASK[n] or 16) local v = variants[idx + 1] if v then return "minecraft:" .. v .. (if data ~= idx then "[data=" .. data .. "]" else "") end end return "minecraft:" .. (Legacy.RENAMED[n] or n) .. (if data ~= 0 then "[data=" .. data .. "]" else "") end function Minecraft.legacyId(s: string): (number?, number?) local name, props = Minecraft.parseState(s) local n = string.match(name, ":(.*)$") or name local id: number?, data = nil, 0 local lid = string.match(n, "^legacy_(%d+)$") if lid then id = tonumber(lid) else local e = reverse()[n] if e then id, data = e[1], e[2] end end if id == nil then return nil, nil end for _, kv in props do if kv[1] == "data" then data = (tonumber(kv[2]) or data) % 16 end end return id, data end function Minecraft.voxels(sx: number, sy: number, sz: number, states: { string }, indices: buffer): Types.Voxels local v = Types.Voxels.new(sx, sy, sz) local lut = buffer.create(#states) local slots: { [string]: number } = {} local used = 0 for i, s in states do local c = Minecraft.color(s) local slot = 0 if c then local key = string.format("%d,%d,%d,%d", c[1], c[2], c[3], c[4]) slot = slots[key] if not slot then if used < 255 then used += 1 slot = used v.palette[slot] = { c[1], c[2], c[3], c[4] } else local best, bd = 1, math.huge for k = 1, 255 do local p = v.palette[k] local d = (p[1] - c[1]) ^ 2 + (p[2] - c[2]) ^ 2 + (p[3] - c[3]) ^ 2 + (p[4] - c[4]) ^ 2 if d < bd then best, bd = k, d end end slot = best end slots[key] = slot end end buffer.writeu8(lut, i - 1, slot) end local n = sx * sy * sz local data, nstates = v.data, #states for i = 0, n - 1 do local s = buffer.readu16(indices, i * 2) buffer.writeu8(data, i, if s < nstates then buffer.readu8(lut, s) else 0) end v.blocks = { palette = states, data = indices } return v end local CANDIDATES: { { any } }? = nil local function candidates(): { { any } } if CANDIDATES then return CANDIDATES end local out = {} for _, d in Colors.DYES do for _, kind in { "wool", "concrete", "terracotta" } do local s = "minecraft:" .. d .. "_" .. kind table.insert(out, { s, Minecraft.color(s) }) end end for _, w in Colors.WOODS do local s = "minecraft:" .. w .. "_planks" table.insert(out, { s, Minecraft.color(s) }) end for _, n in { "stone", "cobblestone", "bricks", "sand", "red_sand", "dirt", "grass_block", "gravel", "deepslate", "sandstone", "quartz_block", "obsidian", "netherrack", "end_stone", "prismarine", "dark_prismarine", "snow_block", "gold_block", "iron_block", "diamond_block", "emerald_block", "lapis_block", "redstone_block", "coal_block", "glowstone", "sponge", "melon", "pumpkin", "hay_block", "bone_block", "clay", "packed_ice", "nether_bricks", "purpur_block", "andesite", "diorite", "granite", "calcite", "tuff", "blackstone", "mud", "moss_block", "amethyst_block", "copper_block", "oxidized_copper" } do local s = "minecraft:" .. n table.insert(out, { s, Minecraft.color(s) }) end CANDIDATES = out return out end function Minecraft.nearestBlock(c: { number }): string local a = c[4] or 255 if a < 200 then local best, bd = "minecraft:glass", math.huge for i, d in Colors.DYES do local w = WOOL[i] local dist = (w[1] - c[1]) ^ 2 + (w[2] - c[2]) ^ 2 + (w[3] - c[3]) ^ 2 if dist < bd then best, bd = "minecraft:" .. d .. "_stained_glass", dist end end return best end local best, bd = "minecraft:stone", math.huge for _, cand in candidates() do local k = cand[2] local dist = (k[1] - c[1]) ^ 2 + (k[2] - c[2]) ^ 2 + (k[3] - c[3]) ^ 2 if dist < bd then best, bd = cand[1], dist end end return best end function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any) local n = v.size[1] * v.size[2] * v.size[3] local b = v.blocks if b then if type(b.palette) ~= "table" or type(b.data) ~= "buffer" or buffer.len(b.data) < n * 2 then return nil, "voxels.blocks must hold a palette and a u16 per cell" end if #b.palette == 0 or #b.palette > 65536 then return nil, "voxels.blocks.palette must have 1 .. 65536 states" end return b.palette, b.data end local states = { "minecraft:air" } local slotOf: { [number]: number } = { [0] = 0 } local byState: { [string]: number } = { ["minecraft:air"] = 0 } local out = buffer.create(n * 2) local data = v.data for i = 0, n - 1 do local p = buffer.readu8(data, i) local s = slotOf[p] if s == nil then local col = v.palette[p] or { 128, 128, 128, 255 } local st = Minecraft.nearestBlock(col) s = byState[st] if s == nil then table.insert(states, st) s = #states - 1 byState[st] = s end slotOf[p] = s end buffer.writeu16(out, i * 2, s :: number) end return states, out end -- block entities: Sponge v3 { pos = { x, y, z }, id, data } <-> flat { x, y, z, id, ... } (MCEdit, Litematica, -- chunks) / Sponge v1 / v2 { Pos, Id, ... } local function int(v: any): number? local n = Nbt.number(v) if n == nil or n ~= n or n % 1 ~= 0 then return nil end return n end local function ints(v: any): { number }? if Nbt.isTag(v) and v.type == "intArray" then return v.value elseif type(v) == "table" and not Nbt.isTag(v) and (v :: any)[1] ~= nil then local out: { number } = {} for i, x in v :: { any } do out[i] = Nbt.number(x) or 0 end return out end return nil end Minecraft.int = int Minecraft.ints = ints local function rest(c: any, skip: { [string]: boolean }): { [string]: any } local out, keys = {}, {} for _, k in Types.keys(c) do if not skip[k] then out[k] = c[k] table.insert(keys, k) end end return Types.object(out, keys) end local FLAT_SKIP = { x = true, y = true, z = true, id = true } local POS_SKIP = { Pos = true, Id = true } function Minecraft.blockEntity(c: any, style: string): any if type(c) ~= "table" or Nbt.isTag(c) then return nil end if style == "flat" then return { pos = { int(c.x) or 0, int(c.y) or 0, int(c.z) or 0 }, id = if type(c.id) == "string" then c.id else nil, data = rest(c, FLAT_SKIP) } end local p = ints(c.Pos) or { 0, 0, 0 } local data = if style == "data" then (if type(c.Data) == "table" then c.Data else Types.object()) else rest(c, POS_SKIP) return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data } end function Minecraft.flatBlockEntity(be: any, style: string): any local o = Types.object() local data = if type(be.data) == "table" then be.data else Types.object() if style == "flat" then Types.set(o, "x", be.pos[1]) Types.set(o, "y", be.pos[2]) Types.set(o, "z", be.pos[3]) if be.id then Types.set(o, "id", be.id) end for _, k in Types.keys(data) do if not FLAT_SKIP[k] then Types.set(o, k, data[k]) end end return o end Types.set(o, "Pos", Nbt.intArray({ be.pos[1], be.pos[2], be.pos[3] })) if be.id then Types.set(o, "Id", be.id) end if style == "data" then Types.set(o, "Data", data) else for _, k in Types.keys(data) do if not POS_SKIP[k] then Types.set(o, k, data[k]) end end end return o end return Minecraft end __FILES["codecs/model/Minecraft/Colors"] = function() -- codecs/model/Minecraft/Colors: default Minecraft block colours as name=rrggbb or name=rrggbbaa. -- Hand-picked approximations; no game assets or wiki tables copied. local Colors = {} Colors.BLOCKS = [[ stone=7d7d7d granite=956756 polished_granite=9a6a59 diorite=bcbcbc polished_diorite=c0c0c2 andesite=888889 polished_andesite=848686 grass_block=6d9a3f dirt=866043 coarse_dirt=77553b podzol=5b3f18 rooted_dirt=90674c mud=3c3a3d cobblestone=7a7a7a bedrock=555555 sand=dbcf9f red_sand=be6621 gravel=837f7e suspicious_sand=d6c996 suspicious_gravel=817c7b sandstone=d8cb9b chiseled_sandstone=d8ca9b cut_sandstone=d9cd9e smooth_sandstone=dfd5a5 red_sandstone=b5621f cut_red_sandstone=bc6620 chiseled_red_sandstone=b7601e smooth_red_sandstone=b5621f sponge=c3c04a wet_sponge=aaab3c glass=c0f5fe50 tinted_glass=2c262ec0 lapis_block=1f438c gold_block=f6d03d iron_block=dcdcdc diamond_block=62ede4 emerald_block=2acb57 redstone_block=af1805 coal_block=101010 netherite_block=433e40 copper_block=c06c50 exposed_copper=a17e68 weathered_copper=6c9a6f oxidized_copper=52a284 cut_copper=bf6b51 raw_iron_block=a6896b raw_gold_block=dda92e raw_copper_block=9a6a4e amethyst_block=8562b8 budding_amethyst=84609f bricks=976253 bookshelf=75603d chiseled_bookshelf=b29159 mossy_cobblestone=6e7660 obsidian=0f0a18 crying_obsidian=200a3c tnt=db4130 spawner=24364a chest=a0742d trapped_chest=a0742d ender_chest=2a3b3c crafting_table=81633c furnace=6d6d6d snow=f9fefe snow_block=f9fefe powder_snow=f8fdfd ice=92b8fec8 packed_ice=8db4fa blue_ice=74a7fd frosted_ice=8cb4fac8 clay=a0a6b3 pumpkin=c6761a carved_pumpkin=c27118 jack_o_lantern=d79a32 netherrack=612626 soul_sand=513e32 soul_soil=4b3a2e basalt=505055 polished_basalt=636367 smooth_basalt=48484e glowstone=ab8354 magma_block=8e3f1f nether_bricks=2c1518 red_nether_bricks=450709 cracked_nether_bricks=281417 chiseled_nether_bricks=2f171c nether_wart_block=720202 warped_wart_block=167879 end_stone=dbdea0 end_stone_bricks=dae0a2 purpur_block=a97ea9 purpur_pillar=ab81ab prismarine=63a29a prismarine_bricks=63ab9e dark_prismarine=335b4b sea_lantern=acc7be hay_block=a68b0c terracotta=985e43 quartz_block=ebe5de smooth_quartz=ece6df quartz_bricks=eae5dd quartz_pillar=ebe6e0 chiseled_quartz_block=e7e2da smooth_stone=9e9e9e stone_bricks=7a7979 mossy_stone_bricks=737969 cracked_stone_bricks=767676 chiseled_stone_bricks=777777 deepslate=505053 cobbled_deepslate=4d4d51 polished_deepslate=484849 deepslate_bricks=474747 cracked_deepslate_bricks=414141 deepslate_tiles=373737 cracked_deepslate_tiles=343434 chiseled_deepslate=363637 reinforced_deepslate=505350 tuff=6c6d67 polished_tuff=626a63 tuff_bricks=626660 calcite=dfe0dc dripstone_block=866b5c pointed_dripstone=816757 moss_block=596d2d moss_carpet=596d2d pale_moss_block=6b7069 melon=6f9118 cactus=587f28 sugar_cane=95c165 bamboo=5d8f1e bamboo_block=7f9030 stripped_bamboo_block=c0ad50 water=3f76e4b4 bubble_column=3f76e4b4 lava=cf5b14 short_grass=5b8a32 grass=5b8a32 tall_grass=5b8a32 fern=586e30 large_fern=586e30 dead_bush=6b4f29 vine=3c6e18 glow_lichen=708079 lily_pad=208030 seagrass=307b16 tall_seagrass=307b16 kelp=3b7f22 kelp_plant=3b7f22 dried_kelp_block=323b27 red_mushroom_block=c82e2d brown_mushroom_block=957051 mushroom_stem=cbc4b9 red_mushroom=d84a3e brown_mushroom=9a7759 slime_block=6fc05bc8 honey_block=fba92fc8 honeycomb_block=e5941e bone_block=e1ddc9 shroomlight=f19346 target=e2aa9e respawn_anchor=4b1e86 lodestone=939599 blackstone=2a2328 polished_blackstone=35303b polished_blackstone_bricks=302a32 cracked_polished_blackstone_bricks=2c2629 chiseled_polished_blackstone=35303b gilded_blackstone=382b26 crimson_nylium=831f1f warped_nylium=2b7265 crimson_roots=7e0812 warped_roots=148a7c packed_mud=8e6b50 mud_bricks=89684f sculk=0d1e24 sculk_catalyst=2d3a3b sculk_sensor=074654 sculk_shrieker=c6cdab redstone_lamp=5f361e note_block=58392a jukebox=5d4030 beacon=75dcd7 observer=626262 piston=9a8d6c sticky_piston=8b9c66 piston_head=9a8d6c dispenser=7a7a7a dropper=7a7a7a hopper=434343 anvil=444444 chipped_anvil=444444 damaged_anvil=444444 cauldron=4a4a4a rail=7d6c4b powered_rail=8a6d3e detector_rail=7b6853 activator_rail=74574b ladder=7c5f35 scaffolding=aa8449 lantern=6a5b54 soul_lantern=4a6366 campfire=6e5638 soul_campfire=4e5d5d barrel=86643b smoker=5a5853 blast_furnace=6c6b6b cartography_table=685032 fletching_table=c5b485 smithing_table=39394a loom=8e7965 stonecutter=7b7672 grindstone=8e8e8e composter=704a26 beehive=b8945b bee_nest=c5964b farmland=8f6646 dirt_path=94793f mycelium=6f6365 torch=ffd80060 wall_torch=ffd80060 soul_torch=6be1e360 redstone_torch=c0210f60 redstone_wire=9e0b0060 lever=6e6e6e60 cobweb=e4e9ea80 iron_bars=8b8d8b90 chain=3a404e90 end_rod=e0d8d0 chorus_plant=5e395e chorus_flower=977a97 dragon_egg=0c0910 end_portal_frame=5b7860 enchanting_table=813838 brewing_stand=7a654f flower_pot=7d4536 cake=f8dede conduit=9f8b71 lectern=ad8a54 bell=fdd533 decorated_pot=8f4f35 crafter=7a6c64 trial_spawner=3b4a55 vault=46545c heavy_core=4c5056 command_block=b5886c chain_command_block=829f8f repeating_command_block=8370b0 structure_block=58475b jigsaw=50455a dandelion=e0c41c poppy=c42b1a blue_orchid=2aa8d0 allium=b878e8 azure_bluet=dfe6d7 red_tulip=c43b1b orange_tulip=e07e1b white_tulip=e0e8db pink_tulip=e8b8d8 oxeye_daisy=e8e8c8 cornflower=4f76d8 lily_of_the_valley=e8e8e8 wither_rose=2a2c18 sunflower=f0c71d lilac=b88cb8 rose_bush=b02a1e peony=e8b8e0 torchflower=d9b14e pitcher_plant=7a97c8 pink_petals=f0b8d0 spore_blossom=d066a8 azalea=5f7a2c flowering_azalea=7c6b6e sweet_berry_bush=3f6a2f cocoa=8c5428 wheat=a99c30 carrots=4a9a1e potatoes=4c9a2a beetroots=5a8a2a nether_wart=8a1818 crimson_fungus=8a2525 warped_fungus=2a7a6e twisting_vines=148a7c weeping_vines=8a1414 hanging_roots=a17561 big_dripleaf=6b8f34 small_dripleaf=6b8f34 cave_vines=5a6d23 frogspawn=66605ca0 sniffer_egg=8a5045 turtle_egg=dcd8b8 sea_pickle=6a7030 mangrove_roots=4b3c27 muddy_mangrove_roots=46413a ochre_froglight=f6e8a6 verdant_froglight=dcf0d6 pearlescent_froglight=f1e1ea creaking_heart=5a4a3c resin_block=d9661c resin_bricks=ce5a1a ]] Colors.DYES = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" } Colors.WOOL = "e9ecec f07613 bd44b3 3aafd9 f8c527 70b919 ed8dac 3e4447 8e8e86 158991 792aac 35399d 724728 546d1b a12722 141519" Colors.CONCRETE = "cfd5d6 e06100 a9309f 2389c6 f0af15 5ea818 d5658e 36393d 7d7d73 157788 64209c 2c2e8f 603b1f 495b24 8e2020 080a0f" Colors.TERRACOTTA = "d1b2a1 a15325 95576c 716c89 ba8523 677534 a14e4e 392a23 876a61 575b5b 764656 4a3b5b 4d3323 4c532a 8f3d2e 251610" Colors.WOODS = { "oak", "spruce", "birch", "jungle", "acacia", "dark_oak", "mangrove", "cherry", "pale_oak", "bamboo", "crimson", "warped" } Colors.PLANKS = "a2834f 735531 c0af79 a07351 a85a32 432b14 763631 e3b3ad e4d9d3 c1ad50 653147 2b6963" Colors.BARK = "6d5533 3a2510 d8d7d2 55441a 676157 3e2f17 543a26 371b22 524a46 7f9030 5c1919 3a3a4d" Colors.LEAVES = "4a7a20 3d5d3d 5f8a3c 3f8a1c 4b7a1e 3c6a18 4b8a28 e5adc2 878d76 5d8f1e 831f1f 2b7265" return Colors end __FILES["codecs/model/Minecraft/Legacy"] = function() -- codecs/model/Minecraft/Legacy: pre-1.13 numeric block ids and their data-value variants. -- From the Minecraft wiki "Java Edition data values/Pre-flattening" (facts, not code). local Legacy = {} local function words(s: string): { string } local out = {} for w in string.gmatch(s, "%S+") do table.insert(out, w) end return out end -- ids 0 .. 255 (NAMES[id + 1]), "-" = unused Legacy.NAMES = words([[air stone grass dirt cobblestone planks sapling bedrock flowing_water water flowing_lava lava sand gravel gold_ore iron_ore coal_ore log leaves sponge glass lapis_ore lapis_block dispenser sandstone noteblock bed golden_rail detector_rail sticky_piston web tallgrass deadbush piston piston_head wool piston_extension yellow_flower red_flower brown_mushroom red_mushroom gold_block iron_block double_stone_slab stone_slab brick_block tnt bookshelf mossy_cobblestone obsidian torch fire mob_spawner oak_stairs chest redstone_wire diamond_ore diamond_block crafting_table wheat farmland furnace lit_furnace standing_sign wooden_door ladder rail stone_stairs wall_sign lever stone_pressure_plate iron_door wooden_pressure_plate redstone_ore lit_redstone_ore unlit_redstone_torch redstone_torch stone_button snow_layer ice snow cactus clay reeds jukebox fence pumpkin netherrack soul_sand glowstone portal lit_pumpkin cake unpowered_repeater powered_repeater stained_glass trapdoor monster_egg stonebrick brown_mushroom_block red_mushroom_block iron_bars glass_pane melon_block pumpkin_stem melon_stem vine fence_gate brick_stairs stone_brick_stairs mycelium waterlily nether_brick nether_brick_fence nether_brick_stairs nether_wart enchanting_table brewing_stand cauldron end_portal end_portal_frame end_stone dragon_egg redstone_lamp lit_redstone_lamp double_wooden_slab wooden_slab cocoa sandstone_stairs emerald_ore ender_chest tripwire_hook tripwire emerald_block spruce_stairs birch_stairs jungle_stairs command_block beacon cobblestone_wall flower_pot carrots potatoes wooden_button skull anvil trapped_chest light_weighted_pressure_plate heavy_weighted_pressure_plate unpowered_comparator powered_comparator daylight_detector redstone_block quartz_ore hopper quartz_block quartz_stairs activator_rail dropper stained_hardened_clay stained_glass_pane leaves2 log2 acacia_stairs dark_oak_stairs slime barrier iron_trapdoor prismarine sea_lantern hay_block carpet hardened_clay coal_block packed_ice double_plant standing_banner wall_banner daylight_detector_inverted red_sandstone red_sandstone_stairs double_stone_slab2 stone_slab2 spruce_fence_gate birch_fence_gate jungle_fence_gate dark_oak_fence_gate acacia_fence_gate spruce_fence birch_fence jungle_fence dark_oak_fence acacia_fence spruce_door birch_door jungle_door acacia_door dark_oak_door end_rod chorus_plant chorus_flower purpur_block purpur_pillar purpur_stairs purpur_double_slab purpur_slab end_bricks beetroots grass_path end_gateway repeating_command_block chain_command_block frosted_ice magma nether_wart_block red_nether_brick bone_block structure_void observer white_shulker_box orange_shulker_box magenta_shulker_box light_blue_shulker_box yellow_shulker_box lime_shulker_box pink_shulker_box gray_shulker_box silver_shulker_box cyan_shulker_box purple_shulker_box blue_shulker_box brown_shulker_box green_shulker_box red_shulker_box black_shulker_box white_glazed_terracotta orange_glazed_terracotta magenta_glazed_terracotta light_blue_glazed_terracotta yellow_glazed_terracotta lime_glazed_terracotta pink_glazed_terracotta gray_glazed_terracotta silver_glazed_terracotta cyan_glazed_terracotta purple_glazed_terracotta blue_glazed_terracotta brown_glazed_terracotta green_glazed_terracotta red_glazed_terracotta black_glazed_terracotta concrete concrete_powder - - structure_block]]) -- one-to-one renames only, so the way back is exact (lit_furnace, powered_repeater, ... keep their legacy names) Legacy.RENAMED = { grass = "grass_block", brick_block = "bricks", stonebrick = "stone_bricks", hardened_clay = "terracotta", melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block", red_nether_brick = "red_nether_bricks", nether_brick = "nether_bricks", end_bricks = "end_stone_bricks", mob_spawner = "spawner", web = "cobweb", snow_layer = "snow", snow = "snow_block", noteblock = "note_block", quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad", tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone", stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion", fence = "oak_fence", fence_gate = "oak_fence_gate", wooden_door = "oak_door", trapdoor = "oak_trapdoor", wooden_pressure_plate = "oak_pressure_plate", wooden_button = "oak_button", stone_stairs = "cobblestone_stairs", standing_sign = "oak_sign", wall_sign = "oak_wall_sign", golden_rail = "powered_rail", portal = "nether_portal", piston_extension = "moving_piston", silver_shulker_box = "light_gray_shulker_box", silver_glazed_terracotta = "light_gray_glazed_terracotta", monster_egg = "infested_stone", standing_banner = "white_banner", wall_banner = "white_wall_banner", skull = "skeleton_skull", bed = "red_bed", } :: { [string]: string } -- legacy names whose data value selects the variant: the modern names by data value (0-based) local DYED = "white orange magenta light_blue yellow lime pink gray light_gray cyan purple blue brown green red black" local function dyed(suffix: string): { string } local out = {} for i, d in words(DYED) do out[i] = d .. "_" .. suffix end return out end Legacy.VARIANTS = { stone = { "stone", "granite", "polished_granite", "diorite", "polished_diorite", "andesite", "polished_andesite" }, dirt = { "dirt", "coarse_dirt", "podzol" }, planks = { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks" }, wooden_slab = { "oak_slab", "spruce_slab", "birch_slab", "jungle_slab", "acacia_slab", "dark_oak_slab" }, sapling = { "oak_sapling", "spruce_sapling", "birch_sapling", "jungle_sapling", "acacia_sapling", "dark_oak_sapling" }, sand = { "sand", "red_sand" }, log = { "oak_log", "spruce_log", "birch_log", "jungle_log" }, -- data % 4 log2 = { "acacia_log", "dark_oak_log" }, leaves = { "oak_leaves", "spruce_leaves", "birch_leaves", "jungle_leaves" }, leaves2 = { "acacia_leaves", "dark_oak_leaves" }, sponge = { "sponge", "wet_sponge" }, sandstone = { "sandstone", "chiseled_sandstone", "cut_sandstone" }, red_sandstone = { "red_sandstone", "chiseled_red_sandstone", "cut_red_sandstone" }, stonebrick = { "stone_bricks", "mossy_stone_bricks", "cracked_stone_bricks", "chiseled_stone_bricks" }, quartz_block = { "quartz_block", "chiseled_quartz_block", "quartz_pillar" }, prismarine = { "prismarine", "prismarine_bricks", "dark_prismarine" }, cobblestone_wall = { "cobblestone_wall", "mossy_cobblestone_wall" }, red_flower = { "poppy", "blue_orchid", "allium", "azure_bluet", "red_tulip", "orange_tulip", "white_tulip", "pink_tulip", "oxeye_daisy" }, double_plant = { "sunflower", "lilac", "tall_grass", "large_fern", "rose_bush", "peony" }, wool = dyed("wool"), carpet = dyed("carpet"), stained_glass = dyed("stained_glass"), stained_glass_pane = dyed("stained_glass_pane"), stained_hardened_clay = dyed("terracotta"), concrete = dyed("concrete"), concrete_powder = dyed("concrete_powder"), } :: { [string]: { string } } Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } :: { [string]: number } return Legacy end __FILES["codecs/model/Minecraft/Packed"] = @native function() -- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code. -- Minecraft wiki "Chunk format", Sponge / Litematica schematic specs: little-endian int64 longs of bits-wide indices, -- spanning long boundaries (Litematica, chunks before 1.16) or floor(64 / bits) per long plus padding (since 1.16). local Packed = {} local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 local writeu8, writeu16 = buffer.writeu8, buffer.writeu16 local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshift, bit32.lshift, bit32.bor @native function Packed.longsNeeded(count: number, bits: number, spanning: boolean): number if spanning then return (count * bits + 63) // 64 end local per = 64 // bits return (count + per - 1) // per end @native function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boolean, out: buffer, max: number): (boolean, string?) if bits < 1 or bits > 16 then return false, "unsupported: " .. bits .. "-bit packed indices" end local need = Packed.longsNeeded(count, bits, spanning) if buffer.len(longs) < need * 8 then return false, "packed array too short (" .. buffer.len(longs) // 8 .. " longs, need " .. need .. ")" end if buffer.len(out) < count * 2 then return false, "output too small" end local n = need * 8 local src = buffer.create(n + 4) buffer.copy(src, 0, longs, 0, n) if spanning then local p = 0 for i = 0, count - 1 do local v = extract(readu32(src, rshift(p, 3)), band(p, 7), bits) if v >= max then return false, "index " .. v .. " past the palette (" .. max .. ")" end writeu16(out, i * 2, v) p += bits end else local per = 64 // bits local i = 0 local base = 0 while i < count do local p = 0 for _ = 1, per do if i >= count then break end local v = extract(readu32(src, base + rshift(p, 3)), band(p, 7), bits) if v >= max then return false, "index " .. v .. " past the palette (" .. max .. ")" end writeu16(out, i * 2, v) i += 1 p += bits end base += 8 end end return true, nil end @native function Packed.pack(indices: buffer, count: number, bits: number, spanning: boolean): buffer local need = Packed.longsNeeded(count, bits, spanning) local out = buffer.create(need * 8 + 4) local per = 64 // bits for i = 0, count - 1 do local v = readu16(indices, i * 2) local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits local at = rshift(p, 3) local sh = band(p, 7) local x = lshift(v, sh) for k = 0, 2 do local bits8 = band(rshift(x, k * 8), 0xff) if bits8 ~= 0 then writeu8(out, at + k, bor(readu8(out, at + k), bits8)) end end end local res = buffer.create(need * 8) buffer.copy(res, 0, out, 0, need * 8) return res end @native function Packed.bitsFor(n: number, min: number): number local b = min while lshift(1, b) < n and b < 31 do b += 1 end return b end -- Sponge BlockData: unsigned LEB128 varints @native function Packed.varints(src: buffer, offset: number, length: number, count: number, out: buffer, max: number): (boolean, string?) if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then return false, "bad varint array arguments" end local p, e = offset, offset + length for i = 0, count - 1 do local v, sh = 0, 0 while true do if p >= e then return false, "truncated: block data ends after " .. i .. " of " .. count .. " entries" end local c = readu8(src, p) p += 1 v += band(c, 0x7f) * 2 ^ sh if c < 128 then break end sh += 7 if sh > 28 then return false, "varint too long" end end if v >= max then return false, "index " .. v .. " past the palette (" .. max .. ")" end writeu16(out, i * 2, v) end return true, nil end @native function Packed.toVarints(indices: buffer, count: number): buffer local out = buffer.create(count * 3) local p = 0 for i = 0, count - 1 do local v = readu16(indices, i * 2) while v >= 128 do writeu8(out, p, band(v, 0x7f) + 128) p += 1 v = rshift(v, 7) end writeu8(out, p, v) p += 1 end local res = buffer.create(p) buffer.copy(res, 0, out, 0, p) return res end -- nibble arrays: Minecraft low nibble first; WorldEdit AddBlocks high nibble first @native function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolean): number local b = readu8(src, offset + rshift(i, 1)) local odd = band(i, 1) == 1 if odd == highFirst then return band(b, 15) end return rshift(b, 4) end @native function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, highFirst: boolean) local at = offset + rshift(i, 1) local b = readu8(dst, at) local odd = band(i, 1) == 1 if odd == highFirst then writeu8(dst, at, bor(band(b, 0xf0), band(v, 15))) else writeu8(dst, at, bor(band(b, 0x0f), lshift(band(v, 15), 4))) end end -- Minecraft order: x fastest, then z, then y (schematics, chunk sections) @native function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: buffer?, ox: number?, oy: number?, oz: number?, dsx: number?, dsy: number?): buffer local out = dst or buffer.create(sx * sy * sz * 2) local bx, by, bz = ox or 0, oy or 0, oz or 0 local wx, wy = dsx or sx, dsy or sy local i = 0 for y = 0, sy - 1 do for z = 0, sz - 1 do local d = (bx + wx * ((by + y) + wy * (bz + z))) * 2 for _ = 0, sx - 1 do writeu16(out, d, readu16(src, i)) i += 2 d += 2 end end end return out end @native function Packed.toYzx(src: buffer, sx: number, sy: number, sz: number): buffer local out = buffer.create(sx * sy * sz * 2) local i = 0 for y = 0, sy - 1 do for z = 0, sz - 1 do local s = (sx * (y + sy * z)) * 2 for _ = 0, sx - 1 do writeu16(out, i, readu16(src, s)) i += 2 s += 2 end end end return out end return Packed end __FILES["codecs/model/Patch"] = @native function() -- 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 @native function Patch.valid(w: number, h: number, n: number): boolean 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 @native function Patch.grid(ctrl: { number }, w: number, h: number, comps: number, levelU: number, levelV: number, maxPoints: number?): ({ number }?, number, number) local lu, lv = math.max(1, math.floor(levelU)), math.max(1, math.floor(levelV)) if not Patch.valid(w, h, #ctrl // comps) or #ctrl ~= w * h * comps then return nil, 0, 0 end local px, py = (w - 1) // 2, (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) :: { number } for gy = 0, gh - 1 do local sy = math.min(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(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 = if j == 0 then bv0 elseif j == 1 then bv1 else bv2 local row = ((sy * 2 + j) * w + sx * 2) * comps for i = 0, 2 do local wgt = bv * (if i == 0 then bu0 elseif i == 1 then bu1 else bu2) local c = row + i * comps for k = 1, comps do out[o + k] += ctrl[c + k] * wgt 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 @native function Patch.triangles(gw: number, gh: number): { number } local out = table.create(math.max(0, (gw - 1) * (gh - 1) * 6)) :: { number } 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 @native function Patch.normalize(pts: { number }, comps: number, at: number) 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 @native function Patch.normals(pts: { number }, comps: number, gw: number, gh: number): { number } local out = table.create(gw * gh * 3, 0) :: { number } @native local function at(x: number, y: number, k: number): number 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, i // gw for _, d in { { 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() -- codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code. -- After D. Eberly, "Triangulation by Ear Clipping" (no code taken). local Polygon = {} type Pt = { x: number, y: number, loop: number, index: number } local function area(pts: { Pt }): number local a = 0 local n = #pts for i = 1, n do local p, q = pts[i], pts[i % n + 1] a += p.x * q.y - q.x * p.y end return a / 2 end local function inside(pts: { Pt }, x: number, y: number): boolean local c = false local n = #pts local j = n for i = 1, n do local a, b = pts[i], pts[j] if (a.y > y) ~= (b.y > y) and x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x then c = not c end j = i end return c end local function cross(o: Pt, a: Pt, b: Pt): number return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) end local function crosses(p1: Pt, p2: Pt, q1: Pt, q2: Pt): boolean if (p1.x == q1.x and p1.y == q1.y) or (p1.x == q2.x and p1.y == q2.y) or (p2.x == q1.x and p2.y == q1.y) or (p2.x == q2.x and p2.y == q2.y) then return false end local d1, d2 = cross(q1, q2, p1), cross(q1, q2, p2) local d3, d4 = cross(p1, p2, q1), cross(p1, p2, q2) return ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0)) end local function visible(m: Pt, v: Pt, rings: { { Pt } }): boolean for _, r in rings do local n = #r for i = 1, n do if crosses(m, v, r[i], r[i % n + 1]) then return false end end end return true end local function bridge(outer: { Pt }, h: { Pt }, others: { { Pt } }): { Pt } local mi = 1 for i, p in h do if p.x > h[mi].x then mi = i end end local m = h[mi] local best, bestD = 0, math.huge for pass = 1, 2 do for i, v in outer do if pass == 2 or v.x >= m.x then local d = (v.x - m.x) ^ 2 + (v.y - m.y) ^ 2 if d < bestD and visible(m, v, others) then best, bestD = i, d end end end if best > 0 then break end end if best == 0 then best = 1 end local out: { Pt } = {} for i = 1, best do table.insert(out, outer[i]) end local n = #h for k = 0, n do table.insert(out, h[(mi - 1 + k) % n + 1]) end for i = best, #outer do table.insert(out, outer[i]) end return out end local function inTri(a: Pt, b: Pt, c: Pt, p: Pt): boolean return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0 end local function clip(ring: { Pt }, out: { number }) local pts = table.clone(ring) local guard = #pts * #pts + 16 while #pts > 3 and guard > 0 do guard -= 1 local n = #pts local found, bestI, bestScore = 0, 1, -math.huge for i = 1, n do local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1] local cr = cross(a, b, c) if cr > 0 then local ok = true for k = 1, n do local p = pts[k] if p ~= a and p ~= b and p ~= c and not (p.x == b.x and p.y == b.y) and not (p.x == a.x and p.y == a.y) and not (p.x == c.x and p.y == c.y) and inTri(a, b, c, p) then ok = false break end end if ok then found = i break end end if cr > bestScore then bestI, bestScore = i, cr end end local i = if found > 0 then found else bestI local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1] if cross(a, b, c) ~= 0 then table.insert(out, a.loop) table.insert(out, a.index) table.insert(out, b.loop) table.insert(out, b.index) table.insert(out, c.loop) table.insert(out, c.index) end table.remove(pts, i) end if #pts == 3 and cross(pts[1], pts[2], pts[3]) > 0 then for k = 1, 3 do table.insert(out, pts[k].loop) table.insert(out, pts[k].index) end end end function Polygon.triangulate(loops: { { number } }): { number } local rings: { { Pt } } = {} local areas: { number } = {} for li, l in loops do local pts: { Pt } = {} for k = 1, #l - 1, 2 do local x, y = l[k], l[k + 1] if type(x) == "number" and type(y) == "number" and x == x and y == y then table.insert(pts, { x = x, y = y, loop = li, index = (k + 1) // 2 }) end end local a = if #pts >= 3 then area(pts) else 0 if a ~= 0 then table.insert(rings, pts) table.insert(areas, math.abs(a)) if a < 0 then -- counter-clockwise for now; holes are flipped below local r: { Pt } = {} for k = #pts, 1, -1 do table.insert(r, pts[k]) end rings[#rings] = r end end end local n = #rings local depth, parent = table.create(n, 0), table.create(n, 0) for i = 1, n do local p = rings[i][1] for j = 1, n do if j ~= i and areas[j] > areas[i] and inside(rings[j], p.x, p.y) then depth[i] += 1 if parent[i] == 0 or areas[j] < areas[parent[i]] then parent[i] = j end end end end local holes: { [number]: { number } } = {} for i = 1, n do if depth[i] % 2 == 1 and parent[i] > 0 then local list = holes[parent[i]] or {} holes[parent[i]] = list table.insert(list, i) end end local out: { number } = {} for i = 1, n do if depth[i] % 2 == 0 then local ring = rings[i] local hs = holes[i] if hs then table.sort(hs, function(a: number, b: number): boolean local ma, mb = -math.huge, -math.huge for _, p in rings[a] do ma = math.max(ma, p.x) end for _, p in rings[b] do mb = math.max(mb, p.x) end return ma > mb end) local flipped: { { Pt } } = {} for _, h in hs do local r: { Pt } = {} local src = rings[h] for k = #src, 1, -1 do table.insert(r, src[k]) end table.insert(flipped, r) end for k, h in flipped do local others: { { Pt } } = { ring } for k2 = k + 1, #flipped do table.insert(others, flipped[k2]) end ring = bridge(ring, h, others) end end clip(ring, out) end end return out end return Polygon end __FILES["codecs/model/Rbx"] = function() -- codecs/model/Rbx: the Roblox instance tree and property values shared by model/rbxm and model/rbxmx. -- Written from the rbx-dom format notes (docs/binary.md, docs/xml.md); checked against rbx-dom through rojo / lune. -- Faces: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32 -- Axes: bits X 1, Y 2, Z 4 -- UniqueId: 32 hex digits: random (16), time (8), index (8) local Rbx = {} type Value = { type: string, value: any } type Instance = { className: string, name: string, properties: { [string]: Value }, children: { Instance }, parent: Instance?, referent: string?, service: boolean?, -- a service (binary INST object format 1; rbxl roots) } type Tree = { kind: "rbxtree", roots: { Instance }, place: boolean, metadata: { [string]: string }, -- binary META / XML entries (ExplicitAutoJoints, ...) extra: { any }, meta: { source: { format: string, [string]: any }?, [string]: any }, } function Rbx.tree(place: boolean?): Tree return { kind = "rbxtree", roots = {}, place = place == true, metadata = {}, extra = {}, meta = {} } end function Rbx.instance(className: string, name: string?): Instance return { className = className, name = name or className, properties = {}, children = {} } end function Rbx.add(parent: any, child: Instance): Instance if parent.kind == "rbxtree" then child.parent = nil table.insert(parent.roots, child) else child.parent = parent table.insert(parent.children, child) end return child end function Rbx.set(inst: Instance, name: string, typ: string, value: any) inst.properties[name] = { type = typ, value = value } end function Rbx.get(inst: Instance, name: string): any local v = inst.properties[name] return if v then v.value else nil end function Rbx.descendants(root: any): () -> (Instance?, number?) local stack: { any } = {} local list = if root.kind == "rbxtree" then root.roots else root.children for i = #list, 1, -1 do table.insert(stack, { list[i], 1 }) end return function(): (Instance?, number?) local top = table.remove(stack) if not top then return nil, nil end local inst, depth = top[1], top[2] for i = #inst.children, 1, -1 do table.insert(stack, { inst.children[i], depth + 1 }) end return inst, depth end end function Rbx.list(tree: any): { Instance } local out = {} for inst in Rbx.descendants(tree) do table.insert(out, inst :: Instance) end return out end function Rbx.find(root: any, path: string): Instance? local cur: any = root for part in string.gmatch(path, "[^/]+") do local list = if cur.kind == "rbxtree" then cur.roots else cur.children local found = nil for _, c in list do if c.name == part then found = c break end end if not found then return nil end cur = found end return if cur.kind == "rbxtree" then nil else cur end function Rbx.fullName(inst: Instance): string local parts = {} local cur: Instance? = inst while cur do table.insert(parts, 1, cur.name) cur = cur.parent end return table.concat(parts, ".") end -- The binary format stores axis-aligned rotations as one byte: id = 6 * n(RightVector) + n(UpVector) + 1, where n is -- the NormalId of a unit axis (+X 0, +Y 1, +Z 2, -X 3, -Y 4, -Z 5) and the third column is their cross product. local AXES = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, { -1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } } local ROTATIONS: { [number]: { number } } = {} for a = 0, 5 do for b = 0, 5 do if a % 3 ~= b % 3 then local r, u = AXES[a + 1], AXES[b + 1] local k = { r[2] * u[3] - r[3] * u[2], r[3] * u[1] - r[1] * u[3], r[1] * u[2] - r[2] * u[1] } -- columns: right, up, back (= right x up) ROTATIONS[6 * a + b + 1] = { r[1], u[1], k[1] + 0, r[2], u[2], k[2] + 0, r[3], u[3], k[3] + 0 } end end end Rbx.ROTATIONS = ROTATIONS local function axisIndex(x: number, y: number, z: number): number? for i, a in AXES do if a[1] == x and a[2] == y and a[3] == z then return i - 1 end end return nil end function Rbx.rotationId(cf: { number }): number local a = axisIndex(cf[4], cf[7], cf[10]) local b = axisIndex(cf[5], cf[8], cf[11]) if not a or not b then return 0 end local id = 6 * a + b + 1 local rot = ROTATIONS[id] if not rot or rot[3] ~= cf[6] or rot[6] ~= cf[9] or rot[9] ~= cf[12] then return 0 end return id end -- binary type ids (rbx-dom docs/binary.md) by type name, and back Rbx.TYPE_IDS = table.freeze({ String = 0x01, BinaryString = 0x01, ProtectedString = 0x01, ContentId = 0x01, Bool = 0x02, Int32 = 0x03, Float32 = 0x04, Float64 = 0x05, UDim = 0x06, UDim2 = 0x07, Ray = 0x08, Faces = 0x09, Axes = 0x0A, BrickColor = 0x0B, Color3 = 0x0C, Vector2 = 0x0D, Vector3 = 0x0E, Vector2int16 = 0x0F, CFrame = 0x10, Enum = 0x12, Ref = 0x13, Vector3int16 = 0x14, NumberSequence = 0x15, ColorSequence = 0x16, NumberRange = 0x17, Rect = 0x18, PhysicalProperties = 0x19, Color3uint8 = 0x1A, Int64 = 0x1B, SharedString = 0x1C, Bytecode = 0x1D, OptionalCFrame = 0x1E, UniqueId = 0x1F, Font = 0x20, SecurityCapabilities = 0x21, Content = 0x22, } :: { [string]: number }) local NAMES: { [number]: string } = {} for name, id in Rbx.TYPE_IDS do if NAMES[id] == nil or name == "String" then NAMES[id] = name end end Rbx.TYPE_NAMES = table.freeze(NAMES) -- BrickColor 194 (Medium stone grey) is Roblox's default local IDENTITY_CF = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } function Rbx.default(typ: string): any if typ == "String" or typ == "BinaryString" or typ == "ProtectedString" or typ == "ContentId" or typ == "Bytecode" or typ == "SharedString" then return "" elseif typ == "Bool" then return false elseif typ == "BrickColor" then return 194 elseif typ == "UDim" or typ == "NumberRange" or typ == "Vector2" or typ == "Vector2int16" then return { 0, 0 } elseif typ == "UDim2" or typ == "Rect" then return { 0, 0, 0, 0 } elseif typ == "Vector3" or typ == "Vector3int16" or typ == "Color3" or typ == "Color3uint8" then return { 0, 0, 0 } elseif typ == "Ray" then return { 0, 0, 0, 0, 0, 0 } elseif typ == "CFrame" then return table.clone(IDENTITY_CF) elseif typ == "NumberSequence" then return { { 0, 0, 0 }, { 1, 0, 0 } } elseif typ == "ColorSequence" then return { { 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0 } } elseif typ == "UniqueId" then return string.rep("0", 32) elseif typ == "Font" then return { family = "rbxasset://fonts/families/SourceSansPro.json", weight = 400, style = "Normal" } elseif typ == "PhysicalProperties" or typ == "Ref" or typ == "OptionalCFrame" or typ == "Content" then return nil end return 0 end Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString = true, ContentId = true, Bytecode = true } :: { [string]: boolean }) return Rbx end __FILES["codecs/model/Rbx/Binary"] = @native function() -- codecs/model/Rbx/Binary: the property column codecs of the Roblox binary format (rbx-dom docs/binary.md). -- PROP columns: byte-interleaved big-endian values, zigzag signed integers, rotated floats, delta-coded referents. local Rbx = __include("codecs/model/Rbx") local Bytes = __include("core/Bytes") local Binary = {} local readu8, readu16, readi16, readu32, readf32, readf64 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readf32, buffer.readf64 local writeu32, readstring = buffer.writeu32, buffer.readstring local writef32 = buffer.writef32 local floor = math.floor local scratch = buffer.create(8) local TWO32 = 4294967296 -- the rotated float encoding: bits rotated left by one (sign in bit 0) @native local function unrotate(x: number): number writeu32(scratch, 0, x // 2 + (x % 2) * 2147483648) return readf32(scratch, 0) end @native local function rotate(v: number): number writef32(scratch, 0, v) local bits = readu32(scratch, 0) return (bits * 2) % TWO32 + bits // 2147483648 end @native local function unzigzag(x: number): number return if x % 2 == 0 then x // 2 else -(x + 1) // 2 end @native local function zigzag32(v: number): number v = floor(v) return (if v >= 0 then v * 2 else -v * 2 - 1) % TWO32 end @native local function u32s(b: buffer, p: number, n: number): { number } local out = table.create(n, 0) local n2, n3 = n * 2, n * 3 for i = 0, n - 1 do out[i + 1] = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + n2 + i) * 256 + readu8(b, p + n3 + i) end return out end @native local function i32s(b: buffer, p: number, n: number): { number } local out = u32s(b, p, n) for i = 1, n do out[i] = unzigzag(out[i]) end return out end @native local function f32s(b: buffer, p: number, n: number): { number } local out = u32s(b, p, n) for i = 1, n do out[i] = unrotate(out[i]) end return out end @native local function i64s(b: buffer, p: number, n: number): { number } local out = table.create(n, 0) for i = 0, n - 1 do local hi = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + 2 * n + i) * 256 + readu8(b, p + 3 * n + i) local lo = readu8(b, p + 4 * n + i) * 16777216 + readu8(b, p + 5 * n + i) * 65536 + readu8(b, p + 6 * n + i) * 256 + readu8(b, p + 7 * n + i) local half = hi * 2147483648 + lo // 2 out[i + 1] = if lo % 2 == 0 then half else -half - 1 end return out end @native local function putU32s(w: Bytes.Writer, vals: { number }) local n = #vals local p = w:reserve(4 * n) local b = w.buf for i = 0, n - 1 do local v = vals[i + 1] % TWO32 buffer.writeu8(b, p + i, v // 16777216) buffer.writeu8(b, p + n + i, (v // 65536) % 256) buffer.writeu8(b, p + 2 * n + i, (v // 256) % 256) buffer.writeu8(b, p + 3 * n + i, v % 256) end w.pos = p + 4 * n end @native local function putI32s(w: Bytes.Writer, vals: { number }) local t = table.create(#vals, 0) for i, v in vals do t[i] = zigzag32(v) end putU32s(w, t) end @native local function putF32s(w: Bytes.Writer, vals: { number }) local t = table.create(#vals, 0) for i, v in vals do t[i] = rotate(v) end putU32s(w, t) end @native local function putI64s(w: Bytes.Writer, vals: { number }) local n = #vals local p = w:reserve(8 * n) local b = w.buf for i = 0, n - 1 do local v = floor(vals[i + 1]) local z = if v >= 0 then v * 2 else -v * 2 - 1 local hi, lo = (z // TWO32) % TWO32, z % TWO32 buffer.writeu8(b, p + i, hi // 16777216) buffer.writeu8(b, p + n + i, (hi // 65536) % 256) buffer.writeu8(b, p + 2 * n + i, (hi // 256) % 256) buffer.writeu8(b, p + 3 * n + i, hi % 256) buffer.writeu8(b, p + 4 * n + i, lo // 16777216) buffer.writeu8(b, p + 5 * n + i, (lo // 65536) % 256) buffer.writeu8(b, p + 6 * n + i, (lo // 256) % 256) buffer.writeu8(b, p + 7 * n + i, lo % 256) end w.pos = p + 8 * n end -- referent arrays: zigzag i32, interleaved, each the difference from the previous one @native function Binary.readRefs(b: buffer, p: number, limit: number, n: number): ({ number }?, number) if n < 0 or p + 4 * n > limit then return nil, p end local out = i32s(b, p, n) local acc = 0 for i = 1, n do acc += out[i] out[i] = acc end return out, p + 4 * n end @native function Binary.writeRefs(w: Bytes.Writer, refs: { number }) local d = table.create(#refs, 0) local prev = 0 for i, r in refs do d[i] = r - prev prev = r end putI32s(w, d) end type Ctx = { ref: ((number) -> any)?, refOf: ((any) -> number)?, shared: { string }?, sharedIndex: ((string) -> number)?, } @native local function str(b: buffer, p: number, limit: number): (string?, number) if p + 4 > limit then return nil, p end local len = readu32(b, p) if p + 4 + len > limit then return nil, p end return readstring(b, p + 4, len), p + 4 + len end @native local function cframes(b: buffer, p: number, limit: number, n: number): ({ any }?, number) local rots: { { number } } = table.create(n) :: any for i = 1, n do if p >= limit then return nil, p end local id = readu8(b, p) p += 1 if id == 0 then if p + 36 > limit then return nil, p end local m = table.create(9, 0) for k = 0, 8 do m[k + 1] = readf32(b, p + 4 * k) end rots[i] = m p += 36 else local m = Rbx.ROTATIONS[id] if not m then return nil, -1 end rots[i] = m end end if p + 12 * n > limit then return nil, p end local xs, ys, zs = f32s(b, p, n), f32s(b, p + 4 * n, n), f32s(b, p + 8 * n, n) local out = table.create(n) for i = 1, n do local m = rots[i] out[i] = { xs[i], ys[i], zs[i], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9] } end return out, p + 12 * n end local FIXED: { [number]: number } = { [0x02] = 1, [0x03] = 4, [0x04] = 4, [0x05] = 8, [0x06] = 8, [0x07] = 16, [0x08] = 24, [0x09] = 1, [0x0A] = 1, [0x0B] = 4, [0x0C] = 12, [0x0D] = 8, [0x0E] = 12, [0x0F] = 4, [0x12] = 4, [0x13] = 4, [0x14] = 6, [0x17] = 8, [0x18] = 16, [0x1A] = 3, [0x1B] = 8, [0x1C] = 4, [0x1F] = 16, [0x21] = 8, } @native function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number, ctx: Ctx): ({ any }?, any) if limit > buffer.len(b) or p < 0 or n < 0 then return nil, "corrupt: bad ranges" end local size = FIXED[t] if size and p + size * n > limit then return nil, "truncated property values" end if t == 0x01 or t == 0x1D then local out = table.create(n, "") for i = 1, n do local s, q = str(b, p, limit) if not s then return nil, "truncated string" end out[i] = s p = q end return out, p elseif t == 0x02 then local out = table.create(n, false) for i = 1, n do out[i] = readu8(b, p + i - 1) ~= 0 end return out, p + n elseif t == 0x03 then return i32s(b, p, n), p + 4 * n elseif t == 0x04 then return f32s(b, p, n), p + 4 * n elseif t == 0x05 then local out = table.create(n, 0) for i = 1, n do out[i] = readf64(b, p + 8 * (i - 1)) end return out, p + 8 * n elseif t == 0x06 then local s, o = f32s(b, p, n), i32s(b, p + 4 * n, n) local out = table.create(n) for i = 1, n do out[i] = { s[i], o[i] } end return out, p + 8 * n elseif t == 0x07 then local xs, ys, xo, yo = f32s(b, p, n), f32s(b, p + 4 * n, n), i32s(b, p + 8 * n, n), i32s(b, p + 12 * n, n) local out = table.create(n) for i = 1, n do out[i] = { xs[i], xo[i], ys[i], yo[i] } end return out, p + 16 * n elseif t == 0x08 then local out = table.create(n) for i = 1, n do local q = p + 24 * (i - 1) out[i] = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12), readf32(b, q + 16), readf32(b, q + 20) } end return out, p + 24 * n elseif t == 0x09 or t == 0x0A then local out = table.create(n, 0) for i = 1, n do out[i] = readu8(b, p + i - 1) end return out, p + n elseif t == 0x0B or t == 0x12 then return u32s(b, p, n), p + 4 * n elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3 local cols: { { number } } = table.create(k) :: any for c = 1, k do cols[c] = f32s(b, p + 4 * n * (c - 1), n) end local out = table.create(n) for i = 1, n do local v = table.create(k, 0) for c = 1, k do v[c] = cols[c][i] end out[i] = v end return out, p + 4 * k * n elseif t == 0x0F or t == 0x14 then local k = if t == 0x0F then 2 else 3 local out = table.create(n) for i = 1, n do local q = p + 2 * k * (i - 1) out[i] = if k == 2 then { readi16(b, q), readi16(b, q + 2) } else { readi16(b, q), readi16(b, q + 2), readi16(b, q + 4) } end return out, p + 2 * k * n elseif t == 0x10 then local out, q = cframes(b, p, limit, n) if not out then return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values" end return out, q elseif t == 0x13 then local refs, q = Binary.readRefs(b, p, limit, n) if not refs then return nil, "truncated referents" end local out = table.create(n) local ref = ctx.ref for i = 1, n do out[i] = if ref and refs[i] >= 0 then ref(refs[i]) else nil end return out, q elseif t == 0x15 or t == 0x16 then local k = if t == 0x15 then 3 else 5 local out = table.create(n) for i = 1, n do if p + 4 > limit then return nil, "truncated sequence" end local count = readu32(b, p) p += 4 if p + count * 4 * k > limit then return nil, "truncated sequence" end local seq = table.create(count) for j = 1, count do local key = table.create(k, 0) for c = 1, k do key[c] = readf32(b, p + 4 * (c - 1)) end seq[j] = key p += 4 * k end out[i] = seq end return out, p elseif t == 0x17 then local out = table.create(n) for i = 1, n do out[i] = { readf32(b, p + 8 * (i - 1)), readf32(b, p + 8 * (i - 1) + 4) } end return out, p + 8 * n elseif t == 0x19 then local out = table.create(n) for i = 1, n do if p >= limit then return nil, "truncated physical properties" end local flag = readu8(b, p) p += 1 if flag % 2 == 1 then local k = if flag // 2 % 2 == 1 then 6 else 5 if p + 4 * k > limit then return nil, "truncated physical properties" end local v = table.create(6, 1) -- acoustic absorption 1 when the file leaves it out for c = 1, k do v[c] = readf32(b, p + 4 * (c - 1)) end out[i] = v p += 4 * k elseif flag ~= 0 then return nil, "unknown" end end return out, p elseif t == 0x1A then local out = table.create(n) for i = 1, n do out[i] = { readu8(b, p + i - 1), readu8(b, p + n + i - 1), readu8(b, p + 2 * n + i - 1) } end return out, p + 3 * n elseif t == 0x1B or t == 0x21 then return i64s(b, p, n), p + 8 * n elseif t == 0x1C then local idx = u32s(b, p, n) local shared: { string } = ctx.shared or {} local out: { string } = table.create(n, "") for i = 1, n do local s = shared[idx[i] + 1] if s == nil then return nil, "corrupt: shared string index out of range" end out[i] = s end return out, p + 4 * n elseif t == 0x1E then if p >= limit or readu8(b, p) ~= 0x10 then return nil, "unknown" end local cfs, q = cframes(b, p + 1, limit, n) if not cfs then return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values" end if q + 1 + n > limit or readu8(b, q) ~= 0x02 then return nil, "truncated optional CFrame flags" end local out = table.create(n) for i = 1, n do out[i] = if readu8(b, q + i) ~= 0 then cfs[i] else nil end return out, q + 1 + n elseif t == 0x1F then local out = table.create(n, "") local hex = table.create(16, "") for i = 0, n - 1 do local by = table.create(16, 0) for k = 0, 15 do by[k + 1] = readu8(b, p + k * n + i) end -- bytes 8..15: the random part rotated left by one bit (as a 64-bit integer); undo it local carry = by[16] % 2 for k = 9, 16 do local v = by[k] by[k] = v // 2 + carry * 128 carry = v % 2 end for k = 1, 8 do hex[k] = string.format("%02x", by[8 + k]) end for k = 1, 8 do hex[8 + k] = string.format("%02x", by[k + 4 - (if k > 4 then 8 else 0)]) end out[i + 1] = table.concat(hex) end return out, p + 16 * n elseif t == 0x20 then local out = table.create(n) for i = 1, n do local fam, q = str(b, p, limit) if not fam or q + 3 > limit then return nil, "truncated font" end local weight, style = readu16(b, q), readu8(b, q + 2) local face, q2 = str(b, q + 3, limit) if not face then return nil, "truncated font" end out[i] = { family = fam, weight = weight, style = if style == 1 then "Italic" else "Normal", cachedFaceId = if face ~= "" then face else nil } p = q2 end return out, p elseif t == 0x22 then if p + 4 * n > limit then return nil, "truncated content" end local kinds = i32s(b, p, n) p += 4 * n if p + 4 > limit then return nil, "truncated content" end local nu = readu32(b, p) p += 4 local uris = table.create(math.min(nu, n)) for j = 1, nu do local s, q = str(b, p, limit) if not s then return nil, "truncated content" end uris[j] = s p = q end if p + 4 > limit then return nil, "truncated content" end local no = readu32(b, p) local objs, q = Binary.readRefs(b, p + 4, limit, no) if not objs or q + 4 > limit then return nil, "truncated content" end if readu32(b, q) ~= 0 then return nil, "unknown" -- external objects: kept raw end p = q + 4 local out = table.create(n) local iu, io = 1, 1 for i = 1, n do local k = kinds[i] if k == 1 then if iu > nu then return nil, "corrupt: content uri count" end out[i] = uris[iu] iu += 1 elseif k == 2 then if io > no then return nil, "corrupt: content object count" end local r = objs[io] out[i] = if ctx.ref and r >= 0 then ctx.ref(r) else nil io += 1 elseif k ~= 0 then return nil, "unknown" end end return out, p end return nil, "unknown" end @native local function num(v: any): number return if type(v) == "number" and v == v then v else 0 end @native local function column(vals: { any }, n: number, c: number): { number } local out = table.create(n, 0) for i = 1, n do local v = vals[i] out[i] = if type(v) == "table" then num(v[c]) else 0 end return out end @native local function putString(w: Bytes.Writer, s: string) w:u32le(#s) w:string(s) end @native local function putCFrames(w: Bytes.Writer, vals: { any }, n: number) for i = 1, n do local v = vals[i] local cf = if type(v) == "table" then v else { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } local id = Rbx.rotationId(cf) w:u8(id) if id == 0 then for k = 4, 12 do w:f32le(num(cf[k])) end end end putF32s(w, column(vals, n, 1)) putF32s(w, column(vals, n, 2)) putF32s(w, column(vals, n, 3)) end @native local function hexByte(s: string, i: number): number return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0 end @native function Binary.encode(t: number, vals: { any }, n: number, w: Bytes.Writer, ctx: Ctx): string? if t == 0x01 or t == 0x1D then for i = 1, n do local v = vals[i] putString(w, if type(v) == "string" then v else "") end elseif t == 0x02 then for i = 1, n do w:u8(if vals[i] then 1 else 0) end elseif t == 0x03 then local c = table.create(n, 0) for i = 1, n do c[i] = num(vals[i]) end putI32s(w, c) elseif t == 0x04 then local c = table.create(n, 0) for i = 1, n do c[i] = num(vals[i]) end putF32s(w, c) elseif t == 0x05 then for i = 1, n do w:f64le(num(vals[i])) end elseif t == 0x06 then putF32s(w, column(vals, n, 1)) putI32s(w, column(vals, n, 2)) elseif t == 0x07 then putF32s(w, column(vals, n, 1)) putF32s(w, column(vals, n, 3)) putI32s(w, column(vals, n, 2)) putI32s(w, column(vals, n, 4)) elseif t == 0x08 then for i = 1, n do local v = vals[i] for c = 1, 6 do w:f32le(if type(v) == "table" then num(v[c]) else 0) end end elseif t == 0x09 or t == 0x0A then for i = 1, n do w:u8(num(vals[i]) % 256) end elseif t == 0x0B or t == 0x12 then local c = table.create(n, 0) for i = 1, n do c[i] = floor(num(vals[i])) end putU32s(w, c) elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3 for c = 1, k do putF32s(w, column(vals, n, c)) end elseif t == 0x0F or t == 0x14 then local k = if t == 0x0F then 2 else 3 for i = 1, n do local v = vals[i] for c = 1, k do local x = floor(if type(v) == "table" then num(v[c]) else 0) % 65536 w:u16le(x) end end elseif t == 0x10 then putCFrames(w, vals, n) elseif t == 0x13 then local refs = table.create(n, -1) local refOf = ctx.refOf for i = 1, n do refs[i] = if refOf and vals[i] ~= nil then refOf(vals[i]) else -1 end Binary.writeRefs(w, refs) elseif t == 0x15 or t == 0x16 then local k = if t == 0x15 then 3 else 5 for i = 1, n do local seq = vals[i] if type(seq) ~= "table" then seq = {} end w:u32le(#seq) for _, key in seq do for c = 1, k do w:f32le(if type(key) == "table" then num(key[c]) else 0) end end end elseif t == 0x17 then for i = 1, n do local v = vals[i] w:f32le(if type(v) == "table" then num(v[1]) else 0) w:f32le(if type(v) == "table" then num(v[2]) else 0) end elseif t == 0x19 then for i = 1, n do local v = vals[i] if type(v) ~= "table" then w:u8(0) else local acoustic = v[6] ~= nil and v[6] ~= 1 -- (rbx-dom leaves the default out) w:u8(if acoustic then 3 else 1) for c = 1, if acoustic then 6 else 5 do w:f32le(num(v[c])) end end end elseif t == 0x1A then for c = 1, 3 do for i = 1, n do local v = vals[i] w:u8(math.clamp(floor(if type(v) == "table" then num(v[c]) else 0), 0, 255)) end end elseif t == 0x1B or t == 0x21 then local c = table.create(n, 0) for i = 1, n do c[i] = num(vals[i]) end putI64s(w, c) elseif t == 0x1C then local idx = table.create(n, 0) local si = ctx.sharedIndex for i = 1, n do local v = vals[i] idx[i] = if si then si(if type(v) == "string" then v else "") else 0 end putU32s(w, idx) elseif t == 0x1E then w:u8(0x10) putCFrames(w, vals, n) w:u8(0x02) for i = 1, n do w:u8(if type(vals[i]) == "table" then 1 else 0) end elseif t == 0x1F then local p = w:reserve(16 * n) local b = w.buf for i = 0, n - 1 do local s = vals[i + 1] if type(s) ~= "string" or #s ~= 32 or string.find(s, "[^%x]") then return "a UniqueId is 32 hex digits" end -- index (hex 25..32) and time (17..24) first, then the random part (1..16) rotated left by one bit local by = table.create(16, 0) for k = 1, 4 do by[k] = hexByte(s, 12 + k) by[4 + k] = hexByte(s, 8 + k) end local top = hexByte(s, 1) // 128 for k = 1, 8 do local v = hexByte(s, k) local nxt = if k < 8 then hexByte(s, k + 1) // 128 else top by[8 + k] = (v * 2) % 256 + nxt end for k = 0, 15 do buffer.writeu8(b, p + k * n + i, by[k + 1]) end end w.pos = p + 16 * n elseif t == 0x20 then for i = 1, n do local v = vals[i] if type(v) ~= "table" then v = Rbx.default("Font") end putString(w, if type(v.family) == "string" then v.family else "") w:u16le(math.clamp(floor(num(v.weight)), 0, 65535)) w:u8(if v.style == "Italic" then 1 else 0) putString(w, if type(v.cachedFaceId) == "string" then v.cachedFaceId else "") end elseif t == 0x22 then local kinds, uris, objs = table.create(n, 0), {}, {} local refOf = ctx.refOf for i = 1, n do local v = vals[i] if type(v) == "string" then kinds[i] = 1 table.insert(uris, v) elseif type(v) == "table" then kinds[i] = 2 table.insert(objs, if refOf then refOf(v) else -1) end end putI32s(w, kinds) w:u32le(#uris) for _, s in uris do putString(w, s) end w:u32le(#objs) Binary.writeRefs(w, objs) w:u32le(0) else return "unknown type id " .. t end return nil end return Binary end __FILES["codecs/model/Rig"] = function() -- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...). New code. local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") local Rig = {} local Scene = Types.Scene local readf32, writef32, writeu16 = buffer.readf32, buffer.writef32, buffer.writeu16 type Joint = { name: string?, parent: number, translation: { number }, rotation: { number }, -- quaternion x, y, z, w scale: { number }?, } type Range = { name: string?, first: number, last: number, fps: number? } type Track = { translation: { number }?, rotation: { number }?, scale: { number }? } function Rig.morph(prim: Types.Primitive, frames: { buffer }, normals: { buffer }?): boolean local pos = prim.attributes.POSITION if not pos or pos.type ~= "f32" or pos.components ~= 3 then return false end local nrm = prim.attributes.NORMAL local n = pos.count * 3 local targets: { { [string]: Types.Accessor } } = {} local ok = true for k, f in frames do if buffer.len(f) < n * 4 then ok = false break end local t: { [string]: Types.Accessor } = {} local d = buffer.create(n * 4) local base = pos.data for i = 0, n - 1 do writef32(d, i * 4, readf32(f, i * 4) - readf32(base, i * 4)) end t.POSITION = Scene.accessor(d, "f32", 3, pos.count) local fn = normals and normals[k] if nrm and fn and nrm.type == "f32" and buffer.len(fn) >= n * 4 then local dn = buffer.create(n * 4) for i = 0, n - 1 do writef32(dn, i * 4, readf32(fn, i * 4) - readf32(nrm.data, i * 4)) end t.NORMAL = Scene.accessor(dn, "f32", 3, pos.count) end targets[k] = t end if ok then prim.targets = targets end return ok end function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, ranges: { Range }, interpolation: string?) for _, rg in ranges do local first, last = math.max(1, math.floor(rg.first)), math.min(targets, math.floor(rg.last)) if last >= first then local keys = last - first + 1 local fps = if rg.fps and rg.fps > 0 then rg.fps else 10 local times = buffer.create(keys * 4) local weights = buffer.create(keys * targets * 4) for k = 0, keys - 1 do writef32(times, k * 4, k / fps) writef32(weights, (k * targets + first - 1 + k) * 4, 1) end table.insert(scene.animations, { name = rg.name, channels = { { node = node, path = "weights" :: any, input = Scene.accessor(times, "f32", 1, keys), output = Scene.accessor(weights, "f32", 1, keys * targets), interpolation = (if interpolation == "STEP" then "STEP" else "LINEAR") :: any, }, }, }) end end end -- Quake's precomputed normal table is not redistributable here function Rig.normals(pos: buffer, count: number, indices: { number }): buffer local out = buffer.create(count * 12) local acc = table.create(count * 3, 0) for k = 1, #indices - 2, 3 do local a, b, c = indices[k], indices[k + 1], indices[k + 2] if a >= 0 and b >= 0 and c >= 0 and a < count and b < count and c < count then local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8) local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx for _, v in { a, b, c } do acc[v * 3 + 1] += nx acc[v * 3 + 2] += ny acc[v * 3 + 3] += nz end end end for v = 0, count - 1 do local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] local l = math.sqrt(x * x + y * y + z * z) if l > 0 then x, y, z = x / l, y / l, z / l end writef32(out, v * 12, x) writef32(out, v * 12 + 4, y) writef32(out, v * 12 + 8, z) end return out end local function trs(j: Joint): { number } return Mat4.compose(j.translation, j.rotation, j.scale) end -- R = Rz * Ry * Rx: the Quake / Half-Life AngleQuaternion convention of MDL bones and SMD skeletons function Rig.angles(x: number, y: number, z: number): { number } local sy, cy = math.sin(z / 2), math.cos(z / 2) local sp, cp = math.sin(y / 2), math.cos(y / 2) local sr, cr = math.sin(x / 2), math.cos(x / 2) return { sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy } end function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number, { { number } }) local n = #joints local world: { { number } } = {} local nodes: { number } = {} for i, j in joints do local p = if j.parent >= 1 and j.parent < i then j.parent else 0 local m = trs(j) local lt, lr, ls = j.translation, j.rotation, j.scale if space == "world" then world[i] = m if p > 0 then local inv = Mat4.inverse(world[p]) if inv then local t, r, s = Mat4.decompose(Mat4.mul(inv, m)) lt, lr, ls = t, r, s end end else world[i] = if p > 0 then Mat4.mul(world[p], m) else m end local node: Types.Node = { name = j.name, children = {}, translation = table.clone(lt), rotation = table.clone(lr), scale = if ls then table.clone(ls) else nil } table.insert(scene.nodes, node) local idx = #scene.nodes nodes[i] = idx if p > 0 then table.insert(scene.nodes[nodes[p]].children, idx) elseif root and scene.nodes[root] then table.insert(scene.nodes[root].children, idx) else table.insert(scene.roots, idx) end end local ibm = buffer.create(n * 64) for i = 1, n do local inv = Mat4.inverseFull(world[i]) or Mat4.identity() for k = 1, 16 do writef32(ibm, ((i - 1) * 16 + k - 1) * 4, inv[k]) end end local acc = Scene.accessor(ibm, "f32", 16, n) acc.matrix = true table.insert(scene.skins, { joints = nodes, inverseBindMatrices = acc, skeleton = if n > 0 then nodes[1] else nil }) return nodes, #scene.skins, world end function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) local n = #lists local jb, wb = buffer.create(n * 8), buffer.create(n * 16) for v, l in lists do local pairs_: { { number } } = {} local at: { [number]: { number } } = {} for k = 1, #l - 1, 2 do if l[k + 1] > 0 then local same = at[l[k]] if same then same[2] += l[k + 1] else local e = { l[k], l[k + 1] } at[l[k]] = e table.insert(pairs_, e) end end end table.sort(pairs_, function(a: { number }, b: { number }): boolean return a[2] > b[2] end) local sum = 0 for k = 1, math.min(4, #pairs_) do sum += pairs_[k][2] end for k = 1, math.min(4, #pairs_) do writeu16(jb, ((v - 1) * 4 + k - 1) * 2, math.clamp(pairs_[k][1], 0, 65535)) writef32(wb, ((v - 1) * 4 + k - 1) * 4, pairs_[k][2] / sum) end end return Scene.accessor(jb, "u16", 4, n), Scene.accessor(wb, "f32", 4, n) end local function floats(t: { number }, count: number, comps: number): Types.Accessor? if #t < count * comps then return nil end local b = buffer.create(count * comps * 4) for i = 1, count * comps do writef32(b, (i - 1) * 4, t[i]) end return Scene.accessor(b, "f32", comps, count) end function Rig.animation(scene: Types.Scene, name: string?, nodes: { number }, times: { number }, tracks: { [number]: Track }, interpolation: string?): number local count = #times local input = floats(times, count, 1) local channels: { Types.Channel } = {} local interp: any = if interpolation == "STEP" then "STEP" else "LINEAR" if input then for j, tr in tracks do local node = nodes[j] if node then for _, path in { "translation", "rotation", "scale" } do local keys = (tr :: any)[path] local acc = keys and floats(keys, count, if path == "rotation" then 4 else 3) if acc then table.insert(channels, { node = node, path = path :: any, input = input, output = acc, interpolation = interp }) end end end end end table.insert(scene.animations, { name = name, channels = channels }) return #scene.animations end return Rig end __FILES["codecs/model/Sampler"] = function() -- codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 animations. New code. local Types = __include("Types") local Sampler = {} type Sample = (t: number) -> { number } type Pose = { [number]: { [string]: { number } } } local function normalize(q: { number }): { number } local l = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) if l <= 0 then return { 0, 0, 0, 1 } end return { q[1] / l, q[2] / l, q[3] / l, q[4] / l } end local function slerp(a: { number }, b: { number }, s: number): { number } local d = a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] local bx, by, bz, bw = b[1], b[2], b[3], b[4] if d < 0 then d, bx, by, bz, bw = -d, -bx, -by, -bz, -bw end local wa, wb if d > 0.9995 then wa, wb = 1 - s, s else local th = math.acos(math.min(d, 1)) local sn = math.sin(th) wa, wb = math.sin((1 - s) * th) / sn, math.sin(s * th) / sn end return normalize({ a[1] * wa + bx * wb, a[2] * wa + by * wb, a[3] * wa + bz * wb, a[4] * wa + bw * wb }) end function Sampler.channel(ch: Types.Channel): Sample? local inp, out = ch.input, ch.output if type(inp) ~= "table" or type(out) ~= "table" then return nil end local IN, OUT = Types.Scene.reader(inp), Types.Scene.reader(out) local n = inp.count if not IN or not OUT or n < 1 then return nil end local cubic = ch.interpolation == "CUBICSPLINE" local per = if cubic then 3 else 1 local comps: number if ch.path == "weights" then comps = (out.count * out.components) // (n * per) else comps = if ch.path == "rotation" then 4 else 3 end if comps < 1 or out.count * out.components < n * per * comps then return nil end local times = table.create(n) :: { number } for k = 1, n do times[k] = IN(k - 1, 0) end local oc = out.components local function get(e: number): { number } local v = table.create(comps) :: { number } for c = 0, comps - 1 do local flat = e * comps + c v[c + 1] = OUT(flat // oc, flat % oc) end return v end local function value(k: number): { number } return get(if cubic then (k - 1) * 3 + 1 else k - 1) end local rot = ch.path == "rotation" local step = ch.interpolation == "STEP" return function(t: number): { number } if t <= times[1] or n == 1 then return if rot then normalize(value(1)) else value(1) end if t >= times[n] then return if rot then normalize(value(n)) else value(n) end local lo, hi = 1, n while hi - lo > 1 do local mid = (lo + hi) // 2 if times[mid] <= t then lo = mid else hi = mid end end local dt = times[hi] - times[lo] local s = if dt > 0 then (t - times[lo]) / dt else 0 if step then return if rot then normalize(value(lo)) else value(lo) end if cubic then local p0, m0 = value(lo), get((lo - 1) * 3 + 2) local p1, m1 = value(hi), get((hi - 1) * 3) local s2, s3 = s * s, s * s * s local h00, h10, h01, h11 = 2 * s3 - 3 * s2 + 1, s3 - 2 * s2 + s, -2 * s3 + 3 * s2, s3 - s2 local v = table.create(comps) :: { number } for c = 1, comps do v[c] = h00 * p0[c] + h10 * dt * m0[c] + h01 * p1[c] + h11 * dt * m1[c] end return if rot then normalize(v) else v end local a, b = value(lo), value(hi) if rot then return slerp(normalize(a), normalize(b), s) end local v = table.create(comps) :: { number } for c = 1, comps do v[c] = a[c] + (b[c] - a[c]) * s end return v end end function Sampler.times(anim: Types.Animation): { number } local seen: { [number]: boolean } = {} local out: { number } = {} for _, ch in anim.channels do local inp = ch.input local IN = type(inp) == "table" and Types.Scene.reader(inp) if IN then for k = 0, inp.count - 1 do local t = IN(k, 0) if not seen[t] and t == t then seen[t] = true table.insert(out, t) end end end end table.sort(out) return out end function Sampler.pose(_scene: Types.Scene, anim: Types.Animation, t: number, samplers: { [any]: any }?): Pose local cache: { [any]: any } = samplers or {} local pose: Pose = {} for _, ch in anim.channels do if cache[ch] == nil then cache[ch] = Sampler.channel(ch) or false end local s: Sample? = cache[ch] or nil if s then local p = pose[ch.node] if not p then p = {} pose[ch.node] = p end p[ch.path] = s(t) end end return pose end return Sampler end __FILES["codecs/model/Vrml"] = function() -- codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d. -- VRML97 ISO/IEC 14772-1, X3D ISO/IEC 19775-1, encodings ISO/IEC 19776-1 (XML) / -2 (classic). New code. local Err = __include("core/Err") local Types = __include("Types") local Deflate = __include("codecs/compress/Deflate") local XmlCodec = __include("codecs/text/Xml") local Parse = __include("codecs/model/Vrml/Parse") local VXml = __include("codecs/model/Vrml/Xml") local Build = __include("codecs/model/Vrml/Build") local Write = __include("codecs/model/Vrml/Write") local Vrml = {} type Graph = Parse.Graph type Node = Parse.Node type Options = Build.Options & { files: { [string]: any }?, resolve: ((uri: string) -> any)?, maxBytes: number?, } local function text(data: buffer | string, maxBytes: number?): (string?, Err.Err?) local b = if type(data) == "string" then buffer.fromstring(data) else data if buffer.len(b) >= 2 and buffer.readu8(b, 0) == 0x1F and buffer.readu8(b, 1) == 0x8B then local out, err = Deflate.gunzip(b) if not out then return nil, err end if buffer.len(out) > (maxBytes or 2 ^ 28) then return nil, Err.new(Err.LIMIT, "inflated file over maxBytes") end b = out end local s = buffer.tostring(b) if string.sub(s, 1, 3) == "\239\187\191" then s = string.sub(s, 4) end return s, nil end local function code(msg: string): string if string.find(msg, "unsupported", 1, true) then return Err.UNSUPPORTED elseif string.find(msg, "limit", 1, true) then return Err.LIMIT elseif string.find(msg, "unterminated", 1, true) then return Err.TRUNCATED end return Err.CORRUPT end function Vrml.parse(s: string): (Graph?, Err.Err?) local g, msg = Parse.parse(s) if not g then return nil, Err.new(code(msg or "parse error"), msg or "parse error") end return g, nil end function Vrml.parseXml(src: any): (Graph?, Err.Err?) local doc = src if type(src) == "string" then local d, err = XmlCodec.decode(src) if not d and err and err.code == Err.TRUNCATED and not string.find(src, "", 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: buffer | string, opts: Options?): (Graph?, Err.Err?) local s, err = text(data, opts and opts.maxBytes) if not s then return nil, err end local head = string.match(s, "^%s*(.?)") if head == "<" then return Vrml.parseXml(s) end if string.sub(s, 1, 4) == "\224\0\0\1" or string.sub(s, 1, 4) == "$EXI" then return nil, Err.new(Err.UNSUPPORTED, "binary X3D (Fast Infoset / EXI encoding)") end return Vrml.parse(s) end function Vrml.fetcher(opts: Options?): (uri: string) -> buffer? return function(uri: string): buffer? if not opts then return nil end local v: any = nil if type(opts.files) == "table" then v = opts.files[uri] or opts.files[string.match(uri, "([^/\\]+)$") or uri] end if v == nil and type(opts.resolve) == "function" then local ok, res = pcall(opts.resolve, uri) v = if ok then res else nil end return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil end end function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?) local o: any = table.clone(opts or {}) o.fetch = o.fetch or Vrml.fetcher(opts) o.load = o.load or function(data: buffer): (any, string?) local g, err = Vrml.graph(data, opts) return g, if err then err.message else nil end local scene, msg = Build.scene(graph, o) if not scene then return nil, Err.new(code(msg or "build failed"), msg or "build failed") end return scene, nil end function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err.Err?) local g, err = Vrml.graph(data, opts) if not g then return nil, err end return Vrml.build(g, opts) end function Vrml.encode(scene: Types.Scene, opts: Write.Options?): (string?, Err.Err?) if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then return nil, Err.new(Err.ARG, "needs a Scene") end local s, msg = Write.text(scene, opts or {}) if not s then return nil, Err.new(Err.ARG, msg or "the scene could not be written") end return s, nil end return Vrml end __FILES["codecs/model/Vrml/Build"] = function() -- codecs/model/Vrml/Build: the VRML97 / X3D node graph to a Scene. Written from the specifications; no third-party code. -- A Transform is one TRS node (translation T + C, rotation R * SR, scale S) plus, when it has a center or scale -- orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children. local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") local Fields = __include("codecs/model/Vrml/Fields") local Geometry = __include("codecs/model/Vrml/Geometry") local Build = {} local S = Types.Scene local nums, num, vec, bool, str, strs, node, nodes = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.str, Fields.strs, Fields.node, Fields.nodes local deg = math.deg type Options = Geometry.Options & { fetch: ((uri: string) -> buffer?)?, load: ((data: buffer) -> (any, string?))?, format: string?, maxInline: number?, } local GROUP = { Group = true, Anchor = true, Billboard = true, Collision = true, StaticGroup = true, CADAssembly = true, CADLayer = true, LayerSet = true, Layer = true, HAnimSegment = true, HAnimSite = true, LOD = true, Switch = true } local TRANSFORM = { Transform = true, CADPart = true, HAnimHumanoid = true, HAnimJoint = true } local CHILDREN = { "children", "skeleton", "segments", "sites", "layers" } local QUIET = { WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true, PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true, CoordinateInterpolator = true, NormalInterpolator = true, TouchSensor = true, ProximitySensor = true, VisibilitySensor = true, PlaneSensor = true, CylinderSensor = true, SphereSensor = true, Script = true, Sound = true, AudioClip = true, MetadataString = true, MetadataFloat = true, MetadataInteger = true, MetadataDouble = true, MetadataSet = true, MetadataBoolean = true, BooleanFilter = true, BooleanToggle = true, BooleanTrigger = true, BooleanSequencer = true, IntegerSequencer = true, IntegerTrigger = true, TimeTrigger = true, KeySensor = true, StringSensor = true, LoadSensor = true, } local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", gif = "image/gif", bmp = "image/bmp", webp = "image/webp", ktx2 = "image/ktx2", dds = "image/vnd-ms.dds", tga = "image/x-tga" } local function quat(r: { number }): { number } return Mat4.axisAngle(r[1], r[2], r[3], deg(r[4])) end local function qmul(a: { number }, b: { number }): { number } return { a[4] * b[1] + a[1] * b[4] + a[2] * b[3] - a[3] * b[2], a[4] * b[2] - a[1] * b[3] + a[2] * b[4] + a[3] * b[1], a[4] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[4], a[4] * b[4] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3], } end local function qrot(q: { number }, v: { number }): { number } local m = Mat4.fromQuat(q) local x, y, z = Mat4.point(m, v[1], v[2], v[3]) return { x, y, z } end local function isZero(v: { number }): boolean return v[1] == 0 and v[2] == 0 and v[3] == 0 end local function isIdentityQ(q: { number }): boolean return q[1] == 0 and q[2] == 0 and q[3] == 0 end local function between(a: { number }, b: { number }): { number } local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3]) if l < 1e-12 then return { 0, 0, 0, 1 } end local bx, by, bz = b[1] / l, b[2] / l, b[3] / l local d = a[1] * bx + a[2] * by + a[3] * bz if d < -0.999999 then return if math.abs(a[1]) < 0.9 then { 0, a[3], -a[2], 0 } else { -a[3], 0, a[1], 0 } end local cx, cy, cz = a[2] * bz - a[3] * by, a[3] * bx - a[1] * bz, a[1] * by - a[2] * bx local w = 1 + d local n = math.sqrt(cx * cx + cy * cy + cz * cz + w * w) return { cx / n, cy / n, cz / n, w / n } end type Ctx = { scene: Types.Scene, opts: Options, meshes: { [any]: any }, materials: { [any]: any }, textures: { [any]: number }, instances: { [any]: { { node: number, center: { number }, so: { number } } } }, skipped: { [string]: number }, depth: number, inline: number, failure: string?, } local function addNode(ctx: Ctx, n: Types.Node, parent: number?): number local nodes_ = ctx.scene.nodes table.insert(nodes_, n) local i = #nodes_ if parent then table.insert(nodes_[parent].children, i) else table.insert(ctx.scene.roots, i) end return i end local function texture(ctx: Ctx, t: any): number? if not t then return nil end if t.type == "MultiTexture" then return texture(ctx, nodes(t, "texture")[1]) end local cached = ctx.textures[t] if cached then return cached end local tex: Types.Texture = { name = t.def } if t.type == "ImageTexture" or t.type == "MovieTexture" then local urls = strs(t, "url") local fetch = ctx.opts.fetch for _, u in urls do local clean = string.match(u, "^([^#?]*)") or u if not tex.uri and not string.find(clean, "^%a[%w+.-]*://") then tex.uri = clean end local data = fetch and fetch(clean) if data then tex.uri, tex.data = clean, data break end end tex.uri = tex.uri or urls[1] local ext = tex.uri and string.match(tex.uri, "%.(%w+)$") tex.mime = if ext then MIME[string.lower(ext)] else nil elseif t.type == "PixelTexture" then -- SFImage: width height components pixels (0xRRGGBBAA style integers, MSB first) local v = nums(t, "image") or {} local w, h, c = math.floor(v[1] or 0), math.floor(v[2] or 0), math.floor(v[3] or 0) if w > 0 and h > 0 and c >= 1 and c <= 4 and w * h <= 2 ^ 24 and #v >= 3 + w * h then local img = Types.Image.new(w, h) for i = 0, w * h - 1 do local px = math.floor(v[4 + i]) % 2 ^ (8 * c) local b = table.create(4, 0) for k = c, 1, -1 do b[k] = px % 256 px //= 256 end local r, g, bl, a if c <= 2 then r, g, bl, a = b[1], b[1], b[1], if c == 2 then b[2] else 255 else r, g, bl, a = b[1], b[2], b[3], if c == 4 then b[4] else 255 end -- the image's first row is the bottom one local row = h - 1 - i // w local o = (row * w + i % w) * 4 buffer.writeu8(img.pixels, o, r) buffer.writeu8(img.pixels, o + 1, g) buffer.writeu8(img.pixels, o + 2, bl) buffer.writeu8(img.pixels, o + 3, a) end tex.image = img end else ctx.skipped[t.type] = (ctx.skipped[t.type] or 0) + 1 return nil end local rs, rt = bool(t, "repeatS", true), bool(t, "repeatT", true) if not rs or not rt then tex.sampler = { wrapS = if rs then "repeat" else "clamp", wrapT = if rt then "repeat" else "clamp" } end table.insert(ctx.scene.textures, tex) ctx.textures[t] = #ctx.scene.textures return #ctx.scene.textures end local function textureRef(ctx: Ctx, t: any, xf: any): Types.TextureRef? local i = texture(ctx, t) if not i then return nil end local ref: Types.TextureRef = { texture = i } if xf and xf.type == "TextureTransform" then local tr, sc, rot = vec(xf, "translation", { 0, 0 }), vec(xf, "scale", { 1, 1 }), num(xf, "rotation", 0) if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot ~= 0 then ref.transform = { offset = tr, scale = sc, rotation = rot } end end return ref end local function material(ctx: Ctx, app: any, solid: boolean): number? if not app and solid then return nil end local key = app or "default" local cache = ctx.materials[key] if type(cache) ~= "table" then cache = {} ctx.materials[key] = cache end local hit = (cache :: any)[solid] if hit then return hit end local m = S.material(app and app.def) m.metallic = 0 local x: { [string]: any } = {} local mat = app and node(app, "material") local tex = app and node(app, "texture") local xf = app and node(app, "textureTransform") if mat and mat.type == "TwoSidedMaterial" then m.doubleSided = true x.twoSided = true end if mat and (mat.type == "Material" or mat.type == "TwoSidedMaterial") then local d, e, sp = vec(mat, "diffuseColor", { 0.8, 0.8, 0.8 }), vec(mat, "emissiveColor", { 0, 0, 0 }), vec(mat, "specularColor", { 0, 0, 0 }) local sh, tr, amb = num(mat, "shininess", 0.2), num(mat, "transparency", 0), num(mat, "ambientIntensity", 0.2) m.name = mat.def or m.name m.baseColor = { d[1], d[2], d[3], 1 - tr } m.emissive = e m.roughness = math.clamp(math.sqrt(2 / (math.max(sh, 0) * 128 + 2)), 0, 1) x.diffuseColor, x.emissiveColor, x.specularColor, x.shininess, x.transparency, x.ambientIntensity = d, e, sp, sh, tr, amb if tr > 0 then m.alphaMode = "blend" end -- X3D 4 texture fields local dt = node(mat, "diffuseTexture") if dt then m.baseColorTexture = textureRef(ctx, dt, nil) end local nt = node(mat, "normalTexture") if nt then m.normalTexture = textureRef(ctx, nt, nil) end elseif mat and mat.type == "PhysicalMaterial" then local b, e = vec(mat, "baseColor", { 1, 1, 1 }), vec(mat, "emissiveColor", { 0, 0, 0 }) local tr = num(mat, "transparency", 0) m.name = mat.def or m.name m.baseColor = { b[1], b[2], b[3], 1 - tr } m.emissive, m.metallic, m.roughness = e, num(mat, "metallic", 1), num(mat, "roughness", 1) if tr > 0 then m.alphaMode = "blend" end local slots: { [string]: string } = { baseTexture = "baseColorTexture", metallicRoughnessTexture = "metallicRoughnessTexture", normalTexture = "normalTexture", occlusionTexture = "occlusionTexture", emissiveTexture = "emissiveTexture" } for field, slot in slots do local t = node(mat, field) if t then (m :: any)[slot] = textureRef(ctx, t, nil) end end elseif mat and mat.type == "UnlitMaterial" then local e = vec(mat, "emissiveColor", { 1, 1, 1 }) m.name = mat.def or m.name m.baseColor = { e[1], e[2], e[3], 1 - num(mat, "transparency", 0) } m.extensions = { KHR_materials_unlit = {} } else -- no material: unlit white (the specifications' default) m.extensions = { KHR_materials_unlit = {} } end if tex and not m.baseColorTexture then m.baseColorTexture = textureRef(ctx, tex, xf) if m.baseColorTexture and xf then x.textureCenter = vec(xf, "center", { 0, 0 }) end end if not solid then m.doubleSided = true end m.extras = { vrml = x } table.insert(ctx.scene.materials, m) local idx = #ctx.scene.materials ;(cache :: any)[solid] = idx return idx end local walk: (ctx: Ctx, n: any, parent: number?) -> () local function shape(ctx: Ctx, n: any, parent: number?) local geo = node(n, "geometry") if not geo then return end local mi = ctx.meshes[n] if mi == nil then local prim, solidOrErr = Geometry.primitive(geo, ctx.opts) if not prim then if solidOrErr then ctx.failure = ctx.failure or solidOrErr else ctx.skipped[geo.type] = (ctx.skipped[geo.type] or 0) + 1 end ctx.meshes[n] = false :: any return end local count = if prim.indices then prim.indices.count else prim.attributes.POSITION.count if count == 0 then ctx.meshes[n] = false return end prim.material = material(ctx, node(n, "appearance"), solidOrErr == true) table.insert(ctx.scene.meshes, { name = n.def or geo.def, primitives = { prim } }) mi = #ctx.scene.meshes ctx.meshes[n] = mi elseif mi == false then return end addNode(ctx, { name = n.def, children = {}, mesh = mi }, parent) end local function viewpoint(ctx: Ctx, n: any, parent: number?) local cam: any if n.type == "OrthoViewpoint" then local f = vec(n, "fieldOfView", { -1, -1, 1, 1 }) cam = { type = "orthographic", xmag = (f[3] - f[1]) / 2, ymag = (f[4] - f[2]) / 2, znear = 0.125, zfar = 1e4 } else cam = { type = "perspective", yfov = num(n, "fieldOfView", 0.785398), znear = 0.125 } end cam.name = n.def or str(n, "description") table.insert(ctx.scene.cameras, cam) local o = vec(n, "orientation", { 0, 0, 1, 0 }) local nd: Types.Node = { name = cam.name, children = {}, camera = #ctx.scene.cameras, translation = vec(n, "position", { 0, 0, 10 }) } if o[4] ~= 0 then nd.rotation = quat(o) end addNode(ctx, nd, parent) end local function light(ctx: Ctx, n: any, parent: number?) local t = n.type local l: Types.Light = { name = n.def, type = "point", color = vec(n, "color", { 1, 1, 1 }), intensity = num(n, "intensity", 1) } local nd: Types.Node = { name = n.def, children = {} } local x: { [string]: any } = { ambientIntensity = num(n, "ambientIntensity", 0), on = bool(n, "on", true), global = bool(n, "global", t == "DirectionalLight") } if t == "DirectionalLight" then l.type = "directional" nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) else nd.translation = vec(n, "location", { 0, 0, 0 }) l.range = num(n, "radius", 100) x.attenuation = vec(n, "attenuation", { 1, 0, 0 }) if t == "SpotLight" then l.type = "spot" nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) local cut = num(n, "cutOffAngle", 0.785398) l.outerCone = cut l.innerCone = math.min(num(n, "beamWidth", 1.570796), cut) end end ;(l :: any).extras = { vrml = x } table.insert(ctx.scene.lights, l) nd.light = #ctx.scene.lights addNode(ctx, nd, parent) end local function children(ctx: Ctx, n: any, parent: number?) if n.type == "Switch" then local which = math.floor(num(n, "whichChoice", -1)) local list = nodes(n, "choice") if #list == 0 then list = nodes(n, "children") end local c = list[which + 1] if which >= 0 and c then walk(ctx, c, parent) end return elseif n.type == "LOD" then local list = nodes(n, "level") if #list == 0 then list = nodes(n, "children") end if list[1] then walk(ctx, list[1], parent) end return end for _, f in CHILDREN do for _, c in nodes(n, f) do walk(ctx, c, parent) end end end local function transform(ctx: Ctx, n: any, parent: number?) local t, c = vec(n, "translation", { 0, 0, 0 }), vec(n, "center", { 0, 0, 0 }) local r, s, so = vec(n, "rotation", { 0, 0, 1, 0 }), vec(n, "scale", { 1, 1, 1 }), vec(n, "scaleOrientation", { 0, 0, 1, 0 }) local qr, qs = quat(r), quat(so) local outer: Types.Node = { name = n.def, children = {} } local tt = { t[1] + c[1], t[2] + c[2], t[3] + c[3] } if not isZero(tt) then outer.translation = tt end local q = if isIdentityQ(qs) then qr else qmul(qr, qs) if not isIdentityQ(q) then outer.rotation = q end if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then outer.scale = s end local oi = addNode(ctx, outer, parent) local list = ctx.instances[n] if not list then list = {} ctx.instances[n] = list end table.insert(list, { node = oi, center = c, so = qs }) local holder = oi if not isZero(c) or not isIdentityQ(qs) then local inv = { -qs[1], -qs[2], -qs[3], qs[4] } local inner: Types.Node = { children = {}, translation = qrot(inv, { -c[1], -c[2], -c[3] }) } if not isIdentityQ(inv) then inner.rotation = inv end holder = addNode(ctx, inner, oi) end children(ctx, n, holder) end local function inline(ctx: Ctx, n: any, parent: number?) local fetch, load = ctx.opts.fetch, ctx.opts.load if not fetch or not load or ctx.inline >= (ctx.opts.maxInline or 8) or not bool(n, "load", true) then ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 return end for _, u in strs(n, "url") do local data = fetch(string.match(u, "^([^#?]*)") or u) if data then local g = load(data) if g then local holder = addNode(ctx, { name = n.def, children = {} }, parent) ctx.inline += 1 for _, root in g.roots do walk(ctx, root, holder) end ctx.inline -= 1 return end end end ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 end function walk(ctx: Ctx, n: any, parent: number?) if ctx.failure or type(n) ~= "table" then return end ctx.depth += 1 if ctx.depth > 200 then ctx.failure = "limit: scene nested deeper than 200" return end local t = n.type if TRANSFORM[t] then transform(ctx, n, parent) elseif GROUP[t] then local holder = parent if n.def or parent == nil then holder = addNode(ctx, { name = n.def, children = {} }, parent) end children(ctx, n, holder) elseif t == "Shape" then shape(ctx, n, parent) elseif t == "CADFace" then for _, s in nodes(n, "shape") do walk(ctx, s, parent) end elseif t == "Viewpoint" or t == "OrthoViewpoint" then viewpoint(ctx, n, parent) elseif t == "DirectionalLight" or t == "PointLight" or t == "SpotLight" then light(ctx, n, parent) elseif t == "Inline" then inline(ctx, n, parent) elseif t == "WorldInfo" then local src = ctx.scene.meta.source :: any src.title = str(n, "title") local info = strs(n, "info") src.info = if #info > 0 then info else nil elseif not QUIET[t] then ctx.skipped[t] = (ctx.skipped[t] or 0) + 1 end ctx.depth -= 1 end local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" } local function animations(ctx: Ctx, routes: { any }) local timer: { [any]: any } = {} for _, r in routes do if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then timer[r.to] = r.from end end local anims: { [any]: Types.Animation } = {} local order: { any } = {} for _, r in routes do local path = TARGET[r.toField] local it = r.from local inst = ctx.instances[r.to] if not (path and inst and (it.type == "PositionInterpolator" or it.type == "OrientationInterpolator")) then continue end if (path == "rotation") ~= (it.type == "OrientationInterpolator") then continue end local key: { number }, kv: { number } = nums(it, "key") or {}, nums(it, "keyValue") or {} local comps = if path == "rotation" then 4 else 3 local n = math.min(#key, #kv // comps) if n == 0 then continue end local ts = timer[it] local cycle = if ts then num(ts, "cycleInterval", 1) else 1 local input = S.accessor(nil, "f32", 1, n) for i = 0, n - 1 do buffer.writef32(input.data, i * 4, key[i + 1] * cycle) end local id = ts or "routes" local anim = anims[id] if not anim then anim = { name = if ts then ts.def else nil, channels = {} } anims[id] = anim table.insert(order, id) end for _, at in inst do local out = S.accessor(nil, "f32", if path == "rotation" then 4 else 3, n) local prev: { number }? = nil for i = 0, n - 1 do local v: { number } if path == "rotation" then v = quat({ kv[i * 4 + 1], kv[i * 4 + 2], kv[i * 4 + 3], kv[i * 4 + 4] }) if not isIdentityQ(at.so) then v = qmul(v, at.so) end if prev and prev[1] * v[1] + prev[2] * v[2] + prev[3] * v[3] + prev[4] * v[4] < 0 then v = { -v[1], -v[2], -v[3], -v[4] } end prev = v elseif path == "translation" then v = { kv[i * 3 + 1] + at.center[1], kv[i * 3 + 2] + at.center[2], kv[i * 3 + 3] + at.center[3] } else v = { kv[i * 3 + 1], kv[i * 3 + 2], kv[i * 3 + 3] } end for c = 1, #v do buffer.writef32(out.data, (i * #v + c - 1) * 4, v[c]) end end table.insert(anim.channels, { node = at.node, path = path :: any, input = input, output = out, interpolation = "LINEAR" :: any }) end end for _, id in order do table.insert(ctx.scene.animations, anims[id]) end end function Build.scene(graph: any, opts: Options): (Types.Scene?, string?) local scene = S.new() scene.meta.up = "y" local units = graph.units or {} scene.meta.unit = if units.length and units.length.factor > 0 then units.length.factor else 1 local h = graph.header or {} local skipped: { [string]: number } = {} scene.meta.source = { format = opts.format or "vrml", version = h.version, encoding = h.encoding, profile = h.profile, x3d = h.x3d, xml = h.xml, meta = graph.meta, components = graph.components, skipped = skipped, } local ctx: Ctx = { scene = scene, opts = opts, meshes = {}, materials = {}, textures = {}, instances = {}, skipped = skipped, depth = 0, inline = 0, failure = nil } for _, n in graph.roots do walk(ctx, n, nil) end if ctx.failure then return nil, ctx.failure end animations(ctx, graph.routes or {}) return scene, nil end return Build end __FILES["codecs/model/Vrml/Fields"] = function() -- codecs/model/Vrml/Fields: typed reads of VRML / X3D node fields (classic arrays or X3D XML attribute strings). local Fields = {} local gmatch, find, sub, byte = string.gmatch, string.find, string.sub, string.byte local function mfString(s: string): { string } local out = {} local p = find(s, "[^%s,]") if not p or byte(s, p) ~= 34 then return if p then { (string.match(s, "^%s*(.-)%s*$") :: string) } else {} end local n = #s while p and p <= n do if byte(s, p) ~= 34 then break end local q = p + 1 local parts = {} while true do local e = find(s, '["\\]', q) if not e then table.insert(parts, sub(s, q)) table.insert(out, table.concat(parts)) return out end table.insert(parts, sub(s, q, e - 1)) if byte(s, e) == 92 then table.insert(parts, sub(s, e + 1, e + 1)) q = e + 2 else p = e + 1 break end end table.insert(out, table.concat(parts)) p = find(s, "[^%s,]", p) end return out end function Fields.nums(node: any, name: string): { number }? local v = node.fields[name] if v == nil then return nil end if type(v) == "string" then local out = {} for w in gmatch(v, "[^%s,]+") do local x = tonumber(w) if x then table.insert(out, x) elseif w == "true" or w == "TRUE" then table.insert(out, 1) elseif w == "false" or w == "FALSE" then table.insert(out, 0) end end node.fields[name] = out return out end if type(v) ~= "table" then return nil end local ok = true for _, x in v do if type(x) ~= "number" then ok = false break end end if ok then return v end local out = {} for _, x in v do if type(x) == "number" then table.insert(out, x) elseif type(x) == "boolean" then table.insert(out, if x then 1 else 0) end end return out end function Fields.num(node: any, name: string, default: number): number local v = Fields.nums(node, name) return if v and type(v[1]) == "number" then v[1] else default end function Fields.vec(node: any, name: string, default: { number }): { number } local v = Fields.nums(node, name) if not v or #v < #default then return default end local out: { number } = {} for i = 1, #default do out[i] = v[i] end return out end function Fields.bool(node: any, name: string, default: boolean): boolean local v = node.fields[name] if type(v) == "string" then local w = string.lower(string.match(v, "^%s*(%S*)") :: string) return if w == "true" then true elseif w == "false" then false else default end if type(v) == "table" and type(v[1]) == "boolean" then return v[1] end return default end function Fields.strs(node: any, name: string): { string } local v = node.fields[name] if type(v) == "string" then local out = mfString(v) node.fields[name] = out return out end local out = {} if type(v) == "table" then for _, x in v do if type(x) == "string" then table.insert(out, x) end end end return out end function Fields.str(node: any, name: string, default: string?): string? local v = node.fields[name] if type(v) == "string" then return v end if type(v) == "table" and type(v[1]) == "string" then return v[1] end return default end function Fields.nodes(node: any, name: string): { any } local v = node.fields[name] local out = {} if type(v) == "table" then for _, x in v do if type(x) == "table" and type(x.type) == "string" then table.insert(out, x) end end end return out end function Fields.node(node: any, name: string): any return Fields.nodes(node, name)[1] end return Fields end __FILES["codecs/model/Vrml/Geometry"] = function() -- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. New code, from the specifications. -- Texture t is flipped to glTF's top-left origin unless flipV = false. local Types = __include("Types") local Fields = __include("codecs/model/Vrml/Fields") local Geometry = {} local S = Types.Scene local nums, num, vec, bool, node = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.node local sqrt, sin, cos, pi = math.sqrt, math.sin, math.cos, math.pi type Options = { flipV: boolean?, triangulate: boolean?, segments: number?, maxVertices: number? } local function f32(list: { number }, comps: number, count: number): Types.Accessor local a = S.accessor(nil, "f32", comps, count) local d = a.data for i = 1, math.min(#list, comps * count) do buffer.writef32(d, (i - 1) * 4, list[i]) end return a end local function u32(list: { number }): Types.Accessor local a = S.accessor(nil, "u32", 1, #list) for i, v in list do buffer.writeu32(a.data, (i - 1) * 4, v) end return a end local function colors(n: any): ({ number }?, number) local c = node(n, "color") if not c then return nil, 3 end local comps = if c.type == "ColorRGBA" then 4 else 3 return nums(c, "color") or {}, comps end local function points(n: any, field: string, sub: string): { number }? local c = node(n, field) return if c then nums(c, sub) or {} else nil end type PolyIn = { P: { number }, corners: { number }, sizes: { number }, N: { number }?, nIdx: { number }?, nFace: boolean?, C: { number }?, cComps: number?, cIdx: { number }?, cFace: boolean?, T: { number }?, tIdx: { number }?, ccw: boolean, } local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?) local P, corners, sizes = m.P, m.corners, m.sizes local np = #P // 3 local N, C, T = m.N, m.C, m.T local cc = m.cComps or 3 local function idx(list: { number }?, perFace: boolean?, f: number, k: number, c: number): number if perFace then return if list and #list > 0 then (list[f] or 0) else f - 1 end return if list and #list > 0 then (list[k] or c) else c end local simple = (N == nil or (not m.nFace and (m.nIdx == nil or #m.nIdx == 0))) and (C == nil or (not m.cFace and (m.cIdx == nil or #m.cIdx == 0))) and (T == nil or m.tIdx == nil or #m.tIdx == 0) local vkey: { [string]: number } = {} local vsrc: { { number } } = {} local out: { number } = {} local outSizes: { number } = {} local k = 0 for f, size in sizes do local face: { number } = {} local valid = size >= 3 for q = 1, size do k += 1 local c = corners[k] if c == nil or c < 0 or c >= np then valid = false end face[q] = k end if valid then local verts: { number } = {} for q, kk in face do local c = corners[kk] if simple then verts[q] = c else local ni = if N then idx(m.nIdx, m.nFace, f, kk, c) else -1 local ci = if C then idx(m.cIdx, m.cFace, f, kk, c) else -1 local ti = if T then idx(m.tIdx, false, f, kk, c) else -1 local key = c .. ":" .. ni .. ":" .. ci .. ":" .. ti local v = vkey[key] if not v then v = #vsrc vsrc[v + 1] = { c, ni, ci, ti } vkey[key] = v if v >= maxV then return nil, "limit: more than " .. maxV .. " vertices" end end verts[q] = v end end if not m.ccw then for a = 2, (size + 1) // 2 do verts[a], verts[size + 2 - a] = verts[size + 2 - a], verts[a] end end if o.triangulate == false then table.insert(outSizes, size) for _, v in verts do table.insert(out, v) end else for a = 2, size - 1 do table.insert(out, verts[1]) table.insert(out, verts[a]) table.insert(out, verts[a + 1]) end end end end local nv = if simple then np else #vsrc if nv > maxV then return nil, "limit: more than " .. maxV .. " vertices" end local flipV = o.flipV ~= false local pos = S.accessor(nil, "f32", 3, nv) local nrm = if N then S.accessor(nil, "f32", 3, nv) else nil local col = if C then S.accessor(nil, "f32", cc, nv) else nil local tex = if T then S.accessor(nil, "f32", 2, nv) else nil local wf = buffer.writef32 for v = 0, nv - 1 do local s = if simple then nil else vsrc[v + 1] local c = if s then s[1] else v for q = 0, 2 do wf(pos.data, (v * 3 + q) * 4, P[c * 3 + q + 1] or 0) end if nrm and N then local ni = if s then s[2] else v for q = 0, 2 do wf(nrm.data, (v * 3 + q) * 4, N[ni * 3 + q + 1] or 0) end end if col and C then local ci = if s then s[3] else v for q = 0, cc - 1 do wf(col.data, (v * cc + q) * 4, C[ci * cc + q + 1] or 1) end end if tex and T then local ti = if s then s[4] else v local tt = T[ti * 2 + 2] or 0 wf(tex.data, v * 8, T[ti * 2 + 1] or 0) wf(tex.data, v * 8 + 4, if flipV then 1 - tt else tt) end end local attrs: { [string]: Types.Accessor } = { POSITION = pos } attrs.NORMAL, attrs.COLOR_0, attrs.TEXCOORD_0 = nrm, col, tex local prim: Types.Primitive = { attributes = attrs, indices = u32(out), mode = "triangles" } if o.triangulate == false then prim.mode = "polygons" prim.faces = u32(outSizes) end return prim end local function split(list: { number }): ({ number }, { number }) local corners, sizes = {}, {} local run = 0 for _, x in list do if x < 0 then if run > 0 then table.insert(sizes, run) end run = 0 else table.insert(corners, x) run += 1 end end if run > 0 then table.insert(sizes, run) end return corners, sizes end -- per-face index lists keep only the entries of faces (the -1 separators of per-corner lists match the corners) local function cornerList(list: { number }?): { number }? if not list or #list == 0 then return nil end local out = {} for _, x in list do if x >= 0 then table.insert(out, x) end end return out end local function faceSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) local P = points(n, "coord", "point") or {} local corners, sizes = split(nums(n, "coordIndex") or {}) local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) local C, cc = colors(n) local tc = node(n, "texCoord") local m: PolyIn = { P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), N = points(n, "normal", "vector"), nFace = not nPer, nIdx = if nPer then cornerList(nums(n, "normalIndex")) else nums(n, "normalIndex"), C = C, cComps = cc, cFace = not cPer, cIdx = if cPer then cornerList(nums(n, "colorIndex")) else nums(n, "colorIndex"), T = if tc and tc.type ~= "TextureCoordinateGenerator" then (nums(if tc.type == "MultiTextureCoordinate" then (node(tc, "texCoord") or tc) else tc, "point") or {}) else nil, tIdx = cornerList(nums(n, "texCoordIndex")), } return polyMesh(m, o, maxV) end local function triSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) local t = n.type local P = points(n, "coord", "point") or {} local np = #P // 3 local index = nums(n, "index") local seq: { number } if string.sub(t, 1, 7) == "Indexed" then seq = index or {} else seq = {} for i = 0, np - 1 do seq[i + 1] = i end end local corners, sizes = {}, {} local function tri(a: number, b: number, c: number) table.insert(corners, a) table.insert(corners, b) table.insert(corners, c) table.insert(sizes, 3) end -- runs: -1 separated (indexed fans / strips) or fanCount / stripCount (plain fans / strips) local function runs(): { { number } } local out = {} local counts = nums(n, if string.find(t, "Fan", 1, true) then "fanCount" else "stripCount") if string.sub(t, 1, 7) == "Indexed" or not counts then local cur = {} for _, x in seq do if x < 0 then table.insert(out, cur) cur = {} else table.insert(cur, x) end end table.insert(out, cur) else local at = 1 for _, c in counts do local cur = {} for q = 0, c - 1 do cur[q + 1] = seq[at + q] end at += c table.insert(out, cur) end end return out end if t == "IndexedTriangleSet" or t == "TriangleSet" then for i = 1, #seq - 2, 3 do tri(seq[i], seq[i + 1], seq[i + 2]) end elseif t == "IndexedQuadSet" or t == "QuadSet" then for i = 1, #seq - 3, 4 do for q = 0, 3 do table.insert(corners, seq[i + q]) end table.insert(sizes, 4) end elseif string.find(t, "Fan", 1, true) then for _, r in runs() do for i = 2, #r - 1 do tri(r[1], r[i], r[i + 1]) end end else for _, r in runs() do for i = 1, #r - 2 do if i % 2 == 1 then tri(r[i], r[i + 1], r[i + 2]) else tri(r[i + 1], r[i], r[i + 2]) end end end end local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) local C, cc = colors(n) local tc = node(n, "texCoord") local m: PolyIn = { P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), N = points(n, "normal", "vector"), nFace = not nPer, C = C, cComps = cc, cFace = not cPer, T = if tc and tc.type == "TextureCoordinate" then nums(tc, "point") or {} else nil, } return polyMesh(m, o, maxV) end local function elevationGrid(n: any, o: Options, maxV: number): (Types.Primitive?, string?) local nx, nz = math.floor(num(n, "xDimension", 0)), math.floor(num(n, "zDimension", 0)) local dx, dz = num(n, "xSpacing", 1), num(n, "zSpacing", 1) local h: { number } = nums(n, "height") or {} if nx < 2 or nz < 2 then return nil, nil end if nx * nz > maxV then return nil, "limit: elevation grid of " .. nx .. " x " .. nz end local P: { number }, T: { number }, corners: { number }, sizes: { number } = {}, {}, {}, {} for z = 0, nz - 1 do for x = 0, nx - 1 do table.insert(P, x * dx) table.insert(P, h[z * nx + x + 1] or 0) table.insert(P, z * dz) table.insert(T, x / (nx - 1)) table.insert(T, z / (nz - 1)) end end for z = 0, nz - 2 do for x = 0, nx - 2 do local a = z * nx + x -- counter-clockwise seen from +y: a, a + nx, a + nx + 1, a + 1 for _, c in { a, a + nx, a + nx + 1, a + 1 } do table.insert(corners, c) end table.insert(sizes, 4) end end local C, cc = colors(n) local tc = node(n, "texCoord") local m: PolyIn = { P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), N = points(n, "normal", "vector"), nFace = not bool(n, "normalPerVertex", true), C = C, cComps = cc, cFace = not bool(n, "colorPerVertex", true), T = if tc then nums(tc, "point") or {} else T, } return polyMesh(m, o, maxV) end local function cross(a: { number }, b: { number }): { number } return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } end local function sub3(a: { number }, b: { number }): { number } return { a[1] - b[1], a[2] - b[2], a[3] - b[3] } end local function norm(a: { number }): ({ number }, number) local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3]) return if l > 1e-12 then { a[1] / l, a[2] / l, a[3] / l } else { 0, 0, 0 }, l end -- rotate v about the unit axis k by angle a (Rodrigues) local function rotate(v: { number }, k: { number }, a: number): { number } local c, s = cos(a), sin(a) local d = (k[1] * v[1] + k[2] * v[2] + k[3] * v[3]) * (1 - c) local kv = cross(k, v) return { v[1] * c + kv[1] * s + k[1] * d, v[2] * c + kv[2] * s + k[2] * d, v[3] * c + kv[3] * s + k[3] * d } end local function extrusion(n: any, o: Options, maxV: number): (Types.Primitive?, string?) local sp = nums(n, "spine") or { 0, 0, 0, 0, 1, 0 } local cs = nums(n, "crossSection") or { 1, 1, 1, -1, -1, -1, -1, 1, 1, 1 } local sc = nums(n, "scale") or { 1, 1 } local ori = nums(n, "orientation") or { 0, 0, 1, 0 } local ns, nc = #sp // 3, #cs // 2 if ns < 2 or nc < 2 then return nil, nil end if ns * nc > maxV then return nil, "limit: extrusion of " .. ns .. " x " .. nc end local spine = {} for i = 1, ns do spine[i] = { sp[i * 3 - 2], sp[i * 3 - 1], sp[i * 3] } end local function same(a: { number }, b: { number }): boolean return math.abs(a[1] - b[1]) < 1e-9 and math.abs(a[2] - b[2]) < 1e-9 and math.abs(a[3] - b[3]) < 1e-9 end local closedSpine = same(spine[1], spine[ns]) local closedCs = math.abs(cs[1] - cs[nc * 2 - 1]) < 1e-9 and math.abs(cs[2] - cs[nc * 2]) < 1e-9 -- spine-aligned cross-section planes: Y along the spine, Z from the bend, X = Y x Z local Ys: { { number } }, Zs: { [number]: { number } } = {}, {} for i = 1, ns do local prev = if i > 1 then spine[i - 1] elseif closedSpine then spine[ns - 1] else nil local nxt = if i < ns then spine[i + 1] elseif closedSpine then spine[2] else nil local y = sub3(nxt or spine[i], prev or spine[i]) Ys[i] = norm(y) if prev and nxt then local z, l = norm(cross(sub3(nxt, spine[i]), sub3(prev, spine[i]))) Zs[i] = if l > 1e-12 then z else nil end end -- missing Z: copy a neighbour's; a straight spine rotates (0, 0, 1) like (0, 1, 0) onto the spine direction local firstZ = nil for i = 1, ns do if Zs[i] then firstZ = Zs[i] break end end for i = 1, ns do if not Ys[i] or (Ys[i][1] == 0 and Ys[i][2] == 0 and Ys[i][3] == 0) then Ys[i] = Ys[i - 1] or { 0, 1, 0 } end end for i = 1, ns do if not Zs[i] then if firstZ then Zs[i] = Zs[i - 1] or firstZ else local y = Ys[i] local axis, l = norm(cross({ 0, 1, 0 }, y)) local ang = math.acos(math.clamp(y[2], -1, 1)) Zs[i] = if l > 1e-12 then rotate({ 0, 0, 1 }, axis, ang) elseif y[2] < 0 then { 0, 0, -1 } else { 0, 0, 1 } end end if i > 1 and Zs[i][1] * Zs[i - 1][1] + Zs[i][2] * Zs[i - 1][2] + Zs[i][3] * Zs[i - 1][3] < 0 then Zs[i] = { -Zs[i][1], -Zs[i][2], -Zs[i][3] } end end local nr = if closedSpine then ns - 1 else ns local nring = if closedCs then nc - 1 else nc local P = {} for i = 1, nr do local y, z = Ys[i], Zs[i] local x = cross(y, z) local si = if #sc >= i * 2 then i else 1 local sx, sz = sc[si * 2 - 1] or 1, sc[si * 2] or 1 local oi = if #ori >= i * 4 then i else 1 local ax, ang = norm({ ori[oi * 4 - 3] or 0, ori[oi * 4 - 2] or 0, ori[oi * 4 - 1] or 1 }), ori[oi * 4] or 0 for j = 1, nring do local v = { cs[j * 2 - 1] * sx, 0, cs[j * 2] * sz } if ang ~= 0 then v = rotate(v, ax, ang) end local s = spine[i] table.insert(P, s[1] + x[1] * v[1] + y[1] * v[2] + z[1] * v[3]) table.insert(P, s[2] + x[2] * v[1] + y[2] * v[2] + z[2] * v[3]) table.insert(P, s[3] + x[3] * v[1] + y[3] * v[2] + z[3] * v[3]) end end local corners, sizes = {}, {} local function at(i: number, j: number): number return ((i - 1) % nr) * nring + (j - 1) % nring end for i = 1, ns - 1 do for j = 1, nc - 1 do for _, c in { at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1) } do table.insert(corners, c) end table.insert(sizes, 4) end end if not closedSpine then if bool(n, "beginCap", true) then for j = 1, nring do table.insert(corners, at(1, j)) end table.insert(sizes, nring) end if bool(n, "endCap", true) then for j = nring, 1, -1 do table.insert(corners, at(ns, j)) end table.insert(sizes, nring) end end return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV) end local function lines(n: any, maxV: number): (any, string?) local P = points(n, "coord", "point") or {} local np = #P // 3 local C, cc = colors(n) local perVertex = bool(n, "colorPerVertex", true) local runs: { { number } } = {} if n.type == "LineSet" then local at = 0 for _, c in nums(n, "vertexCount") or {} do local r = {} for q = 0, c - 1 do r[q + 1] = at + q end at += c table.insert(runs, r) end else local corners, sizes = split(nums(n, "coordIndex") or {}) local k = 0 for _, s in sizes do local r = {} for q = 1, s do r[q] = corners[k + q] end k += s table.insert(runs, r) end end local cIdx = nums(n, "colorIndex") or {} local cList = if perVertex then cornerList(cIdx) else nil local vkey: { [string]: number } = {} local src: { { number } } = {} local out: { number } = {} local k = 0 for li, r in runs do local prev: number? = nil for _, c in r do k += 1 if c == nil or c < 0 or c >= np then prev = nil continue end local ci = if not C then -1 elseif perVertex then (if cList then cList[k] or c else c) else (cIdx[li] or li - 1) local key = c .. ":" .. ci local v = vkey[key] if not v then v = #src src[v + 1] = { c, ci } vkey[key] = v end if prev then table.insert(out, prev) table.insert(out, v) end prev = v end end if #src > maxV then return nil, "limit: more than " .. maxV .. " vertices" end local pos = S.accessor(nil, "f32", 3, #src) local col = if C then S.accessor(nil, "f32", cc, #src) else nil for v, s in src do for q = 0, 2 do buffer.writef32(pos.data, ((v - 1) * 3 + q) * 4, P[s[1] * 3 + q + 1]) end if col and C then for q = 0, cc - 1 do buffer.writef32(col.data, ((v - 1) * cc + q) * 4, C[s[2] * cc + q + 1] or 1) end end end return { attributes = { POSITION = pos, COLOR_0 = col } :: any, indices = u32(out), mode = "lines" } end local function pointSet(n: any, maxV: number): (any, string?) local P = points(n, "coord", "point") or {} local np = #P // 3 if np > maxV then return nil, "limit: more than " .. maxV .. " points" end local C, cc = colors(n) local attrs: { [string]: Types.Accessor } = { POSITION = f32(P, 3, np) } if C then local col = S.accessor(nil, "f32", cc, np) for i = 0, np * cc - 1 do buffer.writef32(col.data, i * 4, C[i + 1] or 1) end attrs.COLOR_0 = col end return { attributes = attrs, mode = "points" } end local function direct(P: { number }, N: { number }, T: { number }, I: { number }, o: Options): Types.Primitive local nv = #P // 3 if o.flipV ~= false then for i = 2, #T, 2 do T[i] = 1 - T[i] end end return { attributes = { POSITION = f32(P, 3, nv), NORMAL = f32(N, 3, nv), TEXCOORD_0 = f32(T, 2, nv) }, indices = u32(I), mode = "triangles", } end local function box(n: any, o: Options): Types.Primitive local s = vec(n, "size", { 2, 2, 2 }) local hx, hy, hz = s[1] / 2, s[2] / 2, s[3] / 2 local P, N, T, I = {}, {}, {}, {} -- faces: normal, u axis, v axis (the specification's texture orientation) local FACES = { { { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 0 } }, { { 0, 0, -1 }, { -1, 0, 0 }, { 0, 1, 0 } }, { { 1, 0, 0 }, { 0, 0, -1 }, { 0, 1, 0 } }, { { -1, 0, 0 }, { 0, 0, 1 }, { 0, 1, 0 } }, { { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 } }, { { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, 1 } }, } for f, face in FACES do local nn, u, v = face[1], face[2], face[3] for _, c in { { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } } do for q = 1, 3 do local h = if q == 1 then hx elseif q == 2 then hy else hz table.insert(P, (nn[q] + u[q] * c[1] + v[q] * c[2]) * h) table.insert(N, nn[q]) end table.insert(T, (c[1] + 1) / 2) table.insert(T, (c[2] + 1) / 2) end local b = (f - 1) * 4 for _, x in { 0, 1, 2, 0, 2, 3 } do table.insert(I, b + x) end end return direct(P, N, T, I, o) end -- a ring of segs + 1 vertices (seam doubled); s starts at the back (-z) and runs counter-clockwise seen from +y local function ring(P: { number }, N: { number }?, T: { number }?, segs: number, y: number, r: number, t: number, ny: number?, nr: number?) for i = 0, segs do local a = 2 * pi * i / segs local x, z = -sin(a), -cos(a) table.insert(P, x * r) table.insert(P, y) table.insert(P, z * r) if N then table.insert(N, x * (nr or 1)) table.insert(N, ny or 0) table.insert(N, z * (nr or 1)) end if T then table.insert(T, i / segs) table.insert(T, t) end end end local function cap(P: { number }, N: { number }, T: { number }, I: { number }, segs: number, y: number, r: number, ny: number) local b = #P // 3 for i = 0, segs - 1 do local a = 2 * pi * i / segs local x, z = -sin(a), -cos(a) table.insert(P, x * r) table.insert(P, y) table.insert(P, z * r) table.insert(N, 0) table.insert(N, ny) table.insert(N, 0) -- the specification maps the cap like a top view: s = x, t = -z (top) or z (bottom) table.insert(T, x / 2 + 0.5) table.insert(T, (if ny > 0 then -z else z) / 2 + 0.5) end for i = 1, segs - 2 do -- the ring runs counter-clockwise seen from +y: in order for the top, reversed for the bottom if ny > 0 then table.insert(I, b) table.insert(I, b + i) table.insert(I, b + i + 1) else table.insert(I, b) table.insert(I, b + i + 1) table.insert(I, b + i) end end end local function band(I: { number }, a: number, b: number, segs: number) for i = 0, segs - 1 do table.insert(I, a + i) table.insert(I, a + i + 1) table.insert(I, b + i + 1) table.insert(I, a + i) table.insert(I, b + i + 1) table.insert(I, b + i) end end local function sphere(n: any, o: Options, segs: number): Types.Primitive local r = num(n, "radius", 1) local rings = math.max(2, segs // 2) local P, N, T, I = {}, {}, {}, {} for j = 0, rings do local phi = pi * j / rings -- from the bottom local y, rr = -cos(phi), sin(phi) ring(P, N, T, segs, y * r, rr * r, j / rings, y, rr) end for j = 0, rings - 1 do band(I, j * (segs + 1), (j + 1) * (segs + 1), segs) end return direct(P, N, T, I, o) end local function cylinder(n: any, o: Options, segs: number, cone: boolean): Types.Primitive local r = num(n, if cone then "bottomRadius" else "radius", 1) local h = num(n, "height", 2) local P, N, T, I = {}, {}, {}, {} if bool(n, "side", true) then -- side normals: a cone's lean outwards by its slope local l = sqrt(r * r + h * h) local ny, nr = if cone and l > 0 then r / l else 0, if cone and l > 0 then h / l else 1 ring(P, N, T, segs, -h / 2, r, 0, ny, nr) ring(P, N, T, segs, h / 2, if cone then 0 else r, 1, ny, nr) band(I, 0, segs + 1, segs) end if not cone and bool(n, "top", true) then cap(P, N, T, I, segs, h / 2, r, 1) end if bool(n, "bottom", true) then cap(P, N, T, I, segs, -h / 2, r, -1) end return direct(P, N, T, I, o) end function Geometry.primitive(n: any, o: Options): (Types.Primitive?, any) local t = n.type local maxV = o.maxVertices or 2 ^ 24 local segs = math.clamp(math.floor(o.segments or 32), 3, 1024) local solid = bool(n, "solid", true) local prim: Types.Primitive?, err: string? = nil, nil if t == "IndexedFaceSet" then prim, err = faceSet(n, o, maxV) elseif t == "IndexedTriangleSet" or t == "TriangleSet" or t == "IndexedTriangleFanSet" or t == "TriangleFanSet" or t == "IndexedTriangleStripSet" or t == "TriangleStripSet" or t == "IndexedQuadSet" or t == "QuadSet" then prim, err = triSet(n, o, maxV) elseif t == "ElevationGrid" then prim, err = elevationGrid(n, o, maxV) elseif t == "Extrusion" then prim, err = extrusion(n, o, maxV) elseif t == "IndexedLineSet" or t == "LineSet" then prim, err = lines(n, maxV) solid = false elseif t == "PointSet" then prim, err = pointSet(n, maxV) solid = false elseif t == "Box" then prim = box(n, o) elseif t == "Sphere" then prim = sphere(n, o, segs) elseif t == "Cylinder" then prim = cylinder(n, o, segs, false) elseif t == "Cone" then prim = cylinder(n, o, segs, true) else return nil, nil end if not prim then return nil, err end return prim, solid end return Geometry end __FILES["codecs/model/Vrml/Parse"] = function() -- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic (ISO/IEC 19776-2) encoding parser. -- Written from the specifications; no third-party code. local Parse = {} type Node = { type: string, def: string?, fields: { [string]: any } } type Route = { from: Node, fromField: string, to: Node, toField: string } type Proto = { name: string, fields: { [string]: any }, body: { Node }, routes: { Route }, extern: boolean? } type Graph = { roots: { Node }, routes: { Route }, header: { [string]: any }, meta: { [string]: string }, components: { string }, units: { [string]: { name: string, factor: number } }, protos: { [string]: Proto }, } type IsRef = { is: string } local find, sub, byte, match, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch local ID1 = "^[^%c%s%d\"#',%+%-%.%[\\%]{}][^%c%s\"#',%.%[\\%]{}]*" local MAX_DEPTH = 200 local DECL = { field = true, exposedField = true, eventIn = true, eventOut = true, initializeOnly = true, inputOutput = true, inputOnly = true, outputOnly = true } local HAS_VALUE = { field = true, exposedField = true, initializeOnly = true, inputOutput = true } local function copy(node: Node, values: { [string]: any }, defaults: { [string]: any }, memo: { [any]: any }): Node local done = memo[node] if done then return done end local out: Node = { type = node.type, def = node.def, fields = {} } memo[node] = out for k, v in node.fields do if type(v) == "table" and type((v :: any).is) == "string" then local name = (v :: any).is local val = values[name] if val == nil then val = defaults[name] end out.fields[k] = val elseif type(v) == "table" then local arr = table.create(#v) for i, x in v do arr[i] = if type(x) == "table" and x.type then copy(x, values, defaults, memo) else x end out.fields[k] = arr else out.fields[k] = v end end return out end function Parse.expand(proto: Proto, values: { [string]: any }, def: string?, routes: { Route }?): Node? if proto.extern or #proto.body == 0 then return nil end local memo = {} local first: Node? = nil for _, n in proto.body do local c = copy(n, values, proto.fields, memo) first = first or c end if routes then for _, r in proto.routes do local from, to = memo[r.from], memo[r.to] if from and to then table.insert(routes, { from = from, fromField = r.fromField, to = to, toField = r.toField }) end end end local f = first :: Node if def then -- the instance gets its own copy of the node so its DEF name is its own local out: Node = { type = f.type, def = def, fields = f.fields } return out end return f end function Parse.parse(text: string): (Graph?, string?) local n = #text local p = 1 local graph: Graph = { roots = {}, routes = {}, header = {}, meta = {}, components = {}, units = {}, protos = {} } local defs: { [string]: Node } = {} local protos: { [string]: Proto } = graph.protos local routes: { Route } = graph.routes local failure: string? = nil local depth = 0 local function line(at: number): number local l = 1 for _ in gmatch(sub(text, 1, at), "\n") do l += 1 end return l end local function fail(msg: string) if not failure then failure = "line " .. line(p) .. ": " .. msg end end -- header line: #VRML V2.0 utf8 / #X3D V3.3 utf8 local v, enc = match(text, "^#VRML V(%S+) (%S+)") if v then graph.header.version, graph.header.encoding = v, enc if v ~= "2.0" then return nil, "unsupported: VRML " .. v .. " (only VRML97 / X3D)" end else v, enc = match(text, "^#X3D V(%S+) (%S+)") if v then graph.header.version, graph.header.encoding, graph.header.x3d = v, enc, true end end local function skip() while true do local q = find(text, "[^%s,]", p) if not q then p = n + 1 return end p = q if byte(text, p) == 35 then -- '#' local e = find(text, "[\r\n]", p) p = if e then e else n + 1 else return end end end local function token(): (string, any) skip() if p > n then return "eof", nil end local c = byte(text, p) if c == 123 or c == 125 or c == 91 or c == 93 then -- { } [ ] p += 1 return string.char(c), nil elseif c == 34 then -- a string: \" and \\ escapes local q = p + 1 local parts = {} while true do local e = find(text, '["\\]', q) if not e then fail("unterminated string") p = n + 1 return "eof", nil end table.insert(parts, sub(text, q, e - 1)) if byte(text, e) == 92 then table.insert(parts, sub(text, e + 1, e + 1)) q = e + 2 else p = e + 1 return "str", table.concat(parts) end end end if (c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46 then local s, e = find(text, "^[+-]?0[xX]%x+", p) if not s then s, e = find(text, "^[+-]?%d*%.?%d*[eE][+-]?%d+", p) end if not s then s, e = find(text, "^[+-]?%d*%.?%d*", p) end local num = tonumber(sub(text, p, e)) if num then p = (e :: number) + 1 return "num", num end if c == 46 then p += 1 return ".", nil end local _, we = find(text, "^[^%s,%[%]{}#\"]+", p) local w = sub(text, p, we) p = (we :: number) + 1 local wl = string.lower(w) local val = if find(wl, "inf", 1, true) then (if c == 45 then -math.huge else math.huge) elseif find(wl, "nan", 1, true) then 0 else nil if val == nil then fail("bad number " .. w) return "eof", nil end return "num", val end local s, e = find(text, ID1, p) if s then p = (e :: number) + 1 return "id", sub(text, s, e) end fail("unexpected character " .. sub(text, p, p)) p = n + 1 return "eof", nil end local function peek(): (string, any) local save = p local k, val = token() p = save return k, val end local parseNode: (first: string) -> (Node?, boolean) local parseProto: (extern: boolean) -> () local parseRoute: () -> () local function value(): any local k, val = token() if k == "[" then local out = {} local close = find(text, "]", p, true) if close then local seg = sub(text, p, close - 1) if not find(seg, "[{}\"#]") then local ok = true for w in gmatch(seg, "[^%s,]+") do local x = tonumber(w) if x then table.insert(out, x) elseif w == "TRUE" or w == "FALSE" then table.insert(out, w == "TRUE") else ok = false break end end if ok then p = close + 1 return out end table.clear(out) end end while not failure do k, val = token() if k == "]" then return out elseif k == "num" or k == "str" then table.insert(out, val) elseif k == "id" and (val == "TRUE" or val == "FALSE") then table.insert(out, val == "TRUE") elseif k == "id" and val == "NULL" then continue elseif k == "id" then local node = parseNode(val) if node then table.insert(out, node) end else fail("unexpected " .. k .. " in a [ ] value") return out end end return out elseif k == "num" then local out = { val } while true do local save = p local k2, v2 = token() if k2 ~= "num" then p = save break end table.insert(out, v2) end return out elseif k == "str" then return { val } elseif k == "id" then if val == "TRUE" or val == "FALSE" then return { val == "TRUE" } elseif val == "NULL" then return {} end local node = parseNode(val) return if node then { node } else {} end fail("missing field value") return {} end local function body(node: Node) while not failure do local k, name = token() if k == "}" then return elseif k ~= "id" then fail("expected a field name in " .. node.type .. ", got " .. k) return end if name == "ROUTE" then parseRoute() elseif name == "PROTO" or name == "EXTERNPROTO" then parseProto(name == "EXTERNPROTO") elseif DECL[name] then -- Script / shader interface: [ | 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: string): (Node?, boolean) if first == "USE" then local k, name = token() if k ~= "id" then fail("USE without a name") return nil, false end local node = defs[name] if not node then fail("USE of an undefined name " .. tostring(name)) end return node, true end local def: string? = nil local typ = first if first == "DEF" then local k, name = token() local k2, t2 = token() if k ~= "id" or k2 ~= "id" then fail("bad DEF") return nil, false end def, typ = name, t2 end local k = token() if k ~= "{" then fail("expected { after " .. typ) return nil, false end depth += 1 if depth > MAX_DEPTH then fail("limit: nodes nested deeper than " .. MAX_DEPTH) return nil, false end local node: Node = { type = typ, def = def, fields = {} } body(node) depth -= 1 local proto = protos[typ] if proto and not proto.extern then local inst = Parse.expand(proto, node.fields, def, routes) if inst then node = inst end elseif proto then (node :: any).extern = true end if def then defs[def] = node end return node, false end -- ROUTE from.field TO to.field function parseRoute() local function path(): (string?, string?) local k1, a = token() local k2 = token() local k3, b = token() if k1 ~= "id" or k2 ~= "." or k3 ~= "id" then return nil, nil end return a, b end local a, af = path() local k, to = token() local b, bf = path() if not (a and af and b and bf) or k ~= "id" or to ~= "TO" then fail("bad ROUTE") return end local from, dst = defs[a :: string], defs[b :: string] if from and dst then table.insert(routes, { from = from, fromField = af :: string, to = dst, toField = bf :: string }) end end -- PROTO name [ interface ] { body } / EXTERNPROTO name [ interface ] url function parseProto(extern: boolean) local k, name = token() if k ~= "id" or token() ~= "[" then fail("bad PROTO") return end local proto: Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } while not failure do local k2, access = token() if k2 == "]" then break elseif k2 ~= "id" or not DECL[access] then fail("bad PROTO interface") return end local _, _t = token() local fk, fname = token() if fk ~= "id" then fail("bad PROTO interface") return end if HAS_VALUE[access] and not extern then proto.fields[fname] = value() end end if extern then value() protos[name] = proto return end if token() ~= "{" then fail("PROTO " .. tostring(name) .. " without a body") return end -- the body has its own DEF names and its own routes local outerDefs, outerRoutes = defs, routes defs, routes = {}, proto.routes while not failure do local k3, w = token() if k3 == "}" then break elseif k3 ~= "id" then fail("bad PROTO body") break elseif w == "ROUTE" then parseRoute() elseif w == "PROTO" or w == "EXTERNPROTO" then parseProto(w == "EXTERNPROTO") else local node = parseNode(w) if node then table.insert(proto.body, node) end end end defs, routes = outerDefs, outerRoutes protos[name] = proto end while not failure do local k, w = token() if k == "eof" then break elseif k ~= "id" then fail("unexpected " .. k) break end if w == "ROUTE" then parseRoute() elseif w == "PROTO" or w == "EXTERNPROTO" then parseProto(w == "EXTERNPROTO") elseif w == "PROFILE" then local _, prof = token() graph.header.profile = prof elseif w == "COMPONENT" then local _, comp = token() -- name:level is one id table.insert(graph.components, tostring(comp)) elseif w == "META" then local _, key = token() local _, val = token() graph.meta[tostring(key)] = tostring(val) elseif w == "UNIT" then local _, cat = token() local _, uname = token() local _, factor = token() if type(cat) == "string" and type(factor) == "number" then graph.units[cat] = { name = tostring(uname), factor = factor } end elseif w == "IMPORT" or w == "EXPORT" then -- IMPORT inline.name AS name / EXPORT name AS name: no effect on the scene local _, _a = token() if peek() == "." then token() token() end local pk, pv = peek() if pk == "id" and pv == "AS" then token() token() end else local node = parseNode(w) if node then table.insert(graph.roots, node) end end end if failure then return nil, failure end return graph, nil end return Parse end __FILES["codecs/model/Vrml/Write"] = function() -- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML. New code. local Types = __include("Types") local Mat4 = __include("codecs/model/Mat4") local Flatten = __include("codecs/model/MeshFlatten") local Xml = __include("codecs/text/Xml") local Write = {} type Options = { encoding: ("vrml97" | "x3dv" | "xml")?, files: { [string]: any }?, name: string?, flipV: boolean? } type WNode = { type: string, def: string?, use: string?, fields: { { any } } } local format, concat = string.format, table.concat local function fmt(v: number): string if v ~= v then return "0" elseif v == math.huge then return "1e38" elseif v == -math.huge then return "-1e38" elseif v == math.floor(v) and math.abs(v) < 2 ^ 53 then return format("%d", v) end return format("%.9g", v) end local function W(t: string, def: string?): WNode return { type = t, def = def, fields = {} } end local function F(n: WNode, name: string, kind: string, value: any, per: number?) table.insert(n.fields, { name, kind, value, per }) end local function namer(): (string?, string) -> string local used: { [string]: boolean } = {} return function(name: string?, fallback: string): string local s = string.gsub(name or "", "[^%w_]", "_") if s == "" or string.find(s, "^%d") then s = fallback .. (if s ~= "" then "_" .. s else "") end local base, k = s, 1 while used[s] do k += 1 s = base .. "_" .. k end used[s] = true return s end end local function axisAngle(q: { number }): { number } local x, y, z, w = q[1], q[2], q[3], q[4] local l = math.sqrt(x * x + y * y + z * z + w * w) if l > 0 then x, y, z, w = x / l, y / l, z / l, w / l end local s = math.sqrt(math.max(0, 1 - w * w)) if s < 1e-9 then return { 0, 0, 1, 0 } end return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) } end local function values(acc: any): { number }? return (Flatten.numbers(acc)) end local function faceSet(prim: any, doubleSided: boolean, o: Options, x3d: boolean): (WNode?, string?) local tmp = { kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } } local keep = function(n: string): boolean return n == "NORMAL" or n == "TEXCOORD_0" or n == "COLOR_0" end local m, err = Flatten.merge(tmp, keep, { triangulate = false }) if not m then return nil, err end if not m.sizes or #m.sizes == 0 then return nil, nil end local g = W("IndexedFaceSet") local coord = W("Coordinate") F(coord, "point", "mf", m.attrs.POSITION.values, 3) F(g, "coord", "node", coord) local idx = {} local p = 0 for _, s in m.sizes do for k = 1, s do table.insert(idx, m.corners[p + k]) end table.insert(idx, -1) p += s end F(g, "coordIndex", "mf", idx, 0) local nrm = m.attrs.NORMAL if nrm then local nn = W("Normal") F(nn, "vector", "mf", nrm.values, 3) F(g, "normal", "node", nn) end local tc = m.attrs.TEXCOORD_0 if tc then local t = W("TextureCoordinate") local vals, c = {}, tc.components for i = 0, m.count - 1 do local s, tt = tc.values[i * c + 1], tc.values[i * c + 2] table.insert(vals, s) table.insert(vals, if o.flipV ~= false then 1 - tt else tt) end F(t, "point", "mf", vals, 2) F(g, "texCoord", "node", t) end local col = m.attrs.COLOR_0 if col then local c = col.components local rgba = c >= 4 and x3d local cn = W(if rgba then "ColorRGBA" else "Color") local vals = {} local scale = if col.raw then (if col.type == "unorm8" then 255 elseif col.type == "unorm16" then 65535 else 1) else 1 for i = 0, m.count - 1 do for k = 1, if rgba then 4 else 3 do table.insert(vals, (col.values[i * c + k] or 1) / scale) end end F(cn, "color", "mf", vals, if rgba then 4 else 3) F(g, "color", "node", cn) end F(g, "solid", "bool", not doubleSided) return g, nil end local function coordNode(prim: any): (WNode?, number) local pos = values(prim.attributes.POSITION) if not pos then return nil, 0 end local nv, pc = prim.attributes.POSITION.count, prim.attributes.POSITION.components local p3 = {} for i = 0, nv - 1 do for k = 1, 3 do table.insert(p3, pos[i * pc + k] or 0) end end local coord = W("Coordinate") F(coord, "point", "mf", p3, 3) return coord, nv end local function colorNode(prim: any, nv: number, x3d: boolean): WNode? local acc = prim.attributes.COLOR_0 local col = acc and values(acc) if not col then return nil end local c = acc.components local rgba = c >= 4 and x3d local vals = {} for i = 0, nv - 1 do for k = 1, if rgba then 4 else 3 do table.insert(vals, col[i * c + k] or 1) end end local cn = W(if rgba then "ColorRGBA" else "Color") F(cn, "color", "mf", vals, if rgba then 4 else 3) return cn end local function lineSet(prim: any, x3d: boolean): (WNode?, string?) local coord, nv = coordNode(prim) if not coord then return nil, "lines without POSITION" end local ind: { number } if prim.indices then ind = values(prim.indices) or {} else ind = {} for i = 0, nv - 1 do ind[i + 1] = i end end local idx = {} local mode = prim.mode if mode == "lines" then for i = 1, #ind - 1, 2 do table.insert(idx, ind[i]) table.insert(idx, ind[i + 1]) table.insert(idx, -1) end else for _, v in ind do table.insert(idx, v) end if mode == "line_loop" and #ind > 0 then table.insert(idx, ind[1]) end table.insert(idx, -1) end for _, v in idx do if v >= nv then return nil, "line index out of range" end end local g = W("IndexedLineSet") F(g, "coord", "node", coord) local cn = colorNode(prim, nv, x3d) if cn then F(g, "color", "node", cn) end F(g, "coordIndex", "mf", idx, 0) return g, nil end local function pointSet(prim: any, x3d: boolean): (WNode?, string?) local coord, nv = coordNode(prim) if not coord then return nil, "points without POSITION" end local g = W("PointSet") F(g, "coord", "node", coord) local cn = colorNode(prim, nv, x3d) if cn then F(g, "color", "node", cn) end return g, nil end local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2" } local function textureUrl(scene: any, i: number, o: Options, written: { [number]: string }): string? if written[i] then return written[i] end local tex = scene.textures[i] if not tex then return nil end local url = tex.uri if tex.data and type(o.files) == "table" then local base = string.match(o.name or "model", "([^/\\]+)$") or "model" base = string.gsub(base, "%.[^.]*$", "") local ext = EXT[tex.mime or ""] or (url and string.match(url, "%.(%w+)$")) or "png" local file = if url and not string.find(url, "^data:") and not string.find(url, "[/\\]") then url else format("%s_%d.%s", base, i, ext) o.files[file] = tex.data url = file end if url then written[i] = url end return url end local function appearance(scene: any, mi: number, o: Options, written: { [number]: string }): WNode local m = scene.materials[mi] local app = W("Appearance") local mat = W("Material") local x = m.extras and m.extras.vrml or {} local c = m.baseColor or { 1, 1, 1, 1 } F(mat, "diffuseColor", "sf", { c[1], c[2], c[3] }) local e = m.emissive or { 0, 0, 0 } if e[1] ~= 0 or e[2] ~= 0 or e[3] ~= 0 then F(mat, "emissiveColor", "sf", { e[1], e[2], e[3] }) end if type(x.specularColor) == "table" then F(mat, "specularColor", "sf", x.specularColor) end local sh = x.shininess if type(sh) ~= "number" then local r = math.max(m.roughness or 1, 1e-3) sh = math.clamp((2 / (r * r) - 2) / 128, 0, 1) end F(mat, "shininess", "sf", { sh }) if type(x.ambientIntensity) == "number" then F(mat, "ambientIntensity", "sf", { x.ambientIntensity }) end if (c[4] or 1) < 1 then F(mat, "transparency", "sf", { 1 - c[4] }) end F(app, "material", "node", mat) local ref = m.baseColorTexture if ref and type(ref.texture) == "number" then local url = textureUrl(scene, ref.texture, o, written) local img = scene.textures[ref.texture] and scene.textures[ref.texture].image if url or (img and img.format == "rgba8" and img.width * img.height <= 2 ^ 20) then local it if url then it = W("ImageTexture") F(it, "url", "mstr", { url }) else -- a decoded image only: PixelTexture (SFImage: width height 4, then 0xRRGGBBAA from the bottom row up) it = W("PixelTexture") local w, h = img.width, img.height local v = { w, h, 4 } for row = h - 1, 0, -1 do for x = 0, w - 1 do table.insert(v, buffer.readu32(img.pixels, (row * w + x) * 4)) end end -- the pixels are little-endian RGBA bytes: swap to 0xRRGGBBAA for i = 4, #v do local p = v[i] v[i] = (p % 256) * 16777216 + (p // 256 % 256) * 65536 + (p // 65536 % 256) * 256 + p // 16777216 end F(it, "image", "sf", v) end local s = scene.textures[ref.texture].sampler if s and s.wrapS == "clamp" then F(it, "repeatS", "bool", false) end if s and s.wrapT == "clamp" then F(it, "repeatT", "bool", false) end F(app, "texture", "node", it) local tf = ref.transform if tf then local tt = W("TextureTransform") if tf.offset then F(tt, "translation", "sf", tf.offset) end if tf.scale then F(tt, "scale", "sf", tf.scale) end if tf.rotation then F(tt, "rotation", "sf", { tf.rotation }) end F(app, "textureTransform", "node", tt) end end end return app end function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, string?) local x3d = o.encoding == "x3dv" or o.encoding == "xml" local name = namer() local nodeDef: { [number]: string } = {} local meshShapes: { [number]: { WNode } } = {} local appDef: { [any]: string } = {} local written: { [number]: string } = {} local failure: string? = nil local function shapes(mi: number): { WNode } local done = meshShapes[mi] if done then local out = {} for _, s in done do table.insert(out, { type = "Shape", use = s.def, fields = {} }) end return out end local mesh = scene.meshes[mi] local out = {} for pi, prim in (if mesh then mesh.primitives else {}) :: { any } do local mode = prim.mode or "triangles" local mat = if type(prim.material) == "number" then scene.materials[prim.material] else nil local geo, err if mode == "lines" or mode == "line_strip" or mode == "line_loop" then geo, err = lineSet(prim, x3d) elseif mode == "points" then geo, err = pointSet(prim, x3d) else geo, err = faceSet(prim, mat ~= nil and mat.doubleSided == true, o, x3d) end if err then failure = failure or err end if geo then local sh = W("Shape", name((mesh.name or "mesh") .. (if #mesh.primitives > 1 then "_" .. pi else ""), "Shape")) if mat then local key = prim.material if appDef[key] then F(sh, "appearance", "node", { type = "Appearance", use = appDef[key], fields = {} }) else local app = appearance(scene, prim.material, o, written) app.def = name(mat.name, "Material") appDef[key] = app.def F(sh, "appearance", "node", app) end end F(sh, "geometry", "node", geo) table.insert(out, sh) end end meshShapes[mi] = out return out end local visiting: { [number]: boolean } = {} local function transform(ni: number): WNode? local n = scene.nodes[ni] if type(n) ~= "table" or visiting[ni] then return nil end visiting[ni] = true local def = name(n.name, "Node") nodeDef[ni] = def local t = W("Transform", def) local tr, rot, sc = n.translation, n.rotation, n.scale if n.matrix then tr, rot, sc = Mat4.decompose(n.matrix) end if tr and (tr[1] ~= 0 or tr[2] ~= 0 or tr[3] ~= 0) then F(t, "translation", "sf", { tr[1], tr[2], tr[3] }) end if rot then local aa = axisAngle(rot) if aa[4] ~= 0 then F(t, "rotation", "sf", aa) end end if sc and (sc[1] ~= 1 or sc[2] ~= 1 or sc[3] ~= 1) then F(t, "scale", "sf", { sc[1], sc[2], sc[3] }) end local kids: { WNode } = {} if type(n.mesh) == "number" then for _, s in shapes(n.mesh) do table.insert(kids, s) end end local cam = if type(n.camera) == "number" then scene.cameras[n.camera] else nil if cam then local v if cam.type == "orthographic" and x3d then v = W("OrthoViewpoint") local xm, ym = cam.xmag or 1, cam.ymag or 1 F(v, "fieldOfView", "sf", { -xm, -ym, xm, ym }) else v = W("Viewpoint") F(v, "fieldOfView", "sf", { cam.yfov or 0.785398 }) end F(v, "position", "sf", { 0, 0, 0 }) if cam.name then F(v, "description", "str", cam.name) end table.insert(kids, v) end local l = if type(n.light) == "number" then scene.lights[n.light] else nil if l then local typ = if l.type == "directional" then "DirectionalLight" elseif l.type == "spot" then "SpotLight" else "PointLight" local ln = W(typ) local c = l.color or { 1, 1, 1 } F(ln, "color", "sf", { c[1], c[2], c[3] }) F(ln, "intensity", "sf", { math.clamp(l.intensity or 1, 0, 1) }) if typ ~= "PointLight" then F(ln, "direction", "sf", { 0, 0, -1 }) end if typ ~= "DirectionalLight" then F(ln, "location", "sf", { 0, 0, 0 }) F(ln, "radius", "sf", { l.range or 100 }) end if typ == "SpotLight" then F(ln, "cutOffAngle", "sf", { l.outerCone or 0.785398 }) F(ln, "beamWidth", "sf", { l.innerCone or 0 }) end table.insert(kids, ln) end for _, c in n.children or {} do local ct = transform(c) if ct then table.insert(kids, ct) end end if #kids > 0 then F(t, "children", "nodes", kids) end visiting[ni] = nil return t end local roots: { WNode } = {} local list = scene.roots if type(list) ~= "table" or #list == 0 then local child = {} for _, n in scene.nodes do for _, c in n.children or {} do child[c] = true end end list = {} for i = 1, #scene.nodes do if not child[i] then table.insert(list, i) end end end for _, ri in list do local t = transform(ri) if t then table.insert(roots, t) end end if #scene.nodes == 0 then for mi = 1, #scene.meshes do for _, s in shapes(mi) do table.insert(roots, s) end end end local routes: { { string } } = {} for ai, anim in scene.animations or {} do local tmax = 0 local chans = {} for _, ch in anim.channels or {} do local target = nodeDef[ch.node] if target and (ch.path == "translation" or ch.path == "rotation" or ch.path == "scale") then local input, output = values(ch.input), values(ch.output) if input and output and #input > 0 then tmax = math.max(tmax, input[#input]) table.insert(chans, { ch, target, input, output }) end end end if #chans > 0 then local cycle = if tmax > 0 then tmax else 1 local ts = W("TimeSensor", name(anim.name, "Animation" .. ai)) F(ts, "cycleInterval", "sf", { cycle }) F(ts, "loop", "bool", true) table.insert(roots, ts) for k, c in chans do local ch, target, input, output = c[1], c[2], c[3], c[4] local rot = ch.path == "rotation" local it = W(if rot then "OrientationInterpolator" else "PositionInterpolator", name(ts.def .. "_" .. k, "Interpolator")) local keys = {} for i, tv in input do keys[i] = tv / cycle end local comps = if rot then 4 else 3 local stride = #output // #input -- CUBICSPLINE stores in-tangent, value, out-tangent per key local off = if ch.interpolation == "CUBICSPLINE" and stride == comps * 3 then comps else 0 local kv = {} for i = 0, #input - 1 do local v = {} for q = 1, comps do v[q] = output[i * stride + off + q] or 0 end if rot then v = axisAngle(v) end for _, x in v do table.insert(kv, x) end end F(it, "key", "mf", keys, 0) F(it, "keyValue", "mf", kv, comps) table.insert(roots, it) table.insert(routes, { ts.def :: string, "fraction_changed", it.def :: string, "set_fraction" }) table.insert(routes, { it.def :: string, "value_changed", target, "set_" .. ch.path }) end end end if failure then return nil, nil, failure end return roots, routes, nil end local function numbers(vals: { number }, per: number?, indent: string): string local out = table.create(#vals) for i, v in vals do out[i] = fmt(v) end if per == 0 then local lines, cur = {}, {} for i, v in vals do table.insert(cur, out[i]) if v == -1 then table.insert(lines, concat(cur, " ")) cur = {} end end if #cur > 0 then table.insert(lines, concat(cur, " ")) end return concat(lines, "\n" .. indent) end if per and per > 0 then local lines = {} for i = 1, #out, per do table.insert(lines, concat(out, " ", i, math.min(i + per - 1, #out))) end return concat(lines, ",\n" .. indent) end return concat(out, " ") end local function quote(s: string): string return '"' .. string.gsub(s, '(["\\])', "\\%1") .. '"' end local function classic(roots: { WNode }, routes: { { string } }, x3d: boolean): string local out = {} if x3d then table.insert(out, "#X3D V3.3 utf8\nPROFILE Interchange\n# written by rosetta\n") else table.insert(out, "#VRML V2.0 utf8\n# written by rosetta\n") end local function emit(n: WNode, ind: string): string if n.use then return "USE " .. n.use end local parts = { (if n.def then "DEF " .. n.def .. " " else "") .. n.type .. " {" } local ind2 = ind .. " " for _, f in n.fields do local fname, kind, v, per = f[1], f[2], f[3], f[4] local s if kind == "sf" then s = numbers(v, nil, ind2) elseif kind == "mf" then s = "[\n" .. ind2 .. " " .. numbers(v, per, ind2 .. " ") .. "\n" .. ind2 .. "]" elseif kind == "bool" then s = if v then "TRUE" else "FALSE" elseif kind == "str" then s = quote(v) elseif kind == "mstr" then local q = {} for i, x in v do q[i] = quote(x) end s = "[ " .. concat(q, " ") .. " ]" elseif kind == "node" then s = emit(v, ind2) else local q = {} for i, x in v do q[i] = ind2 .. " " .. emit(x, ind2 .. " ") end s = "[\n" .. concat(q, "\n") .. "\n" .. ind2 .. "]" end table.insert(parts, ind2 .. fname .. " " .. s) end table.insert(parts, ind .. "}") return concat(parts, "\n") end for _, r in roots do table.insert(out, emit(r, "")) end for _, r in routes do table.insert(out, format("ROUTE %s.%s TO %s.%s", r[1], r[2], r[3], r[4])) end return concat(out, "\n") .. "\n" end local DEFAULT = { Appearance = "appearance", Material = "material", ImageTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", IndexedFaceSet = "geometry", IndexedLineSet = "geometry", PointSet = "geometry" } local function xml(roots: { WNode }, routes: { { string } }): (string?, string?) local function element(n: WNode, field: string): any local attrs = Types.object() local kids = {} if (DEFAULT[n.type] or "children") ~= field then Types.set(attrs, "containerField", field) end if n.use then Types.set(attrs, "USE", n.use) return Xml.element(n.type, attrs :: any) end if n.def then Types.set(attrs, "DEF", n.def) end for _, f in n.fields do local fname, kind, v, per = f[1], f[2], f[3], f[4] if kind == "sf" then Types.set(attrs, fname, numbers(v, nil, "")) elseif kind == "mf" then local s = numbers(v, per, "") Types.set(attrs, fname, (string.gsub(s, "\n", " "))) elseif kind == "bool" then Types.set(attrs, fname, if v then "true" else "false") elseif kind == "str" then Types.set(attrs, fname, v) elseif kind == "mstr" then local q = {} for i, x in v do q[i] = quote(x) end Types.set(attrs, fname, concat(q, " ")) elseif kind == "node" then table.insert(kids, element(v, fname)) else for _, x in v do table.insert(kids, element(x, fname)) end end end return Xml.element(n.type, attrs :: any, kids) end local sceneKids = {} for _, r in roots do table.insert(sceneKids, element(r, "children")) end for _, r in routes do local a = Types.object() Types.set(a, "fromNode", r[1]) Types.set(a, "fromField", r[2]) Types.set(a, "toNode", r[3]) Types.set(a, "toField", r[4]) table.insert(sceneKids, Xml.element("ROUTE", a :: any)) end local ra = Types.object() Types.set(ra, "profile", "Interchange") Types.set(ra, "version", "3.3") local meta = Types.object() Types.set(meta, "name", "generator") Types.set(meta, "content", "rosetta") local root = Xml.element("X3D", ra :: any, { Xml.element("head", nil, { Xml.element("meta", meta :: any) }), Xml.element("Scene", nil, sceneKids) }) local s, err = Xml.encode(Xml.document(root, { version = "1.0", encoding = "UTF-8" }), { indent = 2 }) if not s then return nil, if err then err.message else "xml" end return s, nil end function Write.text(scene: any, o: Options): (string?, string?) local roots, routes, err = Write.graph(scene, o) if not roots or not routes then return nil, err end if o.encoding == "xml" then return xml(roots, routes) end return classic(roots, routes, o.encoding == "x3dv"), nil end return Write end __FILES["codecs/model/Vrml/Xml"] = function() -- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the Vrml/Parse node graph. New code. local Xml = __include("codecs/text/Xml") local Parse = __include("codecs/model/Vrml/Parse") local VXml = {} local GEOMETRY = { "Box", "Sphere", "Cone", "Cylinder", "IndexedFaceSet", "IndexedLineSet", "LineSet", "PointSet", "ElevationGrid", "Extrusion", "Text", "IndexedTriangleSet", "TriangleSet", "IndexedTriangleFanSet", "TriangleFanSet", "IndexedTriangleStripSet", "TriangleStripSet", "IndexedQuadSet", "QuadSet", "Arc2D", "ArcClose2D", "Circle2D", "Disk2D", "Polyline2D", "Polypoint2D", "Rectangle2D", "TriangleSet2D", "GeoElevationGrid", "NurbsPatchSurface", } local CONTAINER: { [string]: string } = { Appearance = "appearance", Material = "material", PhysicalMaterial = "material", TwoSidedMaterial = "material", UnlitMaterial = "material", ImageTexture = "texture", PixelTexture = "texture", MovieTexture = "texture", MultiTexture = "texture", ImageCubeMapTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", CoordinateDouble = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", MultiTextureCoordinate = "texCoord", TextureCoordinateGenerator = "texCoord", FontStyle = "fontStyle", TextureProperties = "textureProperties", FillProperties = "fillProperties", LineProperties = "lineProperties", } for _, g in GEOMETRY do CONTAINER[g] = "geometry" end local function container(el: Xml.Node, typ: string): string local c = el.attrs.containerField if type(c) == "string" and c ~= "" then return c end if string.sub(typ, 1, 8) == "Metadata" then return "metadata" end return CONTAINER[typ] or "children" end function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?) local root = doc.root or doc if type(root) ~= "table" or Xml.localName(root.name) ~= "X3D" then return nil, "no root element" end local graph: Parse.Graph = { roots = {}, routes = {}, header = { x3d = true, xml = true }, meta = {}, components = {}, units = {}, protos = {} } graph.header.version, graph.header.profile = root.attrs.version, root.attrs.profile local defs: { [string]: Parse.Node } = {} local protos = graph.protos local routes = graph.routes local depth = 0 local failure: string? = nil local convert: (el: Xml.Node) -> Parse.Node? local function route(el: Xml.Node) local a = el.attrs local from, to = defs[a.fromNode or ""], defs[a.toNode or ""] local ff, tf = a.fromField, a.toField if from and to and type(ff) == "string" and type(tf) == "string" then table.insert(routes, { from = from, fromField = ff, to = to, toField = tf }) end end local declare: (el: Xml.Node, extern: boolean) -> () local function children(el: Xml.Node, node: Parse.Node) for _, ch in el.children do if type(ch) ~= "table" or string.sub(ch.name, 1, 1) == "#" then continue end local name = Xml.localName(ch.name) if name == "ROUTE" then route(ch) elseif name == "IS" then for _, c in Xml.children(ch, "connect") do local nf, pf = c.attrs.nodeField, c.attrs.protoField if nf and pf then node.fields[nf] = { is = pf } end end elseif name == "ProtoDeclare" or name == "ExternProtoDeclare" then declare(ch, name == "ExternProtoDeclare") elseif name == "field" or name == "fieldValue" then continue -- Script / shader interfaces else local c = convert(ch) if c then local f = container(ch, if name == "ProtoInstance" then "" else name) local list = node.fields[f] if type(list) ~= "table" or (list :: any).is then list = {} node.fields[f] = list end table.insert(list, c) end end end end local function fieldValue(el: Xml.Node): any if el.attrs.value ~= nil then return el.attrs.value end local list = {} for _, ch in el.children do if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then local c = convert(ch) if c then table.insert(list, c) end end end return list end function declare(el: Xml.Node, extern: boolean) local name = el.attrs.name if not name then return end local proto: Parse.Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } local iface = if extern then el else Xml.child(el, "ProtoInterface") if iface then for _, f in Xml.children(iface, "field") do if f.attrs.name then proto.fields[f.attrs.name] = fieldValue(f) end end end local bodyEl = Xml.child(el, "ProtoBody") if bodyEl and not extern then local outerDefs, outerRoutes = defs, routes defs, routes = {}, proto.routes for _, ch in bodyEl.children do if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then local nm = Xml.localName(ch.name) if nm == "ROUTE" then route(ch) elseif nm == "ProtoDeclare" or nm == "ExternProtoDeclare" then declare(ch, nm == "ExternProtoDeclare") else local c = convert(ch) if c then table.insert(proto.body, c) end end end end defs, routes = outerDefs, outerRoutes end protos[name] = proto end function convert(el: Xml.Node): Parse.Node? local a = el.attrs if a.USE then return defs[a.USE] end depth += 1 if depth > 200 then failure = failure or "limit: nodes nested deeper than 200" depth -= 1 return nil end local typ = Xml.localName(el.name) local node: any if typ == "ProtoInstance" then local proto = protos[a.name or ""] local values = {} for _, fv in Xml.children(el, "fieldValue") do if fv.attrs.name then values[fv.attrs.name] = fieldValue(fv) end end local inst = proto and Parse.expand(proto, values, a.DEF, routes) node = inst or { type = a.name or "ProtoInstance", def = a.DEF, fields = values } else node = { type = typ, def = a.DEF, fields = {} } for k, v in a do if k ~= "DEF" and k ~= "USE" and k ~= "containerField" and k ~= "class" and not string.find(k, ":", 1, true) then node.fields[k] = v end end children(el, node) end depth -= 1 if a.DEF then defs[a.DEF] = node end return node end for _, ch in root.children do if type(ch) ~= "table" then continue end local name = Xml.localName(ch.name) if name == "head" then for _, h in ch.children do if type(h) == "table" then local hn = Xml.localName(h.name) if hn == "meta" and h.attrs.name then graph.meta[h.attrs.name] = h.attrs.content or "" elseif hn == "component" and h.attrs.name then table.insert(graph.components, h.attrs.name .. ":" .. (h.attrs.level or "1")) elseif hn == "unit" and h.attrs.category then graph.units[h.attrs.category] = { name = h.attrs.name or "", factor = tonumber(h.attrs.conversionFactor) or 1 } end end end elseif name == "Scene" then local scene: Parse.Node = { type = "Scene", fields = {} } children(ch, scene) local list = scene.fields.children if type(list) == "table" then graph.roots = list end for f, v in scene.fields do -- a top-level node with another containerField still shows if f ~= "children" and type(v) == "table" then for _, x in v do table.insert(graph.roots, x) end end end end end if failure then return nil, failure end return graph, nil end return VXml end __FILES["codecs/text/Json"] = function() -- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. local Err = __include("core/Err") local Types = __include("Types") local Decode = __include("codecs/text/Json/Decode") local Encode = __include("codecs/text/Json/Encode") local Json = {} type DecodeOptions = Decode.Options type EncodeOptions = Encode.Options Json.null = Types.null Json.object = Types.object Json.keys = Types.keys Json.set = Types.set local function text(src: any): (string?, Err.Err?) if type(src) == "string" then return src, nil elseif type(src) == "buffer" then return buffer.tostring(src), nil end return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src)) end local function fail(msg: any, at: any, n: number): Err.Err local m = tostring(msg) local code = if string.find(m, "truncated", 1, true) or string.find(m, "unterminated", 1, true) or (at or 0) >= n then Err.TRUNCATED elseif string.find(m, "nested deeper", 1, true) then Err.LIMIT else Err.CORRUPT return Err.new(code, m, at) end function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err?) local s, terr = text(src) if not s then return nil, terr end local i = if string.sub(s, 1, 3) == "\239\187\191" then 4 else 1 local v, ni, at = Decode.value(s, i, opts) if v == nil then return nil, fail(ni, at, #s) end local e = string.match(s, "^[ \t\n\r]*()", ni) :: any if e <= #s then return nil, Err.new(Err.CORRUPT, "trailing data after the value", e - 1) end return v, nil end function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?): (any, any) local s, terr = text(src) if not s then return nil, terr end local i = string.match(s, "^[ \t\n\r]*()", pos or 1) :: any if i > #s then return nil, nil end local v, ni, at = Decode.value(s, i, opts) if v == nil then return nil, fail(ni, at, #s) end return v, ni end function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, any, Err.Err?) local s, terr = text(src) local pos = 1 local index = 0 local dead = false return function(): (number?, any, Err.Err?) if dead then return nil end index += 1 if not s then dead = true return index, nil, terr end local v, ni = Json.decodeAt(s, pos, opts) if v == nil then dead = true if ni == nil then return nil end return index, nil, ni end pos = ni return index, v, nil end end function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string?, any) local s, terr = text(src) if not s then local done = false return function(): (string?, any) if done then return nil, nil end done = true return "error", terr end end local str: string = s local i = if string.sub(str, 1, 3) == "\239\187\191" then 4 else 1 local nextEv = Decode.events(str, i, opts) return function(): (string?, any) local ev, v, at = nextEv() if ev == "error" then return ev, fail(v, at, #str) end return ev, v end end function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?) local s, msg = Encode.encode(value, opts) if not s then return nil, Err.new(Err.ARG, msg or "cannot encode") end return s, nil end Json.quote = Encode.quote Json.number = Encode.number type Writer = { err: Err.Err?, beginObject: (self: Writer) -> Writer, endObject: (self: Writer) -> Writer, beginArray: (self: Writer) -> Writer, endArray: (self: Writer) -> Writer, key: (self: Writer, k: string) -> Writer, value: (self: Writer, v: any) -> Writer, flush: (self: Writer) -> string, tostring: (self: Writer) -> (string?, Err.Err?), } function Json.writer(opts: EncodeOptions?): Writer local st = Encode.state(opts) local ind = st.indent local kinds: { boolean } = {} local counts: { number } = {} local depth = 0 local keyDone = false local flushed: { string } = {} local w: any = { err = nil } local function bad(msg: string) if not w.err then w.err = Err.new(Err.ARG, msg) end end local function slot(isKey: boolean): boolean if w.err then return false end if depth == 0 then if counts[0] and counts[0] > 0 then bad("one top-level value only") return false end counts[0] = 1 return true end local obj = kinds[depth] if obj and not isKey then if not keyDone then bad("an object member needs a key first") return false end keyDone = false return true end if isKey and not obj then bad("key outside an object") return false end if isKey and keyDone then bad("two keys in a row") return false end if counts[depth] > 0 then table.insert(st.out, ",") end counts[depth] += 1 if ind then table.insert(st.out, "\n" .. string.rep(ind, depth)) end return true end local function open(obj: boolean) if slot(false) then table.insert(st.out, if obj then "{" else "[") depth += 1 kinds[depth], counts[depth] = obj, 0 end return w end local function close(obj: boolean) if w.err then return w end if depth == 0 or kinds[depth] ~= obj or (obj and keyDone) then bad(if obj then "unbalanced endObject" else "unbalanced endArray") return w end if ind and counts[depth] > 0 then table.insert(st.out, "\n" .. string.rep(ind, depth - 1)) end table.insert(st.out, if obj then "}" else "]") depth -= 1 return w end function w.beginObject(_self: Writer): Writer return open(true) end function w.beginArray(_self: Writer): Writer return open(false) end function w.endObject(_self: Writer): Writer return close(true) end function w.endArray(_self: Writer): Writer return close(false) end function w.key(_self: Writer, k: string): Writer if type(k) ~= "string" then bad("key must be a string") elseif slot(true) then table.insert(st.out, Encode.quote(k, st.ascii, st.slash) .. (if ind then ": " else ":")) keyDone = true end return w end function w.value(_self: Writer, v: any): Writer if slot(false) then st.n = #st.out if not Encode.write(st, v, depth) then bad(st.err or "cannot encode") end end return w end function w.flush(_self: Writer): string local s = table.concat(st.out) table.clear(st.out) st.n = 0 table.insert(flushed, s) return s end function w.tostring(_self: Writer): (string?, Err.Err?) if w.err then return nil, w.err end if depth ~= 0 then return nil, Err.new(Err.ARG, "unclosed object / array") end return table.concat(flushed) .. table.concat(st.out), nil end return w :: Writer end return Json end __FILES["codecs/text/Json/Decode"] = @native function() -- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json: iterative, strict grammar. -- \u escapes with surrogate pairs; lone surrogates become WTF-8 bytes. local Text = __include("codecs/text/Text") local Types = __include("Types") local Decode = {} local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char local tonumber = tonumber local concat = table.concat type Options = { ordered: boolean?, bigInts: ("number" | "string")?, null: any?, maxDepth: number?, } local ESC: { [number]: string } = { [34] = '"', [92] = "\\", [47] = "/", [98] = "\b", [102] = "\f", [110] = "\n", [114] = "\r", [116] = "\t", } local utf8char = Text.utf8char Decode.utf8char = utf8char @native local function hex4(s: string, i: number): number? local h = match(s, "^%x%x%x%x", i) if not h then return nil end return tonumber(h, 16) end @native local function str(s: string, i: number): (string?, any, number?) local j = find(s, '[%z\1-\31"\\]', i + 1) if not j then return nil, "unterminated string", #s end local c = byte(s, j) if c == 34 then return sub(s, i + 1, j - 1), j + 1 end local parts = {} local np = 0 local start = i + 1 while true do if c == 34 then np += 1 parts[np] = sub(s, start, j - 1) return concat(parts), j + 1 elseif c ~= 92 then return nil, "control character in string", j - 1 end np += 1 parts[np] = sub(s, start, j - 1) local e = byte(s, j + 1) if e == nil then return nil, "unterminated string", #s end local simple = ESC[e] if simple then np += 1 parts[np] = simple start = j + 2 elseif e == 117 then -- \u local cp = hex4(s, j + 2) if not cp then return nil, "bad \\u escape", j - 1 end start = j + 6 if cp >= 0xD800 and cp <= 0xDBFF and byte(s, start) == 92 and byte(s, start + 1) == 117 then local lo = hex4(s, start + 2) if lo and lo >= 0xDC00 and lo <= 0xDFFF then cp = 0x10000 + (cp - 0xD800) * 1024 + (lo - 0xDC00) start += 6 end end np += 1 parts[np] = utf8char(cp) else return nil, "bad escape", j - 1 end j = find(s, '[%z\1-\31"\\]', start) if not j then return nil, "unterminated string", #s end c = byte(s, j) end end Decode.string = str @native local function num(s: string, i: number, bigStrings: boolean): (any, any, number?) local p = i if byte(s, p) == 45 then p += 1 end local c = byte(s, p) if c == 48 then p += 1 elseif c and c >= 49 and c <= 57 then p = match(s, "^%d*()", p + 1) :: any else return nil, if c == nil then "truncated: expected a value" elseif p == i then "unexpected character" else "bad number", p - 1 end local int = true if byte(s, p) == 46 then local q = match(s, "^%d+()", p + 1) if not q then return nil, "bad fraction", p end p = q :: any int = false end c = byte(s, p) if c == 101 or c == 69 then p += 1 c = byte(s, p) if c == 43 or c == 45 then p += 1 end local q = match(s, "^%d+()", p) if not q then return nil, "bad exponent", p - 1 end p = q :: any int = false end local text = sub(s, i, p - 1) local n = tonumber(text) :: number if n == nil then -- LuaJIT: absurd exponents (1e0066999...) -> nil; they overflow / underflow local m, es = match(text, "^([^eE]*)[eE]([%+%-]?)") local mv = tonumber(m) or 0 n = if mv == 0 then mv elseif es == "-" then mv * 0 else mv * math.huge end if int and bigStrings and p - i > 15 and (n >= 9007199254740992 or n <= -9007199254740992) then return text, p end return n, p end Decode.number = num @native function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) local o: Options = opts or {} local ordered = o.ordered == true local bigStrings = o.bigInts == "string" local nullv = if o.null ~= nil then o.null else Types.null local maxDepth = o.maxDepth or 1000 local object = Types.object local stackT: { any } = {} local stackK: { any } = {} local stackO: { any } = {} local depth = 0 local n = #s local value: any while true do i = match(s, "^[ \t\n\r]*()", i) :: any local c = byte(s, i) local haveValue = true if c == 123 then -- { depth += 1 if depth > maxDepth then return nil, "nested deeper than " .. maxDepth, i - 1 end i = match(s, "^[ \t\n\r]*()", i + 1) :: any local t = {} c = byte(s, i) if c == 125 then i += 1 depth -= 1 value = object(t, {}) elseif c == 34 then local k, ni, at = str(s, i) if k == nil then return nil, ni, at end i = match(s, "^[ \t\n\r]*()", ni) :: any if byte(s, i) ~= 58 then return nil, if i > n then "truncated object" else "expected ':'", i - 1 end i += 1 stackT[depth], stackK[depth] = t, k stackO[depth] = if ordered then {} else true haveValue = false else return nil, if c == nil then "truncated object" else "expected a key", i - 1 end elseif c == 91 then -- [ depth += 1 if depth > maxDepth then return nil, "nested deeper than " .. maxDepth, i - 1 end i = match(s, "^[ \t\n\r]*()", i + 1) :: any if byte(s, i) == 93 then i += 1 depth -= 1 value = {} else stackT[depth], stackK[depth], stackO[depth] = {}, 0, false haveValue = false end elseif c == 34 then local v, ni, at = str(s, i) if v == nil then return nil, ni, at end value, i = v, ni elseif c == 116 then if sub(s, i, i + 3) ~= "true" then return nil, "bad literal", i - 1 end value, i = true, i + 4 elseif c == 102 then if sub(s, i, i + 4) ~= "false" then return nil, "bad literal", i - 1 end value, i = false, i + 5 elseif c == 110 then if sub(s, i, i + 3) ~= "null" then return nil, "bad literal", i - 1 end value, i = nullv, i + 4 elseif c == nil then return nil, "truncated: expected a value", n else local v, ni, at = num(s, i, bigStrings) if v == nil then return nil, ni, at end value, i = v, ni end while haveValue do if depth == 0 then return value, i end local t = stackT[depth] local ord = stackO[depth] if ord then local k = stackK[depth] if ord ~= true and t[k] == nil then table.insert(ord, k) end t[k] = value else local cnt = stackK[depth] + 1 t[cnt] = value stackK[depth] = cnt end i = match(s, "^[ \t\n\r]*()", i) :: any c = byte(s, i) if c == 44 then -- , i = match(s, "^[ \t\n\r]*()", i + 1) :: any if ord then if byte(s, i) ~= 34 then return nil, if i > n then "truncated object" else "expected a key", i - 1 end local k, ni, at = str(s, i) if k == nil then return nil, ni, at end i = match(s, "^[ \t\n\r]*()", ni) :: any if byte(s, i) ~= 58 then return nil, if i > n then "truncated object" else "expected ':'", i - 1 end i += 1 stackK[depth] = k end haveValue = false elseif ord and c == 125 then i += 1 value = if ord ~= true then object(t, ord) elseif next(t) == nil then object(t, {}) else t stackT[depth] = nil depth -= 1 elseif not ord and c == 93 then i += 1 value = t stackT[depth] = nil depth -= 1 elseif c == nil then return nil, if ord then "truncated object" else "truncated array", n else return nil, if ord then "expected ',' or '}'" else "expected ',' or ']'", i - 1 end end end end @native function Decode.events(s: string, i: number, opts: Options?): () -> (string?, any, number?) local o: Options = opts or {} local bigStrings = o.bigInts == "string" local nullv = if o.null ~= nil then o.null else Types.null local maxDepth = o.maxDepth or 1000 local stack: { boolean } = {} local depth = 0 local state = "value" local n = #s @native local function fail(msg: string, at: number): (string, any, number) state = "dead" return "error", msg, at end return @native function(): (string?, any, number?) if state == "dead" then return nil end i = match(s, "^[ \t\n\r]*()", i) :: any local c = byte(s, i) if state == "done" then state = "dead" if c ~= nil then return "error", "trailing data", i - 1 end return nil end if state == "after" then local obj = stack[depth] if c == 44 then i = match(s, "^[ \t\n\r]*()", i + 1) :: any c = byte(s, i) state = if obj then "key" else "value" elseif c == (if obj then 125 else 93) then i += 1 stack[depth] = nil depth -= 1 state = if depth == 0 then "done" else "after" return if obj then "endObject" else "endArray", nil elseif c == nil then return fail("truncated", n) else return fail("expected ',' or a close", i - 1) end end if state == "first" then local obj = stack[depth] if c == (if obj then 125 else 93) then i += 1 stack[depth] = nil depth -= 1 state = if depth == 0 then "done" else "after" return if obj then "endObject" else "endArray", nil end state = if obj then "key" else "value" end if state == "key" then if c ~= 34 then return fail(if c == nil then "truncated" else "expected a key", i - 1) end local k, ni, at = str(s, i) if k == nil then return fail(ni, at :: number) end i = match(s, "^[ \t\n\r]*()", ni) :: any if byte(s, i) ~= 58 then return fail("expected ':'", i - 1) end i += 1 state = "value" return "key", k end local after = if depth == 0 then "done" else "after" if c == 123 or c == 91 then depth += 1 if depth > maxDepth then return fail("nested deeper than " .. maxDepth, i - 1) end stack[depth] = c == 123 i += 1 state = "first" return if c == 123 then "object" else "array", nil elseif c == 34 then local v, ni, at = str(s, i) if v == nil then return fail(ni, at :: number) end i = ni state = after return "value", v elseif c == 116 and sub(s, i, i + 3) == "true" then i += 4 state = after return "value", true elseif c == 102 and sub(s, i, i + 4) == "false" then i += 5 state = after return "value", false elseif c == 110 and sub(s, i, i + 3) == "null" then i += 4 state = after return "value", nullv elseif c == nil then return fail("truncated: expected a value", n) end local v, ni, at = num(s, i, bigStrings) if v == nil then return fail(ni, at :: number) end i = ni state = after return "value", v end end return Decode end __FILES["codecs/text/Json/Encode"] = @native function() -- codecs/text/Json/Encode: the RFC 8259 serializer behind codecs/text/Json. local Types = __include("Types") local Encode = {} local byte, format, gsub = string.byte, string.format, string.gsub local floor, huge = math.floor, math.huge local concat = table.concat type Options = { indent: (number | string)?, sortKeys: boolean?, ascii: boolean?, nan: ("error" | "null")?, emptyTable: ("array" | "object")?, maxDepth: number?, escapeSlash: boolean?, } local ESCAPES: { [string]: string } = { ['"'] = '\\"', ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t", ["/"] = "\\/", } for c = 0, 31 do local ch = string.char(c) if not ESCAPES[ch] then ESCAPES[ch] = format("\\u%04x", c) end end @native local function utf16(cp: number): string if cp < 0x10000 then return format("\\u%04x", cp) end cp -= 0x10000 return format("\\u%04x\\u%04x", 0xD800 + cp // 1024, 0xDC00 + cp % 1024) end @native local function asciiSeq(seq: string): string local out = {} local i, n = 1, #seq while i <= n do local c = byte(seq, i) local cp, len if c < 0xC0 then cp, len = c, 1 elseif c < 0xE0 then cp, len = (c % 32) * 64 + (byte(seq, i + 1) or 128) % 64, 2 elseif c < 0xF0 then cp, len = (c % 16) * 4096 + ((byte(seq, i + 1) or 128) % 64) * 64 + (byte(seq, i + 2) or 128) % 64, 3 else cp, len = (c % 8) * 262144 + ((byte(seq, i + 1) or 128) % 64) * 4096 + ((byte(seq, i + 2) or 128) % 64) * 64 + (byte(seq, i + 3) or 128) % 64, 4 end table.insert(out, utf16(cp)) i += len end return concat(out) end -- ascii escapes DEL too, like Python's ensure_ascii @native local function quote(s: string, ascii: boolean?, slash: boolean?): string local pat = if slash then '[%z\1-\31"\\/]' else '[%z\1-\31"\\]' if string.find(s, pat) then s = gsub(s, pat, ESCAPES) end if ascii and string.find(s, "[\127-\255]") then s = gsub(s, "\127", "\\u007f") s = gsub(s, "[\192-\255][\128-\191]*", asciiSeq) s = gsub(s, "[\128-\191]", asciiSeq) end return '"' .. s .. '"' end Encode.quote = quote local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" } @native local function number(x: number): string? if x ~= x or x == huge or x == -huge then return nil end if x == floor(x) and x > -1e15 and x < 1e15 then if x == 0 and 1 / x < 0 then return "-0" end return format("%d", x) end for _, f in FLOAT_FORMATS do local t = format(f, x) if tonumber(t) == x then return t end end return format("%.17g", x) end Encode.number = number @native local function keyLess(a: any, b: any): boolean local ta, tb = type(a), type(b) if ta ~= tb then return ta == "number" end return a < b end @native local function kind(t: { [any]: any }, emptyObject: boolean): string if Types.isObject(t) then return "object" end local n = #t if n == 0 then if next(t) == nil then return if emptyObject then "object" else "array" end return "object" end local count = 0 for _ in next, t do count += 1 end return if count == n then "array" else "object" end Encode.kind = kind type State = { out: { string }, n: number, indent: string?, sort: boolean, ascii: boolean, slash: boolean, nanNull: boolean, emptyObject: boolean, maxDepth: number, null: any, err: string?, } @native local function put(st: State, s: string) local n = st.n + 1 st.out[n] = s st.n = n end @native local function value(st: State, v: any, depth: number): boolean local tv = type(v) if tv == "string" then put(st, quote(v, st.ascii, st.slash)) elseif tv == "number" then local s = number(v) if not s then if not st.nanNull then st.err = "cannot encode " .. tostring(v) return false end s = "null" end put(st, s) elseif tv == "boolean" then put(st, if v then "true" else "false") elseif v == nil or v == st.null or v == Types.null then put(st, "null") elseif tv == "table" then if Types.Date.is(v) then put(st, '"' .. tostring(v) .. '"') return true end if depth >= st.maxDepth then st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)" return false end local ind = st.indent local nl, nl2 = "", "" if ind then nl = "\n" .. string.rep(ind, depth + 1) nl2 = "\n" .. string.rep(ind, depth) end if kind(v, st.emptyObject) == "array" then local n = #v if n == 0 then put(st, "[]") return true end put(st, "[") for i = 1, n do if i > 1 then put(st, ",") end if ind then put(st, nl) end if not value(st, v[i], depth + 1) then return false end end if ind then put(st, nl2) end put(st, "]") else local keys: { any } if Types.isObject(v) then keys = Types.keys(v) else keys = {} for k in next, v do local tk = type(k) if tk ~= "string" and tk ~= "number" then st.err = "object key of type " .. tk return false end table.insert(keys, k) end if st.sort then table.sort(keys, keyLess) end end if #keys == 0 then put(st, "{}") return true end put(st, "{") local sep = if ind then ": " else ":" for i, k in keys do if i > 1 then put(st, ",") end if ind then put(st, nl) end local ks: string if type(k) == "string" then ks = k elseif type(k) == "number" then ks = number(k) or tostring(k) else st.err = "object key of type " .. type(k) return false end put(st, quote(ks, st.ascii, st.slash)) put(st, sep) if not value(st, v[k], depth + 1) then return false end end if ind then put(st, nl2) end put(st, "}") end elseif tv == "buffer" then st.err = "cannot encode a buffer (encode it as base64 or an array first)" return false else st.err = "cannot encode a " .. tv return false end return true end @native local function state(opts: Options?, nullv: any?): State local o: Options = opts or {} local ind: string? = nil if type(o.indent) == "number" then ind = if o.indent > 0 then string.rep(" ", o.indent) else nil elseif type(o.indent) == "string" then ind = o.indent end return { out = {}, n = 0, indent = ind, sort = o.sortKeys ~= false, ascii = o.ascii == true, slash = o.escapeSlash == true, nanNull = o.nan == "null", emptyObject = o.emptyTable == "object", maxDepth = o.maxDepth or 1000, null = nullv, err = nil, } end Encode.state = state Encode.write = value @native function Encode.encode(v: any, opts: Options?, nullv: any?): (string?, string?) local st = state(opts, nullv) if not value(st, v, 0) then return nil, st.err end return concat(st.out), nil end return Encode end __FILES["codecs/text/Lexer"] = function() -- codecs/text/Lexer: C-style tokens for id Tech / UDMF text (idLib idLexer conventions, UDMF 1.1 §I; no code taken): -- // and /* */ comments, "strings" with backslash escapes, numbers (decimal, float, 0x hex), bare words, and single -- punctuation characters { } ( ) [ ] ; = ,. local Lexer = {} type Kind = "word" | "number" | "string" | "punct" type Lexer = { s: string, p: number, -- next byte to read, 1-based n: number, raw: string?, -- the last token's text as written err: string?, next: (self: Lexer) -> (Kind?, any), peek: (self: Lexer) -> (Kind?, any), line: (self: Lexer, at: number?) -> number, } local find, sub, byte, match = string.find, string.sub, string.byte, string.match local ESC: { [string]: string } = { n = "\n", t = "\t", r = "\r", ["0"] = "\0" } local function skip(L: Lexer): number? local s, p = L.s, L.p while true do p = find(s, "[^ \t\r\n\f\v]", p) if not p then return nil end if byte(s, p) == 47 then local c2 = byte(s, p + 1) if c2 == 47 then local e = find(s, "\n", p + 2, true) if not e then return nil end p = e + 1 elseif c2 == 42 then local _, e = find(s, "*/", p + 2, true) if not e then L.err = "unterminated comment" return nil end p = e + 1 else return p end else return p end end end local function token(L: Lexer): (Kind?, any, number) local p = skip(L) if not p then return nil, nil, L.n + 1 end local s = L.s local c = byte(s, p) if c == 34 then local parts: { string }? = nil local q = p + 1 while true do local e = find(s, "[\"\\]", q) if not e then L.err = "unterminated string" return nil, nil, L.n + 1 end if byte(s, e) == 34 then local tail = sub(s, q, e - 1) if parts then table.insert(parts, tail) L.raw = sub(s, p, e) return "string", table.concat(parts), e + 1 end L.raw = sub(s, p, e) return "string", tail, e + 1 end parts = parts or {} local ch = sub(s, e + 1, e + 1) table.insert(parts :: { string }, sub(s, q, e - 1)) table.insert(parts :: { string }, ESC[ch] or ch) q = e + 2 end end if find("{}()[];=,", string.char(c), 1, true) then L.raw = string.char(c) return "punct", L.raw, p + 1 end local w = match(s, "^[^ \t\r\n\f\v{}()%[%];=,\"]+", p) :: string local e = p + #w -- a comment right after a word ends it local cm = find(w, "/[/*]") if cm then w = sub(w, 1, cm - 1) e = p + #w end L.raw = w if (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then local v = tonumber(w) if v and not find(w, "[iInN]") then return "number", v, e end end return "word", w, e end local function nextToken(L: Lexer): (Kind?, any) local k, v, e = token(L) L.p = e return k, v end local function peek(L: Lexer): (Kind?, any) local raw = L.raw local k, v = token(L) L.raw = raw return k, v end local function line(L: Lexer, at: number?): number local _, n = string.gsub(sub(L.s, 1, (at or L.p) - 1), "\n", "") return n + 1 end function Lexer.new(s: string): Lexer return { s = s, p = 1, n = #s, raw = nil, err = nil, next = nextToken, peek = peek, line = line } end return Lexer end __FILES["codecs/text/Nbt"] = function() -- codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT"). -- Files may be gzip or zlib compressed; a Bedrock level.dat has an 8-byte header. local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") local Deflate = __include("codecs/compress/Deflate") local Value = __include("codecs/text/Nbt/Value") local Binary = __include("codecs/text/Nbt/Binary") local Snbt = __include("codecs/text/Nbt/Snbt") local Nbt = {} type Tag = Value.Tag type Info = { name: string, endian: "big" | "little", varint: boolean?, compression: "gzip" | "zlib" | "none", header: number?, } type DecodeOptions = { endian: ("big" | "little")?, varint: boolean?, nameless: boolean?, maxDepth: number?, maxBytes: number?, } type EncodeOptions = { endian: ("big" | "little")?, varint: boolean?, nameless: boolean?, name: string?, compression: ("gzip" | "zlib" | "none")?, header: number?, level: number?, } Nbt.TAG = Value.IDS Nbt.TAG_NAMES = Value.NAMES Nbt.byte = Value.byte Nbt.short = Value.short Nbt.int = Value.int Nbt.long = Value.long Nbt.float = Value.float Nbt.double = Value.double Nbt.intArray = Value.intArray Nbt.longArray = Value.longArray Nbt.longs = Value.longs Nbt.list = Value.list Nbt.listType = Value.listType Nbt.compound = Value.compound Nbt.typeOf = Value.typeOf Nbt.isTag = Value.isTag Nbt.number = Value.number Nbt.fromHiLo = Value.fromHiLo Nbt.toHiLo = Value.toHiLo local infos: { [any]: Info } = setmetatable({}, { __mode = "k" }) :: any function Nbt.info(v: any): Info? return if type(v) == "table" then infos[v] else nil end function Nbt.setInfo(v: any, info: Info) if type(v) == "table" then infos[v] = info end end function Nbt.read(buf: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (any, any, number?) local b, o, l, aerr = Bytes.span("Nbt.read", buf, offset, length) if not b then return nil, aerr end local v, name, at = Binary.read(b, o, o + l, opts :: any) if v == nil then return nil, Err.from(name, (at or o) - o) end return v, name, at end function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) local out, e = Binary.write(v, opts :: any) if not out then return nil, Err.new(Err.ARG, tostring(e)) end return out, nil end function Nbt.unwrap(buf: buffer | string, offset: number?, length: number?, maxBytes: number?): (buffer?, any, number?, string?) local b, o, l, aerr = Bytes.span("Nbt.unwrap", buf, offset, length) if not b then return nil, aerr end local c0 = if l >= 2 then buffer.readu8(b, o) else 0 local c1 = if l >= 2 then buffer.readu8(b, o + 1) else 0 local out, err, comp if c0 == 0x1f and c1 == 0x8b then out, err = Deflate.gunzip(b, o, l) comp = "gzip" elseif c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0 then out, err = Deflate.zlib(b, o, l) comp = "zlib" else return b, o, o + l, "none" end if not out then return nil, err end if buffer.len(out) > (maxBytes or 2 ^ 28) then return nil, Err.new(Err.LIMIT, "inflates to " .. buffer.len(out) .. " bytes, over maxBytes") end return out, 0, buffer.len(out), comp end type Peek = { compression: string, endian: "big" | "little", header: boolean, rootType: string, name: string, firstType: string?, firstName: string?, head: buffer, } local function plausibleName(b: buffer, p: number, n: number): string? if p + n > buffer.len(b) or n > 256 then return nil end local s = buffer.readstring(b, p, n) if string.find(s, "[%z\1-\31\127]") then return nil end return s end function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? local o = offset or 0 local l = length or (buffer.len(buf) - o) if l < 3 then return nil end local c0, c1 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1) local head: buffer local comp = "none" if c0 == 0x1f and c1 == 0x8b or (c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0) then local h = Deflate.peek(buf, o, l, 1024) if not h then return nil end head, comp = h, if c0 == 0x1f then "gzip" else "zlib" else local n = math.min(l, 1024) head = buffer.create(n) buffer.copy(head, 0, buf, o, n) end local hn = buffer.len(head) local function at(p: number, endian: string, header: boolean): Peek? if p + 3 > hn then return nil end local t = buffer.readu8(head, p) if t ~= 10 and t ~= 9 then return nil end local function u16(q: number): number local a, b = buffer.readu8(head, q), buffer.readu8(head, q + 1) return if endian == "big" then a * 256 + b else b * 256 + a end local nl = u16(p + 1) local name = plausibleName(head, p + 3, nl) if not name then return nil end local res: Peek = { compression = comp, endian = endian :: any, header = header, rootType = Value.NAMES[t], name = name, head = head } local q = p + 3 + nl if t == 10 and q < hn then local ft = buffer.readu8(head, q) if ft > 12 then return nil end if ft == 0 then res.firstType = "end" elseif q + 3 <= hn then local fname = plausibleName(head, q + 3, u16(q + 1)) if fname == nil and q + 3 + u16(q + 1) <= hn then return nil end res.firstType, res.firstName = Value.NAMES[ft], fname end end return res end if hn >= 12 and buffer.readu32(head, 4) == (if comp == "none" then l else -1) - 8 then local r = at(8, "little", true) if r then return r end end return at(0, "big", false) or at(0, "little", false) end function Nbt.decode(buf: buffer | string, opts: DecodeOptions?, offset: number?, length: number?): (any, any) local o: DecodeOptions = opts or {} local b, s, e, comp = Nbt.unwrap(buf, offset, length, o.maxBytes) if not b then return nil, s end local data: buffer, start: number, stop: number = b, s, e :: number local function try(endian: string, from: number, varint: boolean?): (any, any, number?) return Binary.read(data, from, stop, { endian = endian :: any, varint = varint, nameless = o.nameless, maxDepth = o.maxDepth }) end local header: number? = nil local v, name, at if o.varint then v, name, at = try("little", start, true) elseif o.endian then local from = start if o.endian == "little" and stop - start >= 8 and buffer.readu32(data, start + 4) == stop - start - 8 then header, from = buffer.readu32(data, start), start + 8 end v, name, at = try(o.endian, from) else -- Bedrock level.dat: version, length (u32le), then little-endian NBT if stop - start >= 9 and buffer.readu32(data, start + 4) == stop - start - 8 and buffer.readu8(data, start + 8) == 10 then v, name, at = try("little", start + 8) if v ~= nil then header = buffer.readu32(data, start) o = table.clone(o) o.endian = "little" end end if v == nil then local bv, bn, ba = try("big", start) if bv ~= nil and ba == stop then v, name, at, o = bv, bn, ba, table.clone(o) o.endian = "big" else local lv, ln, la = try("little", start) if lv ~= nil and (la == stop or bv == nil) then v, name, at, o = lv, ln, la, table.clone(o) o.endian = "little" elseif bv ~= nil then v, name, at, o = bv, bn, ba, table.clone(o) o.endian = "big" else v, name, at = nil, bn, ba end end end end if v == nil then return nil, Err.from(name, (at or start) - start) end local info: Info = { name = name, endian = if o.varint or o.endian == "little" then "little" else "big", varint = if o.varint then true else nil, compression = comp :: any, header = header, } if type(v) == "table" then infos[v] = info end return v, info end function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local info = Nbt.info(v) local endian = o.endian or (info and info.endian) or "big" local varint = if o.varint ~= nil then o.varint else (info and info.varint) local raw, e = Binary.write(v, { endian = endian, varint = varint, nameless = o.nameless, name = o.name or (info and info.name) or "", }) if not raw then return nil, Err.new(Err.ARG, tostring(e)) end local header = if o.header ~= nil then o.header else (info and info.header) if header then local h = buffer.create(buffer.len(raw) + 8) buffer.writeu32(h, 0, header) buffer.writeu32(h, 4, buffer.len(raw)) buffer.copy(h, 8, raw) raw = h end local comp = o.compression or (info and info.compression) or (if endian == "big" then "gzip" else "none") if comp == "gzip" then return Deflate.gzip(raw, { level = o.level }) elseif comp == "zlib" then return Deflate.zlibCompress(raw, { level = o.level }) elseif comp ~= "none" then return nil, Err.new(Err.ARG, "unknown compression " .. tostring(comp)) end return raw, nil end function Nbt.parse(text: string | buffer, opts: Snbt.ParseOptions?): (any, Err.Err?) local s = if type(text) == "buffer" then buffer.tostring(text) else text if type(s) ~= "string" then return nil, Err.new(Err.ARG, "Nbt.parse: text must be a string") end local v, e, at = Snbt.parse(s, opts) if v == nil then return nil, Err.from(e, (at or 1) - 1) end return v, nil end function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?) local s, e = Snbt.print(v, opts) if not s then return nil, Err.new(Err.ARG, tostring(e)) end return s, nil end function Nbt.get(v: any, path: string): any local cur = v for part in string.gmatch(path, "[^%.]+") do local k, rest = string.match(part, "^([^%[]*)(.*)$") if k ~= "" then if type(cur) ~= "table" or Value.isTag(cur) then return nil end cur = cur[k] end for idx in string.gmatch(rest :: string, "%[(%-?%d+)%]") do local i = tonumber(idx) :: number if type(cur) == "table" and not Value.isTag(cur) then cur = cur[i + 1] elseif Value.isTag(cur) and type(cur.value) == "table" then cur = cur.value[i + 1] elseif type(cur) == "buffer" and i >= 0 and i < buffer.len(cur) then cur = buffer.readi8(cur, i) else return nil end end end return cur end Nbt.object = Types.object Nbt.shortest = Snbt.shortest return Nbt end __FILES["codecs/text/Nbt/Binary"] = function() -- codecs/text/Nbt/Binary: binary NBT read and write, from the Minecraft wiki "NBT format" page and wiki.vg "NBT". -- Java big-endian (modified UTF-8 strings), Bedrock little-endian (UTF-8), and Bedrock network NBT (little-endian, -- zigzag varint int / long, varint lengths). local Bytes = __include("core/Bytes") local Types = __include("Types") local Value = __include("codecs/text/Nbt/Value") local Binary = {} type Options = { endian: ("big" | "little")?, varint: boolean?, nameless: boolean?, maxDepth: number?, name: string?, } local readu8, readi8, readu32, readi16 = buffer.readu8, buffer.readi8, buffer.readu32, buffer.readi16 local readf32, readf64, writeu32, readstring = buffer.readf32, buffer.readf64, buffer.writeu32, buffer.readstring local byteswap = bit32.byteswap local TWO32 = 4294967296 local NAMES, IDS = Value.NAMES, Value.IDS local newTag = Value.TagMeta type State = { b: buffer, p: number, e: number, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number, err: string?, scratch: buffer } -- Java's DataOutput strings: U+0000 as C0 80, supplementary characters as two 3-byte surrogates (CESU-8) local function fromModified(s: string): string if not string.find(s, "[\192\237]") then return s end local out = {} local i, n = 1, #s while i <= n do local c = string.byte(s, i) if c == 0xC0 and string.byte(s, i + 1) == 0x80 then table.insert(out, "\0") i += 2 elseif c == 0xED and i + 5 <= n then local b2, b3, c4, b5, b6 = string.byte(s, i + 1, i + 5) if b2 >= 0xA0 and b2 <= 0xAF and c4 == 0xED and b5 >= 0xB0 and b5 <= 0xBF then local hiS = 0xD000 + (b2 - 0x80) * 64 + (b3 - 0x80) local loS = 0xD000 + (b5 - 0x80) * 64 + (b6 - 0x80) table.insert(out, utf8.char(0x10000 + (hiS - 0xD800) * 1024 + (loS - 0xDC00))) i += 6 else table.insert(out, string.char(c)) i += 1 end else local j = string.find(s, "[\192\237]", i + 1) or n + 1 table.insert(out, string.sub(s, i, j - 1)) i = j end end return table.concat(out) end local function toModified(s: string): string if not string.find(s, "[%z\240-\244]") then return s end local out = {} local i, n = 1, #s while i <= n do local c = string.byte(s, i) if c == 0 then table.insert(out, "\192\128") i += 1 elseif c >= 0xF0 and c <= 0xF4 and i + 3 <= n then local b2, b3, b4 = string.byte(s, i + 1, i + 3) local cp = (c - 0xF0) * 262144 + (b2 - 0x80) * 4096 + (b3 - 0x80) * 64 + (b4 - 0x80) - 0x10000 local hiS, loS = 0xD800 + cp // 1024, 0xDC00 + cp % 1024 table.insert(out, string.char(0xED, 0x80 + (hiS - 0xD000) // 64, 0x80 + hiS % 64)) table.insert(out, string.char(0xED, 0x80 + (loS - 0xD000) // 64, 0x80 + loS % 64)) i += 4 else local j = string.find(s, "[%z\240-\244]", i + 1) or n + 1 table.insert(out, string.sub(s, i, j - 1)) i = j end end return table.concat(out) end Binary.fromModified = fromModified Binary.toModified = toModified local function fail(s: State, msg: string): nil if not s.err then s.err = msg end s.p = s.e return nil end local function need(s: State, n: number): boolean if s.p + n > s.e then fail(s, "truncated") return false end return true end local function u8(s: State): number if not need(s, 1) then return 0 end local v = readu8(s.b, s.p) s.p += 1 return v end local function varuint(s: State): number -- up to 32 bits (5 bytes) local v, mul = 0, 1 for _ = 1, 5 do if not need(s, 1) then return 0 end local c = readu8(s.b, s.p) s.p += 1 v += (c % 128) * mul if c < 128 then return v % TWO32 end mul *= 128 end fail(s, "varint too long") return 0 end local function i16(s: State): number if not need(s, 2) then return 0 end local p = s.p s.p = p + 2 if s.le then return readi16(s.b, p) end local v = readu8(s.b, p) * 256 + readu8(s.b, p + 1) return if v >= 32768 then v - 65536 else v end local function u32raw(s: State): number if not need(s, 4) then return 0 end local p = s.p s.p = p + 4 local v = readu32(s.b, p) return if s.le then v else byteswap(v) end local function i32(s: State): number if s.net then local n = varuint(s) return if n % 2 == 0 then n // 2 else -(n + 1) // 2 end local v = u32raw(s) return if v >= 0x80000000 then v - TWO32 else v end -- a length: i32 (zigzag varint in network NBT) local function len(s: State): number return i32(s) end local function i64(s: State): (number, number) if s.net then local lo, hi, sh = 0, 0, 0 while true do if sh >= 70 or not need(s, 1) then fail(s, "varint too long") return 0, 0 end local c = readu8(s.b, s.p) s.p += 1 local d = c % 128 if sh < 32 then local x = d * 2 ^ sh lo += x % TWO32 hi = (hi + x // TWO32) % TWO32 else hi = (hi + d * 2 ^ (sh - 32)) % TWO32 end sh += 7 if c < 128 then break end end local odd = lo % 2 == 1 lo = lo // 2 + (hi % 2) * 0x80000000 hi = hi // 2 if odd then hi, lo = TWO32 - 1 - hi, TWO32 - 1 - lo end return hi, lo end if s.le then local lo = u32raw(s) return u32raw(s), lo end local hi = u32raw(s) return hi, u32raw(s) end local function f32(s: State): number local v = u32raw(s) writeu32(s.scratch, 0, v) return readf32(s.scratch, 0) end local function f64(s: State): number local hi, lo if s.le then lo = u32raw(s) hi = u32raw(s) else hi = u32raw(s) lo = u32raw(s) end writeu32(s.scratch, 0, lo) writeu32(s.scratch, 4, hi) return readf64(s.scratch, 0) end local function str(s: State): string local n if s.net then n = varuint(s) else n = i16(s) % 65536 end if not need(s, n) then return "" end local v = readstring(s.b, s.p, n) s.p += n return if s.java then fromModified(v) else v end local function tag(name: string, v: any): any return setmetatable({ type = name, value = v }, newTag) end local MIN = { [0] = 0, 1, 2, 4, 8, 4, 8, 4, 2, 5, 1, 4, 4 } local MIN_NET = { [0] = 0, 1, 2, 1, 1, 4, 8, 1, 1, 2, 1, 1, 1 } local payload: (State, number) -> any local function count(s: State, n: number, size: number): boolean if n < 0 then fail(s, "negative length " .. n) return false end if n * size > s.e - s.p then fail(s, "truncated: " .. n .. " elements past the end") return false end return true end payload = function(s: State, id: number): any if id == 3 then return i32(s) elseif id == 8 then return str(s) elseif id == 10 then s.depth += 1 if s.depth > s.maxDepth then return fail(s, "limit: nested deeper than " .. s.maxDepth) end local o, keys = {}, {} while true do local t = u8(s) if s.err then return nil end if t == 0 then break end if t > 12 then return fail(s, "bad tag type " .. t) end local k = str(s) local v = payload(s, t) if s.err then return nil end if o[k] == nil then table.insert(keys, k) end o[k] = v end s.depth -= 1 return Types.object(o, keys) elseif id == 1 then if not need(s, 1) then return nil end s.p += 1 return tag("byte", readi8(s.b, s.p - 1)) elseif id == 2 then return tag("short", i16(s)) elseif id == 4 then local hi, lo = i64(s) return tag("long", Value.fromHiLo(hi, lo)) elseif id == 5 then return tag("float", f32(s)) elseif id == 6 then return tag("double", f64(s)) elseif id == 7 then local n = len(s) if not count(s, n, 1) then return nil end local out = buffer.create(n) buffer.copy(out, 0, s.b, s.p, n) s.p += n return out elseif id == 9 then local et = u8(s) local n = len(s) if s.err then return nil end if et > 12 then return fail(s, "bad list element type " .. et) end if et == 0 and n > 0 then return fail(s, "list of end tags with " .. n .. " elements") end if not count(s, n, (if s.net then MIN_NET else MIN)[et]) then return nil end s.depth += 1 if s.depth > s.maxDepth then return fail(s, "limit: nested deeper than " .. s.maxDepth) end local out = table.create(n) for i = 1, n do local v = payload(s, et) if s.err then return nil end out[i] = v end s.depth -= 1 Value.setListType(out, NAMES[et]) return out elseif id == 11 then local n = len(s) if not count(s, n, if s.net then 1 else 4) then return nil end local out = table.create(n) for i = 1, n do out[i] = i32(s) end return tag("intArray", out) elseif id == 12 then local n = len(s) if not count(s, n, if s.net then 1 else 8) then return nil end local out = buffer.create(n * 8) if s.net then for i = 0, n - 1 do local hi, lo = i64(s) writeu32(out, i * 8, lo) writeu32(out, i * 8 + 4, hi) end elseif s.le then buffer.copy(out, 0, s.b, s.p, n * 8) s.p += n * 8 else local b, p = s.b, s.p for i = 0, n - 1 do local q = p + i * 8 writeu32(out, i * 8 + 4, byteswap(readu32(b, q))) writeu32(out, i * 8, byteswap(readu32(b, q + 4))) end s.p = p + n * 8 end return tag("longArray", out) end return fail(s, "bad tag type " .. id) end function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (any, any, number?) local o: Options = opts or {} local net = o.varint == true local le = net or o.endian == "little" local s: State = { b = b, p = pos, e = limit, le = le, net = net, java = not le, depth = 0, maxDepth = o.maxDepth or 512, err = nil, scratch = buffer.create(8), } local id = u8(s) if s.err then return nil, s.err, pos end if id == 0 or id > 12 then return nil, "bad root tag type " .. id, pos end local name = if o.nameless then "" else str(s) local v = payload(s, id) if s.err then return nil, s.err, s.p end return v, name, s.p end type WState = { w: Bytes.Writer, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number } local function wvaruint(w: Bytes.Writer, v: number) v %= TWO32 while v >= 128 do w:u8(v % 128 + 128) v //= 128 end w:u8(v) end local function wi32(ws: WState, v: number) v %= TWO32 if ws.net then local sv = if v >= 0x80000000 then v - TWO32 else v wvaruint(ws.w, if sv >= 0 then sv * 2 else -sv * 2 - 1) elseif ws.le then ws.w:u32le(v) else ws.w:u32be(v) end end local function wi16(ws: WState, v: number) v %= 65536 if ws.le then ws.w:u16le(v) else ws.w:u16be(v) end end local function wi64(ws: WState, hi: number, lo: number) if ws.net then -- zigzag: (n << 1) ^ (n >> 63) local neg = hi >= 0x80000000 local zh = (hi * 2) % TWO32 + (if lo >= 0x80000000 then 1 else 0) local zl = (lo * 2) % TWO32 if neg then zh, zl = TWO32 - 1 - zh, TWO32 - 1 - zl end while zh > 0 or zl >= 128 do ws.w:u8(zl % 128 + 128) zl = zl // 128 + (zh % 128) * 0x2000000 zh //= 128 end ws.w:u8(zl) elseif ws.le then ws.w:u32le(lo) ws.w:u32le(hi) else ws.w:u32be(hi) ws.w:u32be(lo) end end local function wstr(ws: WState, s: string): string? local v = if ws.java then toModified(s) else s if ws.net then wvaruint(ws.w, #v) else if #v > 65535 then return "string longer than 65535 bytes" end wi16(ws, #v) end ws.w:string(v) return nil end local function integer(v: any, lo: number, hi: number, what: string): (number?, string?) local n = if type(v) == "boolean" then (if v then 1 else 0) else v if type(n) ~= "number" or n % 1 ~= 0 or n < lo or n > hi then return nil, "bad " .. what .. " value " .. tostring(n) end return n, nil end local wpayload: (WState, string, any) -> string? local function wlist(ws: WState, v: { any }): string? local lt = Value.listType(v) local n = #v local wrap = false if not lt then if n == 0 then lt = "end" else local t1, e1 = Value.typeOf(v[1]) if not t1 then return e1 end lt = t1 end end for i = 1, n do local t, e = Value.typeOf(v[i]) if not t then return e end if t ~= lt then wrap = true -- mixed element types: every element becomes a compound { [""] = value }, as Minecraft does end end if wrap then lt = "compound" end if lt == "end" and n > 0 then return "a list of end tags cannot hold elements" end ws.w:u8(IDS[lt :: string]) wi32(ws, n) for i = 1, n do local x = v[i] if wrap and Value.typeOf(x) ~= "compound" then x = Types.object({ [""] = x }, { "" }) end local e = wpayload(ws, lt :: string, x) if e then return e end end return nil end wpayload = function(ws: WState, t: string, v: any): string? local w = ws.w local x = if Value.isTag(v) then v.value else v if t == "int" then local n, e = integer(x, -2147483648, 4294967295, "int") if not n then return e end wi32(ws, n) elseif t == "string" then if type(x) ~= "string" then return "bad string value" end return wstr(ws, x) elseif t == "compound" then ws.depth += 1 if ws.depth > ws.maxDepth then return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" end for _, k in Types.keys(v) do if type(k) ~= "string" then return "compound key " .. tostring(k) .. " is not a string" end local c = v[k] local ct, e = Value.typeOf(c) if not ct then return e .. " (key " .. k .. ")" end w:u8(IDS[ct :: string]) e = wstr(ws, k) if e then return e end e = wpayload(ws, ct :: string, c) if e then return e end end w:u8(0) ws.depth -= 1 elseif t == "list" then ws.depth += 1 if ws.depth > ws.maxDepth then return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" end local e = wlist(ws, v) if e then return e end ws.depth -= 1 elseif t == "byte" then local n, e = integer(x, -128, 255, "byte") if not n then return e end w:u8(n % 256) elseif t == "short" then local n, e = integer(x, -32768, 65535, "short") if not n then return e end wi16(ws, n) elseif t == "long" then local hi, lo = Value.toHiLo(x) if not hi then return "bad long value " .. tostring(x) end wi64(ws, hi, lo :: number) elseif t == "float" or t == "double" then if type(x) ~= "number" then return "bad " .. t .. " value " .. tostring(x) end if t == "float" then if ws.le then w:f32le(x) else w:f32be(x) end elseif ws.le then w:f64le(x) else w:f64be(x) end elseif t == "byteArray" then if type(x) ~= "buffer" then return "bad byteArray value" end wi32(ws, buffer.len(x)) w:bytes(x) elseif t == "intArray" then if type(x) ~= "table" then return "bad intArray value" end wi32(ws, #x) for i = 1, #x do local n, e = integer(x[i], -2147483648, 4294967295, "intArray element") if not n then return e end wi32(ws, n) end elseif t == "longArray" then if type(x) ~= "buffer" or buffer.len(x) % 8 ~= 0 then return "bad longArray value (a buffer of 8-byte little-endian longs)" end local n = buffer.len(x) // 8 wi32(ws, n) if ws.le and not ws.net then w:bytes(x) else for i = 0, n - 1 do wi64(ws, buffer.readu32(x, i * 8 + 4), buffer.readu32(x, i * 8)) end end else return "cannot write tag type " .. t end return nil end function Binary.write(v: any, opts: Options?): (buffer?, string?) local o: Options = opts or {} local net = o.varint == true local le = net or o.endian == "little" local t, e = Value.typeOf(v) if not t then return nil, e end local ws: WState = { w = Bytes.writer(1024), le = le, net = net, java = not le, depth = 0, maxDepth = o.maxDepth or 512 } ws.w:u8(IDS[t :: string]) if not o.nameless then e = wstr(ws, o.name or "") if e then return nil, e end end e = wpayload(ws, t :: string, v) if e then return nil, e end return ws.w:finish(), nil end return Binary end __FILES["codecs/text/Nbt/Snbt"] = function() -- codecs/text/Nbt/Snbt: stringified NBT, parse and print, from the Minecraft wiki "NBT format" SNBT section (1.21.5). -- Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. local Types = __include("Types") local Value = __include("codecs/text/Nbt/Value") local Snbt = {} type ParseOptions = { maxDepth: number? } type PrintOptions = { indent: (number | string)?, quote: string?, } local byte, sub, find = string.byte, string.sub, string.find local TWO32 = 4294967296 local function tag(name: string, v: any): any return setmetatable({ type = name, value = v }, Value.TagMeta) end type P = { s: string, i: number, n: number, err: string?, at: number, depth: number, maxDepth: number } local function fail(p: P, msg: string): nil if not p.err then p.err, p.at = msg, p.i end p.i = p.n + 1 return nil end local function ws(p: P) local _, e = find(p.s, "^%s*", p.i) p.i = (e :: number) + 1 end local function isUnquoted(c: number): boolean return (c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or c == 45 or c == 46 or c == 43 end local ESC: { [string]: string } = { ["\\"] = "\\", ["'"] = "'", ['"'] = '"', n = "\n", t = "\t", r = "\r", b = "\b", f = "\f", s = " " } local function quoted(p: P): string? local q = sub(p.s, p.i, p.i) p.i += 1 local out = {} while true do local j = find(p.s, if q == '"' then '["\\]' else "['\\]", p.i) if not j then return fail(p, "unterminated string") end table.insert(out, sub(p.s, p.i, j - 1)) if sub(p.s, j, j) == q then p.i = j + 1 return table.concat(out) end local c = sub(p.s, j + 1, j + 1) if ESC[c] then table.insert(out, ESC[c]) p.i = j + 2 elseif c == "x" or c == "u" or c == "U" then local nd = if c == "x" then 2 elseif c == "u" then 4 else 8 local hex = sub(p.s, j + 2, j + 1 + nd) if #hex ~= nd or find(hex, "[^%x]") then p.i = j return fail(p, "bad \\" .. c .. " escape") end local cp = tonumber(hex, 16) :: number if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then p.i = j return fail(p, "bad code point in \\" .. c .. " escape") end table.insert(out, utf8.char(cp)) p.i = j + 2 + nd else p.i = j return fail(p, "bad escape \\" .. c) end end end local INT_RANGE: { [string]: { number } } = { b = { -128, 127, 255 }, s = { -32768, 32767, 65535 }, i = { -2147483648, 2147483647, 4294967295 }, } local INT_NAME = { b = "byte", s = "short", i = "int", l = "long" } local function integer(t: string): any local sign, body = string.match(t, "^([+-]?)(.+)$") body = string.gsub(body :: string, "_", "") :: string local radix, digits, suffix = 10, body, "" local low = string.lower(body) local m, sfx if sub(low, 1, 2) == "0x" then -- b and s are hex digits: a byte / short suffix needs its signedness (0x7Fsb, 0xFFub) m, sfx = string.match(sub(body, 3), "^(%x+)([sSuU][bBsSiIlL])$") if not m then m, sfx = string.match(sub(body, 3), "^(%x+)([iIlL]?)$") end if not m then return nil end radix = 16 elseif sub(low, 1, 2) == "0b" then m, sfx = string.match(sub(body, 3), "^([01]+)([sSuU]?[bBsSiIlL]?)$") if m then radix = 2 end end if not m then m, sfx = string.match(body, "^(%d+)([sSuU]?[bBsSiIlL]?)$") if not m then return nil end end digits, suffix = m :: string, string.lower(sfx :: string) local unsigned = false if #suffix == 2 then unsigned = sub(suffix, 1, 1) == "u" suffix = sub(suffix, 2) elseif suffix == "u" then return nil end if suffix == "" then suffix = "i" end if unsigned and sign == "-" then return nil end local hi, lo = 0, 0 for k = 1, #digits do local c = byte(digits, k) local d = if c <= 57 then c - 48 elseif c >= 97 then c - 87 else c - 55 local x = lo * radix + d local carry = x // TWO32 lo = x - carry * TWO32 hi = hi * radix + carry if hi >= TWO32 then return nil end end if suffix == "l" then local neg = sign == "-" if radix == 10 then if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or not neg)) then return nil end end if neg and (hi > 0 or lo > 0) then lo = (TWO32 - lo) % TWO32 hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 end return tag("long", Value.fromHiLo(hi, lo)) end if hi > 0 then return nil end local r = INT_RANGE[suffix] local v = lo if sign == "-" then v = -v end if radix ~= 10 and not unsigned and sign ~= "-" and v > r[2] and v <= r[3] then v -= r[3] + 1 -- hex / binary literals wrap into the signed range (0xFFb = -1b) elseif unsigned then if v > r[3] then return nil end if v > r[2] then v -= r[3] + 1 end end if v < r[1] or v > r[2] then return nil end if suffix == "i" then return v end return tag(INT_NAME[suffix], v) end local function number(t: string): any local low = string.lower(t) if low == "true" then return tag("byte", 1) elseif low == "false" then return tag("byte", 0) end local sfx = sub(low, -1) local special = string.match(low, "^([+-]?)infinity[fd]$") if special then return tag(if sfx == "f" then "float" else "double", if special == "-" then -math.huge else math.huge) elseif low == "nanf" or low == "nand" then return tag(if sfx == "f" then "float" else "double", 0 / 0) end local iv = integer(t) if iv ~= nil then return iv end local body = string.gsub(t, "_", "") local m, fs = string.match(body, "^([+-]?[%d%.]+[eE]?[+-]?%d*)([fFdD]?)$") if not m then return nil end -- mantissa digits[.digits] or .digits, an optional exponent; without a fraction or an exponent a suffix is needed local mant, ex = string.match(m :: string, "^(.-)([eE][+-]?%d+)$") if not mant then mant = m end if not (string.match(mant :: string, "^[+-]?%d+%.?%d*$") or string.match(mant :: string, "^[+-]?%.%d+$")) then return nil end if fs == "" and not ex and not find(mant :: string, ".", 1, true) then return nil end local v = tonumber(m) if not v then return nil end if string.lower(fs :: string) == "f" then local b = buffer.create(4) buffer.writef32(b, 0, v) return tag("float", buffer.readf32(b, 0)) end return tag("double", v) end local parseValue: (P) -> any local function token(p: P): string local j = p.i while j <= p.n and isUnquoted(byte(p.s, j)) do j += 1 end local t = sub(p.s, p.i, j - 1) p.i = j return t end local function key(p: P): string? ws(p) local c = sub(p.s, p.i, p.i) if c == '"' or c == "'" then return quoted(p) end local t = token(p) if t == "" then return fail(p, "expected a key") end return t end local ARRAY = { B = "byte", I = "int", L = "long" } local function array(p: P, kind: string): any local items = {} ws(p) if sub(p.s, p.i, p.i) ~= "]" then while true do ws(p) local at = p.i local t = token(p) local v = if t ~= "" then number(t) else nil local vt = Value.typeOf(v) if v == nil or (vt ~= "byte" and vt ~= "short" and vt ~= "int" and vt ~= "long") then p.i = at return fail(p, "expected an integer in a " .. kind .. " array") end local x: any = if Value.isTag(v) then (v :: any).value else v if kind == "byte" and (x < -128 or x > 127) or kind == "int" and vt == "long" then p.i = at return fail(p, "value out of range in a " .. kind .. " array") end table.insert(items, x) ws(p) local c = sub(p.s, p.i, p.i) p.i += 1 if c == "]" then break elseif c ~= "," then p.i -= 1 return fail(p, "expected , or ]") end ws(p) if sub(p.s, p.i, p.i) == "]" then p.i += 1 break end end else p.i += 1 end if kind == "byte" then local b = buffer.create(#items) for i, x in items do buffer.writei8(b, i - 1, x) end return b elseif kind == "int" then return tag("intArray", items) end return Value.longArray(items) end parseValue = function(p: P): any ws(p) if p.i > p.n then return fail(p, "expected a value") end local c = sub(p.s, p.i, p.i) if c == "{" then p.depth += 1 if p.depth > p.maxDepth then return fail(p, "limit: nested deeper than " .. p.maxDepth) end p.i += 1 local o, keys = {}, {} ws(p) if sub(p.s, p.i, p.i) == "}" then p.i += 1 else while true do local k = key(p) if p.err then return nil end ws(p) if sub(p.s, p.i, p.i) ~= ":" then return fail(p, "expected :") end p.i += 1 local v = parseValue(p) if p.err then return nil end if o[k :: string] == nil then table.insert(keys, k) end o[k :: string] = v ws(p) local d = sub(p.s, p.i, p.i) p.i += 1 if d == "}" then break elseif d ~= "," then p.i -= 1 return fail(p, "expected , or }") end ws(p) if sub(p.s, p.i, p.i) == "}" then p.i += 1 break end end end p.depth -= 1 return Types.object(o, keys) elseif c == "[" then p.depth += 1 if p.depth > p.maxDepth then return fail(p, "limit: nested deeper than " .. p.maxDepth) end p.i += 1 local kind = string.match(p.s, "^%s*([BIL])%s*;", p.i) if kind then local _, e = find(p.s, "^%s*[BIL]%s*;", p.i) p.i = (e :: number) + 1 local v = array(p, ARRAY[kind]) p.depth -= 1 return v end local items = {} local lt: string? = nil local mixed = false ws(p) if sub(p.s, p.i, p.i) == "]" then p.i += 1 else while true do local v = parseValue(p) if p.err then return nil end local t = Value.typeOf(v) if lt == nil then lt = t elseif t ~= lt then mixed = true end table.insert(items, v) ws(p) local d = sub(p.s, p.i, p.i) p.i += 1 if d == "]" then break elseif d ~= "," then p.i -= 1 return fail(p, "expected , or ]") end ws(p) if sub(p.s, p.i, p.i) == "]" then p.i += 1 break end end end p.depth -= 1 if not mixed then Value.setListType(items, lt or "end") end return items elseif c == '"' or c == "'" then return quoted(p) end local at = p.i local t = token(p) if t == "" then return fail(p, "unexpected character " .. string.format("%q", c)) end local v = number(t) if v == nil then if string.match(t, "^[+-]?%d[%d_]*[sSuU]?[bBsSiIlL]$") then p.i = at return fail(p, "number out of range: " .. t) end return t end return v end function Snbt.parse(s: string, opts: ParseOptions?): (any, string?, number?) local p: P = { s = s, i = 1, n = #s, err = nil, at = 1, depth = 0, maxDepth = (opts and opts.maxDepth) or 512 } local v = parseValue(p) if p.err then return nil, p.err, p.at end ws(p) if p.i <= p.n then return nil, "trailing characters after the value", p.i end return v, nil, nil end local function shortest(v: number, single: boolean): string if v ~= v then return "NaN" elseif v == math.huge then return "Infinity" elseif v == -math.huge then return "-Infinity" end local b = buffer.create(4) if single then buffer.writef32(b, 0, v) v = buffer.readf32(b, 0) end local s = "" for digits = if single then 6 else 15, 17 do s = string.format("%." .. digits .. "g", v) local back = tonumber(s) :: number if single then buffer.writef32(b, 0, back) back = buffer.readf32(b, 0) end if back == v then break end end if not find(s, "[%.eEn]") then s ..= ".0" end return s end Snbt.shortest = shortest local function quote(s: string, q: string): string local other = if q == '"' then "'" else '"' local _, nq = string.gsub(s, q, "") local _, no = string.gsub(s, other, "") if nq > no then q = other end local e = string.gsub(s, "[\\" .. q .. "%c]", function(c: string): string if c == "\\" or c == q then return "\\" .. c elseif c == "\n" then return "\\n" elseif c == "\t" then return "\\t" elseif c == "\r" then return "\\r" end return string.format("\\x%02x", byte(c)) end) return q .. e .. q end local function keyText(k: string, q: string): string if k ~= "" and not find(k, "[^%w_%-%.%+]") then return k end return quote(k, q) end type Pr = { out: { string }, indent: string?, q: string, depth: number } local printValue: (Pr, any, number) -> string? local function scalar(v: any, q: string): string? local tv = type(v) if tv == "number" then if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then return string.format("%d", v) end return shortest(v, false) .. "d" elseif tv == "string" then return quote(v, q) elseif tv == "boolean" then return if v then "1b" else "0b" elseif Value.isTag(v) then local t, x = v.type, v.value if t == "byte" then return string.format("%db", x) elseif t == "short" then return string.format("%ds", x) elseif t == "int" then return string.format("%d", x) elseif t == "long" then return (if type(x) == "string" then x else string.format("%d", x)) .. "L" elseif t == "float" then return shortest(x, true) .. "f" elseif t == "double" then return shortest(x, false) .. "d" elseif t == "string" then return quote(x, q) end end return nil end local function seq(pr: Pr, head: string, items: { string }, close: string) if pr.indent and #items > 0 then local pad = string.rep(pr.indent, pr.depth) table.insert(pr.out, head .. "\n" .. pad .. pr.indent .. table.concat(items, ",\n" .. pad .. pr.indent) .. "\n" .. pad .. close) else table.insert(pr.out, head .. table.concat(items, if pr.indent then ", " else ",") .. close) end end local function sub1(pr: Pr, v: any): (string?, string?) local inner: Pr = { out = {}, indent = pr.indent, q = pr.q, depth = pr.depth + 1 } local e = printValue(inner, v, inner.depth) if e then return nil, e end return table.concat(inner.out), nil end printValue = function(pr: Pr, v: any, depth: number): string? if depth > 512 then return "nested deeper than 512 (a cycle?)" end local s = scalar(v, pr.q) if s then table.insert(pr.out, s) return nil end local t, terr = Value.typeOf(v) if not t then return terr end if t == "byteArray" then local items = table.create(buffer.len(v)) :: { string } for i = 0, buffer.len(v) - 1 do items[i + 1] = buffer.readi8(v, i) .. "b" end seq(pr, "[B;", items, "]") elseif t == "intArray" then local items = {} for i, x in v.value do items[i] = string.format("%d", x) end seq(pr, "[I;", items, "]") elseif t == "longArray" then local items = {} for i, x in Value.longs(v) do items[i] = (if type(x) == "string" then x else string.format("%d", x)) .. "L" end seq(pr, "[L;", items, "]") elseif t == "list" then local items: { string } = {} for i = 1, #v do local x, e = sub1(pr, v[i]) if e then return e end items[i] = x :: string end seq(pr, "[", items, "]") else local items = {} for _, k in Types.keys(v) do if type(k) ~= "string" then return "compound key " .. tostring(k) .. " is not a string" end local x, e = sub1(pr, v[k]) if e then return e end table.insert(items, keyText(k, pr.q) .. (if pr.indent then ": " else ":") .. (x :: string)) end seq(pr, "{", items, "}") end return nil end function Snbt.print(v: any, opts: PrintOptions?): (string?, string?) local o: PrintOptions = opts or {} local ind = o.indent local pr: Pr = { out = {}, indent = if type(ind) == "number" then string.rep(" ", ind) elseif type(ind) == "string" then ind else nil, q = if o.quote == "'" then "'" else '"', depth = 0, } local e = printValue(pr, v, 0) if e then return nil, e end return table.concat(pr.out), nil end Value.print = function(v: any): string return Snbt.print(v) or "?" end return Snbt end __FILES["codecs/text/Nbt/Value"] = function() -- codecs/text/Nbt/Value: the NBT value model shared by the binary and SNBT codecs. New code. -- long values are numbers when |v| <= 2^53, else their exact decimal text; longArray values are buffers of -- little-endian two's complement int64s. local Types = __include("Types") local Value = {} -- tag ids (the binary format) <-> names Value.NAMES = { [0] = "end", "byte", "short", "int", "long", "float", "double", "byteArray", "string", "list", "compound", "intArray", "longArray", } :: { [number]: string } Value.IDS = {} :: { [string]: number } for id = 0, 12 do Value.IDS[Value.NAMES[id]] = id end type Tag = { type: string, value: any } local TagMeta: { [string]: any } = {} Value.TagMeta = TagMeta Value.print = function(v: any): string return tostring(v.value) end TagMeta.__tostring = function(v: any): string return Value.print(v) end TagMeta.__eq = function(a: any, b: any): boolean if a.type ~= b.type then return false end local x, y = a.value, b.value if type(x) == "buffer" and type(y) == "buffer" then return buffer.tostring(x) == buffer.tostring(y) elseif type(x) == "table" and type(y) == "table" then if #x ~= #y then return false end for i = 1, #x do if x[i] ~= y[i] then return false end end return true end return x == y end local listTypes: { [any]: string } = setmetatable({}, { __mode = "k" }) :: any local TWO32 = 4294967296 function Value.fromHiLo(hi: number, lo: number): number | string local s = if hi >= 0x80000000 then hi - TWO32 else hi if s >= -0x200000 and s < 0x200000 then return s * TWO32 + lo end local neg = s < 0 if neg then -- magnitude = 2^64 - v lo = (TWO32 - lo) % TWO32 hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 end local parts = {} while hi > 0 or lo > 0 do -- divide (hi, lo) by 10^4: r * 2^32 + lo < 10^4 * 2^32 stays exact, ql < 2^32 local qh = hi // 10000 local x = (hi - qh * 10000) * TWO32 + lo local ql = x // 10000 local d = x - ql * 10000 hi, lo = qh, ql table.insert(parts, 1, string.format(if hi > 0 or lo > 0 then "%04d" else "%d", d)) end return (if neg then "-" else "") .. table.concat(parts) end function Value.toHiLo(v: any): (number?, number?) if type(v) == "number" then if v % 1 ~= 0 or v < -9223372036854775808 or v >= 9223372036854775808 then return nil, nil end local hi = v // TWO32 local lo = v - hi * TWO32 return hi % TWO32, lo elseif type(v) == "string" then local neg, digits = string.match(v, "^(%-?)(%d+)$") if not digits or #digits > 19 then return nil, nil end local hi, lo = 0, 0 for i = 1, #digits do local x = lo * 10 + (string.byte(digits, i) - 48) local carry = x // TWO32 lo = x - carry * TWO32 hi = hi * 10 + carry end if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or neg == "")) then return nil, nil end if neg == "-" and (hi > 0 or lo > 0) then lo = (TWO32 - lo) % TWO32 hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 end return hi, lo end return nil, nil end local function tag(name: string, v: any): Tag return setmetatable({ type = name, value = v }, TagMeta) :: any end function Value.byte(n: number): Tag return tag("byte", n) end function Value.short(n: number): Tag return tag("short", n) end function Value.int(n: number): number return n end function Value.long(v: number | string): Tag if type(v) == "string" then local hi, lo = Value.toHiLo(v) if hi then v = Value.fromHiLo(hi, lo :: number) end end return tag("long", v) end local f32 = buffer.create(4) function Value.float(n: number): Tag buffer.writef32(f32, 0, n) return tag("float", buffer.readf32(f32, 0)) end function Value.double(n: number): Tag return tag("double", n) end function Value.intArray(t: { number }?): Tag return tag("intArray", t or {}) end function Value.longArray(t: { any } | buffer | nil): Tag if type(t) == "buffer" then return tag("longArray", t) end local list: { any } = (t or {}) :: any local b = buffer.create(#list * 8) for i, x in list do local hi, lo = Value.toHiLo(x) buffer.writeu32(b, (i - 1) * 8, lo or 0) buffer.writeu32(b, (i - 1) * 8 + 4, hi or 0) end return tag("longArray", b) end function Value.longs(a: Tag): { number | string } local b: buffer = a.value local out = table.create(buffer.len(b) // 8) :: { number | string } for i = 0, buffer.len(b) // 8 - 1 do out[i + 1] = Value.fromHiLo(buffer.readu32(b, i * 8 + 4), buffer.readu32(b, i * 8)) end return out end function Value.list(name: string, items: { any }?): { any } local t = items or {} listTypes[t] = name return t end function Value.compound(t: { [string]: any }?, keys: { string }?): { [string]: any } return Types.object(t, keys) end function Value.listType(t: any): string? return listTypes[t] end function Value.setListType(t: any, name: string) listTypes[t] = name end function Value.isTag(v: any): boolean return type(v) == "table" and getmetatable(v) == TagMeta end function Value.typeOf(v: any): (string?, string?) local tv = type(v) if tv == "number" then return if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then "int" else "double", nil elseif tv == "string" then return "string", nil elseif tv == "boolean" then return "byte", nil elseif tv == "buffer" then return "byteArray", nil elseif tv == "table" then if getmetatable(v) == TagMeta then local n = v.type if Value.IDS[n] == nil or n == "end" or n == "list" or n == "compound" or n == "string" or n == "int" or n == "byteArray" then if n == "int" or n == "string" or n == "byteArray" then return n, nil end return nil, "bad tag type " .. tostring(n) end return n, nil elseif Types.isObject(v) then return "compound", nil elseif listTypes[v] or v[1] ~= nil or next(v) == nil then return "list", nil end return "compound", nil end return nil, "cannot write a " .. tv .. " as NBT" end function Value.number(v: any): number? if type(v) == "number" then return v elseif type(v) == "boolean" then return if v then 1 else 0 elseif Value.isTag(v) then local x = v.value if type(x) == "number" then return x elseif type(x) == "string" then return tonumber(x) end end return nil end return Value end __FILES["codecs/text/Text"] = function() -- codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting. -- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code). local Text = {} function Text.utf8char(c: number): string local char = string.char if c < 0x80 then return char(c) elseif c < 0x800 then return char(0xC0 + c // 64, 0x80 + c % 64) elseif c < 0x10000 then return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) end return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) end -- CP1252 bytes 0x80..0x9F (undefined ones map to U+FFFD) Text.CP1252 = { [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020, [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152, [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022, [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A, [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178, } function Text.trim(s: string): string return (string.match(s, "^%s*(.-)%s*$") :: string) end function Text.utf16(b: buffer, o: number, n: number, bigEndian: boolean?): string local out = {} local k = 0 local readu16 = buffer.readu16 local function unit(at: number): number local v = readu16(b, at) return if bigEndian then (v % 256) * 256 + v // 256 else v end while k + 1 < n do local c = unit(o + k) k += 2 if c >= 0xD800 and c < 0xDC00 and k + 1 < n then local lo = unit(o + k) if lo >= 0xDC00 and lo < 0xE000 then c = 0x10000 + (c - 0xD800) * 1024 + (lo - 0xDC00) k += 2 end end if c >= 0xD800 and c < 0xE000 then c = 0xFFFD end table.insert(out, Text.utf8char(c)) end return table.concat(out) end function Text.toUtf8(text: string, warnings: { string }?): string if string.sub(text, 1, 3) == "\239\187\191" then text = string.sub(text, 4) end if utf8.len(text) then return text end if warnings then table.insert(warnings, "text is not UTF-8: read as Windows-1252") end local out = table.create(#text) for i = 1, #text do local b = string.byte(text, i) if b < 0x80 then out[i] = string.char(b) else out[i] = utf8.char(if b < 0xA0 then Text.CP1252[b] or 0xFFFD else b) end end return table.concat(out) end function Text.lines(text: string): { string } text = string.gsub(text, "\r\n?", "\n") local out = {} for line in string.gmatch(text .. "\n", "([^\n]*)\n") do table.insert(out, line) end return out end return Text end __FILES["codecs/text/Url"] = function() -- codecs/text/Url: RFC 3986 reference resolution (section 5.2), local-path classification and percent-encoding. -- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code). local Url = {} type Location = { url: string, playable: boolean, reason: string?, [string]: any } type Parts = { scheme: string?, authority: string?, path: string, query: string?, fragment: string?, } -- RFC 3986 appendix B: the five components of a URI reference function Url.split(ref: string): Parts local scheme, rest = string.match(ref, "^([%a][%w+%.%-]*):(.*)$") if not scheme then rest = ref end local s = rest :: string local fragment, query, authority local i = string.find(s, "#", 1, true) if i then fragment = string.sub(s, i + 1) s = string.sub(s, 1, i - 1) end i = string.find(s, "?", 1, true) if i then query = string.sub(s, i + 1) s = string.sub(s, 1, i - 1) end if string.sub(s, 1, 2) == "//" then local j = string.find(s, "/", 3, true) if j then authority = string.sub(s, 3, j - 1) s = string.sub(s, j) else authority = string.sub(s, 3) s = "" end end return { scheme = scheme, authority = authority, path = s, query = query, fragment = fragment } end -- RFC 3986 section 5.3 function Url.join(p: Parts): string local out = {} if p.scheme then table.insert(out, p.scheme .. ":") end if p.authority then table.insert(out, "//" .. p.authority) end table.insert(out, p.path) if p.query then table.insert(out, "?" .. p.query) end if p.fragment then table.insert(out, "#" .. p.fragment) end return table.concat(out) end -- RFC 3986 section 5.2.4 function Url.removeDotSegments(path: string): string local input = path local output = {} while input ~= "" do if string.sub(input, 1, 3) == "../" then input = string.sub(input, 4) elseif string.sub(input, 1, 2) == "./" then input = string.sub(input, 3) elseif string.sub(input, 1, 3) == "/./" then input = string.sub(input, 3) elseif input == "/." then input = "/" elseif string.sub(input, 1, 4) == "/../" then input = string.sub(input, 4) table.remove(output) elseif input == "/.." then input = "/" table.remove(output) elseif input == "." or input == ".." then input = "" else -- move the first segment (with its leading "/", up to the next "/") to the output local j = string.find(input, "/", 2, true) local seg = if j then string.sub(input, 1, j - 1) else input table.insert(output, seg) input = string.sub(input, #seg + 1) end end return table.concat(output) end -- RFC 3986 section 5.2.2 (strict) function Url.resolve(ref: string, base: string): string local r, b = Url.split(ref), Url.split(base) local t: Parts = { path = "" } if r.scheme then t.scheme, t.authority, t.path, t.query = r.scheme, r.authority, Url.removeDotSegments(r.path), r.query else if r.authority then t.authority, t.path, t.query = r.authority, Url.removeDotSegments(r.path), r.query else if r.path == "" then t.path = b.path t.query = if r.query then r.query else b.query else if string.sub(r.path, 1, 1) == "/" then t.path = Url.removeDotSegments(r.path) else -- merge (5.2.3) local merged if b.authority and b.path == "" then merged = "/" .. r.path else local k = string.match(b.path, "^.*()/") merged = (if k then string.sub(b.path, 1, k) else "") .. r.path end t.path = Url.removeDotSegments(merged) end t.query = r.query end t.authority = b.authority end t.scheme = b.scheme end t.fragment = r.fragment return Url.join(t) end -- percent-encoded: controls, space, non-ASCII, "<>\"^`{|}" and "\\"; existing %XX escapes and reserved delimiters stay function Url.encodeUnsafe(s: string): string return (string.gsub(s, "[%z\1-\32\127-\255<>\"%^`{|}\\]", function(c: string): string return string.format("%%%02X", string.byte(c)) end)) end function Url.isWindowsPath(s: string): boolean return string.match(s, "^%a:[\\/]") ~= nil or string.match(s, "^%a:$") ~= nil or string.sub(s, 1, 2) == "\\\\" or string.sub(s, 1, 1) == "\\" end function Url.scheme(s: string): string? if Url.isWindowsPath(s) then return nil end local scheme = string.match(s, "^([%a][%w+%.%-]*):") return if scheme then string.lower(scheme) else nil end function Url.locate(raw: string, base: string?, baseScheme: string?): Location local loc = (string.match(raw, "^%s*(.-)%s*$") :: string) if Url.isWindowsPath(loc) then return { url = loc, playable = false, reason = "local path" } end local scheme = Url.scheme(loc) local url = loc if not scheme and baseScheme == "windows" and base then local dir = string.match(base, "^(.*[\\/])") or "" return { url = dir .. loc, playable = false, reason = "local path" } end if scheme then if scheme == "http" or scheme == "https" then url = Url.encodeUnsafe(Url.resolve(loc, loc)) end elseif base and baseScheme then url = Url.resolve(Url.encodeUnsafe((string.gsub(loc, "\\", "/"))), base) scheme = baseScheme else return { url = loc, playable = false, reason = "relative path without a base URL" } end if scheme == "http" or scheme == "https" then return { url = url, playable = true } elseif scheme == "file" then return { url = url, playable = false, reason = "local path" } end return { url = url, playable = false, reason = "scheme " .. tostring(scheme) } end function Url.base(baseUrl: string?, warnings: { string }?): (string?, string?) if type(baseUrl) ~= "string" or baseUrl == "" then return nil, nil end local s = Url.scheme(baseUrl) if s and Url.split(baseUrl).authority ~= nil or s == "file" then return Url.encodeUnsafe(baseUrl), s elseif Url.isWindowsPath(baseUrl) then return baseUrl, "windows" end if warnings then table.insert(warnings, "base URL is not absolute: " .. baseUrl) end return nil, nil end return Url end __FILES["codecs/text/Xml"] = function() -- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize. New code. -- Not supported: external entities / DTDs, validation, entity values containing markup. local Err = __include("core/Err") local Types = __include("Types") local Parse = __include("codecs/text/Xml/Parse") local Xml = {} type Node = Types.XmlNode type DecodeOptions = Parse.Options & { comments: boolean?, cdata: boolean?, pi: boolean?, parents: boolean?, } type EncodeOptions = { indent: (number | string)?, declaration: boolean?, selfClose: boolean?, } local find, gsub, sub, match = string.find, string.gsub, string.sub, string.match local function text(src: any): (string?, Err.Err?) if type(src) == "string" then return src, nil elseif type(src) == "buffer" then return buffer.tostring(src), nil end return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src)) end local function errCode(msg: string, at: number, n: number): string if find(msg, "unterminated", 1, true) or find(msg, "truncated", 1, true) or find(msg, "unclosed", 1, true) or at >= n then return Err.TRUNCATED elseif find(msg, "over the limit", 1, true) or find(msg, "nested deeper", 1, true) then return Err.LIMIT elseif find(msg, "not supported", 1, true) or find(msg, "unsupported", 1, true) then return Err.UNSUPPORTED end return Err.CORRUPT end function Xml.events(src: string | buffer, opts: Parse.Options?): () -> (string?, any, any, any) local s, terr = text(src) local u, enc = nil, "" if s then u, enc = Parse.toUtf8(s) end if not u then local e = terr or Err.new(if find(enc, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT, enc) local done = false return function(): (string?, any, any, any) if done then return nil end done = true return "error", e end end local str: string = u local nextEv = Parse.events(str, opts) return function(): (string?, any, any, any) local ev, a, b, c = nextEv() if ev == "error" then return ev, Err.new(errCode(a, b, #str), a, b) end return ev, a, b, c end end function Xml.decode(src: string | buffer, opts: DecodeOptions?): (Node?, Err.Err?) local o: DecodeOptions = opts or {} local keepComments, keepCdata, keepPi = o.comments == true, o.cdata == true, o.pi == true local parents = o.parents ~= false local doc: any = { name = "#document", attrs = Types.object(), children = {}, parent = nil } local cur: any = doc local stack = { doc } local depth = 1 for ev, a, b, c in Xml.events(src, o) do if ev == "start" then local node: any = { name = a, attrs = b, children = {}, parent = if parents then cur else nil } if c then node.ns = c end table.insert(cur.children, node) depth += 1 stack[depth] = node cur = node if depth == 2 then doc.root = node end elseif ev == "end" then stack[depth] = nil depth -= 1 cur = stack[depth] elseif ev == "text" or (ev == "cdata" and not keepCdata) then local ch = cur.children local last = #ch if last > 0 and type(ch[last]) == "string" then ch[last] ..= a else ch[last + 1] = a end elseif ev == "cdata" then table.insert(cur.children, { name = "#cdata", attrs = Types.object(), children = {}, text = a, parent = if parents then cur else nil }) elseif ev == "comment" then if keepComments then table.insert(cur.children, { name = "#comment", attrs = Types.object(), children = {}, text = a, parent = if parents then cur else nil }) end elseif ev == "pi" then if keepPi then table.insert(cur.children, { name = "#pi", attrs = Types.object(), children = {}, target = a, text = b, parent = if parents then cur else nil }) end elseif ev == "decl" then doc.declaration = a elseif ev == "doctype" then doc.doctype = { raw = a, name = b.name, publicId = b.publicId, systemId = b.systemId, entities = b.entities } elseif ev == "error" then return nil, a end end return doc, nil end function Xml.element(name: string, attrs: { [string]: string }?, children: { any }?): Node local a = attrs or Types.object() if not Types.isObject(a) then local keys = {} for k in next, a do table.insert(keys, k) end table.sort(keys) a = Types.object(a, keys) end local node: any = { name = name, attrs = a, children = children or {} } for _, ch in node.children do if type(ch) == "table" then ch.parent = node end end return node end function Xml.document(root: Node, declaration: { [string]: string }?): Node local doc: any = { name = "#document", attrs = Types.object(), children = { root }, root = root, declaration = declaration } root.parent = doc return doc end function Xml.append(parent: Node, child: any): any table.insert(parent.children, child) if type(child) == "table" then child.parent = parent end return child end function Xml.setAttr(node: Node, name: string, value: string?) Types.set(node.attrs, name, value) end function Xml.children(node: Node, name: string?): { Node } local out = {} for _, ch in node.children do if type(ch) == "table" and string.byte(ch.name) ~= 35 then if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then table.insert(out, ch) end end end return out end function Xml.child(node: Node, name: string?): Node? for _, ch in node.children do if type(ch) == "table" and string.byte(ch.name) ~= 35 then if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then return ch end end end return nil end function Xml.descendants(node: Node, name: string?): { Node } local out = {} local function walk(n: Node) for _, ch in n.children do if type(ch) == "table" and string.byte(ch.name) ~= 35 then if name == nil or ch.name == name or (not find(name :: string, ":", 1, true) and match(ch.name, ":(.*)$") == name) then table.insert(out, ch) end walk(ch) end end end walk(node) return out end function Xml.text(node: any): string if type(node) == "string" then return node end if node.name == "#cdata" then return node.text or "" end local parts = {} local function walk(n: any) for _, ch in n.children do if type(ch) == "string" then table.insert(parts, ch) elseif ch.name == "#cdata" then table.insert(parts, ch.text or "") elseif string.byte(ch.name) ~= 35 then walk(ch) end end end walk(node) return table.concat(parts) end function Xml.prefix(name: string): string return match(name, "^([^:]*):") or "" end function Xml.localName(name: string): string return match(name, ":(.*)$") or name end function Xml.namespace(node: Node, prefix: string?): string? return Parse.resolve(node, prefix or Xml.prefix(node.name)) end function Xml.clark(node: Node, attrName: string?): string local name = attrName or node.name local prefix = Xml.prefix(name) if attrName and prefix == "" then return name end local uri = Parse.resolve(node, prefix) if uri then return "{" .. uri .. "}" .. Xml.localName(name) end return name end local TEXT_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ["\r"] = " " } local ATTR_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """, ["\t"] = " ", ["\n"] = " ", ["\r"] = " " } function Xml.escape(s: string): string return (gsub(s, "[&<>\r]", TEXT_ESC)) end function Xml.escapeAttr(s: string): string return (gsub(s, '[&<>"\t\n\r]', ATTR_ESC)) end local function badName(name: any): boolean return type(name) ~= "string" or not match(name, "^[%a_:\128-\255][%w_:%.%-\128-\255]*$") end function Xml.encode(node: Node, opts: EncodeOptions?): (string?, Err.Err?) local o: EncodeOptions = opts or {} local ind: string? = nil if type(o.indent) == "number" then ind = if o.indent > 0 then string.rep(" ", o.indent) else nil elseif type(o.indent) == "string" then ind = o.indent end local selfClose = o.selfClose ~= false local out: { string } = {} local err: string? = nil local seen: { [any]: boolean } = {} local write: (n: any, depth: number) -> () function write(n: any, depth: number) if err then return end if type(n) == "string" then table.insert(out, Xml.escape(n)) return end if type(n) ~= "table" or type(n.name) ~= "string" then err = "a child is not a node or a string" return end if seen[n] then err = "a node appears twice (a cycle?)" return end seen[n] = true local name = n.name if name == "#comment" then local t = n.text or "" if find(t, "--", 1, true) or sub(t, -1) == "-" then err = "comment text contains '--'" return end table.insert(out, "") 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 n.children do if i > 1 and ind then table.insert(out, "\n") end write(ch, 0) end else if badName(name) then err = "bad element name " .. tostring(name) return end table.insert(out, "<" .. name) local attrs = n.attrs or {} for _, k in Types.keys(attrs) do local v = attrs[k] if badName(k) then err = "bad attribute name " .. tostring(k) return end if type(v) == "number" or type(v) == "boolean" then v = tostring(v) elseif type(v) ~= "string" then err = "attribute " .. k .. " is not a string" return end table.insert(out, " " .. k .. '="' .. Xml.escapeAttr(v) .. '"') end local ch = n.children or {} if #ch == 0 then table.insert(out, if selfClose then "/>" else ">") return end table.insert(out, ">") local pretty = ind ~= nil if pretty then for _, c in ch do if type(c) == "string" or c.name == "#cdata" then pretty = false break end end end for _, c in ch do if pretty then table.insert(out, "\n" .. string.rep(ind :: string, depth + 1)) end write(c, depth + 1) end if pretty then table.insert(out, "\n" .. string.rep(ind :: string, depth)) end table.insert(out, "") end end local decl = o.declaration if decl == nil then decl = node.name == "#document" end if decl then local d: any = node.declaration or {} table.insert(out, '") table.insert(out, "\n") end if node.name == "#document" and node.doctype then local dt: any = node.doctype local raw = dt.raw if raw == nil then raw = " " .. (dt.name or (if node.root then node.root.name else "root")) if dt.publicId then raw ..= ' PUBLIC "' .. dt.publicId .. '" "' .. (dt.systemId or "") .. '"' elseif dt.systemId then raw ..= ' SYSTEM "' .. dt.systemId .. '"' end end table.insert(out, "\n") end write(node, 0) if err then return nil, Err.new(Err.ARG, err) end if ind and node.name == "#document" then table.insert(out, "\n") end return table.concat(out), nil end return Xml end __FILES["codecs/text/Xml/Parse"] = @native function() -- codecs/text/Xml/Parse: the XML 1.0 pull parser behind codecs/text/Xml: input decoding, line-ending normalization, -- well-formedness checks, predefined entities, character references, internal DOCTYPE entities (expansion-limited). local Text = __include("codecs/text/Text") local Types = __include("Types") local Parse = {} local byte, sub, find, match, char, gsub, lower = string.byte, string.sub, string.find, string.match, string.char, string.gsub, string.lower type Options = { whitespace: boolean?, namespaces: boolean?, entities: { [string]: string }?, maxExpansion: number?, maxDepth: number?, } local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*" local PREDEF: { [string]: string } = { lt = "<", gt = ">", amp = "&", quot = '"', apos = "'" } local utf8char = Text.utf8char Parse.utf8char = utf8char local CP1252: { [number]: number } = { [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020, [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152, [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022, [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A, [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178, } @native local function utf16(s: string, start: number, le: boolean): (string?, string?) local out = table.create(#s // 2) local n = 0 local i = start local len = #s while i + 1 <= len do local a, b = byte(s, i, i + 1) local u = if le then a + b * 256 else a * 256 + b i += 2 if u >= 0xD800 and u <= 0xDBFF then if i + 1 > len then return nil, "truncated UTF-16 surrogate pair" end local c, d = byte(s, i, i + 1) local lo = if le then c + d * 256 else c * 256 + d if lo < 0xDC00 or lo > 0xDFFF then return nil, "bad UTF-16 surrogate pair" end i += 2 u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) elseif u >= 0xDC00 and u <= 0xDFFF then return nil, "bad UTF-16 surrogate pair" end n += 1 out[n] = utf8char(u) end if i <= len then return nil, "odd number of bytes in UTF-16 text" end return table.concat(out), nil end @native function Parse.toUtf8(s: string): (string?, string) local b1, b2, b3 = byte(s, 1, 3) if b1 == 0xEF and b2 == 0xBB and b3 == 0xBF then return sub(s, 4), "utf-8" elseif b1 == 0xFF and b2 == 0xFE then local t, e = utf16(s, 3, true) return t, e or "utf-16le" elseif b1 == 0xFE and b2 == 0xFF then local t, e = utf16(s, 3, false) return t, e or "utf-16be" elseif b1 == 0x3C and b2 == 0 then local t, e = utf16(s, 1, true) return t, e or "utf-16le" elseif b1 == 0 and b2 == 0x3C then local t, e = utf16(s, 1, false) return t, e or "utf-16be" end local decl = match(s, "^<%?xml[^>]-%?>") local enc = if decl then match(decl, "encoding%s*=%s*[\"']([%w%._%-]+)[\"']") else nil if enc then local e = lower(enc) if e == "utf-8" or e == "utf8" or e == "us-ascii" or e == "ascii" then if find(s, "[\128-\255]") and not utf8.len(s) then return nil, "invalid UTF-8" end return s, e elseif e == "iso-8859-1" or e == "latin1" or e == "latin-1" or e == "iso8859-1" or e == "windows-1252" or e == "cp1252" then local w = e == "windows-1252" or e == "cp1252" return (gsub(s, "[\128-\255]", @native function(c: string): string local v = byte(c) return utf8char(if w then CP1252[v] or v else v) end)), e elseif e == "utf-16" or e == "utf-16le" or e == "utf-16be" then return s, "utf-8" -- declared UTF-16 but read as 8-bit text: trust the bytes end return nil, "unsupported encoding " .. enc end if find(s, "[\128-\255]") and not utf8.len(s) then return nil, "invalid UTF-8" end return s, "utf-8" end -- the pseudo-attributes, strictly: version, then encoding?, then standalone?, each after whitespace @native local function xmlDecl(data: string): { [string]: string }? local p = 1 local out: { [string]: string } = {} for k, key in { "version", "encoding", "standalone" } do local ws = match(data, "^[ \t\n]*()", p) :: any local q, v, e = match(data, "^" .. key .. "[ \t\n]*=[ \t\n]*([\"'])(.-)%1()", ws) if q then if k > 1 and ws == p then return nil end if (key == "version" and not match(v, "^1%.%d+$")) or (key == "encoding" and not match(v, "^%a[%w%._%-]*$")) or (key == "standalone" and v ~= "yes" and v ~= "no") then return nil end out[key] = v p = e elseif key == "version" then return nil end end if match(data, "^[ \t\n]*()", p) ~= #data + 1 then return nil end return out end @native function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) local o: Options = opts or {} local keepWs = o.whitespace == true local nsOn = o.namespaces == true local maxExp = o.maxExpansion or 1e7 local maxDepth = o.maxDepth or 10000 local entities: { [string]: string } = {} if o.entities then for k, v in o.entities do entities[k] = v end end local external: { [string]: boolean } = {} local expanded = 0 if find(s, "\r", 1, true) then s = gsub(gsub(s, "\r\n", "\n"), "\r", "\n") end local n = #s local i = 1 local stack: { string } = {} local nsStack: { { [string]: string } } = {} local preserve: { boolean } = {} local depth = 0 local rootSeen = false local rootDone = false local dead = false local pending: { any }? = nil local errMsg: string? = nil local errAt = 0 @native local function fail(msg: string, at: number): (string, string, number) dead = true return "error", msg, at - 1 end local decode: (raw: string, at: number, level: number) -> string? @native function decode(raw: string, at: number, level: number): string? if not find(raw, "&", 1, true) then return raw end local parts = {} local np = 0 local p = 1 while true do local a = find(raw, "&", p, true) if not a then break end np += 1 parts[np] = sub(raw, p, a - 1) local ref, e = match(raw, "^&([^;&%s<]*);()", a) if not ref then errMsg, errAt = "bad reference (no ';')", at + a - 1 return nil end local rep: string if byte(ref) == 35 then -- # local cp = if byte(ref, 2) == 120 then tonumber(match(ref, "^#x(%x+)$") or "", 16) else tonumber(match(ref, "^#(%d+)$") or "") if not cp or cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) or cp == 0xFFFE or cp == 0xFFFF then errMsg, errAt = "bad character reference &" .. ref .. ";", at + a - 1 return nil end rep = utf8char(cp) else local pre = PREDEF[ref] if pre then rep = pre else local ent = entities[ref] if not ent then errMsg = if external[ref] then "external entity &" .. ref .. "; not supported" else "undefined entity &" .. ref .. ";" errAt = at + a - 1 return nil end if level > 40 then errMsg, errAt = "entity references nested too deeply (recursive?)", at + a - 1 return nil end local r = decode(ent, at + a - 1, level + 1) if not r then return nil end rep = r end end expanded += #rep if expanded > maxExp then errMsg, errAt = "entity expansion over the limit", at + a - 1 return nil end np += 1 parts[np] = rep p = e :: any end np += 1 parts[np] = sub(raw, p) return table.concat(parts) end @native local function lookupNs(prefix: string): string? for d = depth, 1, -1 do local m = nsStack[d] if m and m[prefix] ~= nil then return m[prefix] end end if prefix == "xml" then return "http://www.w3.org/XML/1998/namespace" end return nil end @native local function literal(p: number): (string?, number) local q = byte(s, p) if q ~= 34 and q ~= 39 then return nil, p end local e = find(s, if q == 34 then '"' else "'", p + 1, true) if not e then return nil, p end return sub(s, p + 1, e - 1), e + 1 end -- ExternalID: SYSTEM "sys" | PUBLIC "pub" "sys" @native local function externalId(p: number): (string?, string?, number?) local kw = sub(s, p, p + 5) if kw == "SYSTEM" then local q = match(s, "^[ \t\n]+()", p + 6) :: any if not q then return nil, nil, nil end local sys, e = literal(q) if not sys then return nil, nil, nil end return "", sys, e elseif kw == "PUBLIC" then local q = match(s, "^[ \t\n]+()", p + 6) :: any if not q then return nil, nil, nil end local pub, e = literal(q) if not pub or find(pub, "[^ \r\n%w%-'()+,./:=?;!*#@$_%%]") then return nil, nil, nil end local r = match(s, "^[ \t\n]+()", e) :: any if not r then return nil, nil, nil end local sys, e2 = literal(r) if not sys then return nil, nil, nil end return pub, sys, e2 end return nil, nil, nil end @native local function entityValue(v: string): string? if find(v, "%", 1, true) then return nil -- parameter-entity references are not allowed in the internal subset's markup end local p = 1 local parts = {} while true do local a = find(v, "&", p, true) if not a then table.insert(parts, sub(v, p)) break end table.insert(parts, sub(v, p, a - 1)) local hex = match(v, "^&#x(%x+);", a) local dec = match(v, "^&#(%d+);", a) if hex or dec then local cp = tonumber(hex or dec, if hex then 16 else 10) :: number if cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) then return nil end table.insert(parts, utf8char(cp)) p = (find(v, ";", a, true) :: number) + 1 else local name = match(v, "^&([%a_:\128-\255][%w_:%.%-\128-\255]*);", a) if not name then return nil end table.insert(parts, "&" .. name .. ";") p = a + #name + 2 end end return table.concat(parts) end @native local function doctype(): (string?, any) local start = i local p = match(s, "^[ \t\n]+()", i) :: any if not p then return nil, "bad DOCTYPE" end local name = match(s, NAME, p) if not name then return nil, "bad DOCTYPE name" end local info: any = { name = name, entities = {} } p += #name local q = match(s, "^[ \t\n]*()", p) :: any if q > p and (sub(s, q, q + 5) == "SYSTEM" or sub(s, q, q + 5) == "PUBLIC") then local pub, sys, e = externalId(q) if not pub then return nil, "bad DOCTYPE external id" end info.publicId = if pub ~= "" then pub else nil info.systemId = sys q = match(s, "^[ \t\n]*()", e) :: any end if byte(s, q) == 91 then -- the internal subset q += 1 while true do q = match(s, "^[ \t\n]*()", q) :: any local c = byte(s, q) if c == 93 then q += 1 break elseif c == 37 then -- %name; local pe = match(s, "^%%[%a_:\128-\255][%w_:%.%-\128-\255]*;()", q) if not pe then return nil, "bad parameter-entity reference" end q = pe :: any elseif sub(s, q, q + 3) == "` timing line)") end subs.meta.source = { format = "srt" } return subs, nil end -- ------------------------------------------------------------------------------------------------ encode local function stamp(t: number): string local ms = math.floor(t * 1000 + 0.5) return string.format("%02d:%02d:%02d,%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000) end function Srt.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?) if type(subs) ~= "table" or type(subs.cues) ~= "table" then return nil, Err.new(Err.ARG, "needs a Subtitles value") end local nl = if opts and opts.crlf then "\r\n" else "\n" local out = table.create(#subs.cues) for i, c in subs.cues do if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") end local body = string.gsub(c.text, "\r\n?", "\n") local settings = if type(c.settings) == "string" and c.settings ~= "" and string.match(c.settings, "X1:") then " " .. c.settings else "" out[i] = i .. nl .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. nl .. (string.gsub(body, "\n", nl)) .. nl end return buffer.fromstring(table.concat(out, nl) .. nl), nil end return Srt end __FILES["subtitle/vtt"] = function() -- subtitle/vtt: WebVTT (W3C WebVTT, 2019 CR). Supports: the header (meta.header), cue ids, `[hh:]mm:ss.ttt` timings, -- cue settings, NOTE (meta.notes), STYLE (meta.css) and REGION (meta.regions) blocks, BOM, CRLF / CR; cue text as -- written. Encode drops blank lines in cue text and escapes `-->` (cue text cannot hold them). -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Sniff = __include("core/Sniff") local Bytes = __include("core/Bytes") local Types = __include("Types") -- ------------------------------------------------------------------------------------------------ contract local Vtt = { name = "vtt", category = "subtitle", extensions = { "vtt", "webvtt" }, mime = { "text/vtt" }, deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, caps = { decode = true, encode = true, styles = true }, } type DecodeOptions = { maxBytes: number?, -- default 64 MB } type EncodeOptions = {} -- ------------------------------------------------------------------------------------------------ constants local function frac(digits: string): number return (tonumber(digits) :: number) / 10 ^ #digits end local function timestamp(s: string): (number?, string) local h, m, sec, f, rest = string.match(s, "^(%d+):(%d%d):(%d%d)%.(%d+)(.*)$") if h then return tonumber(h) :: number * 3600 + tonumber(m) :: number * 60 + tonumber(sec) :: number + frac(f :: string), rest :: string end local m2, s2, f2, rest2 = string.match(s, "^(%d+):(%d%d)%.(%d+)(.*)$") if m2 then return tonumber(m2) :: number * 60 + tonumber(s2) :: number + frac(f2 :: string), rest2 :: string end return nil, s end local function timing(line: string): (number?, number?, string?) local a, rest = timestamp((string.gsub(line, "^%s+", ""))) if not a then return nil, nil, nil end local after = string.match(rest, "^%s*%-%->%s*(.*)$") if not after then return nil, nil, nil end local b, rest2 = timestamp(after) if not b then return nil, nil, nil end local settings = string.match(rest2, "^%s*(.-)%s*$") or "" return a, b, settings end -- ------------------------------------------------------------------------------------------------ sniff function Vtt.sniff(r: Bytes.Reader): number local head = Sniff.text(r, 10) if string.sub(head, 1, 6) == "WEBVTT" then local c = string.sub(head, 7, 7) if c == "" or c == " " or c == "\t" or c == "\n" or c == "\r" then return 1 end end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Vtt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?) local maxBytes = opts and opts.maxBytes or 2 ^ 26 if r.limit - r.base > maxBytes then return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit") end if Vtt.sniff(r) == 0 then return nil, Err.new(Err.CORRUPT, "missing the WEBVTT signature", r.base) end local s = buffer.readstring(r.buf, r.base, r.limit - r.base) if string.find(s, "\0", 1, true) then return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") end s = Sniff.dropBom(s) s = string.gsub(s, "\r\n", "\n") s = string.gsub(s, "\r", "\n") local lines = string.split(s, "\n") local n = #lines local subs = Types.Subtitles.new() -- the header block: WEBVTT[ text] + lines up to the first blank local header = { (string.match(lines[1], "^WEBVTT[ \t]*(.*)$")) or "" } local i = 2 while i <= n and lines[i] ~= "" do table.insert(header, lines[i]) i += 1 end if #header > 1 or header[1] ~= "" then subs.meta.header = table.concat(header, "\n") end local notes, css, regions = {}, {}, {} while i <= n do if lines[i] == "" then i += 1 continue end local first = i while i <= n and lines[i] ~= "" do i += 1 end local block = table.move(lines, first, i - 1, 1, {}) local head = block[1] if string.match(head, "^NOTE[ \t]") or head == "NOTE" then table.insert(notes, (string.gsub(table.concat(block, "\n"), "^NOTE[ \t]?", ""))) elseif (head == "STYLE" or string.match(head, "^STYLE[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then table.insert(css, table.concat(block, "\n", 2)) elseif (head == "REGION" or string.match(head, "^REGION[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then table.insert(regions, table.concat(block, "\n", 2)) else local k, id = 1, nil local a, b, settings = timing(block[1]) if not a and block[2] then id = block[1] k = 2 a, b, settings = timing(block[2]) end if a then local cue: Types.Cue = { start = a, stop = b :: number, text = table.concat(block, "\n", k + 1), id = id } if settings and settings ~= "" then cue.settings = settings end table.insert(subs.cues, cue) end -- a block with no timing is skipped (the spec's parser ignores it) end end if #notes > 0 then subs.meta.notes = notes end if #css > 0 then subs.meta.css = css end if #regions > 0 then subs.meta.regions = regions end subs.meta.source = { format = "vtt" } return subs, nil end -- ------------------------------------------------------------------------------------------------ encode local function stamp(t: number): string local ms = math.floor(t * 1000 + 0.5) return string.format("%02d:%02d:%02d.%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000) end local function clean(s: string): string s = string.gsub(s, "\r\n?", "\n") s = string.gsub(s, "\n[ \t]*\n", "\n") s = string.gsub(s, "\n[ \t]*\n", "\n") s = string.gsub(s, "^\n+", "") s = string.gsub(s, "%-%->", "-->") return s end function Vtt.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?) if type(subs) ~= "table" or type(subs.cues) ~= "table" then return nil, Err.new(Err.ARG, "needs a Subtitles value") end local meta: any = if type(subs.meta) == "table" then subs.meta else {} local out = {} local header = if type(meta.header) == "string" and meta.header ~= "" then meta.header else nil if header then local h = string.gsub(clean(header), "%-%->", "") table.insert(out, "WEBVTT " .. h .. "\n") else table.insert(out, "WEBVTT\n") end for _, key in { "regions", "css" } do local list = meta[key] if type(list) == "table" then for _, b in list do if type(b) == "string" then table.insert(out, (if key == "css" then "STYLE\n" else "REGION\n") .. clean(b) .. "\n") end end end end for i, c in subs.cues do if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") end local id = if type(c.id) == "string" and c.id ~= "" and not string.find(c.id, "-->", 1, true) then (string.gsub(c.id, "[\r\n]", " ")) .. "\n" else "" local settings = if type(c.settings) == "string" and c.settings ~= "" then " " .. (string.gsub(c.settings, "[\r\n]", " ")) else "" local body = clean(c.text) table.insert(out, id .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. "\n" .. body .. (if body ~= "" then "\n" else "")) end return buffer.fromstring(table.concat(out, "\n")), nil end return Vtt end __FILES["vector/gamemaps"] = function() -- vector/gamemaps: Wolfenstein 3D / Spear of Destiny maps (GAMEMAPS "TED5v1.0" + MAPHEAD: RLEW tag, 100 header -- offsets; map headers of 3 planes, Carmack then RLEW compressed; ModdingWiki "GameMaps Format", no code taken) into a -- TileMap: one tile layer per plane ("walls", "objects", "plane3") with the raw tile values as data (no tileset). -- Either file loads; the other comes through opts.files / opts.resolve. Not supported: writing, uncompressed -- (MAPTEMP / Wolf3D 1.0) maps, Huffman-compressed (Keen) maps. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Input = __include("core/Input") local Types = __include("Types") local Expand = __include("vector/gamemaps/Expand") -- ------------------------------------------------------------------------------------------------ contract local Gamemaps = { name = "gamemaps", category = "vector", extensions = { "wl6", "wl1", "sod", "sdm" }, mime = { "application/x-wolf3d-gamemaps" }, deps = { "core/Err", "core/Bytes", "core/Input", "Types" }, caps = { decode = true, encode = false, tilemap = true }, } -- ------------------------------------------------------------------------------------------------ types type DecodeOptions = { map: number?, -- 1-based map slot, default the first present name: string?, -- the file name: picks the sibling's extension (GAMEMAPS.WL6 <-> MAPHEAD.WL6) files: { [string]: buffer | string }?, resolve: ((uri: string) -> (buffer | string)?)?, mapHead: (buffer | string)?, -- MAPHEAD given directly gameMaps: (buffer | string)?, -- GAMEMAPS given directly maxTiles: number?, -- default 2^20 per plane } type MapInfo = { slot: number, name: string, width: number, height: number, offset: number } -- ------------------------------------------------------------------------------------------------ constants local MAGIC = "TED5v1.0" local LAYERS = { "walls", "objects", "plane3" } -- ------------------------------------------------------------------------------------------------ sniff function Gamemaps.sniff(r: Bytes.Reader): number if r:peek(8) == MAGIC then return 1 end -- MAPHEAD: the RLEW tag 0xABCD, then 100 offsets (0 / -1 when absent) if r:remaining() >= 402 and r:remaining() <= 1024 and buffer.readu16(r.buf, r.base) == 0xABCD then local first = buffer.readi32(r.buf, r.base + 2) if first > 0 then return 0.7 end end return 0 end -- ------------------------------------------------------------------------------------------------ decode local function asBuffer(v: any): buffer? if type(v) == "string" then return buffer.fromstring(v) end return if type(v) == "buffer" then v else nil end local function sibling(opts: DecodeOptions?, stem: string): buffer? local name = opts and opts.name local ext = name and string.match(name, "%.([^./\\]+)$") or "WL6" local dir = name and string.match(name, "^(.*[/\\])") or "" for _, n in { stem .. "." .. ext, string.upper(stem .. "." .. ext), string.lower(stem .. "." .. ext) } do local got = Input.sibling(opts, dir .. n) or Input.sibling(opts, n) if got then return got end end return nil end type Pair = { head: buffer, maps: buffer, tag: number } local function pair(r: Bytes.Reader, opts: DecodeOptions?): (Pair?, Err.Err?) local self = buffer.create(r.limit - r.base) buffer.copy(self, 0, r.buf, r.base, r.limit - r.base) local head: buffer, maps: buffer if buffer.len(self) >= 8 and buffer.readstring(self, 0, 8) == MAGIC then maps = self local got = asBuffer(opts and opts.mapHead) or sibling(opts, "MAPHEAD") if not got then return nil, Err.new(Err.UNSUPPORTED, "MAPHEAD not available (opts.mapHead / opts.files / opts.resolve)") end head = got else head = self local got = asBuffer(opts and opts.gameMaps) or sibling(opts, "GAMEMAPS") if not got then return nil, Err.new(Err.UNSUPPORTED, "GAMEMAPS not available (opts.gameMaps / opts.files / opts.resolve)") end maps = got end if buffer.len(head) < 2 then return nil, Err.new(Err.TRUNCATED, "MAPHEAD") end return { head = head, maps = maps, tag = buffer.readu16(head, 0) }, nil end local function list(p: Pair): { MapInfo } local out: { MapInfo } = {} local hn = math.min(100, (buffer.len(p.head) - 2) // 4) local size = buffer.len(p.maps) for i = 0, hn - 1 do local o = buffer.readi32(p.head, 2 + i * 4) if o > 0 and o + 38 <= size then local nm = buffer.readstring(p.maps, o + 22, 16) local z = string.find(nm, "\0", 1, true) table.insert(out, { slot = i + 1, name = if z then string.sub(nm, 1, z - 1) else nm, width = buffer.readu16(p.maps, o + 18), height = buffer.readu16(p.maps, o + 20), offset = o }) end end return out end function Gamemaps.maps(r: Bytes.Reader, opts: DecodeOptions?): ({ MapInfo }?, Err.Err?) local p, err = pair(r, opts) if not p then return nil, err end return list(p), nil end function Gamemaps.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, Err.Err?) local p, err = pair(r, opts) if not p then return nil, err end local maps = list(p) if #maps == 0 then return nil, Err.new(Err.CORRUPT, "no maps in MAPHEAD") end local want = opts and opts.map local m: MapInfo? = if want then nil else maps[1] for _, x in maps do if x.slot == want then m = x end end if not m then return nil, Err.new(Err.ARG, "no map in slot " .. tostring(want)) end local w, h = m.width, m.height if w == 0 or h == 0 or w * h > (opts and opts.maxTiles or 2 ^ 20) then return nil, Err.new(if w * h == 0 then Err.CORRUPT else Err.LIMIT, "map size " .. w .. " x " .. h) end local b = p.maps local size = buffer.len(b) local tm = Types.TileMap.new(w, h, 64, 64) for k = 0, 2 do local at = buffer.readi32(b, m.offset + k * 4) local n = buffer.readu16(b, m.offset + 12 + k * 2) if at > 0 and n >= 2 then if at + n > size then return nil, Err.new(Err.TRUNCATED, "plane " .. (k + 1) .. " past the end", at) end local carmackLen = buffer.readu16(b, at) local mid, msg = Expand.carmack(b, at + 2, n - 2, carmackLen) if not mid then return nil, Err.from(msg, at) end if carmackLen < 2 or buffer.readu16(mid, 0) ~= w * h * 2 then return nil, Err.new(Err.CORRUPT, "plane " .. (k + 1) .. ": RLEW length is not width x height", at) end local plane, rmsg = Expand.rlew(mid, 2, carmackLen - 2, w * h, p.tag) if not plane then return nil, Err.from(rmsg, at) end local data = table.create(w * h, 0) for i = 0, w * h - 1 do data[i + 1] = buffer.readu16(plane, i * 2) end local layer: Types.TileLayer = { type = "tiles", id = k + 1, name = LAYERS[k + 1], width = w, height = h, data = data, visible = true, opacity = 1, properties = {} } table.insert(tm.layers, layer) end end tm.properties.name = m.name tm.meta.source = { format = "gamemaps", map = m.slot, name = m.name, rlewTag = p.tag, maps = maps } return tm, nil end return Gamemaps end __FILES["vector/gamemaps/Expand"] = @native function() -- vector/gamemaps/Expand: id's Carmack (near 0xA7 / far 0xA8 word copies) and RLEW (tag, count, value) expansion of -- GAMEMAPS planes (ModdingWiki "Carmack compression", "RLEW compression"; no code taken). Words are u16 LE. local Expand = {} local readu8, readu16, writeu16 = buffer.readu8, buffer.readu16, buffer.writeu16 @native function Expand.carmack(b: buffer, at: number, n: number, outBytes: number): (buffer?, string?) if outBytes % 2 ~= 0 then return nil, "odd Carmack length" end local out = buffer.create(outBytes) local words = outBytes // 2 local o = 0 local p, e = at, at + n while o < words do if p + 2 > e then return nil, "truncated Carmack data" end local w = readu16(b, p) p += 2 local hi = w // 256 if hi == 0xA7 or hi == 0xA8 then local count = w % 256 if count == 0 then if p + 1 > e then return nil, "truncated Carmack data" end writeu16(out, o * 2, hi * 256 + readu8(b, p)) p += 1 o += 1 else local from if hi == 0xA7 then if p + 1 > e then return nil, "truncated Carmack data" end from = o - readu8(b, p) p += 1 else if p + 2 > e then return nil, "truncated Carmack data" end from = readu16(b, p) p += 2 end if from < 0 or from >= o or o + count > words then return nil, "bad Carmack copy" end for k = 0, count - 1 do writeu16(out, (o + k) * 2, readu16(out, (from + k) * 2)) end o += count end else writeu16(out, o * 2, w) o += 1 end end return out, nil end @native function Expand.rlew(b: buffer, at: number, n: number, outWords: number, tag: number): (buffer?, string?) local out = buffer.create(outWords * 2) local o = 0 local p, e = at, at + n while o < outWords do if p + 2 > e then return nil, "truncated RLEW data" end local w = readu16(b, p) p += 2 if w == tag then if p + 4 > e then return nil, "truncated RLEW data" end local count, v = readu16(b, p), readu16(b, p + 2) p += 4 if o + count > outWords then return nil, "RLEW run past the plane" end for k = 0, count - 1 do writeu16(out, (o + k) * 2, v) end o += count else writeu16(out, o * 2, w) o += 1 end end return out, nil end return Expand end __FILES["vector/svg"] = function() -- vector/svg: SVG 1.1 / 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: shapes and paths, transforms, -- nested svg / use / symbol, a CSS subset, gradients, clip-path, group opacity, strokes, dashes, units. Not supported -- (meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject, switch conditions, CSS combinators. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Sniff = __include("core/Sniff") local Bytes = __include("core/Bytes") local Types = __include("Types") local Xml = __include("codecs/text/Xml") local Parse = __include("vector/svg/Parse") local Render = __include("vector/svg/Render") local Write = __include("vector/svg/Write") -- ------------------------------------------------------------------------------------------------ contract local Svg = { name = "svg", category = "vector", extensions = { "svg" }, mime = { "image/svg+xml" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "codecs/image/Raster", "codecs/image/Blend", "core/Sniff" }, caps = { decode = true, encode = true, rasterize = true, text = false }, } type DecodeOptions = { maxBytes: number?, -- default 64 MB } type EncodeOptions = {} type RasterizeOptions = Render.Options -- ------------------------------------------------------------------------------------------------ sniff function Svg.sniff(r: Bytes.Reader): number local h = Sniff.text(r, 4096) if not string.match(h, "^%s*<") then return 0 end if string.find(h, ":]") or string.find(h, "<%w+:svg[%s>]") then return 0.95 end return 0 end -- ------------------------------------------------------------------------------------------------ decode function Svg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Vector?, Err.Err?) local maxBytes = opts and opts.maxBytes or 2 ^ 26 if r.limit - r.base > maxBytes then return nil, Err.new(Err.LIMIT, "file is over the byte limit") end local doc, xerr = Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base)) if not doc then return nil, xerr end local v, msg = Parse.document(doc) if not v then return nil, Err.new(Err.CORRUPT, msg or "bad SVG") end v.meta.source = { format = "svg" } return v, nil end -- ------------------------------------------------------------------------------------------------ encode function Svg.encode(v: Types.Vector, opts: EncodeOptions?): (buffer?, Err.Err?) local s, err = Write.vector(v) if not s then return nil, Err.new(Err.ARG, err or "bad Vector") end return buffer.fromstring(s), nil end -- ------------------------------------------------------------------------------------------------ extras function Svg.rasterize(v: Types.Vector, w: number?, h: number?, opts: RasterizeOptions?): (Types.Image?, Err.Err?) if type(v) ~= "table" or type(v.paths) ~= "table" then return nil, Err.new(Err.ARG, "needs a Vector value") end local W = math.ceil(w or v.width or 0) local H = math.ceil(h or v.height or 0) if W < 1 or H < 1 or W * H > 2 ^ 26 then return nil, Err.new(Err.ARG, "bad raster size") end return Render.rasterize(v, W, H, opts), nil end return Svg end __FILES["vector/svg/Parse"] = function() -- vector/svg/Parse: an SVG document (an Xml tree) to a Types.Vector: the cascade, shapes, paints, groups, clips. local Xml = __include("codecs/text/Xml") local Types = __include("Types") local Style = __include("vector/svg/Style") local PathData = __include("vector/svg/PathData") local Parse = {} type Node = Types.XmlNode type M = { number } local IDENTITY = { 1, 0, 0, 1, 0, 0 } local mul = Style.multiply -- properties that inherit, and their initial values local INHERITED: { [string]: string } = { fill = "black", ["fill-opacity"] = "1", ["fill-rule"] = "nonzero", stroke = "none", ["stroke-width"] = "1", ["stroke-opacity"] = "1", ["stroke-linecap"] = "butt", ["stroke-linejoin"] = "miter", ["stroke-miterlimit"] = "4", ["stroke-dasharray"] = "none", ["stroke-dashoffset"] = "0", ["clip-rule"] = "nonzero", visibility = "visible", color = "black", ["font-size"] = "16", } -- not inherited (reset per element) local LOCAL: { [string]: boolean } = { opacity = true, ["clip-path"] = true, display = true, ["stop-color"] = true, ["stop-opacity"] = true, mask = true, filter = true, } local UNSUPPORTED: { [string]: boolean } = { text = true, image = true, pattern = true, mask = true, marker = true, filter = true, foreignObject = true, textPath = true, tspan = true } local CONTAINERS = { g = true, a = true, switch = true } local SHAPES = { path = true, rect = true, circle = true, ellipse = true, line = true, polyline = true, polygon = true } type Ctx = { ids: { [string]: Node }, rules: { Style.Rule }, vector: Types.Vector, groups: { any }, clips: { any }, unsupported: { [string]: number }, vw: number, vh: number, depth: number, useDepth: number, } local function local_(n: Node): string return Xml.localName(n.name) end local function attr(n: Node, k: string): string? local a = n.attrs :: any return a[k] end local function href(n: Node): string? local h = attr(n, "href") or attr(n, "xlink:href") if h == nil then for k, v in pairs(n.attrs :: any) do if type(k) == "string" and Xml.localName(k) == "href" then return v end end end return h end local function refId(s: string?): string? if s == nil then return nil end return string.match(s, "^%s*#(.-)%s*$") or string.match(s, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)") end -- cascade: presentation attributes < CSS rules (by specificity, then order) < style="" local function specified(n: Node, ctx: Ctx): { [string]: string } local out: { [string]: string } = {} for k, v in pairs(n.attrs :: any) do if type(k) == "string" and type(v) == "string" and (INHERITED[k] or LOCAL[k]) then out[k] = v end end if #ctx.rules > 0 then local classes: { [string]: boolean } = {} for c in string.gmatch(attr(n, "class") or "", "%S+") do classes[c] = true end local hits: { Style.Rule } = {} for _, r in ctx.rules do if Style.matches(r.selector, local_(n), attr(n, "id"), classes) then table.insert(hits, r) end end table.sort(hits, function(a: any, b: any): boolean if a.selector.specificity ~= b.selector.specificity then return a.selector.specificity < b.selector.specificity end return a.order < b.order end) for _, r in hits do for k, v in pairs(r.decls) do out[k] = v end end end local st = attr(n, "style") if st then for k, v in pairs(Style.declarations(st)) do out[k] = v end end return out end local function computed(parent: { [string]: string }, n: Node, ctx: Ctx): { [string]: string } local out: { [string]: string } = {} for k in pairs(INHERITED) do out[k] = parent[k] end for k, v in pairs(specified(n, ctx)) do if v == "inherit" then out[k] = parent[k] elseif INHERITED[k] or LOCAL[k] then out[k] = v end end return out end local function len(s: string?, ref: number, st: { [string]: string }, default: number?): number? local fs = Style.length(st["font-size"], 16) or 16 local v = Style.length(s, ref, fs) if v == nil then return default end return v end -- ------------------------------------------------------------------------------------------------ paints local function stops(g: Node, ctx: Ctx, seen: { [Node]: boolean }): { { number } } local list = {} local parentStyle = computed(INHERITED, g, ctx) for _, s in Xml.children(g) do if local_(s) == "stop" then local st = computed(parentStyle, s, ctx) local off = attr(s, "offset") or "0" local o = tonumber(string.match(off, "^%s*([%d.eE+-]+)%s*%%%s*$") or "") local offset = if o then o / 100 else (tonumber(off) or 0) offset = math.clamp(offset, 0, 1) if #list > 0 and offset < list[#list][1] then offset = list[#list][1] end local col = Style.color(st["stop-color"] or "black", Style.color(st.color or "black")) or { 0, 0, 0, 255 } if col == "none" then col = { 0, 0, 0, 0 } end local op = math.clamp(tonumber(st["stop-opacity"] or "1") or 1, 0, 1) table.insert(list, { offset, col[1], col[2], col[3], math.floor(col[4] * op + 0.5) }) end end if #list == 0 then local h = refId(href(g)) local other = if h then ctx.ids[h] else nil if other and not seen[other] then seen[other] = true return stops(other, ctx, seen) end end return list end local function gattr(g: Node, k: string, ctx: Ctx): string? local cur: Node? = g local guard = 0 while cur and guard < 16 do local v = attr(cur, k) if v ~= nil then return v end local h = refId(href(cur)) cur = if h then ctx.ids[h] else nil guard += 1 end return nil end local function gradient(g: Node, opacity: number, ctx: Ctx): any local kind = local_(g) local units = gattr(g, "gradientUnits", ctx) or "objectBoundingBox" local obb = units ~= "userSpaceOnUse" local list = stops(g, ctx, { [g] = true }) if #list == 0 then return "none" end if #list == 1 then local s = list[1] return { type = "color", color = { s[2], s[3], s[4], math.floor(s[5] * opacity + 0.5) } } end local function coord(k: string, default: string, ref: number): number local v = gattr(g, k, ctx) or default local pct = string.match(v, "^%s*([%d.eE+-]+)%s*%%%s*$") if pct then local x = tonumber(pct) or 0 return if obb then x / 100 else x / 100 * ref end return Style.length(v, ref) or 0 end local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2) local p: any = { type = if kind == "linearGradient" then "linear" else "radial", units = if obb then "objectBoundingBox" else "userSpaceOnUse", spread = gattr(g, "spreadMethod", ctx) or "pad", stops = list, opacity = opacity, } local t = gattr(g, "gradientTransform", ctx) if t then p.transform = Style.transform(t) end if p.type == "linear" then p.x1, p.y1 = coord("x1", "0%", ctx.vw), coord("y1", "0%", ctx.vh) p.x2, p.y2 = coord("x2", "100%", ctx.vw), coord("y2", "0%", ctx.vh) else p.cx, p.cy = coord("cx", "50%", ctx.vw), coord("cy", "50%", ctx.vh) p.r = coord("r", "50%", diag) p.fx = if gattr(g, "fx", ctx) then coord("fx", "50%", ctx.vw) else p.cx p.fy = if gattr(g, "fy", ctx) then coord("fy", "50%", ctx.vh) else p.cy p.fr = coord("fr", "0%", diag) end return p end local function paint(value: string?, opacity: number, st: { [string]: string }, ctx: Ctx): any if value == nil then return nil end local id = string.match(value, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)%s*(.*)$") if id then local fallback = string.match(value, "%)%s*(.-)%s*$") local g = ctx.ids[id] if g and (local_(g) == "linearGradient" or local_(g) == "radialGradient") then local p = gradient(g, opacity, ctx) return if p == "none" then nil else p end if g and local_(g) == "pattern" then ctx.unsupported.pattern = (ctx.unsupported.pattern or 0) + 1 end if fallback and fallback ~= "" then return paint(fallback, opacity, st, ctx) end return nil end local c = Style.color(value, Style.color(st.color or "black") :: any) if c == nil or c == "none" then return nil end return { type = "color", color = { c[1], c[2], c[3], math.floor(c[4] * opacity + 0.5) } } end -- ------------------------------------------------------------------------------------------------ shapes local function shape(n: Node, st: { [string]: string }, ctx: Ctx): { PathData.Cmd }? local kind = local_(n) local vw, vh = ctx.vw, ctx.vh local diag = math.sqrt((vw * vw + vh * vh) / 2) if kind == "path" then local d = attr(n, "d") if d == nil then return nil end local cmds = PathData.parse(d) return cmds elseif kind == "rect" then local x, y = len(attr(n, "x"), vw, st, 0) :: number, len(attr(n, "y"), vh, st, 0) :: number local w, h = len(attr(n, "width"), vw, st, 0) :: number, len(attr(n, "height"), vh, st, 0) :: number if w <= 0 or h <= 0 then return nil end local rx: number?, ry: number? = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st) if rx and rx < 0 then rx = nil end if ry and ry < 0 then ry = nil end rx = rx or ry or 0 ry = ry or rx local rx: number, ry: number = math.min(rx :: number, w / 2), math.min(ry :: number, h / 2) if rx <= 0 or ry <= 0 then return { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } } :: { PathData.Cmd } end local out: { PathData.Cmd } = { { op = "M", x + rx, y }, { op = "L", x + w - rx, y } } PathData.arc(x + w - rx, y, rx, ry, 0, false, true, x + w, y + ry, out) table.insert(out, { op = "L", x + w, y + h - ry }) PathData.arc(x + w, y + h - ry, rx, ry, 0, false, true, x + w - rx, y + h, out) table.insert(out, { op = "L", x + rx, y + h }) PathData.arc(x + rx, y + h, rx, ry, 0, false, true, x, y + h - ry, out) table.insert(out, { op = "L", x, y + ry }) PathData.arc(x, y + ry, rx, ry, 0, false, true, x + rx, y, out) table.insert(out, { op = "Z" } :: PathData.Cmd) return out elseif kind == "circle" or kind == "ellipse" then local cx, cy = len(attr(n, "cx"), vw, st, 0) :: number, len(attr(n, "cy"), vh, st, 0) :: number local rx, ry if kind == "circle" then rx = len(attr(n, "r"), diag, st, 0) :: number ry = rx else rx, ry = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st) rx = rx or ry or 0 ry = ry or rx end if (rx :: number) <= 0 or (ry :: number) <= 0 then return nil end local out: { PathData.Cmd } = { { op = "M", cx + rx, cy } } PathData.arc(cx + rx, cy, rx, ry, 0, false, true, cx, cy + ry, out) PathData.arc(cx, cy + ry, rx, ry, 0, false, true, cx - rx, cy, out) PathData.arc(cx - rx, cy, rx, ry, 0, false, true, cx, cy - ry, out) PathData.arc(cx, cy - ry, rx, ry, 0, false, true, cx + rx, cy, out) table.insert(out, { op = "Z" } :: PathData.Cmd) return out elseif kind == "line" then local x1, y1 = len(attr(n, "x1"), vw, st, 0) :: number, len(attr(n, "y1"), vh, st, 0) :: number local x2, y2 = len(attr(n, "x2"), vw, st, 0) :: number, len(attr(n, "y2"), vh, st, 0) :: number return { { op = "M", x1, y1 }, { op = "L", x2, y2 } } :: { PathData.Cmd } elseif kind == "polyline" or kind == "polygon" then local v = Style.numbers(attr(n, "points")) if #v < 4 then return nil end local out: { PathData.Cmd } = { { op = "M", v[1], v[2] } } for i = 3, #v - 1, 2 do table.insert(out, { op = "L", v[i], v[i + 1] }) end if kind == "polygon" then table.insert(out, { op = "Z" } :: PathData.Cmd) end return out end return nil end -- ------------------------------------------------------------------------------------------------ clip paths local function transformOf(n: Node): M local t = attr(n, "transform") if t then return Style.transform(t) or IDENTITY end return IDENTITY end local function clip(ref: string, ctm: M, bbox: { number }?, st: { [string]: string }, ctx: Ctx): number? local cp = ctx.ids[ref] if cp == nil or local_(cp) ~= "clipPath" then return nil end local base = mul(ctm, transformOf(cp)) if attr(cp, "clipPathUnits") == "objectBoundingBox" then if not bbox then return nil end base = mul(base, { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] }) end local cpStyle = computed(st, cp, ctx) local paths = {} local function add(n: Node, parentStyle: { [string]: string }, m: M, depth: number) if depth > 8 then return end local s = computed(parentStyle, n, ctx) if s.display == "none" or s.visibility == "hidden" then return end local k = local_(n) local tm = mul(m, transformOf(n)) if SHAPES[k] then local cmds = shape(n, s, ctx) if cmds and #cmds > 0 then table.insert(paths, { d = cmds, transform = tm, rule = s["clip-rule"] or "nonzero" }) end elseif k == "use" then local h = refId(href(n)) local target = if h then ctx.ids[h] else nil if target then local x, y = len(attr(n, "x"), ctx.vw, s, 0) :: number, len(attr(n, "y"), ctx.vh, s, 0) :: number add(target, s, mul(tm, { 1, 0, 0, 1, x, y }), depth + 1) end end end for _, c in Xml.children(cp) do add(c, cpStyle, base, 0) end table.insert(ctx.clips, { paths = paths }) return #ctx.clips end -- ------------------------------------------------------------------------------------------------ the walk local walk: (n: Node, parentStyle: { [string]: string }, ctm: M, group: number?, ctx: Ctx) -> () local function bboxOf(cmds: { PathData.Cmd }): { number }? local x0, y0, x1, y1 = PathData.bounds(cmds) if not x0 then return nil end return { x0 :: number, y0 :: number, x1 :: number, y1 :: number } end local function emitShape(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx) if st.visibility == "hidden" or st.visibility == "collapse" then return end local cmds = shape(n, st, ctx) if not cmds or #cmds == 0 then return end local tm = mul(ctm, transformOf(n)) local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) local fill = paint(st.fill, math.clamp(tonumber(st["fill-opacity"]) or 1, 0, 1), st, ctx) local stroke = paint(st.stroke, math.clamp(tonumber(st["stroke-opacity"]) or 1, 0, 1), st, ctx) local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2) local sw = len(st["stroke-width"], diag, st, 1) :: number if sw <= 0 then stroke = nil end if fill == nil and stroke == nil then return end if local_(n) == "line" then fill = nil -- a line has no inside end local clipRef = refId(st["clip-path"]) local clipId: number? = nil if clipRef then clipId = clip(clipRef, tm, bboxOf(cmds), st, ctx) if clipId == nil and ctx.ids[clipRef] then return -- a broken clip reference (bad units): nothing shows end end -- opacity on a shape with both a fill and a stroke: a group, so the overlap is not counted twice local g = group if opacity < 1 and fill and stroke then table.insert(ctx.groups, { opacity = opacity, parent = group }) g = #ctx.groups opacity = 1 end local p: any = { d = cmds, fill = fill, fillRule = if st["fill-rule"] == "evenodd" then "evenodd" else "nonzero", stroke = stroke, strokeWidth = sw, transform = tm, opacity = opacity, group = g, clip = clipId, id = attr(n, "id"), } if stroke then p.strokeLineJoin = st["stroke-linejoin"] p.strokeLineCap = st["stroke-linecap"] p.strokeMiterLimit = tonumber(st["stroke-miterlimit"]) or 4 local dash = st["stroke-dasharray"] if dash and dash ~= "none" then local list = {} local ok = true for part in string.gmatch(dash, "[^,%s]+") do local v = len(part, diag, st) if v == nil or v < 0 then ok = false end table.insert(list, v or 0) end local sum = 0 for _, v in list do sum += v end if ok and sum > 0 then if #list % 2 == 1 then table.move(list, 1, #list, #list + 1, list) end p.strokeDashArray = list p.strokeDashOffset = len(st["stroke-dashoffset"], diag, st, 0) end end end table.insert(ctx.vector.paths, p) end function Parse.viewTransform(vb: { number }?, par: string?, x: number, y: number, w: number, h: number): M if vb == nil or vb[3] <= 0 or vb[4] <= 0 then return { 1, 0, 0, 1, x, y } end local sx, sy = w / vb[3], h / vb[4] local align, mode = "xmidymid", "meet" if par then local a, m = string.match(string.lower(par), "^%s*([%w]+)%s*(%a*)") if a == "defer" then a, m = string.match(string.lower(par), "^%s*defer%s+([%w]+)%s*(%a*)") end align = a or align if m and m ~= "" then mode = m end end if align == "none" then return { sx, 0, 0, sy, x - vb[1] * sx, y - vb[2] * sy } end local s = if mode == "slice" then math.max(sx, sy) else math.min(sx, sy) local tx, ty = x - vb[1] * s, y - vb[2] * s local ax, ay = string.match(align, "^x(%a%a%a)y(%a%a%a)$") if ax == "mid" then tx += (w - vb[3] * s) / 2 elseif ax == "max" then tx += w - vb[3] * s end if ay == "mid" then ty += (h - vb[4] * s) / 2 elseif ay == "max" then ty += h - vb[4] * s end return { s, 0, 0, s, tx, ty } end local function viewBox(n: Node): { number }? local v = Style.numbers(attr(n, "viewBox")) if #v == 4 and v[3] > 0 and v[4] > 0 then return v end return nil end local function container(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx, children: { Node }?) local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) local clipRef = refId(st["clip-path"]) local g = group if opacity < 1 or clipRef then local clipId: number? = nil if clipRef then local bbox: { number }? = nil local cp = ctx.ids[clipRef] if cp and attr(cp, "clipPathUnits") == "objectBoundingBox" then local saveV, saveG, saveC = ctx.vector, ctx.groups, ctx.clips local scratch = Types.Vector.new(0, 0) ctx.vector, ctx.groups, ctx.clips = scratch, {}, {} for _, c in children or Xml.children(n) do walk(c, st, IDENTITY, nil, ctx) end ctx.vector, ctx.groups, ctx.clips = saveV, saveG, saveC local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge for _, p in scratch.paths do local b = bboxOf(p.d) if b then local m = p.transform or IDENTITY for _, corner in { { b[1], b[2] }, { b[3], b[2] }, { b[1], b[4] }, { b[3], b[4] } } do local px = m[1] * corner[1] + m[3] * corner[2] + m[5] local py = m[2] * corner[1] + m[4] * corner[2] + m[6] x0, y0, x1, y1 = math.min(x0, px), math.min(y0, py), math.max(x1, px), math.max(y1, py) end end end if x0 <= x1 then bbox = { x0, y0, x1, y1 } end end clipId = clip(clipRef, ctm, bbox, st, ctx) if clipId == nil and cp then return end end table.insert(ctx.groups, { opacity = opacity, parent = group, clip = clipId }) g = #ctx.groups end if local_(n) == "switch" then -- the first child that renders (conditional attributes are not evaluated) for _, c in children or Xml.children(n) do if UNSUPPORTED[local_(c)] == nil then walk(c, st, ctm, g, ctx) return end end return end for _, c in children or Xml.children(n) do walk(c, st, ctm, g, ctx) end end -- nested svg / symbol: overflow is hidden unless it says otherwise local function viewportGroup(n: Node, m: M, x: number, y: number, w: number, h: number, group: number?, ctx: Ctx): number? local ov = attr(n, "overflow") if ov == "visible" or ov == "auto" then return group end local rect = { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } } table.insert(ctx.clips, { paths = { { d = rect, transform = m, rule = "nonzero" } } }) table.insert(ctx.groups, { opacity = 1, parent = group, clip = #ctx.clips }) return #ctx.groups end walk = function(n: Node, parentStyle: { [string]: string }, ctm: M, group: number?, ctx: Ctx) if ctx.depth > 200 then return end local kind = local_(n) if kind == "defs" or kind == "clipPath" or kind == "linearGradient" or kind == "radialGradient" or kind == "symbol" or kind == "style" or kind == "title" or kind == "desc" or kind == "metadata" then return end local st = computed(parentStyle, n, ctx) if st.display == "none" then return end if UNSUPPORTED[kind] then ctx.unsupported[kind] = (ctx.unsupported[kind] or 0) + 1 return end ctx.depth += 1 if CONTAINERS[kind] then container(n, st, mul(ctm, transformOf(n)), group, ctx) elseif SHAPES[kind] then emitShape(n, st, ctm, group, ctx) elseif kind == "use" then local h = refId(href(n)) local target = if h then ctx.ids[h] else nil if target and ctx.useDepth < 16 then ctx.useDepth += 1 local x, y = len(attr(n, "x"), ctx.vw, st, 0) :: number, len(attr(n, "y"), ctx.vh, st, 0) :: number local m = mul(mul(ctm, transformOf(n)), { 1, 0, 0, 1, x, y }) local tk = local_(target) if tk == "symbol" or tk == "svg" then local w = len(attr(n, "width") or attr(target, "width") or "100%", ctx.vw, st, ctx.vw) :: number local h2 = len(attr(n, "height") or attr(target, "height") or "100%", ctx.vh, st, ctx.vh) :: number local vb = viewBox(target) local inner = mul(m, Parse.viewTransform(vb, attr(target, "preserveAspectRatio"), 0, 0, w, h2)) local saveW, saveH = ctx.vw, ctx.vh if vb then ctx.vw, ctx.vh = vb[3], vb[4] end local tst = computed(st, target, ctx) -- the use element's own opacity applies to the symbol's content too local uo = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) if uo < 1 then tst.opacity = tostring(uo * math.clamp(tonumber(tst.opacity or "1") or 1, 0, 1)) end if tst["clip-path"] == nil then tst["clip-path"] = st["clip-path"] end -- the symbol's children as a group of the use element, clipped to its viewport local vg = viewportGroup(target, m, 0, 0, w, h2, group, ctx) container(n, tst, mul(inner, transformOf(target)), vg, ctx, Xml.children(target)) ctx.vw, ctx.vh = saveW, saveH else -- the referenced element as if it were the use element's only child container(n, st, m, group, ctx, { target }) end ctx.useDepth -= 1 end elseif kind == "svg" then local x, y = len(attr(n, "x"), ctx.vw, st, 0) :: number, len(attr(n, "y"), ctx.vh, st, 0) :: number local w = len(attr(n, "width") or "100%", ctx.vw, st, ctx.vw) :: number local h = len(attr(n, "height") or "100%", ctx.vh, st, ctx.vh) :: number local vb = viewBox(n) local m = mul(ctm, Parse.viewTransform(vb, attr(n, "preserveAspectRatio"), x, y, w, h)) local saveW, saveH = ctx.vw, ctx.vh if vb then ctx.vw, ctx.vh = vb[3], vb[4] else ctx.vw, ctx.vh = w, h end container(n, st, m, viewportGroup(n, ctm, x, y, w, h, group, ctx), ctx) ctx.vw, ctx.vh = saveW, saveH end ctx.depth -= 1 end -- ------------------------------------------------------------------------------------------------ entry function Parse.document(doc: any): (Types.Vector?, string?) local root = doc.root if root == nil or Xml.localName(root.name) ~= "svg" then return nil, "the root element is not " end local ids: { [string]: Node } = {} local rules: { Style.Rule } = {} local count = 0 local function index(n: Node) count += 1 if count > 1000000 then return end local id = attr(n, "id") if id and ids[id] == nil then ids[id] = n end if local_(n) == "style" then Style.css(Xml.text(n), rules) end for _, c in Xml.children(n) do index(c) end end index(root) local vb = viewBox(root) local w = Style.length(attr(root, "width") or "100%", if vb then vb[3] else 100) or 100 local h = Style.length(attr(root, "height") or "100%", if vb then vb[4] else 100) or 100 if w <= 0 or h <= 0 then w, h = 100, 100 end local v = Types.Vector.new(w, h) v.viewBox = vb or { 0, 0, w, h } local ctx: Ctx = { ids = ids, rules = rules, vector = v, groups = {}, clips = {}, unsupported = {}, vw = v.viewBox[3], vh = v.viewBox[4], depth = 0, useDepth = 0, } local st = computed(INHERITED, root, ctx) container(root, st, IDENTITY, nil, ctx) v.meta.preserveAspectRatio = attr(root, "preserveAspectRatio") v.meta.groups = ctx.groups v.meta.clips = ctx.clips if next(ctx.unsupported) then v.meta.unsupported = ctx.unsupported end return v, nil end return Parse end __FILES["vector/svg/PathData"] = function() -- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3, SVG 2 "Path data"); arcs to cubics per implementation notes -- F.6 (out-of-range radii scaled up); parsing stops at the first error, keeping the commands so far (as the spec says). local PathData = {} type Cmd = { op: string, [number]: number } local byte, sub, find = string.byte, string.sub, string.find local abs, sqrt, cos, sin, atan2, ceil, pi = math.abs, math.sqrt, math.cos, math.sin, math.atan2, math.ceil, math.pi local ARGS = { M = 2, L = 2, H = 1, V = 1, C = 6, S = 4, Q = 4, T = 2, A = 7, Z = 0 } local function arc(x1: number, y1: number, rx: number, ry: number, phiDeg: number, fa: boolean, fs: boolean, x2: number, y2: number, out: { Cmd }) if x1 == x2 and y1 == y2 then return end rx, ry = abs(rx), abs(ry) if rx == 0 or ry == 0 then table.insert(out, { op = "L", x2, y2 }) return end local phi = phiDeg % 360 * pi / 180 local cp, sp = cos(phi), sin(phi) local dx, dy = (x1 - x2) / 2, (y1 - y2) / 2 local x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy local lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry) if lambda > 1 then local s = sqrt(lambda) rx, ry = rx * s, ry * s end local num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p local den = rx * rx * y1p * y1p + ry * ry * x1p * x1p local coef = if den == 0 then 0 else sqrt(math.max(0, num / den)) if fa == fs then coef = -coef end local cxp, cyp = coef * rx * y1p / ry, -coef * ry * x1p / rx local cx, cy = cp * cxp - sp * cyp + (x1 + x2) / 2, sp * cxp + cp * cyp + (y1 + y2) / 2 local function angle(ux: number, uy: number, vx: number, vy: number): number return atan2(ux * vy - uy * vx, ux * vx + uy * vy) end local ux, uy = (x1p - cxp) / rx, (y1p - cyp) / ry local vx, vy = (-x1p - cxp) / rx, (-y1p - cyp) / ry local t1 = angle(1, 0, ux, uy) local dt = angle(ux, uy, vx, vy) if not fs and dt > 0 then dt -= 2 * pi elseif fs and dt < 0 then dt += 2 * pi end local n = math.max(1, ceil(abs(dt) / (pi / 2) - 1e-9)) local step = dt / n local k = 4 / 3 * math.tan(step / 4) local px, py = x1, y1 for i = 1, n do local a0 = t1 + (i - 1) * step local a1 = t1 + i * step local c0, s0, c1, s1 = cos(a0), sin(a0), cos(a1), sin(a1) -- the unit-circle segment's control points, scaled by the radii, rotated by phi, moved to the centre local e1x, e1y = c0 - k * s0, s0 + k * c0 local e2x, e2y = c1 + k * s1, s1 - k * c1 local ex, ey = c1, s1 local function map(x: number, y: number): (number, number) x, y = x * rx, y * ry return cp * x - sp * y + cx, sp * x + cp * y + cy end local ax, ay = map(e1x, e1y) local bx, by = map(e2x, e2y) local qx, qy = map(ex, ey) if i == n then qx, qy = x2, y2 end table.insert(out, { op = "C", ax, ay, bx, by, qx, qy }) px, py = qx, qy end local _ = px + py end PathData.arc = arc function PathData.parse(d: string): ({ Cmd }, boolean) local out: { Cmd } = {} local i, n = 1, #d local cx, cy = 0, 0 local sx, sy = 0, 0 local lcx, lcy = 0, 0 local last = "" local cmd: string? = nil local rel = false local nums: { number } = table.create(7) :: { number } local function ws() while i <= n do local c = byte(d, i) if c == 32 or c == 9 or c == 10 or c == 13 or c == 12 then i += 1 else break end end end local function comma() ws() if i <= n and byte(d, i) == 44 then i += 1 ws() end end local function digits(): boolean local any = false while i <= n do local c = byte(d, i) if c >= 48 and c <= 57 then i += 1 any = true else break end end return any end -- an SVG number: sign? (digits ("." digits?)? | "." digits) exponent?; "1.5.5" is 1.5 then .5 local function number(): number? ws() local s = i local c = byte(d, i) if c == 43 or c == 45 then i += 1 end local whole = digits() local frac = false if i <= n and byte(d, i) == 46 then i += 1 frac = digits() end if not whole and not frac then i = s return nil end c = byte(d, i) if c == 101 or c == 69 then local save = i i += 1 c = byte(d, i) if c == 43 or c == 45 then i += 1 end if not digits() then i = save end end return tonumber(sub(d, s, i - 1)) end local function flag(): number? ws() local c = byte(d, i) if c == 48 or c == 49 then i += 1 return c - 48 end return nil end while true do ws() if i > n then break end local c = sub(d, i, i) local up = string.upper(c) if ARGS[up] ~= nil and find(c, "%a") then cmd = up rel = c ~= up i += 1 if up == "Z" then table.insert(out, { op = "Z" } :: Cmd) cx, cy = sx, sy last = "Z" cmd = nil continue end elseif cmd == nil then return out, false end local c2 = cmd :: string local na = ARGS[c2] for k = 1, na do local v = if c2 == "A" and (k == 4 or k == 5) then flag() else number() if v == nil then return out, false end nums[k] = v if k < na then comma() end end comma() local ox, oy = if rel then cx else 0, if rel then cy else 0 if c2 == "M" then cx, cy = nums[1] + ox, nums[2] + oy sx, sy = cx, cy table.insert(out, { op = "M", cx, cy }) cmd = "L" -- further pairs are line-tos elseif c2 == "L" then cx, cy = nums[1] + ox, nums[2] + oy table.insert(out, { op = "L", cx, cy }) elseif c2 == "H" then cx = nums[1] + ox table.insert(out, { op = "L", cx, cy }) elseif c2 == "V" then cy = nums[1] + (if rel then cy else 0) table.insert(out, { op = "L", cx, cy }) elseif c2 == "C" then local x1, y1, x2, y2 = nums[1] + ox, nums[2] + oy, nums[3] + ox, nums[4] + oy cx, cy = nums[5] + ox, nums[6] + oy table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy }) lcx, lcy = x2, y2 elseif c2 == "S" then local x1, y1 = cx, cy if last == "C" or last == "S" then x1, y1 = 2 * cx - lcx, 2 * cy - lcy end local x2, y2 = nums[1] + ox, nums[2] + oy cx, cy = nums[3] + ox, nums[4] + oy table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy }) lcx, lcy = x2, y2 elseif c2 == "Q" then local x1, y1 = nums[1] + ox, nums[2] + oy cx, cy = nums[3] + ox, nums[4] + oy table.insert(out, { op = "Q", x1, y1, cx, cy }) lcx, lcy = x1, y1 elseif c2 == "T" then local x1, y1 = cx, cy if last == "Q" or last == "T" then x1, y1 = 2 * cx - lcx, 2 * cy - lcy end cx, cy = nums[1] + ox, nums[2] + oy table.insert(out, { op = "Q", x1, y1, cx, cy }) lcx, lcy = x1, y1 elseif c2 == "A" then local x2, y2 = nums[6] + ox, nums[7] + oy arc(cx, cy, nums[1], nums[2], nums[3], nums[4] ~= 0, nums[5] ~= 0, x2, y2, out) cx, cy = x2, y2 end last = if c2 == "M" then "M" else c2 end return out, true end function PathData.bounds(cmds: { Cmd }): (number?, number?, number?, number?) local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge local px, py = 0, 0 for _, c in cmds do local op = c.op if op == "C" then local ax, ay, bx, by, ex, ey = c[1], c[2], c[3], c[4], c[5], c[6] for axis = 1, 2 do local p0 = if axis == 1 then px else py local p1 = if axis == 1 then ax else ay local p2 = if axis == 1 then bx else by local p3 = if axis == 1 then ex else ey local a = -p0 + 3 * p1 - 3 * p2 + p3 local b = 2 * (p0 - 2 * p1 + p2) local cc = p1 - p0 local ts = {} if abs(a) < 1e-12 then if abs(b) > 1e-12 then table.insert(ts, -cc / b) end else local disc = b * b - 4 * a * cc if disc >= 0 then local s = sqrt(disc) table.insert(ts, (-b + s) / (2 * a)) table.insert(ts, (-b - s) / (2 * a)) end end for _, t in ts do if t > 0 and t < 1 then local mt = 1 - t local v = mt * mt * mt * p0 + 3 * mt * mt * t * p1 + 3 * mt * t * t * p2 + t * t * t * p3 if axis == 1 then x0, x1 = math.min(x0, v), math.max(x1, v) else y0, y1 = math.min(y0, v), math.max(y1, v) end end end end px, py = ex, ey elseif op == "Q" then local ax, ay, ex, ey = c[1], c[2], c[3], c[4] for axis = 1, 2 do local p0 = if axis == 1 then px else py local p1 = if axis == 1 then ax else ay local p2 = if axis == 1 then ex else ey local den = p0 - 2 * p1 + p2 if abs(den) > 1e-12 then local t = (p0 - p1) / den if t > 0 and t < 1 then local mt = 1 - t local v = mt * mt * p0 + 2 * mt * t * p1 + t * t * p2 if axis == 1 then x0, x1 = math.min(x0, v), math.max(x1, v) else y0, y1 = math.min(y0, v), math.max(y1, v) end end end end px, py = ex, ey elseif op == "M" or op == "L" then px, py = c[1], c[2] end if op ~= "Z" then x0, x1 = math.min(x0, px), math.max(x1, px) y0, y1 = math.min(y0, py), math.max(y1, py) end end if x0 > x1 then return nil, nil, nil, nil end return x0, y0, x1, y1 end local function num(v: number): string if v ~= v or v == math.huge or v == -math.huge then return "0" end local r = math.floor(v * 10000 + 0.5) / 10000 if r == math.floor(r) and abs(r) < 1e15 then return string.format("%d", r) end local s = string.format("%.4f", r) s = string.gsub(s, "0+$", "") return s end PathData.num = num function PathData.serialize(cmds: { Cmd }): string local out = {} for _, c in cmds do local k = ARGS[c.op] if k ~= nil then local parts = { c.op } local cnt = if c.op == "C" then 6 elseif c.op == "Q" then 4 elseif c.op == "Z" then 0 else 2 for j = 1, cnt do table.insert(parts, num(tonumber(c[j]) or 0)) end table.insert(out, table.concat(parts, " ")) end end return table.concat(out, " ") end local RASTER = { M = "moveTo", L = "lineTo", Q = "quadTo", C = "cubicTo", Z = "close" } function PathData.toRaster(cmds: { Cmd }): { any } local out = table.create(#cmds) for i, c in cmds do local r: any = { op = RASTER[c.op] or "close" } for j = 1, #c do r[j] = c[j] end out[i] = r end return out end return PathData end __FILES["vector/svg/Render"] = function() -- vector/svg/Render: a Types.Vector to an rgba8 Image via codecs/image/Raster and codecs/image/Blend. local Types = __include("Types") local Raster = __include("codecs/image/Raster") local Blend = __include("codecs/image/Blend") local PathData = __include("vector/svg/PathData") local Parse = __include("vector/svg/Parse") local Render = {} type M = { number } local function mul(m: M, n: M): M return Raster.multiply(m, n) end -- ------------------------------------------------------------------------------------------------ gradients local function stopColor(stops: { { number } }, t: number): (number, number, number, number) local n = #stops if t <= stops[1][1] then local s = stops[1] return s[2], s[3], s[4], s[5] end if t >= stops[n][1] then local s = stops[n] return s[2], s[3], s[4], s[5] end for i = 2, n do local b = stops[i] if t <= b[1] then local a = stops[i - 1] local span = b[1] - a[1] local f = if span > 0 then (t - a[1]) / span else 1 return a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f, a[4] + (b[4] - a[4]) * f, a[5] + (b[5] - a[5]) * f end end local s = stops[n] return s[2], s[3], s[4], s[5] end local function gradientFn(p: any, device: M, bbox: { number }?): ((number, number) -> (number, number, number, number))? local stops = p.stops if type(stops) ~= "table" or #stops == 0 then return nil end local g: M = { 1, 0, 0, 1, 0, 0 } if p.units ~= "userSpaceOnUse" then if not bbox or bbox[3] - bbox[1] <= 0 or bbox[4] - bbox[2] <= 0 then return nil -- a zero-size box: the gradient is not rendered end g = { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] } end if type(p.transform) == "table" then g = mul(g, p.transform) end local inv = Raster.invert(mul(device, g)) if not inv then return nil end local a, b, c, d, e, f = inv[1], inv[2], inv[3], inv[4], inv[5], inv[6] local spread = p.spread local opacity = tonumber(p.opacity) or 1 local function wrap(t: number): number if spread == "repeat" then return t - math.floor(t) elseif spread == "reflect" then local r = t % 2 return if r > 1 then 2 - r else r end return t end if p.type == "linear" then local x1, y1, x2, y2 = p.x1 or 0, p.y1 or 0, p.x2 or 1, p.y2 or 0 local dx, dy = x2 - x1, y2 - y1 local dd = dx * dx + dy * dy if dd == 0 then local r, gg, bb, aa = stopColor(stops, 1) return function(): (number, number, number, number) return r, gg, bb, aa * opacity end end return function(x: number, y: number): (number, number, number, number) local gx, gy = a * x + c * y + e, b * x + d * y + f local t = wrap(((gx - x1) * dx + (gy - y1) * dy) / dd) local r, gg, bb, aa = stopColor(stops, t) return r, gg, bb, aa * opacity end end local cx, cy, r = p.cx or 0.5, p.cy or 0.5, p.r or 0.5 local fx, fy = p.fx or cx, p.fy or cy if r <= 0 then local rr, gg, bb, aa = stopColor(stops, 1) return function(): (number, number, number, number) return rr, gg, bb, aa * opacity end end -- SVG 1.1: a focal point outside the circle moves onto it local fdx, fdy = fx - cx, fy - cy local fd = math.sqrt(fdx * fdx + fdy * fdy) if fd > r * 0.999 then local k = r * 0.999 / fd fx, fy = cx + fdx * k, cy + fdy * k end return function(x: number, y: number): (number, number, number, number) local gx, gy = a * x + c * y + e, b * x + d * y + f local dx, dy = gx - fx, gy - fy local t if dx == 0 and dy == 0 then t = 0 else -- the ray from the focus through the point meets the circle at s: t = 1 / s local ox, oy = fx - cx, fy - cy local qa = dx * dx + dy * dy local qb = 2 * (dx * ox + dy * oy) local qc = ox * ox + oy * oy - r * r local disc = qb * qb - 4 * qa * qc local s = (-qb + math.sqrt(math.max(0, disc))) / (2 * qa) t = if s > 0 then 1 / s else 1 end local rr, gg, bb, aa = stopColor(stops, wrap(t)) return rr, gg, bb, aa * opacity end end -- ------------------------------------------------------------------------------------------------ dashes local function subpaths(cmds: { any }): { { cmds: { any }, closed: boolean } } local out = {} local cur: { any }? = nil for _, c in cmds do if c.op == "M" then cur = { c } table.insert(out, { cmds = cur, closed = false }) elseif c.op == "Z" then if cur then out[#out].closed = true -- a new subpath starts at the same point if more segments follow local first = (cur :: { any })[1] cur = { { op = "M", first[1], first[2] } } table.insert(out, { cmds = cur, closed = false }) end elseif cur then table.insert(cur, c) end end return out end local function polyline(cmds: { any }, tol: number): { number } local pts: { number } = {} local px, py = 0, 0 for _, c in cmds do local op = c.op if op == "M" or op == "L" then px, py = c[1], c[2] table.insert(pts, px) table.insert(pts, py) elseif op == "Q" or op == "C" then local len = 0 local lx, ly = px, py for k = 1, #c - 1, 2 do len += math.sqrt((c[k] - lx) ^ 2 + (c[k + 1] - ly) ^ 2) lx, ly = c[k], c[k + 1] end local steps = math.clamp(math.ceil(math.sqrt(len / math.max(tol, 1e-4))), 1, 512) for i = 1, steps do local t = i / steps local mt = 1 - t local x, y if op == "Q" then x = mt * mt * px + 2 * mt * t * c[1] + t * t * c[3] y = mt * mt * py + 2 * mt * t * c[2] + t * t * c[4] else x = mt * mt * mt * px + 3 * mt * mt * t * c[1] + 3 * mt * t * t * c[3] + t * t * t * c[5] y = mt * mt * mt * py + 3 * mt * mt * t * c[2] + 3 * mt * t * t * c[4] + t * t * t * c[6] end table.insert(pts, x) table.insert(pts, y) end px, py = c[#c - 1], c[#c] end end return pts end local function dashed(cmds: { any }, dashes: { number }, offset: number, tol: number): { any } local out = {} local total = 0 for _, v in dashes do total += v end if total <= 0 then return cmds end for _, sp in subpaths(cmds) do if #sp.cmds < 2 then continue end local pts = polyline(sp.cmds, tol) if #pts < 4 then continue end if sp.closed then table.insert(pts, pts[1]) table.insert(pts, pts[2]) end -- dash state at the start (offset wraps through the pattern) local idx, left = 1, 0 local o = offset % total if o < 0 then o += total end while o > 0 do if o >= dashes[idx] then o -= dashes[idx] idx = idx % #dashes + 1 else break end end left = dashes[idx] - o local on = idx % 2 == 1 local cur: { any }? = nil if on then cur = { { op = "M", pts[1], pts[2] } } end for i = 1, #pts - 3, 2 do local x0, y0, x1, y1 = pts[i], pts[i + 1], pts[i + 2], pts[i + 3] local seg = math.sqrt((x1 - x0) ^ 2 + (y1 - y0) ^ 2) local pos = 0 local guard = 0 while seg - pos > left and guard < 100000 do guard += 1 pos += left local t = pos / seg local x, y = x0 + (x1 - x0) * t, y0 + (y1 - y0) * t if on then table.insert(cur :: { any }, { op = "L", x, y }) for _, c in cur :: { any } do table.insert(out, c) end cur = nil else cur = { { op = "M", x, y } } end on = not on idx = idx % #dashes + 1 left = dashes[idx] end left -= seg - pos if on and cur then table.insert(cur, { op = "L", x1, y1 }) end end if on and cur and #cur > 1 then for _, c in cur do table.insert(out, c) end end end return out end -- ------------------------------------------------------------------------------------------------ rendering type Options = { background: { number }?, -- r, g, b, a; default transparent tolerance: number?, -- device pixels; default 0.1 } local function scaleOf(m: M): number return math.sqrt(math.abs(m[1] * m[4] - m[2] * m[3])) end function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?): Types.Image local o: Options = opts or {} local img = Types.Image.new(w, h) local px = img.pixels local n = w * h local bg = o.background if type(bg) == "table" then local val = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216 for i = 0, n - 1 do buffer.writeu32(px, i * 4, val) end end local meta: any = if type(v.meta) == "table" then v.meta else {} local view = Parse.viewTransform(v.viewBox, meta.preserveAspectRatio, 0, 0, w, h) local groups: { any } = if type(meta.groups) == "table" then meta.groups else {} local clips: { any } = if type(meta.clips) == "table" then meta.clips else {} local tol = o.tolerance or 0.1 local clipCache: { [number]: buffer } = {} local function clipMask(id: number): buffer? if clipCache[id] then return clipCache[id] end local c = clips[id] if type(c) ~= "table" then return nil end local mask = buffer.create(n) for _, cp in (if type(c.paths) == "table" then c.paths else {}) do local m = Raster.mask(PathData.toRaster(cp.d), { transform = mul(view, cp.transform or Raster.IDENTITY), rule = cp.rule, clip = { 0, 0, w, h }, tolerance = tol }) if m then for y = 0, m.height - 1 do for x = 0, m.width - 1 do local cv = buffer.readu8(m.coverage, y * m.width + x) if cv > 0 then local i = (m.y + y) * w + m.x + x local old = buffer.readu8(mask, i) buffer.writeu8(mask, i, math.min(255, old + cv - math.floor(old * cv / 255 + 0.5))) end end end end end clipCache[id] = mask return mask end local stack: { { id: number?, img: Types.Image } } = { { id = nil, img = img } } local function chain(g: number?): { number } local out = {} local guard = 0 while g ~= nil and guard < 256 do table.insert(out, 1, g) local gr = groups[g] g = if type(gr) == "table" then gr.parent else nil guard += 1 end return out end local function pop() local top = table.remove(stack) :: any local below = stack[#stack].img local gr = groups[top.id] or {} local mask: any = nil if gr.clip then local cm = clipMask(gr.clip) mask = if cm then { pixels = cm, width = w, height = h, x = 0, y = 0, default = 0 } else { default = 0 } end Blend.composite(below.pixels, w, h, top.img.pixels, w, h, 0, 0, math.clamp(tonumber(gr.opacity) or 1, 0, 1), "normal", { mask = mask }) end local function draw(target: Types.Image, cmds: { any }, paint: any, device: M, rule: string?, opacity: number, bbox: { number }?) local fill: any if paint.type == "color" then fill = paint.color else fill = gradientFn(paint, device, bbox) if not fill then return end end Raster.fill(target, cmds, fill, { transform = device, rule = rule, opacity = opacity, tolerance = tol }) end for _, p in v.paths do if type(p) ~= "table" or type(p.d) ~= "table" then continue end local want = chain(p.group) local keep = 1 while keep < #stack and stack[keep + 1].id == want[keep] do keep += 1 end while #stack > keep do pop() end for k = keep, #want do table.insert(stack, { id = want[k], img = Types.Image.new(w, h) }) end local device = mul(view, p.transform or Raster.IDENTITY) local target = stack[#stack].img local clipMaskBuf: buffer? = nil if p.clip then clipMaskBuf = clipMask(p.clip) if not clipMaskBuf then continue end target = Types.Image.new(w, h) end local opacity = math.clamp(tonumber(p.opacity) or 1, 0, 1) local rcmds = PathData.toRaster(p.d) local bbox: { number }? = nil if (p.fill and p.fill.type ~= "color") or (p.stroke and p.stroke.type ~= "color") then local x0, y0, x1, y1 = PathData.bounds(p.d) if x0 then bbox = { x0 :: number, y0 :: number, x1 :: number, y1 :: number } end end if type(p.fill) == "table" then draw(target, rcmds, p.fill, device, p.fillRule, opacity, bbox) end if type(p.stroke) == "table" and (tonumber(p.strokeWidth) or 1) > 0 then local scale = math.max(scaleOf(device), 1e-6) local src = p.d if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then src = dashed(p.d, p.strokeDashArray, tonumber(p.strokeDashOffset) or 0, tol / scale) end local outline = Raster.stroke(PathData.toRaster(src), { width = tonumber(p.strokeWidth) or 1, join = p.strokeLineJoin, cap = p.strokeLineCap, miterLimit = p.strokeMiterLimit, tolerance = tol / scale, }) draw(target, outline, p.stroke, device, "nonzero", opacity, bbox) end if clipMaskBuf then Blend.composite(stack[#stack].img.pixels, w, h, target.pixels, w, h, 0, 0, 1, "normal", { mask = { pixels = clipMaskBuf, width = w, height = h, x = 0, y = 0, default = 0 } }) end end while #stack > 1 do pop() end return img end return Render end __FILES["vector/svg/Style"] = function() -- vector/svg/Style: SVG attribute value syntaxes (CSS Color 3, lengths, transform lists) and a