From 5acb0500475d75d8f928c748534a305f865b8a02 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 01:30:08 -0600 Subject: [PATCH] build: regenerate bundles after the comment cleanup of tests and codecs --- build/Rosetta.luau | 6014 +++++++------------------------ build/Rosetta.luau.linemap.json | 928 ++--- build/rosetta.lua | 5178 +++++--------------------- build/rosetta.lua.linemap.json | 928 ++--- 4 files changed, 3152 insertions(+), 9896 deletions(-) diff --git a/build/Rosetta.luau b/build/Rosetta.luau index 05dab0e..bd6adb0 100644 --- a/build/Rosetta.luau +++ b/build/Rosetta.luau @@ -22774,22 +22774,9 @@ return Write end __FILES["codecs/audio/Aac"] = function() --- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program --- config element, explicit and backward-compatible SBR signalling), ADTS headers, and raw_data_block decoding --- (codecs/audio/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it. --- Written from the standard (tables: codecs/audio/Aac/Tables); no third-party code. --- Supports: AAC-LC (object type 2) 1 - 8 channels, all sampling rates, long / short / start / stop windows, sine and KBD --- windows, M/S, intensity stereo, PNS, TNS, pulses. HE-AAC (SBR, PS: object types 5 / 29, or implicit SBR payloads) --- decodes its AAC-LC core at the core rate; `decoder.onExtension` receives every FIL extension payload (the hook for a --- later SBR / PS module), `decoder.sbr` says whether one was seen. Not supported: AAC Main prediction, LTP, SSR gain --- control, coupling channels, 960-sample frames, ER / USAC object types (UNSUPPORTED). --- --- local Aac = require("@rosetta/codecs/audio/Aac") --- local dec, err = Aac.decoder(asc) -- an AudioSpecificConfig (buffer) or { objectType, sfIndex, channels } --- local frames, err = dec:decode(buf, offset, length) -- one raw_data_block -> dec.pcm (frames * channels floats) --- local h = Aac.adts(buf, offset, limit) -- an ADTS header: { headerSize, frameSize, objectType, sfIndex, ... } --- --- Never throws: bad data returns nil, Err. +-- 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") @@ -22810,12 +22797,12 @@ local CONFIG_MAP: { [number]: { number } } = { type Config = { objectType: number, -- 2 = AAC-LC (the core object type when SBR / PS is signalled) sfIndex: number, - sampleRate: number, -- the core rate + sampleRate: number, channelConfig: number, channels: number, - sbr: boolean, -- SBR signalled (explicitly or backward-compatibly) + sbr: boolean, ps: boolean, - extensionRate: number?, -- the SBR output rate + extensionRate: number?, frameLength: number, } @@ -22847,7 +22834,7 @@ local function frequency(br: Bits.BitReader): (number, number) return i, Aac.RATES[i + 1] or 0 end --- pce(br) -> channels (program_config_element) +-- 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) @@ -22873,7 +22860,6 @@ local function pce(br: Bits.BitReader): number return channels end --- config(asc) -> Config | nil, Err: parse an AudioSpecificConfig 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") @@ -22957,7 +22943,6 @@ function Aac.config(asc: buffer): (Config?, Err.Err?) }, nil end --- asc(objectType, sfIndex, channelConfig) -> a 2-byte AudioSpecificConfig function Aac.asc(aot: number, sfIndex: number, channelConfig: number): buffer local b = buffer.create(2) local v = aot * 2048 + sfIndex * 128 + channelConfig * 8 @@ -22968,7 +22953,7 @@ end type Adts = { headerSize: number, -- 7, or 9 with a CRC - frameSize: number, -- the whole frame, header included + frameSize: number, objectType: number, sfIndex: number, sampleRate: number, @@ -22977,7 +22962,6 @@ type Adts = { protected: boolean, } --- adts(buf, offset, limit) -> Adts | nil (not a valid header at offset) 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 @@ -23008,14 +22992,13 @@ function Aac.adts(b: buffer, o: number, limit: number): Adts? } end --- ------------------------------------------------------------------------------------------------ decoder type Decoder = { config: Config, channels: number, sampleRate: number, frameLength: number, - pcm: { number }, -- the last frame: 1024 * channels interleaved floats (-1 .. 1), WAV channel order - sbr: boolean, -- SBR payloads seen in the stream (implicit signalling) or signalled + 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) -> (), @@ -23038,7 +23021,6 @@ local function decode(self: Decoder, buf: buffer, offset: number?, length: numbe self.sbr = true end if chans == 0 then - -- an empty frame (only fill elements): silence for i = 1, 1024 * self.channels do st.pcm[i] = 0 end @@ -23059,7 +23041,6 @@ local function reset(self: Decoder) end end --- decoder(asc | { objectType?, sfIndex, channels }) -> Decoder | nil, Err function Aac.decoder(asc: any): (Decoder?, Err.Err?) local cfg: Config if type(asc) == "buffer" then @@ -23114,12 +23095,8 @@ __FILES["codecs/audio/Aac/Decode"] = @native function() --- codecs/audio/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE / --- FIL / END elements, ics_info with window grouping, section data, scalefactors (with noise energies and intensity --- positions), pulse data, TNS, the eleven spectral codebooks with escapes, dequantisation, M/S and intensity stereo, --- perceptual noise substitution (FFmpeg's LCG so the noise matches it), the filterbank (sine / KBD windows, the four --- window sequences, IMDCT through codecs/audio/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook --- and otherwise skipped. Written from the standard; no third-party code. Never throws: returns nil, message. +-- 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") @@ -23131,14 +23108,13 @@ 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 --- ------------------------------------------------------------------------------------------------ bit reader -- 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 -- bit position -local BL = 0 -- bit limit +local BP = 0 +local BL = 0 local OVER = false -@native local function getBits(n: number): number -- 1 .. 25 +@native local function getBits(n: number): number local p = BP BP = p + n if p > BL then @@ -23162,7 +23138,6 @@ end return getBits(n) end --- ------------------------------------------------------------------------------------------------ Huffman local PEEK = 10 type Book = { tab: { number }, map: { [number]: number }, maxLen: number } @@ -23191,14 +23166,12 @@ for i = 1, 11 do SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i]) end --- the next symbol of a book, -1 for an invalid code @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 - -- a code longer than PEEK bits local code = getBits(PEEK) local map = bk.map for l = PEEK + 1, bk.maxLen do @@ -23211,7 +23184,6 @@ end return -1 end --- per codebook: dimension, unsigned, modulus, offset 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 } @@ -23223,7 +23195,6 @@ for i = 0, 8191 do POW43[i + 1] = i ^ (4 / 3) end --- ------------------------------------------------------------------------------------------------ windows 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 } @@ -23231,37 +23202,34 @@ 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 --- ------------------------------------------------------------------------------------------------ state type Channel = { - spec: { number }, -- 1024 dequantised coefficients (8 x 128 for short windows) - overlap: { number }, -- 1024 samples carried to the next frame + spec: { number }, + overlap: { number }, prevShape: number, - -- this frame's ics windowSequence: number, windowShape: number, maxSfb: number, numGroups: number, groupLen: { number }, - bandType: { number }, -- [g * maxSfb + sfb + 1] + bandType: { number }, sf: { number }, - -- tns - tnsFilters: { { { number } } }, -- per window: { length, order, direction, coefs ... } flattened per filter + tnsFilters: { { { number } } }, } type State = { sfIndex: number, - channels: number, -- configured channels (0: as found) + channels: number, frameLength: number, ch: { Channel }, - pcm: { number }, -- interleaved output floats - random: number, -- PNS generator state - time: { number }, -- 2048 IMDCT scratch - frame: { number }, -- 2048 windowed frame scratch - short: { number }, -- 256 scratch + pcm: { number }, + random: number, + time: { number }, + frame: { number }, + short: { number }, onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?, - extensions: number, -- extension payloads seen (SBR / PS / ...) - sbr: boolean, -- an SBR payload was seen - map: { number }?, -- element channel order -> output channel (1-based) + extensions: number, + sbr: boolean, + map: { number }?, } @native local function newChannel(): Channel @@ -23281,7 +23249,6 @@ type State = { end Decode.newChannel = newChannel --- ------------------------------------------------------------------------------------------------ ics @native local function icsInfo(st: State, c: Channel): string? if getBits(1) ~= 0 then return "reserved ics bit set" @@ -23507,7 +23474,6 @@ end end end --- the spectral data of one channel, dequantised into c.spec (also pulses, noise, intensity zeros) @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] @@ -23643,7 +23609,6 @@ end win += glen end if pulses then - -- long window: add the pulses to the quantised values, then dequantise every band for i = 1, #pulses, 2 do local pos = pulses[i] + 1 if pos <= 1024 then @@ -23722,7 +23687,6 @@ end return spectralData(st, c, pulses) end --- ------------------------------------------------------------------------------------------------ stereo @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] @@ -23776,7 +23740,6 @@ end end end --- ------------------------------------------------------------------------------------------------ filterbank @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 @@ -23801,7 +23764,6 @@ end else local t = st.time Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048) - -- left half if seq == LONG_STOP then local rise = if prev == 1 then KBD_SHORT else SINE_SHORT for n = 1, 448 do @@ -23819,7 +23781,6 @@ end frame[n] = t[n] * rise[n] end end - -- right half if seq == LONG_START then local fall = if shape == 1 then KBD_SHORT else SINE_SHORT for n = 1025, 1472 do @@ -23847,8 +23808,6 @@ end c.prevShape = shape end --- ------------------------------------------------------------------------------------------------ frame --- frame(st, buf, off, len) -> channels decoded | nil, message. Output: st.pcm, 1024 frames interleaved. @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) @@ -24017,10 +23976,9 @@ 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): the scalefactor and the eleven --- spectral Huffman codebooks (code, length per symbol), the scalefactor band offsets per sampling rate (1024 and 128 --- lines) and the TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code; --- see licenses/NOTICE.md). Generated; do not edit. +-- 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 = { @@ -24353,19 +24311,8 @@ return Tables end __FILES["codecs/audio/Ac3"] = function() --- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the --- decoder (codecs/audio/Ac3/Decode). Written from ATSC A/52:2018; no third-party code. A codec (layer 3): audio/ac3 --- (raw .ac3 files) builds on it, and the AC-3 tracks of MKV / MP4 / MPEG-TS / AVI reach it through --- containers/AudioWrap. --- Supports: every acmod (1+1, 1/0 .. 3/2) with or without LFE, 32 / 44.1 / 48 kHz, all bit rates, coupling with phase --- flags, rematrixing, block switching, delta bit allocation, dither, dynamic range control (off by default, --- `drc` = 0 .. 1 scales it). Output: every channel in WAVE order (L R C LFE surrounds), no downmix. Not supported: --- E-AC-3 (bsid 11 .. 16) and the reduced-rate bsid 9 / 10 streams (UNSUPPORTED). --- --- local h = Ac3.header(buf, offset, limit) -- { sampleRate, frameSize, channels, acmod, lfeon, bsid, bitrate } --- local dec = Ac3.decoder({ drc = 0 }) -- dec:decode(buf, offset, length) -> 1536, dec.pcm (interleaved) --- --- Never throws: bad data returns nil, Err. +-- 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") @@ -24377,16 +24324,14 @@ local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } type Header = { sampleRate: number, - frameSize: number, -- bytes - bitrate: number, -- bits per second + frameSize: number, + bitrate: number, channels: number, acmod: number, lfeon: boolean, bsid: number, } --- header(buf, o, limit) -> Header | nil (not an AC-3 / E-AC-3 syncframe header at o). E-AC-3 headers (bsid > 10) --- come back with frameSize from their own frmsiz field so a scanner can step over them. 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 @@ -24444,8 +24389,7 @@ function Ac3.header(b: buffer, o: number, limit: number): Header? } end --- the CRC-16 of A/52 section 7.10.1 (x^16 + x^15 + x^2 + 1, MSB first, zero start): a syncframe checks when the CRC of --- everything after the sync word is 0 +-- 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 @@ -24463,17 +24407,16 @@ function Ac3.crc(b: buffer, o: number, n: number): number return c end --- ------------------------------------------------------------------------------------------------ decoder type Options = { - drc: number?, -- dynamic range control: 0 = off (default, like ffmpeg -drc_scale 0), 1 = as the stream says - crc: boolean?, -- check crc2 (default true): a mismatch is Err.CHECKSUM + drc: number?, -- 0 = off (default, as ffmpeg -drc_scale 0), 1 = as the stream says + crc: boolean?, } type Decoder = { - pcm: { number }, -- the last frame: 1536 * channels interleaved floats, WAVE order + pcm: { number }, channels: number, sampleRate: number, - blocks: { number }, -- the bit offset of each audio block in the last frame (tools: stream editing, analysis) + blocks: { number }, decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), reset: (self: Decoder) -> (), } @@ -24529,12 +24472,9 @@ __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 --- (section 5.3 syntax, 7.1 exponents, 7.2 parametric bit allocation with delta bit allocation, 7.3 mantissas with --- grouping and dither, 7.4 coupling with phase flags, 7.5 rematrixing, 7.7.1 dynamic range, 7.9 the 512 / 2 x 256 --- inverse transforms with block switching) on codecs/audio/Mdct; no third-party code. The bit reader is module state --- over a frame the caller pads by PAD bytes; every section stops when the position passes the frame. No error / --- assert: failures return nil, "message". +-- 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") @@ -24550,7 +24490,6 @@ 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 --- 2^-e for the exponents 0 .. 24 local POW2 = table.create(32, 0) for e = 0, 31 do POW2[e + 1] = 2 ^ -e @@ -24571,7 +24510,6 @@ local WINDOW = Mdct.window("kbd", 512, 5) :: { number } local PLAN512 = Mdct.new(512) :: Mdct.Plan local PLAN256 = Mdct.new(256) :: Mdct.Plan --- ------------------------------------------------------------------------------------------------ bit reader local B: buffer = buffer.create(0) local P = 0 @@ -24589,17 +24527,14 @@ local P = 0 return v end --- ------------------------------------------------------------------------------------------------ state type State = { - -- the frame header fscod: number, acmod: number, lfeon: boolean, nfchans: number, - channels: number, -- output channels - map: { number }, -- output index of slots 1 .. 6 - drc: number, -- the dynamic range scale (0 = off) - -- per channel slot (1 .. 7) + channels: number, + map: { number }, + drc: number, exp: { { number } }, bap: { { number } }, coef: { { number } }, @@ -24614,19 +24549,17 @@ type State = { dbaOffst: { { number } }, dbaLen: { { number } }, dbaBa: { { number } }, - -- coupling cplinu: boolean, chincpl: { boolean }, phsflginu: boolean, cplbegf: number, cplendf: number, cplbndstrc: { boolean }, -- [sbnd + 1], sbnd = 0 .. 17 (absolute sub-band) - cplco: { { number } }, -- [ch][sbnd + 1] - phsflg: { boolean }, -- [sbnd + 1] + cplco: { { number } }, + phsflg: { boolean }, cplfleak: number, cplsleak: number, rematflg: { boolean }, - -- bit allocation parameters sdcycod: number, fdcycod: number, sgaincod: number, @@ -24634,15 +24567,14 @@ type State = { floorcod: number, csnroffst: number, dynrng: { number }, -- gain for Ch1 / Ch2 - seed: number, -- dither generator - -- scratch + seed: number, psd: { number }, bndpsd: { number }, excite: { number }, mask: { number }, y: { number }, pcm: { number }, - blocks: { number }, -- the bit offset of each audio block in the last frame (for tools) + blocks: { number }, } @native local function arrays(n: number, size: number, v: any): { any } @@ -24705,7 +24637,6 @@ end } end --- reset(st): forget the overlap (before a seek) @native function Decode.reset(st: State) for _, d in st.delay do for i = 1, 256 do @@ -24714,9 +24645,7 @@ end end end --- ------------------------------------------------------------------------------------------------ exponents --- read ngrps grouped exponents (7 bits = 3 deltas each) after absexp into e[first + 1 ..] (bins first ..), grpsize --- bins per delta; false when an exponent leaves 0 .. 24 +-- 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 @@ -24743,7 +24672,6 @@ end return true end --- ------------------------------------------------------------------------------------------------ bit allocation @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) @@ -24885,7 +24813,6 @@ end until stop <= lastbin end --- ------------------------------------------------------------------------------------------------ mantissas -- 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 @@ -24896,7 +24823,6 @@ local n1, n2, n4 = 0, 0, 0 return (s / 2147483648 - 1) * 0.707 end --- the mantissas of bins [start, stop) of slot ch into out[], scaled by their exponents (bap 0: dither when asked) @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 @@ -24954,7 +24880,6 @@ end end end --- ------------------------------------------------------------------------------------------------ audio block @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] @@ -24991,7 +24916,6 @@ local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D2 st.dynrng[i] = 1 end end - -- coupling strategy if bits(1) == 1 then st.cplinu = bits(1) == 1 if st.cplinu then @@ -25055,7 +24979,6 @@ local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D2 end end end - -- rematrixing 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 @@ -25068,7 +24991,6 @@ local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D2 end end end - -- exponent strategies local chexpstr = st.chexpstr chexpstr[CPL] = if cplinu then bits(2) else 0 for ch = 1, nf do @@ -25100,7 +25022,6 @@ local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D2 end end endmant[LFE] = 7 - -- exponents if cplinu and chexpstr[CPL] ~= 0 then local abs = bits(4) * 2 local grp = EXPGRP[chexpstr[CPL]] @@ -25138,7 +25059,6 @@ local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D2 if P > limit then return nil, "truncated block" end - -- bit allocation parameters 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 @@ -25163,7 +25083,6 @@ local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D2 st.cplfleak, st.cplsleak = bits(3), bits(3) end end - -- delta bit allocation if bits(1) == 1 then local modes = table.create(7, 0) if cplinu then @@ -25192,14 +25111,12 @@ local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D2 st.dbaOn[ch] = false end end - -- skip field if bits(1) == 1 then P += bits(9) * 8 end if P > limit then return nil, "truncated block" end - -- bit allocation local zero = st.csnroffst == 0 if zero then for ch = 1, nf do @@ -25230,7 +25147,6 @@ local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D2 if st.lfeon then alloc(LFE, 0, 7, true) end - -- mantissas n1, n2, n4 = 0, 0, 0 local gotCpl = false local coef = st.coef @@ -25302,13 +25218,11 @@ local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D2 return true, nil end --- ------------------------------------------------------------------------------------------------ transform --- the inverse transform of slot ch (long or two short), windowed, overlap-added into out[base + i * step] @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 -- 256 scratch + 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] @@ -25334,7 +25248,6 @@ end end end --- ------------------------------------------------------------------------------------------------ frame -- 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 }, @@ -25348,8 +25261,6 @@ local ORDER: { [number]: { number } } = { } local HAS_C = { [0] = false, true, false, true, false, true, false, true } --- frame(st, buf, len, drc) -> 1536 | nil, message: decodes the syncframe at buf[0 .. len) (padded by PAD bytes) --- into st.pcm (1536 * st.channels interleaved floats, WAVE order). drc: the dynamic range scale (0 = off, 1 = full). @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" @@ -25403,7 +25314,6 @@ local HAS_C = { [0] = false, true, false, true, false, true, false, true } local nf = NFCHANS[acmod] local channels = nf + (if lfeon then 1 else 0) if st.acmod ~= acmod or st.lfeon ~= lfeon then - -- a new channel layout: build the output map and forget the overlap 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 @@ -25445,11 +25355,8 @@ return Decode end __FILES["codecs/audio/Ac3/Tables"] = function() --- codecs/audio/Ac3/Tables: the AC-3 constant tables, transcribed from ATSC A/52:2018 (Digital Audio Compression --- Standard) section 7.2.3 (bit allocation: slowdec, fastdec, slowgain, dbpbtab, floortab, fastgain, bndtab / bndsz, --- latab, hth, baptab) and section 5.4 (frame sizes). masktab is derived from bndtab / bndsz, the transform window --- (Table 7.33) is the Kaiser-Bessel-derived window with alpha 5 (codecs/audio/Mdct), which Table 7.33 rounds to five --- decimals. No third-party code. +-- 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 } @@ -25459,7 +25366,7 @@ 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 } --- the 50 bit allocation bands: first bin and width (Table 7.12) +-- 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, @@ -25468,7 +25375,7 @@ 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[bin + 1]: the band of each bin (Table 7.13; bins 253 .. 255 map to 0) +-- 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 @@ -25496,7 +25403,7 @@ T.LATAB = { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, } --- hearing threshold per band (Table 7.15): HTH[fscod + 1][band + 1] +-- hearing threshold (Table 7.15): HTH[fscod + 1][band + 1] T.HTH = { { 0x04d0, 0x04d0, 0x0440, 0x0400, 0x03e0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0, @@ -25551,31 +25458,9 @@ __FILES["codecs/audio/Adpcm"] = @native function() --- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in rosetta; the IMA and --- MS block decoders moved here from audio/wav/Codecs (wav-luau, same author). ADX coefficients, PS-ADPCM and Nintendo --- DSP decoding follow vgmstream r2117 (ISC licence, licenses/vgmstream-LICENSE.txt) so the output is bit-exact with it: --- the ADX scale + 1 and the version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024 --- rounding. Codec kernels only: the formats (wav, aiff, caf, adx, vag, brstm, adpcm, ...) walk the layouts. --- --- Decoders write f32 (sample / 32768) to dst at float index d, every ds floats (interleaving), and keep their running --- state in a caller-owned buffer `st` at byte offset `so` (i32 pairs: IMA pred / step index, the others hist1 / hist2), --- so a decoder can stop between calls and snapshot the state for seeking (codecs/audio/Adpcm/Decoder). --- --- Adpcm.ima(src, p, q0, qs, count, hi, st, so, dst, d, ds) -- IMA nibbles: count samples, nibble q0, q0+qs, ... --- Adpcm.imaQt(src, p, st, so, dst, d, ds) -- Apple ima4: one 34-byte packet -> 64 samples --- Adpcm.imaWav(src, off, avail, ch, spb, dst, d) -> frames -- Microsoft IMA block (WAV / AVI) --- Adpcm.msBlock(src, off, avail, ch, spb, dst, d, coefs, ncoef, st) -> frames -- MS ADPCM block --- Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, st, so, dst, d, ds) -- CRI ADX: 18-byte frames, 32 samples --- Adpcm.adxCoefs(cutoff, rate) -> c1, c2 --- Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) -- Sony PS-ADPCM (VAG): 16-byte frames, 28 samples --- Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) -- Nintendo DSP: 8-byte frames, 14 samples --- Adpcm.modplug(src, p, count, dst, d) -- ModPlug ADPCM (XM / MOD samples) --- Adpcm.swfFrames(src, p, n, ch) -> frames -- Flash (SWF / FLV) ADPCM: one packet's length --- Adpcm.swf(src, p, n, ch, dst, d) -> frames -- Flash ADPCM: one packet of n bytes --- encoders: imaEncode, imaWavEncode, msEncode, adxEncode, psxEncode, dspEncode (see each) --- --- Every function reads only the bytes its arguments describe: the caller checks the ranges (byte counts per call are --- documented on each). Never throws. +-- 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 @@ -25583,7 +25468,6 @@ local floor = math.floor local Adpcm = {} --- ------------------------------------------------------------------------------------------------ IMA 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, @@ -25617,9 +25501,7 @@ for i = 0, 88 do end Adpcm.IMA_STEP = IMA_STEP --- ima: `count` samples of one channel from a nibble stream at byte p: nibble q0, q0 + qs, q0 + 2 qs, ... (nibble q is --- in byte p + q // 2, the low half first unless hi). State: st[so] predictor, st[so + 4] step index. Reads bytes --- p .. p + (q0 + (count - 1) * qs) // 2. +-- 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) @@ -25656,10 +25538,8 @@ Adpcm.IMA_STEP = IMA_STEP writei32(st, so + 4, index) end --- imaQt: one Apple ima4 packet (34 bytes at p: a big-endian header, the predictor's top 9 bits and the 7-bit step --- index, then 64 nibbles low first) -> 64 samples. Apple's decoders keep the running full-precision predictor while --- the header agrees with it (the same step index, the predictor within 127): st carries it from packet to packet --- (zeros before the first). +-- 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) @@ -25674,10 +25554,8 @@ end Adpcm.ima(src, p + 2, 0, 1, 64, false, st, so, dst, d, ds) end --- imaWav: one Microsoft IMA ADPCM block (WAV / AVI) at src[off]: per channel a 4-byte header (s16 predictor = the --- first sample, u8 step index, pad), then groups of 4 bytes (8 nibbles, low first) per channel in turn. avail: the --- bytes present (a truncated last block decodes the whole groups it has). Writes interleaved frames to dst from float --- index d; returns the frame count (<= spb). +-- 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 @@ -25720,15 +25598,12 @@ end return frames end --- ------------------------------------------------------------------------------------------------ MS ADPCM 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 } --- msBlock: one 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. coefs: i32 pairs (coef1, coef2) x --- ncoef (256 = 1.0). state: 20 * ch bytes of scratch. avail: the bytes present. Writes interleaved frames to dst from --- float index d; returns the frame count (<= spb). +-- 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 @@ -25783,15 +25658,14 @@ Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 } return frames end --- ------------------------------------------------------------------------------------------------ CRI ADX local F32 = buffer.create(4) @native local function f32(x: number): number writef32(F32, 0, x) return readf32(F32, 0) end --- adxCoefs(cutoff, rate) -> coef1, coef2 (fixed point, 12 fractional bits): the 2-pole high-pass predictor from the --- header's cutoff frequency, in single precision as CRI's decoders (and vgmstream) compute it +-- 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 @@ -25807,9 +25681,8 @@ end return c1, c2 end --- adx: nframes 18-byte frames of one channel (s16 big-endian scale, 32 nibbles high first), pstride bytes apart from --- p. v3: the version 3 rounding (each product shifted on its own). A scale of 0x8001 (CRI's end marker) decodes as --- silence. Reads p .. p + (nframes - 1) * pstride + 17; writes 32 * nframes samples. +-- 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) @@ -25852,7 +25725,6 @@ end writei32(st, so + 4, h2) end --- ------------------------------------------------------------------------------------------------ PS-ADPCM local PSX1 = { 0, 60, 115, 98, 122 } local PSX2 = { 0, 0, -52, -55, -60 } @@ -25867,9 +25739,8 @@ local PSX2 = { 0, 0, -52, -55, -60 } return if v >= 0 then floor(v) else -floor(-v) end --- psx: nframes 16-byte frames of one channel (filter << 4 | shift, flags, 28 nibbles low first), pstride bytes apart --- from p. Filters past 4 decode as 0 and shifts past 12 as 9 (as vgmstream); a frame with flags 7 is silence. The --- history keeps the unclipped value. Reads p .. p + (nframes - 1) * pstride + 15; writes 28 * nframes samples. +-- 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) @@ -25914,10 +25785,8 @@ end writei32(st, so + 4, h2) end --- ------------------------------------------------------------------------------------------------ Nintendo DSP --- dsp: count samples of one channel from 8-byte frames at p (predictor << 4 | scale shift, 14 nibbles high first). --- coefs: 16 i32 at byte co (8 pairs, 11 fractional bits); a predictor index past 7 uses pair 7. Reads p .. --- p + ceil(count / 14) * 8 - 1. +-- 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) @@ -25955,8 +25824,6 @@ end writei32(st, so + 4, h2) end --- ------------------------------------------------------------------------------------------------ encoders --- the nearest s16 to x * 32768 (NaN -> 0) @native local function toS16(x: number): number local v = floor(x * 32768 + 0.5) if v ~= v then @@ -25970,7 +25837,6 @@ end end Adpcm.toS16 = toS16 --- the IMA nibble for x from (pred, index): the one whose decoded value lands nearest (greedy, all 16 tried) @native local function imaNibble(x: number, pred: number, index: number): number local base = index * 8 + 1 local best, bestErr = 0, math.huge @@ -25990,9 +25856,6 @@ Adpcm.toS16 = toS16 return best end --- imaEncode: count samples of one channel, f32 at float index xi every xs floats of x, into nibbles q0, q0 + qs, ... --- of out at byte p (the other half of each byte is kept). State as Adpcm.ima. Writes bytes p .. --- p + (q0 + (count - 1) * qs) // 2. @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) @@ -26018,9 +25881,7 @@ end writei32(st, so + 4, index) end --- imaWavEncode: one Microsoft IMA block of spb frames (spb = 1 + 8k) from interleaved f32 x at frame xf (frames --- available: n; the rest is padded with the last sample) to out[off] (4 * ch + (spb - 1) / 2 * ch bytes). st: 8 * ch --- bytes carrying the step index from block to block. +-- 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 @@ -26054,8 +25915,6 @@ end end end --- one MS ADPCM channel run for the encoder: the nibbles for samples 2 .. n - 1 with predictor (c1, c2) and the first --- delta; returns the squared error and the nibbles in nibs (when given) @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 @@ -26078,9 +25937,7 @@ end return err end --- msEncode: one MS ADPCM block of spb frames (standard 7 coefficient pairs) from interleaved f32 x at frame xf --- (frames available: n; the rest is padded with silence) to out[off] (7 * ch + (spb - 2) * ch / 2 bytes). Each channel --- takes the predictor with the least error. +-- 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) @@ -26090,7 +25947,6 @@ end for i = 1, spb do xs[i] = if i <= n then toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) else 0 end - -- the first delta from the first steps local sum = 0 for i = 3, math.min(spb, 10) do sum += math.abs(xs[i] - xs[i - 1]) @@ -26118,8 +25974,6 @@ end end end --- one ADX frame for the encoder: the squared error of encoding xs[1..32] with scale from (h1, h2) (v4 rounding), and --- the nibbles in nibs when given; returns the error and the new history @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 @@ -26138,9 +25992,8 @@ end return err, h1, h2 end --- adxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 32) ADX frames +-- 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 --- past count is padded with silence. State as Adpcm.adx. @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) @@ -26157,7 +26010,6 @@ end b = a a = s end - -- the scale that covers the open-loop residual peak, and a few around it, closed loop 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 @@ -26180,9 +26032,6 @@ end writei32(st, so + 4, h2) end --- psxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 28) PS-ADPCM --- frames at out[p], pstride bytes apart, flags byte 0 (the caller sets loop / end flags); every filter and shift is --- tried per frame against Adpcm.psx's decoding, the least squared error wins. State as Adpcm.psx. @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) @@ -26217,7 +26066,6 @@ end end end end - -- the winner again, for its nibbles and history local fi, shift = rshift(bestHead, 4) + 1, band(bestHead, 15) local mul = 2 ^ (20 - shift) for k = 1, 28 do @@ -26238,10 +26086,8 @@ end writei32(st, so + 4, h2) end --- ------------------------------------------------------------------------------------------------ ModPlug --- modplug: ModPlug / OpenMPT ADPCM samples (XM / MOD sample data marked 0xAD): a table of 16 signed byte deltas at --- p, then count nibbles (low first) at p + 16, each adding its table delta to a running signed byte (wrapping). --- Writes count f32 (value / 128) to dst from float index d. Reads p .. p + 16 + ceil(count / 2) - 1. +-- 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 @@ -26256,7 +26102,6 @@ end end end --- ------------------------------------------------------------------------------------------------ Flash ADPCM -- 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 @@ -26269,7 +26114,6 @@ local SWF_INDEX: { { number } } = { { -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 }, } --- swfFrames: the frame count of one Flash ADPCM packet (n bytes at p, n >= 1) @native function Adpcm.swfFrames(src: buffer, p: number, n: number, ch: number): number if n < 1 or ch < 1 then return 0 @@ -26287,7 +26131,6 @@ local SWF_INDEX: { { number } } = { return frames end --- the k-bit (k <= 16) MSB-first value at bit position pos of src[p ..]; bytes at or past e read as 0 @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 @@ -26300,8 +26143,6 @@ end return band(rshift(v, 24 - band(pos, 7) - k), lshift(1, k) - 1) end --- swf: one Flash ADPCM packet (n bytes at p, ch channels) -> interleaved f32 frames to dst from float index d; returns --- the frame count (Adpcm.swfFrames). Reads p .. p + n - 1 only. @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 @@ -26369,28 +26210,8 @@ return Adpcm end __FILES["codecs/audio/Adpcm/Decoder"] = function() --- codecs/audio/Adpcm/Decoder: the streaming Decoder (Types.Decoder) over an ADPCM stream cut into packets, for the --- formats whose state carries from packet to packet (ADX, VAG, BRSTM, raw IMA): codecs/audio/Stream.packets plus --- exact seeking. The codec state (one buffer the packet decoder advances) is snapshotted at every packet start it --- passes; a seek restores the snapshot, else the format's own state for that packet (BRSTM's ADPC history), else --- decodes forward from the nearest earlier snapshot. New in rosetta. --- --- local dec, err = Decoder.packets(dec, { -- dec: the Decoder table (sampleRate, channels, frames, ...) --- count = n, packetFrames = 4096, -- packets of packetFrames frames (the last may be shorter) --- frames = total, -- output frames --- state = st, -- the codec state buffer decode advances --- decode = function(i, out) return frames end, -- packet i (1-based) as interleaved f32 into out from 0 --- restore = function(i) return false end, -- optional: set st for packet i, true if it could --- }) --- --- The layouts the formats share, each returning the Decoder (dec gets read / seek / position) | nil, Err: --- Decoder.interleaved(dec, spec) psx / adx / dsp frames (or s16 / s8 PCM), channels interleaved every --- spec.interleave bytes (VAG, ADX, BRSTM / BCSTM / BFSTM, raw PS-ADPCM) --- Decoder.nibbles(dec, spec) an IMA nibble stream, channels interleaved by nibble (raw IMA, KVAG) --- Decoder.blocks(dec, spec) self-contained blocks: "ms" / "ima_wav" (blockAlign bytes), "ima_qt" (34 bytes --- per channel), raw or inside AIFF-C / CAF --- --- Never throws (decode failures end the stream and land in dec.error, see codecs/audio/Stream). +-- 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") @@ -26428,7 +26249,6 @@ function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?) if snaps[i] then buffer.copy(st, 0, snaps[i]) elseif restore and restore(i) then - -- the format set the state (BRSTM's seek table) else local j = i - 1 while j > 1 and not snaps[j] do @@ -26465,11 +26285,9 @@ function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?) }) end --- ------------------------------------------------------------------------------------------------ layouts 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 --- PCM samples of one channel into every ds-th float of dst from float d 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 @@ -26488,22 +26306,21 @@ local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer, end type InterleavedSpec = { - kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", -- ADPCM frames, or PCM samples laid out the same way + kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", buf: buffer, - offset: number, -- the first row - size: number, -- data bytes (rows past it are cut; a truncated file decodes its whole frames) - interleave: number, -- bytes per channel per row (a multiple of the frame size; mono: any multiple) + offset: number, + size: number, + interleave: number, lastInterleave: number?, -- bytes per channel in the last row (BRSTM's padded last block), default interleave - frames: number?, -- frames to output (default: what the data holds) - c1: number?, -- adx: the predictor (Adpcm.adxCoefs) + frames: number?, + c1: number?, c2: number?, - v3: boolean?, -- adx: version 3 rounding + v3: boolean?, coefs: buffer?, -- dsp: 16 i32 per channel - hist: { number }?, -- initial history, h1 / h2 per channel (default 0) + hist: { number }?, restore: ((row: number, st: buffer) -> boolean)?, -- the exact history at the start of a row (BRSTM ADPC) } --- interleaved(dec, spec) -> Decoder | nil, Err function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?) local ch = dec.channels local kind = spec.kind @@ -26515,9 +26332,8 @@ function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?) end local buf, base, size = spec.buf, spec.offset, spec.size local rowBytes = il * ch - -- rows: the full ones, then the last (which may be shorter, and may be cut by a truncated file) local rows = math.max(1, math.ceil(size / rowBytes)) - local function rowFrames(r: number): number -- the frames row r (0-based) holds whole in every channel + 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) @@ -26581,12 +26397,12 @@ end type NibbleSpec = { buf: buffer, offset: number, - size: number, -- bytes + size: number, hi: boolean?, -- the high nibble first (DVI / KVAG); default low first - frames: number?, -- default: every whole frame of nibbles + frames: number?, } --- nibbles(dec, spec): an IMA stream starting from predictor 0, step index 0, channel c in nibbles c, c + ch, ... +-- 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 @@ -26616,12 +26432,11 @@ type BlockSpec = { buf: buffer, offset: number, size: number, - blockAlign: number?, -- ms / ima_wav: bytes per block - frames: number?, -- default: what the blocks hold + blockAlign: number?, + frames: number?, coefs: { number }?, -- ms: coefficient pairs, flat (default the 7 standard pairs) } --- blockFrames(kind, blockAlign, ch) -> frames per block, or nil when the block cannot hold the headers function Decoder.blockFrames(kind: string, ba: number, ch: number): number? if kind == "ima_qt" then return 64 @@ -26631,7 +26446,6 @@ function Decoder.blockFrames(kind: string, ba: number, ch: number): number? return if ba >= 4 * ch then (ba - 4 * ch) * 2 // ch + 1 else nil end --- blocks(dec, spec): self-contained ADPCM blocks (no state across blocks); a truncated last block decodes what it has function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?) local ch = dec.channels local kind = spec.kind @@ -26648,7 +26462,6 @@ function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?) local rest = size - full * ba local total = full * spb if kind ~= "ima_qt" and rest > 0 then - -- a partial last block: the frames it holds whole 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 @@ -26699,20 +26512,9 @@ return Decoder end __FILES["codecs/audio/Alac"] = function() --- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). --- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice --- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 / --- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels). --- --- local Alac = require("@rosetta/codecs/audio/Alac") --- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped) --- local dec = Alac.decoder(cfg) --- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order) --- local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }) --- local packet = enc:encode(samples, first, frames) -- interleaved integers -> one packet (frames <= 4096) --- local cookie = Alac.cookie(enc.config) -- after encoding: maxFrameBytes / avgBitRate filled --- --- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG. +-- 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") @@ -26721,20 +26523,19 @@ local Encode = __include("codecs/audio/Alac/Encode") local Alac = {} type Config = { - frameLength: number, -- samples per packet (4096) + frameLength: number, compatibleVersion: number, bitDepth: number, - pb: number, -- 40 - mb: number, -- 10 - kb: number, -- 14 + pb: number, + mb: number, + kb: number, channels: number, - maxRun: number, -- 255 + maxRun: number, maxFrameBytes: number, avgBitRate: number, sampleRate: number, } --- ALAC channel k (1-based) -> WAV channel (1-based), per channel count local TO_WAV: { { number } } = { { 1 }, { 1, 2 }, @@ -26745,7 +26546,6 @@ local TO_WAV: { { number } } = { { 3, 1, 2, 5, 6, 7, 4 }, { 3, 7, 8, 1, 2, 5, 6, 4 }, } --- the element layout (channels per element) the encoder writes local ELEMENTS: { { number } } = { { 1 }, { 2 }, @@ -26758,7 +26558,6 @@ local ELEMENTS: { { number } } = { } Alac.TO_WAV = TO_WAV --- config(buf, offset?, length?) -> Config | nil, Err 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 @@ -26804,7 +26603,6 @@ function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, E return c, nil end --- cookie(cfg) -> the 24-byte ALACSpecificConfig function Alac.cookie(c: Config): buffer local w = Bytes.writer(24) w:u32be(c.frameLength) @@ -26821,10 +26619,9 @@ function Alac.cookie(c: Config): buffer return w:finish() end --- ------------------------------------------------------------------------------------------------ decoder type Decoder = { config: Config, - pcm: { number }, -- the last packet's samples, interleaved, WAV order (integers of config.bitDepth bits) + pcm: { number }, decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), state: Decode.State, } @@ -26857,7 +26654,6 @@ local function decode(self: Decoder, buf: buffer, offset: number?, length: numbe return frames, nil end --- decoder(cfg) -> Decoder function Alac.decoder(cfg: Config): Decoder return { config = cfg, @@ -26867,7 +26663,6 @@ function Alac.decoder(cfg: Config): Decoder } end --- ------------------------------------------------------------------------------------------------ encoder type Encoder = { config: Config, encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?), @@ -26900,12 +26695,11 @@ end type EncoderOptions = { sampleRate: number, - channels: number, -- 1 .. 8 - bitDepth: number?, -- 16 (default), 20 or 24 - frameLength: number?, -- default 4096 + channels: number, + bitDepth: number?, + frameLength: number?, } --- encoder(opts) -> Encoder | nil, Err function Alac.encoder(opts: EncoderOptions): (Encoder?, Err.Err?) if type(opts) ~= "table" then return nil, Err.new(Err.ARG, "encoder: expected options") @@ -26954,10 +26748,8 @@ __FILES["codecs/audio/Alac/Decode"] = @native function() --- codecs/audio/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice --- residuals with zero runs, the adaptive FIR predictor (orders 0, 31 and 1 .. 30), stereo unmixing, shifted low bytes, --- uncompressed (escape) frames, 16 / 20 / 24 / 32-bit samples. Written from the ALAC format as published by Apple --- (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). Never throws: returns nil, message. +-- 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 @@ -26973,10 +26765,10 @@ type State = { channels: number, maxRun: number, scratch: buffer, -- the packet + 16 zero bytes (reads past the end are safe; the overrun is checked) - pred: { { number } }, -- per element channel (0, 1): residuals / predictor output + pred: { { number } }, mix: { { number } }, shift: { number }, - out: { number }, -- interleaved output samples (integers), frames * channels + out: { number }, } local POW = table.create(64, 0) @@ -26984,7 +26776,6 @@ for i = 0, 63 do POW[i + 1] = 2 ^ i end --- bit reader over st.scratch: pos = bit position. bits(n) for n <= 25. @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) @@ -27025,7 +26816,6 @@ end return x, pos + k - 1 end --- residuals: n values into out[1..n]; returns the new bit position or -1 @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 @@ -27079,7 +26869,6 @@ end return pos end --- the adaptive FIR predictor: err[1..n] -> out[1..n] (may be the same array); coefs adapt in place @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 @@ -27133,8 +26922,6 @@ end end end --- decode(st, buf, off, len) -> frames | nil, message. Samples land interleaved in st.out (integers), channels in the --- ALAC element order. @native function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) if len <= 0 then return nil, "empty packet" @@ -27149,7 +26936,7 @@ end local limit = len * 8 local pos = 0 local channels = st.channels - local ch = 0 -- next output channel + local ch = 0 local frames = -1 local out = st.out while true do @@ -27284,7 +27071,6 @@ end end shift = 0 end - -- unmix + shifted bytes -> interleaved output local sm = POW[shift + 1] if nch == 2 then local den = POW[mixBits + 1] @@ -27347,7 +27133,6 @@ end return 0, nil end if ch < channels then - -- missing channels: silence for i = 1, frames do for c = ch + 1, channels do out[(i - 1) * channels + c] = 0 @@ -27357,7 +27142,6 @@ end return frames, nil end --- the scratch state for a configuration @native function Decode.state(cfg: any): State local n = cfg.frameLength return { @@ -27383,11 +27167,8 @@ __FILES["codecs/audio/Alac/Encode"] = @native function() --- codecs/audio/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of --- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation, --- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the --- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit --- input. Written for this library from the ALAC format; no third-party code. Never throws. +-- 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 @@ -27409,16 +27190,15 @@ type State = { mb: number, kb: number, channels: number, - out: buffer, -- packet scratch - pos: number, -- bit position in out - cap: number, -- bits available + out: buffer, + pos: number, + cap: number, u: { number }, v: { number }, err: { number }, work: { number }, } --- ------------------------------------------------------------------------------------------------ bit writer @native local function put(st: State, v: number, n: number) local pos = st.pos if pos + n > st.cap then @@ -27448,7 +27228,6 @@ end end end --- ------------------------------------------------------------------------------------------------ rice code @native local function signExtend(v: number, bits: number): number local m = POW[bits + 1] v = v % m @@ -27458,7 +27237,6 @@ end return v end --- the bits of one scalar (no writing) @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 @@ -27478,7 +27256,6 @@ end putBig(st, x, bps) return end - -- pre ones and a zero put(st, POW[pre + 2] - 2, pre + 1) if k ~= 1 then local r = x - pre * m @@ -27490,7 +27267,6 @@ end end end --- code the residuals e[1..n] (write = false: just count the bits) @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 @@ -27544,7 +27320,6 @@ end return bits end --- ------------------------------------------------------------------------------------------------ prediction -- 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] @@ -27583,7 +27358,6 @@ end end end --- LPC coefficients of x[1..n] for the given order (Levinson-Durbin on a Welch-windowed autocorrelation), quantised @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 @@ -27630,7 +27404,6 @@ end return coefs end --- choose order / coefficients for one channel: returns order, coefs (as transmitted), bits @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 @@ -27656,9 +27429,6 @@ end return bestOrder, bestCoefs, bestBits end --- ------------------------------------------------------------------------------------------------ frame --- frame(st, samples, first, frames, map) -> buffer: samples interleaved (integers, WAV channel order) from index --- `first`; map[k] = the input channel (1-based) of ALAC channel k; elements: list of 1 / 2 channel counts @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 @@ -27681,7 +27451,6 @@ end local bps = depth + nch - 1 local mixRes = 0 if nch == 2 then - -- the mix with the smallest first-difference energy local best = math.huge for res = 0, 4 do local cost = 0 @@ -27716,7 +27485,6 @@ end u[i] = samples[first + (i - 1) * channels + a - 1] end end - -- header put(st, if nch == 2 then 1 else 0, 3) put(st, 0, 4) put(st, 0, 12) @@ -27758,7 +27526,6 @@ end end end if not compressed then - -- uncompressed frame buffer.fill(st.out, 0, 0) st.pos = 0 ch = 1 @@ -27810,21 +27577,9 @@ return Encode end __FILES["codecs/audio/Ape"] = function() --- codecs/audio/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28 --- (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt): APEHeader.cpp (the descriptor / --- header / seek table, and the pre-3.98 header), APEInfo / APEDecompress.cpp (frame bytes and alignment); the frame --- decoder is codecs/audio/Ape/Decode. Supports file versions 3.95 and later (3.99+ as the current encoder writes; the --- 3.95 - 3.98 range coder model is ported but has no reference fixture), every compression level (fast, normal, high, --- extra high, insane), 8 / 16 / 24 / 32-bit integer and 32-bit float, 1 - 32 channels, special frames (silence, --- pseudo stereo) and the frame CRC. Not supported: versions before 3.95 (UNSUPPORTED), the "interim" 24-bit --- re-decode for files of the 32-bit era before 8.50, big-endian / signed 8-bit source flags (the samples are returned --- as numbers either way). --- --- local info, err = Ape.info(buf, base, limit) -- header facts + the frame table --- local dec = Ape.decoder(info) --- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved; integers, or floats) --- --- Never throws: bad data returns nil, Err. +-- 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") @@ -27833,7 +27588,7 @@ local Ape = {} type Info = { version: number, -- file version * 1000 (3990) - programVersion: number, -- 13280 (0 when not stored) + programVersion: number, level: number, -- 1000 (fast) .. 5000 (insane) flags: number, channels: number, @@ -27844,16 +27599,15 @@ type Info = { finalFrameBlocks: number, totalFrames: number, totalBlocks: number, - frameStart: { number }, -- byte offset of each frame + frameStart: { number }, firstFrame: number, -- byte offset of frame 1 (the word alignment origin) - dataEnd: number, -- the end of the frame data - limit: number, -- the end of the file data (frames past it are truncated) + 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 --- find(buf, base, limit) -> the offset of "MAC " / "MACF" (after an ID3v2 tag) | nil 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 @@ -27881,7 +27635,6 @@ function Ape.find(buf: buffer, base: number, limit: number): number? return if k then at + k - 1 else nil end --- info(buf, base, limit) -> Info | nil, Err function Ape.info(buf: buffer, base: number, limit: number): (Info?, Err.Err?) local at = Ape.find(buf, base, limit) if not at then @@ -27995,7 +27748,6 @@ function Ape.info(buf: buffer, base: number, limit: number): (Info?, Err.Err?) return info :: Info, nil end --- ------------------------------------------------------------------------------------------------ decoder type Decoder = { info: Info, pcm: { number }, @@ -28023,7 +27775,6 @@ local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) return n2, nil end --- decoder(info) -> Decoder | nil, Err 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 @@ -28043,12 +27794,9 @@ __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 (the range coder and its value model, --- 3.99+) and Old/UnBitArrayOld.cpp (CUnBitArray3891To3989, the 3.95 - 3.98 model), NNFilter / NNFilterCommon.h (the --- neural-net filters of the normal .. insane levels), NewPredictor.cpp (CPredictorDecompress3950toCurrent, its int32 --- and int64 flavours), ScaledFirstOrderFilter.h, Prepare.cpp (Unprepare: X / Y -> channels), APEDecompressCore.cpp --- (special frames, the frame CRC) and FloatTransform.cpp. Never throws: returns nil, message. +-- 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 @@ -28104,8 +27852,8 @@ type State = { bits: number, channels: number, filters: { Filter }, -- per level, applied last to first on decode (as m_spNNFilter2, 1, 0) - V: { { number } }, -- per channel: the frame's values through the stages - S: buffer, -- the frame bytes, word-swapped (+ PAD zeros) + V: { { number } }, + S: buffer, crcbuf: buffer, scratch: buffer, lastX: number, @@ -28120,7 +27868,6 @@ local FILTERS: { [number]: { number } } = { -- level -> { order, shift, ... } in [5000] = { 1280, 15, 256, 13, 16, 11 }, } --- state(version, level, bits, channels) -> State | nil, message @native function Decode.state(version: number, level: number, bits: number, channels: number): (State?, string?) local spec = FILTERS[level] if not spec then @@ -28156,7 +27903,6 @@ local FILTERS: { [number]: { number } } = { -- level -> { order, shift, ... } in }, nil end --- ------------------------------------------------------------------------------------------------ entropy -- 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 @@ -28178,8 +27924,6 @@ type Rc = { q: number, low: number, range: number, prev: number } return r end --- values(st, q, n, order, old) -> q | nil, message: n blocks of range-coded values into st.V[c] for the channels of --- `order` (decode order), from byte q of st.S (the range coder starts there) @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 @@ -28340,13 +28084,11 @@ end return q, nil end --- ------------------------------------------------------------------------------------------------ NN filters -- ((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 --- the int16 dot product of the weights and the inputs from byte b (span bytes) @native local function dot16(M: buffer, I: buffer, b: number, span: number): number local dot = 0 for k = 0, span - 16, 16 do @@ -28374,8 +28116,7 @@ end return dot end --- one CNNFilter over n values of v, in place (DecompressGeneric). The weights, inputs and deltas live in buffers of --- the C types (int16 for 8 - 24-bit files, int32 for 32-bit ones: `wide`), so the weights wrap as the C shorts do +-- 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 @@ -28384,7 +28125,7 @@ end 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 -- the current element (0-based); its history is p - order .. p - 1 + local p = order local total = 512 + order local avg = 0 local span = order * 2 @@ -28463,7 +28204,6 @@ end end end --- ------------------------------------------------------------------------------------------------ predictor -- 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 @@ -28472,8 +28212,7 @@ end return if (v // 1073741824) % 4 >= 2 then 1 else -1 end --- predict(st, a, b?, n) : CPredictorDecompress3950toCurrent over channel a's values (nB = channel b's outputs of the --- block, or 0), single-channel form; stereo uses predictStereo +-- 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 @@ -28531,7 +28270,6 @@ end local xStage = 0 local lastX = 0 for t = 1, n do - -- Y local nA = Y[t] local A0 = yLast yA3 = yA2 @@ -28581,7 +28319,6 @@ end yStage = wrap32(cur + (yStage * 31) // 32) yLast = cur local yv = yStage - -- X nA = X[t] A0 = xLast xA3 = xA2 @@ -28634,10 +28371,6 @@ end end end --- ------------------------------------------------------------------------------------------------ frame --- frame(st, buf, at, rem, stop, n, P, float) -> n | nil, message: the frame whose words start at byte `at` (its first --- byte at at + rem), reading at most up to `stop`; n blocks into P (interleaved integers, or floats when float); cut: --- the data ends at `stop` before the frame does (a running-over decode is then "truncated", else corrupt) @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) @@ -28678,10 +28411,9 @@ end end stored %= TWO31 end - -- the values local V = st.V local order: { number } - local mode -- "silence", "pseudo", "stereo", "mono", "multi" + local mode if C == 1 then if band(special, 1) ~= 0 then mode = "silence" @@ -28736,7 +28468,7 @@ end cb = buffer.create(n * C * bps + 1024) st.crcbuf = cb end - local paired: { [number]: boolean } = {} -- first channel (0-based) of an X / Y pair + local paired: { [number]: boolean } = {} if C == 2 and mode == "stereo" then paired[0] = true elseif C == 4 and (bits == 16 or bits == 24) then @@ -28821,19 +28553,9 @@ return Decode end __FILES["codecs/audio/ApeTag"] = function() --- codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and --- some MP3s) -> Types.Tags. Written from the APEv2 specification (wiki.hydrogenaud.io "APEv2 specification"); no --- third-party code. A tag sits at the end of the file (before an optional ID3v1 tag) as items + a 32-byte footer --- "APETAGEX", with an optional 32-byte header in front (APEv2). Item keys become lower case tag keys (Year -> date, --- Track -> track, Album Artist -> albumartist, Disc -> disc, Comment -> comment); text values holding several --- values (NUL separated) are joined with "; "; binary items (cover art) and external links stay in info.items. --- Never throws. --- --- local tags, info = ApeTag.find(buf, start, limit) -- the tag ending at limit (or before an ID3v1 tag there) --- -- tags: { title = ..., artist = ... } | nil (no tag / malformed) --- -- info: { start = first byte (the header when present), stop = past the footer, version = 1000 | 2000, --- -- items = { { key = "Title", value = "...", kind = "text" | "binary" | "link" } } } --- local tags, info = ApeTag.parse(buf, footer, start) -- the tag whose footer is at byte `footer` (>= start) +-- 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 } @@ -28849,14 +28571,11 @@ local TO_TAG: { [string]: string } = { } local KINDS = { [0] = "text", "binary", "link", "text" } --- tagKey(itemKey) -> the Types.Tags key function ApeTag.tagKey(key: string): string local k = string.lower(key) return TO_TAG[k] or k end --- parse(buf, footer, start?) -> tags, info | nil: the tag whose 32-byte footer starts at byte `footer`; the items --- must lie at or after `start` (default 0) function ApeTag.parse(buf: buffer, footer: number, start: number?): ({ [string]: string }?, Info?) local lo = start or 0 local n = buffer.len(buf) @@ -28911,8 +28630,6 @@ function ApeTag.parse(buf: buffer, footer: number, start: number?): ({ [string]: return tags, { start = first, stop = footer + 32, version = version, items = items } end --- find(buf, start, limit) -> tags, info | nil: the tag at the end of [start, limit), or just before a 128-byte --- ID3v1 tag ("TAG") there function ApeTag.find(buf: buffer, start: number, limit: number): ({ [string]: string }?, Info?) if limit > buffer.len(buf) then limit = buffer.len(buf) @@ -28933,10 +28650,8 @@ return ApeTag end __FILES["codecs/audio/Flac"] = function() --- codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim, --- fixed, LPC, Rice residuals, stereo decorrelation) with CRC-8 / CRC-16 (Frame), and the frame encoder (Encode). --- Absorbed from flac-luau 7083d0d (same author); the encoder is new. Native FLAC / Ogg FLAC streams, metadata and --- seeking are audio/flac. +-- 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"), @@ -28948,15 +28663,8 @@ __FILES["codecs/audio/Flac/Encode"] = @native function() --- codecs/audio/Flac/Encode: the FLAC encoder (RFC 9639). New code, written from the RFC; the presets mirror libFLAC's -0 .. -8 --- (block size 1152 / 4096, max LPC order 0 / 6 / 8 / 12, Rice partition order 3 .. 6, independent / adaptive / --- exhaustive stereo decorrelation). Subframes: CONSTANT, VERBATIM, FIXED (order 0..4, chosen by the residual sum), --- LPC (Levinson-Durbin on the tukey(0.5)-windowed autocorrelation, error-feedback coefficient quantization with --- libFLAC's precision table, the order estimated from the prediction error or searched exhaustively at -8), wasted --- bits; Rice / Rice2 partitions with the partition order and parameters searched per subframe. Frames carry CRC-8 / --- CRC-16; STREAMINFO carries the sizes, total samples and the MD5 of the PCM; VORBIS_COMMENT from the tags; an optional --- SEEKTABLE. Streams: input blocks are pulled from a codecs/audio/Pcm Source, so a Decoder is encoded without decoding it --- whole. Never throws: bad options are rejected by audio/flac before calling in. +-- 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") @@ -28972,8 +28680,6 @@ for i = 0, 63 do POW[i + 1] = 2 ^ i end --- ------------------------------------------------------------------------------------------------ CRCs --- (the decoder's tables: codecs/audio/Flac/Frame; (b, offset, count) here) @native local function crc8(b: buffer, o: number, n: number): number return Frame.crc8(b, o, o + n) end @@ -28982,7 +28688,6 @@ end end Encode.crc8, Encode.crc16 = crc8, crc16 --- ------------------------------------------------------------------------------------------------ bit writer (MSB first) type W = Bits.RawWriter @native local function ensure(w: W, n: number) @@ -29021,12 +28726,11 @@ end end end --- ------------------------------------------------------------------------------------------------ presets type Config = { blockSize: number, maxLpcOrder: number, maxPartitionOrder: number, - stereo: string, -- "independent" | "adaptive" | "exhaustive" + stereo: string, exhaustiveOrder: boolean, } local PRESETS: { Config } = { @@ -29042,22 +28746,20 @@ local PRESETS: { Config } = { } Encode.PRESETS = PRESETS --- ------------------------------------------------------------------------------------------------ analysis --- a subframe plan for one channel signal type Plan = { - kind: number, -- 0 constant, 1 verbatim, 2 fixed, 3 lpc - bits: number, -- estimated size in bits (with the subframe header) + kind: number, + bits: number, order: number, wasted: number, - bps: number, -- sample size after removing wasted bits - res: { number }, -- residual (fixed / lpc), indices 1..n + 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 }, -- the (shifted) samples + x: { number }, } @native local function newPlan(n: number): Plan @@ -29078,7 +28780,6 @@ type Plan = { } end --- scratch per encoder type Scratch = { sums: { number }, counts: { number }, @@ -29094,9 +28795,7 @@ type Scratch = { qlp: { number }, } --- rice(res, n, order, maxP, plan?) -> bits, porder, method (fills scratch.bestKs with the parameters) @native local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP: number): (number, number, number) - -- the finest usable partition order local p = maxP while p > 0 and (n % POW[p + 1] ~= 0 or n // POW[p + 1] <= order) do p -= 1 @@ -29104,7 +28803,6 @@ type Scratch = { local sums, counts = sc.sums, sc.counts local parts = POW[p + 1] local ps = n // parts - -- sums of zig-zag values at the finest order for j = 0, parts - 1 do local s = 0 local a = if j == 0 then order + 1 else j * ps + 1 @@ -29153,7 +28851,6 @@ type Scratch = { if q == 0 then break end - -- merge pairs into the next coarser order for j = 1, np // 2 do sums[j] = sums[2 * j - 1] + sums[2 * j] counts[j] = counts[2 * j - 1] + counts[2 * j] @@ -29171,7 +28868,6 @@ end end end --- fixed predictor residuals @native local function fixedResidual(x: { number }, n: number, order: number, res: { number }) for i = 1, order do res[i] = 0 @@ -29257,7 +28953,6 @@ Encode.bestFixedOrder = bestFixedOrder return 13 end --- quantize coefficients lp[1..order] to precision bits: qlp[1..order], shift | nil @native local function quantize(lp: { number }, order: number, precision: number, qlp: { number }): number? local cmax = 0 for i = 1, order do @@ -29319,7 +29014,6 @@ end end end --- Levinson-Durbin: sc.lpc[o][1..o] and sc.err[o] for o = 1 .. maxOrder; returns the highest usable order @native local function levinson(sc: Scratch, maxOrder: number): number local r = sc.autoc local e = r[1] @@ -29354,10 +29048,8 @@ end return maxOrder end --- choose the subframe for signal x (n samples, bps bits) into plan (reusing its arrays) @native local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps: number, plan: Plan) local x = plan.x - -- constant? local first = src[1] local constant = true for i = 1, n do @@ -29371,7 +29063,6 @@ end plan.res[1] = first return end - -- wasted bits: the common trailing zeros local wasted = 0 do local w = 0 @@ -29398,9 +29089,7 @@ end local b = bps - wasted local hdr = 8 + wasted plan.wasted, plan.bps = wasted, b - -- verbatim plan.kind, plan.bits = 1, hdr + n * b - -- fixed local fo = bestFixedOrder(x, n) if n > fo then local tmp = sc.tmpRes @@ -29413,10 +29102,8 @@ end keepRice(sc, plan, po, me) end end - -- lpc local maxOrder = math.min(cfg.maxLpcOrder, n - 1, 32) if maxOrder > 0 then - -- windowed autocorrelation local win = sc.win if sc.winN ~= n then -- tukey(0.5) @@ -29489,7 +29176,6 @@ end end end --- ------------------------------------------------------------------------------------------------ writing @native local function writeResidual(w: W, plan: Plan, n: number) local method = plan.method put(w, method, 2) @@ -29596,7 +29282,6 @@ local SIZE_CODES: { [number]: number } = { [8] = 1, [12] = 2, [16] = 4, [20] = 5 return 7, 16 end --- ------------------------------------------------------------------------------------------------ encoder type Source = { sampleRate: number, channels: number, @@ -29609,18 +29294,16 @@ type Options = { level: number, bits: number, blockSize: number?, - seekInterval: number, -- seconds between seek points (0 = no SEEKTABLE) - padding: number, -- bytes of PADDING + seekInterval: number, + padding: number, vendor: string, } --- encode(src, opts) -> buffer | nil, message @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 } - -- metadata put(w, 0x664C6143, 32) -- "fLaC" put(w, 0, 1) put(w, 0, 7) @@ -29629,7 +29312,6 @@ type Options = { for _ = 1, 34 do put(w, 0, 8) end - -- seek table placeholders (when the length is known) local seekPoints = 0 local seekAt = 0 local interval = floor(opts.seekInterval * rate) @@ -29639,14 +29321,12 @@ type Options = { seekPoints = 0 end end - -- vorbis comment local comments = VorbisComment.fields(src.tags) local vendor = opts.vendor local vcLen = 4 + #vendor + 4 for _, c in comments do vcLen += 4 + #c end - -- SEEKTABLE if seekPoints > 0 then put(w, 0, 1) put(w, 3, 7) @@ -29694,7 +29374,6 @@ type Options = { end end local audioStart = w.pos - -- frames local md5 = Md5.new() local mbytes = (bps + 7) // 8 local mbuf = buffer.create(bs * ch * mbytes) @@ -29741,7 +29420,6 @@ type Options = { local tmp: buffer? = nil local pendingBuf: buffer? = nil local pendingN, pendingOff = 0, 0 - -- read exactly bs frames (fewer only at the end) @native local function readBlock(): (buffer?, number) local out = buffer.create(bs * ch * 4) local got = 0 @@ -29788,7 +29466,6 @@ type Options = { end end md5:update(mbuf, 0, mo) - -- channel decorrelation local assign = ch - 1 local chosen: { Plan } = {} if ch == 2 and cfg.stereo ~= "independent" then @@ -29847,14 +29524,12 @@ type Options = { chosen[c] = plans[4 + c] end end - -- the frame local need = n * ch * 4 + 64 for _, p in chosen do need += (p.bits // 8) + 8 end ensure(w, need) local start = w.pos - -- seek points: the first frame at or after each multiple of the interval while seekIdx < seekPoints and total >= seekNext do local at = seekAt + seekIdx * 18 local sn, off = total, start - audioStart @@ -29904,7 +29579,6 @@ type Options = { if src.err then return nil, tostring(src.err) end - -- unused seek points stay placeholders; STREAMINFO 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()) @@ -29912,7 +29586,7 @@ type Options = { return out, nil end --- streaminfo(...) -> the 34-byte STREAMINFO body +-- 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) @@ -29938,13 +29612,9 @@ __FILES["codecs/audio/Flac/Frame"] = @native function() --- codecs/audio/Flac/Frame: FLAC frames: header parsing (CRC-8), the sync search, subframes (constant, verbatim, fixed, LPC, wasted bits), --- residuals (Rice / Rice2 partitions, escapes), stereo decorrelation and the CRC-16 check. --- --- The input buffer must have at least PAD zero bytes after the data end (`len`): the bit reader reads 32-bit --- words without bounds checks and instead compares its position with the data end once per sample. Nothing here --- throws: bad data gives nil, err. --- Absorbed from flac-luau 7083d0d (same author, no third-party code). +-- 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 @@ -29999,7 +29669,7 @@ local RATE = { [1] = 88200, [2] = 176400, [3] = 192000, [4] = 8000, [5] = 16000, local BITS = { [1] = 8, [2] = 12, [4] = 16, [5] = 20, [6] = 24, [7] = 32 } type Header = { - offset: number, -- byte offset of the sync code + offset: number, size: number, -- header bytes, CRC-8 included blockSize: number, sampleRate: number, @@ -30010,8 +29680,6 @@ type Header = { number: number, } --- Parse the frame header at pos (data ends at len; the buffer is padded). si gives the STREAMINFO defaults --- (sampleRate, bitsPerSample) for the "from STREAMINFO" codes. Returns nil when it is not a valid header. @native function Frame.header(b: buffer, pos: number, len: number, si: any): Header? if pos < 0 or pos + 6 > len then return nil @@ -30092,7 +29760,6 @@ type Header = { if not bs or not bps or bps < 4 or bps > 32 or p + 1 > len then return nil end - -- CRC-8 over the header if crc8(b, pos, p) ~= readu8(b, p) then return nil end @@ -30109,7 +29776,6 @@ type Header = { } end --- The first valid header at an offset in [pos, limit) @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 @@ -30130,7 +29796,6 @@ end return nil end --- Bit reading for the header parts of subframes: n <= 32 bits at bit position p (unsigned) @native local function bits(b: buffer, p: number, n: number): number if n == 0 then return 0 @@ -30150,7 +29815,6 @@ end return v end --- Residual coding: fills s[order + 1 .. n] with residuals. Returns the new bit position, or -1. @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 @@ -30195,7 +29859,6 @@ end end end elseif k <= 24 then - -- the hot loop: unary quotient + k-bit remainder, zigzag local pk = POW2[k + 1] local rk = 32 - k for j = i, stop do @@ -30217,7 +29880,6 @@ end p += k end else - -- a long run of zeros q = 32 - sh p += q while true do @@ -30385,7 +30047,6 @@ end end end --- One subframe into s[1..n]. Returns the new bit position, or -1. @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 @@ -30495,8 +30156,6 @@ end return p end --- Decode the frame whose header h was parsed (data ends at len). chans[c] are tables of at least h.blockSize --- numbers; they receive the samples. Returns the byte offset after the frame, or nil, err. @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 @@ -30512,7 +30171,7 @@ end return nil, "bad subframe" end end - local e = rshift(p + 7, 3) -- byte align + local e = rshift(p + 7, 3) if e + 2 > len then return nil, "truncated frame" end @@ -30548,19 +30207,10 @@ return Frame end __FILES["codecs/audio/Hively"] = function() --- codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats --- (Load), the replayer with its waveform generator (Tables: triangle / sawtooth / square / noise and the 31 + 31 --- filtered copies) and integer mixer (Player), and the render glue to a Types.Decoder (stereo f32). A port of --- HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt): --- at hvl2wav's settings the output equals hvl2wav's 16-bit samples / 32768, sample for sample. --- --- local Hively = require("@rosetta/codecs/audio/Hively") --- local tune, err = Hively.parse(buf, 0, buffer.len(buf)) -- the replayer's Tune --- local song = Hively.module(tune) -- a Types.Module-shaped value with render() --- local dec = Hively.decoder(tune, { sampleRate = 44100 }) -- a Types.Decoder --- --- Not supported: hvl2wav's -a auto gain; a speed multiplier of 4 at 44.1 kHz renders 880 samples per 50 Hz frame --- (hvl2wav pads each frame to 882 with stale samples). +-- 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") @@ -30571,14 +30221,13 @@ local Hively = {} type Tune = Load.Tune type RenderOptions = { - sampleRate: number?, -- default 44100 (the replayer runs at any rate: 8000..192000) - subsong: number?, -- 0 = the main song (default), 1..n the subsongs - stereo: number?, -- AHX stereo separation 0..4 (0 mono, 4 = 100 % Amiga L R R L); default 0 as hvl2wav. HVL: the file's - loop: boolean?, -- keep playing past the song end (frames / duration still give one pass) + 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) } --- parse(b, base?, limit?) -> Tune | nil, Err 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 @@ -30600,7 +30249,6 @@ local function settings(tune: Tune, opts: RenderOptions?): (number?, number, num return rate, sub, tonumber(o.stereo) or 0, nil end --- frameCount(tune, opts?) -> 50 Hz frames until the song end (as hvl2wav stops), capped by maxDuration 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) @@ -30618,7 +30266,6 @@ function Hively.frameCount(tune: Tune, opts: RenderOptions?): number return n end --- decoder(tune, opts?) -> Types.Decoder | nil, Err function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err.Err?) local rate, sub, stereo, err = settings(tune, opts) if not rate then @@ -30633,7 +30280,7 @@ function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err. 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 -- read position / filled frames inside fbuf + local fpos, ffill = 0, 0 local pos = 0 local function nextFrame() @@ -30696,8 +30343,6 @@ function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err. return (dec :: any) :: Types.Decoder, nil end --- module(tune) -> a Types.Module-shaped value (kind "music"): tracks as patterns (rows * 6 bytes: note, instrument, --- fx, param, fxb, paramb), positions, instruments with their play lists, and render(opts) -> Decoder function Hively.module(tune: Tune): Types.Module local patterns = {} for t = 0, tune.trackNr do @@ -30747,7 +30392,6 @@ function Hively.module(tune: Tune): Types.Module if dec then return dec end - -- the Types contract returns a Decoder: a failed render is an empty one carrying the Err local empty: any = Pcm.audioDecoder(Types.Audio.new(44100, 2, 0)) empty.err = derr return empty @@ -30759,10 +30403,9 @@ 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 -> the replayer's --- Tune. Ported from hvl2wav's replay.c 1.9 loaders (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. Errors are returned as --- (nil, message, kind) for core/Err.from. +-- 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 @@ -30787,23 +30430,23 @@ type Instrument = { plist: { speed: number, length: number, entries: { PlistEntry } }, } type Tune = { - format: string, -- "ahx" | "hvl" - version: number, -- the 4th byte: AHX 0..2, HVL 0..1 + format: string, + version: number, title: string, - channels: number, -- 4 (AHX), 4..16 (HVL) + channels: number, positionNr: number, restart: number, - speedMultiplier: number, -- 1..4 player calls per 50 Hz frame - trackLength: number, -- rows per track, 1..64 - trackNr: number, -- the highest track number stored + speedMultiplier: number, + trackLength: number, + trackNr: number, instrumentNr: number, - subsongs: { number }, -- first positions of subsongs 1..n + 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 }, -- 1-based, as numbered in the file + instruments: { Instrument }, mixgain: number, -- (percent * 256) / 100, HVL only (AHX: set by the stereo separation at render time) - stereo: number, -- HVL: the default stereo separation 0..4 - emptyTrack0: boolean, -- track 0 is not stored (always empty) + stereo: number, + emptyTrack0: boolean, } local function cstring(b: buffer, p: number, limit: number, max: number): (string, number) @@ -30814,7 +30457,6 @@ local function cstring(b: buffer, p: number, limit: number, max: number): (strin return buffer.readstring(b, p, e - p), e end --- parse(b, base, limit) -> Tune | nil, message, kind function Load.parse(b: buffer, base: number, limit: number): (Tune?, string?, string?) local size = limit - base if size < 14 then @@ -31011,11 +30653,9 @@ end __FILES["codecs/audio/Hively/Player"] = @native function() --- codecs/audio/Hively/Player: the AHX / HivelyTracker replayer: positions and tracks (two effect columns in HVL), the --- instrument engine (ADSR, vibrato, the PList performance list, square modulation, the resonant filter sweep, hard cut, --- ring modulation and panning for HVL) and the integer mixer, all as hvl2wav's replay.c 1.9 computes them so the output --- matches hvl2wav sample for sample. 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. +-- 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") @@ -31113,7 +30753,6 @@ type State = { } end --- new(tune, freq, stereo, subsong) -> State | nil (subsong out of range). stereo: AHX separation 0..4 (HVL: the file's) @native function Player.new(tune: Load.Tune, freq: number, stereo: number, subsong: number): State? if subsong < 0 or subsong > #tune.subsongs then return nil @@ -31141,7 +30780,6 @@ end return st end --- ------------------------------------------------------------------------------------------------ steps @native local function setPan(st: State, v: Voice, p: number) v.pan = p v.panMultLeft, v.panMultRight = st.panL[p], st.panR[p] @@ -31381,7 +31019,6 @@ end stepfx3(st, v, fxb, fxbp) end --- ------------------------------------------------------------------------------------------------ frames @native local function plistCommand(st: State, v: Voice, fx: number, param: number) if fx == 0 then if param > 0 and param < 0x40 then @@ -31548,7 +31185,6 @@ end end end - -- ADSR envelope if v.aFrames ~= 0 then v.adsrVolume += v.aVolume v.aFrames -= 1 @@ -31571,10 +31207,8 @@ end end end - -- volume slide v.noteMaxVolume = math.clamp(v.noteMaxVolume + v.volumeSlideUp - v.volumeSlideDown, 0, 0x40) - -- portamento if v.periodSlideOn then if v.periodSlideWithLimit then local d0 = v.periodSlidePeriod - v.periodSlideLimit @@ -31599,7 +31233,6 @@ end end end - -- vibrato if v.vibratoDepth ~= 0 then if v.vibratoDelay <= 0 then v.vibratoPeriod = (VIB[v.vibratoCurrent] * v.vibratoDepth) // 128 @@ -31610,7 +31243,6 @@ end end end - -- PList local pl = v.perfList if pl then if v.instrument and v.perfCurrent < v.instrument.plist.length then @@ -31647,7 +31279,6 @@ end end end - -- perf portamento if v.periodPerfSlideOn then v.periodPerfSlidePeriod = s16(v.periodPerfSlidePeriod - v.periodPerfSlideSpeed) if v.periodPerfSlidePeriod ~= 0 then @@ -31765,7 +31396,6 @@ end end end - -- ring modulation period if v.ringAudioOff >= 0 then local rp = v.ringBasePeriod if v.ringFixedPeriod == 0 then @@ -31783,7 +31413,6 @@ end v.ringAudioPeriod = math.clamp(rp, 0x71, 0xd60) end - -- the period local ap = v.instrPeriod if v.fixedNote == 0 then if v.overrideTranspose ~= 1000 then @@ -31805,7 +31434,6 @@ end v.audioVolume = s16(vol) end --- fill the 0x280-byte voice buffer with repeats of the 4 << waveLength cycle at (src, off) @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) @@ -31841,7 +31469,7 @@ end end end --- irq(st, audio): one player call (hvl_play_irq); audio = false skips the audio side (duration scans) +-- 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 @@ -31899,7 +31527,7 @@ end end end --- mix(st, out, at, n): n stereo frames of f32 into out at frame `at` (hvl_mixchunk: integer mixing, s16 clipping, / 32768) +-- 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 @@ -31983,16 +31611,13 @@ end __FILES["codecs/audio/Hively/Tables"] = @native function() --- codecs/audio/Hively/Tables: the AHX / HivelyTracker replayer's tables: the waveform block (triangle and sawtooth at --- six lengths, 32 square pulse widths, white noise, and the 31 low-pass and 31 high-pass filtered copies of all of --- them, generated as hvl_replay.c does), the sine panning tables, the vibrato sine and the Amiga period table. Ported --- from HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt) --- as hvl2wav builds on 64-bit Linux (`long` is 64-bit there: the noise generator's shifts do not wrap at 32 bits). +-- 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 --- the offsets inside `waves` (bytes) 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 @@ -32167,7 +31792,6 @@ end local cache: { waves: buffer, panL: { number }, panR: { number } }? = nil --- get() -> { waves (int8 buffer), panL, panR (0-based, 256 entries) }: built once, shared read only @native function Tables.get(): { waves: buffer, panL: { number }, panR: { number } } if cache then return cache @@ -32207,28 +31831,14 @@ __FILES["codecs/audio/Mdct"] = @native function() --- codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point --- complex FFT (codecs/audio/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the --- DCT-IV, a plain FFT and the sine / KBD / Vorbis windows. Shared by AAC, Vorbis and Opus (decoders and encoders). --- Written from the textbook definitions (MDCT = DCT-IV of the folded input; DCT-IV through a half-size complex FFT --- with pre / post twiddles); no third-party code. +-- 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 -- --- Both are unnormalised (times `scale`, default 1): windowed forward + inverse + overlap-add with a Princen-Bradley --- window gives the input times N / 4 (AAC: the spec IMDCT is inverse(..., 2 / N), its MDCT has a factor 2). Arrays --- are Luau arrays; `xi` / `yi` are the 1-based index of element 0, coefficient arrays may be strided (CELT --- interleaves its short blocks). --- --- local Mdct = require("@rosetta/codecs/audio/Mdct") --- local plan = Mdct.new(2048) -- nil when N is not a multiple of 4 --- Mdct.forward(plan, x, 1, X, 1) -- 2048 samples -> 1024 coefficients --- Mdct.inverse(plan, X, 1, 1, y, 1, 2 / 2048) -- 1024 coefficients -> 2048 samples --- local w = Mdct.window("sine", 2048) -- or "kbd" (alpha), "vorbis": N values --- --- Never throws: bad sizes return nil from new(); the transforms trust the plan and the array ranges (the caller --- sizes them). +-- 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 @@ -32237,17 +31847,16 @@ local Mdct = {} Mdct.Fft = Fft type Plan = { - n: number, -- window length N - m: number, -- coefficients N / 2 - fft: Fft.Plan, -- N / 4 points + 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 }, -- scratch + re: { number }, im: { number }, - c: { number }, -- DCT-IV output scratch (M) + c: { number }, } --- new(N) -> Plan | nil @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 @@ -32275,7 +31884,6 @@ type Plan = { } end --- the DCT-IV of the M values u (already in plan.re / plan.im as the pre-twiddled pairs) into out[oi + k * os] @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 @@ -32288,8 +31896,7 @@ end end end --- dct4(plan, u, ui, us, out, oi, os, scale?): C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)) for the --- plan's M = N / 2 (its own inverse up to 2 / M) +-- 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 @@ -32302,10 +31909,9 @@ end dct4Post(plan, out, oi, os, scale or 1) end --- forward(plan, x, xi, X, Xi, Xs?, scale?): N samples x[xi ..] -> N / 2 coefficients X[Xi + k * Xs] @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 -- N / 4 + 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 @@ -32331,7 +31937,6 @@ end dct4Post(plan, out, oi, os or 1, scale or 1) end --- inverse(plan, X, Xi, Xs?, y, yi, scale?): N / 2 coefficients X[Xi + k * Xs] -> N samples y[yi ..] (no window) @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 @@ -32346,7 +31951,6 @@ end end end --- ------------------------------------------------------------------------------------------------ windows @native local function besselI0(x: number): number local sum, term = 1, 1 local k = 1 @@ -32362,8 +31966,8 @@ end end Mdct.besselI0 = besselI0 --- window(kind, N, alpha?) -> N values: "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (alpha: AAC uses 4 --- for long, 6 for short windows); "vorbis" sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1. +-- "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 @@ -32401,7 +32005,6 @@ Mdct.besselI0 = besselI0 return w end --- fft(n) -> an Fft plan (Fft.forward(plan, re, im) transforms in place) @native function Mdct.fft(n: number): Fft.Plan? return Fft.new(n) end @@ -32412,10 +32015,8 @@ __FILES["codecs/audio/Mdct/Fft"] = @native function() --- codecs/audio/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for --- other primes), self-sorting Stockham passes ping-ponging between the data and a scratch array (the FFTPACK / --- pocketfft pass structure, written from the textbook decimation-in-frequency derivation; no third-party code). --- Data are separate real / imaginary arrays, 1-based. Never throws. +-- 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 = { @@ -32427,13 +32028,12 @@ type Plan = { -- per pass, generic odd radix: exp(-2 pi i k / p) for k = 0 .. p - 1 rr: { { number } }, ri: { { number } }, - sre: { number }, -- scratch + sre: { number }, sim: { number }, } local cos, sin, pi = math.cos, math.sin, math.pi --- new(n) -> Plan | nil (n < 1 or not an integer) @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 @@ -32600,8 +32200,7 @@ end end end --- forward(plan, re, im): in-place forward DFT X[k] = sum x[j] exp(-2 pi i j k / n) of re[1..n], im[1..n]. --- The inverse (without the 1 / n) is forward(plan, im, re). +-- 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 @@ -32623,11 +32222,9 @@ return Fft end __FILES["codecs/audio/MidiRender"] = function() --- codecs/audio/MidiRender: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, --- and the audio Decoder that plays a Midi through codecs/audio/SoundFont's synth (a SoundFont bank, or the built-in --- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order). --- Format 2: each track is its own song with its own tempo map, played one after another. Shared by every format that --- decodes to a Types.Midi (music/midi, mus, xmi, hmp): attach() adds the meta summary and the render method. +-- 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") @@ -32647,7 +32244,6 @@ local function tempoOf(ev: any): number? return nil end --- tempoMap(midi, track?) -> TempoMap: from every track (format 0 / 1) or from one track (format 2) function Render.tempoMap(midi: Types.Midi, track: number?): TempoMap local changes: { { number } } = {} for ti, t in midi.tracks do @@ -32686,7 +32282,6 @@ function Render.tempoMap(midi: Types.Midi, track: number?): TempoMap return map end --- seconds(map, tick) -> seconds (PPQ through the tempo map; SMPTE divisions are fixed time) function Render.seconds(map: TempoMap, tick: number): number local div = map.division if div < 0 then @@ -32698,7 +32293,6 @@ function Render.seconds(map: TempoMap, tick: number): number return tick / ((if fps == 29 then 29.97 else fps) * tpf) end local ticks = map.ticks - -- binary search for the last change at or before tick local lo, hi = 1, #ticks while lo < hi do local mid = (lo + hi + 1) // 2 @@ -32711,7 +32305,6 @@ function Render.seconds(map: TempoMap, tick: number): number return map.secs[lo] + (tick - ticks[lo]) * map.us[lo] * 1e-6 / div end --- length(midi) -> seconds to the last event (format 2: the tracks one after another) function Render.length(midi: Types.Midi): number if #midi.tracks == 0 then return 0 @@ -32740,7 +32333,6 @@ end type Timeline = { time: { number }, status: { number }, d1: { number }, d2: { number }, length: number } --- timeline(midi) -> the channel messages in play order with their times in seconds function Render.timeline(midi: Types.Midi): Timeline local items: { { any } } = {} local offset = 0 @@ -32786,14 +32378,13 @@ function Render.timeline(midi: Types.Midi): Timeline end type RenderOptions = { - sampleRate: number?, -- default 44100 - soundfont: any?, -- a SoundFont (music/sf2 decode, codecs/audio/SoundFont.parse) or SF2 bytes (buffer / string); default the built-in waveforms - gain: number?, -- linear output gain, default 0.5 - tail: number?, -- seconds rendered after the last event (release tails), default 1 - maxVoices: number?, -- default 256 + sampleRate: number?, + soundfont: any?, + gain: number?, + tail: number?, + maxVoices: number?, } --- decoder(midi, opts?) -> Types.Decoder | nil, Err 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") @@ -32891,19 +32482,16 @@ function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder? return (dec :: any) :: Types.Decoder, nil end --- tempoBytes(division, ticksPerSecond) -> the 3 data bytes of a tempo meta event making each tick last --- 1 / ticksPerSecond seconds at that division (for formats with a fixed tick rate: MUS, XMIDI, HMP / HMI) +-- 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 --- ------------------------------------------------------------------------------------------------ durations type PendingOff = { tick: number, onTick: number, ev: Types.MidiEvent } --- merge(events, offs) -> one tick-ordered event list: for formats that store a duration with each note (XMIDI, HMI). --- events are in file order (ticks never decrease); offs are the generated note-offs. At equal ticks an off whose note --- started earlier goes before the file's events, an off of a zero-length note after them. +-- 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 @@ -32929,11 +32517,9 @@ function Render.merge(events: { Types.MidiEvent }, offs: { PendingOff }): { Type return out end --- ------------------------------------------------------------------------------------------------ attach local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder local dec, err = Render.decoder(self, opts) if not dec then - -- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err) 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) @@ -32949,7 +32535,6 @@ local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder return dec end --- summarize(midi): meta.tempos / timeSignatures / keySignatures / length from the events function Render.summarize(midi: Types.Midi) local tempos, sigs, keys = {}, {}, {} local map = Render.tempoMap(midi) @@ -32973,7 +32558,6 @@ function Render.summarize(midi: Types.Midi) midi.meta.length = Render.length(midi) end --- attach(midi, source): what every MIDI-like decoder does last: the meta summary, meta.source and the render method function Render.attach(midi: Types.Midi, source: { [string]: any }) Render.summarize(midi) midi.meta.source = source @@ -32984,10 +32568,9 @@ 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: --- frame headers (Header), the decoder core (Core: a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt, --- absorbed from mp3-luau c755bbf) with its tables, and the layer III / layer II encoders (Encode3, Encode2: shine-style --- CBR, new) with their analysis tables. ID3 tags, Xing / LAME gapless info, the frame index and seeking are audio/mp3. +-- 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"), @@ -33001,13 +32584,8 @@ __FILES["codecs/audio/Mpa/Analysis"] = @native function() --- codecs/audio/Mpa/Analysis: the MPEG audio polyphase analysis filterbank (ISO/IEC 11172-3 section C.1.3, figure C.4): 32 --- input samples -> one sample in each of the 32 subbands, with the standard's 512-tap window C = D / 32 (D from --- codecs/audio/Mpa/EncTables) and the matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). Shared by the layer II and layer III --- encoders. New code from the standard's flow chart. Never throws. --- --- local st = Analysis.new() --- Analysis.run(st, samples, start, out, outStart) -- samples[start .. start + 31] -> out[outStart .. outStart + 31] +-- 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 = {} @@ -33016,7 +32594,7 @@ 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) -- M[k * 64 + i + 1] +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) @@ -33029,7 +32607,6 @@ type State = { x: { number }, off: number, y: { number } } return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) } end --- run(st, s, si, out, oi): s[si .. si + 31] (oldest first) -> out[oi .. oi + 31] (subbands 0 .. 31) @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 @@ -33066,11 +32643,8 @@ __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. --- State that must survive between frames (MDCT overlap, polyphase history, bit reservoir) lives in a per-stream --- state from Core.newState(); everything else is module scratch, so decoding is synchronous and allocation free. --- All buffer accesses stay in bounds by construction (padded scratch, bounded loops): native code must not throw. +-- 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 @@ -33083,7 +32657,6 @@ 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) @@ -33176,19 +32749,16 @@ for i = 0, 239 do WINT[i + 1] = f32(T.g_win[i]) end ----------------------------------------------------------------------------------------------------------------- --- scratch - 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) -- layer III main data (reservoir + frame) +local MAIN = bcreate(MAX_BITRESERVOIR_BYTES + MAX_FRAME + 4096) local GRBUF = bcreate(576 * 2 * 4) -- [ch][576] f32 -local SCF = bcreate(40 * 4) -- layer III scalefactor gains, f32 -local SYN = bcreate((18 + 15) * 64 * 4) -- synthesis lines / reorder scratch, 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) -- integer scalefactors, 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) -- L12 bit allocation +local BA = bcreate(64) local SCFCOD = bcreate(64) -- layer III side info, per granule x channel (0..3) @@ -33205,19 +32775,16 @@ end local MAXB = { [0] = -1, -1, -1 } local SCFSIZE = { [0] = 0, 0, 0, 0 } --- per-stream state of the frame being decoded (set by decodeFrame) 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): position and limit in bits +-- bit reader (bs_t) local bsBuf: buffer = FRAME local bsPos = 0 local bsLimit = 0 --- n <= 25 @native local function getBits(n: number): number local pos = bsPos bsPos = pos + n @@ -33228,7 +32795,6 @@ local bsLimit = 0 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 @@ -33319,9 +32885,6 @@ end return mdb end ----------------------------------------------------------------------------------------------------------------- --- layer III scalefactors - @native local function ldexpQ2(y: number, e: number): number repeat local s = if e < 120 then e else 120 @@ -33411,7 +32974,6 @@ end 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) @@ -33560,9 +33122,6 @@ end bsPos = limit end ----------------------------------------------------------------------------------------------------------------- --- layer III stereo - -- 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 @@ -33641,9 +33200,6 @@ end end end ----------------------------------------------------------------------------------------------------------------- --- layer III reorder, antialias, IMDCT - @native local function reorder(g: number, sfb: number) local src, dst = g, 0 while true do @@ -33907,7 +33463,7 @@ end t2_7 = d + c t3_7 = (d - c) * 5.10114861 end - do -- row 0 + 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 @@ -33939,7 +33495,7 @@ end t0_6 = (x4 - x3) * 1.30656302 t0_7 = (xt - x7) * 2.56291556 end - do -- row 1 + 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 @@ -33971,7 +33527,7 @@ end t1_6 = (x4 - x3) * 1.30656302 t1_7 = (xt - x7) * 2.56291556 end - do -- row 2 + 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 @@ -34003,7 +33559,7 @@ end t2_6 = (x4 - x3) * 1.30656302 t2_7 = (xt - x7) * 2.56291556 end - do -- row 3 + 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 @@ -34166,7 +33722,6 @@ end end end ----------------------------------------------------------------------------------------------------------------- -- polyphase synthesis (mp3d_DCT_II, mp3d_synth, mp3d_synth_granule) @@ -34194,8 +33749,7 @@ end wf(PCM, (dst + 16 * nch) * 4, a * SCALE) end --- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel. xl = GRBUF float index of the left --- channel's slot, dstl = PCM float index, lins = SYN float index +-- 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) @@ -34321,9 +33875,6 @@ end end end ----------------------------------------------------------------------------------------------------------------- --- layers I and II - 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 } @@ -34436,9 +33987,6 @@ end end end ----------------------------------------------------------------------------------------------------------------- --- API - local Core = {} Core.MAX_FRAME = MAX_FRAME @@ -34471,7 +34019,6 @@ end Core.lastChannels = 0 --- pcm holds n mono samples: spread them to n interleaved stereo pairs (in place) @native function Core.upmix(pcm: buffer, n: number) if buffer.len(pcm) < n * 8 then return @@ -34483,9 +34030,6 @@ Core.lastChannels = 0 end end --- Decodes the frame b[off, off + size) (a whole frame found by the index, header included) into pcm --- (interleaved f32, frame samples x channels) and returns the samples per channel (0 = no output: an --- unfilled bit reservoir, or corrupt data). Core.lastChannels = the frame's channel count. @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 @@ -34550,7 +34094,6 @@ end bsBuf = FRAME return if success then spf else 0 end - -- layers I / II 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) @@ -34574,8 +34117,6 @@ end return spf end --- Layer III side info of the frame b[off, off + size): main_data_begin (-1 = corrupt), the sum of its --- part2_3 lengths in bits, and the main data bytes in the frame. Used by the stream index. @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 @@ -34599,7 +34140,7 @@ end return mdb, sum, (bsLimit - bsPos) // 8 end --- Layer I / II: false when the frame b[off, off + size) needs more bits than it has (minimp3 then drops it). +-- 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 @@ -34703,11 +34244,9 @@ return Core end __FILES["codecs/audio/Mpa/EncTables"] = function() --- codecs/audio/Mpa/EncTables: tables for the MPEG audio encoders, from PDMP3 (public domain / unlicense, by Krister --- Lagerstrom and contributors: licenses/PDMP3-UNLICENSE.txt), which transcribes ISO/IEC 11172-3: the synthesis window D --- (the analysis window is C = D / 32) and the layer III Huffman code trees (the encoders derive codeword tables from --- them). Trees use the standard's decoder layout: an entry with a high byte is a node (high byte: left offset, low --- byte: right offset), otherwise a leaf (x << 4 | y; count1 tables: v w x y bits). +-- 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, @@ -34999,13 +34538,9 @@ __FILES["codecs/audio/Mpa/Encode2"] = @native function() --- codecs/audio/Mpa/Encode2: an MPEG audio layer II (MP2) encoder: constant bit rate, MPEG-1 (32 / 44.1 / 48 kHz) and MPEG-2 --- low sampling frequencies (16 / 22.05 / 24 kHz), mono or stereo. New code written from ISO/IEC 11172-3 (2.4.2.3, --- C.1.5.2): the polyphase analysis (codecs/audio/Mpa/Analysis), one scalefactor per 12-sample part (scfsi 0: all three are --- sent), the standard bit allocation tables (in minimp3's compact form, CC0: licenses/minimp3-CC0.txt, as the decoder --- in this folder reads them), a greedy allocation that always gives the next step to the band with the most noise --- (signal level minus the quantizer's SNR; no psychoacoustic model), uniform midtread quantization and grouping of --- 3 / 5 / 9-level samples. Never throws. +-- 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") @@ -35033,7 +34568,6 @@ local CODE = T.g_bitalloc_code_tab end return POW[ba + 1] - 1 end --- bits for the 3 samples of one granule @native local function tripleBits(ba: number): number if ba >= 17 then return if ba == 17 then 5 elseif ba == 18 then 7 else 10 @@ -35098,7 +34632,6 @@ type Source = { } type Options = { bitrate: number, mode: string, prefix: buffer? } --- encode(src, opts) -> buffer | nil, message @native function Encode2.encode(src: Source, opts: Options): (buffer?, string?) local rate = src.sampleRate local info = RATES[rate] @@ -35115,7 +34648,6 @@ type Options = { bitrate: number, mode: string, prefix: buffer? } if not brIndex then return nil, "unsupported bit rate" end - -- the allocation table (the decoder's choice from the header) local alloc, nbands if not mpeg1 then alloc, nbands = ALLOC_L2M2, 30 @@ -35166,8 +34698,8 @@ type Options = { bitrate: number, mode: string, prefix: buffer? } -- 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) } -- scalefactor index per band and part - local bal = { table.create(32, 0), table.create(32, 0) } -- allocation step (0 = none) per band + 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 @@ -35247,7 +34779,6 @@ type Options = { bitrate: number, mode: string, prefix: buffer? } end end end - -- the frame size and the bits left for scalefactors and samples local frameBytes = slot // rate rest += slot % rate local padding = 0 @@ -35260,8 +34791,7 @@ type Options = { bitrate: number, mode: string, prefix: buffer? } for b = 1, nbands do avail -= bandBits[b] * nch end - -- greedy allocation: the band with the most noise gets its next step while it fits - local level = { table.create(nbands, 0), table.create(nbands, 0) } -- signal level (dB) per band + local level = { table.create(nbands, 0), table.create(nbands, 0) } for c = 1, nch do local sc = scf[c] for b = 1, nbands do @@ -35296,7 +34826,6 @@ type Options = { bitrate: number, mode: string, prefix: buffer? } bal[bestC][bestB] += 1 avail -= bestCost end - -- write the frame 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) @@ -35316,7 +34845,6 @@ type Options = { bitrate: number, mode: string, prefix: buffer? } put(w, 0, 1) put(w, 1, 1) put(w, 0, 2) - -- bit allocation for b = 1, nbands do for c = 1, nch do local st = bal[c][b] @@ -35395,13 +34923,9 @@ __FILES["codecs/audio/Mpa/Encode3"] = @native function() --- codecs/audio/Mpa/Encode3: an MPEG audio layer III encoder in the spirit of shine: constant bit rate, long blocks only, --- global-gain rate control (no psychoacoustic model, scalefactors all zero), no bit reservoir (main_data_begin = 0), --- MPEG-1 (32 / 44.1 / 48 kHz, two granules), MPEG-2 (16 / 22.05 / 24 kHz) and MPEG-2.5 (8 / 11.025 / 12 kHz), mono, --- stereo or joint (mid / side) stereo. New code written from ISO/IEC 11172-3 / 13818-3 (no shine / LAME code): the --- analysis filterbank (codecs/audio/Mpa/Analysis), the 36-point MDCT with the sine window, the alias-reduction butterflies, --- the x^(3/4) quantizer, big_values / count1 partitioning with per-region Huffman table choice; the Huffman codes are --- derived from the standard's decoder trees (codecs/audio/Mpa/EncTables, from PDMP3, public domain). Never throws. +-- 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") @@ -35417,7 +34941,6 @@ for i = 0, 39 do POW[i + 1] = 2 ^ i end --- ------------------------------------------------------------------------------------------------ Huffman codes -- 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 } } = {} @@ -35469,7 +34992,6 @@ for t = 1, 33 do end end local LINBITS = E.LINBITS --- the tables that hold values up to m (m <= 15), smallest first local SMALL: { [number]: { number } } = {} for m = 0, 15 do local list = {} @@ -35481,13 +35003,11 @@ for m = 0, 15 do SMALL[m] = list end --- ------------------------------------------------------------------------------------------------ bit writer type W = Bits.RawWriter local put = Bits.msbPut Encode3.put = put --- ------------------------------------------------------------------------------------------------ constants 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 }, @@ -35512,7 +35032,6 @@ for k = 0, 17 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 --- alias reduction coefficients 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 @@ -35520,16 +35039,15 @@ for i = 1, 8 do CS[i], CA[i] = 1 / s, CI[i] / s end --- ------------------------------------------------------------------------------------------------ Huffman planning type Plan = { bits: number, - bigValues: number, -- pairs - count1: number, -- quadruples - tables: { number }, -- 3 region tables + bigValues: number, + count1: number, + tables: { number }, region0: number, region1: number, c1table: number, -- 0 = A (table 32), 1 = B (33) - addr1: number, -- coefficient index where region 1 starts + addr1: number, addr2: number, } @@ -35537,7 +35055,6 @@ type Plan = { return { bits = 0, bigValues = 0, count1 = 0, tables = { 0, 0, 0 }, region0 = 0, region1 = 0, c1table = 0, addr1 = 0, addr2 = 0 } end --- bits of the pairs ix[a .. b) with table t (ix 1-based: ix[i + 1] is coefficient i) @native local function pairBits(ix: { number }, a: number, b: number, t: number): number if t == 0 then return 0 @@ -35567,7 +35084,6 @@ end return bits end --- the best table for the pairs ix[a .. b): table, bits @native local function chooseTable(ix: { number }, a: number, b: number): (number, number) if b <= a then return 0, 0 @@ -35608,7 +35124,6 @@ end return best, bestBits end --- plan the Huffman coding of ix (576 values, max <= 8206) into p; bounds = scalefactor band starts (1-based list) @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 @@ -35622,7 +35137,6 @@ end end local bv = i -- big_values * 2 coefficients p.bigValues, p.count1 = bv // 2, c1 - -- count1 bits, table A vs B local ba, bb = 0, 0 local lensA = LEN[32] for q = 0, c1 - 1 do @@ -35703,9 +35217,8 @@ end end end --- ------------------------------------------------------------------------------------------------ quantization type Unit = { - xr: { number }, -- 576 MDCT coefficients + xr: { number }, xa: { number }, -- |xr|^(3/4) ix: { number }, sign: { boolean }, @@ -35738,7 +35251,6 @@ end return true end --- the finest global gain whose Huffman size fits budget bits @native local function rateLoop(u: Unit, budget: number, bounds: { number }) local xr, xa, sign = u.xr, u.xa, u.sign local maxa = 0 @@ -35760,7 +35272,6 @@ end u.gain = 0 return end - -- the gain where the largest value quantizes to 0: an upper bound local lo, hi = 0, 255 local best = -1 while lo <= hi do @@ -35791,7 +35302,6 @@ end u.gain = best end --- ------------------------------------------------------------------------------------------------ encoder type Source = { sampleRate: number, channels: number, @@ -35800,12 +35310,11 @@ type Source = { err: any, } type Options = { - bitrate: number, -- kbps, valid for the version - mode: string, -- "stereo" | "joint" | "mono" - prefix: buffer?, -- bytes written before the first frame (an ID3v2 tag) + bitrate: number, + mode: string, + prefix: buffer?, } --- encode(src, opts) -> buffer | nil, message @native function Encode3.encode(src: Source, opts: Options): (buffer?, string?) local rate = src.sampleRate local info = RATES[rate] @@ -35827,7 +35336,6 @@ type Options = { 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 - -- scalefactor band starts (long blocks) local bounds = { 0 } do local acc = 0 @@ -35847,7 +35355,7 @@ type Options = { w.pos = need end local ana = { Analysis.new(), Analysis.new() } - local prev = { table.create(576, 0), table.create(576, 0) } -- previous granule's subband samples [sb * 18 + k + 1] + 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 @@ -35863,7 +35371,6 @@ type Options = { local srcDone = false local flushed = false while true do - -- one frame of input (zero padded at the end; one more silent frame flushes the filterbank delay) local got = 0 while got < spf and not srcDone do if pendN == 0 then @@ -35907,7 +35414,6 @@ type Options = { s[i] = 0 end end - -- analysis + MDCT per granule and channel for g = 1, granules do for c = 1, nch do local cu, pv = cur[c], prev[c] @@ -35958,7 +35464,6 @@ type Options = { end end end - -- the frame size local frameBytes = slotNum // rate rest += slotNum % rate local padding = 0 @@ -35980,7 +35485,6 @@ type Options = { done += 1 end end - -- header 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) @@ -36000,7 +35504,6 @@ type Options = { put(w, 0, 1) put(w, 1, 1) -- original put(w, 0, 2) - -- side info if mpeg1 then put(w, 0, 9) -- main_data_begin put(w, 0, if nch == 1 then 5 else 3) @@ -36032,7 +35535,6 @@ type Options = { put(w, p.c1table, 1) end end - -- main data for g = 1, granules do for c = 1, nch do local u = units[g][c] @@ -36062,9 +35564,8 @@ __FILES["codecs/audio/Mpa/Header"] = @native function() --- codecs/audio/Mpa/Header: MPEG audio frame headers (minimp3's hdr_* macros and functions), frame sync (mp3d_find_frame / --- mp3d_match_frame). Every function reads 4 header bytes at a byte offset of a buffer; callers keep offset + 4 --- inside the buffer. Never throws. +-- 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 @@ -36091,7 +35592,7 @@ H.MAX_FRAME_SYNC_MATCHES = 10 end local valid = H.valid --- hdr_compare: h2 is a valid header of the same version / layer / sample rate / free-format-ness as h1 +-- hdr_compare @native function H.compare(b: buffer, o1: number, o2: number): boolean if not valid(b, o2) then return false @@ -36134,7 +35635,7 @@ local sampleRate = H.sampleRate end local frameSamples = H.frameSamples --- hdr_frame_bytes (without padding); free format = 0 -> freeSize +-- 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) @@ -36169,7 +35670,7 @@ local padding = H.padding return true end --- mp3d_find_frame over b[base, base + n): returns (skip, frame bytes incl. padding or 0, free format size) +-- 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 @@ -36428,19 +35929,9 @@ return T end __FILES["codecs/audio/Musepack"] = function() --- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8: the stream headers (SV7's 32-bit word-swapped --- header, SV8's key / size packets: SH with its CRC, RG, EI, AP, SE), the frame / audio packet index, and the --- decoder (codecs/audio/Musepack/Decode: subband bitstream, requantisation, polyphase synthesis). 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 (the 481-sample synthesis delay and SV8's leading silence are --- dropped, the length is exact). Not supported: SV4 - SV6 (UNSUPPORTED), the SV8 seek table (the packets are indexed --- instead), chapters. --- --- local s, err = Musepack.open(buf, start, limit) -- start: the "MP+" / "MPCK" magic (after an ID3v2 tag) --- -- s: { version, sampleRate, channels, frames, maxBand, ms, profile, encoder, gapless, gain, ... } plus the --- -- codecs/audio/Stream spec: count, start(i), decode(i), pcm(), reset(), skip, stop, preroll --- --- Never throws: bad data returns nil, Err. +-- 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") @@ -36455,7 +35946,7 @@ type Stream = { version: number, sampleRate: number, channels: number, - frames: number, -- output sample frames (gapless) + frames: number, maxBand: number, ms: boolean, profile: number, -- SV7: the profile index (7 telephone .. 13 braindead); SV8: the quality (0 .. 15.875) @@ -36464,8 +35955,7 @@ type Stream = { pns: boolean?, gain: { titleGain: number, titlePeak: number, albumGain: number, albumPeak: number }?, blockFrames: number, -- frames per packet (SV7: 1; SV8: 2^block_pwr) - bytes: number, -- the stream's size in bytes (for the bitrate) - -- the codecs/audio/Stream spec + bytes: number, count: number, start: (i: number) -> number, decode: (i: number) -> (number?, Err.Err?), @@ -36476,7 +35966,6 @@ type Stream = { preroll: number, } --- ------------------------------------------------------------------------------------------------ SV7 -- 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 @@ -36535,7 +36024,7 @@ local function sv7(buf: buffer, start: number, limit: number): (Stream?, Err.Err local size = at(s, pos, 20) local stop = pos + 20 + size + (if i == frames then 11 else 0) if stop > totalBits then - break -- a truncated last frame + break end offs[i], sizes[i] = pos + 20, size pos = stop @@ -36599,7 +36088,6 @@ local function sv7(buf: buffer, start: number, limit: number): (Stream?, Err.Err return out, nil end --- ------------------------------------------------------------------------------------------------ SV8 -- 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 @@ -36634,7 +36122,7 @@ local function sv8(buf: buffer, start: number, limit: number): (Stream?, Err.Err local stop = p + size if stop > limit then if key == "AP" then - break -- a truncated last packet + break end return nil, Err.new(Err.TRUNCATED, key .. " packet", p) end @@ -36758,8 +36246,6 @@ local function sv8(buf: buffer, start: number, limit: number): (Stream?, Err.Err return out, nil end --- ------------------------------------------------------------------------------------------------ open --- magic(buf, p, limit) -> 7 | 8 | 0 (other: "MP+" with another version is 7's family, reported by open) function Musepack.magic(buf: buffer, p: number, limit: number): number if p + 4 > limit then return 0 @@ -36774,7 +36260,6 @@ function Musepack.magic(buf: buffer, p: number, limit: number): number return 0 end --- open(buf, start, limit) -> Stream | nil, Err function Musepack.open(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) local v = Musepack.magic(buf, start, limit) if v == 8 then @@ -36791,13 +36276,9 @@ __FILES["codecs/audio/Musepack/Decode"] = @native function() --- codecs/audio/Musepack/Decode: one Musepack SV7 / SV8 frame (1152 samples per channel): the bitstream (band --- resolutions, scalefactor indices, quantised subband samples, with SV8's canonical Huffman / enumerative codes), --- requantisation (M/S or L/R) and the 32-band polyphase synthesis. 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) in double precision float. The bit reader is module state (decoding is synchronous) over --- a buffer the caller pads by at least PAD bytes past `limit`: the band loops stop as soon as the position passes the --- limit, so every read stays inside the buffer. No error / assert: failures return nil, "message". +-- 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 = @@ -36809,7 +36290,6 @@ Decode.PAD = 8192 Decode.DELAY = 481 -- MPC_DECODER_SYNTH_DELAY Decode.FRAME = 1152 --- ------------------------------------------------------------------------------------------------ tables local L = T.lut local HDR, SCFI7, DSCF7 = L(T.HuffHdr), L(T.HuffSCFI), L(T.HuffDSCF) local Q7: { { T.Lut } } = { @@ -36873,9 +36353,8 @@ for i, v in T.DI do DW[i] = f32(v / 65536) end --- ------------------------------------------------------------------------------------------------ bit reader local B: buffer = buffer.create(0) -local P = 0 -- bit position +local P = 0 @native local function bits(n: number): number if n <= 0 then @@ -36896,7 +36375,6 @@ end return extract(w, 16 - band(P, 7), 16) end --- a table-driven Huffman symbol (plain or canonical) @native local function huff(t: T.Lut): number local code = peek16() local k = rshift(code, 8) + 1 @@ -36966,7 +36444,6 @@ for i = 0, 255 do PARITY[i + 1] = p end --- ------------------------------------------------------------------------------------------------ synthesis -- 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) @@ -37182,26 +36659,25 @@ end V[o + 96 - i] = V[o + i] end end --- ------------------------------------------------------------------------------------------------ state type State = { - version: number, -- 7 | 8 - maxBand: number, -- the highest band index (0 .. 31) + version: number, + maxBand: number, ms: boolean, channels: number, - resL: { number }, -- [band + 1] + resL: { number }, resR: { number }, - scfL: { number }, -- [band * 3 + m + 1] + scfL: { number }, scfR: { number }, scfiL: { number }, scfiR: { number }, dscfL: { boolean }, dscfR: { boolean }, msf: { boolean }, - qL: { number }, -- [band * 36 + k + 1] + qL: { number }, qR: { number }, - yL: { number }, -- [n * 32 + band + 1], n = 0 .. 35 + yL: { number }, yR: { number }, - vL: { number }, -- synthesis history, 2304 + 960 + vL: { number }, vR: { number }, r1: number, r2: number, @@ -37236,9 +36712,7 @@ type State = { return st end --- reset(st, scf): forget the history (before a seek); scf = the scalefactor indices to assume (libmpcdec: 0 at the --- start of the stream, 0x01010101 in the middle of an SV7 stream). The noise generator restarts too, so a seek --- decodes like libmpcdec seeking in a freshly opened stream. +-- 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 @@ -37269,8 +36743,7 @@ end st.r1, st.r2 = r1, r2 end --- ------------------------------------------------------------------------------------------------ SV7 --- mpc_decoder_read_bitstream_sv7 -> true | nil, message +-- 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 @@ -37397,7 +36870,6 @@ end return true, nil end --- ------------------------------------------------------------------------------------------------ SV8 @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 @@ -37592,7 +37064,6 @@ end return true, nil end --- ------------------------------------------------------------------------------------------------ requantisation @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 @@ -37623,7 +37094,7 @@ end end --- mpc_synthese_filter_float for one channel: 36 x 32 subband samples -> 1152 samples at out[base + i * step] +-- 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 @@ -37644,10 +37115,6 @@ end end end --- ------------------------------------------------------------------------------------------------ frames --- frame(st, buf, bitPos, limitBits, key, out, base) -> the bit position after the frame | nil, message: decodes one --- frame from buf (padded by PAD bytes past limitBits / 8) into out[base ..] (1152 * channels interleaved floats). --- key: an SV8 key frame (the first of a block). bitPos < 0 decodes a silent frame (the synthesis tail). @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 @@ -37679,8 +37146,6 @@ end return if bitPos >= 0 then pos else bitPos, nil end --- bitsAt(buf, bitPos, n) -> n (1 .. 24) bits at bitPos (frame headers: the SV7 frame size); the caller keeps --- bitPos / 8 + 4 inside buf @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) @@ -37690,12 +37155,10 @@ return Decode end __FILES["codecs/audio/Musepack/Tables"] = function() --- codecs/audio/Musepack/Tables: the Musepack SV7 / SV8 Huffman tables, the synthesis window and the 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); the tables are transcribed by script. --- Each Huffman table is a flat { code, length, value, ... } list sorted by descending left-aligned 16-bit code; --- canonical (SV8) tables map value - (code >> (16 - length)) through their symbol list. lut(table, sym?) builds the --- 8-bit first-level lookup the decoder uses. +-- 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 = { @@ -38023,15 +37486,14 @@ do end type Lut = { - len: { number }, -- 256 entries: code length when the 8-bit prefix decides the symbol, else 0 - val: { number }, -- the symbol, or the 1-based table entry to scan from + len: { number }, + val: { number }, codes: { number }, lens: { number }, vals: { number }, sym: { number }?, } --- lut(table, sym?) -> Lut function T.lut(tab: { number }, sym: { number }?): Lut local codes, lens, vals = {}, {}, {} for i = 1, #tab, 3 do @@ -38071,11 +37533,8 @@ return T end __FILES["codecs/audio/Opus"] = function() --- codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT --- decoders and the multistream / hybrid decoder that drives them (Decoder), the CELT encoder (CeltEncoder) and the --- CELT inverse MDCT (Mdct, a fused libopus port: see its header for why it is not codecs/audio/Mdct). A port of the --- libopus 1.6 decoder (BSD: licenses/libopus-BSD.txt), absorbed from opus-luau dd2b4e5; the encoder is new. Ogg Opus --- (OpusHead, OpusTags, granules, seeking) is audio/opus. +-- 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"), @@ -38090,12 +37549,9 @@ __FILES["codecs/audio/Opus/Celt"] = @native function() --- codecs/audio/Opus/Celt: CELT decoder (RFC 6716 section 4.3), a port of the libopus float decoder: celt/celt_decoder.c, bands.c, vq.c, --- cwrs.c, rate.c, quant_bands.c, laplace.c, celt.c (comb filter). Only the standard 48 kHz / 960-sample mode is --- needed by Opus. Packet loss concealment is the noise-based variant only (no pitch PLC). --- --- Arrays are Luau tables of numbers. All normalised-band data (X, Y, the folding memory `norm` and the scratch --- copies) lives in one table W, and the "pointers" of the C code are 0-based offsets into it. +-- 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") @@ -38191,7 +37647,6 @@ for n = 1, UK - 1 do end end --- shared workspace (decoding is not re-entrant) local NORM_BASE = 1920 local W = table.create(4096, 0) local TMP = table.create(256, 0) @@ -38253,7 +37708,6 @@ end 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 @@ -38367,7 +37821,6 @@ end end end --- --------------------------------------------------------------------------------------------------------------- -- bit allocation (rate.c) @native local function bits2pulses(bandI: number, LM: number, bits: number): number @@ -38404,7 +37857,7 @@ end return lshift(8 + band(i, 7), rshift(i, 3) - 1) end --- clt_compute_allocation + interp_bits2pulses (decoder side). Returns codedBands, balance, intensity, dualStereo. +-- 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) @@ -38633,7 +38086,6 @@ 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 @@ -38694,7 +38146,6 @@ end end n -= 1 end - -- n == 2 p = 2 * k + 1 local neg = i >= p if neg then @@ -38708,7 +38159,6 @@ end val = if neg then k - k0 else k0 - k iy[idx] = val yy += val * val - -- n == 1 val = if i ~= 0 then -k else k iy[idx + 1] = val yy += val * val @@ -38806,7 +38256,6 @@ end return mask end --- --------------------------------------------------------------------------------------------------------------- -- bands (bands.c) type Ctx = { @@ -38908,7 +38357,6 @@ end return lshift(rshift(qn + 1, 1), 1) end --- returns b, fill, inv, imid, iside, delta, itheta, qalloc @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 @@ -39417,9 +38865,6 @@ end end end --- --------------------------------------------------------------------------------------------------------------- --- synthesis - @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] @@ -39575,9 +39020,6 @@ end end end --- --------------------------------------------------------------------------------------------------------------- --- decoder state - @native local function resetState(st: any) st.rng = 0 st.error = 0 @@ -39685,8 +39127,7 @@ Celt.reset = resetState st.last_frame_type = FRAME_PLC_NOISE end --- celt_decode_with_ec. pcm[pbase + j * channels + c]; frameSize at 48 kHz. dec may be nil (a new range decoder over --- buf[off, off + len)). buf == nil or len <= 1 conceals. Returns the samples per channel, or < 0 on error. +-- 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 @@ -39855,7 +39296,6 @@ end pulses, fineQuant, finePriority, C, LM, ec) unquantFineEnergy(st, start, endb, fineQuant, ec, C) - -- shift the decoder memory by one frame for c = 1, CC do table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) end @@ -39956,12 +39396,9 @@ __FILES["codecs/audio/Opus/CeltEncoder"] = @native function() --- codecs/audio/Opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms frames (LM 3), full band, constant --- bit rate, long MDCTs only (no transient detection), no pitch pre-filter, normal spreading, default allocation trim, --- mono, or stereo as mid / side per band (the angle, intensity when it has no bits; dual L / R stereo on request). The bitstream side is a port of the libopus 1.6 encoder paths --- (celt_encoder.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c; BSD: licenses/libopus-BSD.txt) that --- mirror codecs/audio/Opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/audio/Mdct. --- Never throws. +-- 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") @@ -40022,7 +39459,6 @@ local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } local SPREAD_NORMAL = 2 local SPREAD_FACTOR = { 15, 10, 5 } --- the MDCT window (the decoder's) and plan local WINDOW = table.create(OVERLAP, 0) for i = 0, OVERLAP - 1 do local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) @@ -40071,7 +39507,6 @@ end return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) end --- ------------------------------------------------------------------------------------------------ energy -- 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 @@ -40108,23 +39543,22 @@ end type State = { channels: number, - oldBandE: { number }, -- the decoder's view (2 * 21) + oldBandE: { number }, preMem: { number }, - inMem: { { number } }, -- the last OVERLAP pre-emphasised samples per channel + inMem: { { number } }, frames: number, - X: { { number } }, -- per channel 960 normalised coefficients + X: { { number } }, bandLogE: { number }, - bandE: { number }, -- linear band amplitudes (intensity stereo weights) + bandE: { number }, error: { number }, work: { number }, tmp: { number }, iy: { number }, remaining: number, spread: number, - dual: boolean, -- stereo: L / R coded independently (default false: mid / side) + dual: boolean, } --- new(channels) -> State @native function CeltEncoder.new(channels: number): State local inMem = {} local X = {} @@ -40257,7 +39691,6 @@ end end end --- ------------------------------------------------------------------------------------------------ allocation @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] @@ -40521,7 +39954,6 @@ end return codedBands, balance, intensity, dualStereo end --- ------------------------------------------------------------------------------------------------ PVQ -- 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] @@ -40655,7 +40087,6 @@ 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) - -- rotate a copy (the original band stays for nothing else, but keep it intact) for j = 1, n do ROT[j] = X[xo + j] end @@ -40665,7 +40096,6 @@ local ROT = table.create(256, 0) encUint(enc, icwrs(n, iy), pvqU(n, K) + pvqU(n, K + 1)) end --- ------------------------------------------------------------------------------------------------ bands @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) @@ -40884,14 +40314,10 @@ end end end --- ------------------------------------------------------------------------------------------------ frame --- encodeFrame(st, pcm, base, stride, nbBytes) -> buffer: one CELT frame of nbBytes from 960 samples per channel --- (pcm[base + k * stride + c], floats -1 .. 1, interleaved) @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 - -- pre-emphasis, the windowed 1920-sample MDCT input, band energies, normalisation for c = 1, C do local inMem = st.inMem[c] local m = st.preMem[c] @@ -40943,7 +40369,6 @@ end local enc = RE.new(nbBytes) local totalBits = nbBytes * 8 local oldE = st.oldBandE - -- silence if silent then encBitLogp(enc, true, 15) enc.nbits_total += totalBits - tell(enc) @@ -41034,7 +40459,7 @@ return CeltEncoder end __FILES["codecs/audio/Opus/CeltTables"] = function() --- codecs/audio/Opus/CeltTables: Generated from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, see licenses/). 1-based arrays. +-- codecs/audio/Opus/CeltTables: 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, @@ -41096,9 +40521,8 @@ __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): per-frame mode switching --- between SILK, hybrid and CELT, the redundant CELT frames of mode transitions, cross-fades, PLC fallbacks, the --- multi-frame packet loop and multistream (channel mapping) decoding. Output is 48 kHz float in Luau arrays. +-- 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") @@ -41248,7 +40672,6 @@ end end frameSize = audiosize - -- SILK if mode ~= MODE_CELT then local tooSmall = frameSize < F10 local sarr, sbase = pcm, pbase @@ -41384,8 +40807,7 @@ end return audiosize end --- opus_decode_native: decodes one packet (buf == nil or len == 0: conceal frameSize samples). pcm[pbase + i * ch + c]. --- Returns the samples per channel (or < 0 on error) and the packet's size (self-delimited packets). +-- 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 @@ -41432,7 +40854,6 @@ end return nb, packetOffset end --- --------------------------------------------------------------------------------------------------------------- -- multistream (channel mapping families 0 / 1 / 255) type MS = { @@ -41465,7 +40886,6 @@ end end end --- copies channel `sc` of src (stride sstride) into every output channel mapped to stream channel index `id` @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 @@ -41481,7 +40901,7 @@ end end end --- opus_multistream_decode_native (float). Returns the samples per channel, or < 0 on error. +-- 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) @@ -41523,7 +40943,6 @@ end return frameSize end --- writes src[base + 1 .. base + count] * gain to out as f32 from byte offset o @native function Decoder.writeF32(src: { number }, base: number, count: number, gain: number, out: buffer, o: number) local writef32 = buffer.writef32 if gain == 1 then @@ -41539,8 +40958,6 @@ end end end --- Stereo downmix of n frames of srcCh-channel audio (src[base + 1 ..], interleaved): matrix[c * 2 + 1 / + 2] are the --- left / right weights of channel c. Writes f32 to out from byte offset o. @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 @@ -41564,19 +40981,15 @@ __FILES["codecs/audio/Opus/Mdct"] = @native function() --- codecs/audio/Opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the --- kiss_fft stages used by libopus: radix 5, 3, 4 and 2). The 48 kHz mode uses N = 1920 >> shift for --- shift = 0..3 (FFT sizes 480, 240, 120, 60). Arrays are Luau tables of numbers, 1-based. --- Why not codecs/audio/Mdct (measured by the cleanup pass): the shared transform computes the full N-sample IMDCT through a --- DCT-IV, of which CELT keeps the middle N / 2, so routing the decoder through it made CELT decoding 2-3x slower --- (luau: 25 -> 54-76 ms for 3 s of 32 kbps stereo) and changed the output bits (same SNR against opusdec). This --- fused libopus port (pre-rotation, a kiss_fft with fixed factors, post-rotation, TDAC) stays private. +-- 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, -- FFT size (N / 4) + n: number, factors: { number }, bitrev: { number }, twr: { number }, @@ -41645,13 +41058,11 @@ end local tw = 0.7071067812 local p = 1 for _ = 1, N do - -- k = 0 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 - -- k = 1 local a, b = fr[p + 5], fi[p + 5] tr = (a + b) * tw ti = (b - a) * tw @@ -41659,14 +41070,12 @@ end fi[p + 5] = fi[p + 1] - ti fr[p + 1] += tr fi[p + 1] += ti - -- k = 2 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 - -- k = 3 a, b = fr[p + 7], fi[p + 7] tr = (b - a) * tw ti = -(b + a) * tw @@ -41828,7 +41237,7 @@ end end end --- in-place forward FFT of bit-reversed input (opus_fft_impl) +-- 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 @@ -41858,9 +41267,7 @@ end end end --- clt_mdct_backward: input coefficients inp[inBase + k*stride] (k = 0 .. N/2-1, inBase is the 1-based index of --- coefficient 0), output written to out[outBase .. outBase + N/2 + overlap/2) with TDAC windowing of the first --- `overlap` samples (out[outBase] is sample 0). +-- 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 @@ -41882,7 +41289,6 @@ end xp2 -= 2 * stride end fftImpl(pl) - -- post-rotate local h = outBase + (overlap // 2) for k = 0, N4 - 1 do local re = fi[k + 1] @@ -41957,7 +41363,6 @@ end return if band(toc, 4) ~= 0 then 2 else 1 end --- samples per frame at rate Fs @native function Packet.samplesPerFrame(toc: number, Fs: number): number if band(toc, 0x80) ~= 0 then local a = band(rshift(toc, 3), 3) @@ -41973,7 +41378,6 @@ end end end --- total samples of a packet at 48 kHz, or -1 if invalid @native function Packet.samples(buf: buffer, off: number, len: number): number if len < 1 then return -1 @@ -42011,9 +41415,7 @@ end return 2, 4 * readu8(buf, p + 1) + b0 end --- Splits a packet (opus_packet_parse_impl). Fills offsets[i] / sizes[i] (1-based, absolute buffer offsets) and --- returns the frame count, the TOC byte and the packet's total size including padding (self-delimited packets, as in --- multistream, carry an explicit size for the last frame). The count is -1 for an invalid packet. +-- 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 @@ -42149,19 +41551,8 @@ __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: --- decode_frame, decode_indices, decode_pulses, shell_coder, code_signs, decode_parameters, gain_quant, NLSF_*, --- LPC_fit, LPC_inv_pred_gain, decode_core, stereo_*, CNG, PLC, resampler_private_up2_HQ / IIR_FIR). BSD, see --- licenses/. --- --- local st = Silk.new(apiChannels) --- local ret, n = Silk.decode(st, ctrl, lostFlag, firstFrame, ec, out, outBase) --- ctrl = { nChannelsAPI, nChannelsInternal, API_sampleRate, internalSampleRate, payloadSize_ms } --- decodes one 10 / 20 ms SILK frame and writes n samples per channel (at API_sampleRate) to the Luau array --- `out`, interleaved by nChannelsAPI: out[outBase + i * nChannelsAPI + c], scaled int16 / 32768. --- --- Fixed-point emulation: all values are Luau numbers holding C int32 / int16 values. Products of two int32 values --- (64-bit in C) are split so that every intermediate stays below 2^53 and therefore exact. +-- 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") @@ -42172,7 +41563,7 @@ local floor = math.floor local Silk = {} -local P2 = table.create(64, 0) -- P2[s] = 2^s (1-based by s: P2[s] for s >= 1, P2_0 = 1) +local P2 = table.create(64, 0) for s = 1, 63 do P2[s] = 2 ^ s end @@ -42183,8 +41574,6 @@ end return P2[s] end --- C helpers ----------------------------------------------------------------------------------------------------- - @native local function s16(x: number): number x = x % 65536 if x >= 32768 then @@ -42400,8 +41789,6 @@ end return nrg, shft end --- LPC helpers --------------------------------------------------------------------------------------------------- - -- 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 @@ -42599,8 +41986,6 @@ end end end --- NLSF ---------------------------------------------------------------------------------------------------------- - local CB_NB_MB = { nVectors = 32, order = 10, @@ -42752,8 +42137,6 @@ end nlsfStabilize(pNLSF_Q15, CB.deltaMin_Q15, order) end --- Resampler (decoder side: 8 / 12 / 16 kHz up to the API rate) ---------------------------------------------------- - 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 } @@ -42881,7 +42264,6 @@ end S[1], S[2], S[3], S[4], S[5], S[6] = s0, s1, s2, s3, s4, s5 end --- returns the next output index @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 @@ -42962,8 +42344,6 @@ end end end --- Decoder state ------------------------------------------------------------------------------------------------- - @native local function newChannel(): any return { prev_gain_Q16 = 65536, @@ -43091,8 +42471,6 @@ end return ret end --- Bitstream: indices and pulses --------------------------------------------------------------------------------- - 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 } @@ -43263,8 +42641,6 @@ local signIcdf = { 0, 0 } end end --- Parameters ---------------------------------------------------------------------------------------------------- - local pNLSF_Q15 = table.create(16, 0) local pNLSF0_Q15 = table.create(16, 0) @@ -43362,8 +42738,6 @@ local CB_lags = { end end --- Core synthesis ------------------------------------------------------------------------------------------------ - local sLTP = table.create(320, 0) local sLTP_Q15 = table.create(640, 0) local res_Q14 = table.create(80, 0) @@ -43529,8 +42903,6 @@ local QuantOffsets = { { 100, 240 }, { 32, 100 } } end end --- PLC / CNG ----------------------------------------------------------------------------------------------------- - local HARM_ATT_Q15 = { 32440, 31130 } local PLC_RAND_ATTENUATE_V_Q15 = { 31130, 26214 } local PLC_RAND_ATTENUATE_UV_Q15 = { 32440, 29491 } @@ -43856,8 +43228,6 @@ local CNG_sig = table.create(336, 0) end end --- Frame decode -------------------------------------------------------------------------------------------------- - -- 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 @@ -43908,8 +43278,6 @@ end return L end --- Stereo -------------------------------------------------------------------------------------------------------- - @native local function stereoDecodePred(d: any, pred_Q13: { number }) local n = icdf(d, T.stereo_pred_joint_iCDF, 1, 8) local ix02 = n // 5 @@ -43966,8 +43334,6 @@ end end end --- API ----------------------------------------------------------------------------------------------------------- - type State = any @native function Silk.new(apiChannels: number): State @@ -44594,22 +43960,6 @@ end __FILES["codecs/audio/Pcm"] = function() -- codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. --- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one --- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au, --- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder. --- --- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else --- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read --- local audio = Pcm.collect(src) -- read everything into a Types.Audio --- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder --- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio --- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer --- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/audio/Pcm/Convert) --- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767] --- local x = Pcm.fromInt(s16, 16) -- s / 32768 --- --- Sample formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw. --- Never throws (a decoder's read that throws is caught and ends the stream). local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") @@ -44635,11 +43985,10 @@ Pcm.WAVE_FROM_VORBIS = { type Source = { sampleRate: number, channels: number, - frames: number, -- total frames, 0 = unknown (a streaming decoder without an index) + frames: number, tags: Types.Tags, - -- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end) read: (self: Source, n: number, out: buffer?) -> (buffer, number), - err: Err.Err?, -- set when the underlying decoder failed mid-stream + err: Err.Err?, } local function audioRead(self: any, n: number, out: buffer?): (buffer, number) @@ -44680,7 +44029,6 @@ local function decoderRead(self: any, n: number, out: buffer?): (buffer, number) return b, got end --- source(v) -> Source | nil, Err.ARG: v is a Types.Audio or a Types.Decoder (anything with sampleRate, channels, read) 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") @@ -44703,7 +44051,6 @@ function Pcm.source(v: any): (Source?, Err.Err?) return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") end --- collect(src, maxFrames?) -> Types.Audio | nil, Err (everything the source has; Err.LIMIT past maxFrames) function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) local ch = src.channels local cap = math.max(src.frames, 4096) @@ -44711,7 +44058,6 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) local total = 0 local limit = maxFrames or 2 ^ 31 local tmp: buffer? = nil - -- a known length: one read straight into the result (decoders write into a big enough out buffer: no copy) if src.frames > 0 and src.frames <= limit then local b, n = src:read(src.frames, data) if n > 0 then @@ -44754,9 +44100,6 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) return a, nil end --- drain(dec, source?, maxFrames?) -> Types.Audio | nil, Err: a format's decode() through its open(): every frame of --- the Decoder (dec.frames is only a hint: short or long streams keep what decodes), dec.tags, meta.source = source --- (default dec.source). A decoder that recorded a failure in dec.error (an Err) fails the drain. function Pcm.drain(dec: any, source: { [string]: any }?, maxFrames: number?): (Types.Audio?, Err.Err?) local src, err = Pcm.source(dec) if not src then @@ -44774,9 +44117,6 @@ function Pcm.drain(dec: any, source: { [string]: any }?, maxFrames: number?): (T return a, nil end --- ------------------------------------------------------------------------------------------------ decoders --- rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags?) -> Types.Decoder | nil, Err.ARG: a streaming --- decoder over frames * channels samples of fmt at buf[offset] (the caller has checked the range is inside buf) 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 @@ -44815,14 +44155,12 @@ function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: n return dec :: any, nil end --- audioDecoder(audio) -> Types.Decoder over a decoded Audio (no copy of the samples) 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 --- encode(src, fmt, w) -> frames written | nil, Err: drains src into the Writer w as fmt samples function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Err?) local size = Convert.SIZE[fmt] if not size then @@ -44848,9 +44186,6 @@ function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Er return total, nil end --- ------------------------------------------------------------------------------------------------ conversions --- reorder(buf, offset, frames, channels, map): in place, frame by frame, channel i of the result = channel map[i] --- (1-based) of the input; for converting between channel orders (Pcm.WAVE_FROM_VORBIS) function Pcm.reorder(buf: buffer, offset: number, frames: number, channels: number, map: { number }) local tmp = table.create(channels, 0) local readf32, writef32 = buffer.readf32, buffer.writef32 @@ -44865,7 +44200,6 @@ function Pcm.reorder(buf: buffer, offset: number, frames: number, channels: numb end end --- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0) function Pcm.toInt(x: number, bits: number): number local s = 2 ^ (bits - 1) local v = math.floor(x * s + 0.5) @@ -44880,7 +44214,6 @@ function Pcm.toInt(x: number, bits: number): number return v end --- fromInt(v, bits) -> v / 2^(bits-1) function Pcm.fromInt(v: number, bits: number): number return v / 2 ^ (bits - 1) end @@ -44891,12 +44224,9 @@ __FILES["codecs/audio/Pcm/Convert"] = @native function() --- codecs/audio/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/audio/Pcm). Integers map to --- v / 2^(bits-1) (as ffmpeg does); encoding rounds to nearest and clips. G.711 A-law / mu-law per ITU-T G.711 (the --- classic Sun g711.c algorithm, written from the spec). --- --- Formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw (u8: offset binary). --- Never throws: callers check ranges (Convert.SIZE[fmt] * count bytes) before calling. +-- 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 @@ -44922,7 +44252,6 @@ local SIZE: { [string]: number } = { ulaw = 1, } Convert.SIZE = SIZE --- the integer bit depth of each format (float: 32 / 64; G.711: 16 after expansion) Convert.BITS = { u8 = 8, s8 = 8, @@ -44940,11 +44269,9 @@ Convert.BITS = { ulaw = 16, } --- ------------------------------------------------------------------------------------------------ G.711 -local ALAW = table.create(256, 0) -- code -> linear s16 +local ALAW = table.create(256, 0) local ULAW = table.create(256, 0) for code = 0, 255 do - -- A-law local a = bit32.bxor(code, 0x55) local t = bit32.band(a, 0x0F) * 16 local seg = bit32.rshift(bit32.band(a, 0x70), 4) @@ -44956,7 +44283,6 @@ for code = 0, 255 do t = (t + 0x108) * 2 ^ (seg - 1) end ALAW[code + 1] = if bit32.band(a, 0x80) ~= 0 then t else -t - -- mu-law 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 @@ -44973,7 +44299,6 @@ local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF } return 8 end --- linear s16 -> A-law code @native local function alawEncode(pcm: number): number local mask local v = floor(pcm / 8) -- 13-bit magnitude domain @@ -44998,7 +44323,6 @@ end return bit32.bxor(aval, mask) end --- linear s16 -> mu-law code @native local function ulawEncode(pcm: number): number local v = floor(pcm / 4) -- 14-bit local mask @@ -45026,8 +44350,6 @@ Convert.ulawEncode = ulawEncode Convert.ALAW = ALAW Convert.ULAW = ULAW --- ------------------------------------------------------------------------------------------------ decode --- decode(src, so, fmt, count, dst, do_) -> true | false (unknown fmt): count samples at src[so] -> f32 at dst[do_] @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 @@ -45106,7 +44428,6 @@ Convert.ULAW = ULAW return true end --- ------------------------------------------------------------------------------------------------ encode @native local function q(x: number, s: number): number local v = floor(x * s + 0.5) if v ~= v then @@ -45120,7 +44441,6 @@ end return v end --- encode(src, so, count, fmt, dst, do_) -> true | false: count f32 samples at src[so] -> fmt at dst[do_] @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 @@ -45201,18 +44521,9 @@ __FILES["codecs/audio/Qoa"] = @native function() --- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale --- factor and 20 3-bit residuals over a 4-tap sign-sign LMS predictor. Ported from qoa.h (phoboslab/qoa, Dominic --- Szablewski, MIT: licenses/qoa-LICENSE.txt): the tables, the predictor, the decoder and the encoder's brute-force --- scale factor search, so encoding is byte-for-byte qoa.h's (including its 32-bit wrap in the reciprocal division). --- The 64-bit slices are handled as two 32-bit halves. --- --- local info = Qoa.frameInfo(buf, p, avail) -- { channels, rate, samples, size } | nil, message --- local n, msg = Qoa.decodeFrame(buf, p, avail, dst, d) -- one frame -> interleaved f32 at float index d --- local size = Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) -- n frames of f32 at frame xf -> bytes at out[p] --- local lms = Qoa.newLms(ch) -- the encoder state (history 0, weights 0, 0, -1, 2) --- --- Never throws: decodeFrame checks the frame against avail before reading; encodeFrame needs Qoa.frameSize bytes. +-- 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 @@ -45255,14 +44566,12 @@ end return if v >= 32768 then v - 65536 else v end --- frameSize(channels, slices) -> bytes @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 } --- frameInfo(buf, p, avail) -> the frame header's facts, checked against avail and the slice count | nil, message @native function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string?) if avail < 8 then return nil, "truncated frame header" @@ -45286,8 +44595,6 @@ type FrameInfo = { channels: number, rate: number, samples: number, size: number return { channels = ch, rate = rate, samples = samples, size = size }, nil end --- decodeFrame(buf, p, avail, dst, d) -> samples per channel, frame bytes | nil, message: one frame (its own LMS state --- in the header) as interleaved f32 into dst from float index d (dst holds samples * channels floats there) @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 @@ -45340,8 +44647,7 @@ end return samples, info.size end --- ------------------------------------------------------------------------------------------------ encoder --- newLms(ch) -> the encoder's LMS state: 8 i32 per channel (history 0..3, weights 0..3), weights 0, 0, -1, 2 (<< 13) +-- 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 @@ -45351,7 +44657,6 @@ end return st end --- the nearest s16 to x * 32768 (NaN -> 0) @native local function toS16(x: number): number local v = floor(x * 32768 + 0.5) if v ~= v then @@ -45377,8 +44682,6 @@ end return n + sv - sn end --- encodeFrame(x, xf, n, ch, rate, lms, out, p) -> bytes written: frames xf .. xf + n - 1 (n <= 5120) of interleaved f32 x --- as one QOA frame at out[p] (Qoa.frameSize(ch, ceil(n / 20)) bytes); lms carries the encoder state between frames @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) @@ -45500,44 +44803,32 @@ __FILES["codecs/audio/Resample"] = @native function() --- codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or --- whole-buffer, any channel count, interleaved f32 (the Types.Audio / Decoder layout). Used by the Opus, MP3 and MP2 --- encoders (their input rates are fixed) and ops/AudioOps.resample. New in rosetta (the textbook polyphase --- filter; the kernel is the one the Opus encoder carried). +-- 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 (opts.cutoff, default 0.97) of the lower Nyquist frequency; quality picks the taps per side at the cutoff: +-- 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 (no delay: the filter is centred, the input is zero outside its --- range); a stream of n input frames gives floor(n * to / from + 0.5) output frames. --- --- local out, frames = Resample.buffer(samples, frames, channels, 44100, 48000, { quality = "high" }) --- local rs = Resample.new(44100, 48000, 2) -- nil, message for bad rates --- local b, n = rs:process(chunk, chunkFrames) -- the output frames this input completes --- local b2, n2 = rs:flush() -- the rest (the input end padded with zeros) --- local src2 = Resample.source(pcmSource, 48000) -- a codecs/audio/Pcm Source at the new rate --- --- Never throws: bad arguments return nil, message (the api turns them into Err.ARG). +-- 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")?, -- default "medium" - cutoff: number?, -- pass band edge as a fraction of the lower Nyquist frequency, 0.5 .. 1 (default 0.97) + quality: ("low" | "medium" | "high")?, + cutoff: number?, } type Resampler = { from: number, to: number, channels: number, - -- process(src, frames, out?) -> interleaved f32 buffer, output frames (out is reused when big enough) process: (self: Resampler, src: buffer, frames: number, out: buffer?) -> (buffer, number), - -- flush(out?) -> the remaining output frames; the resampler is finished afterwards flush: (self: Resampler, out: buffer?) -> (buffer, number), } @@ -45568,15 +44859,14 @@ end end type Filter = { - taps: number, -- per phase - half: number, -- taps on the left of the centre (taps = 2 * half) + taps: number, + half: number, phases: number, exact: boolean, h: { number }, -- phase p, tap k: h[p * taps + k + 1] } --- filter(ratio, phases, exact, opts) -> the polyphase table. Phase p is the kernel for an output at fraction --- p / phases past an input sample; tap k multiplies input (floor(t) - half + 1 + k). +-- 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 @@ -45610,7 +44900,6 @@ type Filter = { return { taps = taps, half = half, phases = phases, exact = exact, h = h } end --- the stream state: the input history as an interleaved Lua array; hist[1] is frame `base` (absolute) type State = { from: number, to: number, @@ -45620,15 +44909,14 @@ type State = { L: number, -- to / g hist: { number }, histFrames: number, - base: number, -- the absolute input frame of hist[1] - inFrames: number, -- absolute input frames received - outPos: number, -- next output frame (absolute) + base: number, + inFrames: number, + outPos: number, done: boolean, process: any, flush: any, } --- run(st, lastInput) -> buffer, frames: every output frame whose taps end at or before lastInput (absolute, exclusive) @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 @@ -45658,8 +44946,8 @@ type State = { for j = j0, jmax - 1 do local num = j * M local ip = num // L -- floor(t) - local first = ip - half + 1 -- absolute input frame of tap 0 - local rel = first - base -- frame index in hist + local 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 @@ -45698,7 +44986,6 @@ type State = { end end st.outPos = jmax - -- drop history no future output needs (keep from the next output's first tap) local keepFrom = (jmax * M) // L - half + 1 local drop = keepFrom - base if drop > 0 then @@ -45742,7 +45029,6 @@ end return run(self, total, out) end --- new(from, to, channels, opts?) -> Resampler | nil, message @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" @@ -45786,7 +45072,6 @@ end return st :: any, nil end --- buffer(src, frames, channels, from, to, opts?) -> interleaved f32 buffer, frames | nil, message @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 @@ -45821,8 +45106,6 @@ end return out, got end --- source(src, to, opts?) -> a pull source ({ sampleRate, channels, frames, tags, read, err }, the codecs/audio/Pcm Source --- shape) reading src (any such source: Pcm.source(audioOrDecoder)) at the rate `to` | nil, message @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" @@ -45832,7 +45115,7 @@ end return nil, err end local ch = src.channels - local pending = buffer.create(0) -- produced but not yet returned + local pending = buffer.create(0) local pendingFrames, pendingPos = 0, 0 local ended = false local out = { @@ -45877,19 +45160,8 @@ return Resample end __FILES["codecs/audio/SoundFont"] = function() --- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by --- music/sf2 (the file format) and music/midi (rendering). The synth is a port of TinySoundFont (tsf.h v0.9, MIT, --- (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt); see Parse / Synth for what is covered. --- Without a bank, fallback() is a generated General MIDI set of simple waveforms (sine / triangle / square / saw / --- noise) with a drum kit. --- --- local SoundFont = require("@rosetta/codecs/audio/SoundFont") --- local sf, err = SoundFont.parse(buf) -- buffer | string | core/Bytes Reader -> SoundFont | nil, Err --- local sf = SoundFont.fallback() -- the built-in waveform set --- local s = SoundFont.synth(sf, 44100, { gain = 0.5 }) -- a synth State; SoundFont.Synth.midi(s, 0x90, 60, 100) --- SoundFont.Synth.render(s, out, frame, n) -- mix n stereo f32 frames into out at frame --- --- Never throws: bad data returns nil, Err. +-- 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") @@ -45904,13 +45176,10 @@ type State = Synth.State SoundFont.Synth = Synth SoundFont.defaultRegion = Parse.defaultRegion --- sniff(r) -> true when r starts with RIFF....sfbk function SoundFont.sniff(r: Bytes.Reader): boolean return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk" end --- parse(src, opts?) -> SoundFont | nil, Err. src: buffer | string | Reader. opts.maxRegions (default 10^6), --- opts.maxSamples (default 2^28) function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?) local r: Bytes.Reader if type(src) == "string" then @@ -45929,17 +45198,14 @@ function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?) return sf, err end --- fallback() -> the built-in General MIDI waveform set function SoundFont.fallback(): SoundFont return Fallback.build() end --- isSoundFont(v) -> true for a parsed / fallback SoundFont value 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 --- synth(sf?, sampleRate?, opts?) -> State. opts.gain (linear, default 0.5), opts.maxVoices (default 256) 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 @@ -45948,12 +45214,8 @@ return SoundFont end __FILES["codecs/audio/SoundFont/Fallback"] = function() --- codecs/audio/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont --- (the same shape Parse returns, so the same synth plays it): single-cycle sine / triangle / square / saw waves and a --- looped noise sample, one preset per GM family of 8 programs (piano, chromatic percussion, organ, guitar, bass, --- strings, ensemble, brass, reed, pipe, lead, pad, synth fx, ethnic, percussive, sound fx) with family envelopes, --- filters and vibrato, plus a drum kit on bank 128 (pitch-swept sine kicks and toms, filtered noise snares, hats with --- an exclusive class, cymbals). Written for this library (no third-party code). +-- 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 = {} @@ -45968,7 +45230,6 @@ end local cached: any = nil --- build() -> a SoundFont value (kind "soundfont"); built once, shared (the synth never writes to it) function Fallback.build(): any if cached then return cached @@ -46021,7 +45282,6 @@ function Fallback.build(): any return r end - -- the 16 GM families: wave + envelope / filter / vibrato local families: { { any } } = { { "piano", "triangle", { aDecay = 2.5, aSustain = 0, aRelease = 0.25 } }, { "chromatic", "sine", { aDecay = 1.2, aSustain = 0, aRelease = 0.3 } }, @@ -46046,9 +45306,7 @@ function Fallback.build(): any table.insert(presets, { name = "fallback " .. f[1], preset = program, bank = 0, regions = { region(f[2], f[3]) } }) end - -- the drum kit (bank 128, every program): one region per key local kit = {} - -- fields.semis: the pitch (semitones from the sample's natural pitch) at keytrack 0 local function drum(lo: number, hi: number, wave: string, fields: { [string]: number }) local r = region(wave, fields) r.lokey, r.hikey = lo, hi @@ -46099,21 +45357,15 @@ return Fallback end __FILES["codecs/audio/SoundFont/Parse"] = function() --- codecs/audio/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24 --- when present) as one f32 buffer, and the pdta "hydra" (phdr pbag pmod pgen inst ibag imod igen shdr), flattened --- into playable regions per preset: the instrument global zone, the preset global zone and the preset zone's --- generators merged the way TinySoundFont (tsf.h v0.9, MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt) --- does (tsf_load_presets / tsf_region_operator / tsf_region_envtosecs), with every index and sample offset clamped --- so the synth never reads outside the sample buffer. --- Differences from tsf.h: initialAttenuation is cB * 0.04 dB (FluidSynth's EMU-compatible scale; tsf uses 0.01); --- SF3 (Ogg samples) is not supported; modulators (pmod / imod) are read but not applied (as in tsf.h). --- Never throws: a bad file returns nil, Err. +-- 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 = {} --- a region (one sample zone of a preset), in "absolute" form: envelope / LFO times in seconds, sustain as a level type Region = { [string]: number } type Preset = { name: string, preset: number, bank: number, regions: { Region } } @@ -46123,7 +45375,7 @@ type SoundFont = { info: { [string]: string }, samples: buffer, -- f32 mono, sampleCount + 1 floats (a zero pad sample past the end) sampleCount: number, - presets: { Preset }, -- sorted by bank, then preset number + presets: { Preset }, sampleHeaders: { { [string]: any } }, instruments: { { name: string, zones: number } }, meta: { [string]: any }, @@ -46184,7 +45436,6 @@ local GEN: { [number]: { any } } = { [57] = { "group", "group" }, [58] = { "keycenter", "key" }, } --- the merged fields: value generators once each (several ops share a field), then the four address fields local MERGE: { { any } } = {} do local seen: { [string]: boolean } = {} @@ -46206,7 +45457,7 @@ local FIELDS = { "sampleIndex", } --- clear(relative): tsf_region_clear. relative = a preset zone (all zero: values add to the instrument's) +-- 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 @@ -46236,7 +45487,6 @@ local function copy(r: Region): Region return c end --- the region defaults in absolute form (seconds, levels): what Fallback builds its regions from function Parse.defaultRegion(): Region local r = clear(false) r.keycenter = 60 @@ -46320,7 +45570,6 @@ local function envToSecs(r: Region, p: string, sustainIsGain: boolean) r[p .. "Sustain"] = sus end --- ------------------------------------------------------------------------------------------------ RIFF type Hydra = { [string]: { { number } } } -- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte) @@ -46344,7 +45593,6 @@ local INFO_NAMES = { type Options = { maxRegions: number?, maxSamples: number? } --- parse(r, opts?) -> SoundFont | nil, Err 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 @@ -46401,7 +45649,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) local rec = {} for _, w in layout do if w == 20 then - table.insert(rec, 0) -- the name is read separately + table.insert(rec, 0) sub:skip(20) elseif w == 4 then table.insert(rec, sub:u32le()) @@ -46438,7 +45686,6 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) return nil, Err.new(Err.CORRUPT, "incomplete hydra: no " .. k .. " records") end end - -- samples local sr = smpl :: Bytes.Reader local count = sr:remaining() // 2 if count > maxSamples then @@ -46463,14 +45710,13 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) end sm24 = s24 end - -- presets (tsf_load_presets) + -- 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) - -- [list[i][field], list[i + 1][field]) clamped to [1, limit] (1-based record indexes) 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) @@ -46625,17 +45871,9 @@ 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): --- voices with the DAHDSR volume envelope (exponential decay / release), the modulation envelope to pitch and filter --- cutoff, the modulation and vibrato LFOs (triangle) to pitch / filter / volume, a resonant biquad low-pass, linear --- interpolation, loop modes (none / continuous / until release), 3 dB pan law, exclusive classes; channels with --- program / bank select (CC0 / CC32), drums (bank 128), pitch bend with RPN 0 range and RPN 1 / 2 tuning, CC7 volume, --- CC10 pan, CC11 expression, CC64 sustain, CC120 / 121 / 123. Effects (reverb, chorus) and modulators are not --- implemented (as in tsf.h). Output: interleaved stereo f32, mixed into the caller's buffer. --- Differences from tsf.h: the envelope gain is ramped across each 64-sample block (tsf.h steps it); a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only. --- Native, never throws: every buffer index is in range by construction (the regions are clamped by Parse / Fallback, --- the sample buffer has a zero pad sample, the output range is checked before mixing). +-- 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 @@ -46664,12 +45902,12 @@ type Env = { } type Lfo = { untilStart: number, level: number, delta: number } type Voice = { - preset: number, -- 1-based preset index, -1 = idle + preset: number, key: number, channel: number, - held: boolean, -- note off while sustain was down + held: boolean, region: { [string]: number }, - pitchIn: number, -- timecents + pitchIn: number, pitchOut: number, pos: number, gainDB: number, @@ -46708,14 +45946,14 @@ type Channel = { } type State = { presets: { { regions: { { [string]: number } }, preset: number, bank: number } }, - lookup: { [number]: number }, -- bank * 128 + preset -> preset index + lookup: { [number]: number }, samples: buffer, rate: number, gainDB: number, voices: { Voice }, maxVoices: number, playIndex: number, - channels: { Channel }, -- [1..16] = MIDI channels 0..15 + channels: { Channel }, } @native local function tc2s(tc: number): number @@ -46731,7 +45969,6 @@ end return if g <= 0.00001 then -100 else 20 * math.log10(g) end --- ------------------------------------------------------------------------------------------------ envelope @native local function releaseSamples(e: Env, rate: number): number return floor((if e.release <= 0 then FASTRELEASE else e.release) * rate) end @@ -46841,7 +46078,6 @@ end 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 --- ------------------------------------------------------------------------------------------------ filter / lfo @native local function lowpassSetup(v: Voice, fc: number) -- the biquad from earlevel.com (as tsf.h) local k = tan(PI * fc) @@ -46874,7 +46110,6 @@ end end end --- ------------------------------------------------------------------------------------------------ voices @native local function calcPitch(v: Voice, shift: number, rate: number) local r = v.region local note = v.key + r.transpose + r.tune / 100 @@ -46901,7 +46136,7 @@ end nextSegment(v.amp, SUSTAIN, s.rate) nextSegment(v.mod, SUSTAIN, s.rate) if v.region.loopMode == LOOP_SUSTAIN then - v.loopEnd = v.loopStart -- keep playing, stop looping + v.loopEnd = v.loopStart end end @@ -46928,8 +46163,6 @@ end } end --- new(sf, sampleRate, opts) -> State. sf: { presets, samples } (Parse.parse or Fallback.build). --- opts.gain: output gain (linear, default 0.5); opts.maxVoices (default 256) @native function Synth.new(sf: any, rate: number, gain: number?, maxVoices: number?): State local lookup: { [number]: number } = {} for i, p in sf.presets do @@ -46962,7 +46195,6 @@ end return s.lookup[bank * 128 + preset] or -1 end --- noteOn(s, channel, key, velocity 0..127) @native function Synth.noteOn(s: State, ch: number, key: number, velocity: number) local c = s.channels[ch + 1] if not c then @@ -47052,7 +46284,6 @@ end end end --- noteOff(s, channel, key): ends the oldest matching note (all its regions); held while sustain is down @native function Synth.noteOff(s: State, ch: number, key: number) local c = s.channels[ch + 1] if not c then @@ -47143,7 +46374,7 @@ end end end --- program(s, channel, program): bank select + program change (channel 9: drums, bank 128) +-- 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 @@ -47173,7 +46404,6 @@ end end end --- pitchBend(s, channel, 0..16383) @native function Synth.pitchBend(s: State, ch: number, value: number) local c = s.channels[ch + 1] if not c or c.pitchWheel == value then @@ -47183,7 +46413,6 @@ end applyPitch(s, ch, c) end --- control(s, channel, controller, value 0..127) @native function Synth.control(s: State, ch: number, cc: number, value: number) local c = s.channels[ch + 1] if not c then @@ -47265,7 +46494,6 @@ end end end --- midi(s, status, d1, d2): one channel message @native function Synth.midi(s: State, status: number, d1: number, d2: number) local kind, ch = status // 16, status % 16 if kind == 9 then @@ -47281,7 +46509,6 @@ end end end --- reset(s): all voices off, channels back to their defaults @native function Synth.reset(s: State) for _, v in s.voices do v.preset = -1 @@ -47294,7 +46521,6 @@ end end end --- active(s) -> the number of sounding voices @native function Synth.active(s: State): number local n = 0 for _, v in s.voices do @@ -47305,7 +46531,6 @@ end return n end --- ------------------------------------------------------------------------------------------------ render @native local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSamples: number) local region = v.region local input = s.samples @@ -47397,8 +46622,6 @@ end v.lpActive, v.z1, v.z2 = lpActive, z1, z2 end --- render(s, out, frame, n): mixes n stereo frames into out (interleaved f32) starting at frame; out-of-range --- requests are clipped to the buffer @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 @@ -47410,8 +46633,7 @@ end if n <= 0 then return end - -- the sample buffer must hold every region's range + the pad sample (Parse / Fallback guarantee it; checked here - -- once so a hand-made SoundFont cannot index outside it) + -- 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 @@ -47429,27 +46651,8 @@ return Synth end __FILES["codecs/audio/Stream"] = function() --- codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part --- every packet-based audio format repeated: decode packets in order into a pending float block, return frames in --- read()-sized pieces, drop the encoder priming at the start and the padding at the end (gapless), and seek by --- finding the packet holding the target (with codec pre-roll) and dropping up to it. AAC (ADTS), CAF and M4A use it; --- formats with their own seeking (Opus granule bisection, FLAC, MP3, Vorbis) keep their streams. New in rosetta --- (the loop the three formats carried). --- --- local dec, err = Stream.packets(dec, { -- dec: the Decoder table with its fields (sampleRate, channels, --- count = n, -- frames, duration, bitrate, tags, ...); read / seek / position --- start = function(i) return ... end, -- are added. start(i): packet i's first frame (absolute, before --- decode = function(i) return n, err end,-- trimming); decode(i) -> frames | nil, Err, the samples in pcm() --- pcm = function() return floats end, -- (interleaved, 1-based; or a buffer of f32) until the next decode --- reset = function() end, -- forget codec state (before a seek) --- skip = priming, stop = lastFrame, -- output = absolute frames [skip, stop) --- preroll = 1, -- packets decoded before the one holding a seek target (AAC: 1) --- scale = 1 / 32768, -- optional: read() writes pcm() values * scale (default 1) --- ints = true, -- optional: pcm() holds integers; adds dec:readInt(n, out?), the --- }) -- same frames as read() as i32 (bit-exact checks) --- --- A decode failure ends the stream and is kept in dec.error (Pcm.drain reports it); a failing first packet is --- returned by packets() as the open error. Never throws. +-- 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 = {} @@ -47458,17 +46661,16 @@ type Spec = { count: number, start: (i: number) -> number, decode: (i: number) -> (number?, Err.Err?), - pcm: () -> { number } | buffer, -- a buffer: interleaved f32 from byte 0 + pcm: () -> { number } | buffer, reset: () -> (), - skip: number?, -- default 0 - stop: number?, -- default start(count + 1) - preroll: number?, -- default 0 + skip: number?, + stop: number?, + preroll: number?, cumulative: boolean?, -- frames after a packet = frames before + its output (default: start(i) + its output) - scale: number?, -- read() writes pcm() values times this (default 1) - ints: boolean?, -- pcm() values are integers: dec:readInt(n, out?) returns them as i32 + scale: number?, + ints: boolean?, } --- packets(dec, spec) -> dec (with read / seek / position) | nil, Err (the first packet failed) function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) local sr, ch = dec.sampleRate, dec.channels local count = spec.count @@ -47478,7 +46680,7 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) local preroll = spec.preroll or 0 local decodeP, pcmOf, startOf = spec.decode, spec.pcm, spec.start local nextPacket = 1 - local decoded = 0 -- absolute frame after the packets decoded so far + local decoded = 0 local pendPos, pendN = 0, 0 local dropUntil = skip local pos = 0 @@ -47574,8 +46776,7 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) function dec.seek(_self: any, seconds: number) local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0 - local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip -- absolute frame - -- the last packet starting at or before the target, minus the codec's pre-roll + local 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 @@ -47601,7 +46802,6 @@ function Stream.packets(dec: any, spec: Spec): (any, Err.Err?) return pos / sr end - -- prime: surface a broken first packet as an open error if count > 0 and frames > 0 and not fill() and failed then return nil, failed end @@ -47612,69 +46812,20 @@ return Stream end __FILES["codecs/audio/Tracker"] = function() --- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders --- that map other trackers onto those four effect families (music/mtm, 669, stm, ult, okt, med, ptm, far; helpers in --- codecs/audio/Tracker/Load). The loaders read their files into one Module structure (below); render(module, opts) plays any of them through the standard audio --- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM --- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests. +-- 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. -- --- local Tracker = require("@rosetta/codecs/audio/Tracker") --- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder --- local seconds = Tracker.duration(module) -- one pass, song loops detected +-- 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). -- --- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file): --- format the file format ("mod", "s3m", "xm", "it", "mtm", "669", ...): what the module was read from --- engine "mod" | "s3m" | "xm" | "it": the effect family the engine plays (default: format, so the four --- families need no engine field). Other formats map their effects onto one family (music/mtm: "xm", --- music/669: "s3m", ...) and set the quirks they need in flags. --- preamp optional 0..256: the output gain as OpenMPT's sample pre-amp (gain = preamp / 128); default per family --- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s) --- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume) --- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index) --- linear linear frequency slides (XM / IT flag) or Amiga periods --- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column --- is a sample number (MOD, S3M, IT sample mode) --- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides: also on tick 0; any family), --- amigaLimits (MOD), and the quirks of the other formats (any family): --- periods = "amiga" (ProTracker period table + PAL clock, as MOD) | "hz" (periods are frequencies in --- Hz: 669, FAR; slides move hzSlide Hz per unit, tone portamento hzSlide * hzTonePorta), --- fastPortas (slides on tick 0 too), autoTonePorta (a tone portamento keeps running on later rows), --- autoReset (669: any effect stops the auto slides), st2Tempo (S3M family A: Scream Tracker 2 tempo), --- oktSlides (Oktalyzer note slides), panLaw = "ft2" (square-root panning, OpenMPT's FT2 mix levels), --- envRowHold (MED: envelopes do not advance on a row's first tick) } --- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width, --- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool } --- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels --- cells of 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. The volume column and effects are kept in the --- file's own coding: 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). Engine extension effects (any family, for the other formats): Tracker.EXT (0x40 note --- slide up, 0x41 down, 0x42 / 0x43 the same with retrigger: param = ticks per step << 4 | semitones; --- 0x44 / 0x45 auto portamento up / down (669: every tick until another effect), 0x46 frequency --- adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED)). --- Tracker.cell / Tracker.setCell read and write cells. --- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16, --- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong), --- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil), --- c5speed (S3M / IT), relativeNote, finetune -128..127 (MOD / XM), vibType / vibSweep / vibDepth / --- vibRate (IT auto-vibrato) } --- instruments { Instrument }: { name, sampleMap = { [note] = sample number }, noteMap = { [note] = note }, --- volEnv / panEnv / pitchEnv (Envelope?), fadeout (as stored: XM 0..4095, IT 0..1024), nna (0 cut, --- 1 continue, 2 note off, 3 fade), dct (0 off, 1 note, 2 sample, 3 instrument), dca (0 cut, 1 off, --- 2 fade), globalVolume 0..128, pan (0..256 or nil), pps, ppc (pitch-pan separation / centre), --- cutoff, resonance (0..127 or nil), vibType / vibSweep / vibDepth / vibRate (XM auto-vibrato) } --- Envelope { enabled, ticks = { tick }, values = { volume 0..64 | pan / pitch -32..32 }, loop, loopStart, --- loopEnd, sustain, susStart, susEnd (1-based point indexes), filter (IT pitch envelope as filter) } --- --- Pitch: two period spaces. Linear: P = (ref - note) * 64 - transpose (64 per semitone), 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. --- --- Not supported: MIDI macros other than IT's default filter macros (Z00..Z8F), glissando, ST3 / IT finetune effects --- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation. +-- 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") @@ -47699,38 +46850,32 @@ type Envelope = { susEnd: number, carry: boolean?, filter: boolean?, - raw: any?, -- format-specific fields kept for a faithful re-save (XM) + raw: any?, } type Pattern = { rows: number, data: buffer } type RenderOptions = { - sampleRate: number?, -- default 44100 - interpolation: ("linear" | "none")?, -- default "linear" - stereoSeparation: number?, -- 0..200 % (default 100: the panning as stored; 200 doubles every distance from centre) - loop: boolean?, -- keep playing past the song's end (frames / duration still give one pass); default false - maxDuration: number?, -- seconds; the render stops there (default 3600) + sampleRate: number?, + interpolation: ("linear" | "none")?, + stereoSeparation: number?, + loop: boolean?, + maxDuration: number?, } local CELL = 5 --- engine extension effects (see the Module notes above) Tracker.EXT = Player.EXT --- st2Tempo(byte) -> speed, tempo (BPM): a Scream Tracker 2 tempo byte Tracker.st2Tempo = Tables.st2Tempo local FAMILIES = { mod = true, s3m = true, xm = true, it = true } --- family(module) -> "mod" | "s3m" | "xm" | "it" | nil: the effect family a module plays as 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 --- ------------------------------------------------------------------------------------------------ constructors --- newModule(format, channels, engine?) -> an empty Module (no patterns / samples) with the defaults of the effect family --- (engine, default format) function Tracker.newModule(format: string, channels: number, engine: string?): any local fam = engine or format local m = { @@ -47769,12 +46914,10 @@ function Tracker.newModule(format: string, channels: number, engine: string?): a return m end --- newPattern(rows, channels) -> an empty Pattern function Tracker.newPattern(rows: number, channels: number): Pattern return { rows = rows, data = buffer.create(rows * channels * CELL) } end --- newSample() -> an empty Sample function Tracker.newSample(name: string?): any return { name = name or "", @@ -47805,7 +46948,6 @@ function Tracker.newEnvelope(): Envelope return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 } end --- newInstrument() -> an Instrument mapping every note to sample 0 (none) function Tracker.newInstrument(name: string?): any local sm, nm = table.create(120, 0), table.create(120, 0) for i = 1, 120 do @@ -47835,8 +46977,6 @@ function Tracker.newInstrument(name: string?): any } end --- cell(module, pattern, row, channel) -> note, instrument, volume, effect, parameter (pattern 0-based, row 0-based, --- channel 1-based); nil when out of range 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 @@ -47847,7 +46987,6 @@ function Tracker.cell(m: any, pattern: number, row: number, channel: number): (n 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 --- setCell(module, pattern, row, channel, note, instrument, volume, effect, parameter) -> true | false (out of range) 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 @@ -47863,7 +47002,6 @@ function Tracker.setCell(m: any, pattern: number, row: number, channel: number, return true end --- ------------------------------------------------------------------------------------------------ validation local function num(v: any, lo: number, hi: number): boolean return type(v) == "number" and v == v and v >= lo and v <= hi end @@ -47925,8 +47063,6 @@ local function fixLoop(s0: any, e0: any, t0: any, len: number): (number, number, return s, e, t end --- validate(module) -> true | nil, Err: checks the structure the engine relies on, clamps loops, envelopes and --- numbers into range (in place) function Tracker.validate(m: any): (boolean?, Err.Err?) if type(m) ~= "table" then return nil, Err.new(Err.ARG, "not a module") @@ -48033,11 +47169,9 @@ function Tracker.validate(m: any): (boolean?, Err.Err?) return true, nil end --- ------------------------------------------------------------------------------------------------ rendering local Decoder = {} Decoder.__index = Decoder --- duration(module, opts?) -> seconds of one pass (song loops and the end of the order list detected), or nil, Err function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?) local ok, err = Tracker.validate(m) if not ok then @@ -48064,7 +47198,6 @@ local function newPlayer(self: any) self.pos = 0 end --- render(module, opts?) -> Types.Decoder (stereo f32) | nil, Err function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?) local o: RenderOptions = opts or {} local sr = o.sampleRate or 44100 @@ -48095,13 +47228,11 @@ function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err? return self :: any, nil end --- the Module method: module:render(opts) function Tracker.renderMethod(self: any, opts: RenderOptions?): Types.Decoder local dec = Tracker.render(self, opts) return dec :: any end --- run(self, out?, n) -> frames produced (out nil: advance without mixing) local function run(self: any, out: buffer?, n: number): number local st = self.st local done = 0 @@ -48128,7 +47259,6 @@ local function run(self: any, out: buffer?, n: number): number return done end --- read(n, out?) -> interleaved stereo f32 buffer, frames read (0 at the 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 @@ -48141,7 +47271,6 @@ function Decoder.read(self: any, n: number, out: buffer?): (buffer, number) return o :: buffer, got end --- seek(seconds): replays the song silently up to the position (sample positions included) function Decoder.seek(self: any, seconds: number) local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate)) newPlayer(self) @@ -48152,7 +47281,6 @@ function Decoder.seek(self: any, seconds: number) break end end - -- the gains ramp in from silence after a seek for _, v in self.st.voices do v.gl, v.gr = 0, 0 end @@ -48166,12 +47294,9 @@ return Tracker end __FILES["codecs/audio/Tracker/Load"] = function() --- codecs/audio/Tracker/Load: helpers shared by the tracker loaders that map another format's effects onto one of the --- engine's families (music/mtm, 669, stm, ult, okt, med, ptm, far). Effects are first named the way OpenMPT's loaders --- name them ("portaup", "volslide", "modex", ...), then written in the family's own cell coding: S3M / IT letter --- codes (A = 1) with the IT volume column, or MOD / XM numbers. Ported from OpenMPT's ModCommand helpers --- (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight, CPattern::WriteEffect; BSD licence, --- licenses/openmpt-LICENSE.txt), reduced to what the engine plays. +-- 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") @@ -48181,7 +47306,6 @@ local Load = {} local EXT = Player.EXT --- the S3M / IT letter code of each effect name (engine extension effects included) local IT: { [string]: number } = { speed = 1, jump = 2, @@ -48234,7 +47358,7 @@ end local GLOBAL = { jump = true, ["break"] = true, speed = true, tempo = true, globalvol = true, globalvolslide = true } --- isGlobal(name, param) -> the effect acts on the whole song (OpenMPT's IsGlobalCommand) +-- OpenMPT's IsGlobalCommand function Load.isGlobal(name: string?, param: number): boolean if name == nil then return false @@ -48251,7 +47375,7 @@ function Load.isGlobal(name: string?, param: number): boolean return false end --- modCommand(cmd, param) -> name?, param: a MOD / XM effect number (0..F, XM letters 16..) by name (ConvertModCommand) +-- 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", @@ -48271,8 +47395,7 @@ function Load.modCommand(cmd: number, param: number): (string?, number) return n, param end --- itVolume(name, param, force) -> the IT volume-column byte + 1 (the engine's coding) for an effect that fits there, --- or nil (OpenMPT's ConvertToVolCommand; force: fit it with some loss of precision) +-- 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 @@ -48326,8 +47449,6 @@ function Load.itVolume(name: string?, param: number, force: boolean): number? return nil end --- itEffect(name, param) -> effect code, param in S3M / IT coding (0, 0 for none or an effect the family lacks; MOD's --- extended E commands become their S3M equivalents) function Load.itEffect(name: string?, param: number): (number, number) if name == nil then return 0, 0 @@ -48358,9 +47479,7 @@ function Load.itEffect(name: string?, param: number): (number, number) return code, param end --- fillTwo(name1, param1, name2, param2, lowResOffset?) -> volume byte (engine IT coding, 0 none), effect name, param, --- lost name?, lost param: two effects of one cell into the IT volume column and the effect column, keeping the --- heavier one when both cannot fit (OpenMPT's FillInTwoCommands) +-- 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) @@ -48382,10 +47501,7 @@ function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number return 0, e2, p2, e1, p1 end --- writeEffect(m, pattern (0-based), row, fx, param, retry?, channel?, multiple?) -> true when written: puts an effect --- into a free effect slot of the row (any channel, or the given 1-based one); none free: the next row (retry "next") or --- the previous one ("prev"). The same effect already on the row counts as written unless multiple (OpenMPT's --- CPattern::WriteEffect). +-- 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 @@ -48428,9 +47544,6 @@ function Load.writeEffect(m: any, pattern: number, row: number, fx: number, para return false end --- readSample(buf, offset, frames, spec, sample, budget) -> true | nil, Err: decodes raw PCM (codecs/audio/Tracker/Pcm --- spec) at the absolute buffer offset into the sample (data, length, bits, channels). A short file keeps the frames --- that are there (end = the buffer's length, or spec.limit). budget = { left = f32 bytes still allowed } (maxBytes). 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 @@ -48449,7 +47562,7 @@ function Load.readSample(buf: buffer, offset: number, frames: number, spec: any, return true, nil end --- bcd(n) -> n as the two decimal digits S3M / MOD pattern breaks store (0..99) +-- 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 @@ -48460,18 +47573,13 @@ end __FILES["codecs/audio/Tracker/Mixer"] = @native function() --- codecs/audio/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample --- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole --- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code). --- --- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/audio/Tracker) --- validates the sample buffers' sizes. +-- 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 = {} --- mixVoice(v, out?, off, n, linear, ramp): n frames of voice v added at frame off of out (nil: only advance) @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 @@ -48621,7 +47729,6 @@ local Mixer = {} local _ = ramp end --- mix(st, out?, off, n, linear): every active voice of player st; out nil only advances the sample positions @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 @@ -48635,10 +47742,8 @@ end __FILES["codecs/audio/Tracker/Pcm"] = @native function() --- codecs/audio/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned, --- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back. --- --- Never throws: reads past the source are refused up front (decode returns nil). +-- 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 @@ -48646,20 +47751,18 @@ local floor = math.floor local Pcm = {} type Spec = { - bits: number, -- 8 | 16 + bits: number, signed: boolean, delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag) - channels: number?, -- 1 (default) | 2 + channels: number?, planar: boolean?, -- stereo stored as all left then all right (XM, IT); default interleaved bigEndian: boolean?, } --- bytes(frames, spec) -> the size of the raw data @native function Pcm.bytes(frames: number, spec: Spec): number return frames * (spec.channels or 1) * (spec.bits // 8) end --- decode(buf, off, frames, spec) -> f32 buffer (frames * channels, interleaved) | nil when the source is too short @native function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer? local nch = spec.channels or 1 local bps = spec.bits // 8 @@ -48711,7 +47814,6 @@ end return out end --- encode(samples, frames, spec) -> raw PCM (signed or unsigned, optional delta, interleaved or planar) @native function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer local nch = spec.channels or 1 local bps = spec.bits // 8 @@ -48753,7 +47855,6 @@ end return out end --- bits(samples) -> 8 when every value is exactly representable in 8 bits (data loaded from 8-bit), else 16 @native function Pcm.bitsNeeded(samples: buffer): number for i = 0, buffer.len(samples) // 4 - 1 do local x = readf32(samples, i * 4) * 128 @@ -48769,15 +47870,9 @@ end __FILES["codecs/audio/Tracker/Player"] = @native function() --- codecs/audio/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders, --- speed / tempo, every effect of the four formats (interpreted per format family: ProTracker / FastTracker 2 numeric --- effects, ScreamTracker 3 / Impulse Tracker letter effects), instruments with volume / panning / pitch envelopes, --- fadeout and auto-vibrato, IT new note actions (background voices), duplicate checks and resonant filters, and song --- end / loop detection. Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes, --- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/audio/Tracker/Mixer. --- --- Never throws: the module is validated by codecs/audio/Tracker before a player is made, and every table lookup here is --- guarded. +-- 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 @@ -48792,8 +47887,6 @@ 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 } --- engine extension effects: format-specific commands of the other tracker formats, in any family (see --- codecs/audio/Tracker) local EXT = { NOTE_SLIDE_UP = 0x40, NOTE_SLIDE_DOWN = 0x41, @@ -48806,9 +47899,8 @@ local EXT = { } Player.EXT = EXT -local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions +local BG_VOICES = 64 --- ------------------------------------------------------------------------------------------------ state @native local function newVoice(): any return { active = false, @@ -48869,8 +47961,8 @@ local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions tremorMute = false, surround = false, rampN = 0, - owner = 0, -- the channel whose foreground voice this is (0: free or background) - order = 0, -- allocation age + owner = 0, + order = 0, } end @@ -48895,7 +47987,6 @@ end fx = 0, param = 0, vcmd = 0, - -- memories mPortaUp = 0, mPortaDn = 0, mFineUp = 0, @@ -48955,15 +48046,14 @@ end muted = false, triggered = false, autoPorta = 0, -- auto portamento (EXT 0x44 / 0x45): period units per tick, + down - autoTone = false, -- flags.autoTonePorta: the tone portamento keeps running + autoTone = false, hzAdd = 0, -- EXT 0x46: Hz added to the frequency (669) - slideCount = 0, -- note slides: ticks to the next step + slideCount = 0, mNoteSlide = 0, tonePortaRow = false, } end --- new(module, opts) -> player state (module validated by the caller) @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 @@ -48982,8 +48072,8 @@ end compatG = m.flags.compatGxx or false, fastSlides = flags.fastSlides or false, amigaLimits = flags.amigaLimits or false, - ptPeriods = ptPeriods, -- ProTracker periods (integer table periods, PAL clock) - hz = flags.periods == "hz", -- periods are frequencies in Hz + 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, @@ -49055,8 +48145,6 @@ end return 2 / clamp(m.channels, 2, 8) end --- ------------------------------------------------------------------------------------------------ orders and rows --- startOrder(st, ord, row): resolve skip markers / the end of the order list; sets st.pat or st.ended @native function Player.startOrder(st: any, ord: number, row: number) local m = st.m local order = m.order @@ -49126,8 +48214,6 @@ end end end --- ------------------------------------------------------------------------------------------------ pitch --- the period of a note for a sample (see codecs/audio/Tracker for the two period spaces) @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 @@ -49181,8 +48267,7 @@ end end end --- slide(st, c, units): a pitch slide in period units (positive: down; 4 per effect unit); in Hz mode the frequency --- moves units * hzSlide Hz the other way +-- 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 @@ -49192,7 +48277,6 @@ end clampPeriod(st, c) end --- ------------------------------------------------------------------------------------------------ voices @native local function allocVoice(st: any): any local best, bestScore = nil, math.huge for _, v in st.voices do @@ -49210,7 +48294,6 @@ end best.active = false return best end - -- every voice is busy in the foreground (more channels than voices): reuse an inactive one anyway for _, v in st.voices do if not v.active then local c = st.chans[v.owner] @@ -49220,7 +48303,7 @@ end return v end end - return st.voices[1] -- unreachable: there are more voices than channels + return st.voices[1] end @native local function keyOff(st: any, v: any) @@ -49261,7 +48344,6 @@ end end end --- start(st, c, smp, smpIdx, ins, insIdx, note, period, base, offset): a fresh voice for channel c @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 @@ -49310,7 +48392,6 @@ 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) - -- duplicate check: voices of this channel playing the same instrument 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 @@ -49351,7 +48432,6 @@ end end end --- ------------------------------------------------------------------------------------------------ triggering @native local function isPorta(st: any, fx: number, vcmd: number): boolean local f = st.fmt if f == MOD then @@ -49363,7 +48443,6 @@ end return fx == 7 or fx == 12 or (f == IT and vcmd >= 194 and vcmd <= 203) end --- the sample and real note for an instrument number + note @native local function resolve(st: any, insIdx: number, note: number): (any, number, any, number) local m = st.m if st.insMode then @@ -49437,7 +48516,6 @@ end end end --- trigger(st, c, note, insIdx, vcmd): the note / instrument / volume column part of a cell @native local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: number) local f = st.fmt local m = st.m @@ -49571,7 +48649,6 @@ end end end --- ------------------------------------------------------------------------------------------------ effect helpers @native local function volSlideMod(c: any, param: number) local x, y = param // 16, param % 16 if x > 0 then @@ -49627,8 +48704,7 @@ end c.vol = clamp(c.vol, 0, 64) end --- S3M / IT D-style slide of a value: returns the new value (fine parts only on tick 0, normal parts on other ticks; --- fast: normal parts on tick 0 too) +-- 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 @@ -49653,7 +48729,6 @@ end return value end --- ------------------------------------------------------------------------------------------------ MOD / XM effects @native local function fxModXm(st: any, c: any, tick: number) local fx, param = c.fx, c.param local xm = st.fmt == XM @@ -49967,7 +49042,6 @@ end end end --- ------------------------------------------------------------------------------------------------ S3M / IT effects -- 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 @@ -50375,8 +49449,6 @@ end end end --- ------------------------------------------------------------------------------------------------ extension effects --- the engine extension effects (EXT, codes 0x40..) and the auto slides, in any family @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 @@ -50435,7 +49507,6 @@ end end end --- ------------------------------------------------------------------------------------------------ rows and ticks @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 @@ -50533,7 +49604,6 @@ end end @native local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean): (number, number, boolean) - -- returns value, next position, ended local ticks, values = env.ticks, env.values local n = #ticks if n == 0 then @@ -50574,7 +49644,6 @@ end return value, nextPos, ended end --- per-tick voice update: envelopes, fadeout, auto-vibrato, final frequency, gains and filter @native local function updateVoice(st: any, v: any) local ins = v.ins local it = st.fmt == IT @@ -50645,7 +49714,6 @@ end end v.avPos = (v.avPos + (avSrc.vibRate or 0)) % 256 end - -- frequency local P = v.periodOut + avDelta local freq if st.hz then @@ -50659,7 +49727,6 @@ end freq *= 2 ^ (envPitch / 24) end v.inc = freq / st.sr - -- volume 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, @@ -50668,7 +49735,6 @@ end if v.tremorMute then vol = 0 end - -- panning 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) @@ -50690,7 +49756,6 @@ end v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256 end v.rampN = st.ramp - -- IT resonant filter local cutoff = v.cutoff if filterEnv ~= nil or cutoff < 127 or v.reso > 0 then local cc = cutoff @@ -50715,7 +49780,6 @@ end end end --- tick(st) -> frames to mix for this tick (0 when the song ended) @native function Player.tick(st: any): number if st.ended then return 0 @@ -50728,7 +49792,6 @@ end return 0 end if st.visited[key] then - -- looping on: forget the song so far, keep playing table.clear(st.visited) end st.fineDelay = 0 @@ -50752,7 +49815,6 @@ end if st.ended then return 0 end - -- channel -> foreground voice for i = 1, st.nch do local c = st.chans[i] local v = c.voice @@ -50778,7 +49840,6 @@ 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)) - -- advance st.tick += 1 if st.tick >= st.speed + st.fineDelay then st.tick = 0 @@ -50797,16 +49858,13 @@ end __FILES["codecs/audio/Tracker/Tables"] = @native function() --- codecs/audio/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the --- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M --- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker --- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT). +-- 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 } --- wave64(type, pos) -> -255..255 for pos 0..63: 0 sine, 1 ramp down, 2 square, 3 random (deterministic) local RANDOM: { number } = {} do local s = 12345 @@ -50828,8 +49886,6 @@ end return if p >= 32 then -v else v end --- autoWave(type, pos, it) -> -64..64 for pos 0..255. XM: 0 sine, 1 square, 2 ramp down, 3 ramp up. --- IT: 0 sine, 1 ramp down, 2 square, 3 random. local SINE256: { number } = {} for i = 0, 255 do SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5) @@ -50856,9 +49912,7 @@ end return SINE256[p + 1] end --- ProTracker periods, finetune 0, C-0 .. B-4 (60 notes; ProTracker itself uses C-1 .. B-3). Our note numbers: --- 1 = C-0 (FT2 numbering), so ProTracker C-1 (856) = note 37 and C-2 (428) = note 49, the note that plays a sample at --- its base rate (8363 Hz). +-- 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, @@ -50870,12 +49924,10 @@ local PERIODS = { Tables.PERIODS = PERIODS Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1) --- periodToNote(period) -> note (1..120), 0 for period 0 @native function Tables.periodToNote(period: number): number if period <= 0 then return 0 end - -- exact match first, then the nearest note on a log scale for i = 1, #PERIODS do if PERIODS[i] == period then return i + Tables.PERIOD_FIRST_NOTE - 1 @@ -50885,7 +49937,6 @@ Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = P return math.clamp(n, 1, 120) end --- noteToPeriod(note) -> ProTracker period (finetune 0) for a note, computed past the table's ends @native function Tables.noteToPeriod(note: number): number local i = note - Tables.PERIOD_FIRST_NOTE + 1 if i >= 1 and i <= #PERIODS then @@ -50901,14 +49952,12 @@ Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 } 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 } --- the Amiga clock constant: frequency = AMIGA / period, with period 1712 playing an 8363 Hz sample at its base rate --- (FT2 / ST3 period units, 4x ProTracker's) +-- 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 --- st2Tempo(byte) -> speed, tempo: a Scream Tracker 2 tempo byte (high nibble ticks per row, low nibble a fine factor) --- as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at its 23863 Hz mixing rate, as a fractional BPM) +-- 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 @@ -50924,17 +49973,9 @@ return Tables end __FILES["codecs/audio/Tta"] = function() --- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description --- (the 22-byte header with its CRC-32, the seek table of frame sizes with its CRC-32, frames of 256 / 245 seconds); --- no libtta / ffmpeg code (those are LGPL). The frame decoder is codecs/audio/Tta/Decode. Supports format 1 (plain --- PCM), 8 / 16 / 24 bits, any channel count, the header / seek table / frame CRCs. Not supported: format 2 --- (password-protected: UNSUPPORTED), TTA2. --- --- local info, err = Tta.info(buf, at, limit) -- the header at `at` (after any ID3v2 tag) + the frame table --- local dec = Tta.decoder(info) --- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved integers) --- --- Never throws: bad data returns nil, Err. +-- 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") @@ -50946,14 +49987,13 @@ type Info = { channels: number, bitsPerSample: number, sampleRate: number, - samples: number, -- per channel + samples: number, frameLength: number, -- samples per frame (256 * rate / 245) frames: number, - offsets: { number }, -- each frame's byte offset + offsets: { number }, sizes: { number }, } --- info(buf, at, limit) -> Info | nil, Err: the TTA1 header at byte `at` 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") @@ -51011,7 +50051,6 @@ function Tta.info(buf: buffer, at: number, limit: number): (Info?, Err.Err?) return info, nil end --- ------------------------------------------------------------------------------------------------ decoder type Decoder = { info: Info, pcm: { number }, @@ -51037,7 +50076,6 @@ local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) return got, nil end --- decoder(info, limit) -> Decoder (limit: the end of the file data) function Tta.decoder(info: Info, limit: number): Decoder return { info = info, @@ -51054,10 +50092,8 @@ __FILES["codecs/audio/Tta/Decode"] = @native function() --- codecs/audio/Tta/Decode: one TTA1 frame -> samples. Written from the TTA1 format description (the True Audio --- format notes: adaptive Rice codes with two running sums per channel, the order-8 sign-LMS "hybrid" filter, the --- first-order fixed predictor, inter-channel decorrelation, a CRC-32 per frame); no libtta / ffmpeg code. Checked --- bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). Never throws: returns nil, message. +-- 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 @@ -51069,11 +50105,10 @@ local Decode = {} local TWO31, TWO32 = 2147483648, 4294967296 local INV31 = 1 / TWO31 local PAD = 16 -local P2: { number } = table.create(40, 0) -- P2[k + 1] = 2^k +local P2: { number } = table.create(40, 0) for i = 0, 39 do P2[i + 1] = 2 ^ i end --- ONES[b + 1]: the trailing 1 bits of the byte b local ONES: { number } = table.create(256, 0) for b = 0, 255 do local n, v = 0, b @@ -51084,7 +50119,6 @@ for b = 0, 255 do ONES[b + 1] = n end --- longUnary(S, pos, lim) -> the count of 1 bits from pos, the position after the 0 | nil (past lim) @native local function longUnary(S: buffer, pos: number, lim: number): (number?, number) local unary = 0 while pos <= lim do @@ -51101,9 +50135,8 @@ end type State = { channels: number, - bytes: number, -- 1 .. 3 - S: buffer, -- the frame's bits (+ PAD zeros) - -- per channel: rice k0, k1, sum0, sum1; filter error, Q (weights), X (steps), L (delay line) x 8; the last value + bytes: number, + S: buffer, R: { number }, Q: { number }, X: { number }, @@ -51128,8 +50161,6 @@ type State = { } end --- frame(st, buf, o, len, n, P) -> n | nil, message: the frame of len bytes at o (its CRC-32 last) holding n samples per --- channel, into P (interleaved integers) @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" @@ -51158,15 +50189,14 @@ end Q[c * 8 + i], X[c * 8 + i], L[c * 8 + i] = 0, 0, 0 end end - local pos = 0 -- bit position + local pos = 0 local lim = dlen * 8 - local c = 0 -- the channel of the sample at idx + local c = 0 for idx = 1, n * C do do if pos > lim then return nil, "truncated frame" end - -- the unary prefix: 1 bits up to a 0 (a run past one byte goes to longUnary) local unary local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) local ones = ONES[band(w, 255) + 1] @@ -51275,7 +50305,6 @@ end L[fb + 6] = n6 L[fb + 7] = n7 L[fb + 8] = value - -- the fixed predictor value += (last[c + 1] * (pk - 1)) // pk last[c + 1] = value cur[c + 1] = value @@ -51313,10 +50342,8 @@ return Decode end __FILES["codecs/audio/Vorbis"] = function() --- codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup), --- codebooks (Codebook), audio packets to PCM (Packet: floors 0 / 1, residues 0 / 1 / 2, coupling, the IMDCT through --- codecs/audio/Mdct) and the shared tables. A Luau port of stb_vorbis 1.22 (public domain / MIT, --- licenses/stb_vorbis-LICENSE.txt). Ogg Vorbis (pages, granules, seeking) and the encoder are audio/vorbis. +-- 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"), @@ -51330,14 +50357,9 @@ __FILES["codecs/audio/Vorbis/Codebook"] = @native function() --- codecs/audio/Vorbis/Codebook: the Vorbis LSB-first packet bit reader and codebooks (Vorbis I spec sections 2 and 3): --- reading a codebook from the setup header (ordered / sparse length lists, lookup types 1 and 2, float32_unpack), --- the codeword assignment, and Huffman / VQ decoding. Ported from stb_vorbis 1.22 (public domain / MIT; see --- licenses/stb_vorbis-LICENSE.txt): compute_codewords' lowest-free-leaf assignment, lookup1_values; the decode side --- is a fast table (up to 10 bits) plus a binary tree for longer codes instead of stb's sorted binary search. --- --- Never throws. Reading past the packet end gives zero bits and sets br.eop (the spec's end-of-packet condition); --- an invalid codeword also sets eop and decodes to -1. +-- 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 @@ -51348,22 +50370,20 @@ for i = 0, 40 do POW[i + 1] = 2 ^ i end --- ------------------------------------------------------------------------------------------------ bit reader type Br = { buf: buffer, - pos: number, -- next byte to load + pos: number, limit: number, - acc: number, -- loaded, unread bits (LSB first) + acc: number, cnt: number, - pad: number, -- how many of the top bits of acc are past the end of the packet - eop: boolean, -- read past the end of the packet + 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 --- bits(br, n) -> the next n (0..32) bits as an unsigned number @native local function bits(br: Br, n: number): number if n == 0 then return 0 @@ -51395,7 +50415,7 @@ end end Codebook.bits = bits --- ilog(x): the number of bits needed to hold x (0 for x <= 0) +-- ilog (spec 9.2.1) @native local function ilog(x: number): number local n = 0 while x > 0 do @@ -51415,7 +50435,6 @@ Codebook.ilog = ilog return if sign then -v else v end --- ------------------------------------------------------------------------------------------------ codebooks type Book = { dims: number, entries: number, @@ -51424,9 +50443,9 @@ type Book = { 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, -- 0, 1, 2 - vq: { number }?, -- entries * dims values (lookup 1 / 2, expanded) - used: number, -- entries with a codeword + lookup: number, + vq: { number }?, + used: number, } local MAX_ENTRIES = 2 ^ 20 @@ -51481,7 +50500,6 @@ end available[y + 1] = code + POW[33 - y] + 1 end end - -- walk the MSB-first code into the tree local node = 1 for d = 1, len do local bit = floor(code / POW[33 - d]) % 2 @@ -51518,7 +50536,6 @@ end end end book.used = used - -- the fast table: every fastBits-bit prefix (read LSB first) walked down the tree local fb = math.clamp(maxLen, 1, 10) book.fastBits = fb local size = POW[fb + 1] @@ -51534,7 +50551,7 @@ end fl[idx + 1], fs[idx + 1] = d, -child - 1 break elseif child == 0 then - break -- invalid (-1) + break end node = child if d == fb then @@ -51546,7 +50563,6 @@ end return nil end --- read(br) -> Book | nil, message: one codebook from the setup header @native function Codebook.read(br: Br): (Book?, string?) if bits(br, 24) ~= 0x564342 then return nil, "bad codebook sync" @@ -51666,7 +50682,6 @@ end return book, nil end --- decode(br, book) -> entry number | -1 (end of packet / invalid codeword: br.eop is set) @native local function decode(br: Br, book: Book): number local fb = book.fastBits local acc, cnt = br.acc, br.cnt @@ -51726,18 +50741,10 @@ __FILES["codecs/audio/Vorbis/Packet"] = @native function() --- codecs/audio/Vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8): mode and window shape, floor 1 --- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/audio/Mdct), windowing and overlap-add. --- Floors, residues and coupling are ported from stb_vorbis 1.22 vorbis_decode_packet_rest / decode_residue / --- do_floor / draw_line (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). The overlap follows libvorbis: --- each packet after the first returns the n_prev/4 + n_cur/4 samples between the centres of the two windows, so --- granule positions count exactly the samples returned (the first packet returns none). --- --- local st = Packet.new(ident, setup) --- local n = Packet.decode(st, buf, offset, size) -- frames now in st.out[ch][1 .. n]; -1 = not an audio packet --- Packet.reset(st) -- forget the overlap (after a seek / a gap) --- local bs = Packet.blocksize(st, buf, offset, size) -- the packet's block size (0 = not audio), header bits only --- Never throws: a damaged packet decodes as far as its bits go (the spec's end-of-packet rule) or returns -1. +-- 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") @@ -51756,16 +50763,16 @@ type State = { n1: number, setup: Setup.Setup, plans: { [number]: Mdct.Plan }, - slopes: { [number]: { number } }, -- rising half-window of overlap length L (= blocksize / 2) - spec: { { number } }, -- per channel: n/2 spectral values (residue, then times the floor) - frame: { { number } }, -- per channel: n windowed time samples - tail: { { number } }, -- per channel: the previous frame from its centre on + slopes: { [number]: { number } }, + spec: { { number } }, + frame: { { number } }, + tail: { { number } }, tailLen: number, - prevN: number, -- the previous block size, 0 = no previous frame - out: { { number } }, -- per channel: the returned samples + prevN: number, + out: { { number } }, finalY: { { number } }, step2: { number }, - inter: { number }, -- residue type 2 interleaved scratch + inter: { number }, zero: { boolean }, reallyZero: { boolean }, partClass: { { { number } } }, @@ -51826,7 +50833,6 @@ end st.tailLen = 0 end --- blocksize(st, buf, off, size) -> the block size of an audio packet (0 if not audio) @native function Packet.blocksize(st: State, b: buffer, off: number, size: number): number if size < 1 then return 0 @@ -51843,7 +50849,6 @@ end return if mode.blockflag == 1 then st.n1 else st.n0 end --- ------------------------------------------------------------------------------------------------ floor 1 @native local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number local dy = y1 - y0 local adx = x1 - x0 @@ -51880,7 +50885,6 @@ end end end --- decode the floor of one channel into finalY (-1 = unused point); false = this channel is silent @native local function floorDecode(st: State, br: Codebook.Br, g: Setup.Floor1, finalY: { number }): boolean if bits(br, 1) == 0 then return false @@ -51984,8 +50988,6 @@ end end end --- ------------------------------------------------------------------------------------------------ residue --- add the vectors of one partition to target at offset (0-based) .. offset + psize (bounded by limit) @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 @@ -52029,7 +51031,6 @@ end return true end --- decode residue r for the channels `targets` (nil = do not decode) of length n2 each @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 @@ -52099,7 +51100,6 @@ end classSet += 1 end end - -- de-interleave into the channels that are decoded for j = 1, ch do local t = targets[j] if t then @@ -52153,8 +51153,6 @@ end end end --- ------------------------------------------------------------------------------------------------ packet --- decode(st, buf, off, size) -> frames returned in st.out (0 for the first packet), -1 for a non-audio / bad packet @native function Packet.decode(st: State, b: buffer, off: number, size: number): number if size < 1 then return -1 @@ -52196,7 +51194,6 @@ end local map = setup.mappings[mode.mapping + 1] local ch = st.channels local spec, zero, reallyZero = st.spec, st.zero, st.reallyZero - -- floors for c = 1, ch do local s = map.mux[c] + 1 local g = setup.floors[map.submapFloor[s] + 1] @@ -52211,7 +51208,6 @@ end zero[m], zero[a] = false, false end end - -- residues, per submap for i = 1, map.submaps do local targets: { { number } | false } = {} local k = 0 @@ -52223,7 +51219,6 @@ end end residue(st, br, setup.residues[map.submapResidue[i] + 1], targets, k, n2) end - -- inverse coupling 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 @@ -52245,7 +51240,6 @@ end m[j], a[j] = m2, a2 end end - -- floor curves, IMDCT, windows local plan = st.plans[n] local lslope = st.slopes[leftEnd - leftStart] local rslope = st.slopes[rightEnd - rightStart] @@ -52295,7 +51289,6 @@ end end end end - -- the new tail: this frame from its centre to the end of its window local tl = rightEnd - n2 for c = 1, ch do local tail, fr = st.tail[c], st.frame[c] @@ -52313,11 +51306,9 @@ end __FILES["codecs/audio/Vorbis/Setup"] = @native function() --- codecs/audio/Vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2): identification (channels, rate, --- bitrates, blocksizes), comment (vendor + user comments -> tags) and setup (codebooks, floors, residues, mappings, --- modes). Ported from stb_vorbis 1.22 start_decoder (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). --- Floor 0 is rejected as unsupported, as stb_vorbis does (no encoder has produced it since 2000). --- Never throws: every parser returns nil, message on bad data. +-- 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 = {} @@ -52337,16 +51328,16 @@ type Ident = { type Floor1 = { partitions: number, - partitionClass: { number }, -- 1-based list of class numbers (0-based values) - classDims: { number }, -- [class + 1] + partitionClass: { number }, + classDims: { number }, classSubs: { number }, classMaster: { number }, - subBooks: { { number } }, -- [class + 1][sub + 1] = book (0-based) or -1 + subBooks: { { number } }, multiplier: number, - xlist: { number }, -- [j + 1] + xlist: { number }, values: number, - sorted: { number }, -- point indices (0-based) by increasing x - low: { number }, -- neighbours, [j + 1] (0-based indices) + sorted: { number }, + low: { number }, high: { number }, } @@ -52357,16 +51348,16 @@ type Residue = { partSize: number, classifications: number, classbook: number, - books: { { number } }, -- [class + 1][pass + 1] = book or -1 - classdata: { { number } }, -- [classbook entry + 1][k + 1] = class + books: { { number } }, + classdata: { { number } }, } type Mapping = { submaps: number, couplingSteps: number, - magnitude: { number }, -- [step + 1] channel (0-based) + magnitude: { number }, angle: { number }, - mux: { number }, -- [channel + 1] submap (0-based) + mux: { number }, submapFloor: { number }, submapResidue: { number }, } @@ -52388,7 +51379,6 @@ type Setup = { end Setup.isVorbis = isVorbis --- ident(buf, offset, size) -> Ident | nil, message @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" @@ -52424,7 +51414,6 @@ Setup.isVorbis = isVorbis nil end --- comment(buf, offset, size) -> vendor, { "KEY=value" } | nil, message @native function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?) if not isVorbis(b, o, n, 3) then return nil, nil @@ -52461,14 +51450,12 @@ end return vendor, list end --- setup(buf, offset, size, ident) -> Setup | nil, message @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 - -- codebooks local books: { Codebook.Book } = {} local nbooks = bits(br, 8) + 1 for i = 1, nbooks do @@ -52485,7 +51472,6 @@ end return nil, "bad time domain transform" end end - -- floors local floors: { Floor1 } = {} local maxValues = 0 local nfloors = bits(br, 6) + 1 @@ -52585,7 +51571,6 @@ end maxValues = values end end - -- residues local residues: { Residue } = {} local nres = bits(br, 6) + 1 for i = 1, nres do @@ -52654,7 +51639,6 @@ end classdata = classdata, } end - -- mappings local mappings: { Mapping } = {} local nmaps = bits(br, 6) + 1 local chBits = ilog(channels - 1) @@ -52709,7 +51693,6 @@ end submapResidue = sr, } end - -- modes local modes: { Mode } = {} local nmodes = bits(br, 6) + 1 for i = 1, nmodes do @@ -52743,8 +51726,8 @@ 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). 256 values, index = floor value (1-based here). +-- 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, @@ -52782,34 +51765,23 @@ return table.freeze({ end __FILES["codecs/audio/VorbisComment"] = function() --- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. --- Tag keys are lower case everywhere in rosetta (the same names ID3 / MP4 / RIFF INFO map to): title, artist, --- album, albumartist, date, genre, track, tracktotal, disc, disctotal, comment, composer, ...; TRACKNUMBER becomes --- track, DISCNUMBER disc, DESCRIPTION comment, other fields their lower-cased name. Repeated fields are joined with --- "; " in tags; the raw fields stay available (decoders put them in meta.source.comments). Shared so the three --- formats read and write tags the same way. Never throws. --- --- local tags, raw = VorbisComment.tags({ "TITLE=x", "TRACKNUMBER=3" }) -- { title = "x", track = "3" }, raw list --- local fields = VorbisComment.fields(tags) -- sorted { "TITLE=x", "TRACKNUMBER=3" } +-- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value"; Vorbis, Opus, FLAC) <-> Types.Tags. local VorbisComment = {} -type Field = { key: string, value: string } -- key as written (upper-cased), value +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" } --- tagKey(fieldName) -> the Types.Tags key function VorbisComment.tagKey(name: string): string local k = string.lower(name) return TO_TAG[k] or k end --- fieldName(tagKey) -> the Vorbis comment field name function VorbisComment.fieldName(key: string): string return TO_FIELD[key] or string.upper(key) end --- tags(list of "KEY=value") -> Types.Tags, { Field } (entries without "=" are skipped) function VorbisComment.tags(comments: { string }): ({ [string]: string }, { Field }) local tags: { [string]: string } = {} local raw: { Field } = {} @@ -52826,7 +51798,6 @@ function VorbisComment.tags(comments: { string }): ({ [string]: string }, { Fiel return tags, raw end --- fields(tags) -> "KEY=value" strings in key order (string keys and values only) function VorbisComment.fields(tags: { [any]: any }): { string } local keys = {} for k, v in tags do @@ -52846,20 +51817,9 @@ 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). A codec --- (layer 3). Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt); the hot code is in --- codecs/audio/WavPack/Block. Lossless and hybrid (lossy, and lossless with the .wvc correction blocks), integer 8 - 32 --- bit (with the extended int32 modes) and 32-bit float, mono / stereo / multichannel (one block per mono or stereo --- stream, INITIAL .. FINAL), every decorrelation pass (terms 1 - 8, 17, 18, -1 .. -3), joint stereo, cross --- decorrelation, noise shaping, block CRCs and block checksums. Not supported: DSD, pre-4.0 streams (version < 0x402). --- --- local h, err = WavPack.header(buf, at, limit) -- the 32-byte block header at `at` (nil, message if none) --- local info, err = WavPack.info(buf, at, limit) -- stream facts from the first audio block (channels, rate, ...) --- local dec = WavPack.decoder(info.channels) --- local frames, err = dec:frame(buf, blocks, cbuf?, cblocks?) -- blocks = { offset, ... } of one frame (+ wvc) --- -- dec.pcm: interleaved samples (integers in the container range, or float values), WAV channel order --- --- Never throws: bad data returns nil, Err. +-- 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") @@ -52879,7 +51839,6 @@ local RATES = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 4410 WavPack.MONO, WavPack.HYBRID, WavPack.FLOAT, WavPack.INITIAL, WavPack.FINAL = 4, 8, 0x80, 0x800, 0x1000 WavPack.DSD = 0x80000000 --- header(buf, at, limit?) -> Header | nil, message: a valid "wvpk" block header at byte `at` whose block ends by limit 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 @@ -52917,15 +51876,14 @@ type Info = { channels: number, channelMask: number, sampleRate: number, - bitsPerSample: number, -- the source depth (container bytes * 8 - shift) - bytesPerSample: number, -- the container: 1 .. 4 + bitsPerSample: number, + bytesPerSample: number, float: boolean, hybrid: boolean, - md5: string?, -- 32 hex digits when stored + md5: string?, version: number, } --- info(buf, at, limit?) -> Info | nil, Err: the facts of the stream whose first audio block is at `at` function WavPack.info(buf: buffer, at: number, limit: number?): (Info?, Err.Err?) local h, herr = WavPack.header(buf, at, limit) if not h then @@ -52993,7 +51951,6 @@ function WavPack.info(buf: buffer, at: number, limit: number?): (Info?, Err.Err? return info, nil end --- md5(buf, at, limit?) -> 32 hex digits | nil: an ID_MD5_CHECKSUM in the block at `at` function WavPack.md5(buf: buffer, at: number, limit: number?): string? local h = WavPack.header(buf, at, limit) if not h then @@ -53014,16 +51971,13 @@ function WavPack.md5(buf: buffer, at: number, limit: number?): string? return table.concat(hex) end --- ------------------------------------------------------------------------------------------------ decoder type Decoder = { channels: number, - pcm: { number }, -- the last frame's samples, interleaved (integers in the container range, or floats) + pcm: { number }, frame: (self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?) -> (number?, Err.Err?), state: Block.State, } --- frame(buf, blocks, cbuf?, cblocks?) -> frames | nil, Err: decode one frame (the blocks of one sample range, one per --- mono / stereo stream, in channel order) into dec.pcm; cblocks are the matching .wvc blocks (hybrid lossless) local function frame(self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?): (number?, Err.Err?) local C = self.channels local n = -1 @@ -53069,7 +52023,6 @@ local function frame(self: Decoder, buf: buffer, blocks: { number }, cbuf: buffe return n, nil end --- decoder(channels) -> Decoder function WavPack.decoder(channels: number): Decoder return { channels = channels, @@ -53088,13 +52041,9 @@ __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 (the decorrelation passes, joint --- stereo, the hybrid lossy and hybrid lossless (+ wvc) paths with noise shaping and cross decorrelation, fixup_samples), --- read_words.c (the median-adaptive entropy decoder: get_words_lossless, get_word, read_code), unpack_floats.c, --- decorr_utils.c / entropy_utils.c (the metadata) and open_utils.c (metadata parsing, the block checksum). The block --- CRC (and the wvx CRC) is checked. Not ported: DSD blocks (UNSUPPORTED), pre-4.0 streams, the lossy "mute" heuristics. --- Never throws: returns nil, message. +-- 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 @@ -53106,11 +52055,10 @@ local sign, clamp = math.sign, math.clamp local Block = {} local TWO32 = 4294967296 -local P2: { number } = table.create(34, 0) -- P2[k + 1] = 2^k +local P2: { number } = table.create(34, 0) for i = 0, 33 do P2[i + 1] = 2 ^ i end --- ONES[b + 1]: the number of trailing 1 bits of the byte b local ONES: { number } = table.create(256, 0) for b = 0, 255 do local n, v = 0, b @@ -53121,18 +52069,15 @@ for b = 0, 255 do ONES[b + 1] = n end --- header flags 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 -- per block +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 --- ------------------------------------------------------------------------------------------------ metadata type Meta = { [number]: number } -- id -> offset; id + 256 -> byte length --- meta(buf, p, size) -> Meta | nil, message: the metadata sub-blocks of the block at p (header included in size) @native function Block.meta(buf: buffer, p: number, size: number): (Meta?, string?) local m: Meta = {} local q, stop = p + 32, p + size @@ -53167,7 +52112,6 @@ type Meta = { [number]: number } -- id -> offset; id + 256 -> byte length return m, nil end --- checksum(buf, p, size, m) -> true | false: the ID_BLOCK_CHECKSUM (when there is one) matches @native function Block.checksum(buf: buffer, p: number, m: Meta): boolean local o = m[0x2F] if not o then @@ -53189,7 +52133,6 @@ end return readu16(buf, o) == band(csum, 0xFFFF) end --- ------------------------------------------------------------------------------------------------ state type Reader = { b: buffer, p: number, e: number, n: number } type State = { [string]: any } @@ -53217,7 +52160,6 @@ type State = { [string]: any } } end --- open a bitstream: the bytes [o, o + len) copied with PAD zero bytes after them @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) @@ -53230,8 +52172,6 @@ end R.n = len + PAD end --- ------------------------------------------------------------------------------------------------ bit reading --- bits(R, n) -> the next n (<= 32) bits, LSB first @native local function bits(R: Reader, n: number): number if n <= 0 then return 0 @@ -53239,7 +52179,7 @@ end local p = R.p local byte = rshift(p, 3) if byte + 8 > R.n then - R.p = R.e + 1 -- overrun: the caller's end check fails + R.p = R.e + 1 return 0 end local b = R.b @@ -53257,8 +52197,6 @@ end return bits(R, 1) end --- trailing(R, max) -> the number of 1 bits from the read position (up to max; a byte at a time), consumed with the 0 --- after them when fewer than max @native local function trailing(R: Reader, max: number): number local c = 0 while c < max do @@ -53280,7 +52218,6 @@ end c += 8 R.p = p + 8 end - -- (max reached inside a run of 8: give back the extra ones) R.p -= c - max return max end @@ -53297,7 +52234,7 @@ end return bits(R, c - 1) + P2[c] end --- readCode(R, maxcode) -> 0 .. maxcode (read_code) +-- 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 @@ -53327,16 +52264,13 @@ end return c end --- ------------------------------------------------------------------------------------------------ lossless entropy --- wordsLossless(st, n, stereo) -> true | nil: n samples (n * 2 when stereo) into st.W from the data index (the hot --- loop of get_words_lossless, with the bit reader in locals) +-- 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 - -- (a0, a1, a2): the current channel's medians, (c0, c1, c2) the other's; swapped every sample when stereo 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 @@ -53495,7 +52429,6 @@ end return pos <= lim end --- ------------------------------------------------------------------------------------------------ hybrid entropy @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 @@ -53535,7 +52468,7 @@ end end end --- getWord(st, chan, flags, mono) -> value, correction | nil (get_word; chan 0 / 1) +-- 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 @@ -53651,7 +52584,6 @@ end return if sign == 1 then -mid - 1 else mid, correction end --- ------------------------------------------------------------------------------------------------ decorrelation -- 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 @@ -53766,7 +52698,6 @@ end end end --- ------------------------------------------------------------------------------------------------ hybrid lossless @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 @@ -53959,7 +52890,6 @@ end return true end --- ------------------------------------------------------------------------------------------------ metadata -> state @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] @@ -54145,8 +53075,7 @@ end return nil end --- ------------------------------------------------------------------------------------------------ fixup + output --- the float conversion of one value (float_values; R = the wvx stream or nil) +-- 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 @@ -54247,7 +53176,7 @@ end return readf32(sc, 0) end --- emit: fixup_samples + false stereo + interleave into P (stride C, first channel c0 0-based) +-- 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 @@ -54350,7 +53279,6 @@ end end end end - -- interleave if s == 2 then if c0 == 0 and C == 2 then for k = 0, count - 1 do @@ -54383,9 +53311,6 @@ end end end --- ------------------------------------------------------------------------------------------------ decode --- decode(st, buf, p, size, P, c0, C, cbuf?, cp?, csize?) -> channels written (1 / 2) | nil, message: the block at p --- (header included in size) into P (interleaved, stride C, from channel c0), with its correction block if given @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) @@ -54419,7 +53344,6 @@ end cm, cb, hasC = cmeta, cbuf, true crcWant = readu32(cbuf, cp + 28) end - -- reset st.nterms = 0 local sA, sB, wA, wB = st.sA, st.sB, st.wA, st.wB for k = 1, 128 do @@ -54455,7 +53379,6 @@ end if n == 0 then return out, nil end - -- bitstreams local o = m[0xA] if not o or m[0xA + 256] == 0 or m[0xA + 256] % 2 == 1 then return nil, "no audio bitstream" @@ -54573,13 +53496,12 @@ __FILES["codecs/audio/WavPack/Tables"] = @native function() --- codecs/audio/WavPack/Tables: the WavPack log2 / exp2 tables and the conversions built on them (wp_log2, wp_exp2s, --- restore_weight). Ported from WavPack 5.9.0 entropy_utils.c (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). +-- 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 = {} --- LOG2[x + 1], EXP2[x + 1] for x = 0 .. 255 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, @@ -54601,7 +53523,6 @@ local EXP2: { number } = { 214, 215, 216, 217, 219, 220, 221, 222, 224, 225, 226, 228, 229, 230, 232, 233, 234, 236, 237, 238, 240, 241, 242, 244, 245, 246, 248, 249, 250, 252, 253, 255, } --- exp2s(log) -> the int32 the signed log stands for (wp_exp2s) @native function Tables.exp2s(lg: number): number if lg < 0 then local v = Tables.exp2s(-lg) @@ -54614,7 +53535,6 @@ local EXP2: { number } = { return if r >= 2147483648 then r - 4294967296 else r end --- log2(v) -> wp_log2 of the uint32 v @native function Tables.log2(v: number): number v = (v + rshift(v, 9)) % 4294967296 if v < 256 then @@ -54625,7 +53545,6 @@ end return dbits * 256 + LOG2[band(rshift(v, dbits - 9), 255) + 1] end --- restoreWeight(signed byte) -> the decorrelation weight (restore_weight) @native function Tables.restoreWeight(w: number): number local r = w * 8 if r > 0 then @@ -54638,18 +53557,9 @@ return Tables end __FILES["codecs/compress/Brotli"] = function() --- codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written --- from the RFC (decoder in codecs/compress/Brotli/Decode); the static dictionary, context table and word transforms come from --- google/brotli (MIT, licenses/brotli-LICENSE.txt) through codecs/compress/Brotli/Static (tools/brotli_static.py). --- Supports every RFC 7932 stream (window sizes 10..24, metadata / uncompressed / compressed meta-blocks, the static --- dictionary with all 121 transforms) and the large-window extension (opts.largeWindow). Not supported: compression, --- shared / compound dictionaries (draft "shared brotli"). --- --- local Brotli = require("@rosetta/codecs/compress/Brotli") --- local out, consumedEnd = Brotli.decompress(buf) -- buffer | string --- local out, err = Brotli.decompress(buf, offset, length, { maxBytes = 2^24 }) --- --- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / LIMIT / UNSUPPORTED / ARG). +-- 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") @@ -54661,11 +53571,10 @@ local StaticData = __include("codecs/compress/Brotli/Static") local Brotli = {} type Options = { - maxBytes: number?, -- refuse output larger than this (default 2^30) - largeWindow: boolean?, -- accept the large-window extension (windows up to 2^30; default true) + maxBytes: number?, + largeWindow: boolean?, } --- ------------------------------------------------------------------------------------------------ static data -- 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) @@ -54673,7 +53582,6 @@ end local static: Decode.Static? = nil --- tables() -> the decoded static data (inflated once, on first use) local function tables(): (Decode.Static?, Err.Err?) if static then return static, nil @@ -54696,16 +53604,11 @@ local function tables(): (Decode.Static?, Err.Err?) return static, nil end --- dictionary() -> the 122784-byte RFC 7932 static dictionary (for tests and encoders) function Brotli.dictionary(): buffer? local s = tables() return if s then s.dictionary else nil end --- ------------------------------------------------------------------------------------------------ decompress - --- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. consumedEnd: the input offset just past --- the stream (trailing bytes are ignored). function Brotli.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = Bytes.span("Brotli.decompress", buf, offset, length) if not b then @@ -54743,18 +53646,9 @@ __FILES["codecs/compress/Brotli/Decode"] = @native function() --- codecs/compress/Brotli/Decode: a Brotli (RFC 7932) decoder over a whole in-memory stream. Written from the RFC, with the --- reference decoder (google/brotli c/dec/decode.c, MIT) as the authority on edge cases (simple prefix code alphabet --- widths, repeat codes, padding checks, the large-window extension). Supports every meta-block kind (compressed, --- uncompressed, metadata), block types / counts, the four literal context modes, context maps with RLE and inverse --- move-to-front, NPOSTFIX / NDIRECT distances, the static dictionary with all 121 transforms, window sizes 10..24 and --- large windows (10..30). The whole output is kept, so the window is only used to tell copies from dictionary words. --- --- Bits are read LSB first into a bit buffer of up to 32 bits. Prefix codes decode through tables indexed by the next --- 8 bits; entries are symbol * 32 + length (length < 16), or a link offset * 32 + 16 + subtable bits. --- --- Nothing here throws: every buffer access is checked or in range by construction (the output buffer is sized for each --- meta-block before it is decoded); bad data returns nil, message. +-- 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 @@ -54769,7 +53663,6 @@ type Static = { transforms: { number }, -- 121 x (prefix id, type, suffix id) } --- ------------------------------------------------------------------------------------------------ constants 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 } @@ -54796,7 +53689,6 @@ end local NTRANSFORMS = 121 local MAX_ALLOWED_DISTANCE = 0x7FFFFFFC --- 8-bit reversal local REV8 = bcreate(256) for i = 0, 255 do local r, v = 0, i @@ -54807,19 +53699,15 @@ for i = 0, 255 do writeu8(REV8, i, r) end @native local function reverse(code: number, len: number): number - -- len <= 15 local r = readu8(REV8, band(code, 255)) * 256 + readu8(REV8, band(rshift(code, 8), 255)) return rshift(r, 16 - len) end --- ------------------------------------------------------------------------------------------------ prefix tables local count = table.create(16, 0) local nextc = table.create(16, 0) local subBits = table.create(256, 0) local subOff = table.create(256, 0) --- tableSize(lens, n) -> the entries build() will write (256 + subtables), or -1 for an over-subscribed set. --- Also leaves count / nextc / subBits ready for build(). @native local function prepare(lens: buffer, n: number): number for l = 1, 16 do count[l] = 0 @@ -54877,7 +53765,6 @@ local subOff = table.create(256, 0) return size end --- build(lens, n, T, at): the table prepared by prepare() at entry offset `at` of T (T must have room) @native local function build(lens: buffer, n: number, T: buffer, at: number) local single = -1 local used = 0 @@ -54930,8 +53817,7 @@ end end end --- the largest distance alphabet whose distances stay under MAX_ALLOWED_DISTANCE (large windows); after the reference --- decoder's BrotliCalculateDistanceCodeLimit +-- 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 @@ -54955,8 +53841,6 @@ end return bor(lshift(group, npostfix), postfix) + ndirect + 16 + 1 end --- ------------------------------------------------------------------------------------------------ decoder --- decompress(src, off, len, maxBytes, S, largeWindow) -> out, n, consumedEnd | nil, message @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 @@ -54993,7 +53877,6 @@ end return (ip - lim) * 8 > bc end - -- prefix tables of the current meta-block: T (u32 entries), tpos entries used local T = bcreate(4096 * 4) local tpos = 0 local LENS = bcreate(1128) @@ -55015,7 +53898,6 @@ end return rshift(e, 5) end - -- install(n) -> base: the table for LENS[0 .. n - 1] appended to T, or -1 @native local function install(n: number): number local size = prepare(LENS, n) if size < 0 then @@ -55033,7 +53915,6 @@ end return base end - -- readCode(alphabetMax, limit) -> table base | -1 (corrupt) @native local function readCode(alphabetMax: number, limit: number): number bfill(LENS, 0, 0, limit) local hskip = bits(2) @@ -55189,7 +54070,6 @@ end return BL_OFF[code + 1] + bits(BL_BITS[code + 1]) end - -- readContextMap(size) -> ntrees, map buffer | -1 @native local function readContextMap(size: number): (number, buffer) local ntrees = varLen8() + 1 local map = bcreate(size) @@ -55217,7 +54097,7 @@ end if i + reps > size then return -1, map end - i += reps -- zeros (map is zero-filled) + i += reps end if overrun() then return -1, map @@ -55241,7 +54121,7 @@ end return ntrees, map end - -- ------------------------------------------------------------------ stream header + -- RFC 7932 9.1: stream header fill() local wbits local large = false @@ -55287,7 +54167,7 @@ end local d0, d1, d2, d3 = 4, 11, 15, 16 while true do - -- ---------------------------------------------------------------- meta-block header + -- RFC 7932 9.2: meta-block header if overrun() then return nil, "truncated stream" end @@ -55368,7 +54248,7 @@ end continue end - -- ---------------------------------------------------------------- compressed meta-block + -- 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 @@ -55415,7 +54295,6 @@ end if ntreesD < 0 then return nil, "bad distance context map" end - -- the tree groups local litBase = table.create(ntreesL, 0) for i = 1, ntreesL do local b = readCode(256, 256) @@ -55445,7 +54324,6 @@ end if overrun() then return nil, "truncated meta-block header" end - -- context map slices resolved to table bases local litMap = table.create(64 * nbtL, 0) for i = 0, 64 * nbtL - 1 do litMap[i + 1] = litBase[readu8(cmapL, i) + 1] @@ -55455,7 +54333,6 @@ end distMap[i + 1] = distBase[readu8(cmapD, i) + 1] end - -- block state: current type, previous type local typeL, prevL = 0, 1 local typeI, prevI = 0, 1 local typeD, prevD = 0, 1 @@ -55469,7 +54346,6 @@ end if ip > lim + 4 then return nil, "truncated stream" end - -- command block switch if cntI == 0 then local t = decodeSym(btTreeI) if t == 1 then @@ -55501,7 +54377,6 @@ end if ce > 0 then cpyLen += bits(ce) end - -- literals if insLen > remaining then return nil, "insert past the meta-block end" end @@ -55557,7 +54432,6 @@ end break end end - -- distance local dist local push = true if cell < 2 then @@ -56607,16 +55481,8 @@ return { 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). A codec --- (layer 3): archive/bz2 and tar.bz2 build on it. Written from the format description (no third-party code). --- Supports: block sizes 1..9, every Huffman group layout, block and stream CRCs, concatenated streams (as bzip2 -d). --- Not supported: randomised blocks (bzip2 0.9.0 and older; Err.UNSUPPORTED), compression. --- --- local Bzip2 = require("@rosetta/codecs/compress/Bzip2") --- local out, consumedEnd = Bzip2.decompress(buf) -- | nil, Err --- local out = Bzip2.decompress(buf, offset, length, { maxBytes = 2^24 }) --- --- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / LIMIT / ARG). +-- 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") @@ -56624,10 +55490,9 @@ local Decode = __include("codecs/compress/Bzip2/Decode") local Bzip2 = {} type Options = { - maxBytes: number?, -- refuse output larger than this (default 2^30) + maxBytes: number?, } --- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length) if not b then @@ -56649,7 +55514,6 @@ function Bzip2.decompress(buf: buffer | string, offset: number?, length: number? return res, consumed end --- crc(buf, offset?, length?) -> the CRC-32/BZIP2 of a range (the block CRC bzip2 stores) function Bzip2.crc(buf: buffer, offset: number?, length: number?): number local CT = Decode.crcTable local o = offset or 0 @@ -56667,16 +55531,9 @@ __FILES["codecs/compress/Bzip2/Decode"] = @native function() --- codecs/compress/Bzip2/Decode: bzip2 stream decoder (Julian Seward's format, as documented by the bzip2 1.0.x sources and --- Joe Tsai's "bzip2 format specification"). Written from the format description; no third-party code. --- Per block: MSB-first bit reader on a local 32-bit bit buffer, Huffman groups (10-bit lookup + canonical fallback for --- codes up to 20 bits), MTF + RUNA/RUNB, inverse BWT through one u32 vector (byte in the low 8 bits, next index --- above), RLE1 undo with the block CRC (CRC-32/BZIP2, MSB first) computed on the way out; the combined stream CRC is --- checked at the end-of-stream marker. Concatenated streams are decoded one after the other. --- Not supported: randomised blocks (written only by bzip2 0.9.0 and older). --- --- Never throws: every buffer access is in range by construction; failures return nil, message, kind --- ("truncated" | "corrupt" | "checksum" | "limit" | "unsupported"). +-- 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 @@ -56693,25 +55550,23 @@ for i = 0, 32 do MASK[i + 1] = if i == 32 then 0xFFFFFFFF else 2 ^ i - 1 end -local PBITS = 10 -- primary lookup width +local PBITS = 10 local PSIZE = 1024 local MAXGROUPS = 6 local MAXALPHA = 258 local MAXLEN = 20 --- scratch tables, reused across calls (single-threaded) -local LOOK = bcreate(MAXGROUPS * PSIZE * 4) -- per group: sym * 32 + len (len <= PBITS), 0 = longer code / none +local LOOK = bcreate(MAXGROUPS * PSIZE * 4) local LENS = bcreate(MAXGROUPS * MAXALPHA) -local PERM = table.create(MAXGROUPS * MAXALPHA, 0) -- per group: symbols in canonical order -local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- first code of each length +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) -- index into PERM of the first symbol of each length +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) --- build group g's tables from LENS[g*MAXALPHA .. + n): false when over-subscribed @native local function buildGroup(g: number, n: number): boolean local lbase = g * MAXALPHA local cbase = g * (MAXLEN + 1) @@ -56740,7 +55595,6 @@ local SEQ = table.create(256, 0) end code *= 2 end - -- perm + lookup local pbase = g * MAXALPHA local tbase = g * PSIZE * 4 bfill(LOOK, tbase, 0, PSIZE * 4) @@ -56772,11 +55626,10 @@ end return nb end --- decode(b, o, e, maxBytes) -> out, n, consumedEnd | nil, message, kind @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 -- next input byte (may run past e: zeros are fed, and the overrun is detected) + local p = o local bb, bc = 0, 0 local tt: buffer? = nil local ttSize = 0 @@ -57043,7 +55896,6 @@ end bc -= band(ent, 31) sym = rshift(ent, 5) else - -- a code longer than PBITS: canonical search local v = band(rshift(bb, bc - gmax), MASK[gmax + 1]) sym = -1 for l = PBITS + 1, gmax do @@ -57108,7 +55960,6 @@ end return nil, "bad BWT origin pointer", "corrupt" end - -- inverse BWT: T[pos] |= i << 8 at each byte's sorted position local sum = 0 for i = 0, 255 do local c = CFTAB[i + 1] @@ -57122,7 +55973,6 @@ end writeu32(T, k * 4, bor(readu32(T, k * 4), lshift(i, 8))) end - -- walk, undo RLE1, CRC if op + nblock + 4096 > blen(out) then out = grow(out, op, op + nblock + 4096) end @@ -57195,21 +56045,8 @@ return Decode end __FILES["codecs/compress/Deflate"] = function() --- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. --- A codec (layer 1), not a format: png, zip, gzip, woff, tiff, ... build on it. Absorbed from deflate-luau 1.0.0 --- (same author; no third-party code); the compressor is new. --- --- local Deflate = require("@rosetta/codecs/compress/Deflate") --- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err --- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known --- local out, err = Deflate.inflate(buf, off, len, size, dict) -- with a preset dictionary --- local out, err = Deflate.mszip(buf, { { offset, length, size }, ... }) -- MSZIP blocks ("CK" + deflate, chained) --- local out, err = Deflate.zlib(buf) -- checks the Adler-32 --- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members --- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip --- local head = Deflate.peek(buf, nil, nil, 512) -- the first 512 inflated bytes of gzip / zlib / raw --- --- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG). +-- 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") @@ -57238,11 +56075,6 @@ local function inflateErr(msg: string, at: number?): Err.Err return Err.new(code, "inflate: " .. msg, at) end --- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate. --- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream --- that inflates to a different size is an error. consumedEnd is the input offset just past the final block. --- dict: a preset dictionary (up to 32 KB of data before the stream, as MSZIP's previous block): back references may --- reach into it; the result holds only the new bytes. 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 @@ -57278,7 +56110,6 @@ function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, return shrink(out, n), consumed end --- zlib(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err 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 @@ -57312,7 +56143,6 @@ function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, ex return out, consumed + 4 end --- gzipBody(b, p, e) -> the offset of a gzip member's deflate data (past FEXTRA / FNAME / FCOMMENT / FHCRC) | nil, Err local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?) local flg = buffer.readu8(b, p + 3) if flg >= 0x20 then @@ -57342,8 +56172,6 @@ local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?) return q, nil end --- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is --- not another gzip member (zero padding, garbage) is ignored, as gzip -d does. 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 @@ -57390,7 +56218,6 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): table.insert(parts, out) total += buffer.len(out) p = consumed + 8 - -- skip zero padding local z = p while z < e and buffer.readu8(b, z) == 0 do z += 1 @@ -57411,9 +56238,6 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): return res, nil end --- peek(buf, offset?, length?, n) -> buffer | nil, Err: the first n bytes (fewer when the stream is shorter, or up to --- 258 fewer at a match boundary) a gzip member, zlib stream or raw deflate stream inflates to, without inflating --- the rest or checking checksums: for sniffing compressed files cheaply. 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 @@ -57444,7 +56268,7 @@ function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n: end type CompressOptions = { - level: number?, -- 0 (stored) .. 9 (best); default 6 + level: number?, } local function level(opts: CompressOptions?): number? @@ -57455,7 +56279,6 @@ local function level(opts: CompressOptions?): number? return lv end --- compress(buf, opts?) -> raw deflate buffer | nil, Err function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) local b = toBuffer(buf) local lv = level(opts) @@ -57465,7 +56288,6 @@ function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer return Compress.raw(b, 0, buffer.len(b), lv), nil end --- zlibCompress(buf, opts?) -> zlib stream | nil, Err function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) local b = toBuffer(buf) local lv = level(opts) @@ -57486,7 +56308,6 @@ function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (bu return out, nil end --- gzip(buf, opts?) -> gzip member (no name, mtime 0) | nil, Err function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) local b = toBuffer(buf) local lv = level(opts) @@ -57505,10 +56326,8 @@ function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, E return out, nil end --- mszip(buf, blocks) -> buffer | nil, Err: MSZIP data (Microsoft's blocked deflate, as in CAB folders and DirectX .x --- files): blocks = { { offset, length, size } }, each buf[offset, offset + length) = "CK" + a raw deflate stream that --- inflates to exactly size bytes using the previous block's output (up to 32 KB) as its dictionary. Returns the --- blocks' output concatenated. +-- 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 @@ -57539,7 +56358,6 @@ function Deflate.mszip(buf: buffer, blocks: { { offset: number, length: number, return out, nil end --- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of) 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) @@ -57555,11 +56373,8 @@ __FILES["codecs/compress/Deflate/Compress"] = @native function() --- codecs/compress/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth --- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (codecs/entropy/Huffman --- length-limited codes). Level 0 = stored blocks only. --- --- raw(buf, off, len, level) -> buffer. Never throws (the caller validated the arguments). +-- 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 @@ -57569,11 +56384,10 @@ local floor = math.floor local WSIZE = 32768 local HSIZE = 65536 local MAXMATCH = 258 -local BLOCKSYMS = 16384 -- symbols per block +local BLOCKSYMS = 16384 --- per level (zlib's configuration_table): GOOD = a match this long 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 (no lazy matching). +-- 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 } @@ -57620,14 +56434,12 @@ end local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } --- fixed codes 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) --- reversed (LSB-first) canonical codes for lengths @native local function revCodes(lens: { number }): { number } local codes = Huffman.codes(lens) for i, l in lens do @@ -57645,7 +56457,6 @@ for i = 0, 32 do POW[i + 1] = 2 ^ i end --- ------------------------------------------------------------------------------------------------ bit output type Out = { buf: buffer, op: number, acc: number, cnt: number } @native local function ensure(o: Out, n: number) @@ -57656,7 +56467,6 @@ type Out = { buf: buffer, op: number, acc: number, cnt: number } end end --- put(v, n): n <= 24 bits, LSB first @native local function put(o: Out, v: number, n: number) local acc = o.acc + v * POW[o.cnt + 1] local cnt = o.cnt + n @@ -57681,8 +56491,6 @@ end end end --- ------------------------------------------------------------------------------------------------ blocks --- syms: L[i] = literal 0..255 or 256 + match length; D[i] = distance (0 for literals) @native local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean) local p = s repeat @@ -57763,7 +56571,7 @@ end for i = 1, hdist do all[hlit + i] = dlen[i] end - local cs, cx = {}, {} -- symbol, extra value + local cs, cx = {}, {} local cf = table.create(19, 0) local i = 1 local total = hlit + hdist @@ -57806,7 +56614,6 @@ end while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do hclen -= 1 end - -- costs in bits local dyn = 17 + 3 * hclen + extra for k = 1, 19 do dyn += cf[k] * clen[k] @@ -57853,7 +56660,6 @@ end emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen) end --- ------------------------------------------------------------------------------------------------ LZ77 local Compress = {} @native function Compress.raw(src: buffer, off: number, len: number, level: number): buffer @@ -57890,7 +56696,6 @@ local Compress = {} prev[p % WSIZE + 1] = head[h] head[h] = p end - -- longest match at p among earlier positions: len (0 if < 3), dist @native local function find(p: number, steps: number): (number, number) local maxLen = math.min(MAXMATCH, e - p) if maxLen < 3 then @@ -57914,7 +56719,7 @@ local Compress = {} end local nc = prev[c % WSIZE + 1] if nc >= c then - break -- the slot was reused by a newer position: the chain ends here + break end c = nc steps -= 1 @@ -57931,7 +56736,7 @@ local Compress = {} end local p = off - local stop3 = e - 3 -- positions with 3 bytes ahead can be hashed + local stop3 = e - 3 while p < e do local mlen, mdist = 0, 0 if p <= stop3 then @@ -57940,7 +56745,6 @@ local Compress = {} 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 - -- a literal now, the longer match from p + 1 nsym += 1 L[nsym] = readu8(src, p) D[nsym] = 0 @@ -57990,15 +56794,7 @@ __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); the table builder moved to codecs/entropy/Huffman, whose --- entries are symbol * 32 + length (5 length bits instead of 4). --- --- Bits are read LSB first into a 32-bit bit buffer (refilled 4 bytes at a time with one readu32 while the input --- lasts). Huffman codes decode through a codecs/entropy/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer --- code's primary slot links to a subtable, so a symbol is one or two table reads. --- --- Nothing in this module throws on any input: every buffer read and write is bounds-checked, and corrupt data --- returns nil, message. (Native code must never throw: it crashes Roblox Studio.) +-- 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 @@ -58008,7 +56804,7 @@ local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buf local LITBITS, DISTBITS, CLBITS = 10, 8, 7 local LITMASK, DISTMASK, CLMASK = 1023, 255, 127 --- length codes 257..285 and distance codes 0..29: base value, extra bits +-- 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 = { @@ -58016,15 +56812,13 @@ local DBASE = { 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 } --- the order code-length code lengths are sent in +-- 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 } --- table capacities (entries): primary + one subtable per code longer than the primary width, worst case local LITCAP = Huffman.capacity(288, LITBITS, 15) local DISTCAP = Huffman.capacity(32, DISTBITS, 15) local CLCAP = Huffman.capacity(19, CLBITS, 7) --- fixed Huffman tables local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) local FLITS: number, FDISTS: number do @@ -58041,7 +56835,6 @@ end local Inflate = {} --- Grow out (capacity cap) to hold at least need bytes. Returns the new buffer and capacity. @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) @@ -58049,12 +56842,6 @@ local Inflate = {} return nb, cap end --- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in --- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and --- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing). --- dict: a preset dictionary (the data before the stream, e.g. MSZIP's previous block): out starts with a copy of it, --- distances may reach into it, and outLen includes it (cap does not). --- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message. @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 @@ -58255,7 +57042,6 @@ end end local lsmask = lshift(1, lsub) - 1 local dsmask = lshift(1, dsub) - 1 - -- the symbol loop while true do if bitcnt < 15 then if pos + 4 <= endpos then @@ -58312,7 +57098,6 @@ end if sym > 29 then return nil, "invalid literal/length code" end - -- up to 5 length extra bits + a 15-bit distance code if bitcnt < 20 then if pos + 4 <= endpos then bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) @@ -58402,8 +57187,7 @@ end local s = op - dist if dist >= len then if len <= 16 and op + 16 <= cap then - -- straight-line 16-byte copy (the bytes past len are rewritten later): no inner loop, which - -- keeps LuaJIT's traces simple; chunks read only bytes before op or already copied ones + -- 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)) @@ -58420,7 +57204,6 @@ end bfill(out, op, readu8(out, s), len) op += len else - -- overlapping: the pattern of period dist, copied in growing non-overlapping chunks local rem = len while rem > 0 do local k = math.min(op - s, rem) @@ -58445,17 +57228,9 @@ __FILES["codecs/compress/Explode"] = @native function() --- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ --- archive sectors, old installers, some game data files). A codec (layer 3). Written after the format as documented --- by Mark Adler's blast.c (zlib licence, licenses/blast-LICENSE.txt): the same constant code tables (run-length --- coded Huffman code lengths, length bases / extra bits), the bit order (LSB first, Huffman codes inverted); the --- decoder itself is new code. --- Supports: literal coding off (raw bytes) and on (Huffman coded), 1 / 2 / 4 KB dictionaries, the end code; stops --- early at maxOut bytes (MPQ sectors whose stream has no end code). --- --- local out, err = Explode.decompress(buf, offset?, length?, maxOut?) -- buffer | nil, Err --- --- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / ARG / LIMIT). +-- 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") @@ -58477,7 +57252,6 @@ local EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 } type Code = { count: { number }, symbol: { number } } --- canonical code from run-length coded lengths @native local function construct(rep: { number }): Code local lengths: { number } = {} for _, b in rep do @@ -58508,7 +57282,6 @@ local LIT = construct(LITLEN) local LEN = construct(LENLEN) local DIST = construct(DISTLEN) --- decompress(buf, offset?, length?, maxOut?) -> buffer | nil, Err @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 @@ -58651,26 +57424,14 @@ __FILES["codecs/compress/Lz4"] = @native function() --- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder --- (the reference "fast" strategy: one 4-byte hash table, 64 KB window). A codec (layer 3): model/rbxm chunk bodies, --- and the LZ4 frame format (archive) builds on it. New code, written from the specification. Never throws. --- --- local out, err = Lz4.decompress(src, offset?, length?, outSize?, opts?) -- a block -> buffer | nil, Err --- local packed = Lz4.compress(src, offset?, length?) -- -> buffer (a block) | nil, Err --- local dEnd, msg = Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart?) -- low level (linked blocks) --- local n = Lz4.encodeInto(src, p, n, dst, d) -- low level; dst has bound(n) room --- Lz4.bound(n) -- worst-case block size for n bytes --- --- decodeInto decodes one block from src[p, limit) to dst[d, dstLimit): matches may reach back to histStart (default --- d), so a frame decoder with linked blocks keeps the previous output in front of d. It returns the output end, or --- nil and a message ("truncated", "corrupt: ...", "limit: output ...") for the caller's Err.from. +-- 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?, -- refuse output larger than this when outSize is not given (default 2^28) + maxBytes: number?, } local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32 @@ -58684,7 +57445,6 @@ local MAX_OFFSET = 65535 local HASH_BITS = 13 local HASH_SIZE = 2 ^ HASH_BITS --- ------------------------------------------------------------------------------------------------ decode @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 @@ -58757,7 +57517,6 @@ local HASH_SIZE = 2 ^ HASH_BITS buffer.fill(dst, d, readu8(dst, s), ml) d += ml else - -- an overlapping match repeats the off-byte pattern: copy what is already there, doubling each time local n = ml while n > 0 do local c = d - s @@ -58772,8 +57531,6 @@ local HASH_SIZE = 2 ^ HASH_BITS end end --- decompress(src, offset?, length?, outSize?, opts?) -> buffer | nil, Err: one block. With outSize the output must be --- exactly that long (CORRUPT otherwise); without it the output grows up to opts.maxBytes. @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 @@ -58813,13 +57570,10 @@ end end end --- ------------------------------------------------------------------------------------------------ encode --- bound(n) -> the largest block n input bytes can produce @native function Lz4.bound(n: number): number return n + n // 255 + 16 end --- writes a length's 255-run extension at o; returns the next offset @native local function extend(dst: buffer, o: number, n: number): number while n >= 255 do writeu8(dst, o, 255) @@ -58830,7 +57584,7 @@ end return o + 1 end --- hash(v) -> 1 .. HASH_SIZE: Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles +-- 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 @@ -58839,7 +57593,6 @@ end local hashTable: { number } = table.create(HASH_SIZE, -1e9) --- encodeInto(src, p, n, dst, d) -> the block's length: src[p, p + n) compressed to dst[d ..] (room for bound(n)) @native function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number local op = d local anchor = p @@ -58859,7 +57612,6 @@ local hashTable: { number } = table.create(HASH_SIZE, -1e9) local ref = ht[h] ht[h] = ip if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then - -- back over equal bytes before the match (into the pending literals) while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do ip -= 1 ref -= 1 @@ -58897,7 +57649,6 @@ local hashTable: { number } = table.create(HASH_SIZE, -1e9) ip = a anchor = ip skip = 64 - -- index the position just before the next one (better ratio at no cost) if ip - 2 >= p and ip - 2 < mflimit then local w = readu32(src, ip - 2) ht[hash(w)] = ip - 2 @@ -58908,7 +57659,6 @@ local hashTable: { number } = table.create(HASH_SIZE, -1e9) end end end - -- the last literals local lit = iend - anchor local tok = op op += 1 @@ -58925,7 +57675,6 @@ local hashTable: { number } = table.create(HASH_SIZE, -1e9) return op - d end --- compress(src, offset?, length?) -> buffer (one block) | nil, Err @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 @@ -58944,23 +57693,9 @@ __FILES["codecs/compress/Lzh"] = @native function() --- codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo: --- lh4 / lh5 / lh6 / lh7 / lhx static Huffman blocks (code-length "temp" table, 510 literal / length codes, offset --- bit-length codes); also ARJ methods 1..3 (= "lh6") and Zoo method 2 (= "lh5") --- lh1 adaptive Huffman (LHarc 1.x: 314 codes, grouped frequency tree) with fixed-length --- offset prefixes, 4 KB window --- lzs / lz5 LArc's plain LZSS (2 KB / 4 KB windows, flag bits / flag bytes) --- arj4 ARJ method 4 (unary-prefixed lengths and offsets, no Huffman) --- Every method decodes into a buffer of the known output size; the windows start filled as the original tools fill --- them (spaces; lz5's pattern), and offsets before the start of the output read that fill. --- Ported from lhasa 0.6.0 (Simon Howard, ISC licence: licenses/lhasa-LICENSE.txt): lh_new_decoder.c, lh1_decoder.c, --- lzs_decoder.c, lz5_decoder.c; the static Huffman tables are canonical codes built with codecs/entropy/Huffman instead --- of lhasa's trees. ARJ method 4 is written from the ARJ technical notes (unarj's decode_f description). --- --- local out, err = Lzh.decode(src, off, len, outSize, "lh5") -- buffer | nil, message --- --- Never throws: bad codes / truncated input return nil, message (truncated input: "truncated ..." after the bytes --- decoded so far would be useless, so nothing partial is returned). Not supported: pm0 / pm1 / pm2 (PMarc), lk7. +-- 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 = {} @@ -58969,9 +57704,6 @@ local readu8, writeu8, readu32 = buffer.readu8, buffer.writeu8, buffer.readu32 local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local floor = math.floor --- ------------------------------------------------------------------------------------------------ bit reader --- an MSB-first bit reader over src[pos, limit): acc holds cnt bits (cnt <= 32); past the end, zero bits are read and --- over counts them 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 @@ -59016,7 +57748,6 @@ end return v end --- ------------------------------------------------------------------------------------------------ static Huffman type Table = { tab: buffer, P: number, S: number, single: number } @native local function newTable(nsym: number, P: number): Table @@ -59088,7 +57819,7 @@ end writeu8(lens, i, l) if i == special then local z = bits(r, 2) - i += z -- zeros (already zero) + i += z end i += 1 end @@ -59178,7 +57909,6 @@ local OFFSET_BITS = { lh4 = 4, lh5 = 4, lh6 = 5, lh7 = 5, lhx = 5 } return nil end --- ------------------------------------------------------------------------------------------------ lh1 local NUM_CODES = 314 local NUM_NODES = NUM_CODES * 2 - 1 local REORDER = 32 * 1024 @@ -59204,7 +57934,6 @@ end @native local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: number): string? local r = reader(src, off, len) - -- node arrays (0-based indexes stored at [i + 1]) local leaf = table.create(NUM_NODES, false) local child = table.create(NUM_NODES, 0) local parent = table.create(NUM_NODES, 0) @@ -59344,7 +58073,7 @@ end end end local code = child[ni + 1] - -- increment_for_code + -- lhasa's increment_for_code if freq[1] >= REORDER then reconstruct() end @@ -59381,8 +58110,7 @@ end return nil end --- ------------------------------------------------------------------------------------------------ LArc lzs / lz5 --- the ring of a 2 KB / 4 KB window (positions are absolute ring positions, not distances) +-- 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) @@ -59492,7 +58220,6 @@ end return nil end --- ------------------------------------------------------------------------------------------------ ARJ method 4 @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 @@ -59534,10 +58261,8 @@ end return nil end --- ------------------------------------------------------------------------------------------------ api Lzh.METHODS = { "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "arj4" } --- decode(src, off, len, outSize, method) -> buffer | nil, message @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" @@ -59570,23 +58295,9 @@ return Lzh end __FILES["codecs/compress/Lzma"] = function() --- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): --- archive/xz, archive/7z (and anything else holding LZMA data) build on it. Decode only. --- Written from the LZMA specification (LzmaSpec.cpp, Igor Pavlov, public domain) and the xz file format specification --- 1.2 (Lasse Collin / Igor Pavlov, public domain); the BCJ filters follow xz-embedded (public domain). --- --- local Lzma = require("@rosetta/codecs/compress/Lzma") --- local out, e = Lzma.lzma(buf, off, len, props, unpackSize?, opts?) -- raw LZMA; props = 5-byte buffer / string --- -- or { lc, lp, pb, dictSize } --- local out, e = Lzma.lzma2(buf, off, len, dictSize?, unpackSize?, opts?) -- raw LZMA2 chunks --- local out, e = Lzma.alone(buf, off?, len?, opts?) -- a .lzma file (13-byte header) --- local out, e = Lzma.xz(buf, off?, len?, opts?) -- a .xz file (all streams concatenated) --- Lzma.filter(id, buf, off, len, props?) -- BCJ / delta decode in place (7z) --- --- Each returns buffer, consumedEnd (the input offset just past what was decoded) | nil, Err. opts.maxBytes (default --- 2^30) bounds the output (Err.LIMIT). xz: every stream, block, index and footer is parsed and checked; check types --- none / CRC-32 / CRC-64 are verified, SHA-256 is skipped (not verified). xz filters: LZMA2, delta, x86, PowerPC, --- ARM, ARM-Thumb, SPARC, ARM64; IA-64 and RISC-V are Err.UNSUPPORTED. Never throws. +-- 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") @@ -59601,7 +58312,7 @@ local Lzma = {} local DEFAULT_MAX = 2 ^ 30 type Options = { - maxBytes: number?, -- refuse output larger than this (default 2^30) + maxBytes: number?, } type Props = { lc: number, lp: number, pb: number, dictSize: number? } @@ -59613,7 +58324,6 @@ local function maxOf(opts: Options?): number return if type(m) == "number" and m >= 0 then m else DEFAULT_MAX end --- a decoder message -> Err local function fail(msg: any, at: number?): Err.Err local s = tostring(msg) local code = Err.CORRUPT @@ -59625,7 +58335,6 @@ local function fail(msg: any, at: number?): Err.Err return Err.new(code, s, at) end --- props byte -> lc, lp, pb | nil local function propsByte(d: number): (number?, number, number) if d >= 225 then return nil, 0, 0 @@ -59634,8 +58343,6 @@ local function propsByte(d: number): (number?, number, number) end Lzma.propsByte = propsByte --- ------------------------------------------------------------------------------------------------ LZMA --- decodeLzma(st, b, o, e, unpackSize?) -> consumedEnd | nil, Err: one raw LZMA stream into st (props set) 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 @@ -59658,7 +58365,6 @@ local function decodeLzma(st: Decode.State, b: buffer, o: number, e: number, unp return res :: number, nil end --- lzma(buf, offset, length, props, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err 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 @@ -59696,7 +58402,7 @@ function Lzma.lzma(buf: buffer | string, offset: number?, length: number?, props return Decode.finish(st), consumed end --- alone(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: a .lzma file (props, dict size, u64 size) +-- .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 @@ -59716,8 +58422,6 @@ function Lzma.alone(buf: buffer | string, offset: number?, length: number?, opts return Lzma.lzma(b, o + 13, l - 13, buffer.fromstring(buffer.readstring(b, o, 1)), size, opts) end --- ------------------------------------------------------------------------------------------------ LZMA2 --- decodeLzma2(st, b, o, e) -> consumedEnd | nil, Err: LZMA2 chunks up to the end-of-stream byte local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?) local p = o local needDict, needProps = true, true @@ -59805,7 +58509,6 @@ local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): ( end end --- lzma2(buf, offset?, length?, dictSize?, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err 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 @@ -59823,7 +58526,6 @@ function Lzma.lzma2(buf: buffer | string, offset: number?, length: number?, _dic return Decode.finish(st), consumed end --- ------------------------------------------------------------------------------------------------ filters -- filter ids (xz numbering; 7z's method ids map onto these in archive/7z) Lzma.FILTER = table.freeze({ delta = 0x03, @@ -59846,8 +58548,7 @@ local BCJ: { [number]: (buffer, number, number, number) -> () } = { [0x0A] = Filters.arm64, } --- filter(id, buf, offset, length, props?) -> true | nil, Err: decode a BCJ / delta filter in place. props: the --- filter's property bytes (a string or buffer: BCJ start offset u32le, delta distance - 1) +-- 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 @@ -59872,11 +58573,9 @@ function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?): return true, nil end --- ------------------------------------------------------------------------------------------------ xz 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 } --- vli(b, p, e) -> value, next | nil local function vli(b: buffer, p: number, e: number): (number?, number) local v, mul = 0, 1 for i = 0, 8 do @@ -59901,7 +58600,6 @@ local function crc(b: buffer, o: number, n: number): number return Crc32.raw(b, o, n) end --- one xz stream at o -> next offset | nil, Err (blocks appended to st) 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) @@ -60092,7 +58790,6 @@ local function xzStream(st: Decode.State, b: buffer, o: number, e: number): (num return q + 12, nil end --- xz(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: every stream (and stream padding) in the range 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 @@ -60129,7 +58826,6 @@ function Lzma.xz(buf: buffer | string, offset: number?, length: number?, opts: O return Decode.finish(st), p end --- isXz(buf, offset?) -> true when the bytes start an xz stream 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 @@ -60141,8 +58837,8 @@ __FILES["codecs/compress/Lzma/Crc64"] = @native function() --- codecs/compress/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit --- value is kept as two u32 halves (hi, lo). Written from the xz file format specification. Never throws. +-- 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 @@ -60163,7 +58859,6 @@ end local Crc64 = {} --- of(buf, offset, length) -> hi, lo @native function Crc64.of(b: buffer, o: number, n: number): (number, number) local hi, lo = 0xFFFFFFFF, 0xFFFFFFFF for i = o, o + n - 1 do @@ -60180,17 +58875,9 @@ __FILES["codecs/compress/Lzma/Decode"] = @native function() --- codecs/compress/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z). --- Written from the LZMA specification and its reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain); the --- structure (probability model layout, state transitions, distance / length decoding) follows that document. --- --- The output buffer is also the dictionary: everything decoded stays in memory, so a match may reach back to the last --- dictionary reset (st.dictStart). A decoder state (new) carries the probabilities, the LZ state, the four rep --- distances, a pending match remainder (st.remLen) and the range coder across calls, so LZMA2 can feed it chunk by --- chunk. run() decodes until st.op reaches outEnd, an end marker, or an error. --- --- Never throws: every input read is bounds-checked (a read past the end counts in `over` and fails the call as --- "truncated"), every output write is preceded by a capacity check, and errors return nil, message. +-- 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 @@ -60216,8 +58903,8 @@ local Decode = {} type State = { out: buffer, cap: number, - op: number, -- bytes decoded so far (the next write offset) - dictStart: number, -- the last dictionary reset: matches may not reach before it + op: number, + dictStart: number, maxBytes: number, probs: buffer, nprobs: number, @@ -60229,12 +58916,11 @@ type State = { rep1: number, rep2: number, rep3: number, - remLen: number, -- a match cut by outEnd, finished by the next run + remLen: number, range: number, code: number, } --- new(cap, maxBytes) -> a decoder state with an empty output buffer of capacity cap @native function Decode.new(cap: number, maxBytes: number): State local c = math.max(64, math.min(cap, maxBytes)) return { @@ -60259,7 +58945,6 @@ type State = { } end --- setProps(st, lc, lp, pb) -> ok, message?: new literal / position parameters (resets the probabilities) @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" @@ -60274,7 +58959,6 @@ end return true, nil end --- resetState(st): probabilities to 1/2, LZ state and reps to 0 @native function Decode.resetState(st: State) local p = st.probs for i = 0, st.nprobs - 1 do @@ -60285,13 +58969,11 @@ end st.remLen = 0 end --- resetDict(st): matches may no longer reach before the current position @native function Decode.resetDict(st: State) st.dictStart = st.op st.remLen = 0 end --- rcInit(st, buf, ip, iend) -> next ip | nil, message: the 5 range coder init bytes @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" @@ -60307,7 +58989,6 @@ end return ip + 5, nil end --- ensure(st, need) -> ok: grow the output to hold need bytes (bounded by maxBytes) @native local function ensure(st: State, need: number): boolean if need <= st.cap then return true @@ -60324,7 +59005,6 @@ end end Decode.ensure = ensure --- copy(st, n, b, ip): append n stored bytes (LZMA2 uncompressed chunks); the caller checked the input range @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" @@ -60334,14 +59014,12 @@ Decode.ensure = ensure return true, nil end --- the range decoder state while run() executes (module upvalues: the helpers below are created once, so LuaJIT --- traces stay valid across calls; run() is not re-entrant, and never yields) +-- 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 --- decode one bit with the probability at index i @native local function bit(i: number): number local p = i * 2 local prob = readu16(probs, p) @@ -60423,8 +59101,6 @@ end return 16 + tree(base + 258, 8) end --- run(st, buf, ip, iend, outEnd) -> status, ip | nil, message. status: "full" (st.op reached outEnd) or "eos" (end --- marker). The range coder must have been initialised (rcInit). @native function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: number): (string?, any) probs = st.probs inb = inb0 @@ -60447,7 +59123,6 @@ end local status: string? = nil local msg: string? = nil - -- a pending match from the previous call local remLen = st.remLen if remLen > 0 then local n = math.min(remLen, outEnd - op) @@ -60648,7 +59323,7 @@ end st.state = state st.rep0, st.rep1, st.rep2, st.rep3 = rep0, rep1, rep2, rep3 st.remLen = remLen - probs, inb = EMPTY, EMPTY -- do not keep the caller's buffers alive + probs, inb = EMPTY, EMPTY if msg then return nil, msg end @@ -60658,7 +59333,6 @@ end return status, ip end --- finish(st) -> a buffer of exactly the decoded bytes @native function Decode.finish(st: State): buffer if st.cap == st.op then return st.out @@ -60674,10 +59348,8 @@ __FILES["codecs/compress/Lzma/Filters"] = @native function() --- codecs/compress/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole --- decoded buffer range. Written from the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin, --- public domain): x86, ARM, ARM-Thumb, PowerPC, SPARC, ARM64 and delta. Not supported: IA-64, RISC-V. --- Never throws: every access is inside [o, o + n). +-- 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 @@ -60692,7 +59364,6 @@ local MASK_BITNUM = { [0] = 0, 1, 2, 2, 3, 3, 3, 3 } return b == 0 or b == 0xFF end --- x86(b, o, n, start): BCJ x86 decode; start = the stream position of b[o] (the filter's start offset) @native function Filters.x86(b: buffer, o: number, n: number, start: number) if n <= 4 then return @@ -60840,7 +59511,7 @@ end end end --- delta(b, o, n, dist): b[i] += b[i - dist] (1 <= dist <= 256) +-- 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)) @@ -60853,25 +59524,9 @@ __FILES["codecs/compress/Lzw"] = @native function() --- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and --- image/tiff build on it. New code (no port), written from the GIF89a spec (appendix F) and TIFF 6.0 section 13. --- gif LSB-first codes, a minimum code size 1..11 (2..8 in GIF), clear = 2^min, EOI = clear + 1, the code width --- grows when the next free code reaches 2^width (max 12 bits; a full table stays frozen until a clear). --- tiff MSB-first codes, 8-bit symbols, clear = 256, EOI = 257, "early change": the width grows one code --- earlier (next free code = 2^width - 1). Old-style (pre-6.0, LSB-first, no early change) TIFF LZW is --- detected by its first bytes (0x00 then an odd byte) and decoded too. --- zoo the gif layout with 8-bit symbols and codes up to 13 bits (Zoo archives' method 1; decode only). --- --- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "gif", minCodeSize) -- bytes written --- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "tiff") --- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "zoo") --- local codes = Lzw.encode(data, off, len, "gif", minCodeSize) -- buffer --- local codes = Lzw.encode(data, off, len, "tiff") --- --- decode writes at most maxOut bytes at out[outOff ..] and returns how many it wrote; it stops at EOI, at the end of --- the input or when out is full. err is nil for a clean stream, "truncated" when the input ended without EOI, or --- "corrupt" for an impossible code (everything decoded up to it is kept). Never throws; the caller checks that --- [outOff, outOff + maxOut) lies inside out and [off, off + len) inside src (decode clamps both anyway). +-- 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 @@ -60881,14 +59536,11 @@ local Lzw = {} local MAX_CODES = 4096 -- 12-bit codes (GIF, TIFF) local TABLE = 8192 -- the tables hold 13-bit codes (Zoo) --- per-call tables (allocated once: decode / encode are not re-entrant across coroutines, but never yield) -local prefix = buffer.create(TABLE * 2) -- u16: the code this entry extends -local suffix = buffer.create(TABLE) -- u8: its last byte -local first = buffer.create(TABLE) -- u8: its first byte -local length = buffer.create(TABLE * 2) -- u16: its length +local prefix = buffer.create(TABLE * 2) +local suffix = buffer.create(TABLE) +local first = buffer.create(TABLE) +local length = buffer.create(TABLE * 2) --- ------------------------------------------------------------------------------------------------ decode --- writes the string of code c (length l) ending at out[o + l - 1]; clipped to [o, lim) @native local function emit(out: buffer, o: number, c: number, l: number, lim: number) local p = o + l - 1 if p < lim then @@ -60919,7 +59571,7 @@ end return 0, "corrupt" end local msb = variant == "tiff" - local early = 0 -- 1 for TIFF's early change + local early = 0 local min = minCodeSize or 8 local maxCodes, maxBits = MAX_CODES, 12 if variant == "zoo" then @@ -60953,7 +59605,6 @@ end local p = off local acc, nb = 0, 0 while true do - -- refill (at most 13 + 7 bits held: below 2^21) while nb < size do if p >= e then return o - outOff, "truncated" @@ -60985,7 +59636,7 @@ end return o - outOff, nil else if o >= lim then - return o - outOff, nil -- full: the rest (normally just EOI) is ignored + return o - outOff, nil end if prev < 0 then if c >= clear then @@ -61030,13 +59681,10 @@ end end end --- ------------------------------------------------------------------------------------------------ encode -local HASH = 8192 -- open addressing over (prefix << 8 | byte) keys: a power of two above 4096 entries -local hkey = buffer.create(HASH * 4) -- i32 key + 1 (0 = empty) -local hval = buffer.create(HASH * 2) -- u16 code +local HASH = 8192 +local hkey = buffer.create(HASH * 4) +local hval = buffer.create(HASH * 2) --- encode(data, off, len, variant, minCodeSize?) -> the code stream (GIF: without the sub-block framing). Symbols in --- data must be below 2^minCodeSize (GIF; larger ones are masked) or bytes (TIFF). @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) @@ -61144,19 +59792,9 @@ __FILES["codecs/compress/Lzx"] = @native function() --- codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes, --- verbatim, aligned offset and uncompressed blocks (block sizes of 24 bits, blocks spanning frames), the main and --- length trees sent as deltas of the previous block's code lengths through a 20-symbol pre-tree (runs 17 / 18 / 19), --- the three repeated offsets R0..R2, the Intel E8 call translation header (applied to the first 32768 frames, on the --- output only), and the stream cut into frames of 32768 output bytes, each 16-bit aligned at its end; trees, offsets --- and the window persist across the frames (the CFDATA blocks) of a folder. Written from the specification --- (Microsoft's LZX data format documentation in the Cabinet SDK and the LZX sections of [MS-PATCH]); no code from --- libmspack. Not supported: LZX DELTA reference data and reset intervals (CHM / WIM variants). --- --- local out, err = Lzx.decode(src, offset, length, outSize, windowBits) -- buffer | nil, message --- --- src[offset, offset + length) is the folder's compressed data (the CFDATA payloads concatenated), outSize its exact --- uncompressed size. Never throws: bad or truncated data returns nil, message. +-- 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 @@ -61186,9 +59824,7 @@ do end local SLOTS: { [number]: number } = { [15] = 30, [16] = 32, [17] = 34, [18] = 36, [19] = 38, [20] = 42, [21] = 50 } --- ------------------------------------------------------------------------------------------------ bit reader --- 16-bit little-endian words read most significant bit first; bb holds cnt bits left aligned (cnt <= 32). Past the --- end, zero words are read and over counts their bits. +-- 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) @@ -61210,7 +59846,6 @@ type State = { src: buffer, pos: number, stop: number, bb: number, cnt: number, end end --- bits(s, n) -> the next n (1..17) bits @native local function bits(s: State, n: number): number if s.cnt < n then refill(s) @@ -61221,7 +59856,6 @@ end return v end --- sym(s, tab, P, S) -> the next symbol of an MSB Huffman table, -1 for an invalid code @native local function sym(s: State, tab: buffer, P: number, S: number): number if s.cnt < 16 then refill(s) @@ -61243,7 +59877,7 @@ end return rshift(e, 5) end --- readLens: the code lengths lens[first, last) as deltas of their previous values, through a fresh pre-tree +-- 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)) @@ -61288,8 +59922,7 @@ end return true end --- ------------------------------------------------------------------------------------------------ decode --- E8 translation of the decoded output, frame by frame (absolute call targets back to relative) +-- 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 @@ -61342,7 +59975,6 @@ end local frameEnd = math.min(op + FRAME, outSize) while op < frameEnd do if bremain == 0 then - -- a new block if btype == 3 and band(bsize, 1) == 1 then s.pos += 1 end @@ -61426,7 +60058,6 @@ end local aligned = btype == 2 local start = op while op < runEnd do - -- refill to at least 17 bits while cnt <= 16 do local w = 0 if pos + 2 <= stop then @@ -61595,18 +60226,12 @@ __FILES["codecs/compress/PackBits"] = @native function() --- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF --- ByteRun1, ...): a header byte n < 128 copies n + 1 literal bytes, n > 128 repeats the next byte 257 - n times, --- 128 is a no-op. Decode and encode; moved here from image/tiff (TIFF and PSD both carried a decoder). Never throws. --- --- local written, srcEnd, clean = PackBits.decode(src, p, limit, dst, d, n) -- up to n bytes into dst at d --- local packed = PackBits.encode(src, offset, length) -- a buffer (one row at a time) +-- 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 --- decode(src, p, limit, dst, d, n) -> bytes written (<= n), the source offset after the codes used, clean (false when --- the source ran out before n bytes or a run overflowed n: lenient callers keep what was written, strict ones fail) @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 @@ -61650,7 +60275,6 @@ local readu8, writeu8 = buffer.readu8, buffer.writeu8 return o - d, p, clean end --- encode(src, offset, length) -> buffer: runs of 3+ equal bytes as repeats, the rest as literals (at most 128 each) @native function PackBits.encode(src: buffer, off: number, len: number): buffer local out = buffer.create(len + (len + 127) // 128 + 8) local o = 0 @@ -61692,20 +60316,9 @@ __FILES["codecs/compress/Quantum"] = @native function() --- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft --- Cabinet folders use it: windows of 2^10 .. 2^21 bytes; a 16-bit arithmetic decoder (H / L / C registers with --- underflow handling) over a most-significant-bit-first byte stream; eight adaptive frequency models (the --- 7-symbol selector, four 64-symbol literal models, the offset models for matches of 3, 4 and 5..259 bytes and the --- 27-symbol length model) whose cumulative frequencies grow by 8 per symbol and are rescaled above 3800 (halved, and --- every 50th time rebuilt from the frequencies and re-sorted); position and length footers read as raw bits from the --- same stream. Each CFDATA block is one frame (at most 32768 output bytes) that restarts the arithmetic coder; the --- models and the window persist across the frames of a folder. Written from the public descriptions of the format --- (the Quantum notes by Matthew Russotto and the cabinet documentation); no code from libmspack. --- --- local out, err = Quantum.decode(src, blocks, outSize, windowBits) -- buffer | nil, message --- --- blocks = { { at, len, size } }: each block's compressed bytes src[at, at + len) and its output size; outSize is --- their total. Never throws: bad or truncated data returns nil, message. +-- 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 @@ -61736,8 +60349,7 @@ do end end --- ------------------------------------------------------------------------------------------------ models --- an adaptive model: symbols sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0) +-- 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 @@ -61783,8 +60395,6 @@ end end end --- ------------------------------------------------------------------------------------------------ decode --- the coder and bit reader of one frame 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 @@ -61803,7 +60413,6 @@ type Coder = { src: buffer, pos: number, stop: number, acc: number, cnt: number, return band(rshift(c.acc, c.cnt), 1) end --- raw(c, n) -> the next n (0..19) bits, most significant first @native local function raw(c: Coder, n: number): number local v = 0 for _ = 1, n do @@ -61818,7 +60427,6 @@ end local range = H - L + 1 local total = cum[1] if range <= 0 or C < L or C > H then - -- only corrupt registers get here (the decoder keeps L <= C <= H) c.bad = true return 0 end @@ -61945,24 +60553,16 @@ __FILES["codecs/compress/UnixCompress"] = @native function() --- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code --- width 9..16 and the block mode bit), decode and encode. A codec (layer 3): archive/z builds on it. Codes are --- LSB-first, 9 bits wide at the start; the width grows when the next free code passes 2^width - 1 (up to the --- maximum), and in block mode code 256 clears the table. compress writes codes in groups of eight: when the width --- changes or a CLEAR is read, the rest of the current group (counted from the previous change) is skipped. The encoder --- reproduces ncompress 5.0 bit for bit: greedy longest match, a full table frozen until the compression ratio checked --- every 10000 input bytes drops, then a CLEAR. Written from the ncompress sources (public domain, The Unlicense: read --- for the format and the encoder's ratio check; licenses/ncompress-UNLICENSE.txt). Never throws. --- --- local out, err = UnixCompress.decompress(buf, offset?, length?, { maxBytes = 2^28 }) -- a whole .Z file --- local z = UnixCompress.compress(buf, offset?, length?, { maxBits = 16 }) -- -> a .Z file +-- 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? } -- refuse output larger than this (default 2^30) -type EncodeOptions = { maxBits: number? } -- 9..16, default 16 +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 @@ -61971,14 +60571,11 @@ local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local MAXCODES = 65536 local CHECK_GAP = 10000 --- decoder tables (per call state lives in locals; the tables are reused: decode never yields) -local prefix = bcreate(MAXCODES * 4) -- u32: the code an entry extends -local suffix = bcreate(MAXCODES) -- u8: its last byte -local first = bcreate(MAXCODES) -- u8: its first byte -local length = bcreate(MAXCODES * 4) -- u32: its length +local prefix = bcreate(MAXCODES * 4) +local suffix = bcreate(MAXCODES) +local first = bcreate(MAXCODES) +local length = bcreate(MAXCODES * 4) --- ------------------------------------------------------------------------------------------------ decode --- decompress(buf, offset?, length?, opts?) -> buffer | nil, Err @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 @@ -62012,8 +60609,8 @@ local length = bcreate(MAXCODES * 4) -- u32: its length local op = 0 local totalBits = (n - 3) * 8 local base = o + 3 - local pos = 0 -- bit position from the first code - local gbase = 0 -- where the current group sequence starts + local pos = 0 + local gbase = 0 local nbits = 9 local mask = 511 local maxcode = 511 @@ -62029,7 +60626,6 @@ local length = bcreate(MAXCODES * 4) -- u32: its length mask = lshift(1, nbits) - 1 continue end - -- the code: up to 23 bits from three bytes local q = base + rshift(pos, 3) local acc = readu8(b, q) if q + 1 < o + n then @@ -62101,12 +60697,10 @@ local length = bcreate(MAXCODES * 4) -- u32: its length return res, nil end --- ------------------------------------------------------------------------------------------------ encode -local HSIZE = 1 * 131072 -- open addressing over (prefix << 8 | byte) + 1 keys: twice the 65536 entries +local HSIZE = 1 * 131072 local hkey = bcreate(HSIZE * 4) local hval = bcreate(HSIZE * 4) --- compress(buf, offset?, length?, opts?) -> a .Z file (block mode) | nil, Err @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 @@ -62116,7 +60710,6 @@ local hval = bcreate(HSIZE * 4) 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 - -- at most 17 bits per input byte, plus group padding (< one group per width change / clear) local cap = 3 + n * 2 + 64 local out = bcreate(cap) writeu8(out, 0, 0x1F) @@ -62124,7 +60717,7 @@ local hval = bcreate(HSIZE * 4) writeu8(out, 2, bor(maxbits, 0x80)) local outbits = 24 local boff = 24 - local acc, nb = 0, 0 -- pending bits not yet written (below 2^24) + local acc, nb = 0, 0 local nbits = 9 local extcode = 513 local maxmax = lshift(1, maxbits) @@ -62234,7 +60827,6 @@ local hval = bcreate(HSIZE * 4) checks(i - o) end if rshift(outbits, 3) + 8 > cap then - -- grow (rare: only incompressible input passes 2 bytes per byte) local ncap = cap * 2 local nbuf = bcreate(ncap) bcopy(nbuf, 0, out, 0, cap) @@ -62254,7 +60846,6 @@ local hval = bcreate(HSIZE * 4) return res, nil end --- isCompress(buf, offset?) -> true when the bytes at offset start a .Z file @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 @@ -62266,11 +60857,8 @@ __FILES["codecs/compress/Xxh32"] = @native function() --- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content --- checksums. 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double. --- From the xxHash specification (Yann Collet, BSD-2); no code copied. Never throws (the range is clamped to the buffer). --- --- local h = Xxh32.hash(buf, offset?, length?, seed?) -- a number in 0 .. 2^32 - 1 +-- 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 @@ -62279,7 +60867,6 @@ local readu8, readu32 = buffer.readu8, buffer.readu32 local T32 = 4294967296 local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1 --- a * b mod 2^32 (a, b below 2^32) @native local function mul(a: number, b: number): number local a0 = a % 65536 local a1 = (a - a0) / 65536 @@ -62294,7 +60881,6 @@ end return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1) end --- hash(buf, offset?, length?, seed?) -> XXH32 @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) @@ -62338,17 +60924,7 @@ return Xxh32 end __FILES["codecs/compress/Zstd"] = function() --- codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd --- data build on it. Written from the specification. Supports every frame feature a dictionary-less stream uses: --- concatenated and skippable frames, raw / RLE / compressed blocks, Huffman literals (1 / 4 streams, repeated tables), --- predefined / RLE / compressed / repeated FSE tables, repeat offsets, the XXH64 content checksum (verified). --- Not supported: dictionaries (Err.UNSUPPORTED), compression. --- --- local Zstd = require("@rosetta/codecs/compress/Zstd") --- local out, err = Zstd.decompress(buf) -- -> buffer, consumedEnd | nil, Err --- local out, err = Zstd.decompress(buf, off, len, { maxBytes = 2^24, verify = false }) --- --- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / UNSUPPORTED / LIMIT / ARG). +-- 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") @@ -62356,14 +60932,13 @@ local Decode = __include("codecs/compress/Zstd/Decode") local Zstd = {} type Options = { - maxBytes: number?, -- refuse output larger than this (default 2^30) - verify: boolean?, -- check the content checksum when a frame has one (default true) + maxBytes: number?, + verify: boolean?, } -- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F) Zstd.MAGIC = "\40\181\47\253" --- isFrame(buf, offset?) -> true when a zstd (or skippable) frame starts there 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 @@ -62373,8 +60948,7 @@ function Zstd.isFrame(buf: buffer, offset: number?): boolean return m == 0xFD2FB528 or bit32.band(m, 0xFFFFFFF0) == 0x184D2A50 end --- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. Every frame in the range is decoded --- and the outputs concatenated; data after the last frame that is not a frame is an error (as zstd -d does). +-- 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 @@ -62397,7 +60971,6 @@ function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, return out, consumed end --- xxh64(buf, offset?, length?) -> hi, lo: the XXH64 hash (seed 0) as two unsigned 32-bit halves 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) @@ -62410,16 +60983,8 @@ __FILES["codecs/compress/Zstd/Decode"] = @native function() --- codecs/compress/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the --- BSD reference implementation). Frames (any number, concatenated), skippable frames, raw / RLE / compressed blocks, --- Huffman literals (1 or 4 streams, new or repeated table), FSE sequence tables (predefined / RLE / compressed / --- repeat), repeat offsets, the XXH64 content checksum. Not supported: dictionaries (a non-zero dictionary ID). --- --- The whole output lives in one buffer, so the window is the output itself (offsets are checked against the frame's --- start). Backward bitstreams are read through bit offsets: bits [o - n, o) of a stream come from one readu32 at --- byte (o - n) / 8, bits before the stream start read as zeros. --- --- Nothing here throws on any input: every read is bounds-checked; failures return nil, code, message, offset. +-- 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 @@ -62431,7 +60996,6 @@ local BLOCK_MAX = 131072 local Decode = {} --- ------------------------------------------------------------------------------------------------ tables -- 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 } @@ -62450,7 +61014,6 @@ local ML_DEFAULT = { } 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 } --- highest set bit of 1..2048 local HB = table.create(2048, 0) do local v = 0 @@ -62462,8 +61025,6 @@ do end end --- ------------------------------------------------------------------------------------------------ bit readers --- backward stream starting at byte s: bits [o - n, o) (n <= 25), bits below 0 are zeros @native local function peek(b: buffer, s: number, o: number, n: number): number if n <= 0 then return 0 @@ -62491,7 +61052,6 @@ end return lshift(peek(b, s, o, o), -lo) end --- the bit length of a backward stream [s, e) (up to its end marker), or -1 when the last byte is 0 / it is empty @native local function streamBits(b: buffer, s: number, e: number): number if e <= s then return -1 @@ -62503,7 +61063,6 @@ end return (e - 1 - s) * 8 + HB[last] end --- forward stream: n (<= 24) bits at bit position bp from byte p; bytes at or past e read as zeros @native local function getF(b: buffer, p: number, e: number, bp: number, n: number): number local byte = p + rshift(bp, 3) local v = 0 @@ -62517,11 +61076,10 @@ end return band(rshift(v, band(bp, 7)), lshift(1, n) - 1) end --- ------------------------------------------------------------------------------------------------ FSE -- FSE decoding table entries (u32): symbol | nbBits << 8 | newStateBase << 16 local symTmp = bcreate(512) --- build(norm, nsym, al, t) -> true | nil, message. norm: { [symbol + 1] = normalized count (-1 = "less than 1") } +-- 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 @@ -62575,7 +61133,6 @@ local symTmp = bcreate(512) return true, nil end --- ncount(b, p, e, maxSym, maxAL, norm) -> al, bytesUsed, nsym | nil, message: an FSE table description @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" @@ -62660,8 +61217,7 @@ end end local LL_PRE, ML_PRE, OF_PRE = predefined(LL_DEFAULT, 6), predefined(ML_DEFAULT, 6), predefined(OF_DEFAULT, 5) --- ------------------------------------------------------------------------------------------------ Huffman --- hufTable(b, p, e, st) -> bytesUsed | nil, message: a Huffman tree description into st.huf (u16: sym | nbBits << 8) +-- 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?) @@ -62789,7 +61345,6 @@ local wfse = bcreate(64 * 4) return used, nil end --- one Huffman stream [s, e) -> cnt literals at lit[dp] | nil, message @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 @@ -62820,8 +61375,6 @@ end return nil end --- ------------------------------------------------------------------------------------------------ frames --- grow st.out to hold need bytes (doubling, capped at st.maxBytes): true | false (over the limit) @native local function grow(st: any, need: number): boolean if need > st.maxBytes then return false @@ -62833,7 +61386,6 @@ end return true end --- a compressed block [p, e): nil (ok) | code, message @native local function block(b: buffer, p: number, e: number, st: any): (string?, string?) -- literals section local b0 = readu8(b, p) @@ -63168,7 +61720,6 @@ end bfill(out, op, readu8(out, from), ml) op += ml else - -- overlapping: copy in chunks of `offset` bytes (each chunk's source precedes its destination) local left = ml while left > 0 do local n = if left < offset then left else offset @@ -63199,7 +61750,6 @@ end return nil, nil end --- decompress(b, start, stop, maxBytes, verify) -> out, length, consumedEnd | nil, code, message, offset @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))), @@ -63312,7 +61862,6 @@ end st.rep1, st.rep2, st.rep3 = 1, 4, 8 st.hufBits = nil table.clear(st.tabs) - -- blocks local last = false repeat if pos + 3 > stop then @@ -63392,10 +61941,8 @@ __FILES["codecs/compress/Zstd/Xxh64"] = @native function() --- codecs/compress/Zstd/Xxh64: XXH64 (seed 0) of a buffer range, computed on 32-bit halves held in doubles (Luau and LuaJIT have --- no 64-bit integers). 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is --- exact below 2^53. From the xxHash specification (Yann Collet, BSD-2); no code copied. zstd stores the low 32 bits --- of the hash as the frame content checksum. Never throws (the caller passes an in-range buffer slice). +-- 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 @@ -63407,7 +61954,6 @@ local P3H, P3L = 0x165667B1, 0x9E3779F9 local P4H, P4L = 0x85EBCA77, 0xC2B2AE63 local P5H, P5L = 0x27D4EB2F, 0x165667C5 --- (ah, al) * (bh, bl) mod 2^64 @native local function mul(ah: number, al: number, bh: number, bl: number): (number, number) local a0 = al % 65536 local a1 = (al - a0) / 65536 @@ -63432,7 +61978,6 @@ end return h % T32, l end --- rotl by r in 1..31 @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 @@ -63440,7 +61985,7 @@ end local P1L0, P1L1 = P1L % 65536, P1L // 65536 local P2L0, P2L1 = P2L % 65536, P2L // 65536 --- acc = rotl(acc + input * P2, 31) * P1, with both products written out (the hot path: 4 per 32 input bytes) +-- 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 @@ -63478,7 +62023,6 @@ end local Xxh64 = {} --- hash(b, offset, length) -> hi, lo (the 64-bit hash as two unsigned 32-bit halves) @native function Xxh64.hash(b: buffer, offset: number, length: number): (number, number) local p = offset local e = offset + length @@ -63548,19 +62092,11 @@ end __FILES["codecs/entropy/Huffman"] = @native function() --- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. --- --- Decoding tables (built by buildLsb / buildMsb) are u32 buffers, indexed by the next P bits of the stream: --- entry = symbol * 32 + length a code of `length` <= P bits --- entry = offset * 32 (length 0) a link: index offset + the following S bits (subtable of 2^S entries) --- entry = 0 no code (incomplete code set): the stream is corrupt --- so a symbol is one or two table reads. LSB tables (DEFLATE, VP8L) are indexed by bit-reversed codes, MSB tables --- (JPEG, MPEG) by the code itself. Code lengths are 1..MAXLEN (16), symbols < 2^27. --- The hot loops (codecs/compress/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a --- core/Bits reader. --- --- Encoding: lengths(freqs, maxLen) -> length-limited code lengths; codes(lengths) -> canonical code values. --- Never throws: bad code sets return -1 / nil. +-- 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 @@ -63572,7 +62108,6 @@ local MAXLEN = 16 local Huffman = {} Huffman.MAXLEN = MAXLEN --- 8-bit reversal local REV = table.create(256, 0) for i = 0, 255 do local r, v = 0, i @@ -63583,13 +62118,11 @@ for i = 0, 255 do REV[i + 1] = r end --- reverse(code, len) -> the low len bits of code reversed (len <= 16) @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 --- capacity(nsym, P, maxLen) -> the table entries (u32) needed for nsym symbols, primary width P, codes up to maxLen @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 @@ -63638,7 +62171,6 @@ local nextc = table.create(MAXLEN + 1, 0) local entry = s * 32 + l if l <= P then if msb then - -- the code is the top l bits of the P-bit index: fill every completion of the low bits local first = lshift(c, P - l) local last = first + lshift(1, P - l) - 1 for i = first, last do @@ -63672,7 +62204,7 @@ local nextc = table.create(MAXLEN + 1, 0) else sub = rshift(e, 5) end - local k = l - P -- bits of the code in the subtable index + local k = l - P if msb then local first = lshift(rest, S - k) for i = first, first + lshift(1, S - k) - 1 do @@ -63692,19 +62224,14 @@ local nextc = table.create(MAXLEN + 1, 0) return S end --- buildLsb(lens, off, n, tab, P) -> S: a table for the code lengths lens[off .. off + n - 1] (u8), indexed by the next --- P bits LSB-first (bit-reversed codes). S = the subtable width (0 when no code is longer than P), -1 = an --- over-subscribed or invalid code set. tab must hold capacity(n, P, maxLen) u32 entries. @native function Huffman.buildLsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number return build(lens, off, n, tab, P, false) end --- buildMsb(lens, off, n, tab, P) -> S: the same, indexed by the next P bits MSB-first @native function Huffman.buildMsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number return build(lens, off, n, tab, P, true) end --- decodeLsb(br, tab, P, S) -> symbol, or -1 for an invalid code (br: a core/Bits LSB reader) @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) @@ -63723,7 +62250,6 @@ end return rshift(e, 5) end --- decodeMsb(br, tab, P, S) -> symbol, or -1 (br: a core/Bits MSB reader) @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) @@ -63742,8 +62268,6 @@ end return rshift(e, 5) end --- codes(lengths) -> canonical code values (MSB-first, as written by an MSB writer; reverse() them for LSB streams). --- lengths: { number } indexed 1..n (symbol + 1), 0 = unused. @native function Huffman.codes(lengths: { number }): { number } local cnt = table.create(MAXLEN + 1, 0) for _, l in lengths do @@ -63767,12 +62291,9 @@ end return out end --- lengths(freqs, maxLen) -> code lengths ({ number }, same indexing as freqs), at most maxLen bits, optimal without --- the limit; over the limit, the JPEG Annex K.3 adjustment. A single used symbol gets length 1. @native function Huffman.lengths(freqs: { number }, maxLen: number): { number } local n = #freqs local out = table.create(n, 0) - -- leaves sorted by frequency (ties by symbol, for determinism) local syms = {} for i = 1, n do if freqs[i] > 0 then @@ -63792,14 +62313,13 @@ end end return a < b end) - -- two-queue Huffman: leaves (sorted) and internal nodes (created in increasing weight order) 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 -- next leaf, next internal node to take, next free node + 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 @@ -63816,12 +62336,11 @@ end parent[b] = nn nn += 1 end - -- depths: the root is nn - 1 local depth = table.create(2 * m, 0) for i = nn - 2, 1, -1 do depth[i] = depth[parent[i]] + 1 end - -- count codes per length; limit (JPEG K.3: move pairs from the deepest level up) + -- 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 @@ -63840,7 +62359,6 @@ end bl[j] -= 1 end end - -- the longest codes go to the least frequent symbols (syms is sorted ascending) local k = 1 for l = math.min(deepest, maxLen), 1, -1 do for _ = 1, bl[l] do @@ -63855,12 +62373,8 @@ return Huffman end __FILES["codecs/entropy/RangeCoder"] = function() --- codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt): --- symbols range-coded from the front of a frame, raw bits from its back. Opus (CELT and SILK) uses it; LZMA, VP8 and --- CABAC have their own (different) binary coders. Moved here from audio/opus by the cleanup pass (same code). --- --- local RD = require("@rosetta/codecs/entropy/RangeCoder/Decoder") -- RD.new(buf, base, size), RD.icdf / bits / uint ... --- local RE = require("@rosetta/codecs/entropy/RangeCoder/Encoder") -- RE.new(size), RE.icdf / bits / uint, RE.done +-- 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"), @@ -63872,10 +62386,9 @@ __FILES["codecs/entropy/RangeCoder/Decoder"] = @native function() --- codecs/entropy/RangeCoder/Decoder: the Opus range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus --- frame from a `buffer` slice [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice --- backwards. --- All values stay below 2^32, so plain Luau numbers hold them exactly; floor division is exact below 2^52. +-- 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 = { @@ -63925,7 +62438,7 @@ RangeDecoder.ilog = ilog else rem = 0 end - sym = rshift(bor(lshift(sym, 8), rem), SYM_BITS - CODE_EXTRA) -- (sym << 8 | rem) >> 1 + 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 @@ -63958,7 +62471,6 @@ end return d end --- ec_decode: the cumulative frequency of the next symbol, for a total of ft @native function RangeDecoder.decode(d: Dec, ft: number): number local ext = d.rng // ft d.ext = ext @@ -64000,7 +62512,6 @@ end return ret end --- ec_dec_icdf over a Luau array (1-based) starting at index `off` (icdf[off] is entry 0) @native function RangeDecoder.icdf(d: Dec, icdf: { number }, off: number, ftb: number): number local s = d.rng local v = d.val @@ -64089,10 +62600,8 @@ __FILES["codecs/entropy/RangeCoder/Encoder"] = @native function() --- codecs/entropy/RangeCoder/Encoder: the Opus range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD: --- licenses/libopus-BSD.txt), the mirror of codecs/entropy/RangeCoder/Decoder. Writes one fixed-size frame: the range-coded --- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain --- numbers. Never throws: running out of room sets `error`. +-- 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 = { @@ -64125,7 +62634,6 @@ local floor = math.floor end RangeEncoder.ilog = ilog --- new(storage) -> Enc over a fresh zeroed buffer of storage bytes @native function RangeEncoder.new(storage: number): Enc return { buf = buffer.create(math.max(storage, 1)), @@ -64189,7 +62697,6 @@ end end end --- encode(fl, fh, ft): the symbol [fl, fh) of ft @native function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number) local r = floor(e.rng / ft) if fl > 0 then @@ -64201,7 +62708,6 @@ end normalize(e) end --- encodeBin(fl, fh, bits): ft = 2^bits @native function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number) local ft = 2 ^ bits local r = floor(e.rng / ft) @@ -64214,7 +62720,6 @@ end normalize(e) end --- bitLogp(v, logp): a bit whose probability of being 1 is 2^-logp @native function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number) local r = e.rng local s = floor(r / 2 ^ logp) @@ -64228,7 +62733,6 @@ end normalize(e) end --- icdf(s, icdf, ftb): symbol s (0-based) of an inverse CDF table (1-based Luau array) with 2^ftb total @native function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number) local r = floor(e.rng / 2 ^ ftb) if s > 0 then @@ -64240,7 +62744,6 @@ end normalize(e) end --- bits(fl, n): n raw bits (n <= 25), written from the end of the frame @native function RangeEncoder.bits(e: Enc, fl: number, n: number) local window = e.end_window local used = e.nend_bits @@ -64258,7 +62761,6 @@ end e.nbits_total += n end --- uint(fl, ft): fl uniformly in [0, ft), ft up to 2^32 @native function RangeEncoder.uint(e: Enc, fl: number, ft: number) ft -= 1 local ftb = ilog(ft) @@ -64290,7 +62792,6 @@ local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } return nbits - (l * 8 + b) end --- done(): flush; the frame is e.buf (storage bytes) @native function RangeEncoder.done(e: Enc) local l = 32 - ilog(e.rng) local msk = floor((CODE_TOP - 1) / 2 ^ l) @@ -64341,20 +62842,8 @@ return RangeEncoder end __FILES["codecs/font/Bitmap"] = function() --- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike --- (one pixel size, glyphs as u8 bitmaps, 0 = off / 255 = on) wrapped as a Types.Font whose units are pixels --- (unitsPerEm = the pixel size), glyphIndex / advance / kern work, outline is nil, and rasterize(g) returns the glyph's --- bitmap as an alpha8 Image (img.meta.left / top / advance, as codecs/font/TrueType does; the px argument is ignored, --- img.meta.scale = px / size tells the caller how much to scale). Also: the strike of any Font (its own bitmap, or an --- outline font rasterized at a pixel size and thresholded), which the bitmap font encoders write, and the bit-row --- packing every bitmap font format shares. New code. --- --- local font = Bitmap.font(strike, { family = "Fixed" }, { source = { format = "bdf" } }) --- local strike, err = Bitmap.strike(anyFont, { px = 16, chars = "abc" }) -- font.bitmap, or rasterized --- local pixels = Bitmap.unpack(buf, off, w, h, stride) -- MSB-first 1-bit rows -> u8 0 / 255 --- local bytes = Bitmap.pack(pixels, w, h, stride) -- u8 -> MSB-first rows (buffer) --- --- Never throws: rasterize of a bad glyph index returns nil; unpack reads only inside the buffer (missing bits are 0). +-- 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") @@ -64362,9 +62851,6 @@ local Bitmap = {} local readu8, writeu8 = buffer.readu8, buffer.writeu8 --- ------------------------------------------------------------------------------------------------ bits --- unpack(buf, off, w, h, stride, lsbFirst?) -> u8 pixels (w * h, 0 / 255) from 1-bit rows of stride bytes (MSB = left --- pixel unless lsbFirst); bytes past the end of buf read as 0 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) @@ -64384,7 +62870,6 @@ function Bitmap.unpack(b: buffer, off: number, w: number, h: number, stride: num return out end --- pack(pixels, w, h, stride?, lsbFirst?) -> 1-bit rows (stride bytes each, default ceil(w / 8)); a pixel >= 128 is on 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)) @@ -64402,7 +62887,6 @@ function Bitmap.pack(px: buffer, w: number, h: number, stride: number?, lsbFirst return out end --- ------------------------------------------------------------------------------------------------ font local Face = {} Face.__index = Face @@ -64423,7 +62907,6 @@ function Face.outline(_self: any, _g: number): { any }? return nil end --- rasterize(g, px?) -> the glyph as an alpha8 Image (px is ignored: meta.scale = px / size) 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 @@ -64442,7 +62925,6 @@ function Face.rasterize(self: any, g: number, px: number?): Types.Image? return img end --- font(strike, info?, meta?) -> a Types.Font over the strike (font.bitmap = strike) function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta: { [string]: any }?): any local index: { [number]: number } = {} for i, gl in strike.glyphs do @@ -64478,11 +62960,10 @@ function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta: return f end --- ------------------------------------------------------------------------------------------------ strike type StrikeOptions = { - px: number?, -- pixel size for outline fonts (default 16) - chars: (string | { number })?, -- code points for outline fonts (default 32..126) - threshold: number?, -- coverage 0..255 at or above which a pixel is on (default 128) + px: number?, + chars: (string | { number })?, + threshold: number?, } local function codepoints(chars: (string | { number })?): { number } @@ -64502,7 +62983,6 @@ local function codepoints(chars: (string | { number })?): { number } return out end --- strike(font, opts?) -> the font's BitmapStrike: font.bitmap, else the outline font rasterized at opts.px 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") @@ -64563,19 +63043,9 @@ 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 OpenType fonts --- with a "CFF " table (.otf). Parses the header, the INDEXes, the Top / Private DICTs (name-keyed and CID-keyed --- fonts with FDArray / FDSelect formats 0 and 3), local and global subroutines, and runs charstrings to path commands --- (moveTo / lineTo / cubicTo / close, font units, y up). The charstring interpreter is ported from stb_truetype 1.26 --- (public domain / MIT; Dougall Johnson's Type 2 support) through imgui-luau's imstb_truetype.lua, bounds-checked, --- with fixes: flex1's last delta, an operation budget against subroutine bombs, and the arithmetic / storage --- operators (TN #5177 4.4: and or not abs add sub div neg eq drop put get ifelse random mul sqrt dup exch index roll). --- Not supported: CFF2 (variable fonts), seac accented glyphs in endchar (deprecated in OpenType), hinting. --- --- local cff, err = Cff.parse(buf, offset, length) --- local cmds, err = Cff.outline(cff, glyphIndex) --- --- Never throws: malformed data returns nil, message. +-- 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 @@ -64602,15 +63072,14 @@ type Font = { limit: number, charStrings: Index, gsubrs: Index, - subrs: Index?, -- name-keyed fonts - fdSubrs: { Index? }?, -- CID-keyed fonts: per font dict - fdSelect: number?, -- absolute offset of FDSelect + subrs: Index?, + fdSubrs: { Index? }?, + fdSelect: number?, numGlyphs: number, cid: boolean, fontMatrix: { number }?, } --- INDEX at absolute offset p (within [base, limit)) -> Index | nil local function index(b: buffer, p: number, limit: number): Index? if p + 2 > limit then return nil @@ -64635,7 +63104,6 @@ local function index(b: buffer, p: number, limit: number): Index? return { count = count, offSize = offSize, offsets = offsets, data = data, next = data + last } end --- item(idx, i) -> absolute start, length (nil when out of range / corrupt) local function item(b: buffer, idx: Index, i: number): (number?, number) if i < 0 or i >= idx.count then return nil, 0 @@ -64649,7 +63117,7 @@ local function item(b: buffer, idx: Index, i: number): (number?, number) end Cff.item = item --- DICT at [p, p + n) -> { [op] = { operands } } (two-byte ops are 1200 + second byte) +-- 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 } = {} @@ -64735,7 +63203,6 @@ local function privateSubrs(b: buffer, base: number, limit: number, d: { [number return index(b, ps + s[1], limit) end --- parse(buf, offset, length) -> Font | nil, message 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 @@ -64820,7 +63287,6 @@ local function bias(count: number): number return if count < 1240 then 107 elseif count < 33900 then 1131 else 32768 end --- the local subrs of glyph g (CID fonts: through FDSelect) local function localSubrs(f: Font, g: number): Index? if not f.cid then return f.subrs @@ -64850,7 +63316,6 @@ end local BUDGET = 200000 -- operators per glyph (subroutine bombs) --- outline(f, g) -> path commands | nil, message function Cff.outline(f: Font, g: number): ({ any }?, string?) local b = f.buf local p, len = item(b, f.charStrings, g) @@ -64859,14 +63324,14 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?) end local e = p + len local cmds: { any } = {} - local s: { number } = table.create(48, 0) -- operand stack, 1-based; sp = count + 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 } } = {} -- return addresses { p, e } + local stack: { { number } } = {} local subrs: Index? = nil local haveSubrs = false local ops = 0 @@ -64898,13 +63363,12 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?) x, y = x2 + dx3, y2 + dy3 table.insert(cmds, { op = "cubicTo", x1, y1, x2, y2, x, y }) end - local function S(i: number): number -- operand i (0-based), 0 past the stack + local function S(i: number): number return s[i + 1] or 0 end while true do if p >= e then - -- the end of a subroutine without return, or of the charstring without endchar if #stack > 0 then local r = table.remove(stack) :: { number } p, e = r[1], r[2] @@ -65099,12 +63563,10 @@ function Cff.outline(f: Font, g: number): ({ any }?, string?) 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 - -- arithmetic and storage operators: they leave results on the stack clear = false local top = sp local a, c = S(top - 2), S(top - 1) local function set(n: number, v: number) - -- pop n operands, push v sp = math.max(0, sp - n) sp += 1 s[sp] = v @@ -65222,14 +63684,9 @@ return Cff end __FILES["codecs/font/GlyphNames"] = function() --- codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a --- cmap, PCF / BDF glyph names): the Adobe Glyph List For New Fonts (AGLFN 1.7, Adobe, BSD-3-Clause: --- licenses/agl-LICENSE.txt; the f-ligatures and dotlessj added), the uniXXXX / uXXXX[XX] conventions and --- name.suffix variants ("a.sc" -> a) per the AGL specification; and Adobe StandardEncoding (code -> glyph name). --- Generated once from fontTools.agl / fontTools.encodings.StandardEncoding. --- --- GlyphNames.unicode("Aacute") -> 0xC1 GlyphNames.unicode("uni20AC") -> 0x20AC (nil when unknown) --- GlyphNames.STANDARD[65] -> "A" (StandardEncoding, codes 0..255; nil for .notdef) +-- 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 @@ -65349,7 +63806,6 @@ do end GlyphNames.STANDARD = STANDARD --- unicode(name) -> the code point of a glyph name (the first one for ligature names like "f_i"), or nil function GlyphNames.unicode(name: string): number? local base = string.match(name, "^([^%.]+)") or name local t = byName or load() @@ -65378,22 +63834,8 @@ return GlyphNames end __FILES["codecs/font/TrueType"] = function() --- codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed --- into the standard Font value (Types.Font): metrics (head / hhea / hmtx / OS/2 / post), cmap lookups, glyph outlines --- (codecs/font/TrueType/Glyf for glyf, codecs/font/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments), --- names, and rasterize(glyph, px) through codecs/image/Raster. A codec, not a format: font/ttf, font/woff and font/woff2 all --- build an sfnt and call TrueType.font(). Ported and modernised from stb_truetype 1.26 (public domain / MIT, Sean --- Barrett and contributors) through imgui-luau's imstb_truetype.lua; the rasterizer is codecs/image/Raster instead of stb's. --- Not supported: hinting, variable fonts (fvar / gvar / CFF2), vertical metrics, bitmap strikes (EBDT / CBDT / sbix), --- colour layers (COLR), GSUB substitutions. --- --- local font, err = TrueType.font(buf, offset?, length?, { index = 0 }) -- Types.Font | nil, Err --- local g = font:glyphIndex(0x41) local adv = font:advance(g) -- font units --- local k = font:kern(g1, g2) local cmds = font:outline(g) -- moveTo / lineTo / quadTo / cubicTo --- local img = font:rasterize(g, 32) -- alpha8 Image, 32 px per em; img.meta.left / top / advance (px) --- local n = TrueType.count(buf) -- fonts in a collection (1 for a plain sfnt) --- --- Never throws: malformed fonts return nil, Err from font(), and nil from the per-glyph methods. +-- 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") @@ -65412,7 +63854,6 @@ local function tag(b: buffer, o: number): string return buffer.readstring(b, o, 4) end --- count(buf, offset?) -> the number of fonts (a collection's count, 1 for an sfnt, 0 for neither) function TrueType.count(b: buffer, offset: number?): number local o = offset or 0 local t = tag(b, o) @@ -65425,7 +63866,6 @@ function TrueType.count(b: buffer, offset: number?): number return 0 end --- tables(buf, file, dir) -> { [tag] = { offset (absolute), length } } of the table directory at dir 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 @@ -65443,7 +63883,6 @@ function TrueType.tables(b: buffer, file: number, dir: number, limit: number): ( return out, nil end --- ------------------------------------------------------------------------------------------------ the Font value local Face = {} Face.__index = Face @@ -65495,7 +63934,6 @@ function Face.kern(self: any, a: number, b: number): number return v end --- kernCodepoints(a, b) -> kern between two code points function Face.kernCodepoints(self: any, a: number, b: number): number return self:kern(self:glyphIndex(a), self:glyphIndex(b)) end @@ -65520,7 +63958,6 @@ function Face.outline(self: any, g: number): { any }? return cmds end --- bounds(g) -> xMin, yMin, xMax, yMax of the outline's points (font units), nil for an empty / bad glyph function Face.bounds(self: any, g: number): (number?, number, number, number) local cmds = self:outline(g) if not cmds then @@ -65539,21 +63976,18 @@ function Face.bounds(self: any, g: number): (number?, number, number, number) return x0, y0, x1, y1 end --- scale(px) -> pixels per font unit for an em of px pixels function Face.scale(self: any, px: number): number return px / self.unitsPerEm end type RasterOptions = { - scaleX: number?, -- pixels per font unit (default px / unitsPerEm); scaleY likewise + scaleX: number?, scaleY: number?, - shiftX: number?, -- subpixel shift (pixels) + shiftX: number?, shiftY: number?, } --- rasterize(g, px, opts?) -> alpha8 Image (meta.left / meta.top: the bitmap's offset from the pen position, pixels; --- top counts up from the baseline as FreeType's bitmap_top; meta.advance in pixels) | nil for a bad glyph. Empty --- glyphs give a 0 x 0 image. +-- 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 @@ -65583,10 +64017,8 @@ function Face.rasterize(self: any, g: number, px: number, opts: RasterOptions?): return img end --- ------------------------------------------------------------------------------------------------ parsing -type Options = { index: number? } -- the font in a collection (default 0) +type Options = { index: number? } --- font(buf, offset?, length?, opts?) -> Types.Font | nil, Err function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Options?): (any, Err.Err?) local b = buf local file = offset or 0 @@ -65650,7 +64082,6 @@ function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Opti _numHMetrics = nh, _kernCache = {}, }, Face) - -- outlines if t.glyf and t.loca then font._glyf = { buf = b, @@ -65675,7 +64106,6 @@ function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Opti else return nil, Err.new(Err.UNSUPPORTED, "no glyf or CFF outlines (bitmap-only font?)", dir) end - -- cmap, kerning, names, OS/2, post if t.cmap then font._cmap = Tables.cmap(b, t.cmap[1], t.cmap[2]) end @@ -65718,14 +64148,9 @@ return TrueType end __FILES["codecs/font/TrueType/Glyf"] = function() --- codecs/font/TrueType/Glyf: TrueType glyph outlines (the glyf / loca tables): simple glyphs (contours of on- and --- off-curve points, with the implied on-curve midpoints) and composite glyphs (offsets or point matching, scale / --- x-y scale / 2x2 transforms, SCALED_COMPONENT_OFFSET, nesting up to 8 levels). Ported from stb_truetype 1.26 --- (public domain / MIT, Sean Barrett) through imgui-luau's imstb_truetype.lua, made bounds-checked, with point --- matching and the FreeType component transform (stb scales the offsets of transformed components; FreeType and the --- spec do not). No hinting. --- --- Never throws: every read is range-checked (out of range reads as 0) and malformed glyphs return nil, message. +-- 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 @@ -65754,7 +64179,7 @@ end type Face = { buf: buffer, - glyf: number, -- absolute offset of the glyf table + glyf: number, glyfLen: number, loca: number, locaLen: number, @@ -65763,7 +64188,6 @@ type Face = { [string]: any, } --- (start, length) of glyph g in the glyf table, or nil for an empty glyph / bad index function Glyf.range(f: Face, g: number): (number?, number) if g < 0 or g >= f.numGlyphs or g % 1 ~= 0 then return nil, 0 @@ -65786,7 +64210,6 @@ function Glyf.range(f: Face, g: number): (number?, number) return f.glyf + a, z - a end --- bounds(f, g) -> xMin, yMin, xMax, yMax from the glyph header (nil for empty glyphs) 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 @@ -65796,7 +64219,6 @@ function Glyf.bounds(f: Face, g: number): (number?, number, number, number) return i16(b, o + 2), i16(b, o + 4), i16(b, o + 6), i16(b, o + 8) end --- contours: { { xs, ys, on } } point lists in font units type Contour = { x: { number }, y: { number }, on: { boolean } } local MAX_POINTS = 65536 @@ -65827,7 +64249,6 @@ local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour if p > e then return nil, "instructions past the end" end - -- flags local flags = table.create(n, 0) local i = 1 while i <= n do @@ -65853,7 +64274,6 @@ local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour end end end - -- coordinates local xs = table.create(n, 0) local x = 0 for k = 1, n do @@ -65966,7 +64386,6 @@ local function composite(f: Face, o: number, len: number, depth: number): ({ Con if not child then return nil, err end - -- transform the child's points 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 } @@ -66027,7 +64446,7 @@ contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?) end local o, len = Glyf.range(f, g) if not o then - return {}, nil -- empty glyph (space) + return {}, nil end if len < 10 then return nil, "glyph header past the end" @@ -66039,7 +64458,6 @@ contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?) return composite(f, o, len, depth) end --- outline(f, g) -> path commands (codecs/image/Raster format, font units, y up) | nil, message function Glyf.outline(f: Face, g: number): ({ any }?, string?) local cs, err = contours(f, g, 0) if not cs then @@ -66084,7 +64502,7 @@ function Glyf.outline(f: Face, g: number): ({ any }?, string?) 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 -- back to the start + x, y, isOn = sx, sy, true end if isOn then if off then @@ -66106,7 +64524,6 @@ function Glyf.outline(f: Face, g: number): ({ any }?, string?) return cmds, nil end --- points(f, g) -> the number of points and contours (for tests) function Glyf.counts(f: Face, g: number): (number, number) local cs = contours(f, g, 0) if not cs then @@ -66123,13 +64540,8 @@ return Glyf end __FILES["codecs/font/TrueType/Tables"] = function() --- codecs/font/TrueType/Tables: the sfnt tables besides the outlines: cmap (formats 0, 4, 6, 10, 12, 13; the best Unicode --- subtable, symbol fonts through U+F000), kern (Microsoft version 0 and Apple version 1, format 0 pairs), GPOS pair --- kerning (lookup type 2 formats 1 and 2, reached through the 'kern' feature, including extension lookups, type 9), --- name (UTF-16BE and Mac Roman strings) and OS/2. Written from the OpenType spec, with stb_truetype 1.26 (public --- domain / MIT) as a reference for cmap 4 and the GPOS walk. --- --- Never throws: every read is range-checked (out of range reads as 0). +-- 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 = {} @@ -66158,10 +64570,9 @@ local function u32(b: buffer, o: number): number end Tables.u8, Tables.u16, Tables.i16, Tables.u32 = u8, u16, i16, u32 --- ------------------------------------------------------------------------------------------------ cmap type Cmap = { buf: buffer, at: number, format: number, symbol: boolean } --- pick the best subtable of the cmap table at [o, o + n): Unicode full repertoire, then BMP, then symbol, then Mac +-- 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 @@ -66226,7 +64637,6 @@ local function lookup(c: Cmap, cp: number): number local segX2 = u16(b, t + 6) local segs = segX2 // 2 local ends = t + 14 - -- binary search for the first segment whose end >= cp local lo, hi = 0, segs - 1 while lo < hi do local mid = (lo + hi) // 2 @@ -66277,7 +64687,6 @@ local function lookup(c: Cmap, cp: number): number return 0 end --- glyph(cmap, codepoint) -> glyph index (0 = .notdef) 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 @@ -66289,8 +64698,6 @@ function Tables.glyph(c: Cmap?, cp: number): number return g end --- ------------------------------------------------------------------------------------------------ kern --- the 'kern' table's horizontal format 0 pairs -> { [left * 65536 + right] = value } function Tables.kern(b: buffer, o: number, n: number): { [number]: number } local pairs: { [number]: number } = {} local e = o + n @@ -66343,7 +64750,6 @@ function Tables.kern(b: buffer, o: number, n: number): { [number]: number } return pairs end --- ------------------------------------------------------------------------------------------------ GPOS local function popcount(v: number): number local c = 0 while v ~= 0 do @@ -66353,7 +64759,6 @@ local function popcount(v: number): number return c end --- coverage index of glyph g in the Coverage table at t, or -1 local function coverage(b: buffer, t: number, g: number): number local fmt = u16(b, t) if fmt == 1 then @@ -66415,7 +64820,6 @@ local function classOf(b: buffer, t: number, g: number): number return 0 end --- the x advance adjustment in a value record with format vf at r local function xAdvance(b: buffer, r: number, vf: number): number if band(vf, 4) == 0 then return 0 @@ -66423,7 +64827,6 @@ local function xAdvance(b: buffer, r: number, vf: number): number return i16(b, r + 2 * popcount(band(vf, 3))) end --- one PairPos subtable: (applies, value) 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) @@ -66467,9 +64870,8 @@ local function pairPos(b: buffer, t: number, l: number, r: number): (boolean, nu return false, 0 end -type Gpos = { buf: buffer, subtables: { { number } } } -- per lookup: PairPos subtable offsets +type Gpos = { buf: buffer, subtables: { { number } } } --- the pair-adjustment lookups of the 'kern' feature (any script / language) of the GPOS table at [o, o + n) function Tables.gpos(b: buffer, o: number, n: number): Gpos? if n < 10 or u16(b, o) ~= 1 then return nil @@ -66520,7 +64922,6 @@ function Tables.gpos(b: buffer, o: number, n: number): Gpos? return { buf = b, subtables = lookups } end --- gposKern(gpos, left, right) -> the summed x advance adjustment of the first glyph (font units) function Tables.gposKern(g: Gpos, l: number, r: number): number local total = 0 for _, subs in g.subtables do @@ -66535,7 +64936,6 @@ function Tables.gposKern(g: Gpos, l: number, r: number): number return total end --- ------------------------------------------------------------------------------------------------ name, OS/2 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, @@ -66580,7 +64980,6 @@ local NAME_IDS: { [number]: string } = { [17] = "typographicStyle", } --- names(name table) -> { family, style, fullName, ... } (English Windows names first, then Unicode, then Mac Roman) function Tables.names(b: buffer, o: number, n: number): { [string]: string } local out: { [string]: string } = {} local rank: { [string]: number } = {} @@ -66614,7 +65013,6 @@ function Tables.names(b: buffer, o: number, n: number): { [string]: string } return out end --- os2(OS/2 table) -> the commonly used fields function Tables.os2(b: buffer, o: number, n: number): { [string]: number } local t: { [string]: number } = { version = u16(b, o), @@ -66646,26 +65044,14 @@ __FILES["codecs/image/Bcn"] = @native function() --- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...): --- decode of BC1 (DXT1, with the 3-colour + transparent mode), BC2 (DXT3), BC3 (DXT5), BC4 / BC5 (RGTC / ATI1 / ATI2, --- UNORM and SNORM), BC6H (UF16 / SF16, to rgbaf32) and BC7 (all 8 modes); encode of BC1 / BC3 / BC4 / BC5 (UNORM). --- Decoders ported from Pillow's BcnDecode.c (CC0) with the D3D11 rules; encoders new (stb_dxt-style). Never throws. --- --- local px, err = Bcn.decode("bc7", buf, offset, w, h) -- rgba8 pixels (rgbaf32 for bc6h / bc6hs) --- local blocks = Bcn.encode("bc1", rgba8Pixels, w, h) -- the block data (row-major blocks) --- Bcn.size("bc3", w, h) -- bytes of a w x h image (whole 4x4 blocks) --- --- Channels: BC4 decodes to grey (r = g = b, opaque), BC5 to red + green (blue 0, opaque); SNORM values are biased by --- 128 into rgba8 (-127 -> 1, 0 -> 128, 127 -> 255). BC1 / BC3 / BC5 encode reads R / G (BC4: R), BC1 alpha below --- opts.alphaThreshold (default 128) selects the transparent 3-colour mode. +-- 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 = {} --- kind -> bytes per 4x4 block 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 } --- kinds that decode to rgbaf32 Bcn.FLOAT = table.freeze({ bc6h = true, bc6hs = true }) :: { [string]: boolean } local readu32, writeu32 = buffer.readu32, buffer.writeu32 @@ -66687,7 +65073,6 @@ local BLOCKS: { [string]: (buffer, number, buffer) -> () } = { end, } --- size(kind, w, h) -> bytes of the block data (nil for an unknown kind) @native function Bcn.size(kind: string, w: number, h: number): number? local b = Bcn.BLOCK[kind] if not b then @@ -66696,8 +65081,6 @@ local BLOCKS: { [string]: (buffer, number, buffer) -> () } = { return ((w + 3) // 4) * ((h + 3) // 4) * b end --- decode(kind, src, offset, w, h, out?, outOffset?) -> pixels (rgba8, or rgbaf32 for BC6H) | nil, message. --- out (optional) receives the pixels at outOffset (default 0) instead of a new buffer. @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 @@ -66748,10 +65131,9 @@ end end type EncodeOptions = { - alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128; 0 = always opaque) + alphaThreshold: number?, } --- encode(kind, pixels, w, h, opts?) -> block data | nil, message. pixels: rgba8, w x h; kind = bc1 / bc3 / bc4 / bc5. @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) @@ -66769,12 +65151,9 @@ __FILES["codecs/image/Bcn/Decode"] = @native function() --- codecs/image/Bcn/Decode: the BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC). Ported from Pillow's --- src/libImaging/BcnDecode.c (CC0, licenses/pillow-bcn-CC0.txt) and changed to follow the D3D11 functional spec where --- Pillow does not: BC6H interpolation rounds ((a * (64 - w) + b * w + 32) >> 6), BC6H keeps its float values (no 8-bit --- clamp), BC7's reserved mode 8 and BC6H's reserved modes decode to transparent / zero, BC4 / BC5 SNORM interpolate --- the signed values (-128 reads as -127). Each decoder writes one 4x4 block into a 64-byte (rgba8) or 256-byte --- (rgbaf32) scratch block; the caller clips it into the image. Never throws: the caller checks the source size. +-- 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 = {} @@ -66783,8 +65162,7 @@ local readu8, readu16, readu32, writeu8, writeu32, writef32 = buffer.readu8, buf local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift local HALF = Half.TABLE --- ------------------------------------------------------------------------------------------------ BC1 / BC2 / BC3 -local pal = buffer.create(16) -- 4 rgba8 colours +local pal = buffer.create(16) @native local function c565(c: number): (number, number, number) local r = rshift(band(c, 0xF800), 8) @@ -66793,7 +65171,7 @@ local pal = buffer.create(16) -- 4 rgba8 colours return bor(r, rshift(r, 5)), bor(g, rshift(g, 6)), bor(b, rshift(b, 5)) end --- the BC1 colour block at p into blk (64 bytes); fourColour = BC2 / BC3 (always the 4-colour palette) +-- 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) @@ -66813,7 +65191,6 @@ end end end --- the 8 values of a BC3 alpha / BC4 block (unsigned) into vals local vals = table.create(8, 0) @native local function ramp8(a0: number, a1: number) vals[1], vals[2] = a0, a1 @@ -66846,7 +65223,6 @@ end end end --- one 8-byte BC3 alpha / BC4 block at p into byte `channel` of every blk pixel (and the next ones when spread) @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)) @@ -66906,7 +65282,6 @@ end bc5(src, p, blk, true) end --- ------------------------------------------------------------------------------------------------ BPTC tables -- 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, @@ -66950,7 +65325,6 @@ Decode.SI2, Decode.SI3, Decode.AI0, Decode.AI1, Decode.AI2, Decode.WEIGHTS = SI2 return 0 end --- the 128-bit block as four u32 words: bits(at, n) for n <= 16 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) @@ -66970,7 +65344,6 @@ end return band(v, lshift(1, n) - 1) end --- ------------------------------------------------------------------------------------------------ BC7 -- ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 local MODES7 = { { 3, 4, 0, 0, 4, 0, 1, 0, 3, 0 }, @@ -67109,7 +65482,6 @@ end end end --- ------------------------------------------------------------------------------------------------ BC6H -- ns, transformed, pb, epb, rb, gb, bb local MODES6 = { { 2, 1, 5, 10, 5, 5, 5 }, @@ -67188,7 +65560,6 @@ end return HALF[(v * 31) // 64] end --- one BC6H block into blk as rgbaf32 (256 bytes, alpha 1) @native function Decode.bc6h(src: buffer, p: number, blk: buffer, signed: boolean) load(src, p) local m = band(w0, 31) @@ -67269,11 +65640,8 @@ __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 by --- Fabian Giesen / Sean Barrett, public domain: the principal axis of the block's colours by power iteration, the --- extreme pixels along it as endpoints, then least-squares refinement of the endpoints for the chosen indices, keeping --- the best; single-colour blocks use exact endpoint tables). Indices are chosen against the palette exactly as --- Bcn/Decode rebuilds it. BC4 / BC5 channels try both the 8-value and the 6-value (+ 0 / 255) ramps. Never throws. +-- 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 @@ -67286,7 +65654,6 @@ end return bor(lshift(v, 2), rshift(v, 4)) end --- ------------------------------------------------------------------------------------------------ single colours -- 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 @@ -67324,7 +65691,6 @@ local OM: { { number } }? = nil return t end --- ------------------------------------------------------------------------------------------------ BC1 colour 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) @@ -67345,7 +65711,6 @@ local BEST = table.create(16, 0) end end --- indices for the palette into IDX (0-based); returns the squared error of the used pixels @native local function assign(four: boolean): number local n = if four then 4 else 3 local total = 0 @@ -67376,11 +65741,9 @@ end return qr * 2048 + qg * 32 + qb end --- the endpoint weights of index k (the e0 share) local W4 = { 1, 0, 2 / 3, 1 / 3 } local W3 = { 1, 0, 0.5, 0 } --- least squares endpoints for the current IDX: c0, c1 or nil when degenerate @native local function refine(four: boolean): (number?, number?) local W = if four then W4 else W3 local aa, bb, ab = 0, 0, 0 @@ -67410,8 +65773,6 @@ local W3 = { 1, 0, 0.5, 0 } return q565(r0, g0, b0), q565(r1, g1, b1) end --- encodes R / G / B (USE marks the pixels that count) as a BC1 colour block at out[o]; four = 4-colour mode --- (opaque), else the 3-colour mode with index 3 for the unused (transparent) pixels @native local function colourBlock(out: buffer, o: number, four: boolean) local n, mr, mg, mb = 0, 0, 0, 0 for i = 1, 16 do @@ -67544,7 +65905,6 @@ end writeu32(out, o + 4, bitsv) end --- ------------------------------------------------------------------------------------------------ BC4 channel local V = table.create(16, 0) local RAMP = table.create(8, 0) local SEL = table.create(16, 0) @@ -67582,7 +65942,6 @@ end return total end --- encodes V[1..16] (0..255) as an 8-byte BC4 block at out[o] @native local function channelBlock(out: buffer, o: number) local lo, hi = 255, 0 local lo2, hi2 = 255, 0 @@ -67648,8 +66007,6 @@ end writeu8(out, o + 7, rshift(hi24, 16)) end --- ------------------------------------------------------------------------------------------------ whole images --- the 4x4 block at bx, by of an rgba8 image into R / G / B / A (edge pixels repeat) @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) @@ -67662,7 +66019,6 @@ end end end --- encode(kind, rgba8 pixels, w, h, alphaThreshold) -> the block data (kind = bc1 / bc3 / bc4 / bc5) @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 @@ -67712,17 +66068,8 @@ end __FILES["codecs/image/Blend"] = @native function() --- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable --- blend modes of the W3C Compositing and Blending Level 1 spec (the Photoshop / Aseprite set), opacity, a grey layer --- mask, clipping (source-atop: the backdrop keeps its alpha) and dissolve. Shared by ops/LayerOps (flatten) and the --- layered formats that must write a composite (layered/psd). Never throws: rectangles are clipped to both buffers. --- --- Blend.composite(dst, dw, dh, src, sw, sh, x, y, opacity, "multiply", { clip = false, mask = m }) --- Blend.MODES.multiply -> true --- --- Mode names: normal dissolve darken multiply colorBurn linearBurn darkerColor lighten screen colorDodge linearDodge --- (= add) lighterColor overlay softLight hardLight vividLight linearLight pinLight hardMix difference exclusion --- subtract divide hue saturation color luminosity. Unknown names composite as normal. +-- 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 @@ -67876,9 +66223,6 @@ end return (r - mn) * k, (g - mn) * k, (b - mn) * k end --- composite(dst, dw, dh, src, sw, sh, x, y, opacity, mode, opts?): blends the sw x sh rgba8 src onto the dw x dh rgba8 --- dst with its top-left at (x, y). opacity 0..1. opts.clip: keep the backdrop's alpha (clipping masks). opts.mask: --- { pixels: buffer (1 byte per pixel), width, height, x, y, default: 0..255 } in dst coordinates (outside it: default). @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 @@ -67928,7 +66272,6 @@ end 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 - -- empty backdrop: the source as it is (alpha scaled) writeu32(dst, do_, readu32(src, so)) writeu8(dst, do_ + 3, floor(sa * 255 + 0.5)) else @@ -67985,9 +66328,6 @@ end end end --- lerp(dst, from, t, n, w?, mask?): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity); --- with a mask ({ pixels, width, height, x, y, default } as for composite, in the coordinates of a w-wide canvas) t is --- also scaled by the mask value of each pixel @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 @@ -68024,7 +66364,6 @@ end Blend.composite = composite Blend.lerp = lerp --- ------------------------------------------------------------------------------------------------ layer trees @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 @@ -68036,7 +66375,7 @@ end end local img = m.image local px = img.pixels - if img.format == "rgba8" then -- use the red channel + if img.format == "rgba8" then local n = img.width * img.height local g = buffer.create(n) for i = 0, n - 1 do @@ -68061,7 +66400,6 @@ end 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" - -- the layer's own pixels, as an isolated w x h buffer local src: buffer? = nil if type(l.children) == "table" then if mode == "passThrough" then @@ -68098,10 +66436,6 @@ end end end --- flatten(layers, canvas, w, h, hidden): composites a Types.Layer tree (bottom to top) onto the w x h rgba8 canvas: --- blend modes, opacity x fillOpacity, groups (isolated, or "passThrough": blended straight onto the canvas, the group --- opacity and mask then mixing before / after), clipping layers (clip = true: source-atop onto the layer below), grey masks. --- hidden = true includes invisible layers. @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) @@ -68115,16 +66449,8 @@ __FILES["codecs/image/Dct"] = @native function() -- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). --- Inverse: libjpeg's islow (jidctint.c: the Loeffler-Ligtenberg-Moschytz algorithm, 13-bit constants, two passes with --- PASS1_BITS of scaling between them), plus the reduced 4x4 / 2x2 / 1x1 IDCTs for scaled decodes (jidctred.c); the --- results match libjpeg-turbo's djpeg bit for bit. Absorbed from jpeg-luau 1.0 src/Jpeg/Idct.luau (same author). --- Forward: libjpeg's islow (jfdctint.c) with jcdctmgr.c's rounding quantiser, so an encoder built on it produces --- the same coefficients as cjpeg. Both are Luau translations of IJG code (licenses/libjpeg-turbo-LICENSE.md). --- Values are exact integers in doubles: no overflow even on corrupt coefficients; outputs are clamped to 0..maxv. --- --- Dct.idctComponent(coef, q, bpl, bpc, size, plane, p1, center, maxv) -- every block of a component --- Dct.idctBlock(coef, off, q, plane, out, stride, p1, center, maxv) -- one 8x8 block (u16 samples) --- Dct.fdctQuantize(src, stride, x, y, w, h, div, coef, off) -- one block from u8 samples +-- 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 @@ -68356,10 +66682,7 @@ end end end --- Inverse-transforms every block of a component: coef (i16, 64 per block, natural order) on a bpl x bpc block --- grid, quantisation table q (64 u16, natural order), into plane (u16 samples, (bpl * size) per row) at size x --- size samples per block. p1 is PASS1_BITS (2 for 8-bit, 1 for 12-bit), center the level shift, maxv the top. --- hook (optional): a cooperative yield point after every block row (pcall'ed: it can't throw through here). +-- 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 @@ -68383,13 +66706,10 @@ end end end --- idctBlock(coef, off, q, plane, out, stride, p1, center, maxv): one 8x8 block, coef (i16, natural order) at byte --- offset off, dequantised by q (64 u16), into the u16 plane at sample index out with stride samples per row @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 --- ------------------------------------------------------------------------------------------------ forward local fw = table.create(64, 0) @native local function quant(coef: buffer, off: number, div: buffer, v: number, i: number) @@ -68402,10 +66722,7 @@ local fw = table.create(64, 0) end end --- fdctQuantize(src, stride, x, y, w, h, div, coef, off): the 8x8 block of u8 samples at (x, y) in src (stride bytes --- per row; samples past w - 1 / h - 1 repeat the edge), level-shifted by 128, forward DCT (jfdctint.c islow), then --- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored, q = div (64 u16, natural order). Writes --- 64 i16 at coef[off] (natural order). The caller keeps x < w, y < h and the src range valid. +-- 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 @@ -68512,17 +66829,8 @@ __FILES["codecs/image/Etc"] = @native function() --- codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar --- modes), ETC2 RGBA (an EAC alpha block + ETC2 colour), ETC2 RGB A1 (punch-through alpha) and EAC R11 / RG11 --- (unsigned and signed). Written from the Khronos Data Format Specification 1.3, section 21 (ETC1 / ETC2 / EAC); new --- in rosetta. Shared by the texture formats (KTX, PVR, ...). Never throws: the caller gets a message instead. --- --- local px, err = Etc.decode("etc2_rgba", buf, offset, w, h) -- rgba8 pixels --- local px16 = Etc.decode("eac_rg11", buf, offset, w, h, nil, 0, true) -- rgba16 (EAC keeps its 11 bits) --- Etc.size("etc1", w, h) -- bytes of the block data --- --- Kinds: etc1, etc2_rgb, etc2_rgba, etc2_rgba1, eac_r11, eac_r11s, eac_rg11, eac_rg11s. R11 decodes to grey (r = g = b), --- RG11 to red + green (blue 0); signed values are biased (-1 -> 1, 0 -> 128, +1 -> 255; rgba16: 0 / 32768 / 65535). +-- 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 } @@ -68530,7 +66838,6 @@ Etc.BLOCK = table.freeze({ etc1 = 8, etc2_rgb = 8, etc2_rgba = 16, etc2_rgba1 = 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 --- ------------------------------------------------------------------------------------------------ tables local MOD = { -- the ETC1 intensity modifiers per table: index (msb * 2 + lsb) -> a, b, -a, -b { 2, 8, -2, -8 }, { 5, 17, -5, -17 }, @@ -68568,9 +66875,8 @@ end return clamp8(r) + clamp8(g) * 256 + clamp8(b) * 65536 + 0xFF000000 end --- ------------------------------------------------------------------------------------------------ colour blocks -- blk: 16 u32 rgba8 pixels in raster order (y * 4 + x) -local P = table.create(4, 0) -- T / H paint colours (rgba8 u32) +local P = table.create(4, 0) @native local function be32(src: buffer, p: number): number return byteswap(readu32(src, p)) @@ -68581,7 +66887,7 @@ end return band(rshift(lo, i + 15), 2) + band(rshift(lo, i), 1) end --- ETC1 / ETC2 colour block at p into blk. etc2: T / H / planar modes; punch: the RGB A1 variant (bit 33 = opaque). +-- 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) @@ -68653,7 +66959,6 @@ end r2, g2, b2 = R2 * 8 + rshift(R2, 2), G2 * 8 + rshift(G2, 2), B2 * 8 + rshift(B2, 2) end if not r1 then - -- T / H: the paint colours by index for i = 0, 15 do local x, y = rshift(i, 2), band(i, 3) local idx = pix(lo, i) @@ -68686,10 +66991,8 @@ end end end --- ------------------------------------------------------------------------------------------------ EAC local VALS = table.create(16, 0) --- the 16 values of the EAC block at p into VALS (raster order): mode "alpha" (8-bit), "u11" / "s11" (11-bit) @native local function eac(src: buffer, p: number, mode: string) local base = readu8(src, p) local b1 = readu8(src, p + 1) @@ -68722,7 +67025,6 @@ local VALS = table.create(16, 0) end end --- 11-bit values -> 8 / 16 bits @native local function to8(v: number, signed: boolean): number if signed then return math.floor(v * 127 / 1023 + 0.5) + 128 @@ -68736,15 +67038,11 @@ end return v * 32 + rshift(v, 6) end --- ------------------------------------------------------------------------------------------------ decode --- size(kind, w, h) -> bytes of the block data | nil for an unknown kind @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 --- decode(kind, src, offset, w, h, out?, outOffset?, wide?) -> pixels | nil, message. rgba8, or rgba16 for the EAC --- kinds when wide is true. @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 @@ -68829,17 +67127,11 @@ __FILES["codecs/image/Half"] = @native function() --- codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H, --- OpenEXR HALF channels). New in rosetta. Never throws. --- --- local f = Half.TABLE[h] -- the number of every half bit pattern 0..65535 (a 65536-entry table) --- local f = Half.toFloat(h) -- the same, computed --- local h = Half.fromFloat(f) -- round to nearest even; overflow -> infinity, NaN -> a quiet NaN +-- 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 --- toFloat(h) -> number (h a 16-bit pattern) @native local function toFloat(h: number): number local s = if h >= 32768 then -1 else 1 local e = band(rshift(h, 10), 31) @@ -68861,7 +67153,6 @@ Half.TABLE = TABLE local scratch = buffer.create(4) --- fromFloat(f) -> the nearest half bit pattern (ties to even) @native function Half.fromFloat(f: number): number if f ~= f then return 0x7E00 @@ -68903,36 +67194,9 @@ return Half end __FILES["codecs/image/Jpeg"] = function() --- codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG --- video tracks (AVI / Matroska / QuickTime) decode and encode their frames with it. The engine (Huffman and --- arithmetic scan decoding, IDCTs through codecs/image/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder) --- was absorbed from jpeg-luau 1.0 (same author) into image/jpeg and moved down here; it is bit-exact with libjpeg-turbo's --- djpeg and byte-identical with cjpeg. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md. --- --- local img, err = Jpeg.decode(buf, off?, len?, opts?) -- one JPEG -> rgba8 (or gray8 / yuv420p) Types.Image --- local img = Jpeg.decode(frame, 0, n, { yuv = true }) -- video: yuv420p straight from the IDCT planes --- local out, err = Jpeg.encode(img, opts?) -- rgba8 / rgb8 / gray8 / yuv420p Image -> buffer --- local info, err = Jpeg.info(buf, off?, len?) -- the headers up to the frame header --- --- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit --- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt --- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8), EXIF orientation --- (meta.orientation, applied with opts.orient). Truncated or corrupt scans decode as far as they go --- (meta.truncated = true). --- Motion-JPEG: frames without DHT segments use the T.81 annex K tables; the AVI1 APP0 segment is read (its field --- polarity) and data after EOI is ignored. Two fields back to back (AVI1 interlaced: two JPEGs of half the frame --- height, polarity 1 or 2, or opts.fields = true) are decoded and woven into one frame, the first field on the even --- rows (top field first, as ffmpeg, which ignores the polarity value); a missing or different-sized second field --- leaves the first field alone (meta.source.fields = 1). --- opts.yuv: 8-bit YCbCr frames come out as yuv420p (full-range BT.601, meta.source.range = "full") without colour --- conversion or upsampling: 4:2:0 (2x2 luma) as the planes are; 4:2:2 (2x1 luma, the usual Motion-JPEG camera --- layout) with each pair of chroma rows averaged; 4:4:4 with 2 x 2 chroma averages; grey with chroma 128. Other --- layouts (RGB, CMYK, 4:1:1, 4:4:0, 12-bit) and scaled decodes fall back to rgba8 (check img.format). --- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or --- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, extra APPn / COM segments --- (opts.segments); yuv420p input is coded from its planes as they are (4:2:0, no colour conversion). --- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, 12-bit or CMYK encoding. --- Never throws: bad data or arguments return nil, Err. +-- 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") @@ -68942,28 +67206,25 @@ local Yuv = __include("codecs/image/Jpeg/Yuv") local Jpeg = {} type DecodeOptions = { - scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only) - orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only; rgba8 / gray8) - native: boolean?, -- grey files decode to gray8 (default false: rgba8) - yuv: boolean?, -- 8-bit YCbCr / grey frames decode to yuv420p (default false); see the header for the layouts - fields: boolean?, -- two JPEGs back to back are two fields of one frame (default: when the AVI1 segment says so) - raw: boolean?, -- no colour conversion: 3 / 4 components as R, G, B (, A) bytes (default false; BLP1 BGRA JPEGs) - maxPixels: number?, -- refuse larger images (default 2^26) - -- a cooperative yield point, run after every MCU row of a scan, every block row of the IDCT and every 8 output - -- rows: e.g. a function that calls coroutine.yield() when a time budget is spent, so one image is decoded over - -- several frames (decode then runs inside a coroutine). Errors in it are ignored. + scale: number?, + orient: boolean?, + native: boolean?, + yuv: boolean?, + fields: boolean?, + raw: boolean?, + maxPixels: number?, yield: (() -> ())?, } type EncodeOptions = { - quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables - subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420"; yuv420p input is always 4:2:0) - progressive: boolean?, -- default false - optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises) - gray: boolean?, -- a one-component file (default: true for gray8 images) - restart: number?, -- restart interval in MCUs (default 0 = none) - jfif: boolean?, -- write the JFIF APP0 header (default true) - density: { unit: number, x: number, y: number }?, -- the JFIF density (default unit 0, 1 x 1) - segments: { { marker: number, data: buffer } }?, -- APPn / COM segments written after the JFIF header + 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 = { @@ -68974,11 +67235,11 @@ type Info = { arithmetic: boolean, precision: number, colorSpace: string, - sampling: { { number } }, -- { h, v } per component + sampling: { { number } }, orientation: number, adobe: number?, jfif: boolean, - avi1: number?, -- the AVI1 field polarity, when the segment comes before the frame header + avi1: number?, } local function range(buf: buffer, off: number?, len: number?): (number, number) @@ -68987,7 +67248,6 @@ local function range(buf: buffer, off: number?, len: number?): (number, number) return o, math.clamp(math.floor(tonumber(len) or (n - o)), 0, n - o) end --- the marker parser over [o, o + l): State | nil, Err 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 @@ -69007,7 +67267,6 @@ local function samplingOf(f: any): { { number } } return sampling end --- info(buf, off?, len?) -> Info | nil, Err (reads the headers up to the frame header) 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") @@ -69035,7 +67294,6 @@ function Jpeg.info(buf: buffer, off: number?, len: number?): (Info?, Err.Err?) nil end --- the EXIF orientation applied to rgba8 pixels: buffer, width, height 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 @@ -69068,7 +67326,6 @@ local function orient(px: buffer, w: number, h: number, o: number): (buffer, num return out, ow, oh end --- one JPEG at [o, o + l): Image, State | nil, Err 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 @@ -69135,14 +67392,14 @@ local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions? adobe = s.adobe, jfif = s.jfif, avi1 = s.avi1, - yuv = mode, -- "420" | "422" | "444" | "gray": how the yuv420p planes were made (opts.yuv) + yuv = mode, range = if mode then "full" else nil, fields = 1, } return img, s end --- the start of a second JPEG (FF D8 FF) at or after p, before e; -1 if none +-- 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 @@ -69154,7 +67411,6 @@ local function nextSoi(buf: buffer, p: number, e: number): number return -1 end --- two fields (same size and format) -> one frame of twice the height, field a on the even rows local function weave(a: Types.Image, b: Types.Image): Types.Image local w, hf = a.width, a.height local h = hf * 2 @@ -69162,7 +67418,7 @@ local function weave(a: Types.Image, b: Types.Image): Types.Image local dst = out.pixels if a.format == "yuv420p" then local cw, chf = (w + 1) // 2, (hf + 1) // 2 - local ch = (h + 1) // 2 -- = hf + 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) @@ -69175,7 +67431,6 @@ local function weave(a: Types.Image, b: Types.Image): Types.Image return out end --- decode(buf, off?, len?, opts?) -> Image | nil, Err: one JPEG (or one interlaced Motion-JPEG frame) in [off, off + len) 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") @@ -69211,10 +67466,8 @@ function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOption return img, nil end --- ------------------------------------------------------------------------------------------------ encode local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, yuv420p = 0 } --- encode(img, opts?) -> buffer | nil, Err: an rgba8 / rgb8 / gray8 / yuv420p Image as a baseline or progressive JPEG 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") @@ -69297,15 +67550,9 @@ __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) into quantised --- DCT coefficients (native; never throws). A Luau translation of libjpeg-turbo's jdarith.c (Guido Vollbeding's --- decoder, IJG licence: licenses/libjpeg-turbo-LICENSE.md) and the jaricom.c probability table. --- --- It reads the destuffed scan data that Scan.destuff produces (0xFF 0x00 already removed, RSTn positions recorded); --- past the end of a restart segment it reads zero bytes, the convention libjpeg follows when the decoder runs into a --- marker (libjpeg's encoder also drops trailing zero bytes, so reading past the end is normal and not a sign of --- truncation: the caller flags a scan that runs into the end of the file instead). Statistics bins live in one buffer: DC tables at [t * 64], AC tables at [256 + t * 256], the fixed 0.5 --- bin at [1280]. +-- 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 @@ -69346,7 +67593,7 @@ do end end -local ZZ: buffer = buffer.create(80) -- set by Arith.init (Scan.ZIGZAG) +local ZZ: buffer = buffer.create(80) local STATS = 1281 local POW2 = buffer.create(8) @@ -69355,11 +67602,10 @@ for i = 0, 7 do end local FIXED = 1280 --- decoder state (one scan at a time; never yields) local D: buffer = buffer.create(0) -local P = 0 -- next byte -local SEGEND = 0 -- reads at or past this return 0 -local OVER = 0 -- zero bytes supplied past the end +local P = 0 +local SEGEND = 0 +local OVER = 0 local C, A, CT = 0, 0, -16 local st: buffer = buffer.create(STATS) @@ -69426,7 +67672,7 @@ type ArithComp = { v: number, bw: number, bh: number, - dcTbl: number, -- 0..3 + dcTbl: number, acTbl: number, pred: number, ctx: number, @@ -69437,16 +67683,16 @@ type ArithParams = { mcusX: number, mcusY: number, ri: number, - mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine + mode: number, ss: number, se: number, al: number, - dcL: { number }, -- conditioning per table (DAC), 1-based by table + 1 + dcL: { number }, dcU: { number }, acK: { number }, } --- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24); returns the new predictor or nil on a bad code +-- 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 @@ -69490,7 +67736,7 @@ type ArithParams = { return band(c.pred + v, 0xFFFF) end --- AC coefficients k = ss..se of one block (figure F.20); false on a bad code +-- 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 @@ -69588,7 +67834,6 @@ end ZZ = zigzag end --- run(d, cleanLen, rst, nrst, P) -> truncated: decodes one scan (see Scan.run for the data layout) @native function Arith.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, Pm: ArithParams): boolean local comps = Pm.comps local nc = #comps @@ -69713,19 +67958,9 @@ __FILES["codecs/image/Jpeg/Color"] = @native function() --- codecs/image/Jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never --- throws). Absorbed from jpeg-luau 1.0 src/Jpeg/Color.luau (same author); a Luau translation of libjpeg-turbo's --- jdsample.c / jdcolor.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md). --- --- Upsampling follows libjpeg-turbo's jdsample.c, so the output matches djpeg's defaults: --- FULL the component is at output resolution --- H2V1 "fancy" triangle filter, 3/4 nearer + 1/4 further sample, alternating rounding (1, 2) / 4 --- H2V2 fancy in both directions: vertical 3:1 column sums, then horizontal 3:1, rounding (8, 7) / 16 --- H1V2 fancy vertical only, rounding 1 (upper row) / 2 (lower row) --- REPLICATE any other ratio (or no fancy upsampling): nearest sample, as int_upsample --- Edges replicate the last real sample (downW x downH), as libjpeg does with its context rows. --- Colour conversion is jdcolor.c's table-driven YCbCr -> RGB (16-bit fixed point), plus grey, RGB, CMYK and --- YCCK (Adobe inverted CMYK: R = C * K / 255). +-- 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 @@ -69743,20 +67978,20 @@ Color.RGB = 2 Color.CMYK = 3 Color.YCCK = 4 Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted -Color.RAW = 6 -- no conversion: components 1..4 as R, G, B, A (opts.raw: BLP1's BGRA JPEGs, ...) +Color.RAW = 6 type Comp = { - plane: buffer, -- u16 samples, stride per row + plane: buffer, stride: number, - rows: number, -- plane height - downW: number, -- real samples across / down (the rest is block padding) + rows: number, + downW: number, downH: number, method: number, hIn: number, hOut: number, vIn: number, vOut: number, - row: buffer, -- scratch row (u16, at least max(outW, 2 * downW) + 8 samples) + row: buffer, } type Params = { @@ -69766,13 +68001,12 @@ type Params = { outH: number, maxv: number, pixels: buffer, - -- YCbCr tables (maxv + 1 i32 entries) crr: buffer, cbb: buffer, crg: buffer, cbg: buffer, - toByte: buffer?, -- maxv + 1 u8 entries (12-bit), nil for 8-bit - hook: (() -> ())?, -- a cooperative yield point every 8 rows (pcall'ed: it can't throw through here) + toByte: buffer?, + hook: (() -> ())?, } -- jdcolor.c build_ycc_rgb_table @@ -69793,7 +68027,6 @@ type Params = { return crr, cbb, crg, cbg end --- fills c.row with output row y; returns the buffer and byte offset of the row's samples @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 @@ -69909,7 +68142,6 @@ end continue end if space == 1 and not toByte then - -- the common case: 8-bit YCbCr 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) @@ -69961,12 +68193,9 @@ return Color end __FILES["codecs/image/Jpeg/Decode"] = function() --- codecs/image/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan / --- Arith / Dct / Color / Yuv loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended: --- arithmetic-coded frames (SOF9 / SOF10, DAC), a byte range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM --- / JFIF density collected for meta, the AVI1 APP0 field polarity and the end of the image (Motion-JPEG), and a --- yuv420p output straight from the IDCT planes (outputYuv). The IDCT size choice for scaled decodes follows --- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/image/Jpeg/Decode for the video formats. +-- 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") @@ -69998,7 +68227,7 @@ local function stdTable(class: string, slot: number): buffer? return stdBuilt[key] end --- the EXIF TIFF block (after "Exif\0\0") and its orientation tag, from an APP1 segment at [p, e) +-- 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 @@ -70053,7 +68282,7 @@ type Comp = { bw: number, bh: number, coef: buffer?, - quant: buffer?, -- latched at the component's first scan + quant: buffer?, dct: buffer?, act: buffer?, dcTbl: number, @@ -70086,7 +68315,6 @@ local SOF_REFUSED = { [0xCF] = "hierarchical arithmetic-coded", } --- failures carry a code: "corrupt" | "unsupported" | "limit" | "truncated" local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, string?, string?) if e - p < 6 then return nil, "corrupt", "short SOF" @@ -70190,15 +68418,13 @@ type State = { icc: buffer?, comments: { string }, truncated: boolean, - raw: boolean, -- opts.raw: no colour conversion + raw: boolean, scale: number, avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back) - endPos: number, -- the byte after the EOI marker (or the end of the data) - hook: (() -> ())?, -- opts.yield: the cooperative yield point (scans, IDCT, colour conversion) + endPos: number, + hook: (() -> ())?, } --- parse(b, base, limit, opts, headerOnly) -> State | nil, code, message. Walks the markers in b[base, limit); with --- headerOnly it stops at the frame header, otherwise it decodes every scan into the components' coefficients. 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)" @@ -70549,7 +68775,6 @@ end local toByte12: buffer? = nil --- output(st) -> width, height, rgba8 pixels, colour space | nil, code, message function Decode.output(st: State): (number?, any, any, string?) local f: Frame = st.frame local scale = st.scale @@ -70604,7 +68829,7 @@ function Decode.output(st: State): (number?, any, any, string?) vOut = vOut, row = buffer.create((math.max(outW, 2 * stride) + 8) * 2), }) - c.coef = nil -- free the coefficients early + c.coef = nil end local space = colorSpaceOf(f, st.adobe, st.jfif) local spaceId = SPACE_IDS[space] @@ -70644,14 +68869,8 @@ function Decode.output(st: State): (number?, any, any, string?) return outW, outH, pixels, space end --- outputYuv(st) -> width, height, yuv420p pixels, sampling | nil when the frame has no direct yuv420p form (the --- caller falls back to output). The IDCT output planes as they are, cropped to the image, without colour conversion --- or upsampling: 8-bit YCbCr whose chroma is sampled at half the luma rate both ways ("420", 2x2 / 1x1); half --- horizontally ("422", 2x1 / 1x1 or ffmpeg's 2x2 / 1x2: each pair of chroma rows averaged, rounding up); at the luma --- rate ("444", 1x1 or ffmpeg's 1x2 everywhere: each 2 x 2 chroma block averaged, rounding to nearest); grey ("gray": --- chroma 128). Full scale only (opts.scale = 1). --- one IDCT plane at a time is live (each is cropped into the output before the next component): frame-sized planes --- (up to 4 MB) are kept between calls, so a stream of video frames does not allocate them per frame +-- 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 @@ -70696,7 +68915,7 @@ function Decode.outputYuv(st: State): (number?, number?, buffer?, string?) end for _, c in comps do if c.coef and not c.quant then - return nil, nil, nil, nil -- output() reports the missing table + return nil, nil, nil, nil end end local w, h = f.width, f.height @@ -70736,14 +68955,9 @@ __FILES["codecs/image/Jpeg/Encode"] = @native function() --- codecs/image/Jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman --- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr --- 4:4:4 / 4:2:2 / 4:2:0, or yuv420p planes coded as they are (4:2:0, no colour conversion: the Motion-JPEG --- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/image/Jpeg/Encode. It follows libjpeg-turbo's --- encoder step for step so that its output is byte-identical to cjpeg's for the same settings: jccolor.c --- (fixed-point RGB -> YCbCr), jcsample.c (box downsampling with alternating rounding bias, right-edge replication), --- jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c (codecs/image/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs, --- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md. +-- 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") @@ -70773,7 +68987,6 @@ do end Encode.ZIGZAG = ZZ --- ------------------------------------------------------------------------------------------------ output local OUT = buffer.create(0) local OP = 0 local CAP = 0 @@ -70835,7 +69048,6 @@ end return if v == 0 then 0 else 32 - countlz(v) end --- ------------------------------------------------------------------------------------------------ Huffman tables -- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl) type Derived = { code: buffer, size: buffer } @@ -70957,7 +69169,6 @@ end end Encode.optimal = optimal --- ------------------------------------------------------------------------------------------------ entropy coding state local dcTab: { Derived } = {} local acTab: { Derived } = {} local dcFreq: { { number } } = {} @@ -70976,14 +69187,14 @@ type Comp = { h: number, v: number, tq: number, - td: number, -- DC table slot - ta: number, -- AC table slot - bw: number, -- real blocks across / down + td: number, + ta: number, + bw: number, bh: number, - bpl: number, -- MCU-padded block grid + bpl: number, bpc: number, - coef: buffer, -- i16, 64 per block, natural order - last: number, -- DC predictor + coef: buffer, + last: number, } @native local function dcDiff(c: Comp, diff: number) @@ -71114,7 +69325,7 @@ local absv = table.create(64, 0) end end local r = 0 - local br = 0 -- correction bits added in this block, at CORR[brStart + 1 ..] + local br = 0 local brStart = BE for k = ss, se do local t = absv[k + 1] @@ -71160,10 +69371,8 @@ local absv = table.create(64, 0) end end --- ------------------------------------------------------------------------------------------------ scans type ScanSpec = { comps: { number }, ss: number, se: number, ah: number, al: number } --- iterate the scan's MCUs (or blocks, for one component), calling fn(c, off) per block; restart markers when ri > 0 @native local function walk(comps: { Comp }, mcusX: number, mcusY: number, ri: number, onRestart: (number) -> (), fn: (Comp, number) -> ()) local nc = #comps local units, ux @@ -71225,7 +69434,6 @@ end byte(ah * 16 + al) end --- ------------------------------------------------------------------------------------------------ planes -- jccolor.c rgb_ycc_start tables (16-bit fixed point) @native local function fix(x: number): number return math.floor(x * 65536 + 0.5) @@ -71235,7 +69443,6 @@ 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 --- pixels (rgba8 / rgb8 / gray8) -> Y, Cb, Cr planes (w * h bytes each; Cb / Cr nil for grey output) @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) @@ -71269,8 +69476,7 @@ local OFF = 128 * 65536 + 32768 - 1 return Y, Cb, Cr end --- jcsample.c: a full-resolution plane (w x h) -> the component's samples, (bw * 8) x ch, for factors hf x vf --- (1 or 2 each); full-resolution columns past w - 1 repeat the last one, rows past h - 1 the last row +-- 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 @@ -71297,22 +69503,18 @@ end return out end --- ------------------------------------------------------------------------------------------------ encode type Options = { - quality: number, -- 1..100 - sampling: string, -- "444" | "422" | "420" + quality: number, + sampling: string, progressive: boolean, - optimize: boolean, -- baseline: optimised Huffman tables (progressive always optimises) + optimize: boolean, gray: boolean, - restart: number, -- MCUs per restart interval (0 = none) - segments: { { marker: number, data: buffer } }, -- APPn / COM segments after the JFIF header + restart: number, + segments: { { marker: number, data: buffer } }, jfif: boolean, density: { unit: number, x: number, y: number }?, } --- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8), or bpp 0: --- yuv420p (w * h luma, then ceil(w / 2) * ceil(h / 2) Cb and Cr; opts.sampling must be "420" unless opts.gray). The --- caller validated sizes (1..65535), the buffer length and options. @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) @@ -71354,7 +69556,6 @@ type Options = { qdiv[t] = b end - -- components and their quantised coefficients local comps: { Comp } = {} local srcs = if o.gray then { Y } else { Y, Cb :: buffer, Cr :: buffer } for i, src in srcs do @@ -71403,7 +69604,6 @@ type Options = { comps[i] = c end - -- headers byte(0xFF) byte(0xD8) if o.jfif then @@ -71580,7 +69780,6 @@ type Options = { walk(sComps, mcusX, mcusY, o.restart, onRestart, blockFn) emitEobrun() end - -- gather statistics, then emit the optimal tables this scan uses if not (isDc and ah > 0) then GATHER = true for t = 1, ntab do @@ -71637,16 +69836,8 @@ __FILES["codecs/image/Jpeg/Scan"] = @native function() --- codecs/image/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from --- jpeg-luau 1.0 src/Jpeg/Scan.luau (same author); unchanged but for this header. --- --- `destuff` copies one scan's entropy-coded bytes into a clean buffer: it drops the stuffed 0x00 after each 0xFF, --- records where each RSTn marker fell, and stops at any other marker. The clean buffer is followed by at least --- PAD zero bytes, so the bit reader can read 32 bits at any position up to PAD bytes past the end without a --- bounds check. `run` checks the position once per MCU, and no MCU (at most 10 blocks, enforced by the parser) --- can consume PAD bytes. So every buffer index stays in range, even on garbage data. --- --- The bit reader keeps no state but a bit position: `peek` reads the big-endian 32-bit word that holds it. +-- 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 @@ -71694,8 +69885,7 @@ do end Scan.ZIGZAG = ZZ --- Builds a Huffman table from the 16 code-length counts and the symbols (Luau arrays, 1-based). An --- over-subscribed table keeps the codes that fit; the rest decode as invalid. +-- 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 @@ -71723,7 +69913,6 @@ Scan.ZIGZAG = ZZ writeu8(t, T_VAL + i - 1, symbols[i]) end writeu16(t, T_COUNT, k) - -- fast lookups for i = 1, k do local l = sizes[i] if l <= 9 then @@ -71746,9 +69935,6 @@ Scan.ZIGZAG = ZZ return t end --- Copies the entropy-coded data at src[pos..n) into dst (at least n - pos + PAD bytes): byte stuffing removed, --- RSTn offsets (in dst) stored in rst[1..]. Returns the source position of the marker that ended the scan (or n), --- the clean length, and the RST count. The PAD bytes after the clean data are zeroed. @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 @@ -71806,7 +69992,6 @@ end return readu8(t, T_VAL + idx), pos + l end --- the next s bits (1 <= s <= 16) as an unsigned number @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 @@ -71818,7 +70003,6 @@ end return v end --- sequential (baseline / extended) block: returns pos, DC predictor @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) @@ -71990,11 +70174,11 @@ end end type ScanComp = { - coef: buffer, -- i16 coefficients, 64 per block in natural order, blocks row-major on a bpl-wide grid + coef: buffer, bpl: number, h: number, v: number, - bw: number, -- blocks across / down the component itself (non-interleaved scans) + bw: number, bh: number, dct: buffer?, act: buffer?, @@ -72005,16 +70189,14 @@ type ScanParams = { comps: { ScanComp }, mcusX: number, mcusY: number, - ri: number, -- restart interval in MCUs (0 = none) - mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine + ri: number, + mode: number, ss: number, se: number, al: number, - hook: (() -> ())?, -- a cooperative yield point after every MCU row (pcall'ed: it can't throw through here) + hook: (() -> ())?, } --- Decodes one scan from the clean data d (cleanLen bytes, then PAD zeros). Returns the final bit position and --- whether the data ran out (or overran) before the last MCU. @native function Scan.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, P: ScanParams): (number, boolean) local comps = P.comps local nc = #comps @@ -72162,7 +70344,6 @@ Tables.CHROMA = { 99, 99, 99, 99, 99, 99, 99, 99, } --- quant(base, quality) -> 64 values (natural order) for quality 1..100, clamped to 1..255 (baseline) 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 @@ -72179,23 +70360,18 @@ __FILES["codecs/image/Jpeg/Yuv"] = @native function() --- codecs/image/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16 --- samples, block-padded) cropped into u8 yuv420p planes without colour conversion or upsampling, 4:2:2 / 4:4:4 --- chroma reduced to 4:2:0 by averaging, and the interleaving of two fields (AVI1 interlaced Motion-JPEG). --- The callers (codecs/image/Jpeg/Decode, codecs/image/Jpeg) size every buffer; each loop reads and writes inside those sizes. +-- 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 = {} --- crop(src, stride, w, h, dst, doff): the top-left w x h samples of a u16 plane (stride samples per row) into u8 --- samples at dst[doff], w per row @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 - -- four samples (two u32 reads of two u16 samples, each 0..255) per u32 write 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) @@ -72208,8 +70384,6 @@ local Yuv = {} end end --- rows(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:2:2 chroma) -> u8 w x ceil(h / 2), each output --- row the rounded mean of two source rows (the last row alone when h is odd) @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 @@ -72222,8 +70396,6 @@ end end end --- box(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:4:4 chroma) -> u8 ceil(w / 2) x ceil(h / 2), --- each output sample the rounded mean of a 2 x 2 block (edges repeat the last row / column) @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 @@ -72238,8 +70410,6 @@ end end end --- weave(top, toff, bottom, boff, rowBytes, rows, dst, doff): interleave rows of two planes (field 1 on the even rows, field --- 2 on the odd rows) into rows output rows at dst[doff]; top holds ceil(rows / 2) rows, bottom floor(rows / 2) @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 @@ -72257,21 +70427,13 @@ __FILES["codecs/image/Pixels"] = @native function() --- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP, --- the DIBs inside ICO / CUR, ...): 1 / 2 / 4 / 8-bit indexes through a palette, BGR / BGRA, 5-5-5, bit-masked 16 / --- 24 / 32-bit pixels, RLE4 / RLE8, rows bottom-up or top-down; and the encoder direction (rgba8 -> BGR / BGRA / --- 8-bit indexes, bottom-up). Absorbed from bmp-luau b86aed6 (same author, no third-party code); the encoder loops --- are new. They never throw: the caller validates every size first and hands in a source buffer that holds every --- byte an uncompressed loop can read (a truncated file is copied into a zero-padded buffer); the RLE loop checks each --- read against its end offset. Output: rgba8, top-down rows, one u32 per pixel (bytes R, G, B, A). +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. +-- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8. From bmp-luau b86aed6 (same author); the encoder loops are new. local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift local Pixels = {} --- palette(src, base, n, bgr?) -> a 256-entry u32 palette for indexed(): n RGB triples (BGR when bgr) at src[base..], --- opaque; entries past n (or past the end of src) are opaque black. The game formats' 768-byte palettes (PLAYPAL, --- Quake palette.lmp, Half-Life MDL / WAD3 / BSP 30 textures). @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 @@ -72290,7 +70452,6 @@ local Pixels = {} return pal end --- 1, 2, 4 and 8 bpp through a 256-entry u32 palette (pal) @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 @@ -72344,7 +70505,7 @@ end end end --- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks). Returns the OR of every alpha byte. +-- 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 @@ -72353,7 +70514,6 @@ end 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) - -- swap R and B: B G R A -> R G B A writeu32(dst, d + x * 4, bor(band(p, 0xFF00FF00), band(rshift(p, 16), 0xFF), lshift(band(p, 0xFF), 16))) aor = bor(aor, p) end @@ -72361,9 +70521,6 @@ end return rshift(aor, 24) end --- 16 / 24 / 32 bpp through bit masks. sh* = shift of each mask, m* = mask >> shift, t* = scale tables (u8, one entry --- per masked value). A channel without a mask has m = 0 and a 1-entry table (0 for colour, 255 for alpha). --- Returns the OR of every masked alpha value (before scaling). @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 @@ -72394,16 +70551,14 @@ end return aor end --- Sets every alpha byte to 255 (32-bit images whose alpha channel is all zero are opaque). +-- 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 from src[pos, stop) into dst (pre-filled with transparent black; pixels the stream skips with a --- delta, an early end of line or an early end of bitmap stay transparent). Malformed or truncated data stops the --- decode and keeps what was drawn. Returns the number of pixels written. +-- 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 @@ -72477,7 +70632,6 @@ end return written end --- Encoder: rgba8 (top-down) -> 24 bpp BGR rows, bottom-up, each padded to stride (dst is zero-filled) @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 @@ -72492,20 +70646,17 @@ end end end --- rgba8 -> 32 bpp BGRA, bottom-up @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) - -- R G B A (little-endian u32: R | G << 8 | B << 16 | A << 24) -> B G R A writeu32(dst, d + x * 4, bor(band(v, 0xFF00FF00), band(rshift(v, 16), 255), lshift(band(v, 255), 16))) end end end --- rgba8 -> 8 bpp indexes through idx (a table colour -> index, colours as R | G << 8 | B << 16), bottom-up @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 @@ -72516,8 +70667,6 @@ end end end --- colours(src, n, max) -> the distinct RGB colours in first-appearance order (R | G << 8 | B << 16), whether any --- alpha is below 255; stops counting at max + 1 colours @native function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boolean) local seen: { [number]: boolean } = {} local list: { number } = {} @@ -72542,20 +70691,9 @@ __FILES["codecs/image/Quantize"] = @native function() --- codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette --- writer) builds on it. New code: Heckbert's median cut and Gervautz-Purgathofer octree, both over a 5-bit-per-channel --- weighted histogram (palette colours are the exact means of the pixels they cover), nearest-colour mapping with --- optional Floyd-Steinberg error diffusion. Deterministic: the same palette and indexes on every runtime (no table --- iteration order is ever relied on). --- --- local pal, exact = Quantize.palette(pixels, w, h, 256, { method = "mediancut" }) -- { {r, g, b, 255} }, boolean --- local idx = Quantize.map(pixels, w, h, pal, { dither = true, transparentIndex = 255 }) -- buffer of w * h u8 --- --- Pixels with alpha < 128 are "transparent": palette() ignores them, map() gives them opts.transparentIndex (0-based) --- when set (otherwise they map like opaque pixels). When the opaque pixels have at most maxColors distinct colours, --- palette() returns exactly those (in first-seen order) and exact = true, and map() is then lossless. The octree --- folds whole nodes, so it may return fewer than maxColors entries; below 8 colours median cut is used instead. --- Never throws: bad arguments give an empty palette / a zero-filled index buffer. +-- 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 @@ -72563,18 +70701,17 @@ local blen = buffer.len local Quantize = {} -type Color = { number } -- { r, g, b, a } 0..255 +type Color = { number } type PaletteOptions = { - method: ("mediancut" | "octree")?, -- default "mediancut" + method: ("mediancut" | "octree")?, } type MapOptions = { - dither: boolean?, -- Floyd-Steinberg error diffusion (default false) - transparentIndex: number?, -- 0-based index for pixels with alpha < 128 (default: none) + dither: boolean?, + transparentIndex: number?, } local BINS = 32768 -- 5 bits per channel --- ------------------------------------------------------------------------------------------------ helpers @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) @@ -72609,7 +70746,6 @@ end return { floor(r / n + 0.5), floor(g / n + 0.5), floor(b / n + 0.5), 255 } end --- ------------------------------------------------------------------------------------------------ median cut @native local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color } local bins: { number } = {} for bin = 0, BINS - 1 do @@ -72620,7 +70756,6 @@ end if #bins == 0 then return {} end - -- boxes: { lo, hi } ranges of the bins array local boxes: { { number } } = {} @native local function channel(bin: number, c: number): number if c == 0 then @@ -72631,7 +70766,6 @@ end return bin % 32 end @native local function stats(box: { number }): (number, number, number) - -- returns the widest channel, its range, the pixel count local mins, maxs = { 31, 31, 31 }, { 0, 0, 0 } local n = 0 for i = box[1], box[2] do @@ -72705,11 +70839,10 @@ end return pal end --- ------------------------------------------------------------------------------------------------ octree --- over the histogram bins: 5 levels (one bit of each channel per level). Nodes are array slots. +-- 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 } = {} -- pixel count + local n: { number } = {} local sr: { number }, sg: { number }, sb: { number } = {}, {}, {} local leaf: { boolean } = {} local level: { number } = {} @@ -72718,7 +70851,7 @@ end for k = 1, 8 do child[k] = 0 end - local byLevel: { { number } } = { {}, {}, {}, {}, {} } -- inner nodes per level 0..4, creation order + local byLevel: { { number } } = { {}, {}, {}, {}, {} } table.insert(byLevel[1], 1) local leaves = 0 for bin = 0, BINS - 1 do @@ -72756,7 +70889,6 @@ 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 - -- merges the children (all leaves) into node; returns how many leaves disappeared local merged = 0 for k = 1, 8 do local slot = (node - 1) * 8 + k @@ -72805,7 +70937,6 @@ end leaves -= fold(e[1]) end end - -- collect leaves depth first in child order local pal: { Color } = {} @native local function walk(node: number) if leaf[node] then @@ -72830,15 +70961,12 @@ end return pal end --- ------------------------------------------------------------------------------------------------ palette --- palette(pixels, w, h, maxColors, opts?) -> palette, exact @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 - -- exact colours, in first-seen order (stops counting past maxColors) local seen: { [number]: boolean } = {} local exact: { Color } = {} local over = false @@ -72868,8 +70996,6 @@ end return medianCut(cnt, sums, maxc), false end --- ------------------------------------------------------------------------------------------------ map --- map(pixels, w, h, palette, opts?) -> buffer of w * h palette indexes (0-based) @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) @@ -72878,7 +71004,6 @@ end local out = buffer.create(npx) local dither = opts and opts.dither or false local tidx = opts and opts.transparentIndex - -- the searchable entries (the transparent slot is excluded) local pr: { number }, pg: { number }, pb: { number }, pi: { number } = {}, {}, {}, {} for i, c in palette do if tidx == nil or i - 1 ~= tidx then @@ -72903,7 +71028,7 @@ end end pr, pg, pb, pi = r2, g2, b2, i2 end - local startAt = table.create(256, np) -- the first entry with green >= g (1-based), np + 1 past the end + local startAt = table.create(256, np) do local k = 1 for g = 0, 255 do @@ -72972,7 +71097,6 @@ end end return out end - -- Floyd-Steinberg: error rows (f64 r, g, b per pixel, one extra pixel each side) local rowLen = (w + 2) * 24 local cur, nxt = buffer.create(rowLen), buffer.create(rowLen) for y = 0, h - 1 do @@ -73010,13 +71134,12 @@ end return out end --- quantize(pixels, w, h, maxColors, opts?) -> indexes, palette, exact: palette() then map() (opts of both) @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 -- nothing to diffuse + mo.dither = false end return Quantize.map(pixels, w, h, pal, mo), pal, exact end @@ -73027,29 +71150,9 @@ __FILES["codecs/image/Raster"] = @native function() --- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine --- transform, with the nonzero and even-odd fill rules, plus a polygon stroker. Used by the fonts (glyph outlines) and --- by vector/svg. New code; the coverage accumulation is the signed-area method of font-rs (Raph Levien, Apache-2.0 / --- MIT, an algorithm description, no code copied) and of stb_truetype v2: every edge adds its exact signed area to an --- accumulation row; a running sum along the row gives the winding coverage of each pixel. The rules map the summed --- coverage a as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2. --- --- local R = require("@rosetta/codecs/image/Raster") --- local p = R.path():moveTo(0, 0):lineTo(10, 0):quadTo(10, 10, 0, 10):close() -- or a plain command list: --- local cmds = { { op = "moveTo", 0, 0 }, { op = "lineTo", 10, 0 }, { op = "cubicTo", 12, 2, 12, 8, 10, 10 }, --- { op = "close" } } -- (the Font:outline() format) --- local m = R.mask(cmds, { transform = { 2, 0, 0, 2, 5, 5 }, rule = "evenodd", clip = { 0, 0, 64, 64 } }) --- -- m = { x, y, width, height, coverage: buffer (u8, width * height) } in device pixels, or nil when empty --- R.fill(img, cmds, { 255, 0, 0, 255 }, { transform = t }) -- composite onto an rgba8 Image (source over) --- R.fill(img, cmds, function(x, y) return r, g, b, a end) -- a paint function per covered pixel (gradients) --- local outline = R.stroke(cmds, { width = 2, join = "round", cap = "butt" }) -- a path to fill (nonzero) --- --- Transforms are { a, b, c, d, e, f } (SVG matrix order): x' = a x + c y + e, y' = b x + d y + f. Coordinates are --- pixels with y down; a pixel (i, j) covers [i, i+1) x [j, j+1). Curves are flattened in device space to --- opts.tolerance (default 0.1 px). Subpaths are implicitly closed for filling. --- --- Never throws: malformed commands (missing or non-number operands) are skipped, non-finite coordinates drop the --- edge, sizes are bounded by opts.maxPixels (default 2^26), so it is safe for native code and untrusted paths. +-- 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 @@ -73061,20 +71164,19 @@ type Path = { Cmd } type Transform = { number } type Mask = { x: number, y: number, width: number, height: number, coverage: buffer } type Options = { - transform: Transform?, -- default identity - rule: ("nonzero" | "evenodd")?, -- default "nonzero" - clip: { number }?, -- { x0, y0, x1, y1 } device pixel bounds (integers); default: the path's bounds (fill: the image) - tolerance: number?, -- curve flattening tolerance in device pixels (default 0.1) - maxPixels: number?, -- largest mask (default 2^26) - opacity: number?, -- fill: multiplies the coverage (0..1, default 1) + 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 +-- 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 }) --- multiply(m, n) -> m * n (apply n first, then m) @native function Raster.multiply(m: Transform, n: Transform): Transform return { m[1] * n[1] + m[3] * n[2], @@ -73095,7 +71197,6 @@ end local c, s = math.cos(radians), math.sin(radians) return { c, s, -s, c, 0, 0 } end --- invert(m) -> m^-1 | nil (singular) @native function Raster.invert(m: Transform): Transform? local det = m[1] * m[4] - m[2] * m[3] if det == 0 or det ~= det then @@ -73105,18 +71206,14 @@ end local a, b, c, d = m[4] * id, -m[2] * id, -m[3] * id, m[1] * id return { a, b, c, d, -(a * m[5] + c * m[6]), -(b * m[5] + d * m[6]) } end --- apply(m, x, y) -> x', y' @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 --- ------------------------------------------------------------------------------------------------ path builder local Builder = {} Builder.__index = Builder type Builder = typeof(setmetatable({} :: { cmds: Path }, Builder)) --- path() -> a Builder; every method returns the builder; builder.cmds is the command list (any API taking a path --- takes a builder too) @native function Raster.path(): Builder return setmetatable({ cmds = {} :: Path }, Builder) end @@ -73140,7 +71237,6 @@ end table.insert(self.cmds, { op = "close" } :: Cmd) return self end --- rect(x, y, w, h), ellipse(cx, cy, rx, ry): closed subpaths @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 @@ -73164,7 +71260,6 @@ end return path end --- n numeric operands of a command, or nil @native local function operands(c: any, n: number): boolean if type(c) ~= "table" then return false @@ -73178,9 +71273,6 @@ end return true end --- ------------------------------------------------------------------------------------------------ flattening --- flatten(path, transform?, tolerance?) -> polylines: { { x1, y1, x2, y2, ... } } in device space, one per subpath --- (closed implicitly; the closing point is not repeated), and the bounds x0, y0, x1, y1 (nil when empty) @native local function flatten(path: any, transform: Transform?, tolerance: number?, minLen: number): ({ { number } }, number?, number?, number?, number?) local cmds = commands(path) local polys: { { number } } = {} @@ -73197,8 +71289,8 @@ end tol = 0.1 end local cur: { number }? = nil - local px, py = 0, 0 -- current point (device) - local sx, sy = 0, 0 -- subpath start (device) + 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 } @@ -73306,9 +71398,7 @@ end return flatten(path, transform, tolerance, 6) end --- ------------------------------------------------------------------------------------------------ accumulation --- one edge (x0, y0) -> (x1, y1), already inside [0, W] horizontally, into acc (stride S, H rows): the signed area --- each pixel gains (font-rs's draw_line) +-- 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 @@ -73388,9 +71478,7 @@ end end end --- an edge in mask coordinates, split where it crosses x = 0 and x = W (in its own order: the direction is the --- winding sign); the parts outside are pushed onto the border (their area lies outside the mask, their cover still --- applies to the row) +-- 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 @@ -73402,7 +71490,7 @@ end return end local dx = x1 - x0 - local ta, tb = 2, 2 -- parameters of the crossings with x = 0 and x = W (2 = none) + local ta, tb = 2, 2 if dx ~= 0 then local t0 = (0 - x0) / dx local tw = (W - x0) / dx @@ -73431,8 +71519,6 @@ end line(acc, S, H, clampx(px, W), py, clampx(x1, W), y1) end --- ------------------------------------------------------------------------------------------------ masks --- mask(path, opts?) -> Mask | nil (empty, or over the size limit: then the second result is "limit") @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) @@ -73493,11 +71579,6 @@ end return { x = X0, y = Y0, width = W, height = H, coverage = cov }, nil end --- ------------------------------------------------------------------------------------------------ filling --- fill(img, path, paint, opts?) -> true | false, message. img: an rgba8 Image ({ width, height, pixels }); paint: an --- { r, g, b, a } colour (0..255) or a function(x, y) -> r, g, b, a called per covered pixel (pixel centres in --- device space: x + 0.5, y + 0.5). Composites source-over onto the straight-alpha pixels. opts.clip defaults to the --- image; opts.opacity scales the coverage. @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" @@ -73562,14 +71643,13 @@ end return true, nil end --- ------------------------------------------------------------------------------------------------ stroking type StrokeOptions = { - width: number?, -- default 1 - join: ("miter" | "round" | "bevel")?, -- default "miter" - cap: ("butt" | "round" | "square")?, -- default "butt" - miterLimit: number?, -- default 4 (SVG) - tolerance: number?, -- flattening tolerance in path units (default 0.1); scale it down for magnified strokes - closed: boolean?, -- treat every subpath as closed (default: only subpaths ending with "close") + 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 @@ -73612,8 +71692,6 @@ end end end --- stroke(path, opts?) -> Path: the outline of the stroke as pieces to fill with the nonzero rule (in the path's own --- coordinate space: transform it like the path). Dashes are the caller's job (split the path first). @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 @@ -73666,7 +71744,6 @@ end end continue end - -- drop repeated points 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 @@ -73684,7 +71761,6 @@ end continue end local segs = if closed then n else n - 1 - -- segment bodies local dirs: { number } = {} for s = 0, segs - 1 do local i, j = s, (s + 1) % n @@ -73696,7 +71772,6 @@ end local nx, ny = -uy * hw, ux * hw polygon(out, { x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny }) end - -- joins @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] @@ -73723,7 +71798,7 @@ end arcPoints(x, y, hw, a0, a0 + da, tol, d) polygon(out, d) else - local cosT = ax * bx + ay * by -- angle between directions + 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 @@ -73745,12 +71820,11 @@ end for k = 1, n - 2 do joinAt(k, k - 1, k) end - -- caps 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 -- pointing outwards + 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 }) @@ -73773,33 +71847,20 @@ __FILES["codecs/image/Texel"] = @native function() --- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers --- (DDS's DXGI and legacy bit-mask formats, KTX's Vulkan / OpenGL formats, ...). New in rosetta. Formats are named --- lower case, channels from the lowest address / bit up (DXGI order): r8, rg8, rgb8, bgr8, rgba8, bgra8, bgrx8, a8, --- l8, la8, r16, rgba16, *s (snorm), *ui / *i (integers), *f (half / float: r16f ... rgba32f), and the packed ones: --- b5g6r5, r5g6b5, b5g5r5a1, a1b5g5r5, b4g4r4a4, a4b4g4r4, a4r4g4b4, rgb10a2, bgr10a2, r11g11b10f, rgb9e5; any other --- bit-mask layout through Texel.masked(bytes, rMask, gMask, bMask, aMask, luminance?). Never throws. --- --- local px, fmt = Texel.decode("bgra8", buf, offset, w, h) -- rgba8 pixels --- local px, fmt = Texel.decode("rgba16f", buf, offset, w, h, true) -- native: rgbaf32 (float) / rgba16 (16-bit) --- local desc = Texel.masked(2, 0xF800, 0x07E0, 0x001F, 0) -- a descriptor, accepted by decode --- --- Channels: one-channel formats (r*, l*) are grey (r = g = b), two-channel ones red + green; missing alpha is opaque. --- rgba8 output: unorm rescaled with rounding, snorm biased (8-bit: s + 128), floats clamped to 0..1, integers clamped --- to 0..255. Native output: rgba8 when every channel fits 8 bits unsigned, rgba16 for 9..16-bit unorm, else rgbaf32 --- (snorm -> -1..1, integers as their values). +-- 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 } -- packed channels (c = r g b a l) +type Channel = { c: string, shift: number, bits: number } type Desc = { - bytes: number, -- per texel + bytes: number, kind: "array" | "packed" | "r11g11b10f" | "rgb9e5" | "pair" | "ayuv", - size: number?, -- array: bytes per component (1, 2, 4) - type: string?, -- array: unorm / snorm / uint / sint / float - order: string?, -- array: the components in memory (r g b a l x); pair: the 4 bytes of 2 pixels (yuyv, uyvy, rgbg, grgb) - channels: { Channel }?, -- packed: unorm fields of a little-endian 16 / 32-bit word + 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 @@ -73807,7 +71868,6 @@ local writeu8, writeu16, writeu32, writef32 = buffer.writeu8, buffer.writeu16, b local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local HALF = Half.TABLE --- ------------------------------------------------------------------------------------------------ formats 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 } @@ -73867,8 +71927,6 @@ FORMATS.grgb = { bytes = 2, kind = "pair", order = "grgb" } FORMATS.ayuv = { bytes = 4, kind = "ayuv" } Texel.FORMATS = FORMATS --- masked(bytes, r, g, b, a, luminance?) -> a packed descriptor from bit masks (DDS legacy pixel formats); luminance: --- the r mask is a luminance channel @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 @@ -73894,7 +71952,6 @@ Texel.FORMATS = FORMATS return { bytes = bytes, kind = "packed", channels = ch } end --- size(fmt, w, h) -> bytes (rows tightly packed) | nil @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 @@ -73903,8 +71960,6 @@ end return if d.kind == "pair" then ((w + 1) // 2) * 4 * h else d.bytes * w * h end --- ------------------------------------------------------------------------------------------------ helpers --- the native output of a descriptor: rgba8 / rgba16 / rgbaf32 @native local function nativeOf(d: Desc): string if d.kind == "array" then local t, s = d.type, d.size :: number @@ -73942,7 +71997,6 @@ end return (1 + m / 32) * 2 ^ (e - 15) end --- one component at q of an array format -> a float (native meaning) and its rgba8 byte @native local function component(src: buffer, q: number, size: number, typ: string): (number, number) if typ == "unorm" then if size == 1 then @@ -73976,7 +72030,6 @@ end return v, math.clamp(v, 0, 255) end --- BT.601 limited-range Y'CbCr -> an rgba8 u32 @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) @@ -73985,7 +72038,6 @@ end return r + g * 256 + b * 65536 + a * 16777216 end --- the 4:2:2 pair formats and AYUV -> rgba8 (out is always rgba8: 8-bit sources) @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 "" @@ -74015,9 +72067,6 @@ end return dst end --- ------------------------------------------------------------------------------------------------ decode --- decode(fmt, src, offset, w, h, native?, rowPitch?) -> pixels, pixel format ("rgba8" / "rgba16" / "rgbaf32") | nil, --- message. rowPitch: bytes per source row (default tight). @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 @@ -74038,7 +72087,6 @@ end local n = 0 if d.kind == "array" then local order, size, typ = d.order :: string, d.size :: number, d.type :: string - -- fast paths 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" @@ -74059,7 +72107,7 @@ end return dst, out end local nc = #order - local map = table.create(nc, 0) -- component -> output channel 0..3, 4 = grey, -1 = skip + 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 @@ -74139,7 +72187,6 @@ end if d.kind == "pair" or d.kind == "ayuv" then return yuv(d, src, offset, w, h, pitch, dst), out end - -- shared-exponent / packed floats local nine = d.kind == "rgb9e5" for y = 0, h - 1 do local s = offset + y * pitch @@ -74171,15 +72218,7 @@ return Texel end __FILES["codecs/image/Texture"] = function() --- codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...): --- a format name is a BCn kind (codecs/image/Bcn), an ETC / EAC kind (codecs/image/Etc) or a texel format --- (codecs/image/Texel); decode / size dispatch on it, surfaces() assembles mip levels / faces / layers into one --- Types.Image, halve() makes the next mip level of an image for writers. New in rosetta. Never throws. --- --- local px, pf = Texture.decode("bc7", buf, offset, w, h, native) -- pixels + their pixel format --- Texture.size("etc2_rgb", w, h) -- bytes of one surface --- local img = Texture.image(px, pf, w, h) -- a Types.Image around them --- local smaller = Texture.halve(img) -- box-filtered next mip level +-- 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") @@ -74188,7 +72227,6 @@ local Half = __include("codecs/image/Half") local Texture = {} --- known(name) -> "bcn" | "etc" | "texel" | nil function Texture.known(name: string): string? if Bcn.BLOCK[name] then return "bcn" @@ -74200,12 +72238,10 @@ function Texture.known(name: string): string? return nil end --- size(name, w, h) -> bytes of a w x h surface | nil 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 --- block(name) -> block width, height, bytes (1, 1, texel bytes for texel formats) | nil function Texture.block(name: string): (number?, number?, number?) local b = Bcn.BLOCK[name] or Etc.BLOCK[name] if b then @@ -74218,8 +72254,6 @@ function Texture.block(name: string): (number?, number?, number?) return nil, nil, nil end --- decode(name, src, offset, w, h, native?) -> pixels, pixel format | nil, message. Without native the result is --- rgba8 (BC6H and float texels clamped to 0..1); native keeps rgbaf32 (BC6H, floats) / rgba16 (EAC, 16-bit unorm). 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) @@ -74251,7 +72285,6 @@ function Texture.decode(name: string, src: buffer, offset: number, w: number, h: return Texel.decode(name, src, offset, w, h, native) end --- image(pixels, pixel format, w, h) -> Types.Image 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 @@ -74260,8 +72293,6 @@ end type Surface = { level: number, layer: number, face: number, slice: number, image: Types.Image } --- assemble(surfaces, layout) -> the Image of the first surface with img.frames = every level-0 surface (faces / --- layers / depth slices in order, when more than one) and img.meta.mipmaps = the smaller levels of the first surface function Texture.assemble(list: { Surface }, layout: string): Types.Image? local first: Types.Image? = nil local frames: { Types.Frame } = {} @@ -74289,8 +72320,6 @@ function Texture.assemble(list: { Surface }, layout: string): Types.Image? return img end --- halve(img) -> the next mip level (each dimension halved, at least 1; 2 x 2 box filter), same pixel format --- (rgba8 / rgba16 / rgbaf32) 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) @@ -74321,7 +72350,6 @@ function Texture.halve(img: Types.Image): Types.Image return out end --- toHalf(rgbaf32 pixels, n) -> rgba16f texels (for writers) function Texture.toHalf(px: buffer, n: number): buffer local out = buffer.create(n * 8) local from = Half.fromFloat @@ -74335,27 +72363,9 @@ return Texture end __FILES["codecs/image/Vp8"] = function() --- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the --- WebM / Matroska and IVF video tracks use its decoder object. Key frames are a port of libwebp 1.6 (BSD-3-Clause, --- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals --- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. Inter frames follow libvpx 1.17 (BSD-3-Clause, --- licenses/libvpx-LICENSE.txt), bit-exact with libvpx / ffmpeg on the official test vectors and libvpx streams. --- Supports: key and inter frames of every version / profile (0: six-tap filters, normal loop filter; 1-2: bilinear; --- 3: bilinear with full pixel chroma; the loop filter type is the header's), last / golden / altref references with --- sign bias, hidden (altref) frames, token partitions, segments, loop filter deltas, probability context save / --- restore. Not supported: the horizontal / vertical scale bits (ignored, as libwebp and ffmpeg do), error --- concealment (a damaged frame returns an Err). --- Speed (one Zen 5 core): 640x480 inter frames ~190 fps under luau --codegen, ~220 fps under LuaJIT with the trace --- limits the host module sets (maxtrace=8000; with LuaJIT's default 1000 traces the decoder thrashes: ~70 fps). --- --- local Vp8 = require("@rosetta/codecs/image/Vp8") --- local frame, err = Vp8.decodeFrame(buf, off, len) -- one key frame: a yuv420p Types.Image --- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling) --- local dec = Vp8.newDecoder() -- a stream (WebM, IVF): key and inter frames --- local img, err = dec:decodeFrame(buf, off, len) -- img.meta.source.show == false: a hidden frame --- dec:reset() -- after a seek: the next frame must be a key frame --- --- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG). +-- 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") @@ -74366,7 +72376,7 @@ local Vp8 = {} local DEFAULT_MAX_PIXELS = 2 ^ 28 type Options = { - maxPixels: number?, -- default 2^28 + maxPixels: number?, } local function fail(msg: string?, offset: number?): Err.Err @@ -74387,7 +72397,6 @@ local function range(buf: buffer, off: number?, len: number?): (number, number) return o, math.clamp(len or (n - o), 0, n - o) end --- info(buf, off?, len?) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, Err 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") @@ -74405,14 +72414,10 @@ DecoderMeta.__index = DecoderMeta type Decoder = typeof(setmetatable({} :: { state: Decode.State }, DecoderMeta)) --- newDecoder() -> Decoder: decodes successive frames of one stream function Vp8.newDecoder(): Decoder return setmetatable({ state = Decode.new() }, DecoderMeta) end --- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image (a fresh buffer) | nil, Err. Key and inter frames; --- meta.source = { format = "vp8", keyFrame, show (false: a hidden frame, decoded as a reference but not displayed), --- profile, width, height }. An inter frame before the first key frame (or after reset) returns CORRUPT. 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") @@ -74431,17 +72436,14 @@ function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: return img, nil end --- decoder:reset(): drops the reference frames (after a seek); the next frame must be a key frame function DecoderMeta.reset(self: Decoder) Decode.reset(self.state) end --- decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err (one key frame) function Vp8.decodeFrame(buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?) return Vp8.newDecoder():decodeFrame(buf, off, len, opts) end --- decodePlanes(buf, off?, len?, opts?) -> y, u, v, width, height | nil, Err: one key frame as separate planes 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") @@ -74457,15 +72459,12 @@ function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options return y, u, v, f.width, f.height end --- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height 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 --- toRgba(yuvImage, fancy?) -> rgba8 Image. fancy (default true): libwebp's bilinear chroma upsampling; false: point --- sampling (dwebp -nofancy) 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") @@ -74484,7 +72483,6 @@ function Vp8.toRgba(img: Types.Image, fancy: boolean?): (Types.Image?, Err.Err?) return out, nil end --- yuvToRgba(y, u, v, w, h, fancy?) -> rgba8 pixels from separate planes (alpha 255) 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 @@ -74497,21 +72495,9 @@ __FILES["codecs/image/Vp8/Decode"] = @native function() --- codecs/image/Vp8/Decode: the VP8 frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter / --- quantizer headers, token probability updates, intra modes, residual tokens, the inverse WHT and DCT, intra --- prediction (16x16, 4x4, chroma), and the normal and simple loop filters: a port of libwebp 1.6 src/dec/vp8_dec.c, --- tree_dec.c, quant_dec.c, frame_dec.c, src/dsp/dec.c and src/utils/bit_reader* (BSD-3-Clause, --- licenses/libwebp-LICENSE.txt). Inter frames after libvpx 1.17 vp8/decoder/decodeframe.c, decodemv.c and --- vp8/common/findnearmv.c, vp8_loopfilter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt): reference updates and sign --- bias, the frame context saved around frames that do not refresh it, persistent segment maps and loop filter deltas, --- inter modes from the near vectors, motion vectors, split macroblocks, intra macroblocks in inter frames, per --- reference / mode loop filter levels; the prediction itself is codecs/image/Vp8/Predict. Bit-exact with libvpx / ffmpeg --- (and with libwebp on key frames). Where libvpx and ffmpeg disagree on streams no encoder writes (an intermediate --- clamp of segment filter levels, copying golden to altref and altref to golden in one frame), this follows ffmpeg. --- --- The decoder state (Decode.new) keeps what persists between frames: the frame context, segment / filter headers, the --- segment map, the last / golden / altref frames. Never throws: bad data returns nil, "message" ("truncated: ..." when --- the data ends early). +-- 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") @@ -74530,7 +72516,6 @@ local CAT = { Tables.CAT3, Tables.CAT4, Tables.CAT5, Tables.CAT6 } local Decode = {} --- ------------------------------------------------------------------------------------------------ boolean decoder -- 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 } @@ -74572,8 +72557,8 @@ end return br end --- getBit without a branch on the decoded bit (one inlined copy per call site keeps LuaJIT's trace count down): --- bit = 1 when value >> bits > split, then range = bit ? range - split : split + 1, value -= bit * (split + 1) << bits +-- 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) @@ -74603,10 +72588,8 @@ end return if getBit(br, 0x80) == 1 then -v else v end --- ------------------------------------------------------------------------------------------------ state type Quant = { y1dc: number, y1ac: number, y2dc: number, y2ac: number, uvdc: number, uvac: number } --- a decoded frame / reference: the macroblock aligned planes with a Predict.BORDER pixel border type Ref = Predict.Planes & { extended: boolean } type State = { @@ -74625,12 +72608,12 @@ type State = { 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 }, -- the segment of every macroblock + segMap: { number }, width: number, height: number, mbw: number, mbh: number, - hasKey: boolean, -- a key frame was decoded (inter frames need one) + hasKey: boolean, last: Ref?, golden: Ref?, alt: Ref?, @@ -74642,8 +72625,8 @@ type State = { miMvC: { number }, miSubR: { number }, -- 16 per macroblock miSubC: { number }, - miN: number, -- the size of the mode info arrays (allocated by the first inter frame) - pred: buffer?, -- the inter predictions of a row + miN: number, + pred: buffer?, } @native function Decode.new(): State @@ -74682,13 +72665,11 @@ type State = { } end --- reset(state): drops the references; the next frame must be a key frame @native function Decode.reset(st: State) st.hasKey = false st.last, st.golden, st.alt = nil, nil, nil end --- header(buf, off, len) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, msg @native function Decode.header(buf: buffer, off: number, len: number): (any, string?) if len < 3 then return nil, "truncated: frame tag" @@ -74722,7 +72703,6 @@ end return h, nil end --- ------------------------------------------------------------------------------------------------ residuals @native local function getLargeValue(br: Br, P: { number }, p: number): number local v if getBit(br, P[p + 4]) == 0 then @@ -74753,9 +72733,7 @@ end return v end --- getCoeffs(br, P, t, ctx, dqDc, dqAc, n, out, o) -> the position of the last non-zero coefficient + 1. Writes the --- dequantized coefficients (int16, as libwebp stores them) into out at byte offset o, in raster order. The boolean --- decoder is inlined (the hot loop of lossy decoding); getLargeValue goes through br. +-- 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 @@ -74928,7 +72906,6 @@ local whtTmp = table.create(16, 0) end end --- ------------------------------------------------------------------------------------------------ reconstruction -- 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 @@ -75268,13 +73245,11 @@ end return mode end --- ------------------------------------------------------------------------------------------------ loop filter -- 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. --- simpleFilter(b, p, step, along, thresh): SimpleVFilter16 / SimpleHFilter16 (16 positions). A position whose filter --- value a is 0 changes nothing and is skipped before the mask (flat areas). +-- 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 @@ -75303,7 +73278,7 @@ end end end --- filterEdge(b, p, hs, vs, size, thresh, it, hevT): the macroblock edge filter (FilterLoop26) +-- 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 @@ -75362,8 +73337,7 @@ end end end --- filterInner(b, p, hs, vs, size, thresh, it, hevT): the inner edge filter (FilterLoop24); nothing changes when --- q0 == p0 and p1 == q1 +-- 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 @@ -75410,7 +73384,6 @@ end end end --- ------------------------------------------------------------------------------------------------ inter modes 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 @@ -75472,17 +73445,16 @@ end type Rows = { i4: { boolean }, -- no Y2 block (B_PRED or SPLITMV) - modes: { number }, -- 16 per macroblock: the 16x16 intra mode or the 4x4 ones + modes: { number }, uv: { number }, ref: { number }, -- 0 intra, 1 last, 2 golden, 3 altref - mode: { number }, -- 0..9 (see MODE_LF) + 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) --- readInterMb(st, br, probs, mi, mbx, mby, rows): the modes and motion vectors of one inter frame macroblock (libvpx --- read_mb_modes_mv with vp8_find_near_mvs); mi: its 1-based index in the mode info arrays +-- 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 @@ -75683,11 +73655,10 @@ local nr, nc, cnt = table.create(4, 0), table.create(4, 0), table.create(4, 0) miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = ref, mode, mvr, mvc end --- ------------------------------------------------------------------------------------------------ frame type Frame = { width: number, height: number, - ref: Ref, -- the decoded planes (the decoder keeps them as a reference: copy them out, see cropTo) + ref: Ref, header: any, } @@ -75709,7 +73680,6 @@ local BORDER = Predict.BORDER } end --- a frame buffer no reference uses @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 @@ -75721,7 +73691,6 @@ end return r end --- cropTo(frame, dy, oy, du, ou, dv, ov): copies the visible planes out (luma stride width, chroma ceil(width / 2)) @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 @@ -75736,7 +73705,6 @@ end end end --- decodeFrame(state, buf, off, len, maxPixels) -> Frame | nil, message: one key or inter frame of the stream @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 @@ -75998,7 +73966,6 @@ end end end - -- the frame buffer (macroblock aligned, with a border) and the references 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 @@ -76032,7 +73999,6 @@ end end local coeffs = bcreate(mbw * 768) local dcb = bcreate(32) - -- per macroblock column / row state local intraT = table.create(mbw * 4, 0) local intraL = table.create(4, 0) local topNz = table.create(mbw, 0) @@ -76050,7 +74016,6 @@ end local mbSkip = table.create(mbw, 0) local mbNzY = table.create(mbw, 0) local mbNzUv = table.create(mbw, 0) - -- filter info for the whole frame: limit, ilevel, inner, hev per macroblock local fLimit = table.create(mbw * mbh, 0) local fIlevel = table.create(mbw * mbh, 0) local fInner = table.create(mbw * mbh, 0) @@ -76486,13 +74451,9 @@ __FILES["codecs/image/Vp8/Predict"] = @native function() --- codecs/image/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the --- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the --- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and --- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels --- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the --- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a --- block whose taps leave it is first copied with clamped coordinates. Never throws. +-- 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 @@ -76505,14 +74466,12 @@ local Predict = {} local BORDER = 32 Predict.BORDER = BORDER --- the work buffer stride (codecs/image/Vp8/Decode: BPS) local BPS = 32 -local emu = bcreate(32 * 32) -- a block with its taps, edges replicated -local tmp = bcreate(32 * 32) -- the first (horizontal) pass of a two-dimensional filter +local emu = bcreate(32 * 32) +local tmp = bcreate(32 * 32) --- the six-tap filter along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7). Each output reads --- its six pixels (a sliding window of locals is no faster in Luau and stops LuaJIT's register allocator). +-- 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] @@ -76527,7 +74486,6 @@ local tmp = bcreate(32 * 32) -- the first (horizontal) pass of a two-dimensional end end --- the six-tap filter along columns @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] @@ -76568,9 +74526,6 @@ end end end --- block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil): predicts the w x h block at plane pixel --- (x, y) moved by (mvx, mvy) eighth pixels into dst at d (stride BPS). base: the offset of plane pixel (0, 0); wmax, --- hmax: the last pixel column / row of the (macroblock aligned) plane. @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 @@ -76648,17 +74603,14 @@ type Planes = { Y: buffer, U: buffer, V: buffer, - ys: number, -- luma stride - uvs: number, -- chroma stride - yb: number, -- offset of luma pixel (0, 0) + ys: number, + uvs: number, + yb: number, uvb: number, mbw: number, mbh: number, } --- mb(ref, mbx, mby, mvr, mvc, split, subR, subC, sb, dst, yo, uo, vo, bil, full): the prediction of one inter --- macroblock into the work buffer (luma at yo, chroma at uo / vo). Not split: one vector (mvr, mvc) in eighth pixels; --- split: the 16 block vectors subR / subC[sb + 1 .. sb + 16] (part < 3: the four 8x8 quarters share them). @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 @@ -76721,9 +74673,6 @@ type Planes = { end end --- row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full): predicts the --- inter macroblocks of a row (ref[mbx + 1] > 0: refs[ref]) into pred, macroblock mbx at mbx * chunk + yo / uo / vo; --- mi0 + mbx + 1: the mode info index of macroblock mbx. A loop of its own (LuaJIT traces it apart from the decoder). @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] @@ -76735,7 +74684,6 @@ end end end --- extend(P, stride, base, w, h): fills the BORDER pixels around a w x h plane with its edge pixels @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 @@ -76760,11 +74708,9 @@ return Predict end __FILES["codecs/image/Vp8/Tables"] = function() --- codecs/image/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6 --- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); the inter frame tables --- (sections 16-18: mode / motion vector probabilities, mode contexts, split partitions, sub-pixel filters) from --- libvpx 1.17 vp8/common (entropymode.c, vp8_entropymodedata.h, entropymv.c, modecont.c, decodemv.c, filter.c; --- BSD-3-Clause, licenses/libvpx-LICENSE.txt). Flat 1-based arrays. +-- 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 @@ -77013,9 +74959,8 @@ __FILES["codecs/image/Vp8/Yuv"] = @native function() --- codecs/image/Vp8/Yuv: 4:2:0 Y'CbCr (BT.601, limited range) to rgba8 the way libwebp's decoder does it, bit-exact: the --- 14-bit fixed-point VP8YuvToRgb of src/dsp/yuv.h, with either the "fancy" upsampler (src/dsp/upsampling.c: a 9-3-3-1 --- bilinear filter on the chroma, libwebp's default) or point sampling (dwebp -nofancy). A port of libwebp 1.6 +-- 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 @@ -77031,12 +74976,10 @@ local Yuv = {} return if v < 0 then 0 else 255 end --- (v * coeff) >> 8 for non-negative v @native local function mulHi(v: number, c: number): number return rshift(v * c, 8) end --- rgba(y, u, v) -> the pixel as a little-endian u32 (bytes R G B 255) @native local function rgba(y: number, u: number, v: number): number local yy = mulHi(y, 19077) local r = clip(yy + mulHi(v, 26149) - 14234) @@ -77046,8 +74989,7 @@ end end Yuv.rgba = rgba --- upsamplePair: libwebp UPSAMPLE_FUNC for one or two output rows. ty / by: offsets of the top / bottom luma rows --- (by < 0: no bottom row), tu / cu: offsets of the top / current chroma rows; dt / db: output row offsets. +-- 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) @@ -77092,7 +75034,6 @@ Yuv.rgba = rgba end end --- toRgba(y, u, v, w, h, fancy, out?) -> rgba8 (alpha 255). Planes are tightly packed (chroma ceil(w / 2) wide). @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 @@ -77125,7 +75066,6 @@ end return o end --- setAlpha(rgba, a8, n): copy an alpha plane into the A bytes @native function Yuv.setAlpha(o: buffer, a: buffer, n: number) for i = 0, n - 1 do writeu8(o, i * 4 + 3, readu8(a, i)) @@ -77136,19 +75076,8 @@ return Yuv end __FILES["codecs/image/Vp8L"] = function() --- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): --- image/webp uses it for VP8L frames and for compressed ALPH planes; other containers may carry it too. --- Decoder: a port of libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it. Encoder: new --- (subtract green, predictor and cross-colour transforms with per-tile mode search, colour indexing with pixel --- bundling for <= 256 colours, LZ77 with hash chains and the 2-D distance codes, a colour cache chosen by entropy, --- one prefix code group per image or meta codes for big images). --- --- local Vp8L = require("@rosetta/codecs/image/Vp8L") --- local rgba, w, h, alpha = Vp8L.decode(buf, off, len) -- a VP8L bitstream (0x2f signature) -> rgba8 --- local a8 = Vp8L.decodeAlpha(buf, off, len, w, h) -- a headerless stream's green channel (ALPH) --- local bits = Vp8L.encode(rgba, w, h, { effort = 4 }) -- rgba8 -> a VP8L bitstream --- --- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / LIMIT / ARG). +-- 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") @@ -77174,7 +75103,6 @@ local function range(buf: buffer, off: number?, len: number?): (number, number) return o, math.clamp(len or (n - o), 0, n - o) end --- info(buf, off?, len?) -> { width, height, alpha } | nil, Err: the 5-byte header 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) @@ -77184,7 +75112,6 @@ function Vp8L.info(buf: buffer, off: number?, len: number?): ({ width: number, h return { width = w, height = h, alpha = alpha }, nil end --- decodeArgb(buf, off?, len?, maxPixels?) -> ARGB u32 pixels (0xAARRGGBB), width, height, alphaHint | nil, Err 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) @@ -77194,7 +75121,6 @@ function Vp8L.decodeArgb(buf: buffer, off: number?, len: number?, maxPixels: num return px, w, h, alpha end --- decode(buf, off?, len?, maxPixels?) -> rgba8 pixels, width, height, alphaHint | nil, Err 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 @@ -77203,7 +75129,6 @@ function Vp8L.decode(buf: buffer, off: number?, len: number?, maxPixels: number? return Decode.toRgba(px, w * (h :: number)), w, h, alpha end --- decodeAlpha(buf, off, len, width, height) -> width * height bytes (the green channel) | nil, Err 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) @@ -77213,16 +75138,14 @@ function Vp8L.decodeAlpha(buf: buffer, off: number?, len: number?, width: number return Decode.green(px, width * height), nil end --- toRgba(argb, n) -> rgba8 bytes of n ARGB pixels Vp8L.toRgba = Decode.toRgba type EncodeOptions = { - effort: number?, -- 0..9, default 5: more = smaller and slower (0: no transforms, no LZ77 search) - exact: boolean?, -- default false: keep the RGB of fully transparent pixels (otherwise they may be zeroed) - alphaHint: boolean?, -- the header's "alpha is used" bit; default: any alpha < 255 + effort: number?, + exact: boolean?, + alphaHint: boolean?, } --- encode(rgba, width, height, opts?) -> a VP8L bitstream (signature + header + image stream) | nil, Err 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") @@ -77241,7 +75164,6 @@ function Vp8L.encode(rgba: buffer, width: number, height: number, opts: EncodeOp return Encode.encode(rgba, width, height, effort, o.exact == true, o.alphaHint, false), nil end --- encodeAlpha(a8, width, height, opts?) -> a headerless stream of the plane in green (an ALPH payload) 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") @@ -77260,13 +75182,9 @@ __FILES["codecs/image/Vp8L/Decode"] = @native function() --- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder: prefix codes (two-level tables), meta prefix codes, --- LZ77 backward references with the 2-D distance map, the colour cache, and the four inverse transforms (predictor, --- cross colour, subtract green, colour indexing with pixel bundling). A port of libwebp 1.6 src/dec/vp8l_dec.c, +-- 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) in a buffer, 4 bytes each, rows top to bottom. Never throws: every --- function returns nil, "message" (prefixed "truncated: " when the data ends early) on bad data. +-- 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 @@ -77294,9 +75212,7 @@ local CODE_TO_PLANE = { -- 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 --- ------------------------------------------------------------------------------------------------ bit reader --- LSB-first; bytes past the end read as zero and are counted in `over`: the stream is overrun when fewer bits are --- left in the buffer than phantom bits were added (bitcnt < over * 8). +-- 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, @@ -77327,7 +75243,6 @@ type State = { d.bitbuf, d.bitcnt = bitbuf, bitcnt end --- readBits(d, n) n <= 24 @native local function readBits(d: State, n: number): number if d.bitcnt < n then fill(d) @@ -77342,7 +75257,6 @@ end return d.bitcnt < d.over * 8 end --- ------------------------------------------------------------------------------------------------ prefix codes local count = table.create(MAX_LEN + 1, 0) local offset = table.create(MAX_LEN + 2, 0) @@ -77371,8 +75285,7 @@ end return if step ~= 0 then band(key, step - 1) + step else key end --- build(d, lens (0-based Lua array), n) -> table offset in d.tab, or -1 for an invalid code set (libwebp --- BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits) +-- 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 @@ -77481,7 +75394,6 @@ local sorted = table.create(2400, 0) return root end --- readSymbol(d, at) -> symbol (the reader is refilled to >= 15 bits first) @native local function readSymbol(d: State, at: number): number if d.bitcnt < MAX_LEN then fill(d) @@ -77505,7 +75417,6 @@ end local codeLengths = table.create(2400, 0) local clLens = table.create(19, 0) --- readCode(d, alphabetSize) -> table offset, or -1 @native local function readCode(d: State, size: number): number for i = 1, size do codeLengths[i] = 0 @@ -77584,7 +75495,6 @@ local clLens = table.create(19, 0) return build(d, codeLengths, size) end --- ------------------------------------------------------------------------------------------------ pixel data @native local function subSample(size: number, bits: number): number return rshift(size + lshift(1, bits) - 1, bits) end @@ -77599,7 +75509,6 @@ Decode.subSample = subSample end Decode.cacheKey = cacheKey --- decodeData: the entropy-coded pixels of one level into `data` (w * h u32) @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 @@ -77716,7 +75625,6 @@ Decode.cacheKey = cacheKey return true, nil end --- ------------------------------------------------------------------------------------------------ transforms @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 @@ -77769,7 +75677,7 @@ end return a * 16777216 + r * 65536 + g * 256 + b end --- predict(mode, L, T, TR, TL) -> the predicted pixel (libwebp VP8LPredictors; 14 and 15 are black) +-- 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 @@ -77877,7 +75785,6 @@ end end end --- inverseColorIndexing(src (sw x h), w, h, bits, map (2^(8 >> bits) u32)) -> w x h @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 @@ -77905,12 +75812,10 @@ end return out end --- ------------------------------------------------------------------------------------------------ image stream type Transform = { kind: number, xsize: number, bits: number, data: buffer? } local decodeStream: (d: State, xs: number, ys: number, level0: boolean) -> (buffer?, string?) --- readCodes(d, xs, ys, cacheBits, level0) -> groups (5 table offsets each), huffman image, bits, image width @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 @@ -78067,7 +75972,6 @@ end } end --- header(buf, off, len) -> width, height, alphaHint | nil, message @native function Decode.header(buf: buffer, off: number, len: number): (number?, number, boolean, string?) if len < 5 then return nil, 0, false, "truncated: header" @@ -78085,7 +75989,6 @@ end return w, h, alpha, nil end --- argb(buf, off, len, maxPixels) -> ARGB pixels, width, height, alphaHint | nil, message @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 @@ -78102,13 +76005,11 @@ end return data, w, h, alpha, nil end --- stream(buf, off, len, w, h) -> ARGB pixels | nil, message: a headerless image stream (the ALPH chunk's payload) @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 --- toRgba(argb, n, out?, outOff?) -> rgba8 bytes @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 @@ -78120,7 +76021,6 @@ end return o end --- green(argb, n) -> the green channel as bytes (alpha planes) @native function Decode.green(argb: buffer, n: number): buffer local o = bcreate(n) for k = 0, n - 1 do @@ -78135,12 +76035,7 @@ __FILES["codecs/image/Vp8L/Encode"] = @native function() --- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from the specification (RFC 9649 section 3). --- Transforms: colour indexing with pixel bundling (<= 256 colours), else subtract green + predictor (per-tile mode --- chosen from a residual cost) + cross colour (per-tile least-squares multipliers). Entropy coding: LZ77 with hash --- chains, the left / up run candidates and the 2-D distance codes, a colour cache whose size is chosen by an entropy --- estimate, one prefix code group per image, code lengths limited to 15 bits (codecs/entropy/Huffman) and run-length coded. --- Never throws (the init module validates the arguments). +-- 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 @@ -78173,14 +76068,13 @@ for i, v in CODE_TO_PLANE do PLANE_TO_CODE[v + 1] = i end --- ------------------------------------------------------------------------------------------------ bit writer 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 --- put(w, v, n): the n <= 24 low bits of v, LSB first +-- 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 @@ -78214,7 +76108,6 @@ end return out end --- ------------------------------------------------------------------------------------------------ helpers @native local function subSample(size: number, bits: number): number return rshift(size + lshift(1, bits) - 1, bits) end @@ -78226,7 +76119,6 @@ end return (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 end --- prefix(v) -> code, extra bits, extra value of a length or distance code value v >= 1 @native local function prefix(v: number): (number, number, number) local d = v - 1 if d < 4 then @@ -78243,7 +76135,7 @@ end return 2 * hb + second, eb, band(d, lshift(1, eb) - 1) end --- distCode(xs, dist) -> the distance code value (1..120 for the 2-D plane offsets, else dist + 120) +-- 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 @@ -78277,7 +76169,6 @@ end return clip255(x + (if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1))) end --- predict(mode, L, T, TR, TL): the decoder's predictors (codecs/image/Vp8L/Decode) @native local function predict(mode: number, L: number, T: number, TR: number, TL: number): number if mode == 1 then return L @@ -78322,7 +76213,6 @@ end return ARGB_BLACK end --- COST[v + 1]: an estimate of the bits of a residual byte v (small magnitudes, mod 256, are cheap) local COST = table.create(256, 0) for v = 0, 255 do local m = math.min(v, 256 - v) @@ -78333,12 +76223,10 @@ end 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 --- ------------------------------------------------------------------------------------------------ transforms 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 } --- predictorTransform(px, w, h, bits, effort) -> the modes sub-image; px becomes the residuals @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) @@ -78401,8 +76289,7 @@ end return if m < -128 then -128 elseif m > 127 then 127 else m end --- crossColorTransform(px, w, h, bits) -> the multipliers sub-image; px is transformed in place. Per tile: the --- least-squares multipliers (r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32), kept when they lower the cost +-- 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) @@ -78476,7 +76363,6 @@ end return img end --- ------------------------------------------------------------------------------------------------ LZ77 -- 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 @@ -78512,7 +76398,6 @@ end head[h] = i end end - -- best(i) -> length, distance (0, 0 when no useful match) @native local function best(i: number): (number, number) local max = math.min(MAX_LENGTH, n - i) if max < 2 then @@ -78616,7 +76501,6 @@ end return L, D end --- ------------------------------------------------------------------------------------------------ prefix codes @native local function entropy(h: { number }): number local total = 0 for _, c in h do @@ -78635,7 +76519,6 @@ end return bits / log(2) end --- chooseCache(px, L, effort) -> the colour cache bits (0..10) with the smallest estimated literal cost @native local function chooseCache(px: buffer, L: { number }, effort: number): number if effort < 2 then return 0 @@ -78699,7 +76582,6 @@ end type Code = { lens: { number }, codes: { number }, single: boolean } --- buildCode(freqs, maxLen) -> code lengths, reversed (LSB-first) codes, single (<= 1 used symbol: 0 bits each) @native local function buildCode(freqs: { number }, maxLen: number): Code local lens = Huffman.lengths(freqs, maxLen) local used = 0 @@ -78743,7 +76625,6 @@ end end end --- writeCode(w, code, alphabetSize): the code lengths (a simple code when possible, else run-length coded) @native local function writeCode(w: W, c: Code, size: number) local syms: { number } = {} for s = 0, size - 1 do @@ -78781,7 +76662,7 @@ end -- decoder's "previous" starts at 8), 17 zeros (3..10), 18 zeros (11..138) local tok: { number } = {} local ext: { number } = {} - local keep = 0 -- tokens up to the last non-zero length + local keep = 0 local prev = 8 local s = 1 while s <= size do @@ -78861,8 +76742,7 @@ end end end --- ------------------------------------------------------------------------------------------------ image data --- writeImage(w, px, xs, n, effort, level0): colour cache bits, [the meta-code bit], the five codes, the pixels +-- 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 @@ -78949,8 +76829,6 @@ end end end --- ------------------------------------------------------------------------------------------------ encode --- toArgb(rgba, n, exact) -> ARGB pixels, any alpha < 255. Without exact, fully transparent pixels become 0. @native local function toArgb(rgba: buffer, n: number, exact: boolean): (buffer, boolean) local px = bcreate(n * 4) local alpha = false @@ -78969,7 +76847,6 @@ end return px, alpha end --- palette(px, n) -> the sorted colours when there are at most 256, else nil @native local function palette(px: buffer, n: number): { number }? local seen: { [number]: boolean } = {} local list: { number } = {} @@ -78989,7 +76866,6 @@ end type Config = { palette: { number }?, pbits: number, cc: boolean, ccbits: number } --- stream(px, w, h, effort, cfg, bw): the transforms and the main image of one configuration (px is consumed) @native local function stream(px: buffer, w: number, h: number, effort: number, cfg: Config, bw: W) local n = w * h local xs = w @@ -79057,8 +76933,6 @@ type Config = { palette: { number }?, pbits: number, cc: boolean, ccbits: number writeImage(bw, px, xs, xs * h, effort, true) end --- encode(rgba, w, h, effort, exact, alphaHint?, headerless) -> the VP8L bitstream (headerless: the image stream only, --- as an ALPH chunk stores it). Efforts 6+ try several transform configurations and keep the smallest. @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) @@ -79113,17 +76987,9 @@ __FILES["codecs/image/Yuv"] = @native function() --- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or --- BT.709 matrices, limited ("tv", 16..235 / 16..240: VP8, MPEG-1, H.264) or full ("pc", 0..255: MJPEG / JPEG) range. --- yuv -> rgb uses nearest chroma and 16-bit fixed point with swscale's default (non-accurate) coefficients, so the --- result is within about one level of `ffmpeg -pix_fmt rgba`; rgb -> yuv averages each 2x2 block for the chroma --- (ffmpeg's default rgb -> yuv420p chroma siting is close to this). --- --- Yuv.toRgba(planes, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 buffer (alpha 255) --- Yuv.fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p buffer (Y, then U, then V; ceil(w/2) x ceil(h/2)) --- Yuv.imageToRgba(img) / Yuv.imageFromRgba(img, range?, matrix?) -> Types.Image --- Yuv.scale(src, w, h, dw, dh, out?) -> yuv420p buffer of dw x dh (each plane bilinear; for shrinking by up to 2x per --- axis, larger factors skip source samples); Yuv.imageScale(img, dw, dh) -> Types.Image (yuv420p in and out) +-- 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 @@ -79167,14 +77033,11 @@ local cache: { [string]: Coeffs } = {} return c end --- CLIP[v + 1024] = clamp(v, 0, 255) for v in -1024..1279 local CLIP = bcreate(2304) for i = 0, 2303 do writeu8(CLIP, i, math.clamp(i - 1024, 0, 255)) end --- toRgba(src, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 (w * h * 4) from planes in one buffer: Y at 0 with --- stride w, U at uo and V at vo with stride cw (ceil(w/2) rows of ceil(h/2)) @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) @@ -79206,7 +77069,6 @@ end return dst end --- fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p @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 @@ -79221,7 +77083,6 @@ end 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 - -- fixed point x 65536 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) @@ -79254,7 +77115,6 @@ end return dst end --- the range / matrix an Image's meta records (meta.yuv = { range, matrix }); limited BT.601 when absent @native local function info(img: Types.Image): (string, string) local m = img.meta local y = m and m.yuv @@ -79269,13 +77129,11 @@ end end Yuv.info = info --- planes(w, h) -> uo, vo, cw, ch of a yuv420p buffer @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 --- FULL_Y / FULL_C: limited -> full range sample maps local FULL_Y = bcreate(256) local FULL_C = bcreate(256) for v = 0, 255 do @@ -79283,7 +77141,6 @@ for v = 0, 255 do writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255)) end --- toFullRange(img) -> a yuv420p Image in full range (a limited-range one remapped; a full-range one returned) @native function Yuv.toFullRange(img: Types.Image): Types.Image if img.format ~= "yuv420p" or info(img) == "full" then return img @@ -79304,7 +77161,6 @@ end return out end --- imageToRgba(img) -> an rgba8 Image (yuv420p converted; rgba8 returned as is; nil for other formats) @native function Yuv.imageToRgba(img: Types.Image): Types.Image? if img.format == "rgba8" then return img @@ -79321,7 +77177,6 @@ end return out end --- imageFromRgba(img, range?, matrix?) -> a yuv420p Image (meta.yuv records the range / matrix) @native function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image? if img.format == "yuv420p" then return img @@ -79336,7 +77191,6 @@ end return out end --- one plane (sw x sh bytes at so) -> (dw x dh at do), bilinear in 8-bit fixed point (source sample centres) @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 @@ -79370,8 +77224,6 @@ end end end --- scale(src, w, h, dw, dh, out?) -> a yuv420p buffer of dw x dh (planes Y, U, V; chroma ceil(dw / 2) x ceil(dh / 2)). --- src must hold w x h yuv420p (checked: a short buffer or bad sizes return a zero-filled result of the right size). @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)) @@ -79402,26 +77254,8 @@ end __FILES["codecs/model/Draco"] = function() -- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). --- A codec, not a format: model/gltf (and any format carrying Draco data) calls it on a byte range. --- Ported from Google's Draco 1.5.7 (Apache-2.0, licenses/draco-LICENSE.txt): the decoder only, bitstream versions --- 1.0 - 2.2 for meshes (sequential and Edgebreaker connectivity: standard, predictive and valence traversals; topology --- splits, attribute seams), sequential point clouds and kd-tree point clouds (2.3); attribute decoders generic / --- integer / quantization / octahedral normals; prediction schemes difference, parallelogram, multi-parallelogram, --- constrained multi-parallelogram, tex coords (deprecated and portable), geometric normal, with the wrap and normal --- octahedron transforms; metadata. Values match draco_decoder bit for bit (f32 rounding at every step of the --- dequantization). --- Not supported: the pre-2.3 kd-tree point cloud layouts (Err.UNSUPPORTED). --- --- local Draco = require("@rosetta/codecs/model/Draco") --- local g, err = Draco.decode(buf, off?, len?, opts?) -- buffer | string --- g.kind ("mesh" | "points"), g.numPoints, g.numFaces, g.indices (u32 x 3 per face, or nil for points) --- g.attributes[i] = { name = "POSITION" | "NORMAL" | "COLOR" | "TEX_COORD" | "GENERIC" | ..., uniqueId, --- components, type = "f32" | "u8" | "i16" | ..., normalized, data (per point, packed) } --- Draco.attribute(g, uniqueId) -> the attribute with that unique id (glTF's attribute map) --- g.metadata = { entries = { [name] = buffer }, children = { [name] = Metadata }, attributes = { [uniqueId] = Metadata } } --- --- Options: maxPoints (default 2^24), maxFaces (default 2^24): larger geometry returns Err.LIMIT. --- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT). +-- 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") @@ -79457,7 +77291,6 @@ type Geometry = { } type Header = { major: number, minor: number, kind: "mesh" | "points", method: number, flags: number } --- sniff(buf, off?) -> whether the bytes start with "DRACO" 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" @@ -79479,7 +77312,6 @@ local function header(d: Reader.D): (Header?, string?) return { major = major, minor = minor, kind = if kind == 0 then "points" else "mesh", method = method, flags = flags }, nil end --- info(buf, off?, len?) -> the header 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 @@ -79571,7 +77403,6 @@ local WRITE: { [number]: (buffer, number, number) -> () } = { [11] = buffer.writeu8, } --- per point output buffer of an attribute local function expand(a: Attributes.Attr, numPoints: number): (buffer?, string?) local size = Attributes.DT_LENGTH[a.dataType] local comps = a.comps @@ -79726,7 +77557,6 @@ local function decode(buf: buffer, o: number, l: number, opts: any): (Geometry?, return g, nil, nil end --- decode(src, off?, len?, opts?) -> Geometry | nil, Err 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 @@ -79742,7 +77572,6 @@ function Draco.decode(src: buffer | string, off: number?, len: number?, opts: an return g, nil end --- attribute(g, uniqueId) -> the attribute with that unique id function Draco.attribute(g: Geometry, uniqueId: number): Attribute? for _, a in g.attributes do if a.uniqueId == uniqueId then @@ -79756,13 +77585,9 @@ return Draco end __FILES["codecs/model/Draco/Attributes"] = function() --- codecs/model/Draco/Attributes: Draco attribute decoding. The attributes decoders (one per connectivity: linear --- sequencer for sequential meshes and point clouds, traversal sequencers for Edgebreaker), their attribute --- descriptors, and the sequential attribute decoders: generic (raw values), integer, quantization (dequantized to --- f32 exactly like the C++) and octahedral normals; prediction through codecs/model/Draco/Predict. Bitstream --- versions 1.0 - 2.2. Ported from Google's Draco 1.5.7 (compression/attributes/*, compression/point_cloud/ --- point_cloud_decoder.cc, attributes/attribute_quantization_transform.cc, attribute_octahedron_transform.cc; --- Apache-2.0, licenses/draco-LICENSE.txt). +-- 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") @@ -79777,18 +77602,18 @@ local DT_LENGTH = { [1] = 1, [2] = 1, [3] = 2, [4] = 2, [5] = 4, [6] = 4, [7] = Attributes.DT_LENGTH = DT_LENGTH type Attr = { - id: number, -- 0-based attribute id + 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 }?, -- point -> value (0-based values at [point + 1]); nil = identity + map: { number }?, numValues: number, - portable: { number }?, -- the integer (portable) values - values: { number }?, -- the final values (numbers), flat - raw: buffer?, -- generic attributes: the raw values + portable: { number }?, + values: { number }?, + raw: buffer?, quant: { min: { number }, range: number, bits: number }?, octBits: number?, scheme: Predict.Scheme?, @@ -79801,7 +77626,6 @@ type Decoder = { points: { number }?, } --- the geometry the attributes decode against type Geom = { numPoints: number, mesh: Connectivity.Mesh?, edgebreaker: boolean, kdTree: boolean } local function zigzag(v: number): number @@ -79811,8 +77635,7 @@ local function zigzag(v: number): number return v // 2 end --- the parent (position) getter for a scheme: portable integers from 2.0 on, the final values before (truncated to --- integers unless the scheme works in floats) +-- 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 @@ -79985,7 +77808,6 @@ local function storeValues(a: Attr): (boolean, string?) return true, nil end --- decodes every attribute; returns them in attribute id order function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) local ver = d.ver local numDecoders = Reader.u8(d) @@ -80040,13 +77862,11 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) enc = cad.enc dec.traversal = { ct = cad.ct :: Connectivity.CT, enc = enc, method = 0 } end - -- prediction data: the attribute's own corner table when its seams are in use 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 - -- the attribute descriptors local all: { Attr } = {} for _, dec in decoders do local n = Reader.count(d, 0x0200) @@ -80107,7 +77927,6 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) end return nil end - -- decode for _, dec in decoders do if g.kdTree then local ok, err = KdTree.decode(d, dec.attrs, g.numPoints) @@ -80140,7 +77959,6 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) end end dec.points = points - -- portable values for _, a in dec.attrs do if a.seqType == 0 then local stride = DT_LENGTH[a.dataType] * a.comps @@ -80206,7 +78024,6 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) end end end - -- data needed by the transforms if ver >= 0x0200 then for _, a in dec.attrs do if a.seqType == 2 then @@ -80237,29 +78054,23 @@ return Attributes end __FILES["codecs/model/Draco/Connectivity"] = function() --- codecs/model/Draco/Connectivity: Draco mesh connectivity. The sequential decoder (raw or rANS delta-coded indices) --- and the Edgebreaker decoder (standard, predictive and valence traversals, topology splits, start faces, attribute --- seams), the corner tables they build (the mesh's and one per attribute seam set), and the traversal sequencers --- (depth first and max prediction degree) that order attribute values. Ported from Google's Draco 1.5.7 --- (compression/mesh/mesh_sequential_decoder.cc, mesh_edgebreaker_decoder_impl.cc, mesh_edgebreaker_traversal_*, --- mesh/corner_table, mesh/mesh_attribute_corner_table, compression/mesh/traverser/*; Apache-2.0, --- licenses/draco-LICENSE.txt). Corners, vertices and faces are 0-based values stored at [i + 1]; -1 is invalid. +-- 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 --- a corner table: corner -> vertex, corner -> opposite corner, vertex -> left-most corner type CT = { c2v: { number }, opp: { number }, lmc: { number }, nv: number, nf: number } --- encoding data of one attribute connectivity: vertex -> value index, value index -> corner type Enc = { v2e: { number }, e2c: { number }, numValues: number } type AttrData = { decoderId: number, used: boolean, seams: { number }, ct: CT?, enc: Enc } type Mesh = { - faces: { number }, -- corner -> point + faces: { number }, numFaces: number, numPoints: number, - ct: CT?, -- Edgebreaker only + ct: CT?, attrData: { AttrData }, posEnc: Enc?, posDecoderId: number, @@ -80287,7 +78098,6 @@ local function newEnc(nv: number): Enc return { v2e = table.create(nv, 0), e2c = {}, numValues = 0 } end --- ------------------------------------------------------------------------------------------------ sequential function Connectivity.sequential(d: D): (Mesh?, string?) local numFaces, numPoints if d.ver < 0x0202 then @@ -80362,8 +78172,6 @@ function Connectivity.sequential(d: D): (Mesh?, string?) return { faces = faces, numFaces = numFaces, numPoints = numPoints, ct = nil, attrData = {}, posEnc = nil, posDecoderId = -1 }, nil end --- ------------------------------------------------------------------------------------------------ edgebreaker --- the traversal decoders: symbols, start face configurations, attribute seam bits type Trav = { decodeSymbol: () -> number, newActiveCorner: (corner: number) -> (), @@ -80372,8 +78180,7 @@ type Trav = { seam: (i: number) -> boolean, } --- MeshEdgebreakerTraversalDecoder::Start (the standard parts): symbols (bits), start faces, seam decoders. --- Returns the decoder state and the buffer after them. +-- MeshEdgebreakerTraversalDecoder::Start local function standardStart(buf: D, numAttributeData: number, withSymbols: boolean): (any?, D) local st: any = {} if withSymbols then @@ -80433,7 +78240,7 @@ local function standardSymbol(sym: D): number return s + Reader.bits(sym, 2) * 2 end --- builds the traversal decoder for `kind` (0 standard, 1 predictive, 2 valence); returns it and the buffer after its data +-- 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) @@ -80610,7 +78417,6 @@ local function makeTraversal(kind: number, buf: D, numAttributeData: number, num }, out end --- hole and topology split events; returns the split stack (source / split symbol ids, edges) or nil local function splitEvents(eb: D, numFaces: number): { any }? local ver = eb.ver local n = Reader.count(eb, 0x0200) @@ -80797,7 +78603,6 @@ function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?) end local maxVertices = numEncodedVertices + numSplitSymbols - -- the corner table (filled lazily: nil = invalid) local c2v: { number } = {} local opp: { number } = {} local lmc: { number } = {} @@ -80868,7 +78673,6 @@ function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?) return prevC(O(prevC(c))) end - -- the symbols local stack: { number } = {} local sp = 0 local splitActive: { [number]: number } = {} @@ -81107,7 +78911,6 @@ function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?) d.pos += splitBytes end - -- attribute seams local attrData: { AttrData } = {} for i = 1, numAttributeData do attrData[i] = { decoderId = -1, used = true, seams = {}, ct = nil, enc = newEnc(0) } @@ -81228,9 +79031,7 @@ function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?) }, nil end --- ------------------------------------------------------------------------------------------------ traversal --- MeshTraversalSequencer::GenerateSequence: the point ids in value order; fills enc (v2e, e2c, numValues). --- method 0 = depth first, 1 = max prediction degree. +-- 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 @@ -81331,7 +79132,6 @@ function Connectivity.traverse(ct: CT, faces: { number }, enc: Enc, method: numb end return points end - -- max prediction degree if nvt == 0 then return points end @@ -81420,7 +79220,7 @@ function Connectivity.traverse(ct: CT, faces: { number }, enc: Enc, method: numb return points end --- MeshTraversalSequencer::UpdatePointToAttributeIndexMapping: point -> value index (1-based table of 0-based values) +-- 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 @@ -81443,9 +79243,8 @@ return Connectivity end __FILES["codecs/model/Draco/Int64"] = function() --- codecs/model/Draco/Int64: the 64-bit integer arithmetic Draco's portable tex coord predictor relies on (int64 / --- uint64 with wrap-around, truncating division, IntSqrt), on (hi, lo) pairs of 32-bit halves held in numbers (both --- runtimes: no native 64-bit integers). Two's complement: hi >= 2^31 is negative when read as signed. +-- 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 @@ -81481,7 +79280,6 @@ function Int64.sub(ah: number, al: number, bh: number, bl: number): (number, num return Int64.add(ah, al, nh, nl) end --- the product mod 2^64 (the same bits for signed and unsigned operands) 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 @@ -81500,7 +79298,6 @@ function Int64.isNeg(h: number): boolean return h >= P31 end --- the signed value as a number (exact below 2^53 in magnitude) function Int64.signed(h: number, l: number): number if h >= P31 then return (h - P32) * P32 + l @@ -81508,12 +79305,10 @@ function Int64.signed(h: number, l: number): number return h * P32 + l end --- the unsigned value as a number (rounded past 2^53) function Int64.unsigned(h: number, l: number): number return h * P32 + l end --- unsigned compare: -1, 0, 1 function Int64.ucmp(ah: number, al: number, bh: number, bl: number): number if ah ~= bh then return if ah < bh then -1 else 1 @@ -81524,7 +79319,6 @@ function Int64.ucmp(ah: number, al: number, bh: number, bl: number): number return 0 end --- signed compare: -1, 0, 1 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 @@ -81534,14 +79328,12 @@ function Int64.cmp(ah: number, al: number, bh: number, bl: number): number return Int64.ucmp(0, al, 0, bl) end --- unsigned division (b ~= 0): quotient, remainder 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 - -- r = r * 2 + bit i of a 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 @@ -81558,7 +79350,6 @@ function Int64.udivmod(ah: number, al: number, bh: number, bl: number): (number, return qh, ql, rh, rl end --- signed division truncating toward zero (b ~= 0) function Int64.div(ah: number, al: number, bh: number, bl: number): (number, number) local na, nb = ah >= P31, bh >= P31 if na then @@ -81601,12 +79392,9 @@ return Int64 end __FILES["codecs/model/Draco/KdTree"] = function() --- codecs/model/Draco/KdTree: kd-tree coded point cloud attributes (bitstream 2.3): DynamicIntegerPointsKdTreeDecoder --- at compression levels 0 - 6 (direct bits, rANS bits, folded 32-bit rANS numbers, selected axes) over all the --- attributes of a decoder at once, then the signed offsets and the dequantization of f32 attributes. Ported from --- Google's Draco 1.5.7 (compression/attributes/kd_tree_attributes_decoder.cc, compression/point_cloud/algorithms/ --- dynamic_integer_points_kd_tree_decoder.h, compression/bit_coders/{direct,folded_integer}_bit_decoder; Apache-2.0, --- licenses/draco-LICENSE.txt). The pre-2.3 kd-tree layouts are not supported. +-- 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") @@ -81614,7 +79402,7 @@ local KdTree = {} type D = Reader.D --- a bit source: next() -> 0 / 1, bits(n) -> value (MSB first); bits returns nil when a direct decoder runs out +-- bits(n) reads MSB first type Src = { next: () -> number, bits: (n: number) -> number? } local function direct(d: D): Src? @@ -81724,7 +79512,7 @@ local function msb(n: number): number return k end --- DynamicIntegerPointsKdTreeDecoder::DecodePoints -> points (each a table of `dim` u32 values), or nil +-- 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) @@ -81852,7 +79640,6 @@ end local SIGNED = { [1] = 8, [3] = 16, [5] = 32 } --- decodes the attributes of one kd-tree decoder (Attributes.Attr records: dataType, comps; sets values / numValues) 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" @@ -81895,7 +79682,6 @@ function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, strin a.map = nil off += comps end - -- the data needed by the transforms: f32 quantization, then the signed minima for _, a in attrs do if a.dataType == 9 then local mins = table.create(a.comps, 0) @@ -81923,7 +79709,6 @@ function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, strin a.signedMin = mins end end - -- back to the original values local fround = Predict.fround for _, a in attrs do local vals = a.portable :: { number } @@ -81966,13 +79751,9 @@ return KdTree end __FILES["codecs/model/Draco/Predict"] = function() --- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms. Schemes: difference --- (delta), parallelogram, multi-parallelogram, constrained multi-parallelogram, tex coords (deprecated, float) and --- portable tex coords, geometric normal; transforms: wrap, normal octahedron and canonicalized normal octahedron. --- Integer semantics follow the C++ (int32 wrap, truncating division, exact 64-bit products where they can pass 2^53; --- float math rounded to f32 at every step). Ported from Google's Draco 1.5.7 --- (compression/attributes/prediction_schemes/*, compression/attributes/normal_compression_utils.h; Apache-2.0, --- licenses/draco-LICENSE.txt). +-- 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") @@ -82054,7 +79835,7 @@ local function isqrtProd(a: number, b: number): number end local s = math.floor(math.sqrt(a) * math.sqrt(b)) local ph, pl = twoProd(a, b) - local function le(x: number): boolean -- x * x <= a * b + local function le(x: number): boolean local xh, xl = twoProd(x, x) if xh ~= ph then return xh < ph @@ -82070,7 +79851,6 @@ local function isqrtProd(a: number, b: number): number return s end --- ------------------------------------------------------------------------------------------------ octahedron toolbox type Oct = { bits: number, maxQ: number, maxV: number, center: number, scale: number } function Predict.octahedron(bits: number): Oct? @@ -82174,8 +79954,6 @@ function Predict.octToVector(o: Oct, s: number, t: number): (number, number, num return fround(x * dd), fround(y * dd), fround(z * dd) end --- ------------------------------------------------------------------------------------------------ transforms --- tr.apply(pred, data, off): data[off + 1 ..] holds the corrections and receives the original values type Transform = { kind: number, -- 1 wrap, 2 octahedron, 3 octahedron canonicalized positive: boolean, -- corrections are stored without the zig-zag sign mapping @@ -82221,7 +79999,6 @@ function Predict.decodeTransform(tr: Transform, d: D): boolean return true end --- the original values from a prediction (pred[1 .. comps]) and the corrections at data[off + 1 ..] 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 @@ -82291,10 +80068,7 @@ local function apply(tr: Transform, pred: { number }, data: { number }, off: num end Predict.apply = apply --- ------------------------------------------------------------------------------------------------ schemes --- the mesh data of a scheme: corner table, value -> corner, vertex -> value type MeshData = { ct: CT, e2c: { number }, v2e: { number } } --- the parent position attribute: pos(point) -> x, y, z (portable integers, or floats before 2.0) type Parent = (point: number) -> (number, number, number) type Scheme = { @@ -82302,7 +80076,6 @@ type Scheme = { tr: Transform, md: MeshData?, parent: Parent?, - -- per-scheme decoded data crease: { { boolean } }?, orient: { boolean }?, flips: Reader.Bits?, @@ -82313,7 +80086,6 @@ type Scheme = { local DELTA, PARALLELOGRAM, MULTI, TEXDEP, CONSTRAINED, TEXPORT, GEONORMAL = 0, 1, 2, 3, 4, 5, 6 Predict.GEOMETRIC_NORMAL = GEONORMAL --- whether the scheme needs the position attribute function Predict.needsParent(s: Scheme): boolean return s.md ~= nil and (s.method == TEXDEP or s.method == TEXPORT or s.method == GEONORMAL) end @@ -82456,9 +80228,7 @@ local function swingLeft(ct: CT, c: number): number return nextC(o) end --- the portable tex coord prediction when both neighbours are decoded (MeshPredictionSchemeTexCoordsPortablePredictor --- ::ComputePredictedValue), in int64 / uint64 arithmetic like the C++. Returns "ok", u, v; "fallback" (degenerate --- edge: predict from a neighbour); or "fail", message. +-- 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 @@ -82491,7 +80261,6 @@ local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: n end end end - -- the general case: int64 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) @@ -82603,7 +80372,7 @@ local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: n return "ok", i32(ul), i32(vl) end --- ComputeOriginalValues over data (corrections in, values out, in place); points = the entry -> point map +-- 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 @@ -82879,7 +80648,6 @@ function Predict.compute(s: Scheme, data: { number }, numEntries: number, comps: end return true, nil end - -- geometric normal local o = tr.oct local flips = s.flips if not o or not flips or comps ~= 2 then @@ -82945,12 +80713,9 @@ return Predict end __FILES["codecs/model/Draco/Reader"] = function() --- codecs/model/Draco/Reader: the Draco decoder buffer (little-endian fields, LEB128 varints, LSB-first bit runs) and --- its entropy decoders: rANS symbol coding (tagged and raw schemes, DecodeSymbols) and the binary rANS / rABS bit --- decoder. Ported from Google's Draco 1.5.7 (core/decoder_buffer, core/varint_decoding, compression/entropy/ans.h, --- rans_symbol_decoder.h, symbol_decoding.cc, compression/bit_coders/rans_bit_decoder.cc; Apache-2.0, --- licenses/draco-LICENSE.txt). Bitstream versions 1.0 - 2.2 (fixed-width counts before 2.0 / 2.2). --- A failed read sets the sticky d.bad message and returns 0; callers check d.bad at their boundaries. +-- 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 @@ -82958,13 +80723,13 @@ local band, rshift = bit32.band, bit32.rshift type D = { b: buffer, - pos: number, -- absolute offset in b - limit: number, -- absolute end + pos: number, + limit: number, ver: number, -- major * 256 + minor bad: string?, bitMode: boolean, - bitStart: number, -- absolute byte where the bit run starts - bitOff: number, -- bits consumed + bitStart: number, + bitOff: number, } function Reader.new(b: buffer, pos: number, limit: number, ver: number): D @@ -83028,7 +80793,6 @@ function Reader.i32(d: D): number return readi32(d.b, p) end --- u64 as a number (exact below 2^53; sizes beyond that fail the bounds checks anyway) function Reader.u64(d: D): number local p = d.pos if p + 8 > d.limit then @@ -83078,7 +80842,6 @@ function Reader.count(d: D, fixedBefore: number): number return Reader.varint(d) end --- ------------------------------------------------------------------------------------------------ bit runs -- 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 @@ -83125,7 +80888,6 @@ function Reader.endBits(d: D) d.pos = d.bitStart + (d.bitOff + 7) // 8 end --- ------------------------------------------------------------------------------------------------ rANS symbols -- 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 @@ -83134,12 +80896,12 @@ end type Rans = { b: buffer, - base: number, -- absolute start of the coded bytes - off: number, -- bytes left (read backwards from base + off) + base: number, + off: number, state: number, lBase: number, precBits: number, - lut: { number }, -- rem + 1 -> symbol + 1 + lut: { number }, prob: { number }, cum: { number }, numSymbols: number, @@ -83283,7 +81045,6 @@ local function ransStart(d: D, r: Rans): boolean return true end --- decodes n symbols into out[first .. first + n - 1] (0-based symbol values) 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 @@ -83358,7 +81119,7 @@ local function decodeRaw(d: D, n: number, out: { number }): boolean return true end --- DecodeSymbols(n, components) -> { u32 } (1-based) | nil (d.bad set) +-- DecodeSymbols function Reader.symbols(d: D, n: number, comps: number): { number }? local out = table.create(n, 0) if n == 0 then @@ -83380,7 +81141,6 @@ function Reader.symbols(d: D, n: number, comps: number): { number }? return if ok then out else nil end --- ------------------------------------------------------------------------------------------------ binary rANS 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 @@ -83427,16 +81187,7 @@ return Reader end __FILES["codecs/model/Mat4"] = function() --- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 --- (glTF / FBX / Types.Scene layout: translation at 13..15), quaternions { x, y, z, w }, angles in degrees where a --- format stores degrees. Shared by FBX, Collada, USD and MeshOps instead of a copy in each. New in rosetta (the --- functions come from the former model/fbx/Xform, model/dae/Math and model/usda/Build helpers). --- --- local m = Mat4.compose({ 1, 2, 3 }, quat, { 2, 2, 2 }) -- T * R * S --- local t, r, s = Mat4.decompose(m) -- (decomposeStrict: nil for shear / projective / singular) --- local w = Mat4.mul(parent, m) -- = Types.Scene.mul --- local inv = Mat4.inverse(m) -- affine inverse | nil --- local x, y, z = Mat4.point(m, px, py, pz) +-- codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers. local Types = __include("Types") local Mat4 = {} @@ -83449,7 +81200,6 @@ function Mat4.identity(): M4 return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } end --- mul(a, b) -> a * b Mat4.mul = Types.Scene.mul function Mat4.translation(x: number, y: number, z: number): M4 @@ -83460,7 +81210,6 @@ function Mat4.scaling(x: number, y: number, z: number): M4 return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } end --- rotation(axis, degrees) -> the rotation about axis 1 (X), 2 (Y) or 3 (Z) function Mat4.rotation(axis: number, degrees: number): M4 local a = rad(degrees) local c, s = cos(a), sin(a) @@ -83473,7 +81222,6 @@ function Mat4.rotation(axis: number, degrees: number): M4 end local AXIS = { x = 1, y = 2, z = 3 } --- euler(x, y, z, order?) -> the rotation applying the axes in order (default "xyz": R = Rz * Ry * Rx), degrees function Mat4.euler(x: number, y: number, z: number, order: string?): M4 local o = order or "xyz" local deg = { x = x, y = y, z = z } @@ -83485,7 +81233,6 @@ function Mat4.euler(x: number, y: number, z: number, order: string?): M4 return m end --- axisAngle(x, y, z, degrees) -> quaternion function Mat4.axisAngle(x: number, y: number, z: number, degrees: number): { number } local l = sqrt(x * x + y * y + z * z) if l < 1e-12 then @@ -83496,7 +81243,6 @@ function Mat4.axisAngle(x: number, y: number, z: number, degrees: number): { num return { x * s, y * s, z * s, cos(h) } end --- fromQuat(q) -> the rotation matrix of a quaternion function Mat4.fromQuat(q: { number }): M4 local x, y, z, w = q[1], q[2], q[3], q[4] local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z @@ -83508,7 +81254,6 @@ function Mat4.fromQuat(q: { number }): M4 } end --- quat(m) -> the unit quaternion of the rotation in m's upper 3x3 (columns assumed orthonormal) function Mat4.quat(m: M4): { number } local m00, m01, m02 = m[1], m[5], m[9] local m10, m11, m12 = m[2], m[6], m[10] @@ -83535,7 +81280,6 @@ function Mat4.quat(m: M4): { number } return { x / n, y / n, z / n, w / n } end --- eulerXYZ(q) -> Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion function Mat4.eulerXYZ(q: { number }): { number } local m = Mat4.fromQuat(q) local sy = math.clamp(-m[3], -1, 1) -- m[3] = r20 = -sin(y) @@ -83551,7 +81295,7 @@ function Mat4.eulerXYZ(q: { number }): { number } return { math.deg(x), math.deg(y), math.deg(z) } end --- compose(t?, r?, s?) -> T * R * S (glTF node semantics) +-- 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 @@ -83599,19 +81343,16 @@ local function split(m: M4, strict: boolean): ({ number }?, { number }?, { numbe return { m[13], m[14], m[15] }, Mat4.quat(r), { sx, sy, sz } end --- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale; shear is lost) +-- a negative determinant flips the x scale; shear is lost function Mat4.decompose(m: M4): ({ number }, { number }, { number }) local t, r, s = split(m, false) return t :: { number }, r :: { number }, s :: { number } end --- decomposeStrict(m) -> translation, rotation, scale | nil for matrices TRS cannot express (a projective row, shear, --- a zero scale) function Mat4.decomposeStrict(m: M4): ({ number }?, { number }?, { number }?) return split(m, true) end --- inverse(m) -> the inverse of an affine matrix (general upper 3x3) | nil when singular function Mat4.inverse(m: M4): M4? local a, b, c = m[1], m[5], m[9] local d, e, f = m[2], m[6], m[10] @@ -83635,7 +81376,6 @@ function Mat4.inverse(m: M4): M4? return r end --- inverseFull(m) -> the inverse of any invertible 4x4 (projective rows too) | nil when singular function Mat4.inverseFull(m: M4): M4? local a = m local inv = table.create(16, 0) @@ -83665,12 +81405,10 @@ function Mat4.inverseFull(m: M4): M4? return inv end --- transpose3(m) -> m with its upper 3x3 transposed and no translation (the inverse of a pure rotation) function Mat4.transpose3(m: M4): M4 return { m[1], m[5], m[9], 0, m[2], m[6], m[10], 0, m[3], m[7], m[11], 0, 0, 0, 0, 1 } end --- fromRows(v, at?) -> column-major from 16 row-major values at v[at] (default 1; missing values: identity) function Mat4.fromRows(v: { number }, at: number?): M4 local o = (at or 1) - 1 local m = table.create(16, 0) @@ -83682,7 +81420,6 @@ function Mat4.fromRows(v: { number }, at: number?): M4 return m end --- toRows(m) -> the 16 values row-major function Mat4.toRows(m: M4): { number } local v = table.create(16, 0) for r = 0, 3 do @@ -83693,12 +81430,10 @@ function Mat4.toRows(m: M4): { number } return v end --- point(m, x, y, z) -> m * (x, y, z, 1) function Mat4.point(m: M4, x: number, y: number, z: number): (number, number, number) return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] end --- normalMatrix(m) -> the inverse transpose of the upper 3x3 (for normals) as a 4x4 (identity when singular) function Mat4.normalMatrix(m: M4): M4 local inv = Mat4.inverse({ m[1], m[2], m[3], 0, m[5], m[6], m[7], 0, m[9], m[10], m[11], 0, 0, 0, 0, 1 }) if not inv then @@ -83711,13 +81446,7 @@ 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). Walks --- scene.roots recursively (TRS or column-major `matrix` per node; a scene without nodes uses its meshes as they are), --- applies the transforms to POSITION (and the inverse transpose to NORMAL), reverses the winding under mirroring --- transforms, reads every accessor type to numbers and concatenates all primitives (triangles with or without indices, --- polygons, strips, fans, points; lines are skipped). Shared here because a format cannot require another one --- (ops/MeshOps.merge is the editing-side equivalent). --- Never throws: bad input returns nil, message. +-- 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 = {} @@ -83731,31 +81460,29 @@ local SIZE = Types.COMPONENT_SIZE local NORM: { [string]: number } = { unorm8 = 255, unorm16 = 65535, snorm8 = 127, snorm16 = 32767 } type Attr = { - type: string, -- the accessor type shared by every part ("f32" when the parts disagree) + type: string, components: number, - raw: boolean, -- values are raw integers of a normalized type (unorm8: 0..255), else plain numbers - values: { number }, -- count * components + raw: boolean, + values: { number }, } type PartInfo = { prim: Types.Primitive, mesh: Types.Mesh?, node: Types.Node?, - firstVertex: number, -- 0-based offset of the part's vertices in the merged mesh + firstVertex: number, vertexCount: number, - firstFace: number, -- 0-based offset of the part's faces + firstFace: number, faceCount: number, - identity: boolean, -- no transform was applied + identity: boolean, } type Merged = { - count: number, -- vertices - attrs: { [string]: Attr }, -- POSITION and NORMAL in world space (f32 values), the others as read - sizes: { number }?, -- vertices per face (nil: no part has faces, a point cloud) - corners: { number }, -- 0-based vertex indices, face after face + count: number, + attrs: { [string]: Attr }, + sizes: { number }?, + corners: { number }, parts: { PartInfo }, } --- ------------------------------------------------------------------------------------------------ accessors --- numbers(acc, raw) -> the accessor's count * components values (normalized types divided out unless raw), or nil, msg 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" @@ -83818,10 +81545,9 @@ function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?) return out, nil end --- ------------------------------------------------------------------------------------------------ transforms local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } -local mul = Types.Scene.mul -- column-major 4x4 product a * b +local mul = Types.Scene.mul local function numList(v: any, n: number): boolean if type(v) ~= "table" then @@ -83835,7 +81561,6 @@ local function numList(v: any, n: number): boolean return true end --- a node's local matrix (nil: none), or nil, message local function localMatrix(node: any): ({ number }?, string?) if node.matrix ~= nil then if not numList(node.matrix, 16) then @@ -83898,7 +81623,6 @@ end type Instance = { prim: Types.Primitive, mesh: Types.Mesh?, node: Types.Node?, matrix: { number }? } --- the primitive instances of a scene in traversal order, or nil, message local function instances(scene: any): ({ Instance }?, string?) local out: { Instance } = {} local nodes, meshes = scene.nodes, scene.meshes @@ -83986,8 +81710,6 @@ local function instances(scene: any): ({ Instance }?, string?) return out, nil end --- ------------------------------------------------------------------------------------------------ faces --- the faces of a primitive: sizes (nil = all triangles), corners (0-based), or "points" / "skip", or nil, message local function faces(prim: any, nv: number): (any, any, string?) local mode = prim.mode or "triangles" if mode == "points" then @@ -84064,7 +81786,6 @@ local function faces(prim: any, nv: number): (any, any, string?) return nil, nil, "unknown primitive mode " .. tostring(mode) end --- ------------------------------------------------------------------------------------------------ merge -- 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 @@ -84079,8 +81800,6 @@ local function f32(v: number): number return buffer.readf32(b, 0) end --- merge(scene, keep, opts) -> Merged | nil, message. keep(name) says which attributes to carry (POSITION always). --- opts.triangulate fan-triangulates polygons (faces of fewer than 3 vertices are dropped then). function Flatten.merge(scene: any, keep: (string) -> boolean, opts: { triangulate: boolean? }?): (Merged?, string?) if type(scene) ~= "table" then return nil, "not a scene" @@ -84090,7 +81809,6 @@ function Flatten.merge(scene: any, keep: (string) -> boolean, opts: { triangulat return nil, lerr end local triangulate = opts and opts.triangulate or false - -- the attribute set: union over parts, a type every part agrees on (else f32), the widest component count local types: { [string]: string } = {} local comps: { [string]: number } = {} local used: { Instance } = {} @@ -84257,17 +81975,6 @@ end __FILES["codecs/model/Minecraft"] = function() -- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. --- Block states ("minecraft:oak_stairs[facing=east,half=bottom]": parse / format / NBT compound form), the default --- block colour table (codecs/model/Minecraft/Colors, hand-made) with fallbacks by family, the pre-1.13 numeric ids --- (codecs/model/Minecraft/Legacy), packed index arrays (codecs/model/Minecraft/Packed), and the bridge between block --- grids and Types.Voxels: voxels.blocks holds the exact states (u16 indices into a state palette), voxels.data / --- palette their colours; writing a grid without blocks picks the block nearest in colour for each palette colour. --- --- local Mc = require("@rosetta/codecs/model/Minecraft") --- local name, props = Mc.parseState("minecraft:oak_log[axis=y]") -- "minecraft:oak_log", { { "axis", "y" } } --- local rgba = Mc.color("minecraft:red_wool") -- { r, g, b, a } | nil for air --- local v = Mc.voxels(sx, sy, sz, states, indices) -- a Types.Voxels with .blocks --- local states, indices = Mc.blocksOf(v) -- back (or chosen by colour) local Types = __include("Types") local Nbt = __include("codecs/text/Nbt") local Colors = __include("codecs/model/Minecraft/Colors") @@ -84279,8 +81986,6 @@ local Minecraft = {} Minecraft.Packed = Packed Minecraft.Legacy = Legacy --- ------------------------------------------------------------------------------------------------ block states --- parseState(s) -> name (namespace added when missing), props { { key, value } } in their order function Minecraft.parseState(s: string): (string, { { string } }) local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$") local n = name or "" @@ -84300,7 +82005,6 @@ function Minecraft.parseState(s: string): (string, { { string } }) return n, props end --- stateString(name, props?) -> "name[k=v,...]" (props { { k, v } } in order, or a map: keys sorted) function Minecraft.stateString(name: string, props: { any }?): string if not props or next(props) == nil then return name @@ -84318,7 +82022,6 @@ function Minecraft.stateString(name: string, props: { any }?): string return name .. "[" .. table.concat(parts, ",") .. "]" end --- stateFromNbt(compound) -> the state string of a palette entry { Name, Properties? } (litematic, chunk sections) function Minecraft.stateFromNbt(c: any): string? if type(c) ~= "table" or type(c.Name) ~= "string" then return nil @@ -84333,7 +82036,6 @@ function Minecraft.stateFromNbt(c: any): string? return Minecraft.stateString(c.Name, props) end --- stateToNbt(state) -> { Name, Properties? } (a Types.object; Properties in the state's order) function Minecraft.stateToNbt(s: string): { [string]: any } local name, props = Minecraft.parseState(s) local c = Types.object({ Name = name }, { "Name" }) @@ -84348,19 +82050,16 @@ function Minecraft.stateToNbt(s: string): { [string]: any } return c end --- baseName(state) -> the name without namespace and properties ("minecraft:oak_log[axis=y]" -> "oak_log") 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 } --- isAir(state) -> true for blocks that are not drawn (air, cave_air, void_air, structure_void, light, barrier) function Minecraft.isAir(s: string): boolean return AIR[Minecraft.baseName(s)] == true end --- ------------------------------------------------------------------------------------------------ colours 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 @@ -84516,7 +82215,6 @@ resolve = function(n: string, depth: number): { number }? end local cache: { [string]: { number } | false } = {} --- color(state) -> { r, g, b, a } (0..255) | nil for air-like blocks: the default colour table, families, keywords function Minecraft.color(s: string): { number }? local hit = cache[s] if hit ~= nil then @@ -84526,7 +82224,6 @@ function Minecraft.color(s: string): { number }? local n = string.match(name, ":(.*)$") or name local res: { number }? = nil if not AIR[n] then - -- pre-1.13 names whose data value picks the variant local variants = Legacy.VARIANTS[n] or (if n == "double_wooden_slab" then Legacy.VARIANTS.planks else nil) if variants then local data = 0 @@ -84544,7 +82241,6 @@ function Minecraft.color(s: string): { number }? return res end --- ------------------------------------------------------------------------------------------------ legacy ids local REVERSE: { [string]: { number } }? = nil local function reverse(): { [string]: { number } } if REVERSE then @@ -84576,8 +82272,7 @@ local function reverse(): { [string]: { number } } return r end --- legacyState(id, data) -> the state string for a pre-1.13 block (variant names where the data value picks one, the --- rest of the data value kept as [data=N] so legacyId gives it back exactly) +-- 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 @@ -84594,8 +82289,6 @@ function Minecraft.legacyState(id: number, data: number): string return "minecraft:" .. (Legacy.RENAMED[n] or n) .. (if data ~= 0 then "[data=" .. data .. "]" else "") end --- legacyId(state) -> id, data | nil: the inverse of legacyState (modern names that exist before 1.13 too; their --- properties are not converted to data values) function Minecraft.legacyId(s: string): (number?, number?) local name, props = Minecraft.parseState(s) local n = string.match(name, ":(.*)$") or name @@ -84620,10 +82313,6 @@ function Minecraft.legacyId(s: string): (number?, number?) return id, data end --- ------------------------------------------------------------------------------------------------ voxels --- voxels(sx, sy, sz, states, indices, opts?) -> Types.Voxels: indices (u16 LE per cell in Voxels order: x fastest, --- then y, then z) into states; data / palette from the block colours (air -> 0; up to 255 colours, more merge into --- the nearest one) 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) @@ -84666,7 +82355,6 @@ function Minecraft.voxels(sx: number, sy: number, sz: number, states: { string } return v end --- the blocks a colour grid is written with: full blocks of distinct colours (and stained glass for translucent ones) local CANDIDATES: { { any } }? = nil local function candidates(): { { any } } if CANDIDATES then @@ -84691,7 +82379,6 @@ local function candidates(): { { any } } return out end --- nearestBlock(rgba) -> the block state whose default colour is nearest (translucent colours -> stained glass) function Minecraft.nearestBlock(c: { number }): string local a = c[4] or 255 if a < 200 then @@ -84716,8 +82403,6 @@ function Minecraft.nearestBlock(c: { number }): string return best end --- blocksOf(voxels) -> states, indices (u16 LE per cell): voxels.blocks when present (checked), else a block per --- palette colour (nearestBlock; cell 0 -> "minecraft:air" at index 0) | nil, message function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any) local n = v.size[1] * v.size[2] * v.size[3] local b = v.blocks @@ -84754,9 +82439,8 @@ function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any) return states, out end --- ------------------------------------------------------------------------------------------------ block entities --- Block entity records in one shape, { pos = { x, y, z }, id, data } (Sponge v3's), from / to the flat --- { x, y, z, id, ... } of MCEdit, Litematica and chunks, and Sponge v1 / v2's { Pos, Id, ... }. +-- 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 @@ -84776,8 +82460,8 @@ local function ints(v: any): { number }? end return nil end -Minecraft.int = int -- the integer value of an NBT number | nil -Minecraft.ints = ints -- the numbers of an intArray or a list | nil +Minecraft.int = int +Minecraft.ints = ints local function rest(c: any, skip: { [string]: boolean }): { [string]: any } local out, keys = {}, {} @@ -84793,8 +82477,6 @@ end local FLAT_SKIP = { x = true, y = true, z = true, id = true } local POS_SKIP = { Pos = true, Id = true } --- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2), --- "data" (Sponge v3) function Minecraft.blockEntity(c: any, style: string): any if type(c) ~= "table" or Nbt.isTag(c) then return nil @@ -84807,7 +82489,6 @@ function Minecraft.blockEntity(c: any, style: string): any 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 --- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity) 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() @@ -84845,10 +82526,8 @@ return Minecraft end __FILES["codecs/model/Minecraft/Colors"] = function() --- codecs/model/Minecraft/Colors: the built-in default colour of Minecraft blocks, for showing block grids as coloured --- voxels. Hand-made for this library (approximate average colours picked by eye; no game assets or wiki tables were --- copied): exact block names, then families by dye colour and wood type; codecs/model/Minecraft resolves stairs / --- slabs / walls / ... to their base block and falls back to keywords. Format: name=rrggbb or name=rrggbbaa. +-- 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 = [[ @@ -84912,13 +82591,11 @@ muddy_mangrove_roots=46413a ochre_froglight=f6e8a6 verdant_froglight=dcf0d6 pear creaking_heart=5a4a3c resin_block=d9661c resin_bricks=ce5a1a ]] --- wool-like colour of each dye, then concrete and terracotta (same order as Colors.DYES) 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" --- wood types: planks, bark (log / wood), leaves 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" @@ -84928,10 +82605,8 @@ return Colors end __FILES["codecs/model/Minecraft/Legacy"] = function() --- codecs/model/Minecraft/Legacy: numeric block ids of Minecraft before 1.13 (the .schematic format, Anvil chunks with --- Blocks / Data arrays), from the Minecraft wiki "Java Edition data values/Pre-flattening" page (facts, not code): --- the 1.12 name of every id, and how the data value picks a variant for the blocks whose colour or wood depends on it --- (the modern name of that variant: wool 14 -> red_wool, planks 2 -> birch_planks). +-- 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 } @@ -84975,8 +82650,7 @@ gray_glazed_terracotta silver_glazed_terracotta cyan_glazed_terracotta purple_gl blue_glazed_terracotta brown_glazed_terracotta green_glazed_terracotta red_glazed_terracotta black_glazed_terracotta concrete concrete_powder - - structure_block]]) --- legacy names whose modern name differs (data value not involved; only one-to-one renames, so the way back is exact: --- lit_furnace, powered_repeater, ... keep their legacy names) +-- 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", @@ -85040,18 +82714,15 @@ __FILES["codecs/model/Minecraft/Packed"] = @native function() --- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code, from the Minecraft wiki "Chunk format" and --- the Sponge / Litematica schematic specs: long arrays (little-endian int64s as codecs/text/Nbt keeps them) holding --- bits-wide indices either spanning long boundaries (Litematica, chunks before 1.16) or not (chunks since 1.16: --- floor(64 / bits) per long, the rest padding), and the varint byte arrays of Sponge schematics. Indices are written --- to / read from u16 little-endian buffers. Every access is bounds-checked first; never throws. +-- 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 --- longsNeeded(count, bits, spanning) -> the number of longs a packed array of count indices takes @native function Packed.longsNeeded(count: number, bits: number, spanning: boolean): number if spanning then return (count * bits + 63) // 64 @@ -85060,8 +82731,6 @@ local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshi return (count + per - 1) // per end --- unpack(longs, bits, count, spanning, out, max) -> true | false, message: count indices into out (u16 LE, from byte --- 0); an index >= max is an error. bits 1 .. 16. @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" @@ -85073,7 +82742,6 @@ end if buffer.len(out) < count * 2 then return false, "output too small" end - -- a copy with 4 bytes of padding, so every 32-bit read stays in range local n = need * 8 local src = buffer.create(n + 4) buffer.copy(src, 0, longs, 0, n) @@ -85111,7 +82779,6 @@ end return true, nil end --- pack(indices, count, bits, spanning) -> longs buffer (little-endian int64s): the inverse of unpack @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) @@ -85121,7 +82788,6 @@ end local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits local at = rshift(p, 3) local sh = band(p, 7) - -- OR the value in byte by byte (up to 3 bytes for 16 bits at a shift of 7) local x = lshift(v, sh) for k = 0, 2 do local bits8 = band(rshift(x, k * 8), 0xff) @@ -85135,7 +82801,6 @@ end return res end --- bitsFor(n, min) -> bits for indices 0 .. n - 1 (at least min) @native function Packed.bitsFor(n: number, min: number): number local b = min while lshift(1, b) < n and b < 31 do @@ -85144,8 +82809,7 @@ end return b end --- varints(src, offset, length, count, out, max) -> true | false, message: count unsigned LEB128 varints (Sponge --- BlockData) into out (u16 LE) +-- 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" @@ -85176,7 +82840,6 @@ end return true, nil end --- toVarints(indices, count) -> buffer: count u16 indices as unsigned LEB128 varints @native function Packed.toVarints(indices: buffer, count: number): buffer local out = buffer.create(count * 3) local p = 0 @@ -85195,8 +82858,7 @@ end return res end --- nibble(src, offset, i, highFirst) -> the 4-bit value i of a nibble array (Minecraft: low nibble first; WorldEdit's --- AddBlocks: high nibble first) +-- 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 @@ -85206,7 +82868,6 @@ end return rshift(b, 4) end --- setNibble(dst, offset, i, v, highFirst) @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) @@ -85218,9 +82879,7 @@ end end end --- fromYzx(src, sx, sy, sz, dst?, ox?, oy?, oz?, dsx?, dsy?) -> dst: u16 cells in Minecraft's order (x fastest, then --- z, then y: schematics, chunk sections) to Types.Voxels order (x, then y, then z), into dst (default a new --- sx * sy * sz grid) at cell offset (ox, oy, oz) of a dsx * dsy * ... grid. The caller checks the ranges. +-- 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 @@ -85239,7 +82898,6 @@ end return out end --- toYzx(src, sx, sy, sz) -> buffer: Types.Voxels order to Minecraft's (the inverse of fromYzx) @native function Packed.toYzx(src: buffer, sx: number, sy: number, sz: number): buffer local out = buffer.create(sx * sy * sz * 2) local i = 0 @@ -85260,18 +82918,8 @@ return Packed end __FILES["codecs/model/Polygon"] = function() --- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map --- sectors, ...). Loops are classified by nesting (a loop inside an odd number of other loops is a hole of the --- smallest loop around it), oriented, each hole bridged to its outer loop at a mutually visible vertex, then the --- result is ear-clipped (reflex-vertex test; a polygon that never yields a clean ear clips its least bad corner so --- every input terminates). New in rosetta, after the classic "ear clipping with hole bridging" method --- (D. Eberly, Triangulation by Ear Clipping); no code taken. --- --- local tris = Polygon.triangulate({ { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 } }) --- -- tris = { loop, index, loop, index, loop, index, ... }: three corners per triangle, each a (loop, vertex) pair --- -- (1-based), counter-clockwise --- --- Never throws; degenerate loops (fewer than 3 points, zero area) are ignored. +-- 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 } @@ -85304,7 +82952,6 @@ 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 --- segments p1-p2 and q1-q2 cross properly (touching at an endpoint does not count) 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 @@ -85326,8 +82973,6 @@ local function visible(m: Pt, v: Pt, rings: { { Pt } }): boolean return true end --- splice hole h into ring outer (both oriented: outer counter-clockwise, hole clockwise) at mutually visible --- vertices; others = every ring the bridge must not cross local function bridge(outer: { Pt }, h: { Pt }, others: { { Pt } }): { Pt } local mi = 1 for i, p in h do @@ -85371,7 +83016,6 @@ 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 --- ear clipping of one counter-clockwise ring local function clip(ring: { Pt }, out: { number }) local pts = table.clone(ring) local guard = #pts * #pts + 16 @@ -85420,7 +83064,6 @@ local function clip(ring: { Pt }, out: { number }) end end --- triangulate(loops) -> { loop, index, ... }: loops[i] = { x1, y1, x2, y2, ... } (closed implicitly) function Polygon.triangulate(loops: { { number } }): { number } local rings: { { Pt } } = {} local areas: { number } = {} @@ -85445,7 +83088,6 @@ function Polygon.triangulate(loops: { { number } }): { number } end end end - -- nesting: the parent of a ring is the smallest ring containing its first point local n = #rings local depth, parent = table.create(n, 0), table.create(n, 0) for i = 1, n do @@ -85510,42 +83152,11 @@ return Polygon end __FILES["codecs/model/Rbx"] = function() --- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl, --- model/rbxmx XML rbxmx / rbxlx), the typed property values, the CFrame rotation IDs, and (codecs/model/Rbx/Binary) the --- binary format's property column codecs. Shared here because a format cannot require another one. Written from the --- rbx-dom format notes (docs/binary.md, docs/xml.md) and checked against rbx-dom through rojo / lune. A file library, --- not a Roblox runtime: nothing here creates Instances; a Roblox game reads the tree itself. --- --- local tree = Rbx.tree() -- { kind = "rbxtree", roots = {}, place = false, ... } --- local part = Rbx.instance("Part", "Floor") -- { className, name, properties = {}, children = {} } --- Rbx.set(part, "Size", "Vector3", { 64, 1, 64 }) -- properties.Size = { type = "Vector3", value = {...} } --- Rbx.add(tree, part) -- a root; Rbx.add(parentInstance, child) nests --- for inst, depth in Rbx.descendants(tree) do ... end --- --- Property values are { type = , value = } with these value forms (arrays follow the Roblox constructor --- argument order, so Vector3.new(table.unpack(v.value)) / CFrame.new(table.unpack(v.value)) rebuild them in Roblox): --- String, BinaryString, ProtectedString, ContentId, Bytecode string (bytes) --- SharedString string (the content; writers deduplicate) --- Bool boolean --- Int32, Int64, Float32, Float64 number (Int64 exact to 2^53) --- Enum, BrickColor, SecurityCapabilities number --- Faces number: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32 --- Axes number: bits X 1, Y 2, Z 4 --- UDim { scale, offset } UDim2 { xScale, xOffset, yScale, yOffset } NumberRange { min, max } --- Vector2 / Vector2int16 { x, y } Vector3 / Vector3int16 { x, y, z } Color3 { r, g, b } (0..1) --- Color3uint8 { r, g, b } (0..255) Rect { minX, minY, maxX, maxY } Ray { ox, oy, oz, dx, dy, dz } --- CFrame { x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 } OptionalCFrame: the same, or nil (none) --- NumberSequence { { time, value, envelope } ... } ColorSequence { { time, r, g, b, envelope } ... } --- PhysicalProperties nil (default) | { density, friction, elasticity, frictionWeight, elasticityWeight, --- acousticAbsorption } (decoders fill acousticAbsorption = 1 when the file leaves it out) --- Ref an Instance of the tree, or nil --- UniqueId 32 hex digits: random (16), time (8), index (8) --- Font { family, weight (100..900), style ("Normal" | "Italic"), cachedFaceId? } --- Content nil (none) | string (a URI) | an Instance (object) --- Raw a binary property of a type this library does not know: { typeId, data (the class's whole column), --- index, count }; written back verbatim while the class keeps the same instances in the same order --- XmlRaw an XML property of an unknown type: value = the element (codecs/text/Xml node), written back as it is --- Name is not a property here: it is inst.name. Never throws. +-- 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 = {} @@ -85555,20 +83166,19 @@ type Instance = { name: string, properties: { [string]: Value }, children: { Instance }, - parent: Instance?, -- nil for roots - referent: string?, -- the file's referent (XML "RBX..." id, binary index) when read; writers make their own + parent: Instance?, + referent: string?, service: boolean?, -- a service (binary INST object format 1; rbxl roots) } type Tree = { kind: "rbxtree", roots: { Instance }, - place: boolean, -- a place (rbxl / rbxlx: the roots are services under the DataModel) or a model + place: boolean, metadata: { [string]: string }, -- binary META / XML entries (ExplicitAutoJoints, ...) - extra: { any }, -- unknown binary chunks { name, data } / unknown top-level XML elements, written back + extra: { any }, meta: { source: { format: string, [string]: any }?, [string]: any }, } --- ------------------------------------------------------------------------------------------------ tree function Rbx.tree(place: boolean?): Tree return { kind = "rbxtree", roots = {}, place = place == true, metadata = {}, extra = {}, meta = {} } end @@ -85577,7 +83187,6 @@ function Rbx.instance(className: string, name: string?): Instance return { className = className, name = name or className, properties = {}, children = {} } end --- add(parent, child) -> child: parent is a Tree (child becomes a root) or an Instance function Rbx.add(parent: any, child: Instance): Instance if parent.kind == "rbxtree" then child.parent = nil @@ -85589,19 +83198,15 @@ function Rbx.add(parent: any, child: Instance): Instance return child end --- set(inst, name, type, value): a property (value nil = the type's nil form: Ref none, OptionalCFrame none, ...) function Rbx.set(inst: Instance, name: string, typ: string, value: any) inst.properties[name] = { type = typ, value = value } end --- get(inst, name) -> the property's value (not the Value table), nil when absent function Rbx.get(inst: Instance, name: string): any local v = inst.properties[name] return if v then v.value else nil end --- descendants(treeOrInstance) -> iterator over (instance, depth) in depth-first order (roots / the instance's children --- at depth 1) function Rbx.descendants(root: any): () -> (Instance?, number?) local stack: { any } = {} local list = if root.kind == "rbxtree" then root.roots else root.children @@ -85621,7 +83226,6 @@ function Rbx.descendants(root: any): () -> (Instance?, number?) end end --- list(tree) -> every instance, depth first function Rbx.list(tree: any): { Instance } local out = {} for inst in Rbx.descendants(tree) do @@ -85630,7 +83234,6 @@ function Rbx.list(tree: any): { Instance } return out end --- find(treeOrInstance, path) -> the instance at a "/"-separated path of names ("Workspace/Baseplate"), or nil function Rbx.find(root: any, path: string): Instance? local cur: any = root for part in string.gmatch(path, "[^/]+") do @@ -85650,7 +83253,6 @@ function Rbx.find(root: any, path: string): Instance? return if cur.kind == "rbxtree" then nil else cur end --- fullName(inst) -> "Workspace.Model.Part" (names joined up to the root) function Rbx.fullName(inst: Instance): string local parts = {} local cur: Instance? = inst @@ -85661,12 +83263,10 @@ function Rbx.fullName(inst: Instance): string return table.concat(parts, ".") end --- ------------------------------------------------------------------------------------------------ CFrame rotation ids -- 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 } } --- the rotation of an id as { r00 .. r22 } (row major), or nil for an id that is not a rotation local ROTATIONS: { [number]: { number } } = {} for a = 0, 5 do for b = 0, 5 do @@ -85689,7 +83289,6 @@ local function axisIndex(x: number, y: number, z: number): number? return nil end --- rotationId(cf) -> the id of the CFrame's rotation (cf = { x, y, z, r00 .. r22 }), or 0 when it is not axis aligned function Rbx.rotationId(cf: { number }): number local a = axisIndex(cf[4], cf[7], cf[10]) local b = axisIndex(cf[5], cf[8], cf[11]) @@ -85704,7 +83303,6 @@ function Rbx.rotationId(cf: { number }): number return id end --- ------------------------------------------------------------------------------------------------ values -- binary type ids (rbx-dom docs/binary.md) by type name, and back Rbx.TYPE_IDS = table.freeze({ String = 0x01, @@ -85752,8 +83350,7 @@ for name, id in Rbx.TYPE_IDS do end Rbx.TYPE_NAMES = table.freeze(NAMES) --- the value a binary writer uses for an instance without the property (zero / empty / identity; BrickColor 194, the --- Medium stone grey Roblox defaults to; sequences of two keypoints at times 0 and 1) +-- 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 @@ -85786,7 +83383,6 @@ function Rbx.default(typ: string): any return 0 end --- STRINGS: the string-valued types (one binary type, several XML tags) Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString = true, ContentId = true, Bytecode = true } :: { [string]: boolean }) return Rbx @@ -85795,19 +83391,8 @@ __FILES["codecs/model/Rbx/Binary"] = @native function() --- codecs/model/Rbx/Binary: the property columns of the Roblox binary format (rbx-dom docs/binary.md): one PROP chunk --- holds a property's values for every instance of a class, by type id, with the format's array transforms: byte --- interleaving (all first bytes, then all second bytes, ...), big-endian integers, zigzag signed integers, "rotated" --- floats (sign bit moved to bit 0), delta-coded referents, and CFrame rotation ids (codecs/model/Rbx). Never throws. --- --- local values, pEnd = Binary.decode(typeId, buf, p, limit, n, ctx) -- n plain values (codecs/model/Rbx forms) --- local err = Binary.encode(typeId, values, n, writer, ctx) -- nil, or a message --- Binary.readRefs(buf, p, limit, n) / Binary.writeRefs(writer, refs) -- referent arrays (INST, PRNT) --- --- ctx: { ref = function(referent) -> Instance? (decode), refOf = function(Instance?) -> referent (-1 = none), --- shared = { string } (SSTR entries, 1-based, decode), sharedIndex = function(string) -> 0-based index (encode) }. --- decode returns nil, message on bad data ("truncated", "corrupt: ...", "unknown" for a type id it does not know / --- a layout it cannot read, which the format keeps raw). +-- 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") @@ -85822,7 +83407,6 @@ local floor = math.floor local scratch = buffer.create(8) local TWO32 = 4294967296 --- ------------------------------------------------------------------------------------------------ transforms -- 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) @@ -85841,7 +83425,6 @@ end return (if v >= 0 then v * 2 else -v * 2 - 1) % TWO32 end --- n big-endian u32 values interleaved at p (4n bytes) @native local function u32s(b: buffer, p: number, n: number): { number } local out = table.create(n, 0) local n2, n3 = n * 2, n * 3 @@ -85864,7 +83447,6 @@ end end return out end --- n zigzag i64 values (8n interleaved bytes), as doubles @native local function i64s(b: buffer, p: number, n: number): { number } local out = table.create(n, 0) for i = 0, n - 1 do @@ -85876,7 +83458,6 @@ end return out end --- writers: n values interleaved as big-endian u32 / zigzag i32 / rotated f32 / zigzag i64 @native local function putU32s(w: Bytes.Writer, vals: { number }) local n = #vals local p = w:reserve(4 * n) @@ -85947,7 +83528,6 @@ end putI32s(w, d) end --- ------------------------------------------------------------------------------------------------ decode type Ctx = { ref: ((number) -> any)?, refOf: ((any) -> number)?, @@ -85955,7 +83535,6 @@ type Ctx = { sharedIndex: ((string) -> number)?, } --- a length-prefixed string at p: string, next p (nil when it runs past limit) @native local function str(b: buffer, p: number, limit: number): (string?, number) if p + 4 > limit then return nil, p @@ -86005,7 +83584,7 @@ end return out, p + 12 * n end -local FIXED: { [number]: number } = { -- bytes per value of the fixed-size types +local FIXED: { [number]: number } = { [0x02] = 1, [0x03] = 4, [0x04] = 4, @@ -86032,7 +83611,6 @@ local FIXED: { [number]: number } = { -- bytes per value of the fixed-size types [0x21] = 8, } --- decode(typeId, b, p, limit, n, ctx) -> n values, the end offset | nil, message @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" @@ -86325,11 +83903,9 @@ local FIXED: { [number]: number } = { -- bytes per value of the fixed-size types return nil, "unknown" end --- ------------------------------------------------------------------------------------------------ encode @native local function num(v: any): number return if type(v) == "number" and v == v then v else 0 end --- column c of n array values (missing components 0) @native local function column(vals: { any }, n: number, c: number): { number } local out = table.create(n, 0) for i = 1, n do @@ -86365,8 +83941,6 @@ end return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0 end --- encode(typeId, values, n, w, ctx) -> nil | message: values[1 .. n] in the codecs/model/Rbx forms (nil entries are --- the type's none / default) @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 @@ -86569,18 +84143,7 @@ return Binary end __FILES["codecs/model/Rig"] = function() --- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each --- format only parses its file: vertex-animation frames as morph targets plus "weights" animations, joint hierarchies --- as Scene nodes plus a Skin (inverse bind matrices), per-vertex joint influences as JOINTS_0 / WEIGHTS_0, and --- keyframed joint TRS tracks as animation channels. New in rosetta. --- --- Rig.morph(prim, frames) -- frames[k] = f32 x3 positions: targets[k] = frame k - base --- Rig.morphAnimation(scene, node, #frames, { { name = "run", first = 41, last = 46, fps = 10 } }, "LINEAR") --- local nodes, skin = Rig.skeleton(scene, joints, "world") -- joints = { { name, parent (0 = root), t, r, s? } } --- prim.attributes.JOINTS_0, prim.attributes.WEIGHTS_0 = Rig.influences(lists) -- lists[v] = { j1, w1, j2, w2, ... } --- Rig.animation(scene, "idle", nodes, times, tracks) -- tracks[j] = { translation = {...}, rotation = {...} } --- --- Frames, joints and tracks come from parsed files: the helpers check every count they rely on and never throw. +-- 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") @@ -86591,18 +84154,14 @@ local readf32, writef32, writeu16 = buffer.readf32, buffer.writef32, buffer.writ type Joint = { name: string?, - parent: number, -- 1-based index into the joint list, 0 for a root (parents come before their children) + parent: number, translation: { number }, rotation: { number }, -- quaternion x, y, z, w scale: { number }?, } -type Range = { name: string?, first: number, last: number, fps: number? } -- frames first..last (1-based) -type Track = { translation: { number }?, rotation: { number }?, scale: { number }? } -- flat, one key per time +type Range = { name: string?, first: number, last: number, fps: number? } +type Track = { translation: { number }?, rotation: { number }?, scale: { number }? } --- ------------------------------------------------------------------------------------------------ morph targets --- morph(prim, frames, normals?, base?) -> (): prim.targets[k] = { POSITION = frames[k] - base positions } (and NORMAL --- deltas when normals[k] is given), base = prim.attributes.POSITION (and NORMAL). Every frame buffer must hold as --- many f32 x3 as the base; shorter ones are skipped (false is returned). 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 @@ -86640,9 +84199,6 @@ function Rig.morph(prim: Types.Primitive, frames: { buffer }, normals: { buffer return ok end --- morphAnimation(scene, node, targets, ranges, interpolation?) -> (): one animation per range, a "weights" channel on --- scene.nodes[node] whose key k (at (k - first) / fps seconds) sets target k to 1 and the others to 0 (LINEAR --- blends neighbouring frames, as the games do; default "LINEAR"). Ranges out of 1..targets are clamped / skipped. 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)) @@ -86671,9 +84227,7 @@ function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, r end end --- normals(pos, count, indices) -> f32 x3 buffer: smooth vertex normals (area-weighted face normals, normalised) of a --- triangle list (indices: 0-based, three per triangle; out-of-range triangles are skipped). For formats whose stored --- normals cannot be used (Quake's precomputed normal table is not redistributable here). +-- 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) @@ -86704,13 +84258,11 @@ function Rig.normals(pos: buffer, count: number, indices: { number }): buffer return out end --- ------------------------------------------------------------------------------------------------ skeletons local function trs(j: Joint): { number } return Mat4.compose(j.translation, j.rotation, j.scale) end --- angles(x, y, z) -> quaternion { x, y, z, w } of the Euler angles in radians applied x first, then y, then z --- (R = Rz * Ry * Rx: the Quake / Half-Life "AngleQuaternion" convention of MDL bones and SMD skeletons) +-- 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) @@ -86718,10 +84270,6 @@ function Rig.angles(x: number, y: number, z: number): { number } 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 --- skeleton(scene, joints, space, root?) -> (joint node indices, skin index, world matrices): one node per joint (TRS relative to its --- parent), parented as listed, roots added to scene.roots (or as children of node `root`); a Skin with the inverse --- bind matrices. space "local": joint TRS are relative to the parent (SMD, MDL); "world": in model space (MD5's --- bind pose), converted to local here. A parent index that does not come earlier makes the joint a root. function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number, { { number } }) local n = #joints local world: { { number } } = {} @@ -86767,9 +84315,6 @@ function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "w return nodes, #scene.skins, world end --- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with --- 0-based joint indices (into the skin's joints; a joint listed twice adds up); the four largest weights are kept --- and normalised to sum 1. function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) local n = #lists local jb, wb = buffer.create(n * 8), buffer.create(n * 16) @@ -86780,7 +84325,7 @@ function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) if l[k + 1] > 0 then local same = at[l[k]] if same then - same[2] += l[k + 1] -- the same joint twice: one influence + same[2] += l[k + 1] else local e = { l[k], l[k + 1] } at[l[k]] = e @@ -86803,7 +84348,6 @@ function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) return Scene.accessor(jb, "u16", 4, n), Scene.accessor(wb, "f32", 4, n) end --- ------------------------------------------------------------------------------------------------ animations local function floats(t: { number }, count: number, comps: number): Types.Accessor? if #t < count * comps then return nil @@ -86815,9 +84359,6 @@ local function floats(t: { number }, count: number, comps: number): Types.Access return Scene.accessor(b, "f32", comps, count) end --- animation(scene, name, nodes, times, tracks, interpolation?) -> the animation index: tracks[j] (j = index into --- nodes) holds flat translation (x3) / rotation (quaternion x4) / scale (x3) keys, one per time (seconds); tracks --- with too few keys are skipped. Default interpolation "LINEAR". 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) @@ -86845,17 +84386,7 @@ return Rig end __FILES["codecs/model/Sampler"] = function() --- codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for --- rotations, CUBICSPLINE Hermite splines as glTF 2.0 defines them; times before the first / after the last key hold --- the end values), and the node poses of an animation at a time, for writers of formats that store sampled frames --- (IQM, MD5, BVH, ...). New in rosetta. --- --- local sample = Sampler.channel(ch) -- nil for an unreadable channel --- local v = sample(0.5) -- { x, y, z } / { x, y, z, w } / the morph weights --- local times = Sampler.times(anim) -- every key time of the animation, sorted, unique --- local pose = Sampler.pose(scene, anim, 0.5) -- pose[node] = { translation?, rotation?, scale?, weights? } --- --- Never throws on bad data: unreadable channels are skipped. +-- codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 animations. New code. local Types = __include("Types") local Sampler = {} @@ -86888,7 +84419,6 @@ local function slerp(a: { number }, b: { number }, s: number): { number } return normalize({ a[1] * wa + bx * wb, a[2] * wa + by * wb, a[3] * wa + bz * wb, a[4] * wa + bw * wb }) end --- channel(ch) -> sample(t) | nil function Sampler.channel(ch: Types.Channel): Sample? local inp, out = ch.input, ch.output if type(inp) ~= "table" or type(out) ~= "table" then @@ -86915,7 +84445,6 @@ function Sampler.channel(ch: Types.Channel): Sample? times[k] = IN(k - 1, 0) end local oc = out.components - -- element e (0-based, of comps values) of the flat output local function get(e: number): { number } local v = table.create(comps) :: { number } for c = 0, comps - 1 do @@ -86924,7 +84453,7 @@ function Sampler.channel(ch: Types.Channel): Sample? end return v end - local function value(k: number): { number } -- key k (1-based) + local function value(k: number): { number } return get(if cubic then (k - 1) * 3 + 1 else k - 1) end local rot = ch.path == "rotation" @@ -86973,7 +84502,6 @@ function Sampler.channel(ch: Types.Channel): Sample? end end --- times(anim) -> every key time, sorted and unique function Sampler.times(anim: Types.Animation): { number } local seen: { [number]: boolean } = {} local out: { number } = {} @@ -86994,8 +84522,6 @@ function Sampler.times(anim: Types.Animation): { number } return out end --- pose(scene, anim, t, samplers?) -> pose[node] = { [path] = values } for the animated nodes. samplers: a cache table --- (reuse it across calls for the same animation) function Sampler.pose(_scene: Types.Scene, anim: Types.Animation, t: number, samplers: { [any]: any }?): Pose local cache: { [any]: any } = samplers or {} local pose: Pose = {} @@ -87020,14 +84546,8 @@ return Sampler end __FILES["codecs/model/Vrml"] = function() --- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML, --- .x3dv classic): one parser for the classic encoding (codecs/model/Vrml/Parse), one for the XML encoding --- (codecs/model/Vrml/Xml over codecs/text/Xml), both into the same node graph, and one builder from the graph to a --- Scene (codecs/model/Vrml/Build, codecs/model/Vrml/Geometry). Gzipped files (.wrz / .x3dz / .x3dvz) are inflated --- first. New code, written from ISO/IEC 14772-1 (VRML97), ISO/IEC 19775-1 (X3D) and its encodings 19776-1 / -2. --- --- local graph, err = Vrml.graph(bytes) -- classic or XML, by content --- local scene, err2 = Vrml.decode(bytes, { format = "vrml", files = { ["tex.png"] = png } }) +-- 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") @@ -87042,12 +84562,11 @@ local Vrml = {} type Graph = Parse.Graph type Node = Parse.Node type Options = Build.Options & { - files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) - resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) - maxBytes: number?, -- the inflated size of a gzipped file (default 2^28) + files: { [string]: any }?, + resolve: ((uri: string) -> any)?, + maxBytes: number?, } --- the bytes as text: gzip inflated, UTF-8 BOM dropped 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 @@ -87078,7 +84597,6 @@ local function code(msg: string): string return Err.CORRUPT end --- parse(text) -> the graph of a classic-encoding file (VRML97 / .x3dv) function Vrml.parse(s: string): (Graph?, Err.Err?) local g, msg = Parse.parse(s) if not g then @@ -87087,7 +84605,6 @@ function Vrml.parse(s: string): (Graph?, Err.Err?) return g, nil end --- parseXml(text | XML document) -> the graph of an X3D XML file function Vrml.parseXml(src: any): (Graph?, Err.Err?) local doc = src if type(src) == "string" then @@ -87108,7 +84625,6 @@ function Vrml.parseXml(src: any): (Graph?, Err.Err?) return g, nil end --- graph(bytes, opts?) -> the graph of either encoding (XML when the text starts with "<"); binary X3D is UNSUPPORTED function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?) local s, err = text(data, opts and opts.maxBytes) if not s then @@ -87124,7 +84640,6 @@ function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?) return Vrml.parse(s) end --- fetcher(opts) -> fetch(uri) -> buffer?: opts.files (uri or base name) / opts.resolve function Vrml.fetcher(opts: Options?): (uri: string) -> buffer? return function(uri: string): buffer? if not opts then @@ -87142,7 +84657,6 @@ function Vrml.fetcher(opts: Options?): (uri: string) -> buffer? end end --- build(graph, opts?) -> Scene 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) @@ -87157,7 +84671,6 @@ function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?) return scene, nil end --- decode(bytes, opts?) -> Scene: graph + build function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err.Err?) local g, err = Vrml.graph(data, opts) if not g then @@ -87166,7 +84679,6 @@ function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err. return Vrml.build(g, opts) end --- encode(scene, opts?) -> text: opts.encoding "vrml97" (default) / "x3dv" / "xml"; texture bytes go into opts.files 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") @@ -87182,18 +84694,9 @@ return Vrml end __FILES["codecs/model/Vrml/Build"] = function() --- codecs/model/Vrml/Build: the VRML97 / X3D node graph (codecs/model/Vrml/Parse, codecs/model/Vrml/Xml) to a Scene. --- Written from the specifications; no third-party code. Grouping nodes (Group, Transform with center / scaleOrientation, --- Anchor, Billboard, Collision, StaticGroup, Switch whichChoice, LOD first level, CAD and HAnim groups, Inline through --- the fetch callback) become nodes; a Transform is one TRS node (translation T + C, rotation R * SR, scale S) and, when --- it has a center or scale orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children. --- Shapes become meshes (shared by USE), Appearance / Material / PhysicalMaterial / UnlitMaterial / TwoSidedMaterial --- materials (Phong terms in material.extras.vrml; solid FALSE -> doubleSided), ImageTexture / MovieTexture --- (uri, data through fetch, repeatS / repeatT), PixelTexture (texture.image), TextureTransform (KHR transform: --- translation / scale / rotation; the center in extras); Viewpoint / OrthoViewpoint -> cameras, DirectionalLight / --- PointLight / SpotLight -> lights; ROUTEs from a TimeSensor through Position- / OrientationInterpolators to a --- Transform's translation / rotation / scale -> animations (key times x cycleInterval). Other nodes are counted in --- meta.source.skipped. Never throws: bad data returns nil, message. +-- 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") @@ -87206,16 +84709,15 @@ local nums, num, vec, bool, str, strs, node, nodes = Fields.nums, Fields.num, Fi local deg = math.deg type Options = Geometry.Options & { - fetch: ((uri: string) -> buffer?)?, -- reads textures and Inline files - load: ((data: buffer) -> (any, string?))?, -- an Inline file's bytes -> its graph - format: string?, -- meta.source.format - maxInline: number?, -- Inline nesting (default 8) + 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" } --- nodes with nothing to show (not counted as skipped) local QUIET = { WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true, PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true, @@ -87250,7 +84752,6 @@ end local function isIdentityQ(q: { number }): boolean return q[1] == 0 and q[2] == 0 and q[3] == 0 end --- the rotation taking unit vector a onto b 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 @@ -87259,7 +84760,6 @@ local function between(a: { number }, b: { number }): { number } 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 - -- opposite: half a turn about any perpendicular axis 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 @@ -87293,7 +84793,6 @@ local function addNode(ctx: Ctx, n: Types.Node, parent: number?): number return i end --- ------------------------------------------------------------------------------------------------ materials local function texture(ctx: Ctx, t: any): number? if not t then return nil @@ -87465,7 +84964,6 @@ local function material(ctx: Ctx, app: any, solid: boolean): number? return idx end --- ------------------------------------------------------------------------------------------------ nodes local walk: (ctx: Ctx, n: any, parent: number?) -> () local function shape(ctx: Ctx, n: any, parent: number?) @@ -87487,7 +84985,6 @@ local function shape(ctx: Ctx, n: any, parent: number?) end local count = if prim.indices then prim.indices.count else prim.attributes.POSITION.count if count == 0 then - -- nothing to draw (no valid faces / points) ctx.meshes[n] = false return end @@ -87674,11 +85171,9 @@ function walk(ctx: Ctx, n: any, parent: number?) ctx.depth -= 1 end --- ------------------------------------------------------------------------------------------------ animation local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" } local function animations(ctx: Ctx, routes: { any }) - -- interpolator -> its TimeSensor local timer: { [any]: any } = {} for _, r in routes do if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then @@ -87747,7 +85242,6 @@ local function animations(ctx: Ctx, routes: { any }) end end --- ------------------------------------------------------------------------------------------------ scene function Build.scene(graph: any, opts: Options): (Types.Scene?, string?) local scene = S.new() scene.meta.up = "y" @@ -87774,15 +85268,11 @@ return Build end __FILES["codecs/model/Vrml/Fields"] = function() --- codecs/model/Vrml/Fields: typed reads of node fields for codecs/model/Vrml/Build and Geometry. A classic-encoding --- value is a flat array (numbers, strings, booleans, nodes); an X3D XML value is the raw attribute string, parsed here --- on first use (numbers split on blanks / commas, MFString as quoted strings or one unquoted string, booleans --- true / false). Never throws. +-- 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 --- quoted strings of an MFString attribute ("a" "b \"c\""), or the text itself when it is not quoted local function mfString(s: string): { string } local out = {} local p = find(s, "[^%s,]") @@ -87818,7 +85308,6 @@ local function mfString(s: string): { string } return out end --- nums(node, name) -> the numbers of a field (booleans as 1 / 0), or nil when absent function Fields.nums(node: any, name: string): { number }? local v = node.fields[name] if v == nil then @@ -87868,7 +85357,6 @@ function Fields.num(node: any, name: string, default: number): number return if v and type(v[1]) == "number" then v[1] else default end --- vec(node, name, default) -> the first #default numbers of a field (the default when the field is shorter) function Fields.vec(node: any, name: string, default: { number }): { number } local v = Fields.nums(node, name) if not v or #v < #default then @@ -87922,7 +85410,6 @@ function Fields.str(node: any, name: string, default: string?): string? return default end --- nodes(node, name) -> the nodes of an SFNode / MFNode field function Fields.nodes(node: any, name: string): { any } local v = node.fields[name] local out = {} @@ -87944,14 +85431,8 @@ return Fields end __FILES["codecs/model/Vrml/Geometry"] = function() --- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. Written from the specifications; no --- third-party code. IndexedFaceSet (coord / normal / color / texCoord with their own indices, per-vertex or per-face --- normals and colours, ccw, convex polygons fan-triangulated or kept as "polygons"), the X3D triangle / quad sets --- (IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, TriangleFanSet, IndexedTriangleStripSet, --- TriangleStripSet, IndexedQuadSet, QuadSet), ElevationGrid, Extrusion (spine-aligned cross sections, scale, --- orientation, caps), IndexedLineSet / LineSet ("lines"), PointSet ("points"), and the primitives Box, Sphere, Cone, --- Cylinder tessellated with normals and the specification's texture mapping. Texture coordinates get t flipped to --- glTF's top-left origin unless flipV = false. Never throws: returns nil, message for bad data. +-- 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") @@ -87980,7 +85461,6 @@ local function u32(list: { number }): Types.Accessor return a end --- the colour node's values and component count (Color: 3, ColorRGBA: 4) local function colors(n: any): ({ number }?, number) local c = node(n, "color") if not c then @@ -87995,14 +85475,11 @@ local function points(n: any, field: string, sub: string): { number }? return if c then nums(c, sub) or {} else nil end --- ------------------------------------------------------------------------------------------------ polygon meshes --- Mesh input: faces as corner lists of coordinate indices (0-based) plus, per attribute, a per-corner index list (nil: --- the coordinate index) or per-face indices. type PolyIn = { - P: { number }, -- coordinates, 3 per point - corners: { number }, -- coordinate index per corner, face after face - sizes: { number }, -- corners per face - N: { number }?, nIdx: { number }?, nFace: boolean?, -- normals; per-corner or per-face indices (nil: identity) + 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, @@ -88013,7 +85490,6 @@ local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?) local np = #P // 3 local N, C, T = m.N, m.C, m.T local cc = m.cComps or 3 - -- the attribute index of corner k (1-based) in face f (1-based) 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 @@ -88022,7 +85498,7 @@ local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?) 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 } } = {} -- per output vertex: coord, normal, colour, texcoord indices + local vsrc: { { number } } = {} local out: { number } = {} local outSizes: { number } = {} local k = 0 @@ -88124,7 +85600,6 @@ local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?) return prim end --- split a -1 separated index list into corners + sizes local function split(list: { number }): ({ number }, { number }) local corners, sizes = {}, {} local run = 0 @@ -88175,7 +85650,6 @@ local function faceSet(n: any, o: Options, maxV: number): (Types.Primitive?, str return polyMesh(m, o, maxV) end --- the X3D triangle / quad sets: faces from index (or vertex order) and fan / strip counts local function triSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) local t = n.type local P = points(n, "coord", "point") or {} @@ -88304,7 +85778,6 @@ local function elevationGrid(n: any, o: Options, maxV: number): (Types.Primitive return polyMesh(m, o, maxV) end --- ------------------------------------------------------------------------------------------------ Extrusion 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 @@ -88434,7 +85907,6 @@ local function extrusion(n: any, o: Options, maxV: number): (Types.Primitive?, s return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV) end --- ------------------------------------------------------------------------------------------------ lines, points local function lines(n: any, maxV: number): (any, string?) local P = points(n, "coord", "point") or {} local np = #P // 3 @@ -88528,8 +86000,6 @@ local function pointSet(n: any, maxV: number): (any, string?) return { attributes = attrs, mode = "points" } end --- ------------------------------------------------------------------------------------------------ primitives --- a primitive from flat arrays (positions, normals, uvs with the specification's bottom-left origin, triangles) local function direct(P: { number }, N: { number }, T: { number }, I: { number }, o: Options): Types.Primitive local nv = #P // 3 if o.flipV ~= false then @@ -88573,8 +86043,7 @@ local function box(n: any, o: Options): Types.Primitive return direct(P, N, T, I, o) end --- a ring of segs + 1 vertices (the seam doubled for the texture) at height y, radius r; s starts at the back (-z) --- and runs counter-clockwise seen from +y +-- 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 @@ -88594,7 +86063,6 @@ local function ring(P: { number }, N: { number }?, T: { number }?, segs: number, end end --- a cap disc at height y facing ny (+1 / -1) 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 @@ -88624,7 +86092,6 @@ local function cap(P: { number }, N: { number }, T: { number }, I: { number }, s end end --- quads between two rings of segs + 1 vertices starting at a (lower) and b (upper) local function band(I: { number }, a: number, b: number, segs: number) for i = 0, segs - 1 do table.insert(I, a + i) @@ -88672,9 +86139,6 @@ local function cylinder(n: any, o: Options, segs: number, cone: boolean): Types. return direct(P, N, T, I, o) end --- ------------------------------------------------------------------------------------------------ dispatch --- primitive(geometryNode, opts) -> Primitive | nil, message | nil, nil (a node type without geometry here); --- the second value of a success is the node's solid flag function Geometry.primitive(n: any, o: Options): (Types.Primitive?, any) local t = n.type local maxV = o.maxVertices or 2 ^ 24 @@ -88716,14 +86180,8 @@ return Geometry end __FILES["codecs/model/Vrml/Parse"] = function() --- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic VRML encoding (ISO/IEC 19776-2) parser, into --- the node graph codecs/model/Vrml/Build reads. Written from the specifications; no third-party code. Field types are --- not known without the node schemas, so a field value is kept as a flat array of what the file wrote (numbers, --- strings, booleans, nodes) and the builder reads it as the type it expects. Handles comments, DEF / USE, PROTO --- (instances are expanded: IS fields take the instance's values or the declared defaults; nested PROTOs, ROUTEs inside --- bodies), EXTERNPROTO (instances stay nodes of that type, without a body), Script / shader interface declarations, --- ROUTE, and the X3D header statements (PROFILE, COMPONENT, META, UNIT, IMPORT, EXPORT). Never throws: errors are --- returned as nil, message ("line N: ..."). +-- 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 } } @@ -88732,13 +86190,12 @@ type Proto = { name: string, fields: { [string]: any }, body: { Node }, routes: type Graph = { roots: { Node }, routes: { Route }, - header: { [string]: any }, -- version ("2.0" / "3.3" ...), encoding, x3d (boolean), profile - meta: { [string]: string }, -- META / WorldInfo statements + header: { [string]: any }, + meta: { [string]: string }, components: { string }, units: { [string]: { name: string, factor: number } }, protos: { [string]: Proto }, } --- an IS reference in a PROTO body: fields[name] = { is = "protoField" } type IsRef = { is: string } local find, sub, byte, match, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch @@ -88748,7 +86205,6 @@ 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 } --- copy(node, values, defaults, memo) -> a PROTO body node with its IS fields replaced (shared nodes stay shared) local function copy(node: Node, values: { [string]: any }, defaults: { [string]: any }, memo: { [any]: any }): Node local done = memo[node] if done then @@ -88777,7 +86233,6 @@ local function copy(node: Node, values: { [string]: any }, defaults: { [string]: return out end --- expand(proto, values, def, routes) -> the instance's node (the body's first node), or nil for an EXTERNPROTO function Parse.expand(proto: Proto, values: { [string]: any }, def: string?, routes: { Route }?): Node? if proto.extern or #proto.body == 0 then return nil @@ -88842,8 +86297,6 @@ function Parse.parse(text: string): (Graph?, string?) end end - -- the lexer: skip blanks, commas and comments; returns the next token kind and value - -- kinds: "num", "str", "id", "{", "}", "[", "]", ".", "eof" local function skip() while true do local q = find(text, "[^%s,]", p) @@ -88906,7 +86359,6 @@ function Parse.parse(text: string): (Graph?, string?) p += 1 return ".", nil end - -- +inf / -nan style words: read the word local _, we = find(text, "^[^%s,%[%]{}#\"]+", p) local w = sub(text, p, we) p = (we :: number) + 1 @@ -88938,12 +86390,10 @@ function Parse.parse(text: string): (Graph?, string?) local parseProto: (extern: boolean) -> () local parseRoute: () -> () - -- a field value (after its name): an array of numbers / strings / booleans / nodes local function value(): any local k, val = token() if k == "[" then local out = {} - -- fast path: a bracket of plain numbers (big coordinate arrays) local close = find(text, "]", p, true) if close then local seg = sub(text, p, close - 1) @@ -89015,7 +86465,6 @@ function Parse.parse(text: string): (Graph?, string?) return {} end - -- the fields of a node body, up to its "}" local function body(node: Node) while not failure do local k, name = token() @@ -89162,7 +86611,7 @@ function Parse.parse(text: string): (Graph?, string?) end end if extern then - value() -- the url list + value() protos[name] = proto return end @@ -89195,7 +86644,6 @@ function Parse.parse(text: string): (Graph?, string?) protos[name] = proto end - -- statements while not failure do local k, w = token() if k == "eof" then @@ -89254,17 +86702,7 @@ 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 text, --- for model/vrml and model/x3d. New code. Every node becomes a DEF'd Transform (a matrix is decomposed into TRS; --- shear is lost), each primitive a Shape: triangles / polygons / strips / fans -> IndexedFaceSet (coord, normal, --- texCoord with t flipped back unless flipV = false, color; per-vertex, ccw, solid = not doubleSided), lines -> --- IndexedLineSet, points -> PointSet; a mesh used twice is written once and USE'd. Materials -> Appearance / Material --- (diffuse = baseColor, transparency = 1 - alpha, emissive, shininess from roughness, the Phong terms of --- material.extras.vrml when present) with an ImageTexture (the texture bytes go into opts.files named after the uri or --- opts.name, else url = texture.uri). Cameras -> Viewpoint (X3D: OrthoViewpoint for orthographic ones), lights -> --- Directional / Point / SpotLight, animations (translation / rotation / scale channels) -> a TimeSensor and --- Position / OrientationInterpolators with ROUTEs (cubic splines keep their values, weights channels are dropped). --- Never throws: returns nil, message. +-- 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") @@ -89274,8 +86712,6 @@ local Write = {} type Options = { encoding: ("vrml97" | "x3dv" | "xml")?, files: { [string]: any }?, name: string?, flipV: boolean? } --- a written node: fields in order, each { name, kind, value }; kinds: "sf" / "mf" (numbers; mf groups `per` numbers --- per line), "bool", "str", "mstr" (MFString), "node", "nodes" type WNode = { type: string, def: string?, use: string?, fields: { { any } } } local format, concat = string.format, table.concat @@ -89300,7 +86736,6 @@ local function F(n: WNode, name: string, kind: string, value: any, per: number?) table.insert(n.fields, { name, kind, value, per }) end --- names: valid, unique DEF names local function namer(): (string?, string) -> string local used: { [string]: boolean } = {} return function(name: string?, fallback: string): string @@ -89318,7 +86753,6 @@ local function namer(): (string?, string) -> string end end --- axis-angle of a quaternion (x, y, z, w) 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) @@ -89332,7 +86766,6 @@ local function axisAngle(q: { number }): { number } return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) } end --- ------------------------------------------------------------------------------------------------ geometry local function values(acc: any): { number }? return (Flatten.numbers(acc)) end @@ -89400,7 +86833,6 @@ local function faceSet(prim: any, doubleSided: boolean, o: Options, x3d: boolean return g, nil end --- Coordinate from POSITION, Color / ColorRGBA from COLOR_0 (lines and points) local function coordNode(prim: any): (WNode?, number) local pos = values(prim.attributes.POSITION) if not pos then @@ -89496,7 +86928,6 @@ local function pointSet(prim: any, x3d: boolean): (WNode?, string?) return g, nil end --- ------------------------------------------------------------------------------------------------ materials 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? @@ -89602,7 +87033,6 @@ local function appearance(scene: any, mi: number, o: Options, written: { [number return app end --- ------------------------------------------------------------------------------------------------ the tree function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, string?) local x3d = o.encoding == "x3dv" or o.encoding == "xml" local name = namer() @@ -89615,7 +87045,6 @@ function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, stri local function shapes(mi: number): { WNode } local done = meshShapes[mi] if done then - -- USE the shapes written before local out = {} for _, s in done do table.insert(out, { type = "Shape", use = s.def, fields = {} }) @@ -89744,7 +87173,6 @@ function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, stri local roots: { WNode } = {} local list = scene.roots if type(list) ~= "table" or #list == 0 then - -- no roots: every node without a parent local child = {} for _, n in scene.nodes do for _, c in n.children or {} do @@ -89772,7 +87200,6 @@ function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, stri end end - -- animations: a TimeSensor per animation, an interpolator per channel local routes: { { string } } = {} for ai, anim in scene.animations or {} do local tmax = 0 @@ -89832,14 +87259,12 @@ function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, stri return roots, routes, nil end --- ------------------------------------------------------------------------------------------------ serializers 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 - -- index lists: one face per line local lines, cur = {}, {} for i, v in vals do table.insert(cur, out[i]) @@ -89920,7 +87345,6 @@ local function classic(roots: { WNode }, routes: { { string } }, x3d: boolean): return concat(out, "\n") .. "\n" end --- the containerField a child element needs when it is not its type's default 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?) @@ -89990,7 +87414,6 @@ local function xml(roots: { WNode }, routes: { { string } }): (string?, string?) return s, nil end --- text(scene, opts) -> the file text function Write.text(scene: any, o: Options): (string?, string?) local roots, routes, err = Write.graph(scene, o) if not roots or not routes then @@ -90006,13 +87429,7 @@ return Write end __FILES["codecs/model/Vrml/Xml"] = function() --- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the node graph of codecs/model/Vrml/Parse, so one --- builder serves .wrl, .x3dv and .x3d. Written from the specification; no third-party code. Elements are nodes; --- attributes stay raw strings (the builder parses them as the type it expects); child nodes go into their --- containerField (or the default field of their type: geometry, appearance, material, coord, ...); DEF / USE; ROUTE; --- ProtoDeclare (ProtoInterface fields with value attributes or child nodes, ProtoBody, IS / connect) and --- ProtoInstance (fieldValue) are expanded through Parse.expand; ExternProtoDeclare instances stay plain nodes; head / --- meta, UNIT, component and the profile go into the graph header. Never throws. +-- 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") @@ -90072,7 +87489,6 @@ function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?) end local declare: (el: Xml.Node, extern: boolean) -> () - -- the child elements of a node into its fields 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 @@ -90107,7 +87523,6 @@ function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?) end end - -- a field value of ProtoInterface / fieldValue: the value attribute, or the child nodes local function fieldValue(el: Xml.Node): any if el.attrs.value ~= nil then return el.attrs.value @@ -90247,19 +87662,6 @@ 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. --- Values are plain Luau: objects -> tables (string keys), arrays -> arrays, null -> Types.null (opts.null), numbers --- -> doubles (opts.bigInts = "string" keeps integers past 2^53 as their text). Empty objects are Types.object() so --- they write back as {}; opts.ordered makes every object a Types.object with its key order. --- --- local Json = require("@rosetta/codecs/text/Json") --- local v, err = Json.decode('{"a": [1, 2, null]}') -- string | buffer; nil, Err on bad input --- local s = Json.encode(v, { indent = 2 }) -- string | nil, Err --- for ev, x in Json.events(text) do ... end -- pull events without building the tree --- for i, v, err in Json.lines(ndjson) do ... end -- JSON Lines / concatenated JSON values --- local w = Json.writer({ indent = 2 }); w:beginObject(); w:key("a"); w:value(1); w:endObject(); w:tostring() --- --- Streaming: decodeAt(src, pos) parses one value and returns where the next begins; events() is a pull tokenizer; --- writer() builds output incrementally and flush() hands back the text so far. Never throws. local Err = __include("core/Err") local Types = __include("Types") local Decode = __include("codecs/text/Json/Decode") @@ -90293,8 +87695,6 @@ local function fail(msg: any, at: any, n: number): Err.Err return Err.new(code, m, at) end --- decode(src, opts?) -> value | nil, Err. One JSON text: a value with optional whitespace around it (a UTF-8 BOM is --- skipped). Note a JSON null top-level value decodes to opts.null (Types.null by default), never nil. function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err?) local s, terr = text(src) if not s then @@ -90312,8 +87712,6 @@ function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err? return v, nil end --- decodeAt(src, pos?, opts?) -> value, nextPos | nil, Err. One value starting at pos (1-based, default 1; leading --- whitespace skipped); nextPos is just past it. nil, nil when only whitespace is left. function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?): (any, any) local s, terr = text(src) if not s then @@ -90330,8 +87728,6 @@ function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?) return v, ni end --- lines(src, opts?) -> iterator: index, value (JSON Lines, or any whitespace-separated sequence of JSON values). A --- bad value gives a last index, nil, Err: for i, v, err in Json.lines(s) do if err then ... end end function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, any, Err.Err?) local s, terr = text(src) local pos = 1 @@ -90359,8 +87755,6 @@ function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, end end --- events(src, opts?) -> iterator: event, value. Events: "object", "endObject", "array", "endArray", "key" (the key), --- "value" (a scalar), and on bad input one final "error", Err. function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string?, any) local s, terr = text(src) if not s then @@ -90385,7 +87779,6 @@ function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string? end end --- encode(value, opts?) -> string | nil, Err function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?) local s, msg = Encode.encode(value, opts) if not s then @@ -90394,13 +87787,9 @@ function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?) return s, nil end -Json.quote = Encode.quote -- quote(s) -> '"..."' with JSON escapes -Json.number = Encode.number -- number(x) -> the shortest round-trip text (nil for NaN / inf) +Json.quote = Encode.quote +Json.number = Encode.number --- ------------------------------------------------------------------------------------------------ writer --- writer(opts?) -> a streaming Writer: beginObject / endObject / beginArray / endArray / key(k) / value(v) (any --- value, encoded whole), then tostring() for everything or flush() for the text since the last flush. Misuse (a key --- outside an object, a value where a key is due, unbalanced ends) is recorded in w.err and later calls do nothing. type Writer = { err: Err.Err?, beginObject: (self: Writer) -> Writer, @@ -90416,10 +87805,10 @@ type Writer = { function Json.writer(opts: EncodeOptions?): Writer local st = Encode.state(opts) local ind = st.indent - local kinds: { boolean } = {} -- true = object + local kinds: { boolean } = {} local counts: { number } = {} local depth = 0 - local keyDone = false -- an object's key written, its value due + local keyDone = false local flushed: { string } = {} local w: any = { err = nil } local function bad(msg: string) @@ -90427,7 +87816,6 @@ function Json.writer(opts: EncodeOptions?): Writer w.err = Err.new(Err.ARG, msg) end end - -- before an element: a comma / newline as needed; false when the position is wrong local function slot(isKey: boolean): boolean if w.err then return false @@ -90543,10 +87931,8 @@ end __FILES["codecs/text/Json/Decode"] = @native function() --- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json. Iterative (an explicit container stack, so deep nesting --- is a LIMIT error, never a stack overflow), strict grammar (no comments, trailing commas, leading zeros, NaN, single --- quotes or raw control characters), \u escapes with surrogate pairs (lone surrogates become WTF-8 bytes). Also the --- pull tokenizer behind Json.events. Never throws: failures return nil, message, offset (0-based byte offset). +-- 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") @@ -90557,10 +87943,10 @@ local tonumber = tonumber local concat = table.concat type Options = { - ordered: boolean?, -- every object is a Types.object with its key order (default false: only empty objects are) - bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their exact text (default "number") - null: any?, -- the value for null (default Types.null) - maxDepth: number?, -- nesting limit (default 1000) + ordered: boolean?, + bigInts: ("number" | "string")?, + null: any?, + maxDepth: number?, } local ESC: { [number]: string } = { @@ -90574,7 +87960,6 @@ local ESC: { [number]: string } = { [116] = "\t", } --- utf8 bytes of a code point (surrogates too: WTF-8) local utf8char = Text.utf8char Decode.utf8char = utf8char @@ -90586,7 +87971,6 @@ Decode.utf8char = utf8char return tonumber(h, 16) end --- string(s, i) -> value, next | nil, message, offset. i is at the opening quote. @native local function str(s: string, i: number): (string?, any, number?) local j = find(s, '[%z\1-\31"\\]', i + 1) if not j then @@ -90645,7 +88029,6 @@ end end Decode.string = str --- number(s, i) -> value, next | nil, message, offset @native local function num(s: string, i: number, bigStrings: boolean): (any, any, number?) local p = i if byte(s, p) == 45 then @@ -90696,8 +88079,6 @@ Decode.string = str end Decode.number = num --- decode(s, i, opts) -> value, next | nil, message, offset. Parses one value starting at i (leading whitespace --- skipped); next is the position after the value (trailing whitespace not skipped). @native function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) local o: Options = opts or {} local ordered = o.ordered == true @@ -90706,9 +88087,9 @@ Decode.number = num local maxDepth = o.maxDepth or 1000 local object = Types.object - local stackT: { any } = {} -- containers - local stackK: { any } = {} -- object: the pending key; array: the count - local stackO: { any } = {} -- object: its key order (or true); array: false + local stackT: { any } = {} + local stackK: { any } = {} + local stackO: { any } = {} local depth = 0 local n = #s local value: any @@ -90789,7 +88170,6 @@ Decode.number = num end value, i = v, ni end - -- attach the value to the open containers, closing them as their ends come while haveValue do if depth == 0 then return value, i @@ -90846,17 +88226,13 @@ Decode.number = num end end --- events: a pull tokenizer. next() -> event, value | nil at the end | "error", message, offset. Events: "object", --- "endObject", "array", "endArray", "key" (string), "value" (scalar). The grammar is checked as it goes. @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 } = {} -- true = object + local stack: { boolean } = {} local depth = 0 - -- state: "value" (a value expected), "first" (after { or [: value / key or close), "after" (after a value), - -- "key" (a key expected), "done", "dead" local state = "value" local n = #s @native local function fail(msg: string, at: number): (string, any, number) @@ -90921,7 +88297,6 @@ end state = "value" return "key", k end - -- a value local after = if depth == 0 then "done" else "after" if c == 123 or c == 91 then depth += 1 @@ -90970,10 +88345,7 @@ end __FILES["codecs/text/Json/Encode"] = @native function() --- codecs/text/Json/Encode: the serializer behind codecs/text/Json. Compact or pretty (indent), objects in their Types.object key --- order (plain tables: sorted keys), arrays for tables with keys 1..n, shortest round-trip number text, optional --- ASCII-only output. Never throws: bad values (cycles, NaN / inf, functions, non-string keys that are not numbers) --- return nil, message. +-- codecs/text/Json/Encode: the RFC 8259 serializer behind codecs/text/Json. local Types = __include("Types") local Encode = {} @@ -90983,13 +88355,13 @@ local floor, huge = math.floor, math.huge local concat = table.concat type Options = { - indent: (number | string)?, -- pretty print: spaces per level (or the indent string); default compact - sortKeys: boolean?, -- plain tables' keys sorted (default true; false = next() order, faster) - ascii: boolean?, -- escape every non-ASCII character as \uXXXX (default false: UTF-8 as is) - nan: ("error" | "null")?, -- NaN / inf: an error (default) or null - emptyTable: ("array" | "object")?, -- what a plain empty table is (default "array"; Types.object() is "{}") - maxDepth: number?, -- nesting limit (default 1000; also catches cycles) - escapeSlash: boolean?, -- write / as \/ (default false) + indent: (number | string)?, + sortKeys: boolean?, + ascii: boolean?, + nan: ("error" | "null")?, + emptyTable: ("array" | "object")?, + maxDepth: number?, + escapeSlash: boolean?, } local ESCAPES: { [string]: string } = { @@ -91017,7 +88389,6 @@ end return format("\\u%04x\\u%04x", 0xD800 + cp // 1024, 0xDC00 + cp % 1024) end --- asciify a UTF-8 string's non-ASCII sequences (invalid bytes become \u00XX of the byte: lossy but never throws) @native local function asciiSeq(seq: string): string local out = {} local i, n = 1, #seq @@ -91039,7 +88410,7 @@ end return concat(out) end --- string(s, ascii, slash) -> the quoted JSON string (ascii: DEL too, like Python's ensure_ascii) +-- 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 @@ -91055,7 +88426,6 @@ end Encode.quote = quote local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" } --- number(x) -> the shortest text that reads back as x | nil for NaN / inf @native local function number(x: number): string? if x ~= x or x == huge or x == -huge then return nil @@ -91084,7 +88454,6 @@ Encode.number = number return a < b end --- kind(t, emptyObject) -> "array" (keys exactly 1..n) | "object" @native local function kind(t: { [any]: any }, emptyObject: boolean): string if Types.isObject(t) then return "object" @@ -91265,7 +88634,6 @@ end Encode.state = state Encode.write = value --- encode(v, opts) -> text | nil, message @native function Encode.encode(v: any, opts: Options?, nullv: any?): (string?, string?) local st = state(opts, nullv) if not value(st, v, 0) then @@ -91278,24 +88646,8 @@ return Encode end __FILES["codecs/text/Nbt"] = function() --- codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, --- model/schematic and model/mca use. New code (Minecraft wiki "NBT format", wiki.vg "NBT"). --- Binary: Java big-endian (modified UTF-8 strings), Bedrock little-endian (with or without the 8-byte level.dat --- header) and Bedrock network NBT (varints), every tag type; files may be gzip or zlib compressed (codecs/compress/ --- Deflate). SNBT: parse and print (codecs/text/Nbt/Snbt). Values are plain Luau with typed numbers --- (codecs/text/Nbt/Value): int -> number, string -> string, byteArray -> buffer, compound -> Types.object (key order --- kept), list -> array, the other numeric and array tags -> { type, value } tags, so round trips are exact. --- --- local Nbt = require("@rosetta/codecs/text/Nbt") --- local v, info = Nbt.decode(buf) -- a file: compression and edition detected; info = how it was stored --- print(v.Data.LevelName, v.Data.Time.value) -- int / string plain; long / byte / ... tags have .value --- v.Data.Difficulty = Nbt.byte(2) --- local out = Nbt.encode(v) -- written the way it was read (Nbt.info(v)), or opts --- local text = Nbt.print(v) -- SNBT: {Data:{Difficulty:2b,...}} --- local w = Nbt.parse('{pos:[I;1,2,3],name:"x"}') --- local raw, name, endPos = Nbt.read(buf, 0, nil, { endian = "little" }) -- one uncompressed tag --- --- Never throws: bad data and bad values return nil, Err. +-- 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") @@ -91308,31 +88660,31 @@ local Nbt = {} type Tag = Value.Tag type Info = { - name: string, -- the root tag's name + name: string, endian: "big" | "little", - varint: boolean?, -- Bedrock network NBT + varint: boolean?, compression: "gzip" | "zlib" | "none", - header: number?, -- Bedrock level.dat: the storage version from the 8-byte header + header: number?, } type DecodeOptions = { - endian: ("big" | "little")?, -- default: detected (Java big-endian first) - varint: boolean?, -- Bedrock network NBT - nameless: boolean?, -- no root name (Java network NBT since 1.20.2) - maxDepth: number?, -- nesting limit (default 512) - maxBytes: number?, -- refuse compressed data that inflates past this (default 2^28) -} -type EncodeOptions = { - endian: ("big" | "little")?, -- default: Nbt.info(value).endian, else "big" + endian: ("big" | "little")?, varint: boolean?, nameless: boolean?, - name: string?, -- the root name (default: Nbt.info(value).name, else "") - compression: ("gzip" | "zlib" | "none")?, -- default: Nbt.info(value).compression, else gzip for big-endian - header: number?, -- write the Bedrock level.dat header with this version - level: number?, -- deflate level 0..9 (default 6) + 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 -- name -> id -Nbt.TAG_NAMES = Value.NAMES -- id -> name +Nbt.TAG = Value.IDS +Nbt.TAG_NAMES = Value.NAMES Nbt.byte = Value.byte Nbt.short = Value.short Nbt.int = Value.int @@ -91353,18 +88705,15 @@ Nbt.toHiLo = Value.toHiLo local infos: { [any]: Info } = setmetatable({}, { __mode = "k" }) :: any --- info(value) -> how a decoded root was stored (nil for values not from decode) function Nbt.info(v: any): Info? return if type(v) == "table" then infos[v] else nil end --- setInfo(value, info): what encode uses as defaults function Nbt.setInfo(v: any, info: Info) if type(v) == "table" then infos[v] = info end end --- read(buf, offset?, length?, opts?) -> value, rootName, endOffset | nil, Err: one uncompressed root tag 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 @@ -91377,7 +88726,6 @@ function Nbt.read(buf: buffer | string, offset: number?, length: number?, opts: return v, name, at end --- write(value, opts?) -> buffer | nil, Err: one uncompressed root tag function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) local out, e = Binary.write(v, opts :: any) if not out then @@ -91386,7 +88734,6 @@ function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) return out, nil end --- unwrap(buf, offset?, length?, maxBytes?) -> data, start, end, compression | nil, Err: gzip / zlib detected by magic 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 @@ -91414,14 +88761,14 @@ function Nbt.unwrap(buf: buffer | string, offset: number?, length: number?, maxB end type Peek = { - compression: string, -- "gzip" | "zlib" | "none" + compression: string, endian: "big" | "little", - header: boolean, -- a Bedrock level.dat header - rootType: string, -- "compound" (or "list") - name: string, -- the root name - firstType: string?, -- the first child of a root compound (type and name; "end" when empty), when peeked + header: boolean, + rootType: string, + name: string, + firstType: string?, firstName: string?, - head: buffer, -- the first (up to 1024) uncompressed bytes + head: buffer, } local function plausibleName(b: buffer, p: number, n: number): string? @@ -91435,8 +88782,6 @@ local function plausibleName(b: buffer, p: number, n: number): string? return s end --- peek(buf, offset?, length?) -> Peek | nil: whether the bytes look like an NBT file (inflating at most 1 KiB of a --- gzip / zlib stream), and its root's name and first child: what format sniffs look at. Never fails loudly. function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? local o = offset or 0 local l = length or (buffer.len(buf) - o) @@ -91483,7 +88828,7 @@ function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? return nil end if ft == 0 then - res.firstType = "end" -- an empty root compound + 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 @@ -91503,8 +88848,6 @@ function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? return at(0, "big", false) or at(0, "little", false) end --- decode(buf | string, opts?, offset?, length?) -> value, Info | nil, Err: a whole NBT file (gzip / zlib / raw; Java --- or Bedrock) 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) @@ -91570,7 +88913,6 @@ function Nbt.decode(buf: buffer | string, opts: DecodeOptions?, offset: number?, return v, info end --- encode(value, opts?) -> buffer | nil, Err: a whole NBT file function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local info = Nbt.info(v) @@ -91604,7 +88946,6 @@ function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) return raw, nil end --- parse(text, opts?) -> value | nil, Err: SNBT 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 @@ -91617,7 +88958,6 @@ function Nbt.parse(text: string | buffer, opts: Snbt.ParseOptions?): (any, Err.E return v, nil end --- print(value, opts?) -> text | nil, Err: SNBT (compact, or opts.indent) function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?) local s, e = Snbt.print(v, opts) if not s then @@ -91626,7 +88966,6 @@ function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?) return s, nil end --- get(value, path) -> the value at a dotted path ("Data.Player.Pos[1]"; list indices 0-based like Minecraft's) function Nbt.get(v: any, path: string): any local cur = v for part in string.gmatch(path, "[^%.]+") do @@ -91661,10 +89000,8 @@ 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". --- New code. Three encodings: big-endian (Java Edition files; strings in Java's modified UTF-8, converted to and from --- UTF-8), little-endian (Bedrock files; UTF-8) and Bedrock's network form (little-endian with zigzag varints for int / --- long and varint lengths). All thirteen tag types; values per codecs/text/Nbt/Value. Lengths are checked against --- the bytes left before anything is allocated, and nesting is limited (opts.maxDepth, default 512 like Minecraft). +-- 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") @@ -91672,11 +89009,11 @@ local Value = __include("codecs/text/Nbt/Value") local Binary = {} type Options = { - endian: ("big" | "little")?, -- default "big" (Java) - varint: boolean?, -- Bedrock network NBT (little-endian, varint ints / lengths); implies endian = "little" - nameless: boolean?, -- the root tag has no name (Java network NBT since 1.20.2) - maxDepth: number?, -- nesting limit (default 512) - name: string?, -- write: the root name (default "") + endian: ("big" | "little")?, + varint: boolean?, + nameless: boolean?, + maxDepth: number?, + name: string?, } local readu8, readi8, readu32, readi16 = buffer.readu8, buffer.readi8, buffer.readu32, buffer.readi16 @@ -91688,7 +89025,6 @@ 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 } --- ------------------------------------------------------------------------------------------------ modified UTF-8 -- 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 @@ -91750,7 +89086,6 @@ end Binary.fromModified = fromModified Binary.toModified = toModified --- ------------------------------------------------------------------------------------------------ read local function fail(s: State, msg: string): nil if not s.err then s.err = msg @@ -91831,7 +89166,7 @@ local function len(s: State): number return i32(s) end -local function i64(s: State): (number, number) -- hi, lo +local function i64(s: State): (number, number) if s.net then local lo, hi, sh = 0, 0, 0 while true do @@ -91909,7 +89244,6 @@ local function tag(name: string, v: any): any return setmetatable({ type = name, value = v }, newTag) end --- the smallest encoded size of one element, to bound list lengths before allocating 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 } @@ -92054,7 +89388,6 @@ payload = function(s: State, id: number): any return fail(s, "bad tag type " .. id) end --- read(buf, pos, limit, opts?) -> value, rootName, endPos | nil, message, at function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (any, any, number?) local o: Options = opts or {} local net = o.varint == true @@ -92086,7 +89419,6 @@ function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (an return v, name, s.p end --- ------------------------------------------------------------------------------------------------ write type WState = { w: Bytes.Writer, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number } local function wvaruint(w: Bytes.Writer, v: number) @@ -92099,7 +89431,7 @@ local function wvaruint(w: Bytes.Writer, v: number) end local function wi32(ws: WState, v: number) - v %= TWO32 -- two's complement + 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) @@ -92332,7 +89664,6 @@ wpayload = function(ws: WState, t: string, v: any): string? return nil end --- write(value, opts?) -> buffer | nil, message function Binary.write(v: any, opts: Options?): (buffer?, string?) local o: Options = opts or {} local net = o.varint == true @@ -92360,13 +89691,8 @@ return Binary end __FILES["codecs/text/Nbt/Snbt"] = function() --- codecs/text/Nbt/Snbt: stringified NBT (the text form of /data and /give), parse and print. New code, from the --- Minecraft wiki "NBT format" SNBT section (Java 1.21.5 grammar). Parses: compounds, lists, [B; ...] [I; ...] [L; ...] --- arrays, quoted strings ('...' / "..." with \\ \' \" \n \t \r \b \f \s \xNN \uNNNN \UNNNNNNNN escapes) and unquoted --- strings, numbers with b / s / i / l / f / d suffixes (any case, signed / unsigned s / u prefix), underscores, hex --- 0x and binary 0b integers, exponents, true / false (bytes 1 / 0), NaN / Infinity with a float suffix, trailing --- commas. Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. Prints Minecraft's --- compact form (or indented); floats print as the shortest text that reads back to the same value. +-- 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") @@ -92374,8 +89700,8 @@ local Snbt = {} type ParseOptions = { maxDepth: number? } type PrintOptions = { - indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) - quote: string?, -- the string quote, '"' (default) or "'"; the other one is used when it needs fewer escapes + indent: (number | string)?, + quote: string?, } local byte, sub, find = string.byte, string.sub, string.find @@ -92385,7 +89711,6 @@ local function tag(name: string, v: any): any return setmetatable({ type = name, value = v }, Value.TagMeta) end --- ------------------------------------------------------------------------------------------------ parse type P = { s: string, i: number, n: number, err: string?, at: number, depth: number, maxDepth: number } local function fail(p: P, msg: string): nil @@ -92446,7 +89771,6 @@ local function quoted(p: P): string? end end --- number text -> a value, or nil when it is not a number (then it is an unquoted string) local INT_RANGE: { [string]: { number } } = { b = { -128, 127, 255 }, s = { -32768, 32767, 65535 }, @@ -92496,7 +89820,6 @@ local function integer(t: string): any if unsigned and sign == "-" then return nil end - -- the magnitude as (hi, lo) local hi, lo = 0, 0 for k = 1, #digits do local c = byte(digits, k) @@ -92798,7 +90121,6 @@ parseValue = function(p: P): any return v end --- parse(text, opts?) -> value | nil, message, position (1-based) 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) @@ -92812,7 +90134,6 @@ function Snbt.parse(s: string, opts: ParseOptions?): (any, string?, number?) return v, nil, nil end --- ------------------------------------------------------------------------------------------------ print local function shortest(v: number, single: boolean): string if v ~= v then return "NaN" @@ -92986,7 +90307,6 @@ printValue = function(pr: Pr, v: any, depth: number): string? return nil end --- print(value, opts?) -> text | nil, message function Snbt.print(v: any, opts: PrintOptions?): (string?, string?) local o: PrintOptions = opts or {} local ind = o.indent @@ -93012,14 +90332,8 @@ end __FILES["codecs/text/Nbt/Value"] = function() -- codecs/text/Nbt/Value: the NBT value model shared by the binary and SNBT codecs. New code. --- Plain Luau values with typed numbers, so a decode / encode round trip is exact: --- int -> number string -> string byteArray -> buffer --- compound -> Types.object (key order kept) list -> array (element type in Value.listType) --- byte / short / long / float / double / intArray / longArray -> a tag { type = "", value = ... } with a --- metatable (tostring gives SNBT): long values are numbers when exact (|v| <= 2^53), else their exact decimal --- text; intArray value = { numbers }; longArray value = a buffer of little-endian two's complement int64s. --- Inputs are lenient: a plain number writes as int when integral and in int range, else double; true / false as --- byte 1 / 0; a plain table with string keys as a compound. +-- 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 = {} @@ -93049,7 +90363,6 @@ type Tag = { type: string, value: any } local TagMeta: { [string]: any } = {} Value.TagMeta = TagMeta --- the SNBT printer, filled in by codecs/text/Nbt (Value is below the printer) Value.print = function(v: any): string return tostring(v.value) end @@ -93079,11 +90392,8 @@ end local listTypes: { [any]: string } = setmetatable({}, { __mode = "k" }) :: any --- ------------------------------------------------------------------------------------------------ 64-bit integers local TWO32 = 4294967296 --- fromHiLo(hi, lo) -> a long value: a number when exact, else the exact decimal text (hi, lo: u32 halves of the --- two's complement int64) 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 @@ -93106,7 +90416,6 @@ function Value.fromHiLo(hi: number, lo: number): number | string return (if neg then "-" else "") .. table.concat(parts) end --- toHiLo(v) -> hi, lo (u32 halves) | nil: v a whole number in int64 range or its decimal text function Value.toHiLo(v: any): (number?, number?) if type(v) == "number" then if v % 1 ~= 0 or v < -9223372036854775808 or v >= 9223372036854775808 then @@ -93139,7 +90448,6 @@ function Value.toHiLo(v: any): (number?, number?) return nil, nil end --- ------------------------------------------------------------------------------------------------ constructors local function tag(name: string, v: any): Tag return setmetatable({ type = name, value = v }, TagMeta) :: any end @@ -93152,7 +90460,6 @@ end function Value.int(n: number): number return n end --- long(n | "decimal") -> a long tag (decimal text within 2^53 becomes a number) function Value.long(v: number | string): Tag if type(v) == "string" then local hi, lo = Value.toHiLo(v) @@ -93163,7 +90470,6 @@ function Value.long(v: number | string): Tag return tag("long", v) end local f32 = buffer.create(4) --- float(n) -> a float tag holding n rounded to single precision function Value.float(n: number): Tag buffer.writef32(f32, 0, n) return tag("float", buffer.readf32(f32, 0)) @@ -93174,7 +90480,6 @@ end function Value.intArray(t: { number }?): Tag return tag("intArray", t or {}) end --- longArray(values | buffer) -> a longArray tag (values: numbers / decimal texts; a buffer: 8 bytes each, LE) function Value.longArray(t: { any } | buffer | nil): Tag if type(t) == "buffer" then return tag("longArray", t) @@ -93188,7 +90493,6 @@ function Value.longArray(t: { any } | buffer | nil): Tag end return tag("longArray", b) end --- longs(longArray) -> { number | string }: the elements as long values function Value.longs(a: Tag): { number | string } local b: buffer = a.value local out = table.create(buffer.len(b) // 8) :: { number | string } @@ -93197,7 +90501,6 @@ function Value.longs(a: Tag): { number | string } end return out end --- list(typeName, items?) -> items marked as a list of that element type (an empty list keeps its type) function Value.list(name: string, items: { any }?): { any } local t = items or {} listTypes[t] = name @@ -93206,7 +90509,6 @@ end function Value.compound(t: { [string]: any }?, keys: { string }?): { [string]: any } return Types.object(t, keys) end --- listType(t) -> the element type name recorded for a list (decoded, or made by Value.list) function Value.listType(t: any): string? return listTypes[t] end @@ -93217,7 +90519,6 @@ function Value.isTag(v: any): boolean return type(v) == "table" and getmetatable(v) == TagMeta end --- typeOf(v) -> the tag name v writes as, or nil + why function Value.typeOf(v: any): (string?, string?) local tv = type(v) if tv == "number" then @@ -93248,7 +90549,6 @@ function Value.typeOf(v: any): (string?, string?) return nil, "cannot write a " .. tv .. " as NBT" end --- number(v) -> the numeric value of a number or numeric tag (long texts through tonumber: approximate) function Value.number(v: any): number? if type(v) == "number" then return v @@ -93270,12 +90570,10 @@ end __FILES["codecs/text/Text"] = function() --- codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is --- read as Windows-1252 (classic .m3u / .pls / .ini / .srt files), lines split on CRLF / CR / LF, trim. Absorbed from --- playlist-luau 3fc7fd3 (same author, no third-party code). Never throws. +-- 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 = {} --- utf8char(codepoint) -> its UTF-8 bytes (no validation: the parsers check ranges first; utf8.char would throw) function Text.utf8char(c: number): string local char = string.char if c < 0x80 then @@ -93301,8 +90599,6 @@ function Text.trim(s: string): string return (string.match(s, "^%s*(.-)%s*$") :: string) end --- utf16(buf, offset, length, bigEndian?) -> UTF-8 text of UTF-16 code units (surrogate pairs joined, lone surrogates --- become U+FFFD; an odd last byte is ignored). Font names, 7z / PSD / Windows strings, XML in UTF-16. function Text.utf16(b: buffer, o: number, n: number, bigEndian: boolean?): string local out = {} local k = 0 @@ -93329,7 +90625,6 @@ function Text.utf16(b: buffer, o: number, n: number, bigEndian: boolean?): strin return table.concat(out) end --- toUtf8(text, warnings?) -> text as UTF-8: strips a BOM; text that is not valid UTF-8 is read as Windows-1252 function Text.toUtf8(text: string, warnings: { string }?): string if string.sub(text, 1, 3) == "\239\187\191" then text = string.sub(text, 4) @@ -93366,11 +90661,8 @@ end __FILES["codecs/text/Url"] = function() --- codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, --- Windows / UNC / POSIX local path, relative reference) and percent-encoding of bytes that may not appear in a URI --- (raw spaces and UTF-8 in playlists). Shared by the playlist formats (m3u / HLS, pls, xspf); later DASH / glTF URIs. --- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code): Url.luau, plus locate / base from its --- init.luau. Never throws. +-- 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 } @@ -93383,7 +90675,7 @@ type Parts = { fragment: string?, } --- Splits a URI reference into its five components (RFC 3986 appendix B). +-- 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 @@ -93414,7 +90706,7 @@ function Url.split(ref: string): Parts return { scheme = scheme, authority = authority, path = s, query = query, fragment = fragment } end --- Recomposes components (RFC 3986 section 5.3). +-- RFC 3986 section 5.3 function Url.join(p: Parts): string local out = {} if p.scheme then @@ -93465,7 +90757,7 @@ function Url.removeDotSegments(path: string): string return table.concat(output) end --- Resolves a reference against an absolute base URI (RFC 3986 section 5.2.2, strict). +-- 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 = "" } @@ -93502,15 +90794,13 @@ function Url.resolve(ref: string, base: string): string return Url.join(t) end --- Percent-encodes the bytes that may not appear in a URI (controls, space, non-ASCII, "<>\"^`{|}" and "\\"), --- leaving existing %XX escapes and the reserved delimiters alone. +-- 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 --- Is a location a local Windows path ("C:\x", "C:/x", "\\server\share", "\x")? function Url.isWindowsPath(s: string): boolean return string.match(s, "^%a:[\\/]") ~= nil or string.match(s, "^%a:$") ~= nil @@ -93518,7 +90808,6 @@ function Url.isWindowsPath(s: string): boolean or string.sub(s, 1, 1) == "\\" end --- The scheme of an absolute URI (lower case), or nil. Windows drive letters are not schemes. function Url.scheme(s: string): string? if Url.isWindowsPath(s) then return nil @@ -93527,9 +90816,6 @@ function Url.scheme(s: string): string? return if scheme then string.lower(scheme) else nil end --- locate(raw, base?, baseScheme?) -> { url, playable, reason? }: an entry location resolved against the playlist's --- base (from Url.base). Windows paths stay as they are and are local; relative paths without a base, file: URLs and --- schemes other than http(s) are not playable (reason says why). function Url.locate(raw: string, base: string?, baseScheme: string?): Location local loc = (string.match(raw, "^%s*(.-)%s*$") :: string) if Url.isWindowsPath(loc) then @@ -93538,7 +90824,6 @@ function Url.locate(raw: string, base: string?, baseScheme: string?): Location local scheme = Url.scheme(loc) local url = loc if not scheme and baseScheme == "windows" and base then - -- a playlist on a Windows disk: relative entries are paths next to it local dir = string.match(base, "^(.*[\\/])") or "" return { url = dir .. loc, playable = false, reason = "local path" } end @@ -93547,7 +90832,6 @@ function Url.locate(raw: string, base: string?, baseScheme: string?): Location url = Url.encodeUnsafe(Url.resolve(loc, loc)) end elseif base and baseScheme then - -- a relative reference: Windows separators become URL ones url = Url.resolve(Url.encodeUnsafe((string.gsub(loc, "\\", "/"))), base) scheme = baseScheme else @@ -93561,8 +90845,6 @@ function Url.locate(raw: string, base: string?, baseScheme: string?): Location return { url = url, playable = false, reason = "scheme " .. tostring(scheme) } end --- base(baseUrl?, warnings?) -> base, baseScheme: the base for Url.locate from the playlist's own URL or path ("windows" --- for a Windows path); a non-absolute base is ignored (with a warning) function Url.base(baseUrl: string?, warnings: { string }?): (string?, string?) if type(baseUrl) ~= "string" or baseUrl == "" then return nil, nil @@ -93583,23 +90865,8 @@ return Url end __FILES["codecs/text/Xml"] = function() --- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... --- use. New code. Supports: UTF-8 / UTF-16 / Latin-1 input, the predefined entities, character references, internal --- DOCTYPE entities (expansion limited), CDATA, comments, processing instructions, the XML declaration, namespaces --- (names stay qualified "prefix:local"; opts.namespaces adds each element's URI as node.ns; Xml.clark gives --- "{uri}local"), xml:space. Not supported: external entities / DTDs, validation, entity values containing markup. --- --- local Xml = require("@rosetta/codecs/text/Xml") --- local doc, err = Xml.decode(text) -- a "#document" node; doc.root is the root element --- for _, item in Xml.children(doc.root, "item") do print(item.attrs.id, Xml.text(item)) end --- for ev, a, b in Xml.events(text) do ... end -- "start" name attrs / "end" name / "text" s / ... (SAX-like) --- local s = Xml.encode(doc, { indent = 2 }) --- local e = Xml.element("svg", { width = "10" }, { Xml.element("rect") }) -- build trees --- --- Nodes (Types.XmlNode): { name, attrs (a Types.object: attribute order kept), children = { node | string }, --- parent }. Text children are strings. With opts.comments / opts.cdata / opts.pi, comments, CDATA sections and --- processing instructions are kept as "#comment" / "#cdata" / "#pi" nodes (text = the content, target = the PI --- target); otherwise CDATA merges into the text and the others are dropped. Never throws. +-- 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") @@ -93608,15 +90875,15 @@ local Xml = {} type Node = Types.XmlNode type DecodeOptions = Parse.Options & { - comments: boolean?, -- keep comments as "#comment" nodes (default false) - cdata: boolean?, -- keep CDATA sections as "#cdata" nodes (default false: merged into the text) - pi: boolean?, -- keep processing instructions as "#pi" nodes (default false) - parents: boolean?, -- set node.parent (default true) + comments: boolean?, + cdata: boolean?, + pi: boolean?, + parents: boolean?, } type EncodeOptions = { - indent: (number | string)?, -- pretty print elements that hold only elements (default none) - declaration: boolean?, -- write (default: true for a "#document") - selfClose: boolean?, -- for empty elements (default true) + indent: (number | string)?, + declaration: boolean?, + selfClose: boolean?, } local find, gsub, sub, match = string.find, string.gsub, string.sub, string.match @@ -93641,8 +90908,6 @@ local function errCode(msg: string, at: number, n: number): string return Err.CORRUPT end --- events(src, opts?) -> iterator: event, a, b, c (see codecs/text/Xml/Parse: "decl", "doctype", "start" name attrs ns, --- "end" name, "text" s, "cdata" s, "comment" s, "pi" target data, and on bad input "error" Err as the last event) function Xml.events(src: string | buffer, opts: Parse.Options?): () -> (string?, any, any, any) local s, terr = text(src) local u, enc = nil, "" @@ -93671,9 +90936,6 @@ function Xml.events(src: string | buffer, opts: Parse.Options?): () -> (string?, end end --- decode(src, opts?) -> the "#document" node | nil, Err. doc.root = the root element; doc.declaration = { version, --- encoding, standalone }?; doc.doctype = { raw, name, publicId, systemId, entities }?; doc.children = the root plus --- any kept comments / PIs around it. 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 @@ -93728,9 +90990,6 @@ function Xml.decode(src: string | buffer, opts: DecodeOptions?): (Node?, Err.Err return doc, nil end --- ------------------------------------------------------------------------------------------------ tree helpers --- element(name, attrs?, children?) -> a new element (attrs: a plain table (written sorted) or a Types.object; --- children: nodes or strings; their parent is set) function Xml.element(name: string, attrs: { [string]: string }?, children: { any }?): Node local a = attrs or Types.object() if not Types.isObject(a) then @@ -93750,14 +91009,12 @@ function Xml.element(name: string, attrs: { [string]: string }?, children: { any return node end --- document(root, declaration?) -> a "#document" node around root 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 --- append(parent, child) -> child (a node or a string), parent link set function Xml.append(parent: Node, child: any): any table.insert(parent.children, child) if type(child) == "table" then @@ -93766,13 +91023,10 @@ function Xml.append(parent: Node, child: any): any return child end --- setAttr(node, name, value): set (or with nil remove) an attribute, keeping the order function Xml.setAttr(node: Node, name: string, value: string?) Types.set(node.attrs, name, value) end --- children(node, name?) -> the element children (with that qualified name, or local name when name has no prefix and --- the child's does), in order function Xml.children(node: Node, name: string?): { Node } local out = {} for _, ch in node.children do @@ -93785,7 +91039,6 @@ function Xml.children(node: Node, name: string?): { Node } return out end --- child(node, name?) -> the first matching element child, or nil 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 @@ -93797,7 +91050,6 @@ function Xml.child(node: Node, name: string?): Node? return nil end --- descendants(node, name?) -> every element below node (document order), optionally filtered as children() does function Xml.descendants(node: Node, name: string?): { Node } local out = {} local function walk(n: Node) @@ -93814,7 +91066,6 @@ function Xml.descendants(node: Node, name: string?): { Node } return out end --- text(node) -> all the character data below node, concatenated (CDATA included, comments / PIs not) function Xml.text(node: any): string if type(node) == "string" then return node @@ -93838,7 +91089,6 @@ function Xml.text(node: any): string return table.concat(parts) end --- prefix(name) / localName(name): the parts of a qualified name ("svg:rect" -> "svg", "rect"; "rect" -> "", "rect") function Xml.prefix(name: string): string return match(name, "^([^:]*):") or "" end @@ -93846,14 +91096,10 @@ function Xml.localName(name: string): string return match(name, ":(.*)$") or name end --- namespace(node, prefix?) -> the URI bound to prefix (default: the node's own prefix) at node, through its --- ancestors' xmlns attributes (needs parent links) function Xml.namespace(node: Node, prefix: string?): string? return Parse.resolve(node, prefix or Xml.prefix(node.name)) end --- clark(node, attrName?) -> "{uri}local" (ElementTree's notation) for the element, or for one of its attributes --- (unprefixed attributes have no namespace) function Xml.clark(node: Node, attrName: string?): string local name = attrName or node.name local prefix = Xml.prefix(name) @@ -93867,11 +91113,9 @@ function Xml.clark(node: Node, attrName: string?): string return name end --- ------------------------------------------------------------------------------------------------ encode local TEXT_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ["\r"] = " " } local ATTR_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """, ["\t"] = " ", ["\n"] = " ", ["\r"] = " " } --- escape(s) / escapeAttr(s): text / attribute-value escaping function Xml.escape(s: string): string return (gsub(s, "[&<>\r]", TEXT_ESC)) end @@ -93883,7 +91127,6 @@ local function badName(name: any): boolean return type(name) ~= "string" or not match(name, "^[%a_:\128-\255][%w_:%.%-\128-\255]*$") end --- encode(node, opts?) -> string | nil, Err. node: a "#document" or any node (an element, a comment, ...) function Xml.encode(node: Node, opts: EncodeOptions?): (string?, Err.Err?) local o: EncodeOptions = opts or {} local ind: string? = nil @@ -94026,13 +91269,8 @@ end __FILES["codecs/text/Xml/Parse"] = @native function() --- codecs/text/Xml/Parse: the XML 1.0 pull parser behind codecs/text/Xml. Input decoding (UTF-8, UTF-16 LE / BE by BOM or --- by the first bytes, ISO-8859-1 / US-ASCII / Windows-1252 by the declaration), line-ending normalization, the --- well-formedness rules that matter (one root, matched tags, unique attributes, quoted values, no '<' in values, --- legal names, character references in range, no "--" in comments, no "]]>" in text), the five predefined entities, --- character references and internal general entities from the DOCTYPE (with an expansion limit). Not supported: --- external entities / DTDs (references to them are errors), entity values containing markup (taken as text), --- validation. Never throws: errors are events. +-- 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") @@ -94041,11 +91279,11 @@ 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?, -- keep whitespace-only text (default false: dropped, except inside xml:space="preserve") - namespaces: boolean?, -- resolve namespace prefixes: "start" events carry the element's URI (default false) - entities: { [string]: string }?, -- extra general entities (name -> replacement text) - maxExpansion: number?, -- total characters produced by entity expansion (default 1e7; the billion laughs guard) - maxDepth: number?, -- element nesting limit (default 10000) + whitespace: boolean?, + namespaces: boolean?, + entities: { [string]: string }?, + maxExpansion: number?, + maxDepth: number?, } local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*" @@ -94094,7 +91332,6 @@ local CP1252: { [number]: number } = { return table.concat(out), nil end --- toUtf8(s) -> UTF-8 text (BOM removed), the encoding name | nil, message @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 @@ -94147,7 +91384,7 @@ end 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 -- no whitespace before + return nil end if (key == "version" and not match(v, "^1%.%d+$")) or (key == "encoding" and not match(v, "^%a[%w%._%-]*$")) @@ -94167,17 +91404,6 @@ end return out end --- the events iterator: next() -> event, a, b, c --- "decl", { version, encoding, standalone } the declaration --- "doctype", raw, info raw = the text between ""; info = { name, --- publicId, systemId, entities } --- "start", name, attrs (Types.object), ns ns: the element's namespace URI (opts.namespaces) or nil --- "end", name --- "text", s character data, entities decoded (whitespace-only dropped --- unless opts.whitespace) --- "cdata", s "comment", s "pi", target, data --- "error", message, offset then the iterator ends --- nil at the end of the document. @native function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) local o: Options = opts or {} local keepWs = o.whitespace == true @@ -94204,7 +91430,7 @@ end local rootSeen = false local rootDone = false local dead = false - local pending: { any }? = nil -- an "end" queued after a self-closing start + local pending: { any }? = nil local errMsg: string? = nil local errAt = 0 @@ -94213,7 +91439,6 @@ end return "error", msg, at - 1 end - -- decode entity / character references in raw text; nil on error (errMsg set) 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 @@ -94291,7 +91516,6 @@ end return nil end - -- a quoted literal at p -> its content, the position after it | nil @native local function literal(p: number): (string?, number) local q = byte(s, p) if q ~= 34 and q ~= 39 then @@ -94303,7 +91527,7 @@ end end return sub(s, p + 1, e - 1), e + 1 end - -- an ExternalID (SYSTEM "sys" | PUBLIC "pub" "sys") at p -> publicId, systemId, next | nil + -- 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 @@ -94337,7 +91561,6 @@ end end return nil, nil, nil end - -- check an entity value's references and expand its character references (the rest expand when used) @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 @@ -94371,8 +91594,6 @@ end end return table.concat(parts) end - -- the DOCTYPE at i (just past "' outside quotes while true do local c2 = byte(s, r) if c2 == nil then @@ -94657,7 +91877,6 @@ end end return "pi", target, data end - -- a start tag local name = match(s, NAME, i + 1) if not name then return fail(if i + 1 > n then "truncated tag" else "bad tag name", i + 1) @@ -94718,7 +91937,7 @@ end return fail(errMsg :: string, errAt) end if find(raw, "[\t\n]") then - -- attribute-value normalization: literal tab / newline become spaces (references stay) + -- XML 1.0 3.3.3 attribute-value normalization: literal tab / newline become spaces (references stay) v = decode((gsub(raw, "[\t\n]", " ")), r + 1, 0) :: string end if attrs[an] ~= nil then @@ -94761,14 +91980,13 @@ end stack[depth] = nil nsStack[depth] = nil preserve[depth] = nil - pending = { name } -- depth goes down when the queued "end" is returned + pending = { name } end return "start", name, attrs, uri end end end --- lookup(nsMaps...) helper for the DOM: the namespace URI of prefix, walking an element's ancestors @native function Parse.resolve(node: any, prefix: string): string? local p = node local key = if prefix == "" then "xmlns" else "xmlns:" .. prefix @@ -94793,23 +92011,9 @@ __FILES["codecs/video/Dsp"] = @native function() -- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. --- Block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the IDCT put or added --- into 8-bit planes, constant (DC-only) blocks, half-pel motion compensation four samples at a time. Native, never --- throws (the caller keeps offsets in range). --- --- The IDCT is the Independent JPEG Group's jrevdct.c (the LL&M integer IDCT, CONST_BITS 13, PASS1_BITS 2) as ffmpeg --- ships it (libavcodec/jrevdct.c, IJG licence: licenses/libjpeg-README.ijg), translated mechanically: rows first, then --- columns, with every sparse-input special case of the original kept, because several of them use merged constants --- (FIX_1_306562965 for FIX_0_541196100 - FIX_1_847759065, ...) that round differently from the general case; that --- is what makes ffmpeg's `-idct int` output reproducible here. Changes: Luau, i32 coefficients in natural order --- (ffmpeg's LIBMPEG2 permutation is only a storage order), no int16 wrap of the intermediate values (identical for --- coefficients in the MPEG range), and the put / add clamping fused into the last pass. --- --- Dsp.idct(blk, dst, off, stride, add) -- blk: 64 i32 (256 bytes, row-major), left holding garbage: clear it --- Dsp.fill(dst, off, stride, v, add) -- an 8x8 block of constant v (a DC-only block: v = (dc + 4) >> 3) --- Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) -- half-pel prediction of a w x h block --- Dsp.mcNoRound(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy) -- the same, averages rounded down (H.263+) --- Dsp.edge(src, stride, base, x, y, w, h, pw, ph, out) -- a block with edge samples repeated (EDGE_STRIDE) +-- The IDCT is IJG's jrevdct.c (LL&M, CONST_BITS 13, PASS1_BITS 2) as ffmpeg ships it (libavcodec/jrevdct.c, IJG +-- licence: licenses/libjpeg-README.ijg), translated mechanically: its sparse-input special cases stay because their +-- merged constants round differently. Natural-order i32 coefficients, no int16 wrap, put / add clamping in pass 2. local Dsp = {} local readu8 = buffer.readu8 @@ -94833,7 +92037,6 @@ end Dsp.CLAMP = CLAMP Dsp.COFF = COFF --- ------------------------------------------------------------------------------------------------ IDCT @native function Dsp.idct(blk: buffer, dst: buffer, off: number, stride: number, add: boolean) local tmp0, tmp1, tmp2, tmp3 = 0, 0, 0, 0 local tmp10, tmp11, tmp12, tmp13 = 0, 0, 0, 0 @@ -95425,9 +92628,7 @@ Dsp.COFF = COFF end end --- ------------------------------------------------------------------------------------------------ blocks --- an 8x8 block of the constant v put into dst (add = false) or added to it, clamped (a DC-only block: the IDCT --- of a lone DC coefficient dc is (dc + 4) >> 3 everywhere) +-- the IDCT of a lone DC coefficient dc is (dc + 4) >> 3 everywhere @native function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: boolean) if not add then local c = readu8(CLAMP, v + COFF) * 0x01010101 @@ -95446,12 +92647,9 @@ end end end --- ------------------------------------------------------------------------------------------------ motion --- Motion-compensated prediction of a w x h block (w a multiple of 4) from src (rows sStride apart, from sOff) to dst --- (dStride, dOff): half-pel flags hx / hy, rounding up (MPEG-1 / 2, H.263 rounding_type 0); avg averages into what --- dst holds (the second prediction of a bidirectional block, rounding up). Strides are twice the plane width for --- field prediction. Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits --- each byte into its low 2 bits and high 6 bits so no lane overflows. +-- rounding up (MPEG-1 / 2, H.263 rounding_type 0); strides are twice the plane width for field prediction. +-- Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits each byte into its +-- low 2 bits and high 6 bits so no lane overflows. @native function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number, avg: boolean) for _ = 1, h do for i = 0, w - 4, 4 do @@ -95484,8 +92682,7 @@ end end end --- Dsp.mc with the half-sample averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1: --- RTYPE of an H.263+ picture header, MPEG-4 rounding_control). No averaging into dst. +-- averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1, MPEG-4 rounding_control) @native function Dsp.mcNoRound(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number) if hx == 0 and hy == 0 then Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, 0, 0, false) @@ -95512,9 +92709,8 @@ end end end --- Edge emulation: the (w + 1) x (h + 1) samples at (x, y) of a pw x ph plane (row r at base + r * stride) copied to --- out (rows EDGE_STRIDE apart), coordinates clamped into the plane, so a vector pointing outside the picture --- predicts from repeated edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33; out holds EDGE_SIZE bytes). +-- edge emulation: coordinates clamped into the plane, so a vector pointing outside the picture predicts from repeated +-- edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33) Dsp.EDGE_STRIDE = 32 Dsp.EDGE_SIZE = 32 * 34 + 4 @native function Dsp.edge(src: buffer, stride: number, base: number, x: number, y: number, w: number, h: number, pw: number, ph: number, out: buffer) @@ -95536,21 +92732,8 @@ end __FILES["codecs/video/H263"] = function() -- codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int. --- ITU-T H.263 baseline and the H.263+ picture header. Written from ITU-T H.263 (01/2005) and Adobe's Video File Format Specification v10; the decoding core is --- H263/Decoder.luau (native), the IDCT and motion compensation codecs/video/Dsp, so the output planes equal --- `ffmpeg -idct int` (tests/codecs/h263.luau). Supports sub-QCIF .. 16CIF and H.263+ custom sizes, I and P pictures, --- GOB headers, the rounding type, unrestricted motion vectors (Annex D), Sorenson's escape codes and disposable inter --- pictures. Not supported (UNSUPPORTED): arithmetic coding, advanced prediction / four vectors, PB / B / EI / EP --- pictures and the other H.263+ coding options (advanced intra coding, deblocking filter, slices, ...). --- --- local dec = H263.new({ flv = false }) -- flv = true: Sorenson Spark (FLV1) --- local frame, err = dec:decode(packetData, off?, len?) -- one picture -> Frame (planes decoder-owned) --- local img = H263.frameImage(frame) -- a fresh yuv420p Types.Image (limited range, BT.601) --- local img, err = dec:image(packetData) -- both at once --- local info = H263.header(data, off?, len?, flv?) -- the picture header: width, height, ptype, ... --- dec:reset() -- after a seek: wait for the next I picture --- --- Nothing here throws: bad arguments and bad data come back as nil, Err. +-- From ITU-T H.263 (01/2005) and Adobe's Video File Format Specification v10. Annex D UMV, GOB headers and Sorenson +-- escapes are supported; arithmetic coding, advanced prediction, PB / B / EI / EP and other H.263+ options are not. local Err = __include("core/Err") local Types = __include("Types") local D = __include("codecs/video/H263/Decoder") @@ -95565,22 +92748,21 @@ type Header = D.Header type Frame = { width: number, height: number, - -- decoder-owned planes, valid until the next decode: luma stride `stride`, chroma stride stride / 2 y: buffer, cb: buffer, cr: buffer, stride: number, pictureType: number, -- 1 I, 2 P keyframe: boolean, - disposable: boolean, -- a Sorenson disposable inter picture (not used as a reference) + disposable: boolean, temporalReference: number, - index: number, -- pictures returned so far + index: number, flv: boolean, } type Options = { - flv: boolean?, -- Sorenson Spark (FLV1) bitstreams (default false: H.263) - maxPixels: number?, -- larger pictures are refused (LIMIT; default 4096 * 2304) + flv: boolean?, + maxPixels: number?, } local Decoder = {} @@ -95616,8 +92798,6 @@ local function span(data: any, off: number?, len: number?): (buffer?, number, nu return b, o, n end --- Decodes one picture (a container packet or one picture of an elementary stream). A picture with damaged --- macroblock data still comes back (the damaged part copied from the reference; stats.errors counts them). function Decoder.decode(self: Decoder, data: buffer | string, off: number?, len: number?): (Frame?, Err.Err?) local b, o, n = span(data, off, len) if not b then @@ -95647,7 +92827,6 @@ function Decoder.decode(self: Decoder, data: buffer | string, off: number?, len: }, nil end --- decode + frameImage function Decoder.image(self: Decoder, data: buffer | string, off: number?, len: number?): (Types.Image?, Err.Err?) local f, err = self:decode(data, off, len) if not f then @@ -95656,13 +92835,10 @@ function Decoder.image(self: Decoder, data: buffer | string, off: number?, len: return H263.frameImage(f), nil end --- Forgets the reference picture (after a seek: P pictures fail until the next I picture). function Decoder.reset(self: Decoder) self._core.reset() end --- frameImage(frame) -> a fresh yuv420p Types.Image of the frame, cropped to width x height (chroma ceil(w / 2) x --- ceil(h / 2)), meta.yuv = limited range BT.601; nil for a value that is not a Frame function H263.frameImage(frame: Frame): Types.Image? if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then return nil @@ -95695,8 +92871,6 @@ function H263.frameImage(frame: Frame): Types.Image? return img end --- header(data, off?, len?, flv?) -> Header (width, height, ptype 1 I / 2 P, quant, tr, plus, umv, ...) | nil, Err: --- the first picture header in the data, without decoding (containers use it for the track size) function H263.header(data: buffer | string, off: number?, len: number?, flv: boolean?): (Header?, Err.Err?) local b, o, n = span(data, off, len) if not b then @@ -95715,30 +92889,9 @@ __FILES["codecs/video/H263/Decoder"] = @native function() --- codecs/video/H263/Decoder: the H.263 / Sorenson Spark decoding core (native, never throws). Written from ITU-T --- H.263 (01/2005) and Adobe's Video File Format Specification v10 (the H.263VIDEOPACKET of Sorenson Spark). --- --- H.263: picture headers with PTYPE (sub-QCIF .. 16CIF) and PLUSPTYPE (H.263+: standard and custom picture formats, --- custom pixel aspect ratios and picture clock frequencies, the rounding type RTYPE), I and P pictures, GOB headers --- (with or without stuffing), MCBPC / CBPY / MVD / TCOEF VLCs, DQUANT, the H.263 dequantiser, half-sample motion --- compensation with the H.263 chroma vector rounding, unrestricted motion vectors (Annex D in both header forms, the --- PLUSPTYPE form with its reversible MVD codes and unlimited range), slice structure (Annex K, without rectangular --- slices) and the extended escape of Annex T. Sorenson Spark --- (FLV1): its picture header (sizes, disposable inter pictures, which never become the reference), its 7 / 11-bit --- escape codes (version 1), unrestricted vectors. Not supported (the picture is refused with an "unsupported:" message): --- syntax-based arithmetic coding, advanced prediction (Annex F: four vectors and OBMC), PB / B / EI / EP pictures, --- advanced intra coding, the deblocking filter, rectangular slices, reference picture selection / resampling, reduced --- resolution update, independent segments, the alternative inter VLC, modified quantisation (other than the escape). --- --- The IDCT and motion compensation are codecs/video/Dsp, the dequantiser is the H.263 one (|REC| = QUANT * (2 |LEVEL| --- + 1), minus 1 for an even QUANT, as ffmpeg without the -2048..2047 saturation), and vectors pointing outside the reference read --- repeated edge samples of the macroblock-aligned picture, so valid streams decode exactly as `ffmpeg -idct int` --- (tests/codecs/h263.luau). Corrupt data ends the picture: the rest is copied from the reference (state.errors). --- --- local core = D.new(flv, maxPixels) --- local hdr, msg = D.header(buf, off, len, flv, core.state.opp) -- the picture header (no decoding) --- local store, msg = core.decode(buf, off, len) -- one picture -> the Store decoded into (decoder-owned) --- core.reset() -- forget the reference (after a seek) +-- codecs/video/H263/Decoder: the H.263 / Sorenson Spark decoding core, from ITU-T H.263 (01/2005) and Adobe's Video +-- File Format Specification v10 (H.263VIDEOPACKET). Dequantiser |REC| = QUANT * (2 |LEVEL| + 1), minus 1 for an even +-- QUANT; vectors outside the reference read repeated edge samples of the macroblock-aligned picture, as ffmpeg. local Tb = __include("codecs/video/H263/Tables") local Dsp = __include("codecs/video/Dsp") @@ -95781,7 +92934,7 @@ type Opp = { customPcf: boolean, umv: boolean, ss: boolean, -- slice structured (Annex K) - options: string?, -- the unsupported options set, or nil + options: string?, width: number, height: number, } @@ -95798,15 +92951,15 @@ type Header = { umv: boolean, -- unrestricted vectors, baseline form (long vectors) umvPlus: boolean, -- unrestricted vectors, PLUSPTYPE form rounding: number, -- RTYPE (0: half-sample averages round up) - plus: boolean, -- PLUSPTYPE + plus: boolean, ss: boolean, -- slice structured (Annex K) cpm: boolean, deblock: boolean, -- Sorenson's deblocking hint (not applied, as ffmpeg) aspect: number?, -- PLUSPTYPE pixel aspect ratio code (15: aspectNum / aspectDen) aspectNum: number?, aspectDen: number?, - opp: Opp?, -- the PLUSPTYPE options in force - bitPos: number, -- absolute bit position of the first macroblock + opp: Opp?, + bitPos: number, } type Store = { @@ -95821,13 +92974,11 @@ type Store = { disposable: boolean, } --- ------------------------------------------------------------------------------------------------ header -- the length of a slice's MBA field for a picture of n macroblocks (table K.2) @native function D.mbaBits(n: number): number return if n <= 48 then 6 elseif n <= 99 then 7 elseif n <= 396 then 9 elseif n <= 1584 then 11 elseif n <= 6336 then 13 else 14 end --- n (<= 24) bits at bit position p of buf, zeros past endByte @native local function bitsAt(buf: buffer, endByte: number, p: number, n: number): number local v = 0 for k = p, p + n - 1 do @@ -95838,8 +92989,7 @@ end return v end --- the byte offset of the first picture start code in buf[off, off + len) (H.263: 22 bits 0..01 00000; Sorenson: --- 17 bits 0..01 and version 0 / 1), or -1 +-- picture start code: H.263 22 bits 0..01 00000; Sorenson 17 bits 0..01, then version 0 / 1 @native local function findStart(buf: buffer, off: number, len: number, flv: boolean): number local mask = if flv then 0xF8 else 0xFC for i = off, off + len - 3 do @@ -95850,8 +93000,7 @@ end return -1 end --- header(buf, off, len, flv, opp?) -> Header | nil, message: the picture header of the first picture in --- buf[off, off + len); opp: the PLUSPTYPE options of the previous picture (pictures with UFEP = 0 keep them) +-- pictures with UFEP = 0 keep the previous picture's PLUSPTYPE options (opp) @native function D.header(buf: buffer, off: number, len: number, flv: boolean, opp: Opp?): (Header?, string?) if off < 0 or len < 0 or off + len > buffer.len(buf) then return nil, "bad range" @@ -96054,7 +93203,6 @@ end return h, nil end --- ------------------------------------------------------------------------------------------------ decoder type Core = { decode: (buf: buffer, off: number, len: number) -> (Store?, string?), reset: () -> (), @@ -96079,12 +93227,10 @@ type Core = { opp = nil :: Opp?, maxPixels = maxPixels or 4096 * 2304, } - -- bitstream local data = buffer.create(64 * 1024 + PAD) local endBits = 0 local pos = 0 local err = false - -- picture local W, H = 0, 0 local mbW, mbH = 0, 0 local ls, cs, lh, chh = 0, 0, 0, 0 -- luma / chroma strides, plane heights @@ -96152,8 +93298,7 @@ type Core = { state.width, state.height = w, h end - -- one 8x8 block: intra (INTRADC, then the coded coefficients from position 1) put into dst, or an inter block's - -- coefficients added to the prediction already in dst + -- intra blocks: INTRADC, then the coded coefficients from position 1 @native local function block(intra: boolean, coded: boolean, dst: buffer, off: number, stride: number): boolean local i = 0 local dcOnly = true @@ -96265,7 +93410,6 @@ type Core = { return true end - -- one motion vector component from its prediction (half samples) @native local function motion(pred: number): number if umvPlus then -- reversible codes (Annex D.2): "1" = 0, else 0 x0 (1 x)* 0, the last x the sign @@ -96305,7 +93449,6 @@ type Core = { return (v + 32) % 64 - 32 -- the code pair's value in -16 .. 15.5 end - -- the prediction of macroblock (col, row) from the reference, vector (mx, my) in half samples @native local function predict(col: number, row: number, mx: number, my: number) local hx, hy = mx % 2, my % 2 local sx, sy = col * 16 + (mx - hx) // 2, row * 16 + (my - hy) // 2 @@ -96333,7 +93476,6 @@ type Core = { end end - -- a macroblock copied from the reference (not coded, or concealed); mid-grey without one @native local function copyMb(col: number, row: number) local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8 if ref then @@ -96350,9 +93492,6 @@ type Core = { end end - -- macroblock (col, row) of a picture (P: an inter picture; top: within the first macroblock columns' worth of - -- the picture / a GOB or slice with a header, whose vector predictions do not look up; first: the first - -- macroblock of a slice, whose left neighbour is outside). false on bad data. @native local function macroblock(col: number, row: number, P: boolean, top: boolean, first: boolean): boolean if pos > endBits then return false @@ -96446,7 +93585,6 @@ type Core = { return true end - -- an optional GOB header at a GOB boundary: its GN and GQUANT, or nil @native local function gobHeader(cpm: boolean): (number?, number?) if not startCode() then return nil, nil @@ -96459,7 +93597,6 @@ type Core = { return gn, read(5) end - -- an optional slice header (Annex K, no rectangular slices): its MBA and SQUANT, or nil @native local function sliceHeader(cpm: boolean, mbaBits: number, sepb2: boolean): (number?, number?) if not startCode() then return nil, nil @@ -96583,7 +93720,6 @@ type Core = { if hdr.opp then state.opp = hdr.opp end - -- the data from the header on, with zero padding local need = len + PAD if buffer.len(data) < need then data = buffer.create(need) @@ -96609,22 +93745,17 @@ return D end __FILES["codecs/video/H263/Tables"] = function() --- codecs/video/H263/Tables: the H.263 variable-length codes (ITU-T H.263 (01/2005): table 7 MCBPC for I-pictures, --- table 8 MCBPC for P-pictures, table 12 DQUANT, table 13 CBPY, table 14 MVD, table 16 TCOEF, the zigzag scan of --- figure 14), written from the specification as bit strings and turned into flat lookup tables at load time. --- --- A flat table is indexed by the next K bits of the stream and holds len * 65536 + value (len 0: not a code). --- MCBPC_I / MCBPC_P (K = 9): value = macroblock type * 4 + CBPC (types 0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA, --- 4 INTRA+Q), STUFFING for the stuffing code --- CBPY (K = 6): the intra CBPY (Y1 the most significant bit; inter macroblocks use 15 - value) --- MVD (K = 12): the magnitude 0..32 in half samples (a sign bit follows every code but "1", which is 0) --- TCOEF (K = 12): last * 1024 + run * 16 + level (a sign bit follows), ESCAPE for the escape code +-- codecs/video/H263/Tables: the H.263 variable-length codes (ITU-T H.263 (01/2005) tables 7 / 8 MCBPC, 12 DQUANT, +-- 13 CBPY, 14 MVD, 16 TCOEF, figure 14 zigzag). Flat tables indexed by the next K bits: len * 65536 + value (len 0: none). +-- MCBPC_I / MCBPC_P (K = 9): type * 4 + CBPC (0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA, 4 INTRA+Q), STUFFING +-- CBPY (K = 6): the intra CBPY, Y1 the MSB (inter macroblocks use 15 - value) +-- MVD (K = 12): magnitude 0..32 in half samples (a sign bit follows every code but "1") +-- TCOEF (K = 12): last * 1024 + run * 16 + level (a sign bit follows), ESCAPE local T = {} T.STUFFING = 255 T.ESCAPE = 0xFFFF --- builds a K-bit flat table from { bits, value } pairs local function flat(codes: { { any } }, k: number): buffer local lut = buffer.create(4 * 2 ^ k) for _, c in codes do @@ -96817,34 +93948,10 @@ return T end __FILES["codecs/video/H264"] = function() --- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the --- video/h264 format (raw Annex B streams) and the MP4 / MKV / AVI / TS video tracks use it. Clean-room, written from the --- spec; constant tables taken from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). Bit-exact with the --- reference decoder (checked against ffmpeg per frame). --- Supports: Annex B and AVCC (length-prefixed, with avcC extradata) input; SPS / PPS / slices; CAVLC and CABAC; I, P and --- B slices; every intra mode (4x4, 8x8, 16x16, chroma), quarter-sample luma / eighth-sample chroma motion --- compensation, explicit and implicit weighted prediction, direct spatial and temporal prediction; the 4x4 and 8x8 --- transforms with scaling matrices; the deblocking filter; multiple reference frames, long-term references, MMCO and --- the sliding window, frame_num gaps; POC types 0 / 1 / 2 and output reordering; 8-bit 4:2:0 Constrained Baseline, --- Main, Extended-without-SP/data-partitioning and High profiles; cropping. Corrupt slices are skipped and their --- macroblocks concealed (copied from the latest reference picture). --- Not supported (UNSUPPORTED): interlaced coding (field pictures, MBAFF), 4:0:0 / 4:2:2 / 4:4:4, bit depths above 8, --- lossless (transform bypass), FMO / ASO slice groups, SP / SI slices, data partitioning, SVC / MVC enhancement layers --- (their NAL units are ignored). --- --- local H264 = require("@rosetta/codecs/video/H264") --- local dec = H264.newDecoder() -- or { avcC = buffer } for MP4 samples (length-prefixed) --- for _, au in accessUnits do --- local frames, err = dec:decode(au, pts) -- frames: { { image (yuv420p Types.Image), pts, poc, keyframe } } --- end --- local rest = dec:flush() -- the frames still held for reordering --- --- Speed (one Zen 5 core, tools/bench.luau, libx264 crf 23 clips): Luau --codegen ~220-425 fps at 320x240 and ~75-135 --- fps at 640x360; LuaJIT with the api's trace limits (host/init.luau) about the same or faster, but with LuaJIT's default --- limits (maxtrace=1000) the trace cache thrashes and it drops to ~30-190 fps. Real-time is comfortable at 320x240 and --- feasible at 640x360 for typical bitrates; high-bitrate CIF conformance streams run ~100-150 fps (Luau). --- Never throws: bad data returns nil, Err (core/Err codes ARG / UNSUPPORTED / LIMIT), or frames with the bad slices --- concealed (dec.errors counts them, dec.lastError says why). +-- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau, bit-exact with ffmpeg. +-- Clean-room from the spec; constant tables from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). 8-bit 4:2:0 +-- Constrained Baseline, Main and High. UNSUPPORTED: interlaced coding (field pictures, MBAFF), 4:0:0 / 4:2:2 / 4:4:4, +-- bit depths above 8, lossless, FMO / ASO, SP / SI slices, data partitioning, SVC / MVC (their NAL units are ignored). local Err = __include("core/Err") local Types = __include("Types") local Bitstream = __include("codecs/video/H264/Bitstream") @@ -96856,15 +93963,15 @@ local H264 = {} type Options = { avcC: buffer?, -- AVCDecoderConfigurationRecord (MP4 'avcC', Matroska CodecPrivate): samples are length-prefixed lengthSize: number?, -- NAL length field size for length-prefixed input without avcC (1, 2 or 4) - maxPixels: number?, -- largest picture (default 2^22 luma samples) - lowDelay: boolean?, -- output in decoding order, no reordering delay (streams without B frames / reordering) - deblock: boolean?, -- false skips the deblocking filter (faster, not conformant); default true - yield: (() -> ())?, -- a cooperative yield point (see Decoder Options.yield): pcall'ed every 16 macroblocks + maxPixels: number?, + lowDelay: boolean?, + deblock: boolean?, + yield: (() -> ())?, } type Frame = { - image: Types.Image, -- yuv420p, cropped to the display size; image.meta.source = { format = "h264", poc, ... } - pts: number, -- the pts passed with the access unit holding the picture (default: its decoding index) + image: Types.Image, + pts: number, duration: number, poc: number, keyframe: boolean, @@ -96901,7 +94008,6 @@ local function status(self: H264Decoder): Err.Err? return nil end --- newDecoder(opts?) -> H264Decoder | nil, Err function H264.newDecoder(opts: Options?): (H264Decoder?, Err.Err?) local o = opts or {} if type(o) ~= "table" then @@ -96918,8 +94024,6 @@ function H264.newDecoder(opts: Options?): (H264Decoder?, Err.Err?) return self, nil end --- decoder:configure(avcC) -> true | nil, Err: reads an AVCDecoderConfigurationRecord (its SPS / PPS) and switches to --- length-prefixed input function DecoderMeta.configure(self: H264Decoder, avcC: any): (boolean?, Err.Err?) local b = toBuffer(avcC) if not b then @@ -96945,8 +94049,6 @@ function DecoderMeta.configure(self: H264Decoder, avcC: any): (boolean?, Err.Err return true, nil end --- decoder:decode(data, pts?, off?, len?) -> { Frame } | nil, Err. data: an access unit or any run of NAL units: --- length-prefixed (after configure / with opts.lengthSize), else Annex B (start codes) or one bare NAL unit. function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: number?, len: number?): ({ Frame }?, Err.Err?) local b = toBuffer(data) if not b then @@ -96983,14 +94085,12 @@ function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: num return frames, nil end --- decoder:flush() -> { Frame }: ends the stream (the current picture and every picture held for reordering) function DecoderMeta.flush(self: H264Decoder): { Frame } Decoder.flush(self.state) status(self) return Decoder.take(self.state) end --- decodeAll(data, opts?) -> { Frame } | nil, Err: a whole Annex B (or length-prefixed with opts.avcC) stream function H264.decodeAll(data: any, opts: Options?): ({ Frame }?, Err.Err?) local dec, err = H264.newDecoder(opts) if not dec then @@ -97006,7 +94106,6 @@ function H264.decodeAll(data: any, opts: Options?): ({ Frame }?, Err.Err?) return frames, nil end --- parseAvcC(buf) -> { lengthSize, profile, level, nals } | nil, Err function H264.parseAvcC(data: any): (any, Err.Err?) local b = toBuffer(data) if not b then @@ -97019,11 +94118,6 @@ function H264.parseAvcC(data: any): (any, Err.Err?) return cfg, nil end --- ------------------------------------------------------------------------------------------------ video layer --- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video registry entry for "h264"): --- track.config = avcC (MP4 / Matroska; packets length-prefixed) or nil (Annex B packets: MPEG-TS, AVI, raw .h264). --- Pictures come out in display order with the packet timestamps sorted (display order); a track with --- `ptsInOutputOrder` (raw Annex B, no timestamps) numbers them in output order instead. function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local o: Options = { maxPixels = opts and opts.maxPixels, deblock = opts and opts.deblock, lowDelay = opts and opts.lowDelay, yield = opts and opts.yield } @@ -97052,8 +94146,7 @@ function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodec pts = outIndex or 0 outIndex = pts + 1 elseif #pool > 0 then - -- pictures leave in display order: they take the packet timestamps in increasing order (right for - -- MP4 / MKV / TS pts, and for AVI whose packets only carry decode-order times) + -- pictures take the packet timestamps in increasing order (right for MP4 / MKV / TS pts and AVI's decode-order times) pts = table.remove(pool, 1) end table.insert(queue, { f.image, pts, f.keyframe }) @@ -97103,9 +94196,8 @@ function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodec return self, nil end --- accessUnits(buf, off?, len?) -> { off, len, keyframe, ... } (triples): an Annex B stream cut into access units --- (7.4.1.2.3: a new unit starts at an AUD, SPS, PPS or SEI after a slice, or at a slice with first_mb_in_slice 0 --- after a slice). keyframe: the unit holds an IDR slice. +-- 7.4.1.2.3: a new access unit starts at an AUD, SPS, PPS or SEI after a slice, or at a slice with first_mb_in_slice 0 +-- after a slice function H264.accessUnits(data: any, off: number?, len: number?): { any } local b = toBuffer(data) local out = {} @@ -97130,7 +94222,6 @@ function H264.accessUnits(data: any, off: number?, len: number?): { any } end end if boundary then - -- the unit ends where this NAL's start code begins local s = p while s > start and buffer.readu8(b, s - 1) ~= 1 do s -= 1 @@ -97159,8 +94250,6 @@ function H264.accessUnits(data: any, off: number?, len: number?): { any } return out end --- toAnnexB(config, sample) -> buffer: a length-prefixed sample (MP4 / Matroska) as Annex B; with config (avcC) the --- parameter sets are prepended (pass it for the first sample / keyframes). nil, Err on a bad avcC / sample function H264.toAnnexB(config: buffer?, sample: buffer): (buffer?, Err.Err?) local parts = {} local lengthSize = 4 @@ -97184,7 +94273,6 @@ function H264.toAnnexB(config: buffer?, sample: buffer): (buffer?, Err.Err?) return buffer.fromstring(table.concat(parts)), nil end --- info(data) -> { width, height, profile, level, frameRate?, ... } of the first SPS of an Annex B stream or avcC | nil function H264.info(data: any): any local b = toBuffer(data) if not b then @@ -97223,7 +94311,6 @@ function H264.info(data: any): any return nil end --- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height function H264.planes(img: Types.Image): (number, number, number, number, number) local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2 local ny = img.width * img.height @@ -97236,11 +94323,8 @@ __FILES["codecs/video/H264/Bitstream"] = @native function() --- codecs/video/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B start --- code splitting, AVCC length-prefixed samples, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3) --- parsing, emulation-prevention removal, and the u(n) / ue(v) / se(v) / te(v) readers. Written from the spec. --- Never throws: reads past the end of an RBSP return zero bits (the buffer carries 8 zero bytes of padding and every --- read is range-checked), and callers check `r.pos > r.size` once per syntax structure. +-- codecs/video/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B, +-- AVCC, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3), emulation prevention, u(n) / ue(v) / se(v) / te(v). local Bitstream = {} local readu8 = buffer.readu8 @@ -97248,15 +94332,13 @@ local band, lshift = bit32.band, bit32.lshift type Reader = { buf: buffer, -- the RBSP (emulation prevention removed) followed by 8 zero bytes - pos: number, -- bit position + pos: number, size: number, -- RBSP length in bits (up to the end of the data, trailing bits included) stop: number, -- bit position of the rbsp_stop_one_bit (size when there is none) - n: number, -- buffer length in bytes + n: number, } --- ------------------------------------------------------------------------------------------------ framing --- splitAnnexB(buf, off, len) -> { off1, len1, off2, len2, ... }: NAL unit payload ranges between start codes --- (00 00 01, with any leading zero bytes); trailing zero bytes of a NAL are dropped. +-- start codes are 00 00 01 with any leading zero bytes; trailing zero bytes of a NAL are dropped @native function Bitstream.splitAnnexB(buf: buffer, off: number, len: number): { number } local out = {} local e = off + len @@ -97298,7 +94380,6 @@ type Reader = { return out end --- isAnnexB(buf, off, len) -> true when the data starts with a start code (00 00 01 or 00 00 00 01) @native function Bitstream.isAnnexB(buf: buffer, off: number, len: number): boolean if len >= 3 and readu8(buf, off) == 0 and readu8(buf, off + 1) == 0 then local b2 = readu8(buf, off + 2) @@ -97310,8 +94391,6 @@ end return false end --- splitLength(buf, off, len, size) -> NAL ranges of a length-prefixed (AVCC / MP4 sample) buffer, or nil when a --- length runs past the end (the NALs before it are kept in the second result) @native function Bitstream.splitLength(buf: buffer, off: number, len: number, size: number): ({ number }?, { number }) local out = {} local e = off + len @@ -97334,8 +94413,6 @@ end return out, out end --- parseAvcC(buf, off, len) -> { lengthSize, profile, level, nals = { off, len, ... } (SPS then PPS, + SPS ext) } | --- nil, message @native function Bitstream.parseAvcC(buf: buffer, off: number, len: number): (any, string?) if len < 7 then return nil, "truncated: avcC shorter than 7 bytes" @@ -97375,9 +94452,7 @@ end return cfg, nil end --- ------------------------------------------------------------------------------------------------ rbsp --- reader(buf, off, len, skip) -> Reader over the RBSP of a NAL unit's bytes [off, off + len), the first `skip` --- bytes (the NAL header) left out; emulation_prevention_three_byte (00 00 03) removed. +-- emulation_prevention_three_byte (00 00 03) is removed @native function Bitstream.reader(buf: buffer, off: number, len: number, skip: number): Reader local out = buffer.create(len + 8) local o = 0 @@ -97413,7 +94488,6 @@ end return { buf = out, pos = 0, size = o * 8, stop = stop, n = o + 8 } end --- ------------------------------------------------------------------------------------------------ bits -- Plain arithmetic instead of bit32 (LuaJIT runs bit32 through compat wrappers whose sign fix-ups split traces). local P2 = table.create(33, 1) -- P2[k + 1] = 2^k for k = 0, 32 do @@ -97431,7 +94505,6 @@ for x = 0, 255 do end Bitstream.LZ8 = LZ8 --- clz32(v) -> leading zero bits of a 32-bit value @native local function clz32(v: number): number if v >= 16777216 then return LZ8[v // 16777216 + 1] @@ -97444,7 +94517,6 @@ Bitstream.LZ8 = LZ8 end Bitstream.clz32 = clz32 --- peekAt(b, n, pos) -> the 32 bits at bit position pos of buffer b (n bytes), zeros past the end @native local function peekAt(b: buffer, n: number, pos: number): number local p = pos // 8 if p + 5 > n then @@ -97459,20 +94531,17 @@ Bitstream.clz32 = clz32 end Bitstream.peekAt = peekAt --- peek32(r) -> the next 32 bits (zeros past the end) @native local function peek32(r: Reader): number return peekAt(r.buf, r.n, r.pos) end Bitstream.peek32 = peek32 --- u(r, n) -> n bits (n 1..32) as an unsigned number @native function Bitstream.u(r: Reader, n: number): number local v = peekAt(r.buf, r.n, r.pos) r.pos += n return v // P2[33 - n] end --- u1(r) -> one bit @native function Bitstream.u1(r: Reader): number local pos = r.pos r.pos = pos + 1 @@ -97483,7 +94552,7 @@ end return (readu8(r.buf, p) // P2[8 - (pos - p * 8)]) % 2 end --- ue(r) -> ue(v); a code with more than 31 leading zeros returns 2^32 (out of range for every syntax element) +-- more than 31 leading zeros returns 2^32 (out of range for every syntax element) @native local function ue(r: Reader): number local v = peekAt(r.buf, r.n, r.pos) if v == 0 then @@ -97503,7 +94572,6 @@ end end Bitstream.ue = ue --- se(r) -> se(v) @native function Bitstream.se(r: Reader): number local k = ue(r) if k % 2 == 1 then @@ -97512,7 +94580,6 @@ Bitstream.ue = ue return -(k // 2) end --- te(r, range) -> te(v) with the given range (max value) @native function Bitstream.te(r: Reader, range: number): number if range == 1 then return 1 - Bitstream.u1(r) @@ -97520,7 +94587,7 @@ end return ue(r) end --- moreData(r) -> more_rbsp_data() +-- more_rbsp_data() @native function Bitstream.moreData(r: Reader): boolean return r.pos < r.stop end @@ -97531,12 +94598,9 @@ __FILES["codecs/video/H264/Cabac"] = @native function() --- codecs/video/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3): the --- arithmetic decoding engine (9.3.1.2 / 9.3.3.2), context initialisation (9.3.1.1), the binarizations and context --- index increments of every syntax element (9.3.2 / 9.3.3.1) and residual_block_cabac for 4x4, 8x8 and DC blocks. --- Coefficients are dequantised as they are placed. Written from the spec; tables from Tables. --- The engine keeps codIOffset with `nb` look-ahead bits (low = offset * 2^nb + next bits), so renormalisation is one --- multiply and bytes are fetched one at a time. Never throws: returns false, "message" on bad data. +-- codecs/video/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3): +-- engine (9.3.1.2 / 9.3.3.2), context init (9.3.1.1), binarizations and ctxIdxInc (9.3.2 / 9.3.3.1), residual_block_cabac. +-- codIOffset is kept with `nb` look-ahead bits (low = offset * 2^nb + next bits), so renormalisation is one multiply. local Bitstream = __include("codecs/video/H264/Bitstream") local Tables = __include("codecs/video/H264/Tables") local Mb = __include("codecs/video/H264/Mb") @@ -97549,7 +94613,6 @@ local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y local Cabac = {} --- ------------------------------------------------------------------------------------------------ engine local RANGE_LPS = Tables.RANGE_LPS local TRANS = Tables.TRANS local POW2 = table.create(40, 1) @@ -97581,7 +94644,6 @@ for st = 0, 127 do end end --- the engine (one slice at a time) local ebuf: buffer = buffer.create(1) local epos, elimit = 0, 0 local erange, elow, enb = 510, 0, 0 @@ -97596,8 +94658,7 @@ local erange, elow, enb = 510, 0, 0 enb += 8 end --- decision(ctx) -> bin (9.3.3.2.1), branch-free apart from the byte refill: the LPS test is min(1, low // scaled) --- (low < 2.5 * scaled always), the state step and the bin come from tables +-- decision (9.3.3.2.1): the LPS test is min(1, low // scaled) (low < 2.5 * scaled always) @native local function decision(ctx: number): number local s = ST[ctx + 1] local range = erange @@ -97647,7 +94708,6 @@ end return 0 end --- start the engine at byte p of the rbsp @native local function engineInit(b: buffer, p: number, limit: number) ebuf, epos, elimit = b, p, limit elow, enb = 0, -9 @@ -97677,7 +94737,6 @@ end end end --- ------------------------------------------------------------------------------------------------ residual local ZZ4, ZZ8 = Tables.ZIGZAG4, Tables.ZIGZAG8 local SIG8, LAST8 = Tables.SIG8, Tables.LAST8 local CAT_CBF = { 0, 4, 8, 12, 16 } @@ -97686,8 +94745,7 @@ local CAT_ABS = { 0, 10, 20, 30, 39 } local MAXC = { 16, 15, 16, 4, 15, 64 } local SIGPOS = table.create(64, 0) --- block(cat, out, base, mul, div) -> number of coefficients (cat 0..5); coded_block_flag is decoded by the caller. --- Positions: cat 0 / 2 zig-zag, 1 / 4 zig-zag from 1, 3 raster 0..3, 5 the 8x8 zig-zag +-- positions: cat 0 / 2 zig-zag, 1 / 4 zig-zag from 1, 3 raster 0..3, 5 the 8x8 zig-zag local SCAN = {} do local ac = table.create(15, 0) @@ -97796,7 +94854,6 @@ local SIG3 = { 0, 1, 2 } return n end --- ------------------------------------------------------------------------------------------------ syntax elements -- condition helpers on neighbouring macroblocks (addresses are 1-based here) @native local function leftAddr(S: any, M: any): number return ((M.aL) and (M.addr) or (0)) @@ -97935,7 +94992,6 @@ end return t end --- ref_idx for the partition whose top-left 4x4 is (x, y); rgt: the ref > 0 grid of the list @native local function refIdx(S: any, M: any, rgt: { number }, x: number, y: number): number local g = M.g0 + y * S.w4 + x local inc = 0 @@ -97960,7 +95016,7 @@ end return v end --- mvd component (comp 0 x, 1 y) for the partition at (x, y); grid holds |mvd| (2 per 4x4) +-- the mvd grid holds |mvd| (2 per 4x4) @native local function mvd(S: any, M: any, grid: { number }, x: number, y: number, comp: number): number local g = M.g0 + y * S.w4 + x local sum = 0 @@ -98181,7 +95237,6 @@ end return ca, cb end --- ------------------------------------------------------------------------------------------------ residual @native local function residuals(S: any, M: any): boolean local kind = M.kind local cbp = M.cbp @@ -98306,7 +95361,6 @@ end end end --- ------------------------------------------------------------------------------------------------ macroblock local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } local SUB_N = { 1, 2, 2, 4 } @@ -98626,7 +95680,6 @@ end return interMb(S, M, r, t, true) end --- slice(S, M, r) -> true | false, message @native function Cabac.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local p = (r.pos + 7) // 8 local limit = r.size // 8 @@ -98676,11 +95729,8 @@ __FILES["codecs/video/H264/Cavlc"] = @native function() --- codecs/video/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2): --- mb_skip_run, mb_type / sub_mb_type, intra modes, ref_idx (te), mvd, coded_block_pattern (me), mb_qp_delta and --- residual_block_cavlc (coeff_token, level_prefix / suffix, total_zeros, run_before) with the 8x8 interleaving. --- Coefficients are dequantised as they are placed. Written from the spec; VLC tables from Tables. --- Never throws: returns false, "message" on bad data. +-- codecs/video/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2), +-- residual_block_cavlc with the 8x8 interleaving; coefficients are dequantised as they are placed. local Bitstream = __include("codecs/video/H264/Bitstream") local Tables = __include("codecs/video/H264/Tables") local Mb = __include("codecs/video/H264/Mb") @@ -98692,7 +95742,6 @@ local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y local Cavlc = {} --- ------------------------------------------------------------------------------------------------ vlc tables -- build(entries) -> l1, l2: a two-level lookup on 16 peeked bits. l1[(v >> 8) + 1] = value * 32 + length, or -- -(base) of a second-level block l2[base + (v & 255)]; 0 = no code @native local function build(entries: { { number } }): ({ number }, { number }) @@ -98775,7 +95824,6 @@ local IDENT = { 0, 1, 2, 3 } local INTRA_CBP, INTER_CBP = Tables.INTRA_CBP, Tables.INTER_CBP --- ------------------------------------------------------------------------------------------------ residual local LEVEL = table.create(16, 0) local RUN = table.create(16, 0) @@ -98783,8 +95831,7 @@ local peek = Bitstream.peekAt local clz32 = Bitstream.clz32 local P2 = Bitstream.P2 --- residual(r, nC, maxCoeff, out, base, scan, mul, div) -> TotalCoeff, or -1 on a bad code. Levels go to --- out[base + scan[i] + 1] dequantised as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels) +-- levels go to out[base + scan[i] + 1] as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels) @native local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: { number }, base: number, scan: { number }, mul: { number }?, div: number): number local b, n = r.buf, r.n local pos = r.pos @@ -98931,7 +95978,6 @@ local P2 = Bitstream.P2 end Cavlc.residual = residual --- ------------------------------------------------------------------------------------------------ macroblock local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } local SUB_N = { 1, 2, 2, 4 } @@ -98954,7 +96000,6 @@ local BPAIR1 = { 1, 2, 2, 1, 3, 3, 1, 2, 3 } return v end --- the residual of the parsed macroblock @native local function residuals(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local kind = M.kind local cbp = M.cbp @@ -99079,7 +96124,7 @@ end end end --- intra(S, M, r, t): the intra macroblock types 0..25 (table 7-11) +-- intra macroblock types 0..25 (table 7-11) @native local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean, string?) local addr = M.addr + 1 if t == 25 then @@ -99190,7 +96235,7 @@ end return true end --- inter(S, M, r, t, isB): the P (0..4) and B (0..22) inter macroblock types +-- the P (0..4) and B (0..22) inter macroblock types @native local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: boolean): (boolean, string?) clearLumaGrids(S, M, false) local n0, n1 = S.n0, S.n1 @@ -99384,7 +96429,6 @@ end return true end --- macroblock(S, M, r) -> true | false, message @native local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local t = ue(r) local st = S.type @@ -99402,8 +96446,6 @@ end return interMb(S, M, r, t, true) end --- ------------------------------------------------------------------------------------------------ slice data --- slice(S, M, r) -> true | false, message: decodes macroblocks from S.firstMb until the end of the slice data @native function Cavlc.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local addr = S.firstMb local total = S.mbW * S.mbH @@ -99455,12 +96497,9 @@ __FILES["codecs/video/H264/Deblock"] = @native function() --- codecs/video/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0: --- boundary strengths (8.7.2.1, from the per-4x4 intra / coefficient / reference / motion grids), alpha / beta / tC0 --- (tables 8-16 / 8-17), the bS < 4 and bS = 4 luma and chroma filters, disable_deblocking_filter_idc 0 / 1 / 2 and the --- slice alpha / beta offsets. Written from the spec. Runs over the whole picture in macroblock order once all its --- slices are decoded (the result equals filtering each macroblock as it is decoded). --- Never throws. +-- codecs/video/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0 +-- (bS 8.7.2.1, alpha / beta / tC0 tables 8-16 / 8-17). Runs over the whole picture once its slices are decoded, which +-- equals filtering each macroblock as it is decoded. local Tables = __include("codecs/video/H264/Tables") local readu8, writeu8 = buffer.readu8, buffer.writeu8 @@ -99477,9 +96516,6 @@ end local abs = math.abs --- luma(b, o, across, along, qp, aOff, bOff): filters the 16 samples of one luma edge; `across` steps from q0 to q1 --- (1 for vertical edges, the stride for horizontal ones), `along` to the next sample of the edge; BS holds the four --- strengths @native local function luma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) local indexA = clip3(0, 51, qp + aOff) local alpha = ALPHA[indexA + 13] @@ -99538,7 +96574,7 @@ local abs = math.abs end end --- chroma(b, o, across, along, qp, aOff, bOff): the 8 samples of one chroma edge (bS of luma segment i // 2) +-- chroma: bS of luma segment i // 2 @native local function chroma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) local indexA = clip3(0, 51, qp + aOff) local alpha = ALPHA[indexA + 13] @@ -99569,7 +96605,7 @@ end end end --- motionDiffers(pic, p, q) -> true when the 4x4 blocks p and q (grid indices) need bS 1 (8.7.2.1) +-- the bS 1 motion test of 8.7.2.1 @native local function mvDiff(mvA: { number }, a: number, mvB: { number }, b: number): boolean return abs(mvA[2 * a - 1] - mvB[2 * b - 1]) >= 4 or abs(mvA[2 * a] - mvB[2 * b]) >= 4 end @@ -99610,7 +96646,6 @@ end return (mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q)) and (mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q)) end --- picture(S, pic, params): deblocks the whole picture. params[sliceNum] = { idc, alphaOffset, betaOffset } @native function Deblock.picture(S: any, pic: any, params: { any }) local mbW, mbH = S.mbW, S.mbH local w4 = S.w4 @@ -99657,7 +96692,6 @@ end if t8 and (e == 1 or e == 3) then continue end - -- strengths of the four segments local intraP = intraQ local qpP, qpcP, qpc2P = qpQ, qpcQ, qpc2Q if e == 0 then @@ -99719,12 +96753,9 @@ return Deblock end __FILES["codecs/video/H264/Decoder"] = function() --- codecs/video/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): NAL unit --- dispatch, picture boundaries (7.4.1.2.4), picture order count types 0 / 1 / 2 (8.2.1), frame_num gaps (8.2.5.2), --- reference picture lists with modification (8.2.4), sliding window and adaptive (MMCO 1-6) marking (8.2.5), output --- in POC order through a reorder buffer (num_reorder_frames, else the DPB size), concealment of lost macroblocks, --- deblocking and border extension. Written from the spec. --- Never throws: errors are returned (a corrupt slice is skipped and its macroblocks concealed). +-- codecs/video/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): picture +-- boundaries (7.4.1.2.4), POC types 0 / 1 / 2 (8.2.1), frame_num gaps (8.2.5.2), list modification (8.2.4), marking +-- (8.2.5), output in POC order (num_reorder_frames, else the DPB size). local Bitstream = __include("codecs/video/H264/Bitstream") local Params = __include("codecs/video/H264/Params") local Slice = __include("codecs/video/H264/Slice") @@ -99743,17 +96774,14 @@ local Decoder = {} Decoder.__index = Decoder type Options = { - maxPixels: number?, -- largest picture accepted (default 2^22: 4096 x 1024) - lowDelay: boolean?, -- output pictures in decoding order without reordering (only right for streams without B frames) - deblock: boolean?, -- false skips the loop filter (not conformant: faster, for previews); default true - -- a cooperative yield point, called (pcall'ed: it can't throw through the native code) every YIELD_MBS macroblocks - -- of slice data and every macroblock row of the loop filter: e.g. a function that calls coroutine.yield() once a time - -- budget is spent, to spread one picture over several frames. While a decode is suspended, no other H.264 decode may - -- run in the same Luau VM (the entropy decoders keep their state in module locals); default nil (no calls) + maxPixels: number?, + lowDelay: boolean?, + deblock: boolean?, + -- yield is pcall'ed (it can't throw through native code); the entropy decoders keep state in module locals, so no + -- other H.264 decode may run in the VM while one is suspended yield: (() -> ())?, } --- new(opts) -> decoder state function Decoder.new(opts: Options?): any local o = opts or {} return setmetatable({ @@ -99778,7 +96806,7 @@ function Decoder.new(opts: Options?): any maxLongTermIdx = -1, pool = {}, gray = nil, - frames = 0, -- pictures decoded + frames = 0, errors = 0, lastError = nil, fatal = nil, @@ -99787,7 +96815,6 @@ function Decoder.new(opts: Options?): any }, Decoder) end --- ------------------------------------------------------------------------------------------------ pictures local function newPicture(self: any, sps: any): any local mbW, mbH = sps.mbWidth, sps.mbHeight local pool = self.pool @@ -99856,7 +96883,6 @@ local function grayPicture(self: any, sps: any): any return g end --- ------------------------------------------------------------------------------------------------ output local function emit(self: any, p: any) p.waiting = false local sps = p.sps @@ -99909,7 +96935,6 @@ local function reorderDepth(self: any, sps: any): number return sps.maxDecFrameBuffering or sps.maxDpbFrames end --- ------------------------------------------------------------------------------------------------ reference lists local function shortRefs(self: any): { any } local t = {} for _, p in self.refs do @@ -100008,7 +97033,6 @@ local function modify(self: any, list: { any }, ops: { number }, n: number, sh: return true end --- buildLists(self, sh, cur) -> list0, list1 (arrays of pictures, truncated to num_ref_idx_active) local function buildLists(self: any, sh: any, cur: any): ({ any }, { any }, boolean) picNums(self, sh) local list0, list1 = {}, {} @@ -100088,7 +97112,6 @@ local function buildLists(self: any, sh: any, cur: any): ({ any }, { any }, bool return list0, list1, ok end --- ------------------------------------------------------------------------------------------------ marking local function unmark(self: any, p: any) p.short = false p.long = false @@ -100131,7 +97154,7 @@ local function addRef(self: any, p: any) table.insert(self.refs, p) end --- mark(self, cur, sh): 8.2.5 after decoding the current (reference) picture; returns true when MMCO 5 was present +-- 8.2.5 marking after a reference picture; true when MMCO 5 was present local function mark(self: any, cur: any, sh: any): boolean local sps = sh.sps if sh.idr then @@ -100231,7 +97254,6 @@ local function mark(self: any, cur: any, sh: any): boolean return mmco5 end --- ------------------------------------------------------------------------------------------------ poc local function computePoc(self: any, sh: any): (number, number) local sps = sh.sps local maxFrameNum = 2 ^ sps.log2MaxFrameNum @@ -100297,7 +97319,6 @@ local function computePoc(self: any, sh: any): (number, number) return t, t end --- ------------------------------------------------------------------------------------------------ picture decode local function setupGrids(self: any, sps: any) local mbW, mbH = sps.mbWidth, sps.mbHeight if self.S and self.S.mbW == mbW and self.S.mbH == mbH then @@ -100480,7 +97501,6 @@ local function finishPicture(self: any) p.poc = 0 p.frameNum = 0 end - -- POC / frame_num state for the next pictures if sh.nalRefIdc ~= 0 then if mmco5 then self.prevPocMsb = 0 @@ -100637,7 +97657,6 @@ local function decodeSlice(self: any, sh: any, r: Bitstream.Reader) end end --- nal(self, buf, off, len, pts): one NAL unit (no start code) function Decoder.nal(self: any, buf: buffer, off: number, len: number, pts: number?) if len < 1 then return @@ -100728,13 +97747,11 @@ function Decoder.nal(self: any, buf: buffer, off: number, len: number, pts: numb -- SEI (6), filler (12), SPS extension (13), prefix / SVC / MVC (14, 15, 20) and reserved types are ignored end --- flush(self): finish the current picture and output every waiting picture function Decoder.flush(self: any) finishPicture(self) bump(self, 0) end --- take(self) -> the frames output since the last call function Decoder.take(self: any): { any } local out = self.out self.out = {} @@ -100747,12 +97764,8 @@ __FILES["codecs/video/H264/Inter"] = @native function() --- codecs/video/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3): the 6-tap --- quarter-sample luma filter, eighth-sample bilinear chroma, default / explicit / implicit weighted sample --- prediction, and the picture border extension that makes out-of-picture reference reads equal to the clamped --- sample positions of 8.4.2.2.1. Written from the spec. --- Reference planes carry a border of PAD (luma) / PADC (chroma) replicated samples; callers clamp block positions --- with Inter.clampLuma / clampChroma so every read is inside the buffer. Never throws. +-- codecs/video/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3). +-- Reference planes carry a border of PAD / PADC replicated samples, so reads equal the clamped positions of 8.4.2.2.1. local readu8, writeu8 = buffer.readu8, buffer.writeu8 local Inter = {} @@ -100765,11 +97778,9 @@ local min, max = math.min, math.max return min(max(v, 0), 255) end --- scratch rows of horizontal 6-tap intermediates (unrounded), 21 rows x 16 (+1) columns local B1 = table.create(24 * 17, 0) --- the six-tap filter cases, each a small function (LuaJIT keeps small loops in one trace); sliding windows read each --- sample once per row / column +-- one small function per six-tap case: LuaJIT keeps each loop in one trace @native local function lumaCopy(ref: buffer, s: number, base: number, w: number, h: number, P: { number }) for r = 0, h - 1 do local o = base + r * s @@ -100887,8 +97898,6 @@ end end end --- luma(ref, s, base, fx, fy, w, h, P): the w x h luma prediction for a block whose integer sample (0, 0) is at --- ref[base] and whose fractional offset is (fx, fy) quarter samples; P[r * 16 + c + 1] receives the samples @native function Inter.luma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) if fy == 0 then if fx == 0 then @@ -100907,7 +97916,6 @@ end end end --- chroma(ref, s, base, fx, fy, w, h, P): eighth-sample bilinear chroma prediction @native function Inter.chroma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) if fx == 0 and fy == 0 then for r = 0, h - 1 do @@ -100933,8 +97941,6 @@ end end end --- ------------------------------------------------------------------------------------------------ weighting --- put(P, w, h, b, o, s): P into the picture @native function Inter.put(P: { number }, w: number, h: number, b: buffer, o: number, s: number) for r = 0, h - 1 do local d = r * 16 + 1 @@ -100945,7 +97951,7 @@ end end end --- avg(P0, P1, w, h, b, o, s): default bi-prediction (P0 + P1 + 1) >> 1 +-- default bi-prediction (P0 + P1 + 1) >> 1 @native function Inter.avg(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number) for r = 0, h - 1 do local d = r * 16 + 1 @@ -100956,7 +97962,7 @@ end end end --- weight1(P, w, h, b, o, s, logWD, wt, off): explicit single-list weighting (8-270 / 8-271) +-- explicit single-list weighting (8-270 / 8-271) @native function Inter.weight1(P: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, wt: number, off: number) if logWD >= 1 then local rnd = 2 ^ (logWD - 1) @@ -100979,8 +97985,7 @@ end end end --- weight2(P0, P1, w, h, b, o, s, logWD, w0, w1, off): explicit / implicit bi-prediction weighting (8-272); --- off = (o0 + o1 + 1) >> 1 +-- explicit / implicit bi-prediction weighting (8-272); off = (o0 + o1 + 1) >> 1 @native function Inter.weight2(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, w0: number, w1: number, off: number) local rnd = 2 ^ logWD local div = 2 ^ (logWD + 1) @@ -100993,8 +97998,6 @@ end end end --- ------------------------------------------------------------------------------------------------ borders --- extend(b, o, s, w, h, pad): replicate the edge samples of the w x h plane at b[o] (stride s) into its border @native function Inter.extend(b: buffer, o: number, s: number, w: number, h: number, pad: number) for y = 0, h - 1 do local r = o + y * s @@ -101015,10 +98018,8 @@ __FILES["codecs/video/H264/Intra"] = @native function() --- codecs/video/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (nine directional modes, with the --- 8x8 reference sample filter of 8.3.2.2.1), Intra_16x16 and chroma (DC / horizontal / vertical / plane), 8-bit. --- Written from the spec. Predictions are written straight into the picture plane (row stride `s`, block origin `o`). --- Never throws: every sample read is inside the padded plane (callers pass availability for the edges). +-- codecs/video/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (with the 8x8 reference sample +-- filter of 8.3.2.2.1), Intra_16x16 and chroma, 8-bit. local readu8, writeu8 = buffer.readu8, buffer.writeu8 local Intra = {} @@ -101108,8 +98109,7 @@ end end end --- pred4x4(b, o, s, mode, left, top, topRight, topLeft): Intra_4x4 at plane offset o. Unavailable top-right samples --- repeat p[3, -1]. +-- unavailable top-right samples repeat p[3, -1] @native function Intra.pred4x4(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) if mode == 0 then local t = o - s @@ -101184,7 +98184,6 @@ end directional(E, 4, mode, b, o, s) end --- pred8x8(b, o, s, mode, left, top, topRight, topLeft): Intra_8x8 with the reference sample filter @native function Intra.pred8x8(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) -- unfiltered edges into E: E[1..8] = p[-1, 7..0], E[9] = p[-1, -1], E[10..25] = p[0..15, -1] if left then @@ -101291,7 +98290,6 @@ end end end --- pred16x16(b, o, s, mode, left, top, topLeft) @native function Intra.pred16x16(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) if mode == 0 then local t = o - s @@ -101357,7 +98355,7 @@ end end end --- predChroma(b, o, s, mode, left, top, topLeft): 8x8 chroma (4:2:0); mode 0 DC, 1 horizontal, 2 vertical, 3 plane +-- 8x8 chroma (4:2:0): mode 0 DC, 1 horizontal, 2 vertical, 3 plane @native function Intra.predChroma(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) if mode == 0 then local t = o - s @@ -101428,11 +98426,8 @@ __FILES["codecs/video/H264/Mb"] = @native function() -- codecs/video/H264/Mb: macroblock reconstruction shared by the CAVLC and CABAC parsers (ITU-T H.264 8.3 - 8.5): --- neighbour availability (6.4.11), Intra4x4 / Intra8x8 mode prediction (8.3.1.1 / 8.3.2.1), motion vector prediction --- (8.4.1.3), P_Skip (8.4.1.1), B direct spatial and temporal (8.4.1.2), motion compensation with weighting, intra --- prediction and the residual. Written from the spec; the per-4x4 motion / mode grids follow the usual decoder layout --- (picture-wide arrays, one entry per 4x4 luma block, 1-based). --- Never throws: every index is in range by construction; reference indices past the list use the first entry. +-- neighbour availability (6.4.11), intra mode prediction (8.3.1.1 / 8.3.2.1), motion vector prediction (8.4.1.3), +-- P_Skip (8.4.1.1), B direct (8.4.1.2). Reference indices past the list use the first entry. local Intra = __include("codecs/video/H264/Intra") local Transform = __include("codecs/video/H264/Transform") local Inter = __include("codecs/video/H264/Inter") @@ -101455,7 +98450,6 @@ local BLK_X = { 0, 1, 0, 1, 2, 3, 2, 3, 0, 1, 0, 1, 2, 3, 2, 3 } local BLK_Y = { 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 3, 3 } Mb.BLK_X, Mb.BLK_Y = BLK_X, BLK_Y --- new() -> M, the per-macroblock scratch state @native function Mb.new(): any return { addr = 0, @@ -101505,7 +98499,6 @@ Mb.BLK_X, Mb.BLK_Y = BLK_X, BLK_Y } end --- grids(mbW, mbH) -> the per-picture decoding grids (shared by the slices of one picture) @native function Mb.grids(mbW: number, mbH: number): any local n = mbW * mbH local n4 = n * 16 @@ -101533,8 +98526,6 @@ end } end --- ------------------------------------------------------------------------------------------------ neighbours --- start(S, M, addr): position and neighbour availability of macroblock addr @native function Mb.start(S: any, M: any, addr: number) local mbW = S.mbW local x, y = addr % mbW, addr // mbW @@ -101567,7 +98558,7 @@ end M.qpd = 0 end --- nC(S, M, bx, by) -> nC of luma block (bx, by) (9.2.1) +-- nC of luma block (bx, by) (9.2.1) @native function Mb.nC(S: any, M: any, bx: number, by: number): number local g = M.g0 + by * S.w4 + bx local nzc = S.nzc @@ -101583,7 +98574,6 @@ end return 0 end --- nCc(S, M, tab, bx, by) -> nC of chroma AC block (bx, by) of the plane whose counts are in tab @native function Mb.nCc(S: any, M: any, tab: { number }, bx: number, by: number): number local cw = S.cw4 local g = M.c0 + by * cw + bx @@ -101599,7 +98589,7 @@ end return 0 end --- predMode(S, M, bx, by) -> predIntra4x4PredMode / predIntra8x8PredMode of the block whose top-left 4x4 is (bx, by) +-- predIntra4x4PredMode / predIntra8x8PredMode (8.3.1.1 / 8.3.2.1) @native function Mb.predMode(S: any, M: any, bx: number, by: number): number local la = bx > 0 or M.iL local ta = by > 0 or M.iT @@ -101612,9 +98602,6 @@ end return ((a < b) and (a) or (b)) end --- ------------------------------------------------------------------------------------------------ motion vectors --- neighbour(S, M, list, nx, ny) -> ref (UNAVAIL when not available), mvx, mvy of the 4x4 at (nx, ny) relative to the --- macroblock (nx, ny in -1 .. 4) @native local function neighbour(S: any, M: any, refs: { number }, mvs: { number }, nx: number, ny: number): (number, number, number) local ok if ny < 0 then @@ -101647,8 +98634,7 @@ end return max(min(a, b), min(max(a, b), c)) end --- mvp(S, M, list, x, y, w, ref, shape) -> mvpLX for the partition at (x, y) (4x4 units) of width w with reference --- index ref. shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right +-- shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right (8.4.1.3) @native local function mvp(S: any, M: any, list: number, x: number, y: number, w: number, ref: number, shape: number): (number, number) local pic = S.pic local refs = ((list == 0) and (pic.ref0) or (pic.ref1)) @@ -101701,7 +98687,6 @@ end end Mb.mvp = mvp --- set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y): motion data of a region into the picture grids @native local function set(S: any, M: any, x: number, y: number, w: number, h: number, r0: number, m0x: number, m0y: number, r1: number, m1x: number, m1y: number) local pic = S.pic local ref0, ref1, mv0, mv1, uid0, uid1 = pic.ref0, pic.ref1, pic.mv0, pic.mv1, pic.uid0, pic.uid1 @@ -101728,7 +98713,6 @@ Mb.mvp = mvp M.nreg += 1 end --- clipping helpers @native local function clip3(lo: number, hi: number, v: number): number return min(max(v, lo), hi) end @@ -101741,7 +98725,7 @@ end return -math.floor(-q) end --- distScale(cur, poc0, poc1) -> DistScaleFactor (8-195 .. 8-198), or nil when td is 0 +-- DistScaleFactor (8-195 .. 8-198), nil when td is 0 @native function Mb.distScale(cur: number, poc0: number, poc1: number): number? local tb = clip3(-128, 127, cur - poc0) local td = clip3(-128, 127, poc1 - poc0) @@ -101752,7 +98736,7 @@ end return clip3(-1024, 1023, (tb * tx + 32) // 64) end --- pskip(S, M): P_Skip motion (8.4.1.1) +-- P_Skip motion (8.4.1.1) @native local function pskip(S: any, M: any) local mx, my = 0, 0 if M.aL and M.aT then @@ -101766,7 +98750,7 @@ end set(S, M, 0, 0, 4, 4, 0, mx, my, -1, 0, 0) end --- colocated(S, M, bx, by) -> refIdxCol (-1: intra / none), mvCol x, y, uid of the referenced picture (8.4.1.2.1) +-- refIdxCol (-1: intra / none), mvCol (8.4.1.2.1) @native local function colocated(S: any, M: any, bx: number, by: number): (number, number, number, number) local col = S.colPic if S.direct8x8 then @@ -101795,7 +98779,7 @@ end return ((a > b) and (a) or (b)) end --- spatialRefs(S, M): the macroblock-level references and predictors of spatial direct (8.4.1.2.2), cached in M +-- spatial direct references and predictors (8.4.1.2.2) @native local function spatialRefs(S: any, M: any) local pic = S.pic local r0, r1 = -1, -1 @@ -101836,7 +98820,6 @@ end M.dReady = true end --- direct8(S, M, i8): direct motion of 8x8 quadrant i8 (B_Skip, B_Direct_16x16, B_Direct_8x8) @native local function direct8(S: any, M: any, i8: number) local x0, y0 = (i8 % 2) * 2, (i8 // 2) * 2 local step = ((S.direct8x8) and (2) or (1)) @@ -101885,12 +98868,10 @@ end end end --- partition geometry (4x4 units) of the sub-macroblock shapes local SUB_N = { 1, 2, 2, 4 } local SUB_W = { 2, 2, 1, 1 } local SUB_H = { 2, 1, 2, 1 } --- motion(S, M): motion vectors of an inter macroblock into the grids, and its MC regions @native local function motion(S: any, M: any) local kind = M.kind M.dReady = false @@ -101977,8 +98958,6 @@ local SUB_H = { 2, 1, 2, 1 } end Mb.motion = motion --- ------------------------------------------------------------------------------------------------ motion compensation --- predict(S, M, pic, P, list, x, y, w, h, mvx, mvy, plane): one list's prediction samples of a region into P @native local function predLuma(S: any, ref: any, P: { number }, px: number, py: number, w: number, h: number, mvx: number, mvy: number) local W, H = S.mbW * 16, S.mbH * 16 local ix = px + mvx // 4 @@ -102003,7 +98982,6 @@ end return list[r + 1] or list[1] end --- mc(S, M): inter prediction of every region of the macroblock into the current picture @native local function mc(S: any, M: any) local pic = S.pic local reg = M.reg @@ -102030,7 +99008,6 @@ end local lo = pic.yo + py * ys + px local cx, cy, cw, ch = M.x * 8 + x * 2, M.y * 8 + y * 2, w * 2, h * 2 local co = pic.co + cy * cs + cx - -- weights for this pair local bi = ref0 ~= nil and ref1 ~= nil local explicit = wm == 1 local implicitW0, implicitW1 = 32, 32 @@ -102090,7 +99067,6 @@ end end end --- ------------------------------------------------------------------------------------------------ residual @native local function lumaResidual(S: any, M: any) local pic = S.pic local b, s = pic.y, pic.ys @@ -102142,7 +99118,6 @@ end end end --- ------------------------------------------------------------------------------------------------ intra @native local function intraLuma(S: any, M: any) local pic = S.pic local b, s = pic.y, pic.ys @@ -102247,8 +99222,6 @@ end end end --- ------------------------------------------------------------------------------------------------ macroblock --- recon(S, M): reconstruct the parsed macroblock and store what later macroblocks / deblocking need @native function Mb.recon(S: any, M: any) local kind = M.kind local addr = M.addr + 1 @@ -102264,7 +99237,6 @@ end local nzDb = S.nzDb local g0 = M.g0 if kind <= K_PCM then - -- intra: no motion local ref0, ref1, uid0, uid1 = pic.ref0, pic.ref1, pic.uid0, pic.uid1 for j = 0, 3 do local g = g0 + j * w4 @@ -102314,7 +99286,6 @@ end chromaResidual(S, M) end --- skip(S, M, kind): a P_Skip / B_Skip macroblock (no residual) @native function Mb.skip(S: any, M: any, kind: number) M.kind = kind M.cbp = 0 @@ -102359,10 +99330,9 @@ end __FILES["codecs/video/H264/Params"] = @native function() --- codecs/video/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists with --- the fall-back rules A and B (7.4.2.1.1 / table 7-2), and the dequantisation tables built from them (8.5.9: the --- LevelScale4x4 / LevelScale8x8 functions, premultiplied by 2^(qP / 6)). Written from the spec. --- Never throws: parse functions return nil, "message". +-- codecs/video/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists +-- with the fall-back rules A and B (7.4.2.1.1 / table 7-2), and the dequantisation tables built from them (8.5.9: the +-- LevelScale4x4 / LevelScale8x8 functions, premultiplied by 2^(qP / 6)). local Bitstream = __include("codecs/video/H264/Bitstream") local Tables = __include("codecs/video/H264/Tables") @@ -102377,7 +99347,7 @@ local MAX_DPB_MBS = { [9] = 396, [10] = 396, [11] = 900, [12] = 2376, [13] = 237 local ZIGZAG4, ZIGZAG8 = Tables.ZIGZAG4, Tables.ZIGZAG8 --- scaling_list(): returns the list in raster order, or "default" (useDefaultScalingMatrixFlag) +-- scaling_list(): raster order, or "default" (useDefaultScalingMatrixFlag) @native local function scalingList(r: Bitstream.Reader, size: number): any local list = table.create(size, 0) local last, nxt = 8, 8 @@ -102433,7 +99403,7 @@ end local FLAT16, FLAT64 = table.create(16, 16), table.create(64, 16) --- resolve(lists, fallback) -> 12 raster lists. fallback: nil = rule A (defaults), else the 12 lists of the SPS (rule B) +-- fallback nil = rule A (defaults), else the SPS's 12 lists (rule B) @native local function resolve(lists: { any }, fallback: { { number } }?): { { number } } local out = {} for i = 1, 12 do @@ -102453,7 +99423,6 @@ local FLAT16, FLAT64 = table.create(16, 16), table.create(64, 16) return out end --- ------------------------------------------------------------------------------------------------ vui @native local function hrd(r: Bitstream.Reader) local cnt = ue(r) if cnt > 31 then @@ -102526,8 +99495,6 @@ end end end --- ------------------------------------------------------------------------------------------------ sps --- sps(r) -> the SPS table | nil, message. r is positioned after the NAL header. @native function Params.sps(r: Bitstream.Reader): (any, string?) local sps: any = {} sps.profile = u(r, 8) @@ -102648,8 +99615,6 @@ end return sps, nil end --- ------------------------------------------------------------------------------------------------ pps --- pps(r, spsTable) -> the PPS | nil, message. spsTable: id -> SPS (needed for the scaling list count) @native function Params.pps(r: Bitstream.Reader, spsTable: { [number]: any }): (any, string?) local pps: any = {} pps.id = ue(r) @@ -102710,7 +99675,6 @@ end return pps, nil end --- ------------------------------------------------------------------------------------------------ dequantisation local V4 = { { 10, 16, 13 }, { 11, 18, 14 }, { 13, 20, 16 }, { 14, 23, 18 }, { 16, 25, 20 }, { 18, 29, 23 } } local V8 = { { 20, 18, 32, 19, 25, 24 }, @@ -102783,7 +99747,6 @@ end return { d4 = d4, d8 = d8 } end --- dequant(sps, pps, cache) -> the dequant tables for this pair (cache: a table kept by the decoder, by content) @native function Params.dequant(sps: any, pps: any, cache: { [string]: any }): any local lists: { { number } } if pps.scalingLists then @@ -102815,9 +99778,8 @@ __FILES["codecs/video/H264/Slice"] = @native function() -- codecs/video/H264/Slice: the slice header (ITU-T H.264 7.3.3): ref_pic_list_modification, pred_weight_table and --- dec_ref_pic_marking. Written from the spec. Frame coding only: field pictures (field_pic_flag = 1), MBAFF, --- SP / SI slices, separate colour planes and redundant pictures return "unsupported: ...". --- Never throws: header() returns nil, "message". +-- dec_ref_pic_marking. Frame coding only: field pictures, MBAFF, SP / SI, separate colour planes and redundant +-- pictures return "unsupported: ...". local Bitstream = __include("codecs/video/H264/Bitstream") local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se @@ -102876,7 +99838,6 @@ end return t end --- header(r, nalType, nalRefIdc, spsTable, ppsTable) -> sh | nil, message @native function Slice.header(r: Bitstream.Reader, nalType: number, nalRefIdc: number, spsTable: { [number]: any }, ppsTable: { [number]: any }): (any, string?) local sh: any = {} sh.nalType = nalType @@ -103067,12 +100028,9 @@ end __FILES["codecs/video/H264/Tables"] = @native function() --- codecs/video/H264/Tables: the constant tables of ITU-T H.264 (CAVLC code tables 9-5, 9-7, 9-8, 9-9, 9-10; CABAC context --- initialisation tables 9-12..9-24, rangeTabLPS 9-44 and the state transitions 9-45; the chroma QP table 8-15; the --- me(v) coded_block_pattern mapping 9-4; default scaling lists 7-3 / 7-4; zig-zag scans 8-12 / 8-13; table 9-43; the --- deblocking alpha / beta / tC0 tables 8-16 / 8-17). Values extracted from openh264 2.x (BSD-2-Clause, --- licenses/openh264-LICENSE.txt): encoder_data_tables.cpp, common_tables.cpp, decoder_data_tables.cpp, --- wels_common_basis.h, deblocking.cpp. Flat 1-based arrays; the layouts are noted at each table. +-- codecs/video/H264/Tables: the constant tables of ITU-T H.264 (CAVLC 9-5, 9-7..9-10; CABAC init 9-12..9-24, +-- rangeTabLPS 9-44, transitions 9-45; chroma QP 8-15; me(v) CBP 9-4; scaling lists 7-3 / 7-4; zig-zag 8-12 / 8-13; +-- 9-43; deblocking 8-16 / 8-17). Values from openh264 2.x (BSD-2-Clause, licenses/openh264-LICENSE.txt). local T = {} -- coeff_token per nC class (0: 0<=nC<2, 1: 2<=nC<4, 2: 4<=nC<8, 3: 8<=nC, 4: nC=-1 chroma DC): { code, len, TotalCoeff, @@ -103112,11 +100070,8 @@ __FILES["codecs/video/H264/Transform"] = @native function() --- codecs/video/H264/Transform: the inverse transforms of ITU-T H.264 8.5: the 4x4 and 8x8 integer IDCTs with the residual --- added to the prediction in the plane (8.5.12.2 / 8.5.13.2 / 8.5.14), the 4x4 luma DC and 2x2 chroma DC Hadamard --- transforms with their scaling (8.5.10 / 8.5.11.2). Written from the spec. Coefficients are dequantised already --- (Params.dequant), raster order, in a 1-based table at `base + 1 ...`; the functions zero what they read. --- Never throws. +-- codecs/video/H264/Transform: the inverse transforms of ITU-T H.264 8.5 (4x4 / 8x8 IDCT 8.5.12.2 / 8.5.13.2 / 8.5.14, +-- luma DC / chroma DC Hadamard 8.5.10 / 8.5.11.2). Coefficients come dequantised, raster order, at base + 1; zeroed after use. local readu8, writeu8 = buffer.readu8, buffer.writeu8 local Transform = {} @@ -103126,9 +100081,7 @@ local min, max = math.min, math.max return min(max(v, 0), 255) end --- add4(c, base, b, o, s): inverse 4x4 transform of c[base + 1 .. base + 16], added to the 4x4 block at b[o] (stride s) @native function Transform.add4(c: { number }, base: number, b: buffer, o: number, s: number) - -- rows for i = 0, 3 do local k = base + i * 4 local d0, d1, d2, d3 = c[k + 1], c[k + 2], c[k + 3], c[k + 4] @@ -103141,7 +100094,6 @@ end c[k + 3] = f - g c[k + 4] = e - h end - -- columns for j = 0, 3 do local k = base + j local d0, d1, d2, d3 = c[k + 1], c[k + 5], c[k + 9], c[k + 13] @@ -103161,7 +100113,6 @@ end end end --- addDc4(dc, b, o, s): a 4x4 block whose only coefficient is the (dequantised) DC @native function Transform.addDc4(dc: number, b: buffer, o: number, s: number) local v = (dc + 32) // 64 if v == 0 then @@ -103178,11 +100129,9 @@ end local T8 = table.create(64, 0) --- add8(c, base, b, o, s): inverse 8x8 transform of c[base + 1 .. base + 64] added to the 8x8 block at b[o] @native function Transform.add8(c: { number }, base: number, b: buffer, o: number, s: number) for pass = 0, 1 do for i = 0, 7 do - -- pass 0: rows of c into T8; pass 1: columns of T8 local d0, d1, d2, d3, d4, d5, d6, d7 if pass == 0 then local k = base + i * 8 @@ -103239,8 +100188,7 @@ local T8 = table.create(64, 0) end end --- lumaDc(dc, m, c): the Intra_16x16 DC levels dc[1..16] (raster 4x4 matrix) -> inverse Hadamard, scaled with the --- DC multiplier m (LevelScale4x4(qP % 6, 0, 0) * 2^(qP / 6)), stored at c[blk * 16 + 1] (blk = raster block index) +-- m = LevelScale4x4(qP % 6, 0, 0) * 2^(qP / 6) @native function Transform.lumaDc(dc: { number }, m: number, c: { number }) for i = 0, 3 do local k = i * 4 @@ -103268,7 +100216,6 @@ end end end --- chromaDc(dc, base, m, c, cbase): the 2x2 chroma DC levels dc[base + 1 .. base + 4] -> c[cbase + blk * 16 + 1] @native function Transform.chromaDc(dc: { number }, base: number, m: number, c: { number }, cbase: number) local c0, c1, c2, c3 = dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] = 0, 0, 0, 0 @@ -103287,23 +100234,8 @@ end __FILES["codecs/video/Legacy"] = function() -- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. --- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk --- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak", --- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation --- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey), QuickTime Graphics ("smc", 'smc ') and Smacker --- video ("smackvid", the frames of video/smk: track.config = the header's tree sizes and trees, codecTag SMK2 / SMK4). --- New in rosetta, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's --- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns --- a fresh copy. --- --- Palettes come from the Track: track.palette (256 u32 entries, bytes R, G, B, A: the AVI BITMAPINFO palette, the --- QuickTime sample description's colour table, ...) and a packet's own `palette` (same layout) replaces it from that --- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth). --- --- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder --- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } --- --- Never throws: bad tracks return nil, Err; bad packets return Err from decode(). +-- From the format descriptions (see each submodule), bit-exact with ffmpeg. Palette: track.palette, replaced by a +-- packet's palette (256 u32 entries R, G, B, A); depth: track.bitsPerPixel (AVI biBitCount, QuickTime depth). local Err = __include("core/Err") local Types = __include("Types") local Picture = __include("codecs/video/Legacy/Picture") @@ -103326,11 +100258,10 @@ Legacy.Smacker = Smacker Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } type Options = { - maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26) + maxPixels: number?, [string]: any, } --- the per-codec pieces: make(track) -> state, step(state, data, packet) -> image? | nil, Err? type Codec = { make: (track: Types.Track) -> (any, string?), step: (st: any, data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), @@ -103452,7 +100383,6 @@ local CODECS: { [string]: Codec } = { }, } --- newDecoder(id, track, opts?) -> a Types.VideoCodecDecoder | nil, Err function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Types.VideoCodecDecoder?, Err.Err?) local codec = CODECS[id] if not codec then @@ -103470,7 +100400,6 @@ function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Typ if not st then return nil, fail(msg) end - -- Video.simpleDecoder, without requiring the registry (which requires this module) local queue: { any } = {} local self = {} function self.decode(_: any, packet: Types.Packet): Err.Err? @@ -103493,7 +100422,7 @@ function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Typ function self.flush(_: any) end function self.reset(_: any) table.clear(queue) - st = codec.make(track) or st -- back to a black picture with the track's palette (decoding restarts at a keyframe) + st = codec.make(track) or st end return self :: any, nil end @@ -103504,14 +100433,10 @@ __FILES["codecs/video/Legacy/Cinepak"] = @native function() --- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames: 24-bit colour (codebook entries of 4 luma + 2 chroma, or 4 --- luma for grey), and 8-bit palettised streams (entries are palette indexes). Written from the format description --- (MultimediaWiki "Cinepak"): a frame header (flags, size, width, height, strip count), strips with their own V1 / V4 --- codebooks (full or partial updates, kept per strip between frames, inherited from the strip above unless the frame --- flags say otherwise) and the vector chunks (intra, inter with skip flags, V1-only). Colour codebook entries are --- converted once with the Cinepak YUV formula (r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped). Sega FILM's extra --- header bytes are detected on the first frame. Paints over the previous picture. Bit-exact with ffmpeg's cinepak --- decoder. Never throws: every read is range-checked against its chunk. +-- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames, 24-bit colour and 8-bit palettised. +-- From MultimediaWiki "Cinepak", bit-exact with ffmpeg: a frame header (flags, size, width, height, strip count), strips +-- with V1 / V4 codebooks (inherited from the strip above unless the flags say otherwise) and vector chunks. +-- Colour entries: r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped. local Picture = __include("codecs/video/Legacy/Picture") local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 @@ -103596,7 +100521,7 @@ end end end --- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only); false on truncated data +-- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only) @native local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number, stop: number, x1: number, y1: number, x2: number, y2: number): boolean local stride = pic.stride @@ -103697,8 +100622,6 @@ end return true end --- decode(pic, data, state, hasPalette) -> picture?, message: true = a picture; false + nil = no picture for this --- packet (an empty frame); false + message = an error @native function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?) local n = buffer.len(d) if n < 10 then @@ -103741,7 +100664,6 @@ end local p = 10 + skip strips = math.min(strips, MAX_STRIPS) local books = st.books - -- the coded area: the size rounded up to whole blocks (the picture's plane) local cw, ch = pic.stride, pic.rows local y0 = 0 for i = 0, strips - 1 do @@ -103766,7 +100688,6 @@ end if i > 0 and band(flags, 1) == 0 then buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK) end - -- the strip's chunks: codebooks, then one vector chunk -- (strips start on block boundaries in every known stream: the plane holds whole blocks only) if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then return true, nil @@ -103809,15 +100730,12 @@ __FILES["codecs/video/Legacy/Flic"] = @native function() --- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is --- video/fli). Written from the FLIC file format description (Jim Kent's "FLC - Animator Pro Flic Files", Dr. Dobb's --- 1993; MultimediaWiki "Flic Video"). 8-bit palettised: COLOR_256 (4), COLOR_64 (11, 6-bit entries widened by bit --- replication), DELTA_FLC / SS2 (7: word runs, line skips, last-byte opcode), DELTA_FLI / LC (12: byte runs), BLACK --- (13), BYTE_RUN / BRUN (15), FLI_COPY (16, rows padded to 4), PSTAMP (18, skipped). 15 / 16 / 24-bit FLC and FLX --- (DTA): DELTA / DTA_LC (pixel runs), BLACK, BRUN (byte runs), DTA_BRUN (25, pixel runs), COPY / DTA_COPY (16 / 26); --- pixels are 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. Not supported: 1-bit FLICs, the Magic Carpet --- 6-bit COLOR_256 variant. Paints over the previous picture. Bit-exact with ffmpeg's flic decoder on valid frames. --- Never throws: reads past the frame give zeros, every write is range-checked (a damaged frame gives no picture). +-- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is video/fli). +-- From Jim Kent's "FLC - Animator Pro Flic Files" (Dr. Dobb's 1993) and MultimediaWiki "Flic Video", bit-exact with +-- ffmpeg. 8-bit: COLOR_256 (4), COLOR_64 (11), DELTA_FLC / SS2 (7), DELTA_FLI / LC (12), BLACK (13), BYTE_RUN / BRUN +-- (15), FLI_COPY (16, rows padded to 4), PSTAMP (18). 15 / 16 / 24-bit FLC and FLX (DTA): DELTA / DTA_LC, BLACK, BRUN, +-- DTA_BRUN (25), COPY / DTA_COPY (16 / 26); 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. +-- Not supported: 1-bit FLICs, the Magic Carpet 6-bit COLOR_256 variant. local Types = __include("Types") local Picture = __include("codecs/video/Legacy/Picture") @@ -103826,14 +100744,12 @@ local bfill = buffer.fill local Flic = {} --- the decoding state of one stream: a byte plane (stride = width * bytes per pixel) and the palette type State = { pic: Picture.Picture, depth: number, -- 8, 15, 16, 24 - bpp: number, -- bytes per pixel + bpp: number, } --- state(w, h, depth) -> State | nil, message @native function Flic.state(w: number, h: number, depth: number): (State?, string?) local bpp = if depth == 8 then 1 elseif depth == 15 or depth == 16 then 2 elseif depth == 24 then 3 else 0 if bpp == 0 then @@ -103848,7 +100764,6 @@ end return if v >= 128 then v - 256 else v end --- decode(st, data) -> true | false, message @native function Flic.decode(st: State, d: buffer): (boolean, string?) local pic = st.pic local px = pic.idx :: buffer @@ -104144,7 +101059,6 @@ end return true, nil end --- image(st) -> a fresh rgba8 Image @native function Flic.image(st: State): Types.Image local pic = st.pic if st.bpp == 1 then @@ -104183,12 +101097,10 @@ __FILES["codecs/video/Legacy/Msvideo1"] = @native function() --- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM) frames, 8-bit palettised and 16-bit --- X-R-G-B 1-5-5-5. Written from the format description (MultimediaWiki "Microsoft Video 1"): 4x4 blocks, block rows --- bottom-up (rows of a block bottom-up too), each block a 16-bit code: a skip count (0x84xx - 0x87xx), a 2-colour --- block (16 flag bits + 2 colours; at 16 bits a first colour with bit 15 set makes it an 8-colour block, one colour --- pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), or a 1-colour block. Paints over the previous picture. --- Bit-exact with ffmpeg's msvideo1 decoder. Never throws: every read is range-checked (a damaged frame stops there). +-- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM), 8-bit palettised and 16-bit X-R-G-B 1-5-5-5. +-- From MultimediaWiki "Microsoft Video 1", bit-exact with ffmpeg: 4x4 blocks, block rows (and rows in a block) bottom-up; +-- a 16-bit code per block: skip (0x84xx - 0x87xx), 2-colour (16 flag bits + 2 colours; at 16 bits c0 bit 15 set = 8-colour, +-- a pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), else 1-colour. local Picture = __include("codecs/video/Legacy/Picture") local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 @@ -104196,13 +101108,11 @@ local band = bit32.band local Msvideo1 = {} --- the colour of pixel (x, y) of a block (y = 0 is the block's bottom row) for flag bit f: 2-colour c0 / c1 --- (bit set = c0), 8-colour: colours[quadrant * 2 + (bit clear)] +-- 2-colour: bit set = c0; 8-colour: colours[quadrant * 2 + (bit clear)] @native local function quadrant(x: number, y: number): number return (if y >= 2 then 4 else 0) + (if x >= 2 then 2 else 0) end --- decode(pic, data, bits) -> true | false, message (bits = 8: palettised, else 16-bit) @native function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?) local n = buffer.len(d) local bw, bh = pic.w // 4, pic.h // 4 @@ -104232,7 +101142,6 @@ end if a == 0 and b == 0 and total == 0 then return true, nil end - -- the block's bottom-left pixel; its rows go up local o = (by * 4 + 3) * stride + bx * 4 if band(b, 0xFC) == 0x84 then skip = (b - 0x84) * 256 + a - 1 @@ -104306,11 +101215,8 @@ __FILES["codecs/video/Legacy/Picture"] = @native function() --- codecs/video/Legacy/Picture: the picture every legacy decoder keeps between frames (they are all inter-frame --- codecs: a packet paints over the previous picture). Palettised codecs keep a u8 index plane and a 256-entry palette, --- direct-colour ones an rgba8 plane; both planes are padded (stride / rows) so the codecs' block and run writes past --- the visible edge land in range. Also the 5-5-5 / 5-6-5 to 8-bit tables: channels are widened by bit replication --- (c << 3 | c >> 2), as ffmpeg's swscale does, so the output equals ffmpeg's rgba conversion. New in rosetta. +-- codecs/video/Legacy/Picture: the picture the legacy inter-frame decoders paint over (u8 index plane + palette or rgba8). +-- 5-5-5 / 5-6-5 widen by bit replication (c << 3 | c >> 2), as ffmpeg's swscale does. local Types = __include("Types") local Pixels = __include("codecs/image/Pixels") @@ -104328,7 +101234,6 @@ type Picture = { pal: buffer, -- 256 u32 entries, bytes R, G, B, A } --- new(w, h, palettised, padW?, padH?, palette?) -> a black picture; padW / padH round the plane up (blocks of 4, ...) @native function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture local pw, ph = padW or 1, padH or 1 local stride = ((w + pw - 1) // pw) * pw @@ -104346,7 +101251,6 @@ type Picture = { return p end --- image(p) -> a fresh rgba8 Image of the visible w x h @native function Picture.image(p: Picture): Types.Image local w, h = p.w, p.h local img = Types.Image.new(w, h, "rgba8") @@ -104365,7 +101269,6 @@ end return img end --- setPalette(p, src): a 1024-byte palette (u32 R, G, B, A entries) from a packet or the track @native function Picture.setPalette(p: Picture, src: buffer) if buffer.len(src) >= 1024 then buffer.copy(p.pal, 0, src, 0, 1024) @@ -104375,7 +101278,6 @@ end local lut555: buffer? = nil local lut565: buffer? = nil --- rgb555() -> u32 table: X-R-G-B 1-5-5-5 value -> rgba8 pixel (opaque); 32768 entries @native function Picture.rgb555(): buffer local t = lut555 if t then @@ -104391,7 +101293,6 @@ local lut565: buffer? = nil return b end --- rgb565() -> u32 table: R-G-B 5-6-5 value -> rgba8 pixel; 65536 entries @native function Picture.rgb565(): buffer local t = lut565 if t then @@ -104407,7 +101308,6 @@ end return b end --- copy of a picture's plane (for decoders that read the previous picture while writing the next) @native function Picture.clonePlane(p: Picture): buffer local src = (p.idx or p.rgba) :: buffer local c = buffer.create(buffer.len(src)) @@ -104423,14 +101323,11 @@ __FILES["codecs/video/Legacy/QtRle"] = @native function() --- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey) and --- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). Written from the format description (Apple QuickTime File --- Format; MultimediaWiki "Apple QuickTime RLE"): a chunk size, a header (0x0008: start line + line count), then per --- line a skip byte and run codes until -1 (0: another skip; < 0: one pixel group repeated; > 0: literal groups). --- Groups are 4 pixels at 8 bits, 8 at 4 bits, 16 at 2 bits, 1 pixel at 16 / 24 / 32 bits; the 1-bit layout has its --- own (skip, code) pairs where a skip with bit 7 set moves to the next line. Paints over the previous picture; frames --- shorter than 8 bytes repeat it. Bit-exact with ffmpeg's qtrle decoder on valid streams. Never throws: every read --- and write is range-checked (a damaged frame stops where the damage is). +-- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey), +-- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). From Apple QuickTime File Format and MultimediaWiki "Apple +-- QuickTime RLE", bit-exact with ffmpeg on valid streams: chunk size, header (0x0008: start line + line count), per line +-- a skip byte and codes until -1 (0: another skip; < 0: one group repeated; > 0: literal groups). Groups are 4 pixels at +-- 8 bits, 8 at 4, 16 at 2, 1 at 16 / 24 / 32. Frames shorter than 8 bytes repeat the picture. local Picture = __include("codecs/video/Legacy/Picture") local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 @@ -104505,8 +101402,8 @@ end -- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups @native local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number) - local group = 32 // bpp -- pixels per 4 bytes - local per = 8 // bpp -- pixels per byte + local group = 32 // bpp + local per = 8 // bpp local mask = 2 ^ bpp - 1 for _ = 1, lines do if p >= n then @@ -104646,11 +101543,10 @@ end end end --- decode(pic, data, depth) -> true (a picture, possibly the previous one again) | false, message @native function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?) local n = buffer.len(d) if n < 8 then - return true, nil -- no change + return true, nil end local p = 4 local header = readu8(d, p) * 256 + readu8(d, p + 1) @@ -104686,7 +101582,6 @@ end return true, nil end --- palettised(depth) -> whether the depth uses a palette; pad(depth) -> the row padding the plane needs @native function QtRle.palettised(depth: number): boolean return depth <= 8 or depth > 32 end @@ -104702,17 +101597,12 @@ __FILES["codecs/video/Legacy/Smacker"] = @native function() -- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and --- the Huffman trees Smacker audio shares. Written from the format description (MultimediaWiki "Smacker"). Bits are --- read LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf with its value); --- an 8-bit tree's leaves hold bytes, a "big" tree's leaves hold 16-bit values made of a low-byte and a high-byte --- 8-bit tree, three of them being escape leaves that return the three most recently decoded values instead (a --- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header; --- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a --- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour). --- Trees are flat arrays (a node stores the size of its left subtree, as a negative number); the frame decoder reads --- 10 bits at a time through a lookup table into them. --- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give --- zero bits, a frame whose codes run out of bits gives no picture. +-- the Huffman trees Smacker audio shares. From MultimediaWiki "Smacker", bit-exact with ffmpeg's smackvid. +-- Bits LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf). A big tree's 16-bit +-- leaves pair a low-byte and a high-byte 8-bit tree; three escape leaves return the three most recently decoded values +-- (reset each frame). The header holds the MMAP, MCLR, FULL and TYPE big trees; a frame is 4x4 blocks in raster order, +-- each TYPE code a block type and run length: MONO (two colours + 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds +-- 2x2- and 2x1-doubled modes), SKIP, FILL. local Picture = __include("codecs/video/Legacy/Picture") local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 @@ -104730,7 +101620,6 @@ for i = 1, 59 do end RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048 --- a bit position over buf[0, nbits / 8) type Bits = { buf: buffer, pos: number, nbits: number } @native function Smacker.bits(buf: buffer, offset: number, length: number): Bits @@ -104747,7 +101636,6 @@ end end Smacker.bit = bit --- read(br, n) -> n bits (LSB first; zeros past the end) @native function Smacker.read(br: Bits, n: number): number local v, m = 0, 1 for _ = 1, n do @@ -104758,7 +101646,7 @@ Smacker.bit = bit end local readBits = Smacker.read --- walk(tree, br) -> the leaf value (no end-of-data check: 8-bit trees, as the reference's table lookups) +-- no end-of-data check for 8-bit trees, as the reference's table lookups @native local function walk(tree: { number }, br: Bits): number local i = 1 local e = tree[1] @@ -104773,7 +101661,6 @@ local readBits = Smacker.read end Smacker.walk = walk --- the pre-order tree reader: leaf(index) -> value | nil, message; returns the flat tree (1-based) @native local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?) local vals: { number } = {} local n = 0 @@ -104820,7 +101707,6 @@ Smacker.walk = walk end end --- tree8(br) -> an 8-bit tree (leaves are bytes) | nil, message @native function Smacker.tree8(br: Bits): ({ number }?, string?) local leaves = 0 return build(br, MAX_DEPTH8, 511, @native function(_: number): (number?, string?) @@ -104838,7 +101724,6 @@ local tree8 = Smacker.tree8 type BigTree = { vals: { number }, last: { number }, lut: buffer? } -- last: the escape leaves' indexes (1-based) --- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries) @native local function bigTree(br: Bits, size: number): (BigTree?, string?) if bit(br) == 0 then return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0 @@ -104884,7 +101769,7 @@ end type Trees = { mmap: BigTree, mclr: BigTree, full: BigTree, type: BigTree } --- trees(config) -> the four header trees | nil, message. config = the four u32 tree sizes then the tree bits +-- config = the four u32 tree sizes, then the tree bits @native function Smacker.trees(config: buffer): (Trees?, string?) local n = buffer.len(config) if n <= 16 then @@ -104941,7 +101826,6 @@ end vals[last[1]], vals[last[2]], vals[last[3]] = 0, 0, 0 end --- decode(pic, data, trees, v4) -> true | false, message. pic: palettised, padded to blocks of 4 @native function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?) local px = pic.idx :: buffer local stride = pic.stride @@ -104955,7 +101839,6 @@ end local n = buffer.len(d) local nbits = n * 8 local pos = 0 - -- the next value of a tree (updating its recent-value cache) | -1 when the bits run out inside the tree @native local function code(t: BigTree): number local vals = t.vals local i, p @@ -105108,13 +101991,9 @@ __FILES["codecs/video/Legacy/Smc"] = @native function() --- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised. Written from the format description --- (MultimediaWiki "Apple SMC"): 4x4 blocks in raster order, opcodes in the high nibble with a block count (low nibble --- + 1, or the next byte + 1 when bit 4 is set): skip, repeat the last block, repeat the last pair of blocks, 1-colour --- fill, 2 / 4 / 8-colour blocks (the colour groups go into 256-entry rotating tables, or come from them by index: --- the tables restart every frame) and 16-colour blocks. Paints over the previous picture. Bit-exact with ffmpeg's smc --- decoder (for widths whose rows are not padded: the previous block of a row start is the last block of the row --- above). Never throws: reads past the data give zeros, the block count bounds every write. +-- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised; from MultimediaWiki "Apple SMC", +-- bit-exact with ffmpeg. 4x4 blocks in raster order; opcode in the high nibble, count = low nibble + 1 (bit 4: next +-- byte + 1); the colour-group tables restart every frame. As ffmpeg: a row start's previous block ends the row above. local Picture = __include("codecs/video/Legacy/Picture") local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 @@ -105122,7 +102001,6 @@ local band, rshift = bit32.band, bit32.rshift local Smc = {} --- decode(pic, data, tables) -> true | false, message. tables = Smc.tables() (scratch, reused between frames) @native function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?) local px = pic.idx :: buffer local n = buffer.len(d) @@ -105134,7 +102012,6 @@ local Smc = {} end local blocksWide = (pic.w + 3) // 4 local p = 4 -- flags byte + 24-bit chunk size - -- block position: bx, by (blocks) local bx, by = 0, 0 local pairI, quadI, octI = 0, 0, 0 -- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8) @@ -105266,7 +102143,6 @@ local Smc = {} advance() end else - -- 16-colour blocks for _ = 1, count do if total <= 0 or by >= bh then break @@ -105282,7 +102158,6 @@ local Smc = {} return true, nil end --- tables() -> the colour group scratch (pairs, quads, octets) @native function Smc.tables(): buffer return buffer.create(512 + 1024 + 2048) end @@ -105291,9 +102166,8 @@ return Smc end __FILES["codecs/video/Mpeg1"] = function() --- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder --- decodes MPEG-1 streams): this module keeps the old name and API (Mpeg1.new, frameImage, PICTURE_*, the Frame / --- Options / Decoder types). Absorbed from mpeg1-luau e2e2898 (same author); see codecs/video/Mpeg2. +-- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), the old name and API over codecs/video/Mpeg2. +-- From mpeg1-luau e2e2898 (same author). local Mpeg2 = __include("codecs/video/Mpeg2") type Frame = Mpeg2.Frame @@ -105305,24 +102179,9 @@ end __FILES["codecs/video/Mpeg2"] = function() -- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile). --- Progressive and interlaced (frame and field pictures, field / dual-prime prediction, field DCT), 4:2:0 and 4:2:2, I / --- P / B pictures with display reordering, every MPEG-2 coding tool of Main profile (Mpeg2/Decoder.luau). Output planes --- are bit-exact with `ffmpeg -idct int` (codecs/video/Dsp; tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Grown from --- the MPEG-1 decoder absorbed from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder --- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). codecs/video/Mpeg1 is this --- module under its old name. Frames come out woven (both fields of an interlaced frame, top field on even lines); --- frame.fields / topFieldFirst / repeatFirstField / progressive say how they were coded. --- Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped). --- --- local dec = Mpeg2.new({ reorder = true, rgba = false }) --- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts --- local img = Mpeg2.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true)) --- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces --- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek --- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, chroma, ... } --- local vdec = Mpeg2.newVideoDecoder(track, opts) -- a Types.VideoCodecDecoder (codecs/video/Video: mpeg1, mpeg2) --- --- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). +-- Bit-exact with `ffmpeg -idct int`. Grown from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder +-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). Frames come out woven (top +-- field on even lines). Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped). local Types = __include("Types") local Err = __include("core/Err") local D = __include("codecs/video/Mpeg2/Decoder") @@ -105339,10 +102198,9 @@ type Frame = { pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false } pictureType: number, -- 1 I, 2 P, 3 B temporalReference: number, -- the picture's 10-bit display index within its GOP - index: number, -- frames returned so far (1-based) - tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering) - -- the decoded YCbCr planes (decoder-owned, valid until the next decode): luma stride codedWidth, chroma stride - -- codedWidth / 2, chroma rows half the luma rows (4:2:0) or as many (4:2:2) + index: number, + tag: any, + -- luma stride codedWidth, chroma stride codedWidth / 2; chroma rows half the luma rows (4:2:0) or as many (4:2:2) y: buffer, cb: buffer, cr: buffer, @@ -105350,23 +102208,17 @@ type Frame = { chroma: number, -- 1 = 4:2:0, 2 = 4:2:2 mpeg2: boolean, progressive: boolean, -- progressive_frame (MPEG-1 and progressive MPEG-2: true) - fields: boolean, -- coded as two field pictures + fields: boolean, topFieldFirst: boolean, repeatFirstField: boolean, - clamped: number, -- predictions from outside the reference picture (an invalid stream; edge samples repeated) - concealed: { [number]: boolean }, -- 16-line bands with macroblocks no slice covered (concealed) + clamped: number, + concealed: { [number]: boolean }, } type Options = { - reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the - -- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is - -- display order for streams without B-frames. - rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr) - maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304) - -- a cooperative yield point, run after every slice and every 16 rows of colour conversion: e.g. a function that - -- calls coroutine.yield() when a time budget is spent, to spread a picture over several frames (the decode call - -- then runs inside a coroutine). Don't call this decoder again while a decode is suspended. Errors in it are - -- ignored. See dec:setYield. + reorder: boolean?, + rgba: boolean?, + maxPixels: number?, yield: (() -> ())?, } @@ -105459,7 +102311,6 @@ local function sync(self: Decoder) self.stats.skipped = st.skipped end --- a decoded picture -> the frame to return now (nil while reordering holds it) local function handle(self: Decoder, s: D.Store): Frame? if not self._reorder or s.ptype == D.PICTURE_B then return emit(self, s) @@ -105510,19 +102361,14 @@ local function append(self: Decoder, data: any, offset: number?, len: number?): return true end --- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument. function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean return append(self, data, offset, len) end --- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is --- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one). function Decoder.decodeFrame(self: Decoder): Frame? return run(self, false, nil) end --- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data). --- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag. function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame? if not append(self, data, offset, len) then return nil @@ -105530,8 +102376,6 @@ function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, l return run(self, true, tag) end --- At the end of the stream: decodes what is left of the written data, then returns the reference picture held --- for reordering. Call until it returns nil. function Decoder.flush(self: Decoder): Frame? local f = run(self, true, nil) if f then @@ -105545,24 +102389,15 @@ function Decoder.flush(self: Decoder): Frame? return nil end --- Sets (or clears, nil) the cooperative yield hook (Options.yield). function Decoder.setYield(self: Decoder, hook: (() -> ())?) self._core.setYield(if type(hook) == "function" then hook else nil) end --- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture). function Decoder.reset(self: Decoder) self._core.reset() self._held = nil end --- YCbCr 4:2:0 planes (a frame's y / cb / cr / codedWidth, or copies of them) -> RGBA8 rows row0 .. row1 - 1 of a --- width x height picture, written to out from byte outOffset (default 0) as (row1 - row0) rows of width * 4 bytes. --- row0 is rounded down to even (rows share chroma in pairs); defaults 0 and height. Lets the conversion run in --- bands (on several threads) or only for the frames that are shown. The planes may hold only rows planeRow0 .. --- (planeRow0 even, default 0; their row 0 is picture row planeRow0). hook: a cooperative yield point every 16 rows. --- Returns false (writing nothing) when an argument is out of range. (4:2:0 only: a 4:2:2 frame's chroma has as many --- rows as its luma; use frameImage(frame, true) for those.) function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, width: number, height: number, out: buffer, row0: number?, row1: number?, outOffset: number?, planeRow0: number?, hook: (() -> ())?): boolean if type(y) ~= "buffer" or type(cb) ~= "buffer" or type(cr) ~= "buffer" or type(out) ~= "buffer" then return false @@ -105579,7 +102414,6 @@ function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, wid if r0 < 0 or r1 > h or r1 <= r0 or pr < 0 or pr % 2 ~= 0 or pr > r0 or oo < 0 or oo % 4 ~= 0 then return false end - -- the planes must cover rows pr .. r1 - 1 (luma) and their chroma rows; out the band local lumaRows = r1 - pr local chromaRows = (r1 + 1) // 2 - pr // 2 if buffer.len(y) < lumaRows * cw or buffer.len(cb) < chromaRows * (cw // 2) or buffer.len(cr) < chromaRows * (cw // 2) then @@ -105588,15 +102422,10 @@ function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, wid if buffer.len(out) < oo + (r1 - r0) * w * 4 then return false end - -- rows relative to the planes' first row D.toRgba(y, cb, cr, cw, w, h, out, r0 - pr, r1 - pr, oo, if type(hook) == "function" then hook else nil) return true end --- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to --- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"; 4:2:2 chroma --- averaged over line pairs of the same field), or rgba8 (the decoder's BT.601 conversion) when rgba is true. nil for --- a value that is not a Frame. function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image? if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then return nil @@ -105665,10 +102494,6 @@ function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image? return img end --- ------------------------------------------------------------------------------------------------ VideoCodecDecoder --- newVideoDecoder(track, opts) -> a Types.VideoCodecDecoder (codecs/video/Video's mpeg1 and mpeg2 entries): pictures in --- decode order, reordered for display; the packet's pts travels with its picture. A packet may hold any number of --- pictures (MPEG-PS / TS units, AVI chunks) or part of one (written as a stream). function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) local queue: { any } = {} @@ -105687,7 +102512,7 @@ function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecode if not ok then return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f)) end - while f do -- more pictures in the packet + while f do push(f) f = dec:decode(packet.data, 0, 0, tag) end @@ -105721,25 +102546,10 @@ end __FILES["codecs/video/Mpeg2/Decoder"] = @native function() --- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (native, never throws). --- ISO/IEC 11172-2 and ISO/IEC 13818-2 Main profile: I, P and B pictures; progressive and interlaced sequences; frame --- pictures (frame / field motion compensation, frame / field DCT) and field pictures (field and 16x8 motion --- compensation, the second field predicted from the first); dual-prime; 4:2:0 and 4:2:2; intra DC precision 8..11; --- linear and non-linear quantiser scales; Table B-15 intra VLCs; the alternate scan; custom (and chroma) quantiser --- matrices; mismatch control; concealment motion vectors; sequence headers anywhere (size changes). Not supported: --- 4:4:4, the scalable / multiview extensions, D-pictures (skipped). --- --- Grown from the MPEG-1 core absorbed from mpeg1-luau e2e2898 (same author; a port of jsmpeg's decoder, src/mpeg1.js --- by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt, with table-driven VLCs, B-pictures and SWAR motion --- compensation). The IDCT and motion compensation are codecs/video/Dsp (the IDCT bit-exact with ffmpeg's -idct int), --- and dequantisation follows ffmpeg's arithmetic, so the output planes equal `ffmpeg -idct int` decoding for valid --- streams (tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Coefficients are saturated to -2048..2047 (13818-2 --- 7.4.3; ffmpeg omits it, valid streams never reach it) and motion vectors pointing outside the reference are --- clamped (ffmpeg skips the prediction): both only matter for corrupt data. --- --- Everything works on flat buffers allocated per sequence size: no allocation per block, macroblock or picture. --- Every read position is checked against the data end (plus a zero pad that bounds the overrun of one macroblock), --- motion vectors are clamped to the reference picture, and bad data ends the slice instead of raising. +-- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (ISO/IEC 11172-2, 13818-2 Main profile). +-- From mpeg1-luau e2e2898 (same author; a port of jsmpeg's src/mpeg1.js by Dominic Szablewski, MIT, +-- licenses/jsmpeg-MIT.txt). Dequantisation follows ffmpeg's arithmetic; coefficients are saturated to -2048..2047 +-- (13818-2 7.4.3; ffmpeg omits it) and vectors outside the reference are clamped (ffmpeg skips the prediction). local V = __include("codecs/video/Mpeg2/Vlc") local T = __include("codecs/video/Mpeg2/Tables") local Dsp = __include("codecs/video/Dsp") @@ -105804,17 +102614,13 @@ local RBIAS = COFF * 256 - 298 * 16 - 409 * 128 - 128 local GBIAS = COFF * 256 - 298 * 16 + 100 * 128 + 208 * 128 - 160 local BBIAS = COFF * 256 - 298 * 16 - 516 * 128 - 72 --- clamp to 0..255 by lookup: RGB_CLAMP[v + COFF] = clamp(v, 0, 255) for v in [-COFF, COFF + 255] (the colour biases --- include COFF * 256, so the shifted sums below are indices): the same values as math.clamp, 2-3x faster natively +-- clamp by lookup: RGB_CLAMP[v + COFF] for v in [-COFF, COFF + 255]; the colour biases include COFF * 256 local RGB_CLAMP = buffer.create(2 * COFF + 256) for i = 0, 2 * COFF + 255 do buffer.writeu8(RGB_CLAMP, i, math.clamp(i - COFF, 0, 255)) end --- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path. --- Rows row0 .. row1 - 1 of the planes (row0 even; default 0 .. h) into out from byte oo (default 0). hook (optional) --- runs every 16 rows (a cooperative yield point; it is pcall'ed, so it can't throw through here). (From mpeg1-luau's --- later banded conversion.) +-- 4:2:0 -> RGBA8 with nearest chroma, like ffmpeg's default swscale path; hook is pcall'ed (can't throw through here) @native local function toRgba(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer, row0: number?, row1: number?, oo: number?, hook: (() -> ())?) -- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four local r0: number = row0 or 0 @@ -105908,16 +102714,10 @@ type Store = { } type Core = { - -- data write: (src: buffer, off: number, n: number) -> (), - -- decodes the next picture; atEnd: the end of the data ends the picture. Returns the store decoded into (nil when - -- no picture is complete or it could not be decoded), and whether more data is needed. A frame coded as two field - -- pictures comes back once, after its second field. nextPicture: (atEnd: boolean, tag: any) -> (Store?, boolean), toRgba: (s: Store, out: buffer) -> (), reset: () -> (), - -- a cooperative yield point (e.g. coroutine.yield when over a time budget), run after every slice and every 16 - -- rows of colour conversion; nil = none. pcall'ed: it can't throw through the native code. setYield: (hook: (() -> ())?) -> (), state: { width: number, @@ -105965,7 +102765,6 @@ type Core = { refNew = nil :: Store?, } - -- bitstream local data = buffer.create(64 * 1024 + PAD) local dataLen = 0 local readByte = 0 -- next byte to look at for a start code @@ -105973,7 +102772,6 @@ type Core = { local pos = 0 -- bit position inside data local err = false - -- sequence local hasSeq = false local mpeg2 = false local chroma = 1 -- 1 = 4:2:0, 2 = 4:2:2 @@ -105994,7 +102792,6 @@ type Core = { -- the sequence header's values, applied (and the stores allocated) once its extension has been seen local seqW, seqH = 0, 0 - -- picture local ptype = 0 local fc00, fc01, fc10, fc11 = 1, 1, 1, 1 -- f_code[s][t] local fullPelFw, fullPelBw = false, false @@ -106020,7 +102817,6 @@ type Core = { local pendingFw: Store? = nil local pendingBw: Store? = nil - -- slice / macroblock local qscale = 2 local mbAddr, mbRow, mbCol = 0, 0, 0 local dcY, dcCb, dcCr = 128, 128, 128 @@ -106063,7 +102859,6 @@ type Core = { return band(e, 0xFFFF) - 32768 end - -- byte offset of the next 00 00 01 xx at or after from (with xx before to), or -1 @native local function findStart(from: number, to: number): number local i = from while i + 3 < to do @@ -106117,7 +102912,6 @@ type Core = { end end - -- the sequence (header + extension) takes effect: sizes and stores @native local function applySequence(): boolean local w, h = seqW, seqH if w == 0 or h == 0 or w * h > state.maxPixels then @@ -106149,7 +102943,6 @@ type Core = { return true end - -- sequence header at byte p (after the start code); false when invalid @native local function sequenceHeader(p: number): boolean pos = p * 8 local w = read(12) @@ -106266,11 +103059,6 @@ type Core = { return (pred + d + range) % (2 * range) - range end - -- ------------------------------------------------------------------------------------------------ prediction - -- One prediction of the current macroblock part from the reference planes rY / rCb / rCr: field-based (sp >= 0: - -- source field sp, destination field dp of the frame, line stride 2 * cw) or frame-based (sp < 0); rowY / h: the - -- first luma line of the part in those lines and its height; (mvx, mvy) in half samples; avg averages into the - -- first prediction. local EDGE = buffer.create(Dsp.EDGE_SIZE) @native local function mcPart(rY: buffer, rCb: buffer, rCr: buffer, sp: number, dp: number, rowY: number, h: number, mvx: number, mvy: number, avg: boolean) local stride, sb, db, ph = cw, 0, 0, lumaH @@ -106279,7 +103067,6 @@ type Core = { stride, sb, db, ph = 2 * cw, sp * cw, dp * cw, lumaH // 2 cs, csb, cdb = 2 * chw, sp * chw, dp * chw end - -- luma local hx, hy = band(mvx, 1), band(mvy, 1) local sx = mbCol * 16 + (mvx - hx) // 2 local sy = rowY + (mvy - hy) // 2 @@ -106344,7 +103131,6 @@ type Core = { return (bwS or cur) :: Store end - -- the prediction of direction d (0 forward, 1 backward); avg: the second one of a bidirectional macroblock @native local function predictDir(d: number, avg: boolean) local o = d * 8 if not fieldPic then @@ -106388,7 +103174,6 @@ type Core = { end end - -- the prediction of a non-intra macroblock from the current motion state @native local function predictMb() if ptype == 2 then predictDir(0, false) @@ -106422,10 +103207,8 @@ type Core = { end end - -- Macroblocks no slice covers. ffmpeg's encoder skips the last macroblock of a row at the end of an MPEG-1 - -- slice (the next slice starts on the next row), and ffmpeg's decoder conceals it as a skipped macroblock; so do - -- we: P (and a damaged I) copies the reference with a zero vector, B repeats the prediction of the macroblock - -- before the gap. + -- macroblocks no slice covers: ffmpeg's encoder skips a row's last macroblock at an MPEG-1 slice end and its decoder + -- conceals it as skipped; so do we (P / damaged I: zero-vector copy, B: the prediction before the gap) local covered = 0 local gapFw, gapBw = false, false local GAP = table.create(16, 0) @@ -106482,9 +103265,7 @@ type Core = { FSEL[1], FSEL[2], FSEL[3], FSEL[4] = f1, f2, f3, f4 end - -- ------------------------------------------------------------------------------------------------ blocks - -- one 8x8 block b (0..3 luma, then Cb / Cr alternating): coefficients, dequantisation, IDCT into the picture. - -- False on a bitstream error. + -- block b: 0..3 luma, then Cb / Cr alternating @native local function decodeBlock(b: number): boolean local n = 0 local q: buffer @@ -106549,7 +103330,6 @@ type Core = { local qs = qscale local m2 = mpeg2 while true do - -- inline peek local bp = rshift(pos, 3) local w = bswap(readu32(data, bp)) local s = band(pos, 7) @@ -106632,7 +103412,7 @@ type Core = { if m2 then parityOdd = bxor(parityOdd, band(m, 1)) end - -- saturate + -- saturation (13818-2 7.4.3) if m > 2047 then m = 2047 elseif m < -2048 then @@ -106650,7 +103430,6 @@ type Core = { writei32(blk, 252, if v % 2 ~= 0 then v - 1 else v + 1) onlyDc = false end - -- reconstruction local dst, off, stride if luma then dst = curY @@ -106694,7 +103473,6 @@ type Core = { return true end - -- ------------------------------------------------------------------------------------------------ macroblocks @native local function getQscale(code: number): number if qScaleType == 1 then return readu8(NON_LINEAR, code) @@ -106772,7 +103550,6 @@ type Core = { end end - -- one macroblock (with the skipped ones before it). False on a bitstream error or the end of the slice data. @native local function decodeMacroblock(first: boolean, endBits: number): boolean local inc = 0 local t = vlc(MBAI, MBAI_BITS) @@ -106974,7 +103751,6 @@ type Core = { end end - -- ------------------------------------------------------------------------------------------------ pictures -- the frame a picture completes becomes the newest reference (I / P) @native local function finishFrame(s: Store) if s.ptype ~= 3 then @@ -106983,8 +103759,7 @@ type Core = { end end - -- The picture header at byte p (after 00 00 01 00) and its extensions, up to stop: the byte of the first slice - -- start code (-1: none) and the temporal reference, or nil when the picture is skipped + -- the picture header (after 00 00 01 00) and its extensions @native local function pictureHeader(p: number, stop: number): (number?, number) pos = p * 8 local tref = read(10) @@ -107037,7 +103812,6 @@ type Core = { return at, tref end - -- the frame the picture decodes into (the pending one for a second field) and its references; false: skipped @native local function selectTarget(tref: number, tag: any): boolean fieldPic = picStruct ~= 3 parity = if picStruct == 2 then 1 else 0 @@ -107091,7 +103865,6 @@ type Core = { return true end - -- plane addressing of the current picture @native local function setAddressing() local target = cur :: Store curY, curCb, curCr = target.y, target.cb, target.cr @@ -107111,15 +103884,12 @@ type Core = { mbIntra = false end - -- The picture whose header starts at byte p (after 00 00 01 00) and ends at byte stop: the decoded frame, or nil - -- (skipped, or the first field of a frame). @native local function decodePicture(p: number, stop: number, tag: any): Store? local first, tref = pictureHeader(p, stop) if first == nil or not selectTarget(tref, tag) then return nil end setAddressing() - -- slices local at = first :: number while at >= 0 do local code = readu8(data, at + 3) @@ -107164,7 +103934,6 @@ type Core = { if n <= 0 then return end - -- drop consumed bytes, keeping the scan state relative if readByte > 0 then local keep = dataLen - readByte if keep > 0 then @@ -107189,7 +103958,6 @@ type Core = { buffer.fill(data, dataLen, 0, PAD) end - -- the sequence header unit at byte at (up to stop): the header, then its extensions @native local function sequenceUnit(at: number, stop: number) local ok = sequenceHeader(at + 4) local s = findStart(at + 4, stop) @@ -107284,10 +104052,9 @@ return D end __FILES["codecs/video/Mpeg2/Tables"] = function() --- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. Those of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, --- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from --- mpeg1-luau e2e2898), lists 0-based like the JS arrays; the MPEG-2 ones (DC sizes up to 11, Table B-15, the --- non-linear quantiser scale, the alternate scan) are the tables of ISO/IEC 13818-2 annex B / section 7. +-- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. +-- MPEG-1: jsmpeg's (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), 0-based, via +-- mpeg1-luau e2e2898. MPEG-2 (DC sizes to 11, B-15, non-linear quantiser scale, alternate scan): ISO/IEC 13818-2 annex B / 7. local T = {} T.PICTURE_RATE = { [0] = 0.0, 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, @@ -107425,15 +104192,9 @@ end __FILES["codecs/video/Mpeg2/Vlc"] = function() -- codecs/video/Mpeg2/Vlc: lookup tables for the MPEG-1 / MPEG-2 variable-length codes, built at load time (Tables.luau). --- --- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds --- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level --- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF, --- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the --- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one --- more bit); DCT_FIRST keeps "1" as run 0 / level 1. DCT_B15 is MPEG-2's Table B-15 (intra_vlc_format = 1), DC_LUMA / --- DC_CHROMA cover sizes up to 11. Absorbed from mpeg1-luau e2e2898 (same author, built from jsmpeg's binary trees); --- the MPEG-2 tables are built from code lists. +-- Flat: indexed by the next K bits, len * 65536 + (value + 32768), len 0 = invalid. DCT: two-level (8 + 8 bits), +-- len * 65536 + run * 256 + level, ESC = 0xFFFF, EOB = 0xFFFE, or SUB + subtable for a long-code prefix. +-- DCT_NEXT: "10" = end_of_block, "11" = run 0 / level 1 (jsmpeg reads "1" + one bit); DCT_FIRST: "1" = run 0 / level 1. local T = __include("codecs/video/Mpeg2/Tables") local V = {} @@ -107478,7 +104239,6 @@ local function flat(tree: { [number]: number }): (buffer, number) return flatLeaves(leaves(tree)) end --- { { code, length } } indexed from 1 -> leaves with value = index - 1 local function codeLeaves(codes: { { number } }): { Leaf } local out: { Leaf } = {} for i, c in codes do @@ -107491,7 +104251,6 @@ V.SUB = 0x1000000 V.ESC = 0xFFFF V.EOB = 0xFFFE --- two-level table: 256 first-level entries, then 256-entry subtables for prefixes of codes longer than 8 bits local function twoLevel(ls: { Leaf }): buffer local subs: { [number]: number } = {} local nsub = 0 @@ -107570,22 +104329,9 @@ return V end __FILES["codecs/video/Theora"] = function() --- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska --- (V_THEORA). A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt): Header.luau --- (identification / comment / setup headers, dequantisation tables, Huffman trees) and Decoder.luau (native frames). --- Supports: every Theora I stream (bitstream 3.2.x and older 3.x): intra and inter frames, golden frames, 4MV --- macro blocks, all three pixel formats (4:2:0, 4:2:2, 4:4:4), picture regions smaller than the coded frame (odd sizes, --- offsets), empty packets (a repeated frame). Output is bit-exact with libtheora / ffmpeg (tests/codecs/theora.luau); --- yuv420p images average 4:2:2 / 4:4:4 chroma down (planes() keeps the native layout). --- Not supported: libtheora's optional post-processing (deblocking / deringing, off by default there too). --- --- local dec = Theora.new({ idHeader, commentHeader, setupHeader }) -- or the Xiph-laced Matroska CodecPrivate --- local kind = dec:decode(packet) -- "key" | "inter" | "dup" (empty packet / no coded blocks) | nil, Err --- local img = dec:image() -- a fresh yuv420p Types.Image of the picture region --- local y, u, v, cw, ch = dec:planes() -- native planes (chroma cw x ch), top-down --- Theora.granuleFrame(dec.info, granulepos) -- the 0-based frame index of an Ogg granule position --- --- Never throws: bad headers / packets come back as nil, Err (a corrupt frame still updates the picture). +-- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg and Matroska (V_THEORA). +-- A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt), bit-exact with libtheora / +-- ffmpeg; libtheora's optional post-processing is not supported. local Err = __include("core/Err") local Types = __include("Types") local VorbisComment = __include("codecs/audio/VorbisComment") @@ -107597,12 +104343,11 @@ local Theora = {} type Info = Header.Info type Options = { - maxPixels: number?, -- larger coded frames are refused (default 4096 * 2304) + maxPixels: number?, } local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" } --- isHeader(buf, off?, len?) -> 1 / 2 / 3 for the identification / comment / setup header, else nil function Theora.isHeader(b: buffer, off: number?, len: number?): number? local o = off or 0 local n = len or (buffer.len(b) - o) @@ -107616,7 +104361,6 @@ function Theora.isHeader(b: buffer, off: number?, len: number?): number? return nil end --- splitConfig(config) -> the three header packets from Matroska's Xiph-laced CodecPrivate (or nil) function Theora.splitConfig(c: buffer): { buffer }? local n = buffer.len(c) if n < 3 or buffer.readu8(c, 0) ~= 2 then @@ -107648,7 +104392,6 @@ function Theora.splitConfig(c: buffer): { buffer }? return out end --- info(idHeader) -> Header.Info (frame / picture size, frame rate, granule shift, pixel format, ...) | nil, Err function Theora.info(h: buffer): (Header.Info?, Err.Err?) local ok, info, err = pcall(Header.info, h, 0, buffer.len(h)) if not ok or not info then @@ -107657,7 +104400,6 @@ function Theora.info(h: buffer): (Header.Info?, Err.Err?) return info, nil end --- comment(commentHeader) -> vendor, { "KEY=value" }, tags (lower-case keys) | nil, nil, nil, Err function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }?, Err.Err?) local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h)) if not ok or not vendor or not list then @@ -107666,7 +104408,6 @@ function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }? return vendor, list, (VorbisComment.tags(list)), nil end --- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none) function Theora.granuleFrame(info: Header.Info, g: number): number if g < 0 then return -1 @@ -107682,7 +104423,6 @@ function Theora.granuleFrame(info: Header.Info, g: number): number return f end --- ------------------------------------------------------------------------------------------------ decoder local Dec = {} Dec.__index = Dec @@ -107697,14 +104437,13 @@ type TheoraDecoder = typeof(setmetatable( frameRate: number, pixelFormat: string, -- "yuv420p" | "yuv422p" | "yuv444p" aspect: number, -- pixel aspect ratio (1 when unknown) - frames: number, -- packets decoded (dupes included) + frames: number, _st: Decoder.State, - _any: boolean, -- a frame was decoded + _any: boolean, }, Dec )) --- new(headers, opts?) -> TheoraDecoder | nil, Err: headers = the three header packets, or the Xiph-laced config function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecoder?, Err.Err?) local list: { buffer }? = nil if type(headers) == "buffer" then @@ -107748,7 +104487,6 @@ function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecode }, Dec), nil end --- decode(data, off?, len?) -> "key" | "inter" | "dup" | nil, Err. Header packets are skipped (nil, nil). function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number?): (string?, Err.Err?) local o = off or 0 local n = len or (buffer.len(data) - o) @@ -107769,7 +104507,6 @@ function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number return kind, nil end --- reset(): after a seek (the next frame should be a keyframe; until then inter frames predict from grey / old data) function Dec.reset(self: TheoraDecoder) local st = self._st st.shown = st.prev @@ -107781,8 +104518,6 @@ local function window(self: TheoraDecoder): (number, number, number, number) return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight end --- planes() -> y, u, v (fresh top-down buffers of the picture region, chroma in the native layout), chroma width, --- chroma height function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, number) local st = self._st local x0, y0, w, h = window(self) @@ -107794,7 +104529,6 @@ function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, numbe return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch end --- image() -> a fresh yuv420p Types.Image of the picture (4:2:2 / 4:4:4 chroma averaged down) function Dec.image(self: TheoraDecoder): Types.Image local y, u, v, cw, ch = self:planes() local w, h = self.width, self.height @@ -107818,9 +104552,6 @@ function Dec.image(self: TheoraDecoder): Types.Image return img end --- ------------------------------------------------------------------------------------------------ registry --- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video entry "theora"): track.config --- holds the three headers (Xiph-laced, as Matroska's CodecPrivate); one picture per packet, empty packets repeat function Theora.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) if not track.config then return nil, Err.new(Err.CORRUPT, "Theora track without its headers") @@ -107863,22 +104594,10 @@ __FILES["codecs/video/Theora/Decoder"] = @native function() --- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7; native, never throws). A --- Luau port of libtheora 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, --- idct.c, fragment.c) with the bit-exact reconstruction of the specification: --- * frame header, coded super block / block flags (the run-length codes), macro block modes (the 8 mode --- alphabets), motion vectors (VLC / fixed length, last / prior vectors, 4MV with the chroma averages of each pixel --- format), per-block qi indices, DC / AC tokens with EOB runs across blocks, planes and coefficients; --- * DC prediction, dequantisation, the spec's 16-bit integer IDCT (DC-only blocks as libtheora: (dc * q + 15) >> 5), --- half-pel motion compensation (two-reference average toward zero), the loop filter, border extension for --- unrestricted motion vectors, golden / previous reference frames; --- * 4:2:0, 4:2:2 and 4:4:4; empty packets repeat the previous frame. --- Differences from libtheora: coefficients are kept per fragment (64 i16 each) instead of libtheora's token lists, --- the frame is reconstructed whole (no MCU pipelining, same result), there is no post-processing (libtheora's default), --- and intermediate IDCT sums are not wrapped to 16 bits (only out-of-range streams differ). --- --- Planes are stored in Theora's own orientation (row 0 is the bottom of the picture) with 16 (luma) / 8 (subsampled --- chroma) pixels of edge padding; output() turns the picture region into top-down planes. +-- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7). A Luau port of libtheora +-- 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, idct.c, fragment.c). +-- DC-only blocks as libtheora: (dc * q + 15) >> 5; IDCT sums are not wrapped to 16 bits (only out-of-range streams differ). +-- Planes are in Theora's orientation (row 0 = bottom) with 16 (luma) / 8 (subsampled chroma) pixels of edge padding. local Header = __include("codecs/video/Theora/Header") local readu8 = buffer.readu8 @@ -108073,7 +104792,6 @@ type State = { keyframes: number, } --- new(info, setup) -> State @native function D.new(info: Header.Info, setup: Header.Setup): State local pf = info.pixelFormat local hdec = if pf % 2 == 0 then 1 else 0 @@ -108244,7 +104962,6 @@ type State = { return st :: State end --- ------------------------------------------------------------------------------------------------ reconstruction -- the 8-point IDCT of libtheora's idct8 (the spec's), on 8 values; returns the 8 outputs @native local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, x7: number): (number, number, number, number, number, number, number, number) local t0 = (C4 * (x0 + x4)) // 65536 @@ -108384,7 +105101,6 @@ end st.last[fi] = 0 idctRows(blk, st.tmp) end - -- the prediction if ri == SELF then for y = 0, 7 do bfill(dst, pos + y * stride, 128, 8) @@ -108414,7 +105130,6 @@ end end end end - -- the residual if last ~= 0 then idctAdd(st.tmp, dst, pos, stride) elseif fv ~= 0 then @@ -108427,7 +105142,6 @@ end end end --- ------------------------------------------------------------------------------------------------ loop filter @native local function filterH(b: buffer, p: number, stride: number, bv: { number }) p -= 2 for _ = 0, 7 do @@ -108597,14 +105311,10 @@ end end end --- ------------------------------------------------------------------------------------------------ frame decode --- decode(st, data, off, len) -> kind ("key" | "inter" | "dup") | nil, message. The picture is then in --- st.refs[st.shown]. @native function D.decode(st: State, data: buffer, off: number, len: number): (string?, string?) if len <= 0 then return "dup", nil end - -- a zero-padded copy: reads past the end give zero bits, every read site clamps pos to the end first local bb = buffer.create(len + 24) bcopy(bb, 0, data, off, len) local maxp = len * 8 @@ -109078,7 +105788,6 @@ end dcPredict(st) - -- reconstruction into a free reference buffer local self = 1 while self == st.gold or self == st.prev do self += 1 @@ -109111,9 +105820,6 @@ end return if intra then "key" else "inter", nil end --- ------------------------------------------------------------------------------------------------ output --- the picture region of the shown frame as top-down planes: plane(st, pli, x0, y0, w, h) copies a w x h window whose --- top-left corner is (x0, y0) counted from the top of the plane @native function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: number): buffer local src = st.refs[st.shown][pli + 1] local stride, origin, ph = st.stride[pli + 1], st.origin[pli + 1], st.ph[pli + 1] @@ -109125,8 +105831,7 @@ end return out end --- downsample(src, cw, ch, hdec, dst, off, ow, oh): 4:2:2 (hdec 1: rows averaged in pairs) or 4:4:4 (hdec 0: 2x2 --- averages) chroma of cw x ch into ow x oh 4:2:0 chroma at dst[off] +-- 4:2:2 (rows averaged in pairs) or 4:4:4 (2x2 averages) chroma down to 4:2:0 @native function D.downsample(src: buffer, cw: number, ch: number, hdec: number, dst: buffer, off: number, ow: number, oh: number) for r = 0, oh - 1 do local r0 = math.min(2 * r, ch - 1) @@ -109151,13 +105856,9 @@ return D end __FILES["codecs/video/Theora/Header"] = function() --- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6): identification (frame / --- picture size and offsets, frame rate, aspect, colour space, pixel format, keyframe granule shift), comment (Vorbis --- comment layout) and setup (loop-filter limits, quantisation parameters, the 80 DCT token Huffman trees), and the --- tables derived from them: the dequantisation matrices of every qi / plane / intra-inter and the collapsed Huffman --- lookup tables the frame decoder walks. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause: --- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c (the tree unpacking; --- the table layout here is simpler). Never throws: bad headers return nil, message. +-- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6) and the dequantisation and +-- Huffman lookup tables derived from them. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause, +-- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c. local Bits = __include("core/Bits") local H = {} @@ -109170,7 +105871,7 @@ type Info = { frameHeight: number, picWidth: number, -- the picture region (the displayed part) picHeight: number, - picX: number, -- from the left + picX: number, picY: number, -- from the bottom, as stored fpsNum: number, fpsDen: number, @@ -109205,8 +105906,7 @@ local function ilog(v: number): number return n end --- ------------------------------------------------------------------------------------------------ identification --- info(buf, off, len) -> Info | nil, message: the packet starting with 0x80 "theora" +-- identification header: 0x80 "theora" function H.info(b: buffer, off: number, len: number): (Info?, string?) if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then return nil, "not a Theora identification header" @@ -109251,8 +105951,7 @@ function H.info(b: buffer, off: number, len: number): (Info?, string?) return info, nil end --- ------------------------------------------------------------------------------------------------ comment --- comment(buf, off, len) -> vendor, { "KEY=value" } | nil, message: the packet starting with 0x81 "theora" +-- comment header: 0x81 "theora" function H.comment(b: buffer, off: number, len: number): (string?, { string }?, string?) if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then return nil, nil, "not a Theora comment header" @@ -109291,7 +105990,6 @@ function H.comment(b: buffer, off: number, len: number): (string?, { string }?, return vendor, list, nil end --- ------------------------------------------------------------------------------------------------ Huffman trees -- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in -- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf -- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits). @@ -109318,7 +106016,6 @@ local function readTree(br: any): ({ number }?, { number }?, { number }?) return nil, nil, nil end local t = br:read(5) - -- insert the leaf local n = 1 for d = 1, len do local k = (code // 2 ^ (32 - d)) % 2 @@ -109399,11 +106096,10 @@ local function buildTable(out: { number }, kid0: { number }, kid1: { number }, t return node(1) end --- ------------------------------------------------------------------------------------------------ setup local DC_MIN = { 16, 32 } local AC_MIN = { 8, 16 } --- setup(buf, off, len) -> Setup | nil, message: the packet starting with 0x82 "theora" +-- setup header: 0x82 "theora" function H.setup(b: buffer, off: number, len: number): (Setup?, string?) if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then return nil, "not a Theora setup header" @@ -109524,20 +106220,6 @@ end __FILES["codecs/video/Video"] = function() -- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in rosetta. --- --- Registry: our codec ids ("vp8", "mjpeg", "mpeg1", "h264", "rawvideo", ...) with the containers' names for them --- (AVI / MOV FourCCs, Matroska CodecIDs, MPEG stream types) and, for the codecs we can decode, a constructor of a --- Types.VideoCodecDecoder (packets in, pictures out). Containers map their own ids through Video.fromFourcc / --- Video.fromMatroska so a track's codec is known even without a decoder (remuxing still works). Another codec plugs --- in with one line in BUILTIN (static: Roblox has no dynamic require) or at run time with Video.register(entry). --- --- local Video = require("@rosetta/codecs/video/Video") --- Video.fromFourcc("MJPG") --> "mjpeg" Video.fromMatroska("V_VP8") --> "vp8" --- local dec = Video.decoder(track, opts) -- a VideoCodecDecoder | nil, Err (UNSUPPORTED: no decoder) --- local v = Video.open(demuxer, opts) -- a Types.VideoDecoder over a Types.Demuxer (formats' open()) --- local v = Video.fromFrames(images, delays) -- a frames-backed VideoDecoder (animated GIF / APNG / WebP) --- --- Never throws: bad data / missing codecs come back as nil, Err. local Err = __include("core/Err") local Types = __include("Types") local Yuv = __include("codecs/image/Yuv") @@ -109545,18 +106227,15 @@ local Yuv = __include("codecs/image/Yuv") local Video = {} type Entry = { - id: string, -- our codec id - name: string, -- a human name + id: string, + name: string, fourcc: { string }?, -- AVI biCompression / MOV sample entry FourCCs matroska: { string }?, -- Matroska / WebM CodecIDs - -- new(track, opts) -> a decoder instance (nil = decode not supported) new: ((track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?))?, [string]: any, } --- ------------------------------------------------------------------------------------------------ simple decoders --- one picture per packet, no reordering: decodeOne(data, packet) -> Image | nil, Err (nil, nil: a packet with no --- picture to show, such as a hidden VP8 altref frame) +-- decodeOne -> nil, nil: a packet with no picture to show (a hidden VP8 altref frame) function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), resetFn: (() -> ())?): Types.VideoCodecDecoder local queue: { any } = {} local self = {} @@ -109737,8 +106416,7 @@ local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDec end), nil end --- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout --- allows, else rgba8 +-- Motion JPEG: yuv420p straight from the planes (full range) when the layout allows, else rgba8 local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local Jpeg = __include("codecs/image/Jpeg") local o: Jpeg.DecodeOptions = { yuv = true, maxPixels = opts and opts.maxPixels } @@ -109764,20 +106442,16 @@ local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?) return Jpeg.encode(src, { quality = opts and opts.quality or 90 }) end --- MPEG-1 / MPEG-2 video (codecs/video/Mpeg2): pictures in decode order, reordered for display local function mpeg2Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local Mpeg2 = __include("codecs/video/Mpeg2") return Mpeg2.newVideoDecoder(track, opts) end --- H.264 / AVC (codecs/video/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264); --- pictures in display order with the pts of their packet local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local H264 = __include("codecs/video/H264") return H264.newVideoDecoder(track, opts) end --- H.263 / Sorenson Spark (codecs/video/H263): one picture per packet, no reordering local function h263Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local H263 = __include("codecs/video/H263") local dec = H263.new({ flv = track.codec == "flv1", maxPixels = opts and opts.maxPixels }) @@ -109788,22 +106462,18 @@ local function h263Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec end), nil end --- Theora (codecs/video/Theora): track.config = the three headers, Xiph-laced (Matroska's CodecPrivate; video/ogv --- builds the same); one picture per packet, empty packets repeat the previous one local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local Theora = __include("codecs/video/Theora") return Theora.newVideoDecoder(track, opts) end --- FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC, Smacker (codecs/video/Legacy) local function legacyDecoder(id: string): (track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?) return function(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) return __include("codecs/video/Legacy").newDecoder(id, track, opts) end end --- ------------------------------------------------------------------------------------------------ registry --- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. +-- FourCCs compare case-sensitively first, then upper-cased local BUILTIN: { Entry } = { { id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder }, { id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" }, new = mjpegDecoder, encode = mjpegEncode }, @@ -109823,7 +106493,6 @@ local BUILTIN: { Entry } = { { id = "flashsv", name = "Flash Screen Video", fourcc = { "FSV1" } }, { id = "flashsv2", name = "Flash Screen Video 2" }, { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, - -- legacy inter-frame codecs (codecs/video/Legacy; rgba8 pictures, palettes from track.palette) { id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") }, { id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") }, { id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") }, @@ -109836,7 +106505,6 @@ local byId: { [string]: Entry } = {} local byFourcc: { [string]: string } = {} local byMatroska: { [string]: string } = {} --- register(entry): adds or replaces a codec (by id); its fourcc / matroska names map to it function Video.register(entry: Entry): (boolean, Err.Err?) if type(entry) ~= "table" or type(entry.id) ~= "string" then return false, Err.new(Err.ARG, "register: needs an entry with an id") @@ -109858,31 +106526,25 @@ for _, e in BUILTIN do Video.register(e) end --- the registry (read only by convention): id -> Entry Video.codecs = byId --- fromFourcc(fourcc) -> codec id | nil function Video.fromFourcc(fcc: string): string? return byFourcc[fcc] or byFourcc[string.upper(fcc)] or byFourcc[string.lower(fcc)] end --- fromMatroska(codecId) -> codec id | nil (V_MPEG4/ISO/AVC -> h264, ...) function Video.fromMatroska(id: string): string? return byMatroska[id] end --- names(codecId) -> the Entry (FourCCs / Matroska ids for writers) | nil function Video.entry(id: string): Entry? return byId[id] end --- canDecode(codecId) -> boolean function Video.canDecode(id: string): boolean local e = byId[id] return e ~= nil and e.new ~= nil end --- decoder(track, opts?) -> a VideoCodecDecoder for the track's codec | nil, Err (UNSUPPORTED when none is registered) function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local e = byId[track.codec] if not e or not e.new then @@ -109895,7 +106557,6 @@ function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder return dec, err end --- ------------------------------------------------------------------------------------------------ VideoDecoder local function toRGBA(_self: any, f: any): Types.Image local img = if type(f) == "table" and f.image then f.image else f local out = Yuv.imageToRgba(img) @@ -109903,22 +106564,16 @@ local function toRGBA(_self: any, f: any): Types.Image end type OpenOptions = { - rgba: boolean?, -- nextFrame returns rgba8 images (default false: the codec's native yuv420p) - track: number?, -- the video track id (default: the first video track) + rgba: boolean?, + track: number?, maxPixels: number?, - openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?, -- the api's audio hook - audio: boolean?, -- false: do not open the audio track - -- shrink yuv420p frames so the longer side is at most this many pixels (aspect kept; bilinear, Yuv.scale), before - -- any rgba conversion. v.width / v.height stay the source size; frame.image has the output size. Default: none + openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?, + audio: boolean?, maxSide: number?, - -- passed to codecs that support a cooperative yield point (H.264: codecs/video/H264 Options.yield) yield: (() -> ())?, [string]: any, } --- open(demuxer, opts?) -> a Types.VideoDecoder over the demuxer's video track (and audio track through --- opts.openAudio). A video track without a decoder still opens: nextFrame returns nil, Err.UNSUPPORTED, and --- the demuxer (remuxing) and audio work. function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) local o: OpenOptions = opts or {} local track: Types.Track? = nil @@ -109959,7 +106614,6 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec if v.frames == 0 and v.frameRate > 0 and v.duration > 0 then v.frames = math.floor(v.duration * v.frameRate + 0.5) end - -- audio if o.audio ~= false then local at = demuxer:track("audio") if at then @@ -109993,8 +106647,7 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec local t = (pts or 0) / scale - start if t + 1e-9 >= skipUntil then if index < 0 then - -- the first frame after a seek: its position in the stream (constant-rate: round(pts * fps); - -- without a frame rate, counted from the seek) + -- after a seek: constant-rate index = round(pts * fps), else counted from the seek index = if v.frameRate > 0 then math.max(0, math.floor(t * v.frameRate + 0.5)) else 0 end index += 1 @@ -110055,9 +106708,6 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec return v, nil end --- ------------------------------------------------------------------------------------------------ frames-backed --- fromFrames(images, delays, opts?) -> a VideoDecoder over full-canvas images (animated GIF / APNG / WebP after --- coalescing): delays[i] seconds (a number = every frame). opts.format / opts.loops / opts.meta are recorded. function Video.fromFrames(images: { Types.Image }, delays: (number | { number })?, opts: any?): (Types.VideoDecoder?, Err.Err?) if type(images) ~= "table" or #images == 0 or type(images[1]) ~= "table" then return nil, Err.new(Err.ARG, "fromFrames: needs a list of Images") @@ -110126,18 +106776,8 @@ return Video end __FILES["codecs/video/Video/Source"] = function() --- codecs/video/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given: --- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either --- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM, --- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw --- yuv420p frames, PCM audio from the audio Decoder). New in rosetta. --- --- local streams, err = Source.streams(value, opts, { --- video = { copy = { vp8 = true }, encode = "mjpeg" }, -- copy: codec ids the container takes ("*" = any) --- audio = { copy = { opus = true, vorbis = true }, pcm = true }, --- }) --- -- streams[i] = { kind, codec, copied, width, height, frameRate, sampleRate, channels, bitsPerSample, config, --- -- track, packets = { { pts, duration (seconds), keyframe, data } } } +-- codecs/video/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from a VideoDecoder +-- or a Demuxer: each stream is copied (remuxed) or produced (decoded frames re-encoded, PCM audio). local Err = __include("core/Err") local Types = __include("Types") local Yuv = __include("codecs/image/Yuv") @@ -110168,7 +106808,6 @@ local function allows(set: { [string]: boolean }?, codec: string): boolean return set ~= nil and (set[codec] == true or set["*"] == true) end --- the packets of a source track, times in seconds local function copyPackets(dmx: any, track: Types.Track): { OutPacket } local out = {} local scale = if track.timescale and track.timescale > 0 then track.timescale else 1 @@ -110199,8 +106838,6 @@ local function trackStream(track: Types.Track, packets: { OutPacket }): Stream } end --- encodeFrames(video, codec, opts) -> the video's frames encoded with the registry's encoder for codec ("rawvideo": --- yuv420p planes) local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err?) local encode: ((img: Types.Image, opts: any) -> (buffer?, Err.Err?))? = nil if codec ~= "rawvideo" then @@ -110267,7 +106904,6 @@ local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err } :: Stream, nil end --- pcmFrom(decoder, opts) -> an s16le stream from an audio Decoder (chunks of opts.audioChunk frames, default 4096) local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?) local ch, rate = dec.channels, dec.sampleRate if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then @@ -110311,7 +106947,6 @@ local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?) } :: Stream, nil end --- streams(value, opts, want) -> { Stream } | nil, Err function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.Err?) local o = opts or {} if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then @@ -110319,7 +106954,6 @@ function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.E end local dmx = if value.kind == "demuxer" then value else value.demuxer local out: { Stream } = {} - -- video local vt: Types.Track? = if value.kind == "video" then value.track else (dmx and dmx:track("video")) local wv = want.video if wv and o.video ~= false then @@ -110335,7 +106969,6 @@ function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.E return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (if wv.encode then "" else " (this container cannot take it and it cannot be re-encoded)")) end end - -- audio local wa = want.audio if wa and o.audio ~= false then local at: Types.Track? = dmx and dmx:track("audio") @@ -110359,7 +106992,7 @@ function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.E return out, nil end --- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond +-- integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond function Source.rational(fps: number): (number, number) if fps ~= fps or fps <= 0 then return 25, 1 @@ -110374,9 +107007,6 @@ function Source.rational(fps: number): (number, number) return math.floor(fps * 1000 + 0.5), 1000 end --- constantRate(stream, maxFps?) -> num, den, { OutPacket }: a video stream at a constant frame rate for the --- containers that have one (AVI, Y4M): the rate of the shortest frame (at most maxFps, default 100), each packet --- repeated to fill its duration (a GIF's 100 / 50 / 200 ms frames become 2, 1 and 4 frames at 20 fps) function Source.constantRate(s: Stream, maxFps: number?): (number, number, { OutPacket }) local fd = math.huge for _, p in s.packets do @@ -110404,8 +107034,6 @@ function Source.constantRate(s: Stream, maxFps: number?): (number, number, { Out return num, den, out end --- interleave(streams) -> { { stream index, packet } } merged by decode time (dts, else pts); each stream keeps its --- own order function Source.interleave(streams: { Stream }): { { any } } local order = {} local pos = table.create(#streams, 1) diff --git a/build/Rosetta.luau.linemap.json b/build/Rosetta.luau.linemap.json index b05f2e3..4ef4981 100644 --- a/build/Rosetta.luau.linemap.json +++ b/build/Rosetta.luau.linemap.json @@ -72,468 +72,468 @@ [21947, "src/Rosetta/cad/step/Parse.luau"], [22522, "src/Rosetta/cad/step/Write.luau"], [22776, "src/Rosetta/codecs/audio/Aac/init.luau"], -[23114, "src/Rosetta/codecs/audio/Aac/Decode.luau"], -[24019, "src/Rosetta/codecs/audio/Aac/Tables.luau"], -[24355, "src/Rosetta/codecs/audio/Ac3/init.luau"], -[24529, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], -[25447, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], -[25551, "src/Rosetta/codecs/audio/Adpcm/init.luau"], -[26371, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], -[26701, "src/Rosetta/codecs/audio/Alac/init.luau"], -[26954, "src/Rosetta/codecs/audio/Alac/Decode.luau"], -[27383, "src/Rosetta/codecs/audio/Alac/Encode.luau"], -[27812, "src/Rosetta/codecs/audio/Ape/init.luau"], -[28043, "src/Rosetta/codecs/audio/Ape/Decode.luau"], -[28823, "src/Rosetta/codecs/audio/ApeTag.luau"], -[28935, "src/Rosetta/codecs/audio/Flac/init.luau"], -[28948, "src/Rosetta/codecs/audio/Flac/Encode.luau"], -[29938, "src/Rosetta/codecs/audio/Flac/Frame.luau"], -[30550, "src/Rosetta/codecs/audio/Hively/init.luau"], -[30761, "src/Rosetta/codecs/audio/Hively/Load.luau"], -[31012, "src/Rosetta/codecs/audio/Hively/Player.luau"], -[31984, "src/Rosetta/codecs/audio/Hively/Tables.luau"], -[32207, "src/Rosetta/codecs/audio/Mdct/init.luau"], -[32412, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], -[32625, "src/Rosetta/codecs/audio/MidiRender.luau"], -[32986, "src/Rosetta/codecs/audio/Mpa/init.luau"], -[33001, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], -[33066, "src/Rosetta/codecs/audio/Mpa/Core.luau"], -[34705, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], -[34999, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], -[35395, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], -[36062, "src/Rosetta/codecs/audio/Mpa/Header.luau"], -[36204, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], -[36430, "src/Rosetta/codecs/audio/Musepack/init.luau"], -[36791, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[37692, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[38073, "src/Rosetta/codecs/audio/Opus/init.luau"], -[38090, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[39956, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[41036, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[41096, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[41564, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[41912, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[42149, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[44221, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[44595, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[44891, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[45201, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[45500, "src/Rosetta/codecs/audio/Resample/init.luau"], -[45879, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[45950, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[46101, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[46626, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[47431, "src/Rosetta/codecs/audio/Stream.luau"], -[47614, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[48168, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[48461, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[48636, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[48770, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[50798, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[50926, "src/Rosetta/codecs/audio/Tta/init.luau"], -[51054, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[51315, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[51330, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[51726, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[52314, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[52745, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[52784, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[52848, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[53088, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[54573, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[54640, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[54743, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[55741, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[56609, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[56667, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[57197, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[57555, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[57989, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[58445, "src/Rosetta/codecs/compress/Explode.luau"], -[58651, "src/Rosetta/codecs/compress/Lz4.luau"], -[58944, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[59572, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[60141, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[60180, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[60674, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[60853, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[61144, "src/Rosetta/codecs/compress/Lzx.luau"], -[61595, "src/Rosetta/codecs/compress/PackBits.luau"], -[61692, "src/Rosetta/codecs/compress/Quantum.luau"], -[61945, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[62266, "src/Rosetta/codecs/compress/Xxh32.luau"], -[62340, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[62410, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[63392, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[63549, "src/Rosetta/codecs/entropy/Huffman.luau"], -[63857, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[63872, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[64089, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[64343, "src/Rosetta/codecs/font/Bitmap.luau"], -[64565, "src/Rosetta/codecs/font/Cff/init.luau"], -[65224, "src/Rosetta/codecs/font/GlyphNames.luau"], -[65380, "src/Rosetta/codecs/font/TrueType/init.luau"], -[65720, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[66125, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[66646, "src/Rosetta/codecs/image/Bcn/init.luau"], -[66769, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[67269, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[67713, "src/Rosetta/codecs/image/Blend.luau"], -[68114, "src/Rosetta/codecs/image/Dct/init.luau"], -[68512, "src/Rosetta/codecs/image/Etc.luau"], -[68829, "src/Rosetta/codecs/image/Half.luau"], -[68905, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[69297, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[69713, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[69963, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[70736, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[71637, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[72100, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[72179, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[72257, "src/Rosetta/codecs/image/Pixels.luau"], -[72542, "src/Rosetta/codecs/image/Quantize/init.luau"], -[73027, "src/Rosetta/codecs/image/Raster.luau"], -[73773, "src/Rosetta/codecs/image/Texel.luau"], -[74173, "src/Rosetta/codecs/image/Texture.luau"], -[74337, "src/Rosetta/codecs/image/Vp8/init.luau"], -[74497, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[76486, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[76762, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[77013, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[77138, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[77260, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[78135, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[79113, "src/Rosetta/codecs/image/Yuv.luau"], -[79403, "src/Rosetta/codecs/model/Draco/init.luau"], -[79758, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[80239, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[81445, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[81603, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[81968, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[82947, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[83429, "src/Rosetta/codecs/model/Mat4.luau"], -[83713, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[84258, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[84847, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[84930, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[85040, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[85262, "src/Rosetta/codecs/model/Polygon.luau"], -[85512, "src/Rosetta/codecs/model/Rbx/init.luau"], -[85795, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[86571, "src/Rosetta/codecs/model/Rig.luau"], -[86847, "src/Rosetta/codecs/model/Sampler.luau"], -[87022, "src/Rosetta/codecs/model/Vrml/init.luau"], -[87184, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[87776, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[87946, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[88718, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[89256, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[90008, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[90248, "src/Rosetta/codecs/text/Json/init.luau"], -[90544, "src/Rosetta/codecs/text/Json/Decode.luau"], -[90971, "src/Rosetta/codecs/text/Json/Encode.luau"], -[91280, "src/Rosetta/codecs/text/Nbt/init.luau"], -[91662, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[92362, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[93013, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[93271, "src/Rosetta/codecs/text/Text/init.luau"], -[93367, "src/Rosetta/codecs/text/Url/init.luau"], -[93585, "src/Rosetta/codecs/text/Xml/init.luau"], -[94027, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[94792, "src/Rosetta/codecs/video/Dsp.luau"], -[95537, "src/Rosetta/codecs/video/H263/init.luau"], -[95715, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[96611, "src/Rosetta/codecs/video/H263/Tables.luau"], -[96819, "src/Rosetta/codecs/video/H264/init.luau"], -[97236, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[97531, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[98676, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[99455, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[99721, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[100747, "src/Rosetta/codecs/video/H264/Inter.luau"], -[101015, "src/Rosetta/codecs/video/H264/Intra.luau"], -[101427, "src/Rosetta/codecs/video/H264/Mb.luau"], -[102360, "src/Rosetta/codecs/video/H264/Params.luau"], -[102815, "src/Rosetta/codecs/video/H264/Slice.luau"], -[103068, "src/Rosetta/codecs/video/H264/Tables.luau"], -[103112, "src/Rosetta/codecs/video/H264/Transform.luau"], -[103288, "src/Rosetta/codecs/video/Legacy/init.luau"], -[103504, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[103809, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[104183, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[104306, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[104423, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[104701, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[105108, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[105293, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[105306, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[105722, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[107286, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[107426, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[107572, "src/Rosetta/codecs/video/Theora/init.luau"], -[107863, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[109153, "src/Rosetta/codecs/video/Theora/Header.luau"], -[109525, "src/Rosetta/codecs/video/Video/init.luau"], -[110128, "src/Rosetta/codecs/video/Video/Source.luau"], -[110435, "src/Rosetta/containers/Archive.luau"], -[110728, "src/Rosetta/containers/AudioWrap.luau"], -[111249, "src/Rosetta/containers/Avi/init.luau"], -[111821, "src/Rosetta/containers/Chunks.luau"], -[111965, "src/Rosetta/containers/Cpio.luau"], -[112407, "src/Rosetta/containers/Demux.luau"], -[112705, "src/Rosetta/containers/Ebml/init.luau"], -[113042, "src/Rosetta/containers/Fat.luau"], -[113751, "src/Rosetta/containers/Iso9660.luau"], -[114278, "src/Rosetta/containers/IsoBmff/init.luau"], -[114468, "src/Rosetta/containers/IsoBmff/Box.luau"], -[114663, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[115527, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[116057, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[116578, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[116700, "src/Rosetta/containers/MacFile.luau"], -[116860, "src/Rosetta/containers/MpegEs.luau"], -[117035, "src/Rosetta/containers/MpegPs/init.luau"], -[117261, "src/Rosetta/containers/MpegTs/init.luau"], -[118078, "src/Rosetta/containers/Ogg/init.luau"], -[118536, "src/Rosetta/containers/Ogg/Mux.luau"], -[118746, "src/Rosetta/containers/Ogg/Page.luau"], -[118923, "src/Rosetta/containers/Riff/init.luau"], -[119268, "src/Rosetta/containers/Tar.luau"], -[119696, "src/Rosetta/containers/Zip/init.luau"], -[120356, "src/Rosetta/core/Adler32.luau"], -[120408, "src/Rosetta/core/Base64.luau"], -[120577, "src/Rosetta/core/Bits.luau"], -[120889, "src/Rosetta/core/Bytes.luau"], -[121458, "src/Rosetta/core/Crc16.luau"], -[121512, "src/Rosetta/core/Crc32.luau"], -[121635, "src/Rosetta/core/Err.luau"], -[121731, "src/Rosetta/core/Input.luau"], -[121815, "src/Rosetta/core/Md5.luau"], -[121981, "src/Rosetta/core/Sniff.luau"], -[122019, "src/Rosetta/data/cbor/init.luau"], -[122121, "src/Rosetta/data/cbor/Codec.luau"], -[122698, "src/Rosetta/data/csv/init.luau"], -[123015, "src/Rosetta/data/ini/init.luau"], -[123266, "src/Rosetta/data/json/init.luau"], -[123359, "src/Rosetta/data/msgpack/init.luau"], -[123451, "src/Rosetta/data/msgpack/Codec.luau"], -[123899, "src/Rosetta/data/nbt/init.luau"], -[123961, "src/Rosetta/data/plist/init.luau"], -[124269, "src/Rosetta/data/plist/Binary.luau"], -[124542, "src/Rosetta/data/snbt/init.luau"], -[124607, "src/Rosetta/data/toml/init.luau"], -[124679, "src/Rosetta/data/toml/Decode.luau"], -[125316, "src/Rosetta/data/toml/Encode.luau"], -[125532, "src/Rosetta/data/xml/init.luau"], -[125589, "src/Rosetta/data/yaml/init.luau"], -[125668, "src/Rosetta/data/yaml/Emit.luau"], -[125969, "src/Rosetta/data/yaml/Parse.luau"], -[127293, "src/Rosetta/font/bdf/init.luau"], -[127590, "src/Rosetta/font/bmfont/init.luau"], -[128032, "src/Rosetta/font/bmfont/Parse.luau"], -[128491, "src/Rosetta/font/eot/init.luau"], -[128726, "src/Rosetta/font/fon/init.luau"], -[129016, "src/Rosetta/font/hershey/init.luau"], -[129218, "src/Rosetta/font/pcf/init.luau"], -[129510, "src/Rosetta/font/psf/init.luau"], -[129840, "src/Rosetta/font/ttf/init.luau"], -[129894, "src/Rosetta/font/type1/init.luau"], -[130264, "src/Rosetta/font/type1/Charstring.luau"], -[130549, "src/Rosetta/font/woff/init.luau"], -[130683, "src/Rosetta/font/woff2/init.luau"], -[130742, "src/Rosetta/font/woff2/Rebuild.luau"], -[131292, "src/Rosetta/host/init.luau"], -[131344, "src/Rosetta/host/Love.luau"], -[131495, "src/Rosetta/host/LuaJIT.luau"], -[131545, "src/Rosetta/host/Luau.luau"], -[131568, "src/Rosetta/host/Roblox.luau"], -[131959, "src/Rosetta/image/ani/init.luau"], -[132144, "src/Rosetta/image/blp/init.luau"], -[132412, "src/Rosetta/image/bmp/init.luau"], -[132843, "src/Rosetta/image/dds/init.luau"], -[133342, "src/Rosetta/image/exr/init.luau"], -[134126, "src/Rosetta/image/exr/Codec.luau"], -[134245, "src/Rosetta/image/exr/Piz.luau"], -[134614, "src/Rosetta/image/gif/init.luau"], -[135150, "src/Rosetta/image/gif/Decode.luau"], -[135220, "src/Rosetta/image/hdr/init.luau"], -[135456, "src/Rosetta/image/hdr/Codec.luau"], -[135677, "src/Rosetta/image/icns/init.luau"], -[136016, "src/Rosetta/image/ico/init.luau"], -[136300, "src/Rosetta/image/ico/Dib.luau"], -[136401, "src/Rosetta/image/ilbm/init.luau"], -[136727, "src/Rosetta/image/jpeg/init.luau"], -[136878, "src/Rosetta/image/ktx/init.luau"], -[137552, "src/Rosetta/image/pcx/init.luau"], -[137820, "src/Rosetta/image/png/init.luau"], -[138418, "src/Rosetta/image/png/Apng.luau"], -[138502, "src/Rosetta/image/png/Decode.luau"], -[138757, "src/Rosetta/image/png/Encode.luau"], -[138921, "src/Rosetta/image/pnm/init.luau"], -[139307, "src/Rosetta/image/pnm/Codec.luau"], -[139598, "src/Rosetta/image/qoi/init.luau"], -[139722, "src/Rosetta/image/qoi/Codec.luau"], -[139876, "src/Rosetta/image/sgi/init.luau"], -[140164, "src/Rosetta/image/sunras/init.luau"], -[140413, "src/Rosetta/image/tga/init.luau"], -[140691, "src/Rosetta/image/tga/Codec.luau"], -[140850, "src/Rosetta/image/tiff/init.luau"], -[141694, "src/Rosetta/image/tiff/Pixels.luau"], -[142095, "src/Rosetta/image/tim/init.luau"], -[142344, "src/Rosetta/image/vtf/init.luau"], -[142591, "src/Rosetta/image/webp/init.luau"], -[143220, "src/Rosetta/image/webp/Alpha.luau"], -[143298, "src/Rosetta/image/webp/Anim.luau"], -[143462, "src/Rosetta/image/xbm/init.luau"], -[143626, "src/Rosetta/image/xpm/init.luau"], -[143900, "src/Rosetta/image/xpm/Names.luau"], -[143959, "src/Rosetta/layered/aseprite/init.luau"], -[144715, "src/Rosetta/layered/ora/init.luau"], -[145010, "src/Rosetta/layered/psd/init.luau"], -[145755, "src/Rosetta/layered/psd/Channels.luau"], -[146126, "src/Rosetta/model/3ds/init.luau"], -[146228, "src/Rosetta/model/3ds/Build.luau"], -[146893, "src/Rosetta/model/3ds/Read.luau"], -[147401, "src/Rosetta/model/3ds/Write.luau"], -[148230, "src/Rosetta/model/3mf/init.luau"], -[148327, "src/Rosetta/model/3mf/Read.luau"], -[148927, "src/Rosetta/model/3mf/Write.luau"], -[149346, "src/Rosetta/model/b3d/init.luau"], -[149416, "src/Rosetta/model/b3d/Read.luau"], -[149994, "src/Rosetta/model/bsp/init.luau"], -[150146, "src/Rosetta/model/bsp/Brush.luau"], -[150439, "src/Rosetta/model/bsp/Quake3.luau"], -[150702, "src/Rosetta/model/dae/init.luau"], -[150910, "src/Rosetta/model/dae/Math.luau"], -[150958, "src/Rosetta/model/dae/Read.luau"], -[152840, "src/Rosetta/model/dae/Write.luau"], -[153218, "src/Rosetta/model/fbx/init.luau"], -[153386, "src/Rosetta/model/fbx/Ascii.luau"], -[153662, "src/Rosetta/model/fbx/Binary.luau"], -[154125, "src/Rosetta/model/fbx/Read.luau"], -[155511, "src/Rosetta/model/fbx/Write.luau"], -[156509, "src/Rosetta/model/fbx/Xform.luau"], -[156553, "src/Rosetta/model/gltf/init.luau"], -[156807, "src/Rosetta/model/gltf/Pack.luau"], -[156883, "src/Rosetta/model/gltf/Read.luau"], -[157632, "src/Rosetta/model/gltf/Write.luau"], -[158330, "src/Rosetta/model/iqm/init.luau"], -[158414, "src/Rosetta/model/iqm/Read.luau"], -[158775, "src/Rosetta/model/iqm/Write.luau"], -[159483, "src/Rosetta/model/ldraw/init.luau"], -[159590, "src/Rosetta/model/ldraw/Colors.luau"], -[159911, "src/Rosetta/model/ldraw/Read.luau"], -[160493, "src/Rosetta/model/lwo/init.luau"], -[160581, "src/Rosetta/model/lwo/Build.luau"], -[161052, "src/Rosetta/model/lwo/Parse.luau"], -[161605, "src/Rosetta/model/mca/init.luau"], -[161962, "src/Rosetta/model/mca/Chunk.luau"], -[162099, "src/Rosetta/model/mca/Lz4Block.luau"], -[162171, "src/Rosetta/model/md2/init.luau"], -[162382, "src/Rosetta/model/md3/init.luau"], -[162618, "src/Rosetta/model/md5/init.luau"], -[162703, "src/Rosetta/model/md5/Read.luau"], -[163145, "src/Rosetta/model/mdl/init.luau"], -[163231, "src/Rosetta/model/mdl/HalfLife.luau"], -[163573, "src/Rosetta/model/mdl/Quake.luau"], -[163797, "src/Rosetta/model/ms3d/init.luau"], -[163881, "src/Rosetta/model/ms3d/Read.luau"], -[164347, "src/Rosetta/model/ms3d/Write.luau"], -[164835, "src/Rosetta/model/obj/init.luau"], -[165600, "src/Rosetta/model/obj/Mtl.luau"], -[165896, "src/Rosetta/model/off/init.luau"], -[166378, "src/Rosetta/model/ply/init.luau"], -[167528, "src/Rosetta/model/ply/Binary.luau"], -[167742, "src/Rosetta/model/pmx/init.luau"], -[167821, "src/Rosetta/model/pmx/Build.luau"], -[168130, "src/Rosetta/model/pmx/Pmd.luau"], -[168471, "src/Rosetta/model/pmx/Read.luau"], -[168884, "src/Rosetta/model/qb/init.luau"], -[169287, "src/Rosetta/model/rbxm/init.luau"], -[169894, "src/Rosetta/model/rbxmx/init.luau"], -[170563, "src/Rosetta/model/robloxmesh/init.luau"], -[171249, "src/Rosetta/model/robloxmesh/Parse.luau"], -[171711, "src/Rosetta/model/robloxmesh/Write.luau"], -[171822, "src/Rosetta/model/schematic/init.luau"], -[172158, "src/Rosetta/model/schematic/Common.luau"], -[172288, "src/Rosetta/model/schematic/Litematic.luau"], -[172505, "src/Rosetta/model/schematic/Mcedit.luau"], -[172756, "src/Rosetta/model/schematic/Sponge.luau"], -[172889, "src/Rosetta/model/smd/init.luau"], -[172960, "src/Rosetta/model/smd/Read.luau"], -[173237, "src/Rosetta/model/smd/Write.luau"], -[173489, "src/Rosetta/model/stl/init.luau"], -[173958, "src/Rosetta/model/stl/Decode.luau"], -[174037, "src/Rosetta/model/usda/init.luau"], -[174260, "src/Rosetta/model/usda/Build.luau"], -[175577, "src/Rosetta/model/usda/Parse.luau"], -[176399, "src/Rosetta/model/usda/Write.luau"], -[177241, "src/Rosetta/model/vox/init.luau"], -[178146, "src/Rosetta/model/vox/Grid.luau"], -[178209, "src/Rosetta/model/vrml/init.luau"], -[178288, "src/Rosetta/model/x/init.luau"], -[178432, "src/Rosetta/model/x/Build.luau"], -[179008, "src/Rosetta/model/x/Parse.luau"], -[179316, "src/Rosetta/model/x3d/init.luau"], -[179403, "src/Rosetta/music/669/init.luau"], -[179614, "src/Rosetta/music/ahx/init.luau"], -[179669, "src/Rosetta/music/far/init.luau"], -[179903, "src/Rosetta/music/hmp/init.luau"], -[180178, "src/Rosetta/music/hvl/init.luau"], -[180233, "src/Rosetta/music/it/init.luau"], -[180662, "src/Rosetta/music/it/Itsex.luau"], -[180784, "src/Rosetta/music/med/init.luau"], -[181447, "src/Rosetta/music/midi/init.luau"], -[181603, "src/Rosetta/music/midi/Smf.luau"], -[182023, "src/Rosetta/music/mod/init.luau"], -[182386, "src/Rosetta/music/mtm/init.luau"], -[182614, "src/Rosetta/music/mus/init.luau"], -[182779, "src/Rosetta/music/okt/init.luau"], -[183067, "src/Rosetta/music/ptm/init.luau"], -[183296, "src/Rosetta/music/s3m/init.luau"], -[183540, "src/Rosetta/music/sf2/init.luau"], -[183586, "src/Rosetta/music/stm/init.luau"], -[183821, "src/Rosetta/music/ult/init.luau"], -[184132, "src/Rosetta/music/umx/init.luau"], -[184356, "src/Rosetta/music/xm/init.luau"], -[184931, "src/Rosetta/music/xmi/init.luau"], -[185148, "src/Rosetta/ops/AudioOps.luau"], -[185632, "src/Rosetta/ops/ImageOps/init.luau"], -[186323, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[186845, "src/Rosetta/ops/LayerOps.luau"], -[186948, "src/Rosetta/ops/MeshOps/init.luau"], -[188037, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[188206, "src/Rosetta/ops/MusicOps.luau"], -[188577, "src/Rosetta/playlist/m3u/init.luau"], -[188946, "src/Rosetta/playlist/pls/init.luau"], -[189133, "src/Rosetta/playlist/xspf/init.luau"], -[189349, "src/Rosetta/subtitle/ass/init.luau"], -[189807, "src/Rosetta/subtitle/srt/init.luau"], -[189987, "src/Rosetta/subtitle/vtt/init.luau"], -[190197, "src/Rosetta/vector/svg/init.luau"], -[190293, "src/Rosetta/vector/svg/Parse.luau"], -[191053, "src/Rosetta/vector/svg/PathData.luau"], -[191432, "src/Rosetta/vector/svg/Render.luau"], -[191861, "src/Rosetta/vector/svg/Style.luau"], -[192244, "src/Rosetta/vector/svg/Write.luau"], -[192449, "src/Rosetta/vector/tiled/init.luau"], -[192638, "src/Rosetta/vector/tiled/Data.luau"], -[192796, "src/Rosetta/vector/tiled/Tmj.luau"], -[193432, "src/Rosetta/vector/tiled/Tmx.luau"], -[194052, "src/Rosetta/video/avi/init.luau"], -[194357, "src/Rosetta/video/fli/init.luau"], -[194516, "src/Rosetta/video/flv/init.luau"], -[194920, "src/Rosetta/video/flv/Amf.luau"], -[195088, "src/Rosetta/video/flv/Mux.luau"], -[195378, "src/Rosetta/video/h264/init.luau"], -[195525, "src/Rosetta/video/mkv/init.luau"], -[195696, "src/Rosetta/video/mkv/Mux.luau"], -[195983, "src/Rosetta/video/mkv/Parse.luau"], -[196715, "src/Rosetta/video/mp4/init.luau"], -[197058, "src/Rosetta/video/mpegps/init.luau"], -[197253, "src/Rosetta/video/mpegts/init.luau"], -[197501, "src/Rosetta/video/ogv/init.luau"], -[197910, "src/Rosetta/video/smk/init.luau"], -[198232, "src/Rosetta/video/smk/Audio.luau"], -[198357, "src/Rosetta/video/y4m/init.luau"] +[23095, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[23978, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[24313, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[24472, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[25357, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[25458, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[26212, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[26514, "src/Rosetta/codecs/audio/Alac/init.luau"], +[26748, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[27167, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[27579, "src/Rosetta/codecs/audio/Ape/init.luau"], +[27794, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[28555, "src/Rosetta/codecs/audio/ApeTag.luau"], +[28652, "src/Rosetta/codecs/audio/Flac/init.luau"], +[28663, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[29612, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[30209, "src/Rosetta/codecs/audio/Hively/init.luau"], +[30405, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[30654, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[31612, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[31831, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[32015, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[32224, "src/Rosetta/codecs/audio/MidiRender.luau"], +[32570, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[32584, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[32643, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[34246, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[34538, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[34923, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[35564, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[35705, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[35931, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[36276, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[37157, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[37535, "src/Rosetta/codecs/audio/Opus/init.luau"], +[37549, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[39396, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[40461, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[40521, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[40981, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[41318, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[41551, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[43587, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[43961, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[44224, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[44521, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[44803, "src/Rosetta/codecs/audio/Resample/init.luau"], +[45162, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[45216, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[45359, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[45872, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[46653, "src/Rosetta/codecs/audio/Stream.luau"], +[46814, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[47296, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[47574, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[47743, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[47871, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[49859, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[49975, "src/Rosetta/codecs/audio/Tta/init.luau"], +[50092, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[50344, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[50357, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[50741, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[51307, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[51728, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[51767, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[51819, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[52041, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[53496, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[53559, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[53646, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[54615, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[55483, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[55531, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[56047, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[56373, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[56793, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[57228, "src/Rosetta/codecs/compress/Explode.luau"], +[57424, "src/Rosetta/codecs/compress/Lz4.luau"], +[57693, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[58297, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[58837, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[58875, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[59348, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[59524, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[59792, "src/Rosetta/codecs/compress/Lzx.luau"], +[60226, "src/Rosetta/codecs/compress/PackBits.luau"], +[60316, "src/Rosetta/codecs/compress/Quantum.luau"], +[60553, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[60857, "src/Rosetta/codecs/compress/Xxh32.luau"], +[60926, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[60983, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[61941, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[62093, "src/Rosetta/codecs/entropy/Huffman.luau"], +[62375, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[62386, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[62600, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[62844, "src/Rosetta/codecs/font/Bitmap.luau"], +[63045, "src/Rosetta/codecs/font/Cff/init.luau"], +[63686, "src/Rosetta/codecs/font/GlyphNames.luau"], +[63836, "src/Rosetta/codecs/font/TrueType/init.luau"], +[64150, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[64542, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[65044, "src/Rosetta/codecs/image/Bcn/init.luau"], +[65151, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[65640, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[66069, "src/Rosetta/codecs/image/Blend.luau"], +[66448, "src/Rosetta/codecs/image/Dct/init.luau"], +[66829, "src/Rosetta/codecs/image/Etc.luau"], +[67127, "src/Rosetta/codecs/image/Half.luau"], +[67196, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[67550, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[67958, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[68195, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[68955, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[69836, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[70282, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[70360, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[70427, "src/Rosetta/codecs/image/Pixels.luau"], +[70691, "src/Rosetta/codecs/image/Quantize/init.luau"], +[71150, "src/Rosetta/codecs/image/Raster.luau"], +[71847, "src/Rosetta/codecs/image/Texel.luau"], +[72220, "src/Rosetta/codecs/image/Texture.luau"], +[72365, "src/Rosetta/codecs/image/Vp8/init.luau"], +[72495, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[74451, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[74710, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[74959, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[75078, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[75182, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[76035, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[76987, "src/Rosetta/codecs/image/Yuv.luau"], +[77255, "src/Rosetta/codecs/model/Draco/init.luau"], +[77587, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[78056, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[79245, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[79394, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[79753, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[80715, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[81189, "src/Rosetta/codecs/model/Mat4.luau"], +[81448, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[81976, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[82528, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[82607, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[82714, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[82920, "src/Rosetta/codecs/model/Polygon.luau"], +[83154, "src/Rosetta/codecs/model/Rbx/init.luau"], +[83391, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[84145, "src/Rosetta/codecs/model/Rig.luau"], +[84388, "src/Rosetta/codecs/model/Sampler.luau"], +[84548, "src/Rosetta/codecs/model/Vrml/init.luau"], +[84696, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[85270, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[85433, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[86182, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[86704, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[87431, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[87663, "src/Rosetta/codecs/text/Json/init.luau"], +[87932, "src/Rosetta/codecs/text/Json/Decode.luau"], +[88346, "src/Rosetta/codecs/text/Json/Encode.luau"], +[88648, "src/Rosetta/codecs/text/Nbt/init.luau"], +[89001, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[89693, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[90333, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[90571, "src/Rosetta/codecs/text/Text/init.luau"], +[90662, "src/Rosetta/codecs/text/Url/init.luau"], +[90867, "src/Rosetta/codecs/text/Xml/init.luau"], +[91270, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[92010, "src/Rosetta/codecs/video/Dsp.luau"], +[92733, "src/Rosetta/codecs/video/H263/init.luau"], +[92889, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[93747, "src/Rosetta/codecs/video/H263/Tables.luau"], +[93950, "src/Rosetta/codecs/video/H264/init.luau"], +[94323, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[94598, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[95729, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[96497, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[96755, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[97764, "src/Rosetta/codecs/video/H264/Inter.luau"], +[98018, "src/Rosetta/codecs/video/H264/Intra.luau"], +[98425, "src/Rosetta/codecs/video/H264/Mb.luau"], +[99331, "src/Rosetta/codecs/video/H264/Params.luau"], +[99778, "src/Rosetta/codecs/video/H264/Slice.luau"], +[100029, "src/Rosetta/codecs/video/H264/Tables.luau"], +[100070, "src/Rosetta/codecs/video/H264/Transform.luau"], +[100235, "src/Rosetta/codecs/video/Legacy/init.luau"], +[100433, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[100730, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[101097, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[101215, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[101323, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[101596, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[101991, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[102168, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[102180, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[102547, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[104054, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[104193, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[104331, "src/Rosetta/codecs/video/Theora/init.luau"], +[104594, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[105858, "src/Rosetta/codecs/video/Theora/Header.luau"], +[106221, "src/Rosetta/codecs/video/Video/init.luau"], +[106778, "src/Rosetta/codecs/video/Video/Source.luau"], +[107063, "src/Rosetta/containers/Archive.luau"], +[107356, "src/Rosetta/containers/AudioWrap.luau"], +[107877, "src/Rosetta/containers/Avi/init.luau"], +[108449, "src/Rosetta/containers/Chunks.luau"], +[108593, "src/Rosetta/containers/Cpio.luau"], +[109035, "src/Rosetta/containers/Demux.luau"], +[109333, "src/Rosetta/containers/Ebml/init.luau"], +[109670, "src/Rosetta/containers/Fat.luau"], +[110379, "src/Rosetta/containers/Iso9660.luau"], +[110906, "src/Rosetta/containers/IsoBmff/init.luau"], +[111096, "src/Rosetta/containers/IsoBmff/Box.luau"], +[111291, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[112155, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[112685, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[113206, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[113328, "src/Rosetta/containers/MacFile.luau"], +[113488, "src/Rosetta/containers/MpegEs.luau"], +[113663, "src/Rosetta/containers/MpegPs/init.luau"], +[113889, "src/Rosetta/containers/MpegTs/init.luau"], +[114706, "src/Rosetta/containers/Ogg/init.luau"], +[115164, "src/Rosetta/containers/Ogg/Mux.luau"], +[115374, "src/Rosetta/containers/Ogg/Page.luau"], +[115551, "src/Rosetta/containers/Riff/init.luau"], +[115896, "src/Rosetta/containers/Tar.luau"], +[116324, "src/Rosetta/containers/Zip/init.luau"], +[116984, "src/Rosetta/core/Adler32.luau"], +[117036, "src/Rosetta/core/Base64.luau"], +[117205, "src/Rosetta/core/Bits.luau"], +[117517, "src/Rosetta/core/Bytes.luau"], +[118086, "src/Rosetta/core/Crc16.luau"], +[118140, "src/Rosetta/core/Crc32.luau"], +[118263, "src/Rosetta/core/Err.luau"], +[118359, "src/Rosetta/core/Input.luau"], +[118443, "src/Rosetta/core/Md5.luau"], +[118609, "src/Rosetta/core/Sniff.luau"], +[118647, "src/Rosetta/data/cbor/init.luau"], +[118749, "src/Rosetta/data/cbor/Codec.luau"], +[119326, "src/Rosetta/data/csv/init.luau"], +[119643, "src/Rosetta/data/ini/init.luau"], +[119894, "src/Rosetta/data/json/init.luau"], +[119987, "src/Rosetta/data/msgpack/init.luau"], +[120079, "src/Rosetta/data/msgpack/Codec.luau"], +[120527, "src/Rosetta/data/nbt/init.luau"], +[120589, "src/Rosetta/data/plist/init.luau"], +[120897, "src/Rosetta/data/plist/Binary.luau"], +[121170, "src/Rosetta/data/snbt/init.luau"], +[121235, "src/Rosetta/data/toml/init.luau"], +[121307, "src/Rosetta/data/toml/Decode.luau"], +[121944, "src/Rosetta/data/toml/Encode.luau"], +[122160, "src/Rosetta/data/xml/init.luau"], +[122217, "src/Rosetta/data/yaml/init.luau"], +[122296, "src/Rosetta/data/yaml/Emit.luau"], +[122597, "src/Rosetta/data/yaml/Parse.luau"], +[123921, "src/Rosetta/font/bdf/init.luau"], +[124218, "src/Rosetta/font/bmfont/init.luau"], +[124660, "src/Rosetta/font/bmfont/Parse.luau"], +[125119, "src/Rosetta/font/eot/init.luau"], +[125354, "src/Rosetta/font/fon/init.luau"], +[125644, "src/Rosetta/font/hershey/init.luau"], +[125846, "src/Rosetta/font/pcf/init.luau"], +[126138, "src/Rosetta/font/psf/init.luau"], +[126468, "src/Rosetta/font/ttf/init.luau"], +[126522, "src/Rosetta/font/type1/init.luau"], +[126892, "src/Rosetta/font/type1/Charstring.luau"], +[127177, "src/Rosetta/font/woff/init.luau"], +[127311, "src/Rosetta/font/woff2/init.luau"], +[127370, "src/Rosetta/font/woff2/Rebuild.luau"], +[127920, "src/Rosetta/host/init.luau"], +[127972, "src/Rosetta/host/Love.luau"], +[128123, "src/Rosetta/host/LuaJIT.luau"], +[128173, "src/Rosetta/host/Luau.luau"], +[128196, "src/Rosetta/host/Roblox.luau"], +[128587, "src/Rosetta/image/ani/init.luau"], +[128772, "src/Rosetta/image/blp/init.luau"], +[129040, "src/Rosetta/image/bmp/init.luau"], +[129471, "src/Rosetta/image/dds/init.luau"], +[129970, "src/Rosetta/image/exr/init.luau"], +[130754, "src/Rosetta/image/exr/Codec.luau"], +[130873, "src/Rosetta/image/exr/Piz.luau"], +[131242, "src/Rosetta/image/gif/init.luau"], +[131778, "src/Rosetta/image/gif/Decode.luau"], +[131848, "src/Rosetta/image/hdr/init.luau"], +[132084, "src/Rosetta/image/hdr/Codec.luau"], +[132305, "src/Rosetta/image/icns/init.luau"], +[132644, "src/Rosetta/image/ico/init.luau"], +[132928, "src/Rosetta/image/ico/Dib.luau"], +[133029, "src/Rosetta/image/ilbm/init.luau"], +[133355, "src/Rosetta/image/jpeg/init.luau"], +[133506, "src/Rosetta/image/ktx/init.luau"], +[134180, "src/Rosetta/image/pcx/init.luau"], +[134448, "src/Rosetta/image/png/init.luau"], +[135046, "src/Rosetta/image/png/Apng.luau"], +[135130, "src/Rosetta/image/png/Decode.luau"], +[135385, "src/Rosetta/image/png/Encode.luau"], +[135549, "src/Rosetta/image/pnm/init.luau"], +[135935, "src/Rosetta/image/pnm/Codec.luau"], +[136226, "src/Rosetta/image/qoi/init.luau"], +[136350, "src/Rosetta/image/qoi/Codec.luau"], +[136504, "src/Rosetta/image/sgi/init.luau"], +[136792, "src/Rosetta/image/sunras/init.luau"], +[137041, "src/Rosetta/image/tga/init.luau"], +[137319, "src/Rosetta/image/tga/Codec.luau"], +[137478, "src/Rosetta/image/tiff/init.luau"], +[138322, "src/Rosetta/image/tiff/Pixels.luau"], +[138723, "src/Rosetta/image/tim/init.luau"], +[138972, "src/Rosetta/image/vtf/init.luau"], +[139219, "src/Rosetta/image/webp/init.luau"], +[139848, "src/Rosetta/image/webp/Alpha.luau"], +[139926, "src/Rosetta/image/webp/Anim.luau"], +[140090, "src/Rosetta/image/xbm/init.luau"], +[140254, "src/Rosetta/image/xpm/init.luau"], +[140528, "src/Rosetta/image/xpm/Names.luau"], +[140587, "src/Rosetta/layered/aseprite/init.luau"], +[141343, "src/Rosetta/layered/ora/init.luau"], +[141638, "src/Rosetta/layered/psd/init.luau"], +[142383, "src/Rosetta/layered/psd/Channels.luau"], +[142754, "src/Rosetta/model/3ds/init.luau"], +[142856, "src/Rosetta/model/3ds/Build.luau"], +[143521, "src/Rosetta/model/3ds/Read.luau"], +[144029, "src/Rosetta/model/3ds/Write.luau"], +[144858, "src/Rosetta/model/3mf/init.luau"], +[144955, "src/Rosetta/model/3mf/Read.luau"], +[145555, "src/Rosetta/model/3mf/Write.luau"], +[145974, "src/Rosetta/model/b3d/init.luau"], +[146044, "src/Rosetta/model/b3d/Read.luau"], +[146622, "src/Rosetta/model/bsp/init.luau"], +[146774, "src/Rosetta/model/bsp/Brush.luau"], +[147067, "src/Rosetta/model/bsp/Quake3.luau"], +[147330, "src/Rosetta/model/dae/init.luau"], +[147538, "src/Rosetta/model/dae/Math.luau"], +[147586, "src/Rosetta/model/dae/Read.luau"], +[149468, "src/Rosetta/model/dae/Write.luau"], +[149846, "src/Rosetta/model/fbx/init.luau"], +[150014, "src/Rosetta/model/fbx/Ascii.luau"], +[150290, "src/Rosetta/model/fbx/Binary.luau"], +[150753, "src/Rosetta/model/fbx/Read.luau"], +[152139, "src/Rosetta/model/fbx/Write.luau"], +[153137, "src/Rosetta/model/fbx/Xform.luau"], +[153181, "src/Rosetta/model/gltf/init.luau"], +[153435, "src/Rosetta/model/gltf/Pack.luau"], +[153511, "src/Rosetta/model/gltf/Read.luau"], +[154260, "src/Rosetta/model/gltf/Write.luau"], +[154958, "src/Rosetta/model/iqm/init.luau"], +[155042, "src/Rosetta/model/iqm/Read.luau"], +[155403, "src/Rosetta/model/iqm/Write.luau"], +[156111, "src/Rosetta/model/ldraw/init.luau"], +[156218, "src/Rosetta/model/ldraw/Colors.luau"], +[156539, "src/Rosetta/model/ldraw/Read.luau"], +[157121, "src/Rosetta/model/lwo/init.luau"], +[157209, "src/Rosetta/model/lwo/Build.luau"], +[157680, "src/Rosetta/model/lwo/Parse.luau"], +[158233, "src/Rosetta/model/mca/init.luau"], +[158590, "src/Rosetta/model/mca/Chunk.luau"], +[158727, "src/Rosetta/model/mca/Lz4Block.luau"], +[158799, "src/Rosetta/model/md2/init.luau"], +[159010, "src/Rosetta/model/md3/init.luau"], +[159246, "src/Rosetta/model/md5/init.luau"], +[159331, "src/Rosetta/model/md5/Read.luau"], +[159773, "src/Rosetta/model/mdl/init.luau"], +[159859, "src/Rosetta/model/mdl/HalfLife.luau"], +[160201, "src/Rosetta/model/mdl/Quake.luau"], +[160425, "src/Rosetta/model/ms3d/init.luau"], +[160509, "src/Rosetta/model/ms3d/Read.luau"], +[160975, "src/Rosetta/model/ms3d/Write.luau"], +[161463, "src/Rosetta/model/obj/init.luau"], +[162228, "src/Rosetta/model/obj/Mtl.luau"], +[162524, "src/Rosetta/model/off/init.luau"], +[163006, "src/Rosetta/model/ply/init.luau"], +[164156, "src/Rosetta/model/ply/Binary.luau"], +[164370, "src/Rosetta/model/pmx/init.luau"], +[164449, "src/Rosetta/model/pmx/Build.luau"], +[164758, "src/Rosetta/model/pmx/Pmd.luau"], +[165099, "src/Rosetta/model/pmx/Read.luau"], +[165512, "src/Rosetta/model/qb/init.luau"], +[165915, "src/Rosetta/model/rbxm/init.luau"], +[166522, "src/Rosetta/model/rbxmx/init.luau"], +[167191, "src/Rosetta/model/robloxmesh/init.luau"], +[167877, "src/Rosetta/model/robloxmesh/Parse.luau"], +[168339, "src/Rosetta/model/robloxmesh/Write.luau"], +[168450, "src/Rosetta/model/schematic/init.luau"], +[168786, "src/Rosetta/model/schematic/Common.luau"], +[168916, "src/Rosetta/model/schematic/Litematic.luau"], +[169133, "src/Rosetta/model/schematic/Mcedit.luau"], +[169384, "src/Rosetta/model/schematic/Sponge.luau"], +[169517, "src/Rosetta/model/smd/init.luau"], +[169588, "src/Rosetta/model/smd/Read.luau"], +[169865, "src/Rosetta/model/smd/Write.luau"], +[170117, "src/Rosetta/model/stl/init.luau"], +[170586, "src/Rosetta/model/stl/Decode.luau"], +[170665, "src/Rosetta/model/usda/init.luau"], +[170888, "src/Rosetta/model/usda/Build.luau"], +[172205, "src/Rosetta/model/usda/Parse.luau"], +[173027, "src/Rosetta/model/usda/Write.luau"], +[173869, "src/Rosetta/model/vox/init.luau"], +[174774, "src/Rosetta/model/vox/Grid.luau"], +[174837, "src/Rosetta/model/vrml/init.luau"], +[174916, "src/Rosetta/model/x/init.luau"], +[175060, "src/Rosetta/model/x/Build.luau"], +[175636, "src/Rosetta/model/x/Parse.luau"], +[175944, "src/Rosetta/model/x3d/init.luau"], +[176031, "src/Rosetta/music/669/init.luau"], +[176242, "src/Rosetta/music/ahx/init.luau"], +[176297, "src/Rosetta/music/far/init.luau"], +[176531, "src/Rosetta/music/hmp/init.luau"], +[176806, "src/Rosetta/music/hvl/init.luau"], +[176861, "src/Rosetta/music/it/init.luau"], +[177290, "src/Rosetta/music/it/Itsex.luau"], +[177412, "src/Rosetta/music/med/init.luau"], +[178075, "src/Rosetta/music/midi/init.luau"], +[178231, "src/Rosetta/music/midi/Smf.luau"], +[178651, "src/Rosetta/music/mod/init.luau"], +[179014, "src/Rosetta/music/mtm/init.luau"], +[179242, "src/Rosetta/music/mus/init.luau"], +[179407, "src/Rosetta/music/okt/init.luau"], +[179695, "src/Rosetta/music/ptm/init.luau"], +[179924, "src/Rosetta/music/s3m/init.luau"], +[180168, "src/Rosetta/music/sf2/init.luau"], +[180214, "src/Rosetta/music/stm/init.luau"], +[180449, "src/Rosetta/music/ult/init.luau"], +[180760, "src/Rosetta/music/umx/init.luau"], +[180984, "src/Rosetta/music/xm/init.luau"], +[181559, "src/Rosetta/music/xmi/init.luau"], +[181776, "src/Rosetta/ops/AudioOps.luau"], +[182260, "src/Rosetta/ops/ImageOps/init.luau"], +[182951, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[183473, "src/Rosetta/ops/LayerOps.luau"], +[183576, "src/Rosetta/ops/MeshOps/init.luau"], +[184665, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[184834, "src/Rosetta/ops/MusicOps.luau"], +[185205, "src/Rosetta/playlist/m3u/init.luau"], +[185574, "src/Rosetta/playlist/pls/init.luau"], +[185761, "src/Rosetta/playlist/xspf/init.luau"], +[185977, "src/Rosetta/subtitle/ass/init.luau"], +[186435, "src/Rosetta/subtitle/srt/init.luau"], +[186615, "src/Rosetta/subtitle/vtt/init.luau"], +[186825, "src/Rosetta/vector/svg/init.luau"], +[186921, "src/Rosetta/vector/svg/Parse.luau"], +[187681, "src/Rosetta/vector/svg/PathData.luau"], +[188060, "src/Rosetta/vector/svg/Render.luau"], +[188489, "src/Rosetta/vector/svg/Style.luau"], +[188872, "src/Rosetta/vector/svg/Write.luau"], +[189077, "src/Rosetta/vector/tiled/init.luau"], +[189266, "src/Rosetta/vector/tiled/Data.luau"], +[189424, "src/Rosetta/vector/tiled/Tmj.luau"], +[190060, "src/Rosetta/vector/tiled/Tmx.luau"], +[190680, "src/Rosetta/video/avi/init.luau"], +[190985, "src/Rosetta/video/fli/init.luau"], +[191144, "src/Rosetta/video/flv/init.luau"], +[191548, "src/Rosetta/video/flv/Amf.luau"], +[191716, "src/Rosetta/video/flv/Mux.luau"], +[192006, "src/Rosetta/video/h264/init.luau"], +[192153, "src/Rosetta/video/mkv/init.luau"], +[192324, "src/Rosetta/video/mkv/Mux.luau"], +[192611, "src/Rosetta/video/mkv/Parse.luau"], +[193343, "src/Rosetta/video/mp4/init.luau"], +[193686, "src/Rosetta/video/mpegps/init.luau"], +[193881, "src/Rosetta/video/mpegts/init.luau"], +[194129, "src/Rosetta/video/ogv/init.luau"], +[194538, "src/Rosetta/video/smk/init.luau"], +[194860, "src/Rosetta/video/smk/Audio.luau"], +[194985, "src/Rosetta/video/y4m/init.luau"] ] diff --git a/build/rosetta.lua b/build/rosetta.lua index 1cfa771..8ff95f6 100644 --- a/build/rosetta.lua +++ b/build/rosetta.lua @@ -23436,22 +23436,9 @@ return Write end __FILES["codecs/audio/Aac"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program --- config element, explicit and backward-compatible SBR signalling), ADTS headers, and raw_data_block decoding --- (codecs/audio/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it. --- Written from the standard (tables: codecs/audio/Aac/Tables); no third-party code. --- Supports: AAC-LC (object type 2) 1 - 8 channels, all sampling rates, long / short / start / stop windows, sine and KBD --- windows, M/S, intensity stereo, PNS, TNS, pulses. HE-AAC (SBR, PS: object types 5 / 29, or implicit SBR payloads) --- decodes its AAC-LC core at the core rate; `decoder.onExtension` receives every FIL extension payload (the hook for a --- later SBR / PS module), `decoder.sbr` says whether one was seen. Not supported: AAC Main prediction, LTP, SSR gain --- control, coupling channels, 960-sample frames, ER / USAC object types (UNSUPPORTED). --- --- local Aac = require("rosetta.codecs.audio.Aac") --- local dec, err = Aac.decoder(asc) -- an AudioSpecificConfig (buffer) or { objectType, sfIndex, channels } --- local frames, err = dec:decode(buf, offset, length) -- one raw_data_block -> dec.pcm (frames * channels floats) --- local h = Aac.adts(buf, offset, limit) -- an ADTS header: { headerSize, frameSize, objectType, sfIndex, ... } --- --- Never throws: bad data returns nil, Err. +-- 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") @@ -23509,7 +23496,7 @@ local i = br:read(4) return i, Aac.RATES[i + 1] or 0 end --- pce(br) -> channels (program_config_element) +-- program_config_element local function pce(br) br:read(4 + 2 + 4) local front, side, back = br:read(4), br:read(4), br:read(4) @@ -23535,7 +23522,6 @@ br:read(4 + 2 + 4) return channels end --- config(asc) -> Config | nil, Err: parse an AudioSpecificConfig function Aac.config(asc) if type(asc) ~= "buffer" or buffer.len(asc) < 2 then return nil, Err.new(Err.TRUNCATED, "AudioSpecificConfig is shorter than 2 bytes") @@ -23619,7 +23605,6 @@ if type(asc) ~= "buffer" or buffer.len(asc) < 2 then }, nil end --- asc(objectType, sfIndex, channelConfig) -> a 2-byte AudioSpecificConfig function Aac.asc(aot, sfIndex, channelConfig) local b = buffer.create(2) local v = aot * 2048 + sfIndex * 128 + channelConfig * 8 @@ -23628,7 +23613,6 @@ local b = buffer.create(2) return b end --- adts(buf, offset, limit) -> Adts | nil (not a valid header at offset) @@ -23669,7 +23653,6 @@ if o < 0 or o + 7 > limit or o + 7 > buffer.len(b) then protected = protected, } end --- ------------------------------------------------------------------------------------------------ decoder @@ -23700,7 +23683,6 @@ local o = offset or 0 self.sbr = true end if chans == 0 then - -- an empty frame (only fill elements): silence for i = 1, 1024 * self.channels do st.pcm[i] = 0 end @@ -23721,7 +23703,6 @@ local function reset(self) end end --- decoder(asc | { objectType?, sfIndex, channels }) -> Decoder | nil, Err function Aac.decoder(asc) local cfg if type(asc) == "buffer" then @@ -23776,12 +23757,8 @@ __FILES["codecs/audio/Aac/Decode"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/audio/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE / --- FIL / END elements, ics_info with window grouping, section data, scalefactors (with noise energies and intensity --- positions), pulse data, TNS, the eleven spectral codebooks with escapes, dequantisation, M/S and intensity stereo, --- perceptual noise substitution (FFmpeg's LCG so the noise matches it), the filterbank (sine / KBD windows, the four --- window sequences, IMDCT through codecs/audio/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook --- and otherwise skipped. Written from the standard; no third-party code. Never throws: returns nil, message. +-- 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") @@ -23793,11 +23770,10 @@ 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 --- ------------------------------------------------------------------------------------------------ bit reader -- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields) local B= buffer.create(16) -local BP = 0 -- bit position -local BL = 0 -- bit limit +local BP = 0 +local BL = 0 local OVER = false local function getBits(n) @@ -23824,7 +23800,6 @@ if n > 24 then return getBits(n) end --- ------------------------------------------------------------------------------------------------ Huffman local PEEK = 10 @@ -23853,14 +23828,12 @@ for i = 1, 11 do SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i]) end --- the next symbol of a book, -1 for an invalid code local function huff(bk) local e = bk.tab[peekBits(PEEK) + 1] if e > 0 then BP =BP+ band(e, 31) return rshift(e, 5) end - -- a code longer than PEEK bits local code = getBits(PEEK) local map = bk.map for l = PEEK + 1, bk.maxLen do @@ -23873,7 +23846,6 @@ local e = bk.tab[peekBits(PEEK) + 1] return -1 end --- per codebook: dimension, unsigned, modulus, offset 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 } @@ -23885,16 +23857,12 @@ for i = 0, 8191 do POW43[i + 1] = i ^ (4 / 3) end --- ------------------------------------------------------------------------------------------------ windows local SINE_LONG = (Mdct.window("sine", 2048) ) local KBD_LONG = (Mdct.window("kbd", 2048, 4) ) local SINE_SHORT = (Mdct.window("sine", 256) ) local KBD_SHORT = (Mdct.window("kbd", 256, 6) ) local PLAN_LONG = (Mdct.new(2048) ) -local PLAN_SHORT = (Mdct.new(256) )-- ------------------------------------------------------------------------------------------------ state - - - +local PLAN_SHORT = (Mdct.new(256) ) @@ -23943,7 +23911,6 @@ return { end Decode.newChannel = newChannel --- ------------------------------------------------------------------------------------------------ ics local function icsInfo(st, c) if getBits(1) ~= 0 then return "reserved ics bit set" @@ -24169,7 +24136,6 @@ local function applyTns(st, c) end end --- the spectral data of one channel, dequantised into c.spec (also pulses, noise, intensity zeros) local function spectralData(st, c, pulses) local short = c.windowSequence == EIGHT_SHORT local swb = (short and{Tables.SWB_SHORT[st.sfIndex + 1] }or{Tables.SWB_LONG[st.sfIndex + 1] @@ -24305,7 +24271,6 @@ __DARKLUA_CONTINUE_26=true until true if not __DARKLUA_CONTINUE_26 then break en win =win+ glen end if pulses then - -- long window: add the pulses to the quantised values, then dequantise every band for i = 1, #pulses, 2 do local pos = pulses[i] + 1 if pos <= 1024 then @@ -24384,7 +24349,6 @@ local globalGain = getBits(8) return spectralData(st, c, pulses) end --- ------------------------------------------------------------------------------------------------ stereo local function msStereo(st, l, r, mask) local short = l.windowSequence == EIGHT_SHORT local swb = (short and{Tables.SWB_SHORT[st.sfIndex + 1] }or{Tables.SWB_LONG[st.sfIndex + 1] @@ -24438,7 +24402,6 @@ local function intensity(st, l, r, mask, msPresent) end end --- ------------------------------------------------------------------------------------------------ filterbank local function filterbank(st, c, out, stride, offset) local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape local spec, overlap = c.spec, c.overlap @@ -24463,7 +24426,6 @@ end end else local t = st.time Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048) - -- left half if seq == LONG_STOP then local rise = (prev == 1 and{KBD_SHORT }or{SINE_SHORT })[1] for n = 1, 448 do @@ -24481,7 +24443,6 @@ end end frame[n] = t[n] * rise[n] end end - -- right half if seq == LONG_START then local fall = (shape == 1 and{KBD_SHORT }or{SINE_SHORT })[1] for n = 1025, 1472 do @@ -24509,8 +24470,6 @@ end end c.prevShape = shape end --- ------------------------------------------------------------------------------------------------ frame --- frame(st, buf, off, len) -> channels decoded | nil, message. Output: st.pcm, 1024 frames interleaved. function Decode.frame(st, buf, off, len) if buffer.len(B) < len + 16 then B = buffer.create(len + 256) @@ -24679,10 +24638,9 @@ return Decode end __FILES["codecs/audio/Aac/Tables"] = function() --!strict --- codecs/audio/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven --- spectral Huffman codebooks (code, length per symbol), the scalefactor band offsets per sampling rate (1024 and 128 --- lines) and the TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code; --- see licenses/NOTICE.md). Generated; do not edit. +-- 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 = { @@ -25015,19 +24973,8 @@ return Tables end __FILES["codecs/audio/Ac3"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the --- decoder (codecs/audio/Ac3/Decode). Written from ATSC A/52:2018; no third-party code. A codec (layer 3): audio/ac3 --- (raw .ac3 files) builds on it, and the AC-3 tracks of MKV / MP4 / MPEG-TS / AVI reach it through --- containers/AudioWrap. --- Supports: every acmod (1+1, 1/0 .. 3/2) with or without LFE, 32 / 44.1 / 48 kHz, all bit rates, coupling with phase --- flags, rematrixing, block switching, delta bit allocation, dither, dynamic range control (off by default, --- `drc` = 0 .. 1 scales it). Output: every channel in WAVE order (L R C LFE surrounds), no downmix. Not supported: --- E-AC-3 (bsid 11 .. 16) and the reduced-rate bsid 9 / 10 streams (UNSUPPORTED). --- --- local h = Ac3.header(buf, offset, limit) -- { sampleRate, frameSize, channels, acmod, lfeon, bsid, bitrate } --- local dec = Ac3.decoder({ drc = 0 }) -- dec:decode(buf, offset, length) -> 1536, dec.pcm (interleaved) --- --- Never throws: bad data returns nil, Err. +-- 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") @@ -25037,8 +24984,6 @@ local Ac3 = {} local readu8 = buffer.readu8 local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } --- header(buf, o, limit) -> Header | nil (not an AC-3 / E-AC-3 syncframe header at o). E-AC-3 headers (bsid > 10) --- come back with frameSize from their own frmsiz field so a scanner can step over them. @@ -25106,8 +25051,7 @@ if o < 0 or o + 8 > limit or o + 8 > buffer.len(b) then } end --- the CRC-16 of A/52 section 7.10.1 (x^16 + x^15 + x^2 + 1, MSB first, zero start): a syncframe checks when the CRC of --- everything after the sync word is 0 +-- 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 @@ -25124,7 +25068,6 @@ local c = 0 end return c end --- ------------------------------------------------------------------------------------------------ decoder @@ -25191,12 +25134,9 @@ __FILES["codecs/audio/Ac3/Decode"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/audio/Ac3/Decode: one AC-3 syncframe (6 audio blocks of 256 samples) -> PCM. Written from ATSC A/52:2018 --- (section 5.3 syntax, 7.1 exponents, 7.2 parametric bit allocation with delta bit allocation, 7.3 mantissas with --- grouping and dither, 7.4 coupling with phase flags, 7.5 rematrixing, 7.7.1 dynamic range, 7.9 the 512 / 2 x 256 --- inverse transforms with block switching) on codecs/audio/Mdct; no third-party code. The bit reader is module state --- over a frame the caller pads by PAD bytes; every section stops when the position passes the frame. No error / --- assert: failures return nil, "message". +-- 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") @@ -25212,7 +25152,6 @@ 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 --- 2^-e for the exponents 0 .. 24 local POW2 = table.create(32, 0) for e = 0, 31 do POW2[e + 1] = 2 ^ -e @@ -25232,7 +25171,6 @@ local QBITS = { [6] = 5, [7] = 6, [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = local WINDOW = (Mdct.window("kbd", 512, 5) ) local PLAN512 = (Mdct.new(512) ) local PLAN256 = (Mdct.new(256) ) --- ------------------------------------------------------------------------------------------------ bit reader local B= buffer.create(0) local P = 0 @@ -25250,12 +25188,6 @@ if n <= 0 then P =P+ n return v end --- ------------------------------------------------------------------------------------------------ state - - - - - @@ -25367,7 +25299,6 @@ return { } end --- reset(st): forget the overlap (before a seek) function Decode.reset(st) for _, d in __iter(st.delay) do for i = 1, 256 do @@ -25376,9 +25307,7 @@ function Decode.reset(st) end end --- ------------------------------------------------------------------------------------------------ exponents --- read ngrps grouped exponents (7 bits = 3 deltas each) after absexp into e[first + 1 ..] (bins first ..), grpsize --- bins per delta; false when an exponent leaves 0 .. 24 +-- grouped exponents: 7 bits = 3 deltas each after absexp, grpsize bins per delta; each exponent stays in 0 .. 24 local function exponents(e, absexp, ngrps, grpsize, first) local prev = absexp local k = first + 1 @@ -25405,7 +25334,6 @@ local prev = absexp return true end --- ------------------------------------------------------------------------------------------------ bit allocation local function logadd(a, b) local c = a - b local adr = min(rshift((c >= 0 and{c }or{(-c)})[1], 1), 255) @@ -25547,7 +25475,6 @@ end end until stop <= lastbin end --- ------------------------------------------------------------------------------------------------ mantissas -- 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 @@ -25558,7 +25485,6 @@ local s = (st.seed * 1664525 + 1013904223) % 4294967296 return (s / 2147483648 - 1) * 0.707 end --- the mantissas of bins [start, stop) of slot ch into out[], scaled by their exponents (bap 0: dither when asked) local function mantissas(st, ch, start, stop, out, dith) local e, bap = st.exp[ch], st.bap[ch] for bin = start, stop - 1 do @@ -25616,7 +25542,6 @@ local function mantissas(st, ch, start, stop, out, dith) end end --- ------------------------------------------------------------------------------------------------ audio block local function readDba(st, ch) local nseg = bits(3) + 1 local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] @@ -25653,7 +25578,6 @@ local nf, acmod = st.nfchans, st.acmod st.dynrng[i] = 1 end end - -- coupling strategy if bits(1) == 1 then st.cplinu = bits(1) == 1 if st.cplinu then @@ -25717,7 +25641,6 @@ local nf, acmod = st.nfchans, st.acmod end end end - -- rematrixing if acmod == 2 then if bits(1) == 1 then local n = (not cplinu or cplbegf > 2 )and 4 or(cplbegf > 0 and 3 or 2 @@ -25730,7 +25653,6 @@ local nf, acmod = st.nfchans, st.acmod end end end - -- exponent strategies local chexpstr = st.chexpstr chexpstr[CPL] = (cplinu and{(bits(2) )}or{0 })[1] for ch = 1, nf do @@ -25762,7 +25684,6 @@ local nf, acmod = st.nfchans, st.acmod end end endmant[LFE] = 7 - -- exponents if cplinu and chexpstr[CPL] ~= 0 then local abs = bits(4) * 2 local grp = EXPGRP[chexpstr[CPL] ] @@ -25800,7 +25721,6 @@ local nf, acmod = st.nfchans, st.acmod if P > limit then return nil, "truncated block" end - -- bit allocation parameters 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 @@ -25825,7 +25745,6 @@ local nf, acmod = st.nfchans, st.acmod st.cplfleak, st.cplsleak = bits(3), bits(3) end end - -- delta bit allocation if bits(1) == 1 then local modes = table.create(7, 0) if cplinu then @@ -25854,14 +25773,12 @@ local nf, acmod = st.nfchans, st.acmod st.dbaOn[ch] = false end end - -- skip field if bits(1) == 1 then P =P+ bits(9) * 8 end if P > limit then return nil, "truncated block" end - -- bit allocation local zero = st.csnroffst == 0 if zero then for ch = 1, nf do @@ -25892,7 +25809,6 @@ local nf, acmod = st.nfchans, st.acmod if st.lfeon then alloc(LFE, 0, 7, true) end - -- mantissas n1, n2, n4 = 0, 0, 0 local gotCpl = false local coef = st.coef @@ -25964,13 +25880,11 @@ local nf, acmod = st.nfchans, st.acmod return true, nil end --- ------------------------------------------------------------------------------------------------ transform --- the inverse transform of slot ch (long or two short), windowed, overlap-added into out[base + i * step] local function synth(st, ch, short, gain, out, base, step) local x, y, d, w = st.coef[ch], st.y, st.delay[ch], WINDOW if short then -- two 256-point transforms of the interleaved coefficients, phases alpha = -1 (n0 = 0) and +1 (n0 = N / 2) - local z = st.psd -- 256 scratch + 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] @@ -25996,7 +25910,6 @@ local function synth(st, ch, short, gain, out, base, step) end end --- ------------------------------------------------------------------------------------------------ frame -- the output index of each slot (1 .. 5 full bandwidth, 6 LFE) in WAVE order: L R C LFE surrounds local ORDER= { [0] = { 1, 2 }, @@ -26010,8 +25923,6 @@ local ORDER= { } local HAS_C = { [0] = false, true, false, true, false, true, false, true } --- frame(st, buf, len, drc) -> 1536 | nil, message: decodes the syncframe at buf[0 .. len) (padded by PAD bytes) --- into st.pcm (1536 * st.channels interleaved floats, WAVE order). drc: the dynamic range scale (0 = off, 1 = full). function Decode.frame(st, buf, len, drc) if len < 8 or buffer.len(buf) < len + Decode.PAD then return nil, "truncated frame" @@ -26065,7 +25976,6 @@ if len < 8 or buffer.len(buf) < len + Decode.PAD then local nf = NFCHANS[acmod] local channels = nf + (lfeon and 1 or 0) if st.acmod ~= acmod or st.lfeon ~= lfeon then - -- a new channel layout: build the output map and forget the overlap local order = ORDER[acmod] local map = table.create(6, 0) local nfront = HAS_C[acmod] and 3 or(acmod == 1 and 1 or 2 @@ -26107,11 +26017,8 @@ return Decode end __FILES["codecs/audio/Ac3/Tables"] = function() --!strict --- codecs/audio/Ac3/Tables: the AC-3 constant tables, transcribed from ATSC A/52:2018 (Digital Audio Compression --- Standard) section 7.2.3 (bit allocation: slowdec, fastdec, slowgain, dbpbtab, floortab, fastgain, bndtab / bndsz, --- latab, hth, baptab) and section 5.4 (frame sizes). masktab is derived from bndtab / bndsz, the transform window --- (Table 7.33) is the Kaiser-Bessel-derived window with alpha 5 (codecs/audio/Mdct), which Table 7.33 rounds to five --- decimals. No third-party code. +-- 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 } @@ -26121,7 +26028,7 @@ 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 } --- the 50 bit allocation bands: first bin and width (Table 7.12) +-- 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, @@ -26130,7 +26037,7 @@ 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[bin + 1]: the band of each bin (Table 7.13; bins 253 .. 255 map to 0) +-- 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 @@ -26158,7 +26065,7 @@ T.LATAB = { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, } --- hearing threshold per band (Table 7.15): HTH[fscod + 1][band + 1] +-- hearing threshold (Table 7.15): HTH[fscod + 1][band + 1] T.HTH = { { 0x04d0, 0x04d0, 0x0440, 0x0400, 0x03e0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0, @@ -26213,31 +26120,9 @@ __FILES["codecs/audio/Adpcm"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in rosetta; the IMA and --- MS block decoders moved here from audio/wav/Codecs (wav-luau, same author). ADX coefficients, PS-ADPCM and Nintendo --- DSP decoding follow vgmstream r2117 (ISC licence, licenses/vgmstream-LICENSE.txt) so the output is bit-exact with it: --- the ADX scale + 1 and the version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024 --- rounding. Codec kernels only: the formats (wav, aiff, caf, adx, vag, brstm, adpcm, ...) walk the layouts. --- --- Decoders write f32 (sample / 32768) to dst at float index d, every ds floats (interleaving), and keep their running --- state in a caller-owned buffer `st` at byte offset `so` (i32 pairs: IMA pred / step index, the others hist1 / hist2), --- so a decoder can stop between calls and snapshot the state for seeking (codecs/audio/Adpcm/Decoder). --- --- Adpcm.ima(src, p, q0, qs, count, hi, st, so, dst, d, ds) -- IMA nibbles: count samples, nibble q0, q0+qs, ... --- Adpcm.imaQt(src, p, st, so, dst, d, ds) -- Apple ima4: one 34-byte packet -> 64 samples --- Adpcm.imaWav(src, off, avail, ch, spb, dst, d) -> frames -- Microsoft IMA block (WAV / AVI) --- Adpcm.msBlock(src, off, avail, ch, spb, dst, d, coefs, ncoef, st) -> frames -- MS ADPCM block --- Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, st, so, dst, d, ds) -- CRI ADX: 18-byte frames, 32 samples --- Adpcm.adxCoefs(cutoff, rate) -> c1, c2 --- Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) -- Sony PS-ADPCM (VAG): 16-byte frames, 28 samples --- Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) -- Nintendo DSP: 8-byte frames, 14 samples --- Adpcm.modplug(src, p, count, dst, d) -- ModPlug ADPCM (XM / MOD samples) --- Adpcm.swfFrames(src, p, n, ch) -> frames -- Flash (SWF / FLV) ADPCM: one packet's length --- Adpcm.swf(src, p, n, ch, dst, d) -> frames -- Flash ADPCM: one packet of n bytes --- encoders: imaEncode, imaWavEncode, msEncode, adxEncode, psxEncode, dspEncode (see each) --- --- Every function reads only the bytes its arguments describe: the caller checks the ranges (byte counts per call are --- documented on each). Never throws. +-- 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 @@ -26245,7 +26130,6 @@ local floor = math.floor local Adpcm = {} --- ------------------------------------------------------------------------------------------------ IMA 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, @@ -26279,9 +26163,7 @@ for i = 0, 88 do end Adpcm.IMA_STEP = IMA_STEP --- ima: `count` samples of one channel from a nibble stream at byte p: nibble q0, q0 + qs, q0 + 2 qs, ... (nibble q is --- in byte p + q // 2, the low half first unless hi). State: st[so] predictor, st[so + 4] step index. Reads bytes --- p .. p + (q0 + (count - 1) * qs) // 2. +-- IMA nibble q is in byte p + q // 2, the low half first unless hi function Adpcm.ima(src, p, q0, qs, count, hi, st, so, dst, d, ds) local pred = readi32(st, so) @@ -26318,10 +26200,8 @@ function Adpcm.ima(src, p, q0, qs, count, hi, st, so, writei32(st, so + 4, index) end --- imaQt: one Apple ima4 packet (34 bytes at p: a big-endian header, the predictor's top 9 bits and the 7-bit step --- index, then 64 nibbles low first) -> 64 samples. Apple's decoders keep the running full-precision predictor while --- the header agrees with it (the same step index, the predictor within 127): st carries it from packet to packet --- (zeros before the first). +-- Apple ima4: 34 bytes: a big-endian header (the predictor's top 9 bits, 7-bit step index), 64 nibbles low first; +-- Apple's decoders keep the full-precision predictor while the header agrees (same step index, within 127) function Adpcm.imaQt(src, p, st, so, dst, d, ds) local h = readu8(src, p) * 256 + readu8(src, p + 1) local pred = band(h, 0xFF80) @@ -26336,10 +26216,8 @@ function Adpcm.imaQt(src, p, st, so, dst, d, ds) Adpcm.ima(src, p + 2, 0, 1, 64, false, st, so, dst, d, ds) end --- imaWav: one Microsoft IMA ADPCM block (WAV / AVI) at src[off]: per channel a 4-byte header (s16 predictor = the --- first sample, u8 step index, pad), then groups of 4 bytes (8 nibbles, low first) per channel in turn. avail: the --- bytes present (a truncated last block decodes the whole groups it has). Writes interleaved frames to dst from float --- index d; returns the frame count (<= spb). +-- Microsoft IMA block: per channel s16 predictor (= the first sample), u8 step index, pad; then 4-byte groups +-- (8 nibbles, low first) per channel in turn function Adpcm.imaWav(src, off, avail, ch, spb, dst, d) if avail < 4 * ch then return 0 @@ -26382,15 +26260,12 @@ if avail < 4 * ch then return frames end --- ------------------------------------------------------------------------------------------------ MS ADPCM 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 } --- msBlock: one 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. coefs: i32 pairs (coef1, coef2) x --- ncoef (256 = 1.0). state: 20 * ch bytes of scratch. avail: the bytes present. Writes interleaved frames to dst from --- float index d; returns the frame count (<= spb). +-- MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for every channel +-- in turn), then nibbles high first, channels interleaved per nibble; coefficients 256 = 1.0 function Adpcm.msBlock(src, off, avail, ch, spb, dst, d, coefs, ncoef, state) local hdr = 7 * ch @@ -26445,15 +26320,14 @@ local hdr = 7 * ch return frames end --- ------------------------------------------------------------------------------------------------ CRI ADX local F32 = buffer.create(4) local function f32(x) writef32(F32, 0, x) return readf32(F32, 0) end --- adxCoefs(cutoff, rate) -> coef1, coef2 (fixed point, 12 fractional bits): the 2-pole high-pass predictor from the --- header's cutoff frequency, in single precision as CRI's decoders (and vgmstream) compute it +-- coef1, coef2 (12 fractional bits): the 2-pole high-pass predictor from the header's cutoff, in single precision as +-- CRI's decoders (and vgmstream) compute it function Adpcm.adxCoefs(cutoff, rate) if rate <= 0 then return 0, 0 @@ -26469,9 +26343,8 @@ if rate <= 0 then )})[1] return c1, c2 end --- adx: nframes 18-byte frames of one channel (s16 big-endian scale, 32 nibbles high first), pstride bytes apart from --- p. v3: the version 3 rounding (each product shifted on its own). A scale of 0x8001 (CRI's end marker) decodes as --- silence. Reads p .. p + (nframes - 1) * pstride + 17; writes 32 * nframes samples. +-- ADX frame: s16 big-endian scale, 32 nibbles high first. v3 shifts each product on its own; scale 0x8001 (CRI's end +-- marker) decodes as silence function Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, st, so, dst, d, ds) local h1, h2 = readi32(st, so), readi32(st, so + 4) @@ -26514,7 +26387,6 @@ function Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, writei32(st, so + 4, h2) end --- ------------------------------------------------------------------------------------------------ PS-ADPCM local PSX1 = { 0, 60, 115, 98, 122 } local PSX2 = { 0, 0, -52, -55, -60 } @@ -26529,9 +26401,8 @@ local x = PSX1[f] * h1 + PSX2[f] * h2 return (v >= 0 and{(floor(v) )}or{(-floor(-v) )})[1]end --- psx: nframes 16-byte frames of one channel (filter << 4 | shift, flags, 28 nibbles low first), pstride bytes apart --- from p. Filters past 4 decode as 0 and shifts past 12 as 9 (as vgmstream); a frame with flags 7 is silence. The --- history keeps the unclipped value. Reads p .. p + (nframes - 1) * pstride + 15; writes 28 * nframes samples. +-- PS-ADPCM frame: filter << 4 | shift, flags, 28 nibbles low first. Filters past 4 decode as 0 and shifts past 12 as 9 +-- (as vgmstream); flags 7 is silence; the history keeps the unclipped value function Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) local h1, h2 = readi32(st, so), readi32(st, so + 4) @@ -26576,10 +26447,8 @@ function Adpcm.psx(src, p, pstride, nframes, st, so, dst, writei32(st, so + 4, h2) end --- ------------------------------------------------------------------------------------------------ Nintendo DSP --- dsp: count samples of one channel from 8-byte frames at p (predictor << 4 | scale shift, 14 nibbles high first). --- coefs: 16 i32 at byte co (8 pairs, 11 fractional bits); a predictor index past 7 uses pair 7. Reads p .. --- p + ceil(count / 14) * 8 - 1. +-- DSP frame: predictor << 4 | scale shift, 14 nibbles high first; coefs 8 pairs, 11 fractional bits; a predictor +-- index past 7 uses pair 7 function Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) local h1, h2 = readi32(st, so), readi32(st, so + 4) @@ -26617,8 +26486,6 @@ function Adpcm.dsp(src, p, count, coefs, co, st, so, writei32(st, so + 4, h2) end --- ------------------------------------------------------------------------------------------------ encoders --- the nearest s16 to x * 32768 (NaN -> 0) local function toS16(x) local v = floor(x * 32768 + 0.5) if v ~= v then @@ -26632,7 +26499,6 @@ local v = floor(x * 32768 + 0.5) end Adpcm.toS16 = toS16 --- the IMA nibble for x from (pred, index): the one whose decoded value lands nearest (greedy, all 16 tried) local function imaNibble(x, pred, index) local base = index * 8 + 1 local best, bestErr = 0, math.huge @@ -26652,9 +26518,6 @@ local base = index * 8 + 1 return best end --- imaEncode: count samples of one channel, f32 at float index xi every xs floats of x, into nibbles q0, q0 + qs, ... --- of out at byte p (the other half of each byte is kept). State as Adpcm.ima. Writes bytes p .. --- p + (q0 + (count - 1) * qs) // 2. function Adpcm.imaEncode(x, xi, xs, count, st, so, out, p, q0, qs, hi) local pred = readi32(st, so) @@ -26680,9 +26543,7 @@ function Adpcm.imaEncode(x, xi, xs, count, st, so, out, writei32(st, so + 4, index) end --- imaWavEncode: one Microsoft IMA block of spb frames (spb = 1 + 8k) from interleaved f32 x at frame xf (frames --- available: n; the rest is padded with the last sample) to out[off] (4 * ch + (spb - 1) / 2 * ch bytes). st: 8 * ch --- bytes carrying the step index from block to block. +-- Microsoft IMA block: spb = 1 + 8k frames, 4 * ch + (spb - 1) / 2 * ch bytes function Adpcm.imaWavEncode(x, xf, n, ch, spb, st, out, off) local groups = math.floor((spb - 1) / 8 ) for c = 0, ch - 1 do @@ -26716,8 +26577,6 @@ function Adpcm.imaWavEncode(x, xf, n, ch, spb, st, out, off) end end --- one MS ADPCM channel run for the encoder: the nibbles for samples 2 .. n - 1 with predictor (c1, c2) and the first --- delta; returns the squared error and the nibbles in nibs (when given) local function msTrial(xs, n, c1, c2, delta0, nibs) local s1, s2 = xs[2], xs[1] local idelta = delta0 @@ -26740,9 +26599,7 @@ local s1, s2 = xs[2], xs[1] return err end --- msEncode: one MS ADPCM block of spb frames (standard 7 coefficient pairs) from interleaved f32 x at frame xf --- (frames available: n; the rest is padded with silence) to out[off] (7 * ch + (spb - 2) * ch / 2 bytes). Each channel --- takes the predictor with the least error. +-- MS ADPCM block (standard 7 coefficient pairs): 7 * ch + (spb - 2) * ch / 2 bytes function Adpcm.msEncode(x, xf, n, ch, spb, out, off) local C1, C2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 local xs = table.create(spb, 0) @@ -26752,7 +26609,6 @@ function Adpcm.msEncode(x, xf, n, ch, spb, out, off) for i = 1, spb do xs[i] = (i <= n and{(toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) )}or{0 })[1] end - -- the first delta from the first steps local sum = 0 for i = 3, math.min(spb, 10) do sum =sum+ math.abs(xs[i] - xs[i - 1]) @@ -26780,8 +26636,6 @@ function Adpcm.msEncode(x, xf, n, ch, spb, out, off) end end --- one ADX frame for the encoder: the squared error of encoding xs[1..32] with scale from (h1, h2) (v4 rounding), and --- the nibbles in nibs when given; returns the error and the new history local function adxTrial(xs, scale, c1, c2, h1, h2, nibs) local err = 0 for k = 1, 32 do @@ -26800,9 +26654,8 @@ local err = 0 return err, h1, h2 end --- adxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 32) ADX frames +-- 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 --- past count is padded with silence. State as Adpcm.adx. function Adpcm.adxEncode(x, xi, xs, count, c1, c2, st, so, out, p, pstride) local h1, h2 = readi32(st, so), readi32(st, so + 4) @@ -26819,7 +26672,6 @@ function Adpcm.adxEncode(x, xi, xs, count, c1, c2, st, so, b = a a = s end - -- the scale that covers the open-loop residual peak, and a few around it, closed loop local base = math.max(1, math.floor((peak + 6) / 7)) local best, bestErr = base, math.huge for _, m in __iter({ 1, 0.75, 1.25, 0.5, 1.6 }) do @@ -26842,9 +26694,6 @@ function Adpcm.adxEncode(x, xi, xs, count, c1, c2, st, so, writei32(st, so + 4, h2) end --- psxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 28) PS-ADPCM --- frames at out[p], pstride bytes apart, flags byte 0 (the caller sets loop / end flags); every filter and shift is --- tried per frame against Adpcm.psx's decoding, the least squared error wins. State as Adpcm.psx. function Adpcm.psxEncode(x, xi, xs, count, st, so, out, p, pstride) local h1, h2 = readi32(st, so), readi32(st, so + 4) @@ -26879,7 +26728,6 @@ function Adpcm.psxEncode(x, xi, xs, count, st, so, out, end end end - -- the winner again, for its nibbles and history local fi, shift = rshift(bestHead, 4) + 1, band(bestHead, 15) local mul = 2 ^ (20 - shift) for k = 1, 28 do @@ -26900,10 +26748,8 @@ function Adpcm.psxEncode(x, xi, xs, count, st, so, out, writei32(st, so + 4, h2) end --- ------------------------------------------------------------------------------------------------ ModPlug --- modplug: ModPlug / OpenMPT ADPCM samples (XM / MOD sample data marked 0xAD): a table of 16 signed byte deltas at --- p, then count nibbles (low first) at p + 16, each adding its table delta to a running signed byte (wrapping). --- Writes count f32 (value / 128) to dst from float index d. Reads p .. p + 16 + ceil(count / 2) - 1. +-- ModPlug / OpenMPT ADPCM (sample data marked 0xAD): 16 signed byte deltas, then nibbles low first, each adding its +-- delta to a wrapping signed byte; value / 128 function Adpcm.modplug(src, p, count, dst, d) local tab = table.create(16, 0) for k = 0, 15 do @@ -26918,7 +26764,6 @@ function Adpcm.modplug(src, p, count, dst, d) end end --- ------------------------------------------------------------------------------------------------ Flash ADPCM -- 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 @@ -26931,7 +26776,6 @@ local SWF_INDEX= { { -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 }, } --- swfFrames: the frame count of one Flash ADPCM packet (n bytes at p, n >= 1) function Adpcm.swfFrames(src, p, n, ch) if n < 1 or ch < 1 then return 0 @@ -26949,7 +26793,6 @@ if n < 1 or ch < 1 then return frames end --- the k-bit (k <= 16) MSB-first value at bit position pos of src[p ..]; bytes at or past e read as 0 local function msb(src, p, e, pos, k) local q = p + rshift(pos, 3) local v = readu8(src, q) * 65536 @@ -26962,8 +26805,6 @@ local q = p + rshift(pos, 3) return band(rshift(v, 24 - band(pos, 7) - k), lshift(1, k) - 1) end --- swf: one Flash ADPCM packet (n bytes at p, ch channels) -> interleaved f32 frames to dst from float index d; returns --- the frame count (Adpcm.swfFrames). Reads p .. p + n - 1 only. function Adpcm.swf(src, p, n, ch, dst, d) local frames = Adpcm.swfFrames(src, p, n, ch) if frames == 0 then @@ -27031,28 +26872,8 @@ return Adpcm end __FILES["codecs/audio/Adpcm/Decoder"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- codecs/audio/Adpcm/Decoder: the streaming Decoder (Types.Decoder) over an ADPCM stream cut into packets, for the --- formats whose state carries from packet to packet (ADX, VAG, BRSTM, raw IMA): codecs/audio/Stream.packets plus --- exact seeking. The codec state (one buffer the packet decoder advances) is snapshotted at every packet start it --- passes; a seek restores the snapshot, else the format's own state for that packet (BRSTM's ADPC history), else --- decodes forward from the nearest earlier snapshot. New in rosetta. --- --- local dec, err = Decoder.packets(dec, { -- dec: the Decoder table (sampleRate, channels, frames, ...) --- count = n, packetFrames = 4096, -- packets of packetFrames frames (the last may be shorter) --- frames = total, -- output frames --- state = st, -- the codec state buffer decode advances --- decode = function(i, out) return frames end, -- packet i (1-based) as interleaved f32 into out from 0 --- restore = function(i) return false end, -- optional: set st for packet i, true if it could --- }) --- --- The layouts the formats share, each returning the Decoder (dec gets read / seek / position) | nil, Err: --- Decoder.interleaved(dec, spec) psx / adx / dsp frames (or s16 / s8 PCM), channels interleaved every --- spec.interleave bytes (VAG, ADX, BRSTM / BCSTM / BFSTM, raw PS-ADPCM) --- Decoder.nibbles(dec, spec) an IMA nibble stream, channels interleaved by nibble (raw IMA, KVAG) --- Decoder.blocks(dec, spec) self-contained blocks: "ms" / "ima_wav" (blockAlign bytes), "ima_qt" (34 bytes --- per channel), raw or inside AIFF-C / CAF --- --- Never throws (decode failures end the stream and land in dec.error, see codecs/audio/Stream). +-- 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") @@ -27090,7 +26911,6 @@ if i ~= nextPacket then if snaps[i] then buffer.copy(st, 0, snaps[i]) elseif restore and restore(i) then - -- the format set the state (BRSTM's seek table) else local j = i - 1 while j > 1 and not snaps[j] do @@ -27127,11 +26947,9 @@ return out }) end --- ------------------------------------------------------------------------------------------------ layouts local FRAME= { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame local SPF= { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame --- PCM samples of one channel into every ds-th float of dst from float d local function pcm(kind, src, p, n, dst, d, ds) if kind == "s8" then for k = 0, n - 1 do @@ -27149,7 +26967,6 @@ local function pcm(kind, src, p, n, dst, d, ds) end end --- interleaved(dec, spec) -> Decoder | nil, Err @@ -27177,7 +26994,6 @@ local ch = dec.channels end local buf, base, size = spec.buf, spec.offset, spec.size local rowBytes = il * ch - -- rows: the full ones, then the last (which may be shorter, and may be cut by a truncated file) local rows = math.max(1, math.ceil(size / rowBytes)) local function rowFrames(r) local width = (r == rows - 1 and{last }or{il @@ -27240,7 +27056,7 @@ local got = 0 }) end --- nibbles(dec, spec): an IMA stream starting from predictor 0, step index 0, channel c in nibbles c, c + ch, ... +-- IMA from predictor 0, step index 0; channel c in nibbles c, c + ch, ... @@ -27273,7 +27089,6 @@ local f0 = (i - 1) * 4096 }) end --- blockFrames(kind, blockAlign, ch) -> frames per block, or nil when the block cannot hold the headers @@ -27293,7 +27108,6 @@ if kind == "ima_qt" then return (ba >= 4 * ch and((math.floor((ba - 4 * ch) * 2 / ch )+ 1 ))or(nil ))end --- blocks(dec, spec): self-contained ADPCM blocks (no state across blocks); a truncated last block decodes what it has function Decoder.blocks(dec, spec) local ch = dec.channels local kind = spec.kind @@ -27310,7 +27124,6 @@ local ch = dec.channels ) local rest = size - full * ba local total = full * spb if kind ~= "ima_qt" and rest > 0 then - -- a partial last block: the frames it holds whole if kind == "ms" then total =total+ (rest >= 7 * ch and{(math.min(spb, 2 + math.floor(((rest - 7 * ch) * 2) / ch)) )}or{0 })[1] elseif rest >= 4 * ch then @@ -27361,20 +27174,9 @@ return Decoder end __FILES["codecs/audio/Alac"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). --- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice --- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 / --- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels). --- --- local Alac = require("rosetta.codecs.audio.Alac") --- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped) --- local dec = Alac.decoder(cfg) --- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order) --- local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }) --- local packet = enc:encode(samples, first, frames) -- interleaved integers -> one packet (frames <= 4096) --- local cookie = Alac.cookie(enc.config) -- after encoding: maxFrameBytes / avgBitRate filled --- --- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG. +-- 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") @@ -27382,7 +27184,6 @@ local Encode = __include("codecs/audio/Alac/Encode") local Alac = {} --- ALAC channel k (1-based) -> WAV channel (1-based), per channel count @@ -27407,7 +27208,6 @@ local TO_WAV= { { 3, 1, 2, 5, 6, 7, 4 }, { 3, 7, 8, 1, 2, 5, 6, 4 }, } --- the element layout (channels per element) the encoder writes local ELEMENTS= { { 1 }, { 2 }, @@ -27420,7 +27220,6 @@ local ELEMENTS= { } Alac.TO_WAV = TO_WAV --- config(buf, offset?, length?) -> Config | nil, Err function Alac.config(buf, offset, length) local r = Bytes.reader(buf, offset, length) -- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie @@ -27466,7 +27265,6 @@ local r = Bytes.reader(buf, offset, length) return c, nil end --- cookie(cfg) -> the 24-byte ALACSpecificConfig function Alac.cookie(c) local w = Bytes.writer(24) w:u32be(c.frameLength) @@ -27482,7 +27280,6 @@ local w = Bytes.writer(24) w:u32be(c.sampleRate) return w:finish() end --- ------------------------------------------------------------------------------------------------ decoder @@ -27519,7 +27316,6 @@ local o = offset or 0 return frames, nil end --- decoder(cfg) -> Decoder function Alac.decoder(cfg) return { config = cfg, @@ -27528,7 +27324,6 @@ return { state = Decode.state(cfg), } end --- ------------------------------------------------------------------------------------------------ encoder @@ -27560,7 +27355,6 @@ local cfg = self.config return pkt, nil end --- encoder(opts) -> Encoder | nil, Err @@ -27616,10 +27410,8 @@ __FILES["codecs/audio/Alac/Decode"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/audio/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice --- residuals with zero runs, the adaptive FIR predictor (orders 0, 31 and 1 .. 30), stereo unmixing, shifted low bytes, --- uncompressed (escape) frames, 16 / 20 / 24 / 32-bit samples. Written from the ALAC format as published by Apple --- (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). Never throws: returns nil, message. +-- 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 @@ -27646,7 +27438,6 @@ for i = 0, 63 do POW[i + 1] = 2 ^ i end --- bit reader over st.scratch: pos = bit position. bits(n) for n <= 25. local function bitsAt(b, pos, n) local w = byteswap(readu32(b, rshift(pos, 3))) return rshift(lshift(w, band(pos, 7)), 32 - n) @@ -27687,7 +27478,6 @@ local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7)) return x, pos + k - 1 end --- residuals: n values into out[1..n]; returns the new bit position or -1 local function rice(b, pos, limit, out, n, bps, mult, st) local history = st.mb local kb = st.kb @@ -27741,7 +27531,6 @@ local history = st.mb return pos end --- the adaptive FIR predictor: err[1..n] -> out[1..n] (may be the same array); coefs adapt in place local function predict(err, out, n, bps, coefs, order, quant) out[1] = err[1] if n <= 1 then @@ -27795,8 +27584,6 @@ local function predict(err, out, n, bps, coefs, order, quant) end end --- decode(st, buf, off, len) -> frames | nil, message. Samples land interleaved in st.out (integers), channels in the --- ALAC element order. function Decode.frame(st, buf, off, len) if len <= 0 then return nil, "empty packet" @@ -27811,7 +27598,7 @@ if len <= 0 then local limit = len * 8 local pos = 0 local channels = st.channels - local ch = 0 -- next output channel + local ch = 0 local frames = -1 local out = st.out while true do @@ -27946,7 +27733,6 @@ if pos + order[c] * 16 > limit then end shift = 0 end - -- unmix + shifted bytes -> interleaved output local sm = POW[shift + 1] if nch == 2 then local den = POW[mixBits + 1] @@ -28009,7 +27795,6 @@ if pos + order[c] * 16 > limit then return 0, nil end if ch < channels then - -- missing channels: silence for i = 1, frames do for c = ch + 1, channels do out[(i - 1) * channels + c] = 0 @@ -28019,7 +27804,6 @@ if pos + order[c] * 16 > limit then return frames, nil end --- the scratch state for a configuration function Decode.state(cfg) local n = cfg.frameLength return { @@ -28045,11 +27829,8 @@ __FILES["codecs/audio/Alac/Encode"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/audio/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of --- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation, --- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the --- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit --- input. Written for this library from the ALAC format; no third-party code. Never throws. +-- 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 @@ -28064,7 +27845,6 @@ end local DENSHIFT = 9 local PB_FACTOR = 4 --- ------------------------------------------------------------------------------------------------ bit writer @@ -28110,7 +27890,6 @@ local function putBig(st, v, n) end end --- ------------------------------------------------------------------------------------------------ rice code local function signExtend(v, bits) local m = POW[bits + 1] v = v % m @@ -28120,7 +27899,6 @@ local m = POW[bits + 1] return v end --- the bits of one scalar (no writing) local function scalarBits(x, k, m, bps) local pre = (k == 1 and{x }or{(floor(x / m) )})[1] if pre >= 9 then @@ -28140,7 +27918,6 @@ local function scalar(st, x, k, m, bps) putBig(st, x, bps) return end - -- pre ones and a zero put(st, POW[pre + 2] - 2, pre + 1) if k ~= 1 then local r = x - pre * m @@ -28152,7 +27929,6 @@ local function scalar(st, x, k, m, bps) end end --- code the residuals e[1..n] (write = false: just count the bits) local function rice(st, e, n, bps, mult, write) local history = st.mb local kb = st.kb @@ -28206,7 +27982,6 @@ local history = st.mb return bits end --- ------------------------------------------------------------------------------------------------ prediction -- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder) local function residuals(x, e, n, bps, coefs, order, quant) e[1] = x[1] @@ -28245,7 +28020,6 @@ local function residuals(x, e, n, bps, coefs, order, quant) end end --- LPC coefficients of x[1..n] for the given order (Levinson-Durbin on a Welch-windowed autocorrelation), quantised local function lpc(x, n, order, work) local ac = table.create(order + 1, 0) for i = 1, n do @@ -28292,7 +28066,6 @@ local ac = table.create(order + 1, 0) return coefs end --- choose order / coefficients for one channel: returns order, coefs (as transmitted), bits local function analyse(st, x, n, bps) local mult = floor(st.pb * PB_FACTOR / 4) local bestOrder, bestCoefs, bestBits = 0, {}, math.huge @@ -28318,9 +28091,6 @@ __DARKLUA_CONTINUE_17=true until true if not __DARKLUA_CONTINUE_17 then break en return bestOrder, bestCoefs, bestBits end --- ------------------------------------------------------------------------------------------------ frame --- frame(st, samples, first, frames, map) -> buffer: samples interleaved (integers, WAV channel order) from index --- `first`; map[k] = the input channel (1-based) of ALAC channel k; elements: list of 1 / 2 channel counts function Encode.frame(st, samples, first, frames, map, elements) local channels, depth = st.channels, st.bitDepth local n = frames @@ -28343,7 +28113,6 @@ local channels, depth = st.channels, st.bitDepth local bps = depth + nch - 1 local mixRes = 0 if nch == 2 then - -- the mix with the smallest first-difference energy local best = math.huge for res = 0, 4 do local cost = 0 @@ -28378,7 +28147,6 @@ local channels, depth = st.channels, st.bitDepth u[i] = samples[first + (i - 1) * channels + a - 1] end end - -- header put(st, nch == 2 and 1 or 0, 3) put(st, 0, 4) put(st, 0, 12) @@ -28420,7 +28188,6 @@ local channels, depth = st.channels, st.bitDepth end end if not compressed then - -- uncompressed frame buffer.fill(st.out, 0, 0) st.pos = 0 ch = 1 @@ -28472,21 +28239,9 @@ return Encode end __FILES["codecs/audio/Ape"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- codecs/audio/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28 --- (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt): APEHeader.cpp (the descriptor / --- header / seek table, and the pre-3.98 header), APEInfo / APEDecompress.cpp (frame bytes and alignment); the frame --- decoder is codecs/audio/Ape/Decode. Supports file versions 3.95 and later (3.99+ as the current encoder writes; the --- 3.95 - 3.98 range coder model is ported but has no reference fixture), every compression level (fast, normal, high, --- extra high, insane), 8 / 16 / 24 / 32-bit integer and 32-bit float, 1 - 32 channels, special frames (silence, --- pseudo stereo) and the frame CRC. Not supported: versions before 3.95 (UNSUPPORTED), the "interim" 24-bit --- re-decode for files of the 32-bit era before 8.50, big-endian / signed 8-bit source flags (the samples are returned --- as numbers either way). --- --- local info, err = Ape.info(buf, base, limit) -- header facts + the frame table --- local dec = Ape.decoder(info) --- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved; integers, or floats) --- --- Never throws: bad data returns nil, Err. +-- 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") @@ -28515,7 +28270,6 @@ local Ape = {} local FLAG_8, FLAG_24, FLAG_PEAK, FLAG_SEEKN, FLAG_WAVHDR, FLAG_FLOAT = 1, 8, 4, 16, 32, 4096 --- find(buf, base, limit) -> the offset of "MAC " / "MACF" (after an ID3v2 tag) | nil function Ape.find(buf, base, limit) local at = base if limit - at >= 10 and buffer.readstring(buf, at, 3) == "ID3" then @@ -28543,7 +28297,6 @@ local at = base return (k and((at + k - 1 ))or(nil ))end --- info(buf, base, limit) -> Info | nil, Err function Ape.info(buf, base, limit) local at = Ape.find(buf, base, limit) if not at then @@ -28656,7 +28409,6 @@ local at = Ape.find(buf, base, limit) info.limit = limit return info , nil end --- ------------------------------------------------------------------------------------------------ decoder @@ -28685,7 +28437,6 @@ local info = self.info return n2, nil end --- decoder(info) -> Decoder | nil, Err function Ape.decoder(info) local st, msg = Decode.state(info.version, info.level, info.bitsPerSample, info.channels) if not st then @@ -28705,12 +28456,9 @@ __FILES["codecs/audio/Ape/Decode"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/audio/Ape/Decode: one Monkey's Audio frame -> samples. Ported from the Monkey's Audio SDK 13.28 (Matthew T. --- Ashland, BSD 3-clause, licenses/monkeys-audio-LICENSE.txt): UnBitArray.cpp (the range coder and its value model, --- 3.99+) and Old/UnBitArrayOld.cpp (CUnBitArray3891To3989, the 3.95 - 3.98 model), NNFilter / NNFilterCommon.h (the --- neural-net filters of the normal .. insane levels), NewPredictor.cpp (CPredictorDecompress3950toCurrent, its int32 --- and int64 flavours), ScaledFirstOrderFilter.h, Prepare.cpp (Unprepare: X / Y -> channels), APEDecompressCore.cpp --- (special frames, the frame CRC) and FloatTransform.cpp. Never throws: returns nil, message. +-- 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 @@ -28782,7 +28530,6 @@ local FILTERS= { -- level -> { order, shift, ... } in m_spNNFilter, 1, 2 order [5000] = { 1280, 15, 256, 13, 16, 11 }, } --- state(version, level, bits, channels) -> State | nil, message function Decode.state(version, level, bits, channels) local spec = FILTERS[level] if not spec then @@ -28817,7 +28564,6 @@ local spec = FILTERS[level] rc = { q = 0, low = 0, range = 0, prev = 0 }, }, nil end --- ------------------------------------------------------------------------------------------------ entropy -- the range coder as a record (the 3.95 - 3.98 model's RangeDecodeFastWithUpdate) @@ -28840,8 +28586,6 @@ local q, low, range, prev = rc.q, rc.low, rc.range, rc.prev return r end --- values(st, q, n, order, old) -> q | nil, message: n blocks of range-coded values into st.V[c] for the channels of --- `order` (decode order), from byte q of st.S (the range coder starts there) local function values(st, q, lim, n, order, old) local S = st.S local V = st.V @@ -29002,13 +28746,11 @@ local S = st.S return q, nil end --- ------------------------------------------------------------------------------------------------ NN filters -- ((v >> s) & m) ~= 0 for an int64 v (s given as 2^s) local function negBit(v, p2, m) return band((math.floor(v / p2)) % TWO32, m) ~= 0 end --- the int16 dot product of the weights and the inputs from byte b (span bytes) local function dot16(M, I, b, span) local dot = 0 for k = 0, span - 16, 16 do @@ -29036,8 +28778,7 @@ local dot = 0 return dot end --- one CNNFilter over n values of v, in place (DecompressGeneric). The weights, inputs and deltas live in buffers of --- the C types (int16 for 8 - 24-bit files, int32 for 32-bit ones: `wide`), so the weights wrap as the C shorts do +-- one CNNFilter (DecompressGeneric); weights in the C types (int16 up to 24-bit files, int32 for 32-bit) wrap as C does local function nnFilter(f, v, n, newDelta, wide) local order, M, I, D = f.order, f.M, f.I, f.D local es = wide and 4 or 2 @@ -29046,7 +28787,7 @@ local function nnFilter(f, v, n, newDelta, wide) ) 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 -- the current element (0-based); its history is p - order .. p - 1 + local p = order local total = 512 + order local avg = 0 local span = order * 2 @@ -29125,7 +28866,6 @@ local function nnFilter(f, v, n, newDelta, wide) end end --- ------------------------------------------------------------------------------------------------ predictor -- the adapt sign of a 32-bit file's int64 prediction value: ((v >> 30) & 2) - 1, or 0 local function adaptWide(v) if v == 0 then @@ -29134,8 +28874,7 @@ if v == 0 then return (math.floor(v / 1073741824)) % 4 >= 2 and 1 or-1 end --- predict(st, a, b?, n) : CPredictorDecompress3950toCurrent over channel a's values (nB = channel b's outputs of the --- block, or 0), single-channel form; stereo uses predictStereo +-- CPredictorDecompress3950toCurrent, single-channel form local function predictOne(st, v, n) local wide = st.bits >= 32 local lastA, prevA0, A1, A2, A3 = 0, 0, 0, 0, 0 @@ -29193,7 +28932,6 @@ local function predictStereo(st, X, Y, n) local xStage = 0 local lastX = 0 for t = 1, n do - -- Y local nA = Y[t] local A0 = yLast yA3 = yA2 @@ -29243,7 +28981,6 @@ local function predictStereo(st, X, Y, n) yStage = wrap32(cur + math.floor((yStage * 31) / 32)) yLast = cur local yv = yStage - -- X nA = X[t] A0 = xLast xA3 = xA2 @@ -29296,10 +29033,6 @@ local function predictStereo(st, X, Y, n) end end --- ------------------------------------------------------------------------------------------------ frame --- frame(st, buf, at, rem, stop, n, P, float) -> n | nil, message: the frame whose words start at byte `at` (its first --- byte at at + rem), reading at most up to `stop`; n blocks into P (interleaved integers, or floats when float); cut: --- the data ends at `stop` before the frame does (a running-over decode is then "truncated", else corrupt) function Decode.frame(st, buf, at, rem, stop, n, P, float, cut) local C, bits = st.channels, st.bits local len = math.max(0, stop - at) @@ -29340,10 +29073,9 @@ return readu8(S, q) * 16777216 + readu8(S, q + 1) * 65536 + readu8(S, q + 2) * 2 end stored =stored% TWO31 end - -- the values local V = st.V local order -local mode -- "silence", "pseudo", "stereo", "mono", "multi" +local mode if C == 1 then if band(special, 1) ~= 0 then mode = "silence" @@ -29398,7 +29130,7 @@ local mode -- "silence", "pseudo", "stereo", "mono", "multi" cb = buffer.create(n * C * bps + 1024) st.crcbuf = cb end - local paired= {} -- first channel (0-based) of an X / Y pair + local paired= {} if C == 2 and mode == "stereo" then paired[0] = true elseif C == 4 and (bits == 16 or bits == 24) then @@ -29483,19 +29215,9 @@ return Decode end __FILES["codecs/audio/ApeTag"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and --- some MP3s) -> Types.Tags. Written from the APEv2 specification (wiki.hydrogenaud.io "APEv2 specification"); no --- third-party code. A tag sits at the end of the file (before an optional ID3v1 tag) as items + a 32-byte footer --- "APETAGEX", with an optional 32-byte header in front (APEv2). Item keys become lower case tag keys (Year -> date, --- Track -> track, Album Artist -> albumartist, Disc -> disc, Comment -> comment); text values holding several --- values (NUL separated) are joined with "; "; binary items (cover art) and external links stay in info.items. --- Never throws. --- --- local tags, info = ApeTag.find(buf, start, limit) -- the tag ending at limit (or before an ID3v1 tag there) --- -- tags: { title = ..., artist = ... } | nil (no tag / malformed) --- -- info: { start = first byte (the header when present), stop = past the footer, version = 1000 | 2000, --- -- items = { { key = "Title", value = "...", kind = "text" | "binary" | "link" } } } --- local tags, info = ApeTag.parse(buf, footer, start) -- the tag whose footer is at byte `footer` (>= start) +-- 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 = {} @@ -29511,14 +29233,11 @@ local TO_TAG= { } local KINDS = { [0] = "text", "binary", "link", "text" } --- tagKey(itemKey) -> the Types.Tags key function ApeTag.tagKey(key) local k = string.lower(key) return TO_TAG[k] or k end --- parse(buf, footer, start?) -> tags, info | nil: the tag whose 32-byte footer starts at byte `footer`; the items --- must lie at or after `start` (default 0) function ApeTag.parse(buf, footer, start) local lo = start or 0 local n = buffer.len(buf) @@ -29573,8 +29292,6 @@ local lo = start or 0 return tags, { start = first, stop = footer + 32, version = version, items = items } end --- find(buf, start, limit) -> tags, info | nil: the tag at the end of [start, limit), or just before a 128-byte --- ID3v1 tag ("TAG") there function ApeTag.find(buf, start, limit) if limit > buffer.len(buf) then limit = buffer.len(buf) @@ -29595,10 +29312,8 @@ return ApeTag end __FILES["codecs/audio/Flac"] = function() --!strict --- codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim, --- fixed, LPC, Rice residuals, stereo decorrelation) with CRC-8 / CRC-16 (Frame), and the frame encoder (Encode). --- Absorbed from flac-luau 7083d0d (same author); the encoder is new. Native FLAC / Ogg FLAC streams, metadata and --- seeking are audio/flac. +-- 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"), @@ -29610,15 +29325,8 @@ __FILES["codecs/audio/Flac/Encode"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 --- codecs/audio/Flac/Encode: the FLAC encoder (RFC 9639). New code, written from the RFC; the presets mirror libFLAC's -0 .. -8 --- (block size 1152 / 4096, max LPC order 0 / 6 / 8 / 12, Rice partition order 3 .. 6, independent / adaptive / --- exhaustive stereo decorrelation). Subframes: CONSTANT, VERBATIM, FIXED (order 0..4, chosen by the residual sum), --- LPC (Levinson-Durbin on the tukey(0.5)-windowed autocorrelation, error-feedback coefficient quantization with --- libFLAC's precision table, the order estimated from the prediction error or searched exhaustively at -8), wasted --- bits; Rice / Rice2 partitions with the partition order and parameters searched per subframe. Frames carry CRC-8 / --- CRC-16; STREAMINFO carries the sizes, total samples and the MD5 of the PCM; VORBIS_COMMENT from the tags; an optional --- SEEKTABLE. Streams: input blocks are pulled from a codecs/audio/Pcm Source, so a Decoder is encoded without decoding it --- whole. Never throws: bad options are rejected by audio/flac before calling in. +-- 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") @@ -29634,8 +29342,6 @@ for i = 0, 63 do POW[i + 1] = 2 ^ i end --- ------------------------------------------------------------------------------------------------ CRCs --- (the decoder's tables: codecs/audio/Flac/Frame; (b, offset, count) here) local function crc8(b, o, n) return Frame.crc8(b, o, o + n) end @@ -29643,7 +29349,6 @@ local function crc16(b, o, n) return Frame.crc16(b, o, o + n) end Encode.crc8, Encode.crc16 = crc8, crc16 --- ------------------------------------------------------------------------------------------------ bit writer (MSB first) @@ -29682,7 +29387,6 @@ local function putUtf8(w, v) put(w, 0x80 + floor(v / POW[6 * k + 1]) % 64, 8) end end --- ------------------------------------------------------------------------------------------------ presets @@ -29703,8 +29407,6 @@ local PRESETS= { { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = true }, } Encode.PRESETS = PRESETS --- ------------------------------------------------------------------------------------------------ analysis --- a subframe plan for one channel signal @@ -29739,8 +29441,6 @@ return { x = table.create(n, 0), } end --- scratch per encoder --- rice(res, n, order, maxP, plan?) -> bits, porder, method (fills scratch.bestKs with the parameters) @@ -29757,8 +29457,7 @@ end -local function rice(sc, res, n, order, maxP) -- the finest usable partition order - +local function rice(sc, res, n, order, maxP) local p = maxP while p > 0 and (n % POW[p + 1] ~= 0 or math.floor(n / POW[p + 1] )<= order) do p =p- 1 @@ -29766,8 +29465,7 @@ local p = maxP local sums, counts = sc.sums, sc.counts local parts = POW[p + 1] local ps = math.floor(n / parts -) -- sums of zig-zag values at the finest order - for j = 0, parts - 1 do +) for j = 0, parts - 1 do local s = 0 local a = (j == 0 and((order + 1 ))or((j * ps + 1 ))) local e = (j + 1) * ps @@ -29815,7 +29513,6 @@ local p = maxP if q == 0 then break end - -- merge pairs into the next coarser order for j = 1, math.floor(np / 2 )do sums[j] = sums[2 * j - 1] + sums[2 * j] counts[j] = counts[2 * j - 1] + counts[2 * j] @@ -29833,7 +29530,6 @@ local function keepRice(sc, plan, porder, method) end end --- fixed predictor residuals local function fixedResidual(x, n, order, res) for i = 1, order do res[i] = 0 @@ -29919,7 +29615,6 @@ if bps > 16 then return 13 end --- quantize coefficients lp[1..order] to precision bits: qlp[1..order], shift | nil local function quantize(lp, order, precision, qlp) local cmax = 0 for i = 1, order do @@ -29981,7 +29676,6 @@ local function lpcResidual(x, n, order, qlp, shift, res) end end --- Levinson-Durbin: sc.lpc[o][1..o] and sc.err[o] for o = 1 .. maxOrder; returns the highest usable order local function levinson(sc, maxOrder) local r = sc.autoc local e = r[1] @@ -30016,10 +29710,8 @@ local r = sc.autoc return maxOrder end --- choose the subframe for signal x (n samples, bps bits) into plan (reusing its arrays) local function analyze(sc, cfg, src, n, bps, plan) local x = plan.x - -- constant? local first = src[1] local constant = true for i = 1, n do @@ -30033,7 +29725,6 @@ local function analyze(sc, cfg, src, n, bps, plan) plan.res[1] = first return end - -- wasted bits: the common trailing zeros local wasted = 0 do local w = 0 @@ -30060,9 +29751,7 @@ local function analyze(sc, cfg, src, n, bps, plan) local b = bps - wasted local hdr = 8 + wasted plan.wasted, plan.bps = wasted, b - -- verbatim plan.kind, plan.bits = 1, hdr + n * b - -- fixed local fo = bestFixedOrder(x, n) if n > fo then local tmp = sc.tmpRes @@ -30075,10 +29764,8 @@ local function analyze(sc, cfg, src, n, bps, plan) keepRice(sc, plan, po, me) end end - -- lpc local maxOrder = math.min(cfg.maxLpcOrder, n - 1, 32) if maxOrder > 0 then - -- windowed autocorrelation local win = sc.win if sc.winN ~= n then -- tukey(0.5) @@ -30151,7 +29838,6 @@ local function analyze(sc, cfg, src, n, bps, plan) end end --- ------------------------------------------------------------------------------------------------ writing local function writeResidual(w, plan, n) local method = plan.method put(w, method, 2) @@ -30257,8 +29943,6 @@ if n == 192 then end return 7, 16 end --- ------------------------------------------------------------------------------------------------ encoder --- encode(src, opts) -> buffer | nil, message @@ -30282,7 +29966,6 @@ local cfg = PRESETS[opts.level + 1] local ch, rate, bps = src.channels, src.sampleRate, opts.bits local bs = opts.blockSize or cfg.blockSize local w= { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } - -- metadata put(w, 0x664C6143, 32) -- "fLaC" put(w, 0, 1) put(w, 0, 7) @@ -30291,7 +29974,6 @@ local cfg = PRESETS[opts.level + 1] for _ = 1, 34 do put(w, 0, 8) end - -- seek table placeholders (when the length is known) local seekPoints = 0 local seekAt = 0 local interval = floor(opts.seekInterval * rate) @@ -30301,14 +29983,12 @@ local cfg = PRESETS[opts.level + 1] seekPoints = 0 end end - -- vorbis comment local comments = VorbisComment.fields(src.tags) local vendor = opts.vendor local vcLen = 4 + #vendor + 4 for _, c in __iter(comments) do vcLen =vcLen+ (4 + #c ) end - -- SEEKTABLE if seekPoints > 0 then put(w, 0, 1) put(w, 3, 7) @@ -30356,7 +30036,6 @@ local cfg = PRESETS[opts.level + 1] end end local audioStart = w.pos - -- frames local md5 = Md5.new() local mbytes = math.floor((bps + 7) / 8 ) local mbuf = buffer.create(bs * ch * mbytes) @@ -30403,7 +30082,6 @@ for c = 1, ch do local tmp= nil local pendingBuf= nil local pendingN, pendingOff = 0, 0 - -- read exactly bs frames (fewer only at the end) local function readBlock() local out = buffer.create(bs * ch * 4) local got = 0 @@ -30450,7 +30128,6 @@ local out = buffer.create(bs * ch * 4) end end md5:update(mbuf, 0, mo) - -- channel decorrelation local assign = ch - 1 local chosen= {} if ch == 2 and cfg.stereo ~= "independent" then @@ -30509,14 +30186,12 @@ local out = buffer.create(bs * ch * 4) chosen[c] = plans[4 + c] end end - -- the frame local need = n * ch * 4 + 64 for _, p in __iter(chosen) do need =need+ ((math.floor(p.bits / 8)) + 8 ) end ensure(w, need) local start = w.pos - -- seek points: the first frame at or after each multiple of the interval while seekIdx < seekPoints and total >= seekNext do local at = seekAt + seekIdx * 18 local sn, off = total, start - audioStart @@ -30566,7 +30241,6 @@ local out = buffer.create(bs * ch * 4) if src.err then return nil, tostring(src.err) end - -- unused seek points stay placeholders; STREAMINFO local out = buffer.create(w.pos) buffer.copy(out, 0, w.buf, 0, w.pos) local si = Encode.streaminfo(bs, (frameNo > 0 and{minFrame }or{0})[1], maxFrame, rate, ch, bps, total, md5:digest()) @@ -30574,7 +30248,7 @@ local out = buffer.create(bs * ch * 4) return out, nil end --- streaminfo(...) -> the 34-byte STREAMINFO body +-- STREAMINFO: 34 bytes function Encode.streaminfo(bs, minFrame, maxFrame, rate, ch, bps, total, md5) local w= { buf = buffer.create(64), pos = 0, acc = 0, cnt = 0 } put(w, bs, 16) @@ -30600,13 +30274,9 @@ __FILES["codecs/audio/Flac/Frame"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/audio/Flac/Frame: FLAC frames: header parsing (CRC-8), the sync search, subframes (constant, verbatim, fixed, LPC, wasted bits), --- residuals (Rice / Rice2 partitions, escapes), stereo decorrelation and the CRC-16 check. --- --- The input buffer must have at least PAD zero bytes after the data end (`len`): the bit reader reads 32-bit --- words without bounds checks and instead compares its position with the data end once per sample. Nothing here --- throws: bad data gives nil, err. --- Absorbed from flac-luau 7083d0d (same author, no third-party code). +-- 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 @@ -30660,8 +30330,6 @@ local RATE = { [1] = 88200, [2] = 176400, [3] = 192000, [4] = 8000, [5] = 16000, [8] = 32000, [9] = 44100, [10] = 48000, [11] = 96000 } local BITS = { [1] = 8, [2] = 12, [4] = 16, [5] = 20, [6] = 24, [7] = 32 } --- Parse the frame header at pos (data ends at len; the buffer is padded). si gives the STREAMINFO defaults --- (sampleRate, bitsPerSample) for the "from STREAMINFO" codes. Returns nil when it is not a valid header. @@ -30754,7 +30422,6 @@ if pos < 0 or pos + 6 > len then if not bs or not bps or bps < 4 or bps > 32 or p + 1 > len then return nil end - -- CRC-8 over the header if crc8(b, pos, p) ~= readu8(b, p) then return nil end @@ -30771,7 +30438,6 @@ if pos < 0 or pos + 6 > len then } end --- The first valid header at an offset in [pos, limit) function Frame.find(b, pos, limit, len, si) local lim = math.min(limit, len - 6) if pos < 0 then @@ -30792,7 +30458,6 @@ local lim = math.min(limit, len - 6) return nil end --- Bit reading for the header parts of subframes: n <= 32 bits at bit position p (unsigned) local function bits(b, p, n) if n == 0 then return 0 @@ -30812,7 +30477,6 @@ local v = bits(b, p, n) return v end --- Residual coding: fills s[order + 1 .. n] with residuals. Returns the new bit position, or -1. local function residual(b, p, lim, s, n, order) local method = bits(b, p, 2) if method > 1 then @@ -30857,7 +30521,6 @@ local method = bits(b, p, 2) end end elseif k <= 24 then - -- the hot loop: unary quotient + k-bit remainder, zigzag local pk = POW2[k + 1] local rk = 32 - k for j = i, stop do @@ -30879,7 +30542,6 @@ local method = bits(b, p, 2) p =p+ k end else - -- a long run of zeros q = 32 - sh p =p+ q while true do @@ -31047,7 +30709,6 @@ local function lpc(s, n, cf, order, shift) end end --- One subframe into s[1..n]. Returns the new bit position, or -1. local function subframe(b, p, lim, s, n, bps, cf) if p > lim then return -1 @@ -31157,8 +30818,6 @@ if p > lim then return p end --- Decode the frame whose header h was parsed (data ends at len). chans[c] are tables of at least h.blockSize --- numbers; they receive the samples. Returns the byte offset after the frame, or nil, err. function Frame.decode(b, len, h, chans, cf, checkCrc) local n = h.blockSize local lim = len * 8 @@ -31174,7 +30833,7 @@ local n = h.blockSize return nil, "bad subframe" end end - local e = rshift(p + 7, 3) -- byte align + local e = rshift(p + 7, 3) if e + 2 > len then return nil, "truncated frame" end @@ -31210,19 +30869,10 @@ return Frame end __FILES["codecs/audio/Hively"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats --- (Load), the replayer with its waveform generator (Tables: triangle / sawtooth / square / noise and the 31 + 31 --- filtered copies) and integer mixer (Player), and the render glue to a Types.Decoder (stereo f32). A port of --- HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt): --- at hvl2wav's settings the output equals hvl2wav's 16-bit samples / 32768, sample for sample. --- --- local Hively = require("rosetta.codecs.audio.Hively") --- local tune, err = Hively.parse(buf, 0, buffer.len(buf)) -- the replayer's Tune --- local song = Hively.module(tune) -- a Types.Module-shaped value with render() --- local dec = Hively.decoder(tune, { sampleRate = 44100 }) -- a Types.Decoder --- --- Not supported: hvl2wav's -a auto gain; a speed multiplier of 4 at 44.1 kHz renders 880 samples per 50 Hz frame --- (hvl2wav pads each frame to 882 with stale samples). +-- 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") @@ -31231,7 +30881,6 @@ local Pcm = __include("codecs/audio/Pcm") local Hively = {} --- parse(b, base?, limit?) -> Tune | nil, Err @@ -31262,7 +30911,6 @@ local o= opts or {} return rate, sub, tonumber(o.stereo) or 0, nil end --- frameCount(tune, opts?) -> 50 Hz frames until the song end (as hvl2wav stops), capped by maxDuration function Hively.frameCount(tune, opts) local rate, sub, stereo = settings(tune, opts) local st = rate and Player.new(tune, rate , stereo, sub) @@ -31280,7 +30928,6 @@ local rate, sub, stereo = settings(tune, opts) return n end --- decoder(tune, opts?) -> Types.Decoder | nil, Err function Hively.decoder(tune, opts) local rate, sub, stereo, err = settings(tune, opts) if not rate then @@ -31295,7 +30942,7 @@ local mult = tune.speedMultiplier local loop = opts ~= nil and opts.loop == true local st = (Player.new(tune, sr, stereo, sub) ) local fbuf = buffer.create(perFrame * 8) - local fpos, ffill = 0, 0 -- read position / filled frames inside fbuf + local fpos, ffill = 0, 0 local pos = 0 local function nextFrame() @@ -31358,8 +31005,6 @@ return pos / sr return (dec ) , nil end --- module(tune) -> a Types.Module-shaped value (kind "music"): tracks as patterns (rows * 6 bytes: note, instrument, --- fx, param, fxb, paramb), positions, instruments with their play lists, and render(opts) -> Decoder function Hively.module(tune) local patterns = {} for t = 0, tune.trackNr do @@ -31409,7 +31054,6 @@ local dec, derr = Hively.decoder(self.tune, opts) if dec then return dec end - -- the Types contract returns a Decoder: a failed render is an empty one carrying the Err local empty= Pcm.audioDecoder(Types.Audio.new(44100, 2, 0)) empty.err = derr return empty @@ -31421,10 +31065,9 @@ return Hively end __FILES["codecs/audio/Hively/Load"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- codecs/audio/Hively/Load: AHX ("THX\0".."THX\2") and HivelyTracker ("HVL\0", "HVL\1") module files -> the replayer's --- Tune. Ported from hvl2wav's replay.c 1.9 loaders (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. Errors are returned as --- (nil, message, kind) for core/Err.from. +-- 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 @@ -31476,7 +31119,6 @@ local e = p return buffer.readstring(b, p, e - p), e end --- parse(b, base, limit) -> Tune | nil, message, kind function Load.parse(b, base, limit) local size = limit - base if size < 14 then @@ -31673,11 +31315,9 @@ end __FILES["codecs/audio/Hively/Player"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --- codecs/audio/Hively/Player: the AHX / HivelyTracker replayer: positions and tracks (two effect columns in HVL), the --- instrument engine (ADSR, vibrato, the PList performance list, square modulation, the resonant filter sweep, hard cut, --- ring modulation and panning for HVL) and the integer mixer, all as hvl2wav's replay.c 1.9 computes them so the output --- matches hvl2wav sample for sample. 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. +-- 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") @@ -31775,7 +31415,6 @@ return { } end --- new(tune, freq, stereo, subsong) -> State | nil (subsong out of range). stereo: AHX separation 0..4 (HVL: the file's) function Player.new(tune, freq, stereo, subsong) if subsong < 0 or subsong > #tune.subsongs then return nil @@ -31803,7 +31442,6 @@ if subsong < 0 or subsong > #tune.subsongs then return st end --- ------------------------------------------------------------------------------------------------ steps local function setPan(st, v, p) v.pan = p v.panMultLeft, v.panMultRight = st.panL[p], st.panR[p] @@ -32043,7 +31681,6 @@ local function processStep(st, v) stepfx3(st, v, fxb, fxbp) end --- ------------------------------------------------------------------------------------------------ frames local function plistCommand(st, v, fx, param) if fx == 0 then if param > 0 and param < 0x40 then @@ -32210,7 +31847,6 @@ local function processFrame(st, v) end end - -- ADSR envelope if v.aFrames ~= 0 then v.adsrVolume =v.adsrVolume+ v.aVolume v.aFrames =v.aFrames- 1 @@ -32233,10 +31869,8 @@ local function processFrame(st, v) end end - -- volume slide v.noteMaxVolume = math.clamp(v.noteMaxVolume + v.volumeSlideUp - v.volumeSlideDown, 0, 0x40) - -- portamento if v.periodSlideOn then if v.periodSlideWithLimit then local d0 = v.periodSlidePeriod - v.periodSlideLimit @@ -32261,7 +31895,6 @@ local function processFrame(st, v) end end - -- vibrato if v.vibratoDepth ~= 0 then if v.vibratoDelay <= 0 then v.vibratoPeriod = math.floor((VIB[v.vibratoCurrent] * v.vibratoDepth) / 128 @@ -32272,7 +31905,6 @@ local function processFrame(st, v) end end - -- PList local pl = v.perfList if pl then if v.instrument and v.perfCurrent < v.instrument.plist.length then @@ -32309,7 +31941,6 @@ local function processFrame(st, v) end end - -- perf portamento if v.periodPerfSlideOn then v.periodPerfSlidePeriod = s16(v.periodPerfSlidePeriod - v.periodPerfSlideSpeed) if v.periodPerfSlidePeriod ~= 0 then @@ -32427,7 +32058,6 @@ local function processFrame(st, v) end end - -- ring modulation period if v.ringAudioOff >= 0 then local rp = v.ringBasePeriod if v.ringFixedPeriod == 0 then @@ -32445,7 +32075,6 @@ local function processFrame(st, v) v.ringAudioPeriod = math.clamp(rp, 0x71, 0xd60) end - -- the period local ap = v.instrPeriod if v.fixedNote == 0 then if v.overrideTranspose ~= 1000 then @@ -32467,7 +32096,6 @@ local function processFrame(st, v) ) v.audioVolume = s16(vol) end --- fill the 0x280-byte voice buffer with repeats of the 4 << waveLength cycle at (src, off) local function fillCycles(dst, src, off, len) if off < 0 or off + len > buffer.len(src) then buffer.fill(dst, 0, 0, 0x281) @@ -32503,7 +32131,7 @@ local function setAudio(st, v) end end --- irq(st, audio): one player call (hvl_play_irq); audio = false skips the audio side (duration scans) +-- hvl_play_irq (audio = false skips the audio side) function Player.irq(st, audio) local tune = st.tune local nch = st.channels @@ -32561,7 +32189,7 @@ function Player.irq(st, audio) end end --- mix(st, out, at, n): n stereo frames of f32 into out at frame `at` (hvl_mixchunk: integer mixing, s16 clipping, / 32768) +-- hvl_mixchunk: integer mixing, s16 clipping, / 32768 function Player.mix(st, out, at, n) local nch = st.channels local voices = st.voices @@ -32645,16 +32273,13 @@ end __FILES["codecs/audio/Hively/Tables"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --- codecs/audio/Hively/Tables: the AHX / HivelyTracker replayer's tables: the waveform block (triangle and sawtooth at --- six lengths, 32 square pulse widths, white noise, and the 31 low-pass and 31 high-pass filtered copies of all of --- them, generated as hvl_replay.c does), the sine panning tables, the vibrato sine and the Amiga period table. Ported --- from HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt) --- as hvl2wav builds on 64-bit Linux (`long` is 64-bit there: the noise generator's shifts do not wrap at 32 bits). +-- 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 --- the offsets inside `waves` (bytes) 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 @@ -32829,7 +32454,6 @@ end local cache= nil --- get() -> { waves (int8 buffer), panL, panR (0-based, 256 entries) }: built once, shared read only function Tables.get() if cache then return cache @@ -32869,28 +32493,14 @@ __FILES["codecs/audio/Mdct"] = function() local __compat = __compat local type = __compat.type --!strict --!native --!optimize 2 --- codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point --- complex FFT (codecs/audio/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the --- DCT-IV, a plain FFT and the sine / KBD / Vorbis windows. Shared by AAC, Vorbis and Opus (decoders and encoders). --- Written from the textbook definitions (MDCT = DCT-IV of the folded input; DCT-IV through a half-size complex FFT --- with pre / post twiddles); no third-party code. +-- 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 -- --- Both are unnormalised (times `scale`, default 1): windowed forward + inverse + overlap-add with a Princen-Bradley --- window gives the input times N / 4 (AAC: the spec IMDCT is inverse(..., 2 / N), its MDCT has a factor 2). Arrays --- are Luau arrays; `xi` / `yi` are the 1-based index of element 0, coefficient arrays may be strided (CELT --- interleaves its short blocks). --- --- local Mdct = require("rosetta.codecs.audio.Mdct") --- local plan = Mdct.new(2048) -- nil when N is not a multiple of 4 --- Mdct.forward(plan, x, 1, X, 1) -- 2048 samples -> 1024 coefficients --- Mdct.inverse(plan, X, 1, 1, y, 1, 2 / 2048) -- 1024 coefficients -> 2048 samples --- local w = Mdct.window("sine", 2048) -- or "kbd" (alpha), "vorbis": N values --- --- Never throws: bad sizes return nil from new(); the transforms trust the plan and the array ranges (the caller --- sizes them). +-- 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 @@ -32898,7 +32508,6 @@ local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt local Mdct = {} Mdct.Fft = Fft --- new(N) -> Plan | nil @@ -32937,7 +32546,6 @@ if type(n) ~= "number" or n < 4 or n % 4 ~= 0 or n > 2 ^ 24 then } end --- the DCT-IV of the M values u (already in plan.re / plan.im as the pre-twiddled pairs) into out[oi + k * os] local function dct4Post(plan, out, oi, os, scale) local q, m = math.floor(plan.n / 4), plan.m local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws @@ -32950,8 +32558,7 @@ local function dct4Post(plan, out, oi, os, scale) end end --- dct4(plan, u, ui, us, out, oi, os, scale?): C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)) for the --- plan's M = N / 2 (its own inverse up to 2 / M) +-- C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)), M = N / 2 (its own inverse up to 2 / M) function Mdct.dct4(plan, u, ui, us, out, oi, os, scale) local q, m = math.floor(plan.n / 4), plan.m local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws @@ -32964,10 +32571,9 @@ function Mdct.dct4(plan, u, ui, us, out, oi, os, scale) dct4Post(plan, out, oi, os, scale or 1) end --- forward(plan, x, xi, X, Xi, Xs?, scale?): N samples x[xi ..] -> N / 2 coefficients X[Xi + k * Xs] function Mdct.forward(plan, x, xi, out, oi, os, scale) local q, m = math.floor(plan.n / 4), plan.m - local h = math.floor(m / 2 -- N / 4 + local h = math.floor(m / 2 ) local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws -- fold: u[j] = -x[3M/2 - 1 - j] - x[3M/2 + j] (j < M/2), x[j - M/2] - x[3M/2 - 1 - j] (j >= M/2) local b3 = xi + 3 * h @@ -32993,7 +32599,6 @@ function Mdct.forward(plan, x, xi, out, oi, os, scale) dct4Post(plan, out, oi, os or 1, scale or 1) end --- inverse(plan, X, Xi, Xs?, y, yi, scale?): N / 2 coefficients X[Xi + k * Xs] -> N samples y[yi ..] (no window) function Mdct.inverse(plan, inp, ii, is, y, yi, scale) local m = plan.m local h = math.floor(m / 2 @@ -33008,7 +32613,6 @@ function Mdct.inverse(plan, inp, ii, is, y, yi, scale) end end --- ------------------------------------------------------------------------------------------------ windows local function besselI0(x) local sum, term = 1, 1 local k = 1 @@ -33024,8 +32628,8 @@ local sum, term = 1, 1 end Mdct.besselI0 = besselI0 --- window(kind, N, alpha?) -> N values: "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (alpha: AAC uses 4 --- for long, 6 for short windows); "vorbis" sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1. +-- "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (AAC: alpha 4 long, 6 short); "vorbis" +-- sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1. function Mdct.window(kind, n, alpha) if type(n) ~= "number" or n < 2 or n % 2 ~= 0 then return nil @@ -33063,7 +32667,6 @@ if type(n) ~= "number" or n < 2 or n % 2 ~= 0 then return w end --- fft(n) -> an Fft plan (Fft.forward(plan, re, im) transforms in place) function Mdct.fft(n) return Fft.new(n) end @@ -33074,10 +32677,8 @@ __FILES["codecs/audio/Mdct/Fft"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --!native --!optimize 2 --- codecs/audio/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for --- other primes), self-sorting Stockham passes ping-ponging between the data and a scratch array (the FFTPACK / --- pocketfft pass structure, written from the textbook decimation-in-frequency derivation; no third-party code). --- Data are separate real / imaginary arrays, 1-based. Never throws. +-- 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 = {} @@ -33095,7 +32696,6 @@ local Fft = {} local cos, sin, pi = math.cos, math.sin, math.pi --- new(n) -> Plan | nil (n < 1 or not an integer) function Fft.new(n) if type(n) ~= "number" or n < 1 or n % 1 ~= 0 or n > 2 ^ 24 then return nil @@ -33262,8 +32862,7 @@ local function pass(p, ido, l1, ar, ai, br, bi, tr, ti, cr, ci) end end --- forward(plan, re, im): in-place forward DFT X[k] = sum x[j] exp(-2 pi i j k / n) of re[1..n], im[1..n]. --- The inverse (without the 1 / n) is forward(plan, im, re). +-- X[k] = sum x[j] exp(-2 pi i j k / n), in place; the inverse (without 1 / n) is forward(plan, im, re) function Fft.forward(plan, re, im) local n = plan.n local ar, ai, br, bi = re, im, plan.sre, plan.sim @@ -33285,11 +32884,9 @@ return Fft end __FILES["codecs/audio/MidiRender"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/audio/MidiRender: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, --- and the audio Decoder that plays a Midi through codecs/audio/SoundFont's synth (a SoundFont bank, or the built-in --- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order). --- Format 2: each track is its own song with its own tempo map, played one after another. Shared by every format that --- decodes to a Types.Midi (music/midi, mus, xmi, hmp): attach() adds the meta summary and the render method. +-- 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") @@ -33309,7 +32906,6 @@ if ev.type == "meta" and ev.meta == 0x51 and type(ev.data) == "table" and #ev.da return nil end --- tempoMap(midi, track?) -> TempoMap: from every track (format 0 / 1) or from one track (format 2) function Render.tempoMap(midi, track) local changes= {} for ti, t in __iter(midi.tracks) do @@ -33348,7 +32944,6 @@ if a[1] ~= b[1] then return map end --- seconds(map, tick) -> seconds (PPQ through the tempo map; SMPTE divisions are fixed time) function Render.seconds(map, tick) local div = map.division if div < 0 then @@ -33360,7 +32955,6 @@ local div = map.division return tick / ((fps == 29 and 29.97 or fps) * tpf) end local ticks = map.ticks - -- binary search for the last change at or before tick local lo, hi = 1, #ticks while lo < hi do local mid = math.floor((lo + hi + 1) / 2 @@ -33373,7 +32967,6 @@ local div = map.division return map.secs[lo] + (tick - ticks[lo]) * map.us[lo] * 1e-6 / div end --- length(midi) -> seconds to the last event (format 2: the tracks one after another) function Render.length(midi) if #midi.tracks == 0 then return 0 @@ -33400,7 +32993,6 @@ if #midi.tracks == 0 then return Render.seconds(map, last) end --- timeline(midi) -> the channel messages in play order with their times in seconds function Render.timeline(midi) @@ -33447,7 +33039,6 @@ if a[1] ~= b[1] then return tl end --- decoder(midi, opts?) -> Types.Decoder | nil, Err @@ -33553,17 +33144,14 @@ return pos / rate return (dec ) , nil end --- tempoBytes(division, ticksPerSecond) -> the 3 data bytes of a tempo meta event making each tick last --- 1 / ticksPerSecond seconds at that division (for formats with a fixed tick rate: MUS, XMIDI, HMP / HMI) +-- tempo meta making each tick last 1 / ticksPerSecond s at that division (MUS, XMIDI, HMP / HMI) function Render.tempoBytes(division, ticksPerSecond) local us = math.clamp(math.floor(division * 1e6 / ticksPerSecond + 0.5), 1, 0xFFFFFF) return { math.floor(us / 65536), (math.floor(us / 256)) % 256, us % 256 } end --- ------------------------------------------------------------------------------------------------ durations --- merge(events, offs) -> one tick-ordered event list: for formats that store a duration with each note (XMIDI, HMI). --- events are in file order (ticks never decrease); offs are the generated note-offs. At equal ticks an off whose note --- started earlier goes before the file's events, an off of a zero-length note after them. +-- XMIDI / HMI note durations: at equal ticks an off whose note started earlier goes before the file's events, +-- an off of a zero-length note after them function Render.merge(events, offs) @@ -33591,11 +33179,9 @@ local k = 1 return out end --- ------------------------------------------------------------------------------------------------ attach local function render(self, opts) local dec, err = Render.decoder(self, opts) if not dec then - -- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err) local empty= { sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err, read = function(_self, _n, out) @@ -33611,7 +33197,6 @@ return 0 return dec end --- summarize(midi): meta.tempos / timeSignatures / keySignatures / length from the events function Render.summarize(midi) local tempos, sigs, keys = {}, {}, {} local map = Render.tempoMap(midi) @@ -33635,7 +33220,6 @@ if ev.meta == 0x51 and #d >= 3 then midi.meta.length = Render.length(midi) end --- attach(midi, source): what every MIDI-like decoder does last: the meta summary, meta.source and the render method function Render.attach(midi, source) Render.summarize(midi) midi.meta.source = source @@ -33646,10 +33230,9 @@ return Render end __FILES["codecs/audio/Mpa"] = function() --!strict --- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it: --- frame headers (Header), the decoder core (Core: a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt, --- absorbed from mp3-luau c755bbf) with its tables, and the layer III / layer II encoders (Encode3, Encode2: shine-style --- CBR, new) with their analysis tables. ID3 tags, Xing / LAME gapless info, the frame index and seeking are audio/mp3. +-- 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"), @@ -33663,13 +33246,8 @@ __FILES["codecs/audio/Mpa/Analysis"] = function() --!strict --!native --!optimize 2 --- codecs/audio/Mpa/Analysis: the MPEG audio polyphase analysis filterbank (ISO/IEC 11172-3 section C.1.3, figure C.4): 32 --- input samples -> one sample in each of the 32 subbands, with the standard's 512-tap window C = D / 32 (D from --- codecs/audio/Mpa/EncTables) and the matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). Shared by the layer II and layer III --- encoders. New code from the standard's flow chart. Never throws. --- --- local st = Analysis.new() --- Analysis.run(st, samples, start, out, outStart) -- samples[start .. start + 31] -> out[outStart .. outStart + 31] +-- 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 = {} @@ -33678,7 +33256,7 @@ 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) -- M[k * 64 + i + 1] +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) @@ -33691,7 +33269,6 @@ function Analysis.new() return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) } end --- run(st, s, si, out, oi): s[si .. si + 31] (oldest first) -> out[oi .. oi + 31] (subbands 0 .. 31) function Analysis.run(st, s, si, out, oi) -- the window X is kept twice (x[p] and x[p + 512]) so X[i] = x[off + i + 1] without a modulo local x = st.x @@ -33728,11 +33305,8 @@ __FILES["codecs/audio/Mpa/Core"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/audio/Mpa/Core: a line-by-line port of minimp3's mp3dec_decode_frame (https://github.com/lieff/minimp3, --- CC0) for layers I, II and III, using its scalar (non-SIMD) code paths and float output. --- State that must survive between frames (MDCT overlap, polyphase history, bit reservoir) lives in a per-stream --- state from Core.newState(); everything else is module scratch, so decoding is synchronous and allocation free. --- All buffer accesses stay in bounds by construction (padded scratch, bounded loops): native code must not throw. +-- 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 @@ -33745,7 +33319,6 @@ 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) @@ -33838,19 +33411,16 @@ for i = 0, 239 do WINT[i + 1] = f32(T.g_win[i]) end ----------------------------------------------------------------------------------------------------------------- --- scratch - 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) -- layer III main data (reservoir + frame) +local MAIN = bcreate(MAX_BITRESERVOIR_BYTES + MAX_FRAME + 4096) local GRBUF = bcreate(576 * 2 * 4) -- [ch][576] f32 -local SCF = bcreate(40 * 4) -- layer III scalefactor gains, f32 -local SYN = bcreate((18 + 15) * 64 * 4) -- synthesis lines / reorder scratch, 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) -- integer scalefactors, 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) -- L12 bit allocation +local BA = bcreate(64) local SCFCOD = bcreate(64) -- layer III side info, per granule x channel (0..3) @@ -33867,19 +33437,16 @@ end local MAXB = { [0] = -1, -1, -1 } local SCFSIZE = { [0] = 0, 0, 0, 0 } --- per-stream state of the frame being decoded (set by decodeFrame) local OVL= bcreate(4) -- mdct_overlap[2][9*32] local QMF= bcreate(4) -- qmf_state[15*2*32] local PCM= bcreate(4) ----------------------------------------------------------------------------------------------------------------- --- bit reader (bs_t): position and limit in bits +-- bit reader (bs_t) local bsBuf= FRAME local bsPos = 0 local bsLimit = 0 --- n <= 25 local function getBits(n) local pos = bsPos bsPos = pos + n @@ -33890,7 +33457,6 @@ local pos = bsPos return rshift(w, 32 - n) end ----------------------------------------------------------------------------------------------------------------- -- layer III side info (L3_read_side_info): fills GR_*, returns main_data_begin or -1 local function readSideInfo(h1, h2, h3) @@ -33981,9 +33547,6 @@ local mono = band(h3, 0xC0) == 0xC0 return mdb end ----------------------------------------------------------------------------------------------------------------- --- layer III scalefactors - local function ldexpQ2(y, e) repeat local s = (e < 120 and{e }or{120 @@ -34073,7 +33636,6 @@ local function decodeScalefactors(h1, h3, istOff, gr, ch) end end ----------------------------------------------------------------------------------------------------------------- -- layer III Huffman decoding (L3_huffman) into GRBUF[dst ..], reads MAIN through a 32-bit cache local function huffman(dst, gr, limit) @@ -34222,9 +33784,6 @@ local function huffman(dst, gr, limit) bsPos = limit end ----------------------------------------------------------------------------------------------------------------- --- layer III stereo - -- L3_midside_stereo on GRBUF[left .. left + n) and its right channel at + 576 local function midside(left, n) for i = left * 4, (left + n - 1) * 4, 4 do @@ -34303,9 +33862,6 @@ local function intensityStereo(h1, h3, gr) end end ----------------------------------------------------------------------------------------------------------------- --- layer III reorder, antialias, IMDCT - local function reorder(g, sfb) local src, dst = g, 0 while true do @@ -34569,7 +34125,7 @@ local function dctII(g, n) t2_7 = d + c t3_7 = (d - c) * 5.10114861 end - do -- row 0 + do local x0, x1, x2, x3, x4, x5, x6, x7 = t0_0, t0_1, t0_2, t0_3, t0_4, t0_5, t0_6, t0_7 local xt = x0 - x7 x0 =x0+ x7 @@ -34601,7 +34157,7 @@ local function dctII(g, n) t0_6 = (x4 - x3) * 1.30656302 t0_7 = (xt - x7) * 2.56291556 end - do -- row 1 + do local x0, x1, x2, x3, x4, x5, x6, x7 = t1_0, t1_1, t1_2, t1_3, t1_4, t1_5, t1_6, t1_7 local xt = x0 - x7 x0 =x0+ x7 @@ -34633,7 +34189,7 @@ local function dctII(g, n) t1_6 = (x4 - x3) * 1.30656302 t1_7 = (xt - x7) * 2.56291556 end - do -- row 2 + do local x0, x1, x2, x3, x4, x5, x6, x7 = t2_0, t2_1, t2_2, t2_3, t2_4, t2_5, t2_6, t2_7 local xt = x0 - x7 x0 =x0+ x7 @@ -34665,7 +34221,7 @@ local function dctII(g, n) t2_6 = (x4 - x3) * 1.30656302 t2_7 = (xt - x7) * 2.56291556 end - do -- row 3 + do local x0, x1, x2, x3, x4, x5, x6, x7 = t3_0, t3_1, t3_2, t3_3, t3_4, t3_5, t3_6, t3_7 local xt = x0 - x7 x0 =x0+ x7 @@ -34828,7 +34384,6 @@ local function l3Decode(h1, h2, h3, grBase, nch) end end ----------------------------------------------------------------------------------------------------------------- -- polyphase synthesis (mp3d_DCT_II, mp3d_synth, mp3d_synth_granule) @@ -34856,8 +34411,7 @@ local function synthPair(dst, nch, z) wf(PCM, (dst + 16 * nch) * 4, a * SCALE) end --- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel. xl = GRBUF float index of the left --- channel's slot, dstl = PCM float index, lins = SYN float index +-- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel local function synth(xl, dstl, nch, lins) local xr = xl + 576 * (nch - 1) local dstr = dstl + (nch - 1) @@ -34983,9 +34537,6 @@ local function synthGranule(nbands, nch, pcm) end end ----------------------------------------------------------------------------------------------------------------- --- layers I and II - 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 } @@ -35098,9 +34649,6 @@ local function l12ApplyScf(scfOff) end end ----------------------------------------------------------------------------------------------------------------- --- API - local Core = {} Core.MAX_FRAME = MAX_FRAME @@ -35133,7 +34681,6 @@ end Core.lastChannels = 0 --- pcm holds n mono samples: spread them to n interleaved stereo pairs (in place) function Core.upmix(pcm, n) if buffer.len(pcm) < n * 8 then return @@ -35145,9 +34692,6 @@ function Core.upmix(pcm, n) end end --- Decodes the frame b[off, off + size) (a whole frame found by the index, header included) into pcm --- (interleaved f32, frame samples x channels) and returns the samples per channel (0 = no output: an --- unfilled bit reservoir, or corrupt data). Core.lastChannels = the frame's channel count. function Core.decodeFrame(st, b, off, size, pcm) if size < 4 or size > MAX_FRAME or off < 0 or off + size > buffer.len(b) then st.needReset = true @@ -35212,7 +34756,6 @@ if size < 4 or size > MAX_FRAME or off < 0 or off + size > buffer.len(b) then bsBuf = FRAME return (success and{spf }or{0 })[1] end - -- layers I / II local kbps = 2 * HALFRATE[(band(h1, 8) ~= 0 and 45 or 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)] l12ReadScaleInfo(h1, h2, h3, kbps) bfill(GRBUF, 0, 0) @@ -35236,8 +34779,6 @@ if size < 4 or size > MAX_FRAME or off < 0 or off + size > buffer.len(b) then return spf end --- Layer III side info of the frame b[off, off + size): main_data_begin (-1 = corrupt), the sum of its --- part2_3 lengths in bits, and the main data bytes in the frame. Used by the stream index. function Core.probeL3(b, off, size) local n = min(size, 64) if size < 4 or off + n > buffer.len(b) then @@ -35261,7 +34802,7 @@ local n = min(size, 64) return mdb, sum, math.floor((bsLimit - bsPos) / 8 )end --- Layer I / II: false when the frame b[off, off + size) needs more bits than it has (minimp3 then drops it). +-- Layer I / II: minimp3 drops a frame that needs more bits than it has function Core.probeL12(b, off, size) if size < 4 or size > MAX_FRAME or off + size > buffer.len(b) then return false @@ -35365,11 +34906,9 @@ return Core end __FILES["codecs/audio/Mpa/EncTables"] = function() --!strict --- codecs/audio/Mpa/EncTables: tables for the MPEG audio encoders, from PDMP3 (public domain / unlicense, by Krister --- Lagerstrom and contributors: licenses/PDMP3-UNLICENSE.txt), which transcribes ISO/IEC 11172-3: the synthesis window D --- (the analysis window is C = D / 32) and the layer III Huffman code trees (the encoders derive codeword tables from --- them). Trees use the standard's decoder layout: an entry with a high byte is a node (high byte: left offset, low --- byte: right offset), otherwise a leaf (x << 4 | y; count1 tables: v w x y bits). +-- 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, @@ -35661,13 +35200,9 @@ __FILES["codecs/audio/Mpa/Encode2"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- codecs/audio/Mpa/Encode2: an MPEG audio layer II (MP2) encoder: constant bit rate, MPEG-1 (32 / 44.1 / 48 kHz) and MPEG-2 --- low sampling frequencies (16 / 22.05 / 24 kHz), mono or stereo. New code written from ISO/IEC 11172-3 (2.4.2.3, --- C.1.5.2): the polyphase analysis (codecs/audio/Mpa/Analysis), one scalefactor per 12-sample part (scfsi 0: all three are --- sent), the standard bit allocation tables (in minimp3's compact form, CC0: licenses/minimp3-CC0.txt, as the decoder --- in this folder reads them), a greedy allocation that always gives the next step to the band with the most noise --- (signal level minus the quantizer's SNR; no psychoacoustic model), uniform midtread quantization and grouping of --- 3 / 5 / 9-level samples. Never throws. +-- 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") @@ -35695,7 +35230,6 @@ if ba >= 17 then ) end return POW[ba + 1] - 1 end --- bits for the 3 samples of one granule local function tripleBits(ba) if ba >= 17 then return ba == 17 and 5 or(ba == 18 and 7 or 10 @@ -35751,7 +35285,6 @@ Encode2.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } local put = Bits.msbPut --- encode(src, opts) -> buffer | nil, message @@ -35777,7 +35310,6 @@ local rate = src.sampleRate if not brIndex then return nil, "unsupported bit rate" end - -- the allocation table (the decoder's choice from the header) local alloc, nbands if not mpeg1 then alloc, nbands = ALLOC_L2M2, 30 @@ -35828,8 +35360,8 @@ if buffer.len(pf) > buffer.len(w.buf) - 16 then -- 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) } -- scalefactor index per band and part - local bal = { table.create(32, 0), table.create(32, 0) } -- allocation step (0 = none) per band + local scf = { table.create(32 * 3, 0), table.create(32 * 3, 0) } + local bal = { table.create(32, 0), table.create(32, 0) } local slot = 144000 * kbps local rest = 0 local tmp= nil @@ -35909,7 +35441,6 @@ for i = 0, take - 1 do end end end - -- the frame size and the bits left for scalefactors and samples local frameBytes = math.floor(slot / rate ) rest =rest+ slot % rate local padding = 0 @@ -35922,8 +35453,7 @@ for i = 0, take - 1 do for b = 1, nbands do avail =avail- bandBits[b] * nch end - -- greedy allocation: the band with the most noise gets its next step while it fits - local level = { table.create(nbands, 0), table.create(nbands, 0) } -- signal level (dB) per band + local level = { table.create(nbands, 0), table.create(nbands, 0) } for c = 1, nch do local sc = scf[c] for b = 1, nbands do @@ -35958,7 +35488,6 @@ for i = 0, take - 1 do do local __DARKLUA_VAR= bal[bestC]__DARKLUA_VAR[bestB]=__DARKLUA_VAR[bestB]+ 1 end avail =avail- bestCost end - -- write the frame 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) @@ -35978,7 +35507,6 @@ end avail =avail- bestCost put(w, 0, 1) put(w, 1, 1) put(w, 0, 2) - -- bit allocation for b = 1, nbands do for c = 1, nch do local st = bal[c][b] @@ -36057,13 +35585,9 @@ __FILES["codecs/audio/Mpa/Encode3"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/audio/Mpa/Encode3: an MPEG audio layer III encoder in the spirit of shine: constant bit rate, long blocks only, --- global-gain rate control (no psychoacoustic model, scalefactors all zero), no bit reservoir (main_data_begin = 0), --- MPEG-1 (32 / 44.1 / 48 kHz, two granules), MPEG-2 (16 / 22.05 / 24 kHz) and MPEG-2.5 (8 / 11.025 / 12 kHz), mono, --- stereo or joint (mid / side) stereo. New code written from ISO/IEC 11172-3 / 13818-3 (no shine / LAME code): the --- analysis filterbank (codecs/audio/Mpa/Analysis), the 36-point MDCT with the sine window, the alias-reduction butterflies, --- the x^(3/4) quantizer, big_values / count1 partitioning with per-region Huffman table choice; the Huffman codes are --- derived from the standard's decoder trees (codecs/audio/Mpa/EncTables, from PDMP3, public domain). Never throws. +-- 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") @@ -36079,7 +35603,6 @@ for i = 0, 39 do POW[i + 1] = 2 ^ i end --- ------------------------------------------------------------------------------------------------ Huffman codes -- 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= {} @@ -36131,7 +35654,6 @@ for t = 1, 33 do end end local LINBITS = E.LINBITS --- the tables that hold values up to m (m <= 15), smallest first local SMALL= {} for m = 0, 15 do local list = {} @@ -36142,14 +35664,12 @@ for m = 0, 15 do end SMALL[m] = list end --- ------------------------------------------------------------------------------------------------ bit writer local put = Bits.msbPut Encode3.put = put --- ------------------------------------------------------------------------------------------------ constants 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 }, @@ -36174,14 +35694,12 @@ for k = 0, 17 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 --- alias reduction coefficients 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 --- ------------------------------------------------------------------------------------------------ Huffman planning @@ -36199,7 +35717,6 @@ local function newPlan() return { bits = 0, bigValues = 0, count1 = 0, tables = { 0, 0, 0 }, region0 = 0, region1 = 0, c1table = 0, addr1 = 0, addr2 = 0 } end --- bits of the pairs ix[a .. b) with table t (ix 1-based: ix[i + 1] is coefficient i) local function pairBits(ix, a, b, t) if t == 0 then return 0 @@ -36229,7 +35746,6 @@ if t == 0 then return bits end --- the best table for the pairs ix[a .. b): table, bits local function chooseTable(ix, a, b) if b <= a then return 0, 0 @@ -36270,7 +35786,6 @@ if b <= a then return best, bestBits end --- plan the Huffman coding of ix (576 values, max <= 8206) into p; bounds = scalefactor band starts (1-based list) local function plan(ix, bounds, p) local i = 576 while i > 1 and ix[i] == 0 and ix[i - 1] == 0 do @@ -36284,7 +35799,6 @@ local function plan(ix, bounds, p) end local bv = i -- big_values * 2 coefficients p.bigValues, p.count1 = math.floor(bv / 2), c1 - -- count1 bits, table A vs B local ba, bb = 0, 0 local lensA = LEN[32] for q = 0, c1 - 1 do @@ -36364,7 +35878,6 @@ local function writeHuffman(w, ix, sign, p) end end end --- ------------------------------------------------------------------------------------------------ quantization @@ -36400,7 +35913,6 @@ local step = 2 ^ (-(g - 210) * 3 / 16) return true end --- the finest global gain whose Huffman size fits budget bits local function rateLoop(u, budget, bounds) local xr, xa, sign = u.xr, u.xa, u.sign local maxa = 0 @@ -36422,7 +35934,6 @@ local function rateLoop(u, budget, bounds) u.gain = 0 return end - -- the gain where the largest value quantizes to 0: an upper bound local lo, hi = 0, 255 local best = -1 while lo <= hi do @@ -36452,8 +35963,6 @@ local function rateLoop(u, budget, bounds) end u.gain = best end --- ------------------------------------------------------------------------------------------------ encoder --- encode(src, opts) -> buffer | nil, message @@ -36489,7 +35998,6 @@ local rate = src.sampleRate end local sideBytes = (mpeg1 and{(nch == 1 and 17 or 32) }or{(nch == 1 and 9 or 17) })[1] local slotNum = (mpeg1 and 144000 or 72000) * kbps -- frame bytes * rate - -- scalefactor band starts (long blocks) local bounds = { 0 } do local acc = 0 @@ -36509,7 +36017,7 @@ local need = buffer.len(pf) w.pos = need end local ana = { Analysis.new(), Analysis.new() } - local prev = { table.create(576, 0), table.create(576, 0) } -- previous granule's subband samples [sb * 18 + k + 1] + 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 @@ -36525,7 +36033,6 @@ local need = buffer.len(pf) local srcDone = false local flushed = false while true do - -- one frame of input (zero padded at the end; one more silent frame flushes the filterbank delay) local got = 0 while got < spf and not srcDone do if pendN == 0 then @@ -36569,7 +36076,6 @@ for i = 0, take - 1 do s[i] = 0 end end - -- analysis + MDCT per granule and channel for g = 1, granules do for c = 1, nch do local cu, pv = cur[c], prev[c] @@ -36620,7 +36126,6 @@ for i = 0, take - 1 do end end end - -- the frame size local frameBytes = math.floor(slotNum / rate ) rest =rest+ slotNum % rate local padding = 0 @@ -36642,7 +36147,6 @@ for i = 0, take - 1 do done =done+ 1 end end - -- header 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) @@ -36662,7 +36166,6 @@ for i = 0, take - 1 do put(w, 0, 1) put(w, 1, 1) -- original put(w, 0, 2) - -- side info if mpeg1 then put(w, 0, 9) -- main_data_begin put(w, 0, nch == 1 and 5 or 3) @@ -36694,7 +36197,6 @@ for i = 0, take - 1 do put(w, p.c1table, 1) end end - -- main data for g = 1, granules do for c = 1, nch do local u = units[g][c] @@ -36724,9 +36226,8 @@ __FILES["codecs/audio/Mpa/Header"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/audio/Mpa/Header: MPEG audio frame headers (minimp3's hdr_* macros and functions), frame sync (mp3d_find_frame / --- mp3d_match_frame). Every function reads 4 header bytes at a byte offset of a buffer; callers keep offset + 4 --- inside the buffer. Never throws. +-- 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 @@ -36753,7 +36254,7 @@ if ru8(b, o) ~= 0xFF then end local valid = H.valid --- hdr_compare: h2 is a valid header of the same version / layer / sample rate / free-format-ness as h1 +-- hdr_compare function H.compare(b, o1, o2) if not valid(b, o2) then return false @@ -36796,7 +36297,7 @@ if band(h1, 6) == 6 then end local frameSamples = H.frameSamples --- hdr_frame_bytes (without padding); free format = 0 -> freeSize +-- hdr_frame_bytes (without padding) function H.frameBytes(b, o, freeSize) local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) local hz = sampleRate(h1, h2) @@ -36831,7 +36332,7 @@ local i = 0 return true end --- mp3d_find_frame over b[base, base + n): returns (skip, frame bytes incl. padding or 0, free format size) +-- mp3d_find_frame function H.findFrame(b, base, n, ffb) for i = 0, n - 5 do local o = base + i @@ -37090,19 +36591,9 @@ return T end __FILES["codecs/audio/Musepack"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8: the stream headers (SV7's 32-bit word-swapped --- header, SV8's key / size packets: SH with its CRC, RG, EI, AP, SE), the frame / audio packet index, and the --- decoder (codecs/audio/Musepack/Decode: subband bitstream, requantisation, polyphase synthesis). 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 (the 481-sample synthesis delay and SV8's leading silence are --- dropped, the length is exact). Not supported: SV4 - SV6 (UNSUPPORTED), the SV8 seek table (the packets are indexed --- instead), chapters. --- --- local s, err = Musepack.open(buf, start, limit) -- start: the "MP+" / "MPCK" magic (after an ID3v2 tag) --- -- s: { version, sampleRate, channels, frames, maxBand, ms, profile, encoder, gapless, gain, ... } plus the --- -- codecs/audio/Stream spec: count, start(i), decode(i), pcm(), reset(), skip, stop, preroll --- --- Never throws: bad data returns nil, Err. +-- 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") @@ -37113,7 +36604,6 @@ local RATES = { 44100, 48000, 37800, 32000 } local FRAME, DELAY, PAD = Decode.FRAME, Decode.DELAY, Decode.PAD local readu8 = buffer.readu8 --- ------------------------------------------------------------------------------------------------ SV7 -- SV7 reads the stream as little-endian 32-bit words, most significant bit first: swap them into a padded copy @@ -37137,7 +36627,6 @@ local readu8 = buffer.readu8 - local function swapped(buf, p, limit) @@ -37197,7 +36686,7 @@ if limit - start < 32 then local size = at(s, pos, 20) local stop = pos + 20 + size + (i == frames and 11 or 0) if stop > totalBits then - break -- a truncated last frame + break end offs[i], sizes[i] = pos + 20, size pos = stop @@ -37261,7 +36750,6 @@ return pcm return out, nil end --- ------------------------------------------------------------------------------------------------ SV8 -- a packet size: 7 bits per byte, most significant first, bit 7 = more local function varint(buf, p, limit) local v = 0 @@ -37296,7 +36784,7 @@ local p = start + 4 local stop = p + size if stop > limit then if key == "AP" then - break -- a truncated last packet + break end return nil, Err.new(Err.TRUNCATED, key .. " packet", p) end @@ -37420,8 +36908,6 @@ return pcm return out, nil end --- ------------------------------------------------------------------------------------------------ open --- magic(buf, p, limit) -> 7 | 8 | 0 (other: "MP+" with another version is 7's family, reported by open) function Musepack.magic(buf, p, limit) if p + 4 > limit then return 0 @@ -37436,7 +36922,6 @@ if p + 4 > limit then return 0 end --- open(buf, start, limit) -> Stream | nil, Err function Musepack.open(buf, start, limit) local v = Musepack.magic(buf, start, limit) if v == 8 then @@ -37453,13 +36938,9 @@ __FILES["codecs/audio/Musepack/Decode"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/audio/Musepack/Decode: one Musepack SV7 / SV8 frame (1152 samples per channel): the bitstream (band --- resolutions, scalefactor indices, quantised subband samples, with SV8's canonical Huffman / enumerative codes), --- requantisation (M/S or L/R) and the 32-band polyphase synthesis. 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) in double precision float. The bit reader is module state (decoding is synchronous) over --- a buffer the caller pads by at least PAD bytes past `limit`: the band loops stop as soon as the position passes the --- limit, so every read stays inside the buffer. No error / assert: failures return nil, "message". +-- 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 = @@ -37471,7 +36952,6 @@ Decode.PAD = 8192 Decode.DELAY = 481 -- MPC_DECODER_SYNTH_DELAY Decode.FRAME = 1152 --- ------------------------------------------------------------------------------------------------ tables local L = T.lut local HDR, SCFI7, DSCF7 = L(T.HuffHdr), L(T.HuffSCFI), L(T.HuffDSCF) local Q7= { @@ -37535,9 +37015,8 @@ for i, v in __iter(T.DI) do DW[i] = f32(v / 65536) end --- ------------------------------------------------------------------------------------------------ bit reader local B= buffer.create(0) -local P = 0 -- bit position +local P = 0 local function bits(n) if n <= 0 then @@ -37558,7 +37037,6 @@ local w = bswap(readu32(B, rshift(P, 3))) return extract(w, 16 - band(P, 7), 16) end --- a table-driven Huffman symbol (plain or canonical) local function huff(t) local code = peek16() local k = rshift(code, 8) + 1 @@ -37628,7 +37106,6 @@ for i = 0, 255 do PARITY[i + 1] = p end --- ------------------------------------------------------------------------------------------------ synthesis -- mpc_compute_new_V: 32 subband samples Y[y .. y + 31] -> 64 V values at V[o .. o + 63] (the ISO 11172-3 matrixing -- through Byeong Gi Lee's fast DCT) local function newV(Y, y, V, o) @@ -37844,7 +37321,6 @@ local function newV(Y, y, V, o) V[o + 96 - i] = V[o + i] end end --- ------------------------------------------------------------------------------------------------ state @@ -37898,9 +37374,7 @@ local st= { return st end --- reset(st, scf): forget the history (before a seek); scf = the scalefactor indices to assume (libmpcdec: 0 at the --- start of the stream, 0x01010101 in the middle of an SV7 stream). The noise generator restarts too, so a seek --- decodes like libmpcdec seeking in a freshly opened stream. +-- libmpcdec assumes scf 0 at the stream start, 0x01010101 mid-SV7; the noise generator restarts, as in a fresh stream function Decode.reset(st, scf) for i = 1, 99 do st.scfL[i] = scf @@ -37931,8 +37405,7 @@ local function noise(st, q, o) st.r1, st.r2 = r1, r2 end --- ------------------------------------------------------------------------------------------------ SV7 --- mpc_decoder_read_bitstream_sv7 -> true | nil, message +-- mpc_decoder_read_bitstream_sv7 local function readSv7(st, limit) local resL, resR, msf = st.resL, st.resR, st.msf local maxUsed = 0 @@ -38059,7 +37532,6 @@ local resL, resR, msf = st.resL, st.resR, st.msf return true, nil end --- ------------------------------------------------------------------------------------------------ SV8 local function readSv8(st, key, limit) local resL, resR, msf = st.resL, st.resR, st.msf local maxBand = st.maxBand @@ -38254,7 +37726,6 @@ local resL, resR, msf = st.resL, st.resR, st.msf return true, nil end --- ------------------------------------------------------------------------------------------------ requantisation local function requant(st) local resL, resR, msf = st.resL, st.resR, st.msf local scfL, scfR, qL, qR, yL, yR = st.scfL, st.scfR, st.qL, st.qR, st.yL, st.yR @@ -38285,7 +37756,7 @@ local function requant(st) end --- mpc_synthese_filter_float for one channel: 36 x 32 subband samples -> 1152 samples at out[base + i * step] +-- mpc_synthese_filter_float local function synth(V, Y, out, base, step) table.move(V, 1, 960, 2305) local o = 2304 + 1 @@ -38306,10 +37777,6 @@ local function synth(V, Y, out, base, step) end end --- ------------------------------------------------------------------------------------------------ frames --- frame(st, buf, bitPos, limitBits, key, out, base) -> the bit position after the frame | nil, message: decodes one --- frame from buf (padded by PAD bytes past limitBits / 8) into out[base ..] (1152 * channels interleaved floats). --- key: an SV8 key frame (the first of a block). bitPos < 0 decodes a silent frame (the synthesis tail). function Decode.frame(st, buf, bitPos, limitBits, key, out, base) if bitPos >= 0 then if rshift(limitBits, 3) + Decode.PAD > buffer.len(buf) or bitPos > limitBits then @@ -38341,8 +37808,6 @@ if bitPos >= 0 then return (bitPos >= 0 and{pos }or{bitPos})[1], nil end --- bitsAt(buf, bitPos, n) -> n (1 .. 24) bits at bitPos (frame headers: the SV7 frame size); the caller keeps --- bitPos / 8 + 4 inside buf function Decode.bitsAt(buf, bitPos, n) local w = bswap(readu32(buf, rshift(bitPos, 3))) return extract(w, 32 - band(bitPos, 7) - n, n) @@ -38352,12 +37817,10 @@ return Decode end __FILES["codecs/audio/Musepack/Tables"] = function() local __compat = __compat local bit32 = __compat.bit32 --!strict --- codecs/audio/Musepack/Tables: the Musepack SV7 / SV8 Huffman tables, the synthesis window and the 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); the tables are transcribed by script. --- Each Huffman table is a flat { code, length, value, ... } list sorted by descending left-aligned 16-bit code; --- canonical (SV8) tables map value - (code >> (16 - length)) through their symbol list. lut(table, sym?) builds the --- 8-bit first-level lookup the decoder uses. +-- 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 = { @@ -38684,7 +38147,6 @@ do T.CNK_LOST[16][32] = 0 end --- lut(table, sym?) -> Lut @@ -38733,11 +38195,8 @@ return T end __FILES["codecs/audio/Opus"] = function() --!strict --- codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT --- decoders and the multistream / hybrid decoder that drives them (Decoder), the CELT encoder (CeltEncoder) and the --- CELT inverse MDCT (Mdct, a fused libopus port: see its header for why it is not codecs/audio/Mdct). A port of the --- libopus 1.6 decoder (BSD: licenses/libopus-BSD.txt), absorbed from opus-luau dd2b4e5; the encoder is new. Ogg Opus --- (OpusHead, OpusTags, granules, seeking) is audio/opus. +-- 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"), @@ -38752,12 +38211,9 @@ __FILES["codecs/audio/Opus/Celt"] = function() local __compat = __compat local bit32 = __compat.bit32 --!strict --!native --!optimize 2 --- codecs/audio/Opus/Celt: CELT decoder (RFC 6716 section 4.3), a port of the libopus float decoder: celt/celt_decoder.c, bands.c, vq.c, --- cwrs.c, rate.c, quant_bands.c, laplace.c, celt.c (comb filter). Only the standard 48 kHz / 960-sample mode is --- needed by Opus. Packet loss concealment is the noise-based variant only (no pitch PLC). --- --- Arrays are Luau tables of numbers. All normalised-band data (X, Y, the folding memory `norm` and the scratch --- copies) lives in one table W, and the "pointers" of the C code are 0-based offsets into it. +-- 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") @@ -38853,7 +38309,6 @@ for n = 1, UK - 1 do end end --- shared workspace (decoding is not re-entrant) local NORM_BASE = 1920 local W = table.create(4096, 0) local TMP = table.create(256, 0) @@ -38915,7 +38370,6 @@ local lc = RD.ilog(icos) return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) end --- --------------------------------------------------------------------------------------------------------------- -- energy (quant_bands.c, laplace.c) local function laplaceDecode(dec, fs, decay) @@ -39029,7 +38483,6 @@ __DARKLUA_CONTINUE_10=true until true if not __DARKLUA_CONTINUE_10 then break en end end --- --------------------------------------------------------------------------------------------------------------- -- bit allocation (rate.c) local function bits2pulses(bandI, LM, bits) @@ -39066,7 +38519,7 @@ if i < 8 then return lshift(8 + band(i, 7), rshift(i, 3) - 1) end --- clt_compute_allocation + interp_bits2pulses (decoder side). Returns codedBands, balance, intensity, dualStereo. +-- clt_compute_allocation + interp_bits2pulses (decoder side) local function computeAllocation(start, endb, offsets, cap, allocTrim, total, pulses, ebits, finePriority, C, LM, ec) total = imax(total, 0) @@ -39295,7 +38748,6 @@ end local extraBits = extraFine * C * 8 return codedBands, balance, intensity, dualStereo end --- --------------------------------------------------------------------------------------------------------------- -- PVQ (cwrs.c, vq.c) local function cwrsi(n, k, i, iy) @@ -39356,7 +38808,6 @@ local yy = 0 end n =n- 1 end - -- n == 2 p = 2 * k + 1 local neg = i >= p if neg then @@ -39370,7 +38821,6 @@ local yy = 0 val = (neg and((k - k0 ))or((k0 - k ))) iy[idx] = val yy =yy+ val * val - -- n == 1 val = (i ~= 0 and{(-k )}or{k })[1] iy[idx + 1] = val yy =yy+ val * val @@ -39467,7 +38917,6 @@ local iy = IY end return mask end --- --------------------------------------------------------------------------------------------------------------- -- bands (bands.c) @@ -39570,7 +39019,6 @@ local N2 = 2 * N - 1 return lshift(rshift(qn + 1, 1), 1) end --- returns b, fill, inv, imid, iside, delta, itheta, qalloc local function computeTheta(N, b, B, B0, LM, stereo, fill) local i = ctx.i local ec = ctx.ec @@ -40079,9 +39527,6 @@ local function antiCollapse(st, C, size, LM, start, endb, end end --- --------------------------------------------------------------------------------------------------------------- --- synthesis - local function denormaliseBands(X, freq, logE, eoff, start, endb, M, silence) local N = M * SHORT_MDCT local bound = M * EB[endb + 1] @@ -40237,9 +39682,6 @@ local function deemphasis(st, CC, N, pcm, pbase, accum) end end --- --------------------------------------------------------------------------------------------------------------- --- decoder state - local function resetState(st) st.rng = 0 st.error = 0 @@ -40347,8 +39789,7 @@ local function decodeLost(st, N, LM) st.last_frame_type = FRAME_PLC_NOISE end --- celt_decode_with_ec. pcm[pbase + j * channels + c]; frameSize at 48 kHz. dec may be nil (a new range decoder over --- buf[off, off + len)). buf == nil or len <= 1 conceals. Returns the samples per channel, or < 0 on error. +-- celt_decode_with_ec (buf nil or len <= 1 conceals) function Celt.decode(st, buf, off, len, pcm, pbase, frameSize, dec, accum) local CC = st.channels @@ -40517,7 +39958,6 @@ local oldBandE, oldLogE, oldLogE2, bgLogE = st.oldBandE, st.oldLogE, st.oldLogE2 pulses, fineQuant, finePriority, C, LM, ec) unquantFineEnergy(st, start, endb, fineQuant, ec, C) - -- shift the decoder memory by one frame for c = 1, CC do table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) end @@ -40618,12 +40058,9 @@ __FILES["codecs/audio/Opus/CeltEncoder"] = function() local __compat = __compat local bit32 = __compat.bit32 --!strict --!native --!optimize 2 --- codecs/audio/Opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms frames (LM 3), full band, constant --- bit rate, long MDCTs only (no transient detection), no pitch pre-filter, normal spreading, default allocation trim, --- mono, or stereo as mid / side per band (the angle, intensity when it has no bits; dual L / R stereo on request). The bitstream side is a port of the libopus 1.6 encoder paths --- (celt_encoder.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c; BSD: licenses/libopus-BSD.txt) that --- mirror codecs/audio/Opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/audio/Mdct. --- Never throws. +-- 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") @@ -40684,7 +40121,6 @@ local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } local SPREAD_NORMAL = 2 local SPREAD_FACTOR = { 15, 10, 5 } --- the MDCT window (the decoder's) and plan local WINDOW = table.create(OVERLAP, 0) for i = 0, OVERLAP - 1 do local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) @@ -40733,7 +40169,6 @@ local lc = RE.ilog(icos) return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) end --- ------------------------------------------------------------------------------------------------ energy -- ec_laplace_encode: returns the value actually coded (clamped in the flat tail) local function laplaceEncode(enc, value, fs, decay) local fl = 0 @@ -40768,7 +40203,6 @@ local fl = 0 return value end --- new(channels) -> State @@ -40919,7 +40353,6 @@ __DARKLUA_CONTINUE_11=true until true if not __DARKLUA_CONTINUE_11 then break en end end --- ------------------------------------------------------------------------------------------------ allocation local function bits2pulses(bandI, lm, bits) local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] local lo, hi = 0, CACHE_BITS[base + 1] @@ -41183,7 +40616,6 @@ end local extraBits = extraFine * C * 8 return codedBands, balance, intensity, dualStereo end --- ------------------------------------------------------------------------------------------------ PVQ -- icwrs: the index of the pulse vector iy[1..n] local function icwrs(n, iy) local j = n -- 1-based position of _y[n - 1] @@ -41317,7 +40749,6 @@ local SCRATCH_A = table.create(256, 0) local ROT = table.create(256, 0) local function algQuant(st, X, xo, n, K, enc) - -- rotate a copy (the original band stays for nothing else, but keep it intact) for j = 1, n do ROT[j] = X[xo + j] end @@ -41327,7 +40758,6 @@ local function algQuant(st, X, xo, n, K, enc) encUint(enc, icwrs(n, iy), pvqU(n, K) + pvqU(n, K + 1)) end --- ------------------------------------------------------------------------------------------------ bands local function computeQn(n, b, offset, pulseCap) local N2 = 2 * n - 1 local qb = tdiv(b + N2 * offset, N2) @@ -41546,14 +40976,10 @@ local function quantAllBands(st, C, pulses, dualStereo, totalBits, ) end end --- ------------------------------------------------------------------------------------------------ frame --- encodeFrame(st, pcm, base, stride, nbBytes) -> buffer: one CELT frame of nbBytes from 960 samples per channel --- (pcm[base + k * stride + c], floats -1 .. 1, interleaved) function CeltEncoder.encodeFrame(st, pcm, base, stride, nbBytes) local C = st.channels local work, tmp = st.work, st.tmp local silent = true - -- pre-emphasis, the windowed 1920-sample MDCT input, band energies, normalisation for c = 1, C do local inMem = st.inMem[c] local m = st.preMem[c] @@ -41605,7 +41031,6 @@ local C = st.channels local enc = RE.new(nbBytes) local totalBits = nbBytes * 8 local oldE = st.oldBandE - -- silence if silent then encBitLogp(enc, true, 15) enc.nbits_total =enc.nbits_total+ (totalBits - tell(enc) @@ -41696,7 +41121,7 @@ return CeltEncoder end __FILES["codecs/audio/Opus/CeltTables"] = function() --!strict --- codecs/audio/Opus/CeltTables: Generated from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, see licenses/). 1-based arrays. +-- codecs/audio/Opus/CeltTables: 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, @@ -41758,9 +41183,8 @@ __FILES["codecs/audio/Opus/Decoder"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/audio/Opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching --- between SILK, hybrid and CELT, the redundant CELT frames of mode transitions, cross-fades, PLC fallbacks, the --- multi-frame packet loop and multistream (channel mapping) decoding. Output is 48 kHz float in Luau arrays. +-- 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") @@ -41910,7 +41334,6 @@ local ch = st.channels end frameSize = audiosize - -- SILK if mode ~= MODE_CELT then local tooSmall = frameSize < F10 local sarr, sbase = pcm, pbase @@ -42046,8 +41469,7 @@ local ch = st.channels return audiosize end --- opus_decode_native: decodes one packet (buf == nil or len == 0: conceal frameSize samples). pcm[pbase + i * ch + c]. --- Returns the samples per channel (or < 0 on error) and the packet's size (self-delimited packets). +-- opus_decode_native (buf nil or len 0: conceal frameSize samples) function Decoder.decode(st, buf, off, len, pcm, pbase, frameSize, selfDelimited) local ch = st.channels if buf == nil or len == 0 then @@ -42093,7 +41515,6 @@ local toc = readu8(b, off) st.last_packet_duration = nb return nb, packetOffset end --- --------------------------------------------------------------------------------------------------------------- -- multistream (channel mapping families 0 / 1 / 255) @@ -42127,7 +41548,6 @@ function Decoder.resetMultistream(ms) end end --- copies channel `sc` of src (stride sstride) into every output channel mapped to stream channel index `id` local function copyOut(ms, id, src, sc, sstride, pcm, pbase, n) local nch = ms.channels for c = 0, nch - 1 do @@ -42143,7 +41563,7 @@ local function copyOut(ms, id, src, sc, sstride, pcm, pbase, n) end end --- opus_multistream_decode_native (float). Returns the samples per channel, or < 0 on error. +-- opus_multistream_decode_native function Decoder.decodeMultistream(ms, buf, off, len, pcm, pbase, frameSize) local doPlc = buf == nil or len == 0 frameSize = min(frameSize, 5760) @@ -42185,7 +41605,6 @@ local doPlc = buf == nil or len == 0 return frameSize end --- writes src[base + 1 .. base + count] * gain to out as f32 from byte offset o function Decoder.writeF32(src, base, count, gain, out, o) local writef32 = buffer.writef32 if gain == 1 then @@ -42201,8 +41620,6 @@ function Decoder.writeF32(src, base, count, gain, out, o) end end --- Stereo downmix of n frames of srcCh-channel audio (src[base + 1 ..], interleaved): matrix[c * 2 + 1 / + 2] are the --- left / right weights of channel c. Writes f32 to out from byte offset o. function Decoder.writeDownmix(src, base, n, srcCh, matrix, gain, out, o) local writef32 = buffer.writef32 local p = base @@ -42226,13 +41643,9 @@ __FILES["codecs/audio/Opus/Mdct"] = function() --!strict --!native --!optimize 2 --- codecs/audio/Opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the --- kiss_fft stages used by libopus: radix 5, 3, 4 and 2). The 48 kHz mode uses N = 1920 >> shift for --- shift = 0..3 (FFT sizes 480, 240, 120, 60). Arrays are Luau tables of numbers, 1-based. --- Why not codecs/audio/Mdct (measured by the cleanup pass): the shared transform computes the full N-sample IMDCT through a --- DCT-IV, of which CELT keeps the middle N / 2, so routing the decoder through it made CELT decoding 2-3x slower --- (luau: 25 -> 54-76 ms for 3 s of 32 kbps stereo) and changed the output bits (same SNR against opusdec). This --- fused libopus port (pre-rotation, a kiss_fft with fixed factors, post-rotation, TDAC) stays private. +-- 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 @@ -42307,13 +41720,11 @@ local function bfly2(fr, fi, N) local tw = 0.7071067812 local p = 1 for _ = 1, N do - -- k = 0 local tr, ti = fr[p + 4], fi[p + 4] fr[p + 4] = fr[p] - tr fi[p + 4] = fi[p] - ti fr[p]=fr[p]+ tr fi[p]=fi[p]+ ti - -- k = 1 local a, b = fr[p + 5], fi[p + 5] tr = (a + b) * tw ti = (b - a) * tw @@ -42321,15 +41732,13 @@ local function bfly2(fr, fi, N) fi[p + 5] = fi[p + 1] - ti do local __DARKLUA_VAR=p + 1 fr[__DARKLUA_VAR]=fr[__DARKLUA_VAR]+ tr end do local __DARKLUA_VAR0=p + 1 fi[__DARKLUA_VAR0]=fi[__DARKLUA_VAR0]+ ti -end -- k = 2 - tr = fi[p + 6] +end tr = fi[p + 6] ti = -fr[p + 6] fr[p + 6] = fr[p + 2] - tr fi[p + 6] = fi[p + 2] - ti do local __DARKLUA_VAR1=p + 2 fr[__DARKLUA_VAR1]=fr[__DARKLUA_VAR1]+ tr end do local __DARKLUA_VAR2=p + 2 fi[__DARKLUA_VAR2]=fi[__DARKLUA_VAR2]+ ti -end -- k = 3 - a, b = fr[p + 7], fi[p + 7] +end a, b = fr[p + 7], fi[p + 7] tr = (b - a) * tw ti = -(b + a) * tw fr[p + 7] = fr[p + 3] - tr @@ -42490,7 +41899,7 @@ local function bfly5(fr, fi, fstride, twr, twi, m, N, mm) end end --- in-place forward FFT of bit-reversed input (opus_fft_impl) +-- opus_fft_impl (bit-reversed input) local function fftImpl(pl) local factors = pl.factors local fr, fi, twr, twi = pl.fr, pl.fi, pl.twr, pl.twi @@ -42520,9 +41929,7 @@ local function fftImpl(pl) end end --- clt_mdct_backward: input coefficients inp[inBase + k*stride] (k = 0 .. N/2-1, inBase is the 1-based index of --- coefficient 0), output written to out[outBase .. outBase + N/2 + overlap/2) with TDAC windowing of the first --- `overlap` samples (out[outBase] is sample 0). +-- clt_mdct_backward function Mdct.backward(inp, inBase, out, outBase, window, overlap, shift, stride) local pl = plans[shift + 1] local N4 = pl.n @@ -42544,7 +41951,6 @@ function Mdct.backward(inp, inBase, out, outBase, window, overlap, shift, stride xp2 =xp2- 2 * stride end fftImpl(pl) - -- post-rotate local h = outBase + (math.floor(overlap / 2)) for k = 0, N4 - 1 do local re = fi[k + 1] @@ -42619,7 +42025,6 @@ function Packet.channels(toc) return band(toc, 4) ~= 0 and 2 or 1 end --- samples per frame at rate Fs function Packet.samplesPerFrame(toc, Fs) if band(toc, 0x80) ~= 0 then local a = band(rshift(toc, 3), 3) @@ -42635,7 +42040,6 @@ if band(toc, 0x80) ~= 0 then ) end end --- total samples of a packet at 48 kHz, or -1 if invalid function Packet.samples(buf, off, len) if len < 1 then return -1 @@ -42673,9 +42077,7 @@ if len < 1 then return 2, 4 * readu8(buf, p + 1) + b0 end --- Splits a packet (opus_packet_parse_impl). Fills offsets[i] / sizes[i] (1-based, absolute buffer offsets) and --- returns the frame count, the TOC byte and the packet's total size including padding (self-delimited packets, as in --- multistream, carry an explicit size for the last frame). The count is -1 for an invalid packet. +-- opus_packet_parse_impl; self-delimited packets (multistream) carry an explicit size for the last frame function Packet.parse(buf, off, len, offsets, sizes, selfDelimited) if len < 1 then return -1, 0, 0 @@ -42811,19 +42213,8 @@ __FILES["codecs/audio/Opus/Silk"] = function() local __compat = __compat local bit32, __iter = __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/audio/Opus/Silk: SILK decoder: a bit-exact port of the libopus fixed-point SILK decoder (silk/dec_API.c and what it calls: --- decode_frame, decode_indices, decode_pulses, shell_coder, code_signs, decode_parameters, gain_quant, NLSF_*, --- LPC_fit, LPC_inv_pred_gain, decode_core, stereo_*, CNG, PLC, resampler_private_up2_HQ / IIR_FIR). BSD, see --- licenses/. --- --- local st = Silk.new(apiChannels) --- local ret, n = Silk.decode(st, ctrl, lostFlag, firstFrame, ec, out, outBase) --- ctrl = { nChannelsAPI, nChannelsInternal, API_sampleRate, internalSampleRate, payloadSize_ms } --- decodes one 10 / 20 ms SILK frame and writes n samples per channel (at API_sampleRate) to the Luau array --- `out`, interleaved by nChannelsAPI: out[outBase + i * nChannelsAPI + c], scaled int16 / 32768. --- --- Fixed-point emulation: all values are Luau numbers holding C int32 / int16 values. Products of two int32 values --- (64-bit in C) are split so that every intermediate stays below 2^53 and therefore exact. +-- 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") @@ -42834,7 +42225,7 @@ local floor = math.floor local Silk = {} -local P2 = table.create(64, 0) -- P2[s] = 2^s (1-based by s: P2[s] for s >= 1, P2_0 = 1) +local P2 = table.create(64, 0) for s = 1, 63 do P2[s] = 2 ^ s end @@ -42845,8 +42236,6 @@ if s == 0 then return P2[s] end --- C helpers ----------------------------------------------------------------------------------------------------- - local function s16(x) x = x % 65536 if x >= 32768 then @@ -43062,8 +42451,6 @@ local shft = 31 - clz32(len) return nrg, shft end --- LPC helpers --------------------------------------------------------------------------------------------------- - -- silk_bwexpander (int16 coefficients), ar 1-based local function bwexpander(ar, d, chirp_Q16) local chirp_minus_one_Q16 = chirp_Q16 - 65536 @@ -43261,8 +42648,6 @@ local function lpcAnalysisFilter(out, oo, inp, io, B, len, d) end end --- NLSF ---------------------------------------------------------------------------------------------------------- - local CB_NB_MB = { nVectors = 32, order = 10, @@ -43414,8 +42799,6 @@ local function nlsfDecode(pNLSF_Q15, NLSFIndices, CB) nlsfStabilize(pNLSF_Q15, CB.deltaMin_Q15, order) end --- Resampler (decoder side: 8 / 12 / 16 kHz up to the API rate) ---------------------------------------------------- - 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 } @@ -43543,7 +42926,6 @@ local function up2HQ(S, out, oo, inp, io, len) S[1], S[2], S[3], S[4], S[5], S[6] = s0, s1, s2, s3, s4, s5 end --- returns the next output index local function iirFirInterpol(out, oo, buf, max_index_Q16, incr) local index_Q16 = 0 while index_Q16 < max_index_Q16 do @@ -43624,8 +43006,6 @@ local function resampler(S, out, inp, io, inLen) end end --- Decoder state ------------------------------------------------------------------------------------------------- - local function newChannel() return { prev_gain_Q16 = 65536, @@ -43753,8 +43133,6 @@ local ret = 0 return ret end --- Bitstream: indices and pulses --------------------------------------------------------------------------------- - 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 } @@ -43925,8 +43303,6 @@ local function decodePulses(d, pulses, signalType, quantOffsetType, frame_length end end --- Parameters ---------------------------------------------------------------------------------------------------- - local pNLSF_Q15 = table.create(16, 0) local pNLSF0_Q15 = table.create(16, 0) @@ -44024,8 +43400,6 @@ local function decodeParameters(ch, ctrl, condCoding) end end --- Core synthesis ------------------------------------------------------------------------------------------------ - local sLTP = table.create(320, 0) local sLTP_Q15 = table.create(640, 0) local res_Q14 = table.create(80, 0) @@ -44191,8 +43565,6 @@ local function decodeCore(ch, ctrl, xq, xo, pulses) end end --- PLC / CNG ----------------------------------------------------------------------------------------------------- - local HARM_ATT_Q15 = { 32440, 31130 } local PLC_RAND_ATTENUATE_V_Q15 = { 31130, 26214 } local PLC_RAND_ATTENUATE_UV_Q15 = { 32440, 29491 } @@ -44518,8 +43890,6 @@ local function cng(ch, ctrl, frame, fo, length) end end --- Frame decode -------------------------------------------------------------------------------------------------- - -- silk_decode_frame: writes frame_length samples to out[fo ..] local function decodeFrame(ch, d, out, fo, lostFlag, condCoding) local L = ch.frame_length @@ -44570,8 +43940,6 @@ local L = ch.frame_length return L end --- Stereo -------------------------------------------------------------------------------------------------------- - local function stereoDecodePred(d, pred_Q13) local n = icdf(d, T.stereo_pred_joint_iCDF, 1, 8) local ix02 = math.floor(n / 5 @@ -44627,8 +43995,6 @@ local function stereoMSToLR(state, x1, x2, pred_Q13, fs_kHz, frame_length) x2[n + 2] = sat16(a - b) end end --- API ----------------------------------------------------------------------------------------------------------- - @@ -45256,22 +44622,6 @@ end __FILES["codecs/audio/Pcm"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. --- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one --- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au, --- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder. --- --- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else --- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read --- local audio = Pcm.collect(src) -- read everything into a Types.Audio --- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder --- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio --- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer --- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/audio/Pcm/Convert) --- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767] --- local x = Pcm.fromInt(s16, 16) -- s / 32768 --- --- Sample formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw. --- Never throws (a decoder's read that throws is caught and ends the stream). local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Types = __include("Types") @@ -45303,7 +44653,6 @@ Pcm.WAVE_FROM_VORBIS = { - local function audioRead(self, n, out) local a = self._audio local ch = a.channels @@ -45342,7 +44691,6 @@ if self._done then return b, got end --- source(v) -> Source | nil, Err.ARG: v is a Types.Audio or a Types.Decoder (anything with sampleRate, channels, read) function Pcm.source(v) if type(v) ~= "table" then return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") @@ -45365,7 +44713,6 @@ if type(v) ~= "table" then return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") end --- collect(src, maxFrames?) -> Types.Audio | nil, Err (everything the source has; Err.LIMIT past maxFrames) function Pcm.collect(src, maxFrames) local ch = src.channels local cap = math.max(src.frames, 4096) @@ -45373,7 +44720,6 @@ local ch = src.channels local total = 0 local limit = maxFrames or 2 ^ 31 local tmp= nil - -- a known length: one read straight into the result (decoders write into a big enough out buffer: no copy) if src.frames > 0 and src.frames <= limit then local b, n = src:read(src.frames, data) if n > 0 then @@ -45416,9 +44762,6 @@ local ch = src.channels return a, nil end --- drain(dec, source?, maxFrames?) -> Types.Audio | nil, Err: a format's decode() through its open(): every frame of --- the Decoder (dec.frames is only a hint: short or long streams keep what decodes), dec.tags, meta.source = source --- (default dec.source). A decoder that recorded a failure in dec.error (an Err) fails the drain. function Pcm.drain(dec, source, maxFrames) local src, err = Pcm.source(dec) if not src then @@ -45436,9 +44779,6 @@ local src, err = Pcm.source(dec) return a, nil end --- ------------------------------------------------------------------------------------------------ decoders --- rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags?) -> Types.Decoder | nil, Err.ARG: a streaming --- decoder over frames * channels samples of fmt at buf[offset] (the caller has checked the range is inside buf) function Pcm.rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags) local size = Convert.SIZE[fmt] if not size then @@ -45477,14 +44817,12 @@ return pos / sampleRate return dec , nil end --- audioDecoder(audio) -> Types.Decoder over a decoded Audio (no copy of the samples) function Pcm.audioDecoder(a) local d = (Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) ) d.bitrate = a.sampleRate * a.channels * 32 return d end --- encode(src, fmt, w) -> frames written | nil, Err: drains src into the Writer w as fmt samples function Pcm.encode(src, fmt, w) local size = Convert.SIZE[fmt] if not size then @@ -45510,9 +44848,6 @@ local size = Convert.SIZE[fmt] return total, nil end --- ------------------------------------------------------------------------------------------------ conversions --- reorder(buf, offset, frames, channels, map): in place, frame by frame, channel i of the result = channel map[i] --- (1-based) of the input; for converting between channel orders (Pcm.WAVE_FROM_VORBIS) function Pcm.reorder(buf, offset, frames, channels, map) local tmp = table.create(channels, 0) local readf32, writef32 = buffer.readf32, buffer.writef32 @@ -45527,7 +44862,6 @@ function Pcm.reorder(buf, offset, frames, channels, map) end end --- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0) function Pcm.toInt(x, bits) local s = 2 ^ (bits - 1) local v = math.floor(x * s + 0.5) @@ -45542,7 +44876,6 @@ local s = 2 ^ (bits - 1) return v end --- fromInt(v, bits) -> v / 2^(bits-1) function Pcm.fromInt(v, bits) return v / 2 ^ (bits - 1) end @@ -45553,12 +44886,9 @@ __FILES["codecs/audio/Pcm/Convert"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/audio/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/audio/Pcm). Integers map to --- v / 2^(bits-1) (as ffmpeg does); encoding rounds to nearest and clips. G.711 A-law / mu-law per ITU-T G.711 (the --- classic Sun g711.c algorithm, written from the spec). --- --- Formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw (u8: offset binary). --- Never throws: callers check ranges (Convert.SIZE[fmt] * count bytes) before calling. +-- 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 @@ -45584,7 +44914,6 @@ local SIZE= { ulaw = 1, } Convert.SIZE = SIZE --- the integer bit depth of each format (float: 32 / 64; G.711: 16 after expansion) Convert.BITS = { u8 = 8, s8 = 8, @@ -45602,11 +44931,9 @@ Convert.BITS = { ulaw = 16, } --- ------------------------------------------------------------------------------------------------ G.711 -local ALAW = table.create(256, 0) -- code -> linear s16 +local ALAW = table.create(256, 0) local ULAW = table.create(256, 0) for code = 0, 255 do - -- A-law local a = bit32.bxor(code, 0x55) local t = bit32.band(a, 0x0F) * 16 local seg = bit32.rshift(bit32.band(a, 0x70), 4) @@ -45618,8 +44945,7 @@ for code = 0, 255 do t = (t + 0x108) * 2 ^ (seg - 1) end ALAW[code + 1] = (bit32.band(a, 0x80) ~= 0 and{t }or{(-t -)})[1] -- mu-law - local u = bit32.bxor(code, 0xFF) +)})[1] local u = bit32.bxor(code, 0xFF) local m = (bit32.band(u, 0x0F) * 8 + 0x84) * 2 ^ bit32.rshift(bit32.band(u, 0x70), 4) ULAW[code + 1] = (bit32.band(u, 0x80) ~= 0 and((0x84 - m ))or((m - 0x84 )))end @@ -45635,7 +44961,6 @@ for i = 1, 8 do return 8 end --- linear s16 -> A-law code local function alawEncode(pcm) local mask local v = floor(pcm / 8) -- 13-bit magnitude domain @@ -45660,7 +44985,6 @@ local mask return bit32.bxor(aval, mask) end --- linear s16 -> mu-law code local function ulawEncode(pcm) local v = floor(pcm / 4) -- 14-bit local mask @@ -45688,8 +45012,6 @@ Convert.ulawEncode = ulawEncode Convert.ALAW = ALAW Convert.ULAW = ULAW --- ------------------------------------------------------------------------------------------------ decode --- decode(src, so, fmt, count, dst, do_) -> true | false (unknown fmt): count samples at src[so] -> f32 at dst[do_] function Convert.decode(src, so, fmt, count, dst, d) if fmt == "s16le" then for i = 0, count - 1 do @@ -45768,7 +45090,6 @@ if fmt == "s16le" then return true end --- ------------------------------------------------------------------------------------------------ encode local function q(x, s) local v = floor(x * s + 0.5) if v ~= v then @@ -45782,7 +45103,6 @@ local v = floor(x * s + 0.5) return v end --- encode(src, so, count, fmt, dst, do_) -> true | false: count f32 samples at src[so] -> fmt at dst[do_] function Convert.encode(src, so, count, fmt, dst, d) if fmt == "s16le" then for i = 0, count - 1 do @@ -45863,18 +45183,9 @@ __FILES["codecs/audio/Qoa"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale --- factor and 20 3-bit residuals over a 4-tap sign-sign LMS predictor. Ported from qoa.h (phoboslab/qoa, Dominic --- Szablewski, MIT: licenses/qoa-LICENSE.txt): the tables, the predictor, the decoder and the encoder's brute-force --- scale factor search, so encoding is byte-for-byte qoa.h's (including its 32-bit wrap in the reciprocal division). --- The 64-bit slices are handled as two 32-bit halves. --- --- local info = Qoa.frameInfo(buf, p, avail) -- { channels, rate, samples, size } | nil, message --- local n, msg = Qoa.decodeFrame(buf, p, avail, dst, d) -- one frame -> interleaved f32 at float index d --- local size = Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) -- n frames of f32 at frame xf -> bytes at out[p] --- local lms = Qoa.newLms(ch) -- the encoder state (history 0, weights 0, 0, -1, 2) --- --- Never throws: decodeFrame checks the frame against avail before reading; encodeFrame needs Qoa.frameSize bytes. +-- 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 @@ -45917,12 +45228,10 @@ local function s16(v) return (v >= 32768 and((v - 65536 ))or(v ))end --- frameSize(channels, slices) -> bytes function Qoa.frameSize(ch, slices) return 8 + 16 * ch + 8 * slices * ch end --- frameInfo(buf, p, avail) -> the frame header's facts, checked against avail and the slice count | nil, message function Qoa.frameInfo(b, p, avail) @@ -45948,8 +45257,6 @@ if avail < 8 then return { channels = ch, rate = rate, samples = samples, size = size }, nil end --- decodeFrame(buf, p, avail, dst, d) -> samples per channel, frame bytes | nil, message: one frame (its own LMS state --- in the header) as interleaved f32 into dst from float index d (dst holds samples * channels floats there) function Qoa.decodeFrame(b, p, avail, dst, d) local info, msg = Qoa.frameInfo(b, p, avail) if not info then @@ -46002,8 +45309,7 @@ end return samples, info.size end --- ------------------------------------------------------------------------------------------------ encoder --- newLms(ch) -> the encoder's LMS state: 8 i32 per channel (history 0..3, weights 0..3), weights 0, 0, -1, 2 (<< 13) +-- LMS state: 8 i32 per channel (history 0..3, weights 0..3); initial weights 0, 0, -1, 2 (<< 13) function Qoa.newLms(ch) local st = buffer.create(32 * ch) for c = 0, ch - 1 do @@ -46013,7 +45319,6 @@ local st = buffer.create(32 * ch) return st end --- the nearest s16 to x * 32768 (NaN -> 0) local function toS16(x) local v = floor(x * 32768 + 0.5) if v ~= v then @@ -46039,8 +45344,6 @@ local x = v * RECIP[sf + 1] + 32768 ) return n + sv - sn end --- encodeFrame(x, xf, n, ch, rate, lms, out, p) -> bytes written: frames xf .. xf + n - 1 (n <= 5120) of interleaved f32 x --- as one QOA frame at out[p] (Qoa.frameSize(ch, ceil(n / 20)) bytes); lms carries the encoder state between frames function Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) local slices = math.floor((n + 19) / 20 ) local size = Qoa.frameSize(ch, slices) @@ -46162,30 +45465,20 @@ __FILES["codecs/audio/Resample"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --!native --!optimize 2 --- codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or --- whole-buffer, any channel count, interleaved f32 (the Types.Audio / Decoder layout). Used by the Opus, MP3 and MP2 --- encoders (their input rates are fixed) and ops/AudioOps.resample. New in rosetta (the textbook polyphase --- filter; the kernel is the one the Opus encoder carried). +-- 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 (opts.cutoff, default 0.97) of the lower Nyquist frequency; quality picks the taps per side at the cutoff: +-- 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 (no delay: the filter is centred, the input is zero outside its --- range); a stream of n input frames gives floor(n * to / from + 0.5) output frames. --- --- local out, frames = Resample.buffer(samples, frames, channels, 44100, 48000, { quality = "high" }) --- local rs = Resample.new(44100, 48000, 2) -- nil, message for bad rates --- local b, n = rs:process(chunk, chunkFrames) -- the output frames this input completes --- local b2, n2 = rs:flush() -- the rest (the input end padded with zeros) --- local src2 = Resample.source(pcmSource, 48000) -- a codecs/audio/Pcm Source at the new rate --- --- Never throws: bad arguments return nil, message (the api turns them into Err.ARG). +-- 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 = {} @@ -46201,8 +45494,6 @@ local Resample = {} - - local QUALITY = { low = { 8, 6 }, medium = { 16, 8 }, high = { 32, 10 } } local MAX_EXACT = 4096 local INTERP_PHASES = 4096 @@ -46229,8 +45520,7 @@ while b ~= 0 do return a end --- filter(ratio, phases, exact, opts) -> the polyphase table. Phase p is the kernel for an output at fraction --- p / phases past an input sample; tap k multiplies input (floor(t) - half + 1 + k). +-- phase p: an output p / phases past an input sample; tap k multiplies input floor(t) - half + 1 + k @@ -46271,8 +45561,6 @@ end end end return { taps = taps, half = half, phases = phases, exact = exact, h = h } end --- the stream state: the input history as an interleaved Lua array; hist[1] is frame `base` (absolute) --- run(st, lastInput) -> buffer, frames: every output frame whose taps end at or before lastInput (absolute, exclusive) @@ -46320,8 +45608,8 @@ local f = st.f for j = j0, jmax - 1 do local num = j * M local ip = math.floor(num / L -- floor(t) -) local first = ip - half + 1 -- absolute input frame of tap 0 - local rel = first - base -- frame index in hist +) local first = ip - half + 1 + local rel = first - base local kLo = (rel < 0 and{(-rel )}or{0 })[1] local kHi = taps - 1 if rel + kHi >= histFrames then @@ -46360,7 +45648,6 @@ local f = st.f end end st.outPos = jmax - -- drop history no future output needs (keep from the next output's first tap) local keepFrom = math.floor((jmax * M) / L )- half + 1 local drop = keepFrom - base if drop > 0 then @@ -46404,7 +45691,6 @@ if self.done then return run(self, total, out) end --- new(from, to, channels, opts?) -> Resampler | nil, message function Resample.new(from, to, channels, opts) if type(from) ~= "number" or type(to) ~= "number" or from ~= from or to ~= to or from <= 0 or to <= 0 or from > 2 ^ 24 or to > 2 ^ 24 then return nil, "bad sample rates" @@ -46448,7 +45734,6 @@ if type(from) ~= "number" or type(to) ~= "number" or from ~= from or to ~= to or return st , nil end --- buffer(src, frames, channels, from, to, opts?) -> interleaved f32 buffer, frames | nil, message function Resample.buffer(src, frames, channels, from, to, opts) local rs, err = Resample.new(from, to, channels, opts) if not rs then @@ -46483,8 +45768,6 @@ end return out, got end --- source(src, to, opts?) -> a pull source ({ sampleRate, channels, frames, tags, read, err }, the codecs/audio/Pcm Source --- shape) reading src (any such source: Pcm.source(audioOrDecoder)) at the rate `to` | nil, message function Resample.source(src, to, opts) if type(src) ~= "table" or type(src.read) ~= "function" then return nil, "needs a source" @@ -46494,7 +45777,7 @@ if type(src) ~= "table" or type(src.read) ~= "function" then return nil, err end local ch = src.channels - local pending = buffer.create(0) -- produced but not yet returned + local pending = buffer.create(0) local pendingFrames, pendingPos = 0, 0 local ended = false local out = { @@ -46539,19 +45822,8 @@ return Resample end __FILES["codecs/audio/SoundFont"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by --- music/sf2 (the file format) and music/midi (rendering). The synth is a port of TinySoundFont (tsf.h v0.9, MIT, --- (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt); see Parse / Synth for what is covered. --- Without a bank, fallback() is a generated General MIDI set of simple waveforms (sine / triangle / square / saw / --- noise) with a drum kit. --- --- local SoundFont = require("rosetta.codecs.audio.SoundFont") --- local sf, err = SoundFont.parse(buf) -- buffer | string | core/Bytes Reader -> SoundFont | nil, Err --- local sf = SoundFont.fallback() -- the built-in waveform set --- local s = SoundFont.synth(sf, 44100, { gain = 0.5 }) -- a synth State; SoundFont.Synth.midi(s, 0x90, 60, 100) --- SoundFont.Synth.render(s, out, frame, n) -- mix n stereo f32 frames into out at frame --- --- Never throws: bad data returns nil, Err. +-- 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") @@ -46566,13 +45838,10 @@ local SoundFont = {} SoundFont.Synth = Synth SoundFont.defaultRegion = Parse.defaultRegion --- sniff(r) -> true when r starts with RIFF....sfbk function SoundFont.sniff(r) return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk" end --- parse(src, opts?) -> SoundFont | nil, Err. src: buffer | string | Reader. opts.maxRegions (default 10^6), --- opts.maxSamples (default 2^28) function SoundFont.parse(src, opts) local r if type(src) == "string" then @@ -46591,17 +45860,14 @@ if type(src) == "string" then return sf, err end --- fallback() -> the built-in General MIDI waveform set function SoundFont.fallback() return Fallback.build() end --- isSoundFont(v) -> true for a parsed / fallback SoundFont value function SoundFont.isSoundFont(v) return type(v) == "table" and v.kind == "soundfont" and type(v.samples) == "buffer" and type(v.presets) == "table" end --- synth(sf?, sampleRate?, opts?) -> State. opts.gain (linear, default 0.5), opts.maxVoices (default 256) function SoundFont.synth(sf, sampleRate, opts) return Synth.new(sf or Fallback.build(), sampleRate or 44100, opts and opts.gain, opts and opts.maxVoices) end @@ -46610,12 +45876,8 @@ return SoundFont end __FILES["codecs/audio/SoundFont/Fallback"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- codecs/audio/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont --- (the same shape Parse returns, so the same synth plays it): single-cycle sine / triangle / square / saw waves and a --- looped noise sample, one preset per GM family of 8 programs (piano, chromatic percussion, organ, guitar, bass, --- strings, ensemble, brass, reed, pipe, lead, pad, synth fx, ethnic, percussive, sound fx) with family envelopes, --- filters and vibrato, plus a drum kit on bank 128 (pitch-swept sine kicks and toms, filtered noise snares, hats with --- an exclusive class, cymbals). Written for this library (no third-party code). +-- 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 = {} @@ -46630,7 +45892,6 @@ end local cached= nil --- build() -> a SoundFont value (kind "soundfont"); built once, shared (the synth never writes to it) function Fallback.build() if cached then return cached @@ -46683,7 +45944,6 @@ local r = Parse.defaultRegion() return r end - -- the 16 GM families: wave + envelope / filter / vibrato local families= { { "piano", "triangle", { aDecay = 2.5, aSustain = 0, aRelease = 0.25 } }, { "chromatic", "sine", { aDecay = 1.2, aSustain = 0, aRelease = 0.3 } }, @@ -46708,9 +45968,7 @@ local r = Parse.defaultRegion() table.insert(presets, { name = "fallback " .. f[1], preset = program, bank = 0, regions = { region(f[2], f[3]) } }) end - -- the drum kit (bank 128, every program): one region per key local kit = {} - -- fields.semis: the pitch (semitones from the sample's natural pitch) at keytrack 0 local function drum(lo, hi, wave, fields) local r = region(wave, fields) r.lokey, r.hikey = lo, hi @@ -46761,20 +46019,14 @@ return Fallback end __FILES["codecs/audio/SoundFont/Parse"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/audio/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24 --- when present) as one f32 buffer, and the pdta "hydra" (phdr pbag pmod pgen inst ibag imod igen shdr), flattened --- into playable regions per preset: the instrument global zone, the preset global zone and the preset zone's --- generators merged the way TinySoundFont (tsf.h v0.9, MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt) --- does (tsf_load_presets / tsf_region_operator / tsf_region_envtosecs), with every index and sample offset clamped --- so the synth never reads outside the sample buffer. --- Differences from tsf.h: initialAttenuation is cB * 0.04 dB (FluidSynth's EMU-compatible scale; tsf uses 0.01); --- SF3 (Ogg samples) is not supported; modulators (pmod / imod) are read but not applied (as in tsf.h). --- Never throws: a bad file returns nil, Err. +-- 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 = {} --- a region (one sample zone of a preset), in "absolute" form: envelope / LFO times in seconds, sustain as a level @@ -46846,7 +46098,6 @@ local GEN= { [57] = { "group", "group" }, [58] = { "keycenter", "key" }, } --- the merged fields: value generators once each (several ops share a field), then the four address fields local MERGE= {} do local seen= {} @@ -46868,7 +46119,7 @@ local FIELDS = { "sampleIndex", } --- clear(relative): tsf_region_clear. relative = a preset zone (all zero: values add to the instrument's) +-- tsf_region_clear (relative: a preset zone, all zero so values add to the instrument's) local function clear(relative) local r= {} for _, f in __iter(FIELDS) do @@ -46898,7 +46149,6 @@ local c= {} return c end --- the region defaults in absolute form (seconds, levels): what Fallback builds its regions from function Parse.defaultRegion() local r = clear(false) r.keycenter = 60 @@ -46981,9 +46231,8 @@ local function envToSecs(r, p, sustainIsGain) end r[p .. "Sustain"] = sus end --- ------------------------------------------------------------------------------------------------ RIFF --- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte) +-- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte) local LAYOUT= { @@ -47004,7 +46253,6 @@ local INFO_NAMES = { ICOP = "copyright", ICMT = "comment", ISFT = "software", } --- parse(r, opts?) -> SoundFont | nil, Err function Parse.parse(r, opts) @@ -47063,7 +46311,7 @@ for i = 1, n do local rec = {} for _, w in __iter(layout) do if w == 20 then - table.insert(rec, 0) -- the name is read separately + table.insert(rec, 0) sub:skip(20) elseif w == 4 then table.insert(rec, sub:u32le()) @@ -47100,7 +46348,6 @@ end return nil, Err.new(Err.CORRUPT, "incomplete hydra: no " .. k .. " records") end end - -- samples local sr = smpl local count = math.floor(sr:remaining() / 2 ) if count > maxSamples then @@ -47125,14 +46372,13 @@ local count = math.floor(sr:remaining() / 2 end sm24 = s24 end - -- presets (tsf_load_presets) + -- tsf_load_presets local phdr, pbag, pgen = hydra.phdr, hydra.pbag, hydra.pgen local inst, ibag, igen, shdr = hydra.inst, hydra.ibag, hydra.igen, hydra.shdr local phdrNames, instNames, shdrNames = (hydra ).phdrNames, (hydra ).instNames, (hydra ).shdrNames local nInst = #inst - 1 -- the last record of each list is the terminal one local nShdr = #shdr - 1 - local function range(list, i, field, limit) -- [list[i][field], list[i + 1][field]) clamped to [1, limit] (1-based record indexes) - + local function range(list, i, field, limit) local a = list[i][field] + 1 local b = (list[i + 1] and((list[i + 1][field] + 1 ))or(a )) return math.max(1, a), math.min(b, limit + 1) @@ -47287,17 +46533,9 @@ end __FILES["codecs/audio/SoundFont/Synth"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --- codecs/audio/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. A port of TinySoundFont (tsf.h v0.9, --- MIT, (c) 2017-2025 Bernhard Schelling, based on SFZero (c) 2012 Steve Folta; licenses/TinySoundFont-LICENSE.txt): --- voices with the DAHDSR volume envelope (exponential decay / release), the modulation envelope to pitch and filter --- cutoff, the modulation and vibrato LFOs (triangle) to pitch / filter / volume, a resonant biquad low-pass, linear --- interpolation, loop modes (none / continuous / until release), 3 dB pan law, exclusive classes; channels with --- program / bank select (CC0 / CC32), drums (bank 128), pitch bend with RPN 0 range and RPN 1 / 2 tuning, CC7 volume, --- CC10 pan, CC11 expression, CC64 sustain, CC120 / 121 / 123. Effects (reverb, chorus) and modulators are not --- implemented (as in tsf.h). Output: interleaved stereo f32, mixed into the caller's buffer. --- Differences from tsf.h: the envelope gain is ramped across each 64-sample block (tsf.h steps it); a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only. --- Native, never throws: every buffer index is in range by construction (the regions are clamped by Parse / Fallback, --- the sample buffer has a zero pad sample, the output range is checked before mixing). +-- 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 @@ -47393,7 +46631,6 @@ local function gain2db(g) return g <= 0.00001 and-100 or 20 * math.log10(g) end --- ------------------------------------------------------------------------------------------------ envelope local function releaseSamples(e, rate) return floor(((e.release <= 0 and{FASTRELEASE }or{e.release})[1]) * rate) end @@ -47503,7 +46740,6 @@ local function newEnv() return { segment = DONE, isExp = false, isAmp = false, vel = 0, level = 0, slope = 0, untilNext = 0, delay = 0, attack = 0, hold = 0, decay = 0, sustain = 0, release = 0 } end --- ------------------------------------------------------------------------------------------------ filter / lfo local function lowpassSetup(v, fc) -- the biquad from earlevel.com (as tsf.h) local k = tan(PI * fc) @@ -47536,7 +46772,6 @@ local function lfoProcess(l, n) end end --- ------------------------------------------------------------------------------------------------ voices local function calcPitch(v, shift, rate) local r = v.region local note = v.key + r.transpose + r.tune / 100 @@ -47563,7 +46798,7 @@ local function voiceEnd(s, v) nextSegment(v.amp, SUSTAIN, s.rate) nextSegment(v.mod, SUSTAIN, s.rate) if v.region.loopMode == LOOP_SUSTAIN then - v.loopEnd = v.loopStart -- keep playing, stop looping + v.loopEnd = v.loopStart end end @@ -47590,8 +46825,6 @@ return { } end --- new(sf, sampleRate, opts) -> State. sf: { presets, samples } (Parse.parse or Fallback.build). --- opts.gain: output gain (linear, default 0.5); opts.maxVoices (default 256) function Synth.new(sf, rate, gain, maxVoices) local lookup= {} for i, p in __iter(sf.presets) do @@ -47624,7 +46857,6 @@ local function presetIndex(s, bank, preset) return s.lookup[bank * 128 + preset] or -1 end --- noteOn(s, channel, key, velocity 0..127) function Synth.noteOn(s, ch, key, velocity) local c = s.channels[ch + 1] if not c then @@ -47714,7 +46946,6 @@ v.region = region __DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end end end --- noteOff(s, channel, key): ends the oldest matching note (all its regions); held while sustain is down function Synth.noteOff(s, ch, key) local c = s.channels[ch + 1] if not c then @@ -47805,7 +47036,7 @@ local function setSustain(s, ch, c, on) end end --- program(s, channel, program): bank select + program change (channel 9: drums, bank 128) +-- channel 9: drums (bank 128) function Synth.program(s, ch, program) local c = s.channels[ch + 1] if not c then @@ -47835,7 +47066,6 @@ function Synth.program(s, ch, program) end end --- pitchBend(s, channel, 0..16383) function Synth.pitchBend(s, ch, value) local c = s.channels[ch + 1] if not c or c.pitchWheel == value then @@ -47845,7 +47075,6 @@ function Synth.pitchBend(s, ch, value) applyPitch(s, ch, c) end --- control(s, channel, controller, value 0..127) function Synth.control(s, ch, cc, value) local c = s.channels[ch + 1] if not c then @@ -47927,7 +47156,6 @@ function Synth.control(s, ch, cc, value) end end --- midi(s, status, d1, d2): one channel message function Synth.midi(s, status, d1, d2) local kind, ch = math.floor(status / 16), status % 16 if kind == 9 then @@ -47943,7 +47171,6 @@ function Synth.midi(s, status, d1, d2) end end --- reset(s): all voices off, channels back to their defaults function Synth.reset(s) for _, v in __iter(s.voices) do v.preset = -1 @@ -47956,7 +47183,6 @@ function Synth.reset(s) end end --- active(s) -> the number of sounding voices function Synth.active(s) local n = 0 for _, v in __iter(s.voices) do @@ -47967,7 +47193,6 @@ local n = 0 return n end --- ------------------------------------------------------------------------------------------------ render local function voiceRender(s, v, out, frame, numSamples) local region = v.region local input = s.samples @@ -48059,8 +47284,6 @@ local function voiceRender(s, v, out, frame, numSamples) v.lpActive, v.z1, v.z2 = lpActive, z1, z2 end --- render(s, out, frame, n): mixes n stereo frames into out (interleaved f32) starting at frame; out-of-range --- requests are clipped to the buffer function Synth.render(s, out, frame, n) local room = math.floor(blen(out) / 8 )- frame if frame < 0 or room <= 0 then @@ -48072,8 +47295,7 @@ function Synth.render(s, out, frame, n) if n <= 0 then return end - -- the sample buffer must hold every region's range + the pad sample (Parse / Fallback guarantee it; checked here - -- once so a hand-made SoundFont cannot index outside it) + -- the sample buffer must hold every region's range + the pad sample (checked once against hand-made SoundFonts) local count = math.floor(blen(s.samples) / 4 )- 1 for _, v in __iter(s.voices) do if v.preset ~= -1 then @@ -48091,32 +47313,12 @@ return Synth end __FILES["codecs/audio/Stream"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part --- every packet-based audio format repeated: decode packets in order into a pending float block, return frames in --- read()-sized pieces, drop the encoder priming at the start and the padding at the end (gapless), and seek by --- finding the packet holding the target (with codec pre-roll) and dropping up to it. AAC (ADTS), CAF and M4A use it; --- formats with their own seeking (Opus granule bisection, FLAC, MP3, Vorbis) keep their streams. New in rosetta --- (the loop the three formats carried). --- --- local dec, err = Stream.packets(dec, { -- dec: the Decoder table with its fields (sampleRate, channels, --- count = n, -- frames, duration, bitrate, tags, ...); read / seek / position --- start = function(i) return ... end, -- are added. start(i): packet i's first frame (absolute, before --- decode = function(i) return n, err end,-- trimming); decode(i) -> frames | nil, Err, the samples in pcm() --- pcm = function() return floats end, -- (interleaved, 1-based; or a buffer of f32) until the next decode --- reset = function() end, -- forget codec state (before a seek) --- skip = priming, stop = lastFrame, -- output = absolute frames [skip, stop) --- preroll = 1, -- packets decoded before the one holding a seek target (AAC: 1) --- scale = 1 / 32768, -- optional: read() writes pcm() values * scale (default 1) --- ints = true, -- optional: pcm() holds integers; adds dec:readInt(n, out?), the --- }) -- same frames as read() as i32 (bit-exact checks) --- --- A decode failure ends the stream and is kept in dec.error (Pcm.drain reports it); a failing first packet is --- returned by packets() as the open error. Never throws. +-- 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 = {} --- packets(dec, spec) -> dec (with read / seek / position) | nil, Err (the first packet failed) @@ -48140,7 +47342,7 @@ local sr, ch = dec.sampleRate, dec.channels local preroll = spec.preroll or 0 local decodeP, pcmOf, startOf = spec.decode, spec.pcm, spec.start local nextPacket = 1 - local decoded = 0 -- absolute frame after the packets decoded so far + local decoded = 0 local pendPos, pendN = 0, 0 local dropUntil = skip local pos = 0 @@ -48236,8 +47438,7 @@ return pull(n, out, true) function dec.seek(_self, seconds) local sec = (type(seconds) == "number" and seconds == seconds and{seconds }or{0 -})[1] local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip -- absolute frame - -- the last packet starting at or before the target, minus the codec's pre-roll +})[1] local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip local lo, hi, found = 1, count, 1 while lo <= hi do local mid = math.floor((lo + hi) / 2 @@ -48263,7 +47464,6 @@ return pull(n, out, true) return pos / sr end - -- prime: surface a broken first packet as an open error if count > 0 and frames > 0 and not fill() and failed then return nil, failed end @@ -48274,69 +47474,20 @@ return Stream end __FILES["codecs/audio/Tracker"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders --- that map other trackers onto those four effect families (music/mtm, 669, stm, ult, okt, med, ptm, far; helpers in --- codecs/audio/Tracker/Load). The loaders read their files into one Module structure (below); render(module, opts) plays any of them through the standard audio --- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM --- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests. +-- 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. -- --- local Tracker = require("rosetta.codecs.audio.Tracker") --- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder --- local seconds = Tracker.duration(module) -- one pass, song loops detected +-- 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). -- --- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file): --- format the file format ("mod", "s3m", "xm", "it", "mtm", "669", ...): what the module was read from --- engine "mod" | "s3m" | "xm" | "it": the effect family the engine plays (default: format, so the four --- families need no engine field). Other formats map their effects onto one family (music/mtm: "xm", --- music/669: "s3m", ...) and set the quirks they need in flags. --- preamp optional 0..256: the output gain as OpenMPT's sample pre-amp (gain = preamp / 128); default per family --- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s) --- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume) --- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index) --- linear linear frequency slides (XM / IT flag) or Amiga periods --- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column --- is a sample number (MOD, S3M, IT sample mode) --- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides: also on tick 0; any family), --- amigaLimits (MOD), and the quirks of the other formats (any family): --- periods = "amiga" (ProTracker period table + PAL clock, as MOD) | "hz" (periods are frequencies in --- Hz: 669, FAR; slides move hzSlide Hz per unit, tone portamento hzSlide * hzTonePorta), --- fastPortas (slides on tick 0 too), autoTonePorta (a tone portamento keeps running on later rows), --- autoReset (669: any effect stops the auto slides), st2Tempo (S3M family A: Scream Tracker 2 tempo), --- oktSlides (Oktalyzer note slides), panLaw = "ft2" (square-root panning, OpenMPT's FT2 mix levels), --- envRowHold (MED: envelopes do not advance on a row's first tick) } --- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width, --- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool } --- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels --- cells of 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. The volume column and effects are kept in the --- file's own coding: 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). Engine extension effects (any family, for the other formats): Tracker.EXT (0x40 note --- slide up, 0x41 down, 0x42 / 0x43 the same with retrigger: param = ticks per step << 4 | semitones; --- 0x44 / 0x45 auto portamento up / down (669: every tick until another effect), 0x46 frequency --- adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED)). --- Tracker.cell / Tracker.setCell read and write cells. --- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16, --- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong), --- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil), --- c5speed (S3M / IT), relativeNote, finetune -128..127 (MOD / XM), vibType / vibSweep / vibDepth / --- vibRate (IT auto-vibrato) } --- instruments { Instrument }: { name, sampleMap = { [note] = sample number }, noteMap = { [note] = note }, --- volEnv / panEnv / pitchEnv (Envelope?), fadeout (as stored: XM 0..4095, IT 0..1024), nna (0 cut, --- 1 continue, 2 note off, 3 fade), dct (0 off, 1 note, 2 sample, 3 instrument), dca (0 cut, 1 off, --- 2 fade), globalVolume 0..128, pan (0..256 or nil), pps, ppc (pitch-pan separation / centre), --- cutoff, resonance (0..127 or nil), vibType / vibSweep / vibDepth / vibRate (XM auto-vibrato) } --- Envelope { enabled, ticks = { tick }, values = { volume 0..64 | pan / pitch -32..32 }, loop, loopStart, --- loopEnd, sustain, susStart, susEnd (1-based point indexes), filter (IT pitch envelope as filter) } --- --- Pitch: two period spaces. Linear: P = (ref - note) * 64 - transpose (64 per semitone), 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. --- --- Not supported: MIDI macros other than IT's default filter macros (Z00..Z8F), glissando, ST3 / IT finetune effects --- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation. +-- 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") @@ -48376,23 +47527,17 @@ Tracker.Tables = Tables local CELL = 5 --- engine extension effects (see the Module notes above) Tracker.EXT = Player.EXT --- st2Tempo(byte) -> speed, tempo (BPM): a Scream Tracker 2 tempo byte Tracker.st2Tempo = Tables.st2Tempo local FAMILIES = { mod = true, s3m = true, xm = true, it = true } --- family(module) -> "mod" | "s3m" | "xm" | "it" | nil: the effect family a module plays as function Tracker.family(m) local f = m.engine or m.format return (type(f) == "string" and FAMILIES[f] and{f }or{nil })[1]end --- ------------------------------------------------------------------------------------------------ constructors --- newModule(format, channels, engine?) -> an empty Module (no patterns / samples) with the defaults of the effect family --- (engine, default format) function Tracker.newModule(format, channels, engine) local fam = engine or format local m = { @@ -48431,12 +47576,10 @@ local fam = engine or format return m end --- newPattern(rows, channels) -> an empty Pattern function Tracker.newPattern(rows, channels) return { rows = rows, data = buffer.create(rows * channels * CELL) } end --- newSample() -> an empty Sample function Tracker.newSample(name) return { name = name or "", @@ -48467,7 +47610,6 @@ function Tracker.newEnvelope() return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 } end --- newInstrument() -> an Instrument mapping every note to sample 0 (none) function Tracker.newInstrument(name) local sm, nm = table.create(120, 0), table.create(120, 0) for i = 1, 120 do @@ -48497,8 +47639,6 @@ local sm, nm = table.create(120, 0), table.create(120, 0) } end --- cell(module, pattern, row, channel) -> note, instrument, volume, effect, parameter (pattern 0-based, row 0-based, --- channel 1-based); nil when out of range function Tracker.cell(m, pattern, row, channel) local p = m.patterns[pattern + 1] if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then @@ -48509,7 +47649,6 @@ local p = m.patterns[pattern + 1] 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 --- setCell(module, pattern, row, channel, note, instrument, volume, effect, parameter) -> true | false (out of range) function Tracker.setCell(m, pattern, row, channel, note, ins, vol, fx, param) local p = m.patterns[pattern + 1] if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then @@ -48525,7 +47664,6 @@ local p = m.patterns[pattern + 1] return true end --- ------------------------------------------------------------------------------------------------ validation local function num(v, lo, hi) return type(v) == "number" and v == v and v >= lo and v <= hi end @@ -48587,8 +47725,6 @@ if not num(t0, 0, 2) or t0 == 0 or not num(s0, -2 ^ 52, 2 ^ 52) or not num(e0, - return s, e, t end --- validate(module) -> true | nil, Err: checks the structure the engine relies on, clamps loops, envelopes and --- numbers into range (in place) function Tracker.validate(m) if type(m) ~= "table" then return nil, Err.new(Err.ARG, "not a module") @@ -48695,11 +47831,9 @@ if type(m) ~= "table" then return true, nil end --- ------------------------------------------------------------------------------------------------ rendering local Decoder = {} Decoder.__index = Decoder --- duration(module, opts?) -> seconds of one pass (song loops and the end of the order list detected), or nil, Err function Tracker.duration(m, opts) local ok, err = Tracker.validate(m) if not ok then @@ -48726,7 +47860,6 @@ local function newPlayer(self) self.pos = 0 end --- render(module, opts?) -> Types.Decoder (stereo f32) | nil, Err function Tracker.render(m, opts) local o= opts or {} local sr = o.sampleRate or 44100 @@ -48757,13 +47890,11 @@ local o= opts or {} return self , nil end --- the Module method: module:render(opts) function Tracker.renderMethod(self, opts) local dec = Tracker.render(self, opts) return dec end --- run(self, out?, n) -> frames produced (out nil: advance without mixing) local function run(self, out, n) local st = self.st local done = 0 @@ -48790,7 +47921,6 @@ __DARKLUA_CONTINUE_13=true until true if not __DARKLUA_CONTINUE_13 then break en return done end --- read(n, out?) -> interleaved stereo f32 buffer, frames read (0 at the end) function Decoder.read(self, n, out) n = math.max(0, math.floor(tonumber(n) or 0)) local o = out @@ -48803,7 +47933,6 @@ n = math.max(0, math.floor(tonumber(n) or 0)) return o , got end --- seek(seconds): replays the song silently up to the position (sample positions included) function Decoder.seek(self, seconds) local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate)) newPlayer(self) @@ -48814,7 +47943,6 @@ function Decoder.seek(self, seconds) break end end - -- the gains ramp in from silence after a seek for _, v in __iter(self.st.voices) do v.gl, v.gr = 0, 0 end @@ -48828,12 +47956,9 @@ return Tracker end __FILES["codecs/audio/Tracker/Load"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- codecs/audio/Tracker/Load: helpers shared by the tracker loaders that map another format's effects onto one of the --- engine's families (music/mtm, 669, stm, ult, okt, med, ptm, far). Effects are first named the way OpenMPT's loaders --- name them ("portaup", "volslide", "modex", ...), then written in the family's own cell coding: S3M / IT letter --- codes (A = 1) with the IT volume column, or MOD / XM numbers. Ported from OpenMPT's ModCommand helpers --- (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight, CPattern::WriteEffect; BSD licence, --- licenses/openmpt-LICENSE.txt), reduced to what the engine plays. +-- 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") @@ -48843,7 +47968,6 @@ local Load = {} local EXT = Player.EXT --- the S3M / IT letter code of each effect name (engine extension effects included) local IT= { speed = 1, jump = 2, @@ -48896,7 +48020,7 @@ end local GLOBAL = { jump = true, ["break"] = true, speed = true, tempo = true, globalvol = true, globalvolslide = true } --- isGlobal(name, param) -> the effect acts on the whole song (OpenMPT's IsGlobalCommand) +-- OpenMPT's IsGlobalCommand function Load.isGlobal(name, param) if name == nil then return false @@ -48913,7 +48037,7 @@ if name == nil then return false end --- modCommand(cmd, param) -> name?, param: a MOD / XM effect number (0..F, XM letters 16..) by name (ConvertModCommand) +-- OpenMPT's ConvertModCommand local MODFX= { [0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [5] = "toneportavol", [6] = "vibratovol", [7] = "tremolo", [8] = "panning8", [9] = "offset", [10] = "volslide", [11] = "jump", @@ -48933,8 +48057,7 @@ if cmd == 0 and param == 0 then return n, param end --- itVolume(name, param, force) -> the IT volume-column byte + 1 (the engine's coding) for an effect that fits there, --- or nil (OpenMPT's ConvertToVolCommand; force: fit it with some loss of precision) +-- OpenMPT's ConvertToVolCommand (force: fit with some loss of precision) function Load.itVolume(name, param, force) if name == "volume" then return math.min(param, 64) + 1 @@ -48988,8 +48111,6 @@ if name == "volume" then return nil end --- itEffect(name, param) -> effect code, param in S3M / IT coding (0, 0 for none or an effect the family lacks; MOD's --- extended E commands become their S3M equivalents) function Load.itEffect(name, param) if name == nil then return 0, 0 @@ -49020,9 +48141,7 @@ if name == nil then return code, param end --- fillTwo(name1, param1, name2, param2, lowResOffset?) -> volume byte (engine IT coding, 0 none), effect name, param, --- lost name?, lost param: two effects of one cell into the IT volume column and the effect column, keeping the --- heavier one when both cannot fit (OpenMPT's FillInTwoCommands) +-- OpenMPT's FillInTwoCommands function Load.fillTwo(e1, p1, e2, p2) if e1 ~= nil and e1 == e2 then e2 = nil -- the same effect twice: keep one (most are absolute; slides are kept once too, a simplification) @@ -49044,10 +48163,7 @@ if e1 ~= nil and e1 == e2 then return 0, e2, p2, e1, p1 end --- writeEffect(m, pattern (0-based), row, fx, param, retry?, channel?, multiple?) -> true when written: puts an effect --- into a free effect slot of the row (any channel, or the given 1-based one); none free: the next row (retry "next") or --- the previous one ("prev"). The same effect already on the row counts as written unless multiple (OpenMPT's --- CPattern::WriteEffect). +-- OpenMPT's CPattern::WriteEffect function Load.writeEffect(m, pattern, row, fx, param, retry, channel, multiple) local p = m.patterns[pattern + 1] if not p then @@ -49090,9 +48206,6 @@ local p = m.patterns[pattern + 1] return false end --- readSample(buf, offset, frames, spec, sample, budget) -> true | nil, Err: decodes raw PCM (codecs/audio/Tracker/Pcm --- spec) at the absolute buffer offset into the sample (data, length, bits, channels). A short file keeps the frames --- that are there (end = the buffer's length, or spec.limit). budget = { left = f32 bytes still allowed } (maxBytes). function Load.readSample(buf, offset, frames, spec, s, budget) local nch = spec.channels or 1 local bps = math.floor(spec.bits / 8 @@ -49111,7 +48224,7 @@ local nch = spec.channels or 1 return true, nil end --- bcd(n) -> n as the two decimal digits S3M / MOD pattern breaks store (0..99) +-- S3M / MOD pattern breaks store the row as two decimal digits function Load.bcd(n) n = math.clamp(math.floor(n), 0, 99) return (math.floor(n / 10)) * 16 + n % 10 @@ -49122,18 +48235,13 @@ end __FILES["codecs/audio/Tracker/Mixer"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --- codecs/audio/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample --- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole --- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code). --- --- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/audio/Tracker) --- validates the sample buffers' sizes. +-- 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 = {} --- mixVoice(v, out?, off, n, linear, ramp): n frames of voice v added at frame off of out (nil: only advance) local function mixVoice(v, out, off, n, linear, ramp) local data= v.data local nch = v.nch @@ -49283,7 +48391,6 @@ __DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end local _ = ramp end --- mix(st, out?, off, n, linear): every active voice of player st; out nil only advances the sample positions function Mixer.mix(st, out, off, n, linear) for _, v in __iter(st.voices) do if v.active and v.data then @@ -49297,17 +48404,14 @@ end __FILES["codecs/audio/Tracker/Pcm"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --- codecs/audio/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned, --- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back. --- --- Never throws: reads past the source are refused up front (decode returns nil). +-- 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 = {} --- bytes(frames, spec) -> the size of the raw data @@ -49321,7 +48425,6 @@ function Pcm.bytes(frames, spec) return frames * (spec.channels or 1) * (math.floor(spec.bits / 8)) end --- decode(buf, off, frames, spec) -> f32 buffer (frames * channels, interleaved) | nil when the source is too short function Pcm.decode(buf, off, frames, spec) local nch = spec.channels or 1 local bps = math.floor(spec.bits / 8 @@ -49373,7 +48476,6 @@ local nch = spec.channels or 1 return out end --- encode(samples, frames, spec) -> raw PCM (signed or unsigned, optional delta, interleaved or planar) function Pcm.encode(samples, frames, spec) local nch = spec.channels or 1 local bps = math.floor(spec.bits / 8 @@ -49415,7 +48517,6 @@ local nch = spec.channels or 1 return out end --- bits(samples) -> 8 when every value is exactly representable in 8 bits (data loaded from 8-bit), else 16 function Pcm.bitsNeeded(samples) for i = 0, math.floor(buffer.len(samples) / 4 )- 1 do local x = readf32(samples, i * 4) * 128 @@ -49431,15 +48532,9 @@ end __FILES["codecs/audio/Tracker/Player"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native --- codecs/audio/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders, --- speed / tempo, every effect of the four formats (interpreted per format family: ProTracker / FastTracker 2 numeric --- effects, ScreamTracker 3 / Impulse Tracker letter effects), instruments with volume / panning / pitch envelopes, --- fadeout and auto-vibrato, IT new note actions (background voices), duplicate checks and resonant filters, and song --- end / loop detection. Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes, --- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/audio/Tracker/Mixer. --- --- Never throws: the module is validated by codecs/audio/Tracker before a player is made, and every table lookup here is --- guarded. +-- 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 @@ -49454,8 +48549,6 @@ 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 } --- engine extension effects: format-specific commands of the other tracker formats, in any family (see --- codecs/audio/Tracker) local EXT = { NOTE_SLIDE_UP = 0x40, NOTE_SLIDE_DOWN = 0x41, @@ -49468,9 +48561,8 @@ local EXT = { } Player.EXT = EXT -local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions +local BG_VOICES = 64 --- ------------------------------------------------------------------------------------------------ state local function newVoice() return { active = false, @@ -49531,8 +48623,8 @@ return { tremorMute = false, surround = false, rampN = 0, - owner = 0, -- the channel whose foreground voice this is (0: free or background) - order = 0, -- allocation age + owner = 0, + order = 0, } end @@ -49557,7 +48649,6 @@ return { fx = 0, param = 0, vcmd = 0, - -- memories mPortaUp = 0, mPortaDn = 0, mFineUp = 0, @@ -49617,15 +48708,14 @@ return { muted = false, triggered = false, autoPorta = 0, -- auto portamento (EXT 0x44 / 0x45): period units per tick, + down - autoTone = false, -- flags.autoTonePorta: the tone portamento keeps running + autoTone = false, hzAdd = 0, -- EXT 0x46: Hz added to the frequency (669) - slideCount = 0, -- note slides: ticks to the next step + slideCount = 0, mNoteSlide = 0, tonePortaRow = false, } end --- new(module, opts) -> player state (module validated by the caller) function Player.new(m, sampleRate, opts) local fmt = FAMILY[m.engine or m.format] or MOD local flags = m.flags @@ -49644,8 +48734,8 @@ local fmt = FAMILY[m.engine or m.format] or MOD compatG = m.flags.compatGxx or false, fastSlides = flags.fastSlides or false, amigaLimits = flags.amigaLimits or false, - ptPeriods = ptPeriods, -- ProTracker periods (integer table periods, PAL clock) - hz = flags.periods == "hz", -- periods are frequencies in Hz + ptPeriods = ptPeriods, + hz = flags.periods == "hz", hzScale = (type(flags.hzSlide) == "number" and{flags.hzSlide }or{1})[1], hzTone = (type(flags.hzTonePorta) == "number" and{flags.hzTonePorta }or{1})[1], fastPortas = flags.fastPortas or false, @@ -49717,8 +48807,6 @@ if type(m.preamp) == "number" then return 2 / clamp(m.channels, 2, 8) end --- ------------------------------------------------------------------------------------------------ orders and rows --- startOrder(st, ord, row): resolve skip markers / the end of the order list; sets st.pat or st.ended function Player.startOrder(st, ord, row) local m = st.m local order = m.order @@ -49788,8 +48876,6 @@ local function advanceRow(st) end end --- ------------------------------------------------------------------------------------------------ pitch --- the period of a note for a sample (see codecs/audio/Tracker for the two period spaces) local function notePeriod(st, note, smp, ft) local base, ref, tr if st.fmt == MOD or st.fmt == XM then @@ -49843,8 +48929,7 @@ local function clampPeriod(st, c) end end --- slide(st, c, units): a pitch slide in period units (positive: down; 4 per effect unit); in Hz mode the frequency --- moves units * hzSlide Hz the other way +-- pitch slides in period units (positive: down; 4 per effect unit); in Hz mode the frequency moves units * hzSlide Hz the other way local function slide(st, c, units) if st.hz then c.period =c.period- units * st.hzScale @@ -49854,7 +48939,6 @@ local function slide(st, c, units) clampPeriod(st, c) end --- ------------------------------------------------------------------------------------------------ voices local function allocVoice(st) local best, bestScore = nil, math.huge for _, v in __iter(st.voices) do @@ -49872,7 +48956,6 @@ local best, bestScore = nil, math.huge best.active = false return best end - -- every voice is busy in the foreground (more channels than voices): reuse an inactive one anyway for _, v in __iter(st.voices) do if not v.active then local c = st.chans[v.owner] @@ -49882,7 +48965,7 @@ local best, bestScore = nil, math.huge return v end end - return st.voices[1] -- unreachable: there are more voices than channels + return st.voices[1] end local function keyOff(st, v) @@ -49923,7 +49006,6 @@ local function cutVoice(v) end end --- start(st, c, smp, smpIdx, ins, insIdx, note, period, base, offset): a fresh voice for channel c local function startVoice(st, c, smp, smpIdx, ins, insIdx, note, period, base, keepEnv) local v = c.voice if v == nil or v.bg then @@ -49972,7 +49054,6 @@ end -- IT new note actions on the channel's current voice (and duplicate checks on all its voices) local function newNoteAction(st, c, ins, insIdx, note, smpIdx) - -- duplicate check: voices of this channel playing the same instrument if ins and ins.dct and ins.dct > 0 then for _, u in __iter(st.voices) do if u.active and u.chan == c.idx and u.insIdx == insIdx then @@ -50013,7 +49094,6 @@ local function newNoteAction(st, c, ins, insIdx, note, smpIdx) end end --- ------------------------------------------------------------------------------------------------ triggering local function isPorta(st, fx, vcmd) local f = st.fmt if f == MOD then @@ -50025,7 +49105,6 @@ local f = st.fmt return fx == 7 or fx == 12 or (f == IT and vcmd >= 194 and vcmd <= 203) end --- the sample and real note for an instrument number + note local function resolve(st, insIdx, note) local m = st.m if st.insMode then @@ -50099,7 +49178,6 @@ local function sampleOffset(st, c, v) end end --- trigger(st, c, note, insIdx, vcmd): the note / instrument / volume column part of a cell local function trigger(st, c, note, insIdx, vcmd) local f = st.fmt local m = st.m @@ -50233,7 +49311,6 @@ local function trigger(st, c, note, insIdx, vcmd) end end --- ------------------------------------------------------------------------------------------------ effect helpers local function volSlideMod(c, param) local x, y = math.floor(param / 16), param % 16 if x > 0 then @@ -50289,8 +49366,7 @@ local function retrigVolume(c, x) c.vol = clamp(c.vol, 0, 64) end --- S3M / IT D-style slide of a value: returns the new value (fine parts only on tick 0, normal parts on other ticks; --- fast: normal parts on tick 0 too) +-- S3M / IT D-style slide: fine parts only on tick 0, normal parts on other ticks (fast: normal parts on tick 0 too) local function dSlide(value, param, tick, fast, hi) local x, y = math.floor(param / 16), param % 16 if y == 0xF and x > 0 then @@ -50315,7 +49391,6 @@ local x, y = math.floor(param / 16), param % 16 return value end --- ------------------------------------------------------------------------------------------------ MOD / XM effects local function fxModXm(st, c, tick) local fx, param = c.fx, c.param local xm = st.fmt == XM @@ -50629,7 +49704,6 @@ local function volColXm(st, c, tick) end end --- ------------------------------------------------------------------------------------------------ S3M / IT effects -- the parameter after memory: IT keeps one memory per effect group, ST3 one memory for most effects local function mem(st, c, field, param) if st.fmt == S3M then @@ -51037,8 +50111,6 @@ local function volColIt(st, c, tick) end end --- ------------------------------------------------------------------------------------------------ extension effects --- the engine extension effects (EXT, codes 0x40..) and the auto slides, in any family local function fxExt(st, c, tick) local fx, param = c.fx, c.param if fx >= EXT.NOTE_SLIDE_UP and fx <= EXT.NOTE_SLIDE_DOWN_RETRIG then @@ -51097,7 +50169,6 @@ local function fxExt(st, c, tick) end end --- ------------------------------------------------------------------------------------------------ rows and ticks local function noteDelayOf(st, fx, param) if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and math.floor(param / 16 )== 0xD then return param % 16 @@ -51194,8 +50265,7 @@ local function processRow(st) local _ = m end -local function updateEnvelope(env, pos, keyOn, it) -- returns value, next position, ended - +local function updateEnvelope(env, pos, keyOn, it) local ticks, values = env.ticks, env.values local n = #ticks if n == 0 then @@ -51236,7 +50306,6 @@ local ticks, values = env.ticks, env.values return value, nextPos, ended end --- per-tick voice update: envelopes, fadeout, auto-vibrato, final frequency, gains and filter local function updateVoice(st, v) local ins = v.ins local it = st.fmt == IT @@ -51307,7 +50376,6 @@ local function updateVoice(st, v) end v.avPos = (v.avPos + (avSrc.vibRate or 0)) % 256 end - -- frequency local P = v.periodOut + avDelta local freq if st.hz then @@ -51321,7 +50389,6 @@ local function updateVoice(st, v) freq =freq* 2 ^ (envPitch / 24) end v.inc = freq / st.sr - -- volume 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, @@ -51330,7 +50397,6 @@ local function updateVoice(st, v) ) if v.tremorMute then vol = 0 end - -- panning 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) @@ -51352,7 +50418,6 @@ local function updateVoice(st, v) v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256 end v.rampN = st.ramp - -- IT resonant filter local cutoff = v.cutoff if filterEnv ~= nil or cutoff < 127 or v.reso > 0 then local cc = cutoff @@ -51377,7 +50442,6 @@ local function updateVoice(st, v) end end --- tick(st) -> frames to mix for this tick (0 when the song ended) function Player.tick(st) if st.ended then return 0 @@ -51390,7 +50454,6 @@ if st.ended then return 0 end if st.visited[key] then - -- looping on: forget the song so far, keep playing table.clear(st.visited) end st.fineDelay = 0 @@ -51414,7 +50477,6 @@ if st.ended then if st.ended then return 0 end - -- channel -> foreground voice for i = 1, st.nch do local c = st.chans[i] local v = c.voice @@ -51440,7 +50502,6 @@ if st.ended then 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)) - -- advance st.tick =st.tick+ 1 if st.tick >= st.speed + st.fineDelay then st.tick = 0 @@ -51459,16 +50520,13 @@ end __FILES["codecs/audio/Tracker/Tables"] = function() --!strict --!native --- codecs/audio/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the --- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M --- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker --- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT). +-- 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 } --- wave64(type, pos) -> -255..255 for pos 0..63: 0 sine, 1 ramp down, 2 square, 3 random (deterministic) local RANDOM= {} do local s = 12345 @@ -51490,8 +50548,6 @@ local p = pos % 64 return (p >= 32 and{(-v )}or{v })[1]end --- autoWave(type, pos, it) -> -64..64 for pos 0..255. XM: 0 sine, 1 square, 2 ramp down, 3 ramp up. --- IT: 0 sine, 1 ramp down, 2 square, 3 random. local SINE256= {} for i = 0, 255 do SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5) @@ -51518,9 +50574,7 @@ local p = pos % 256 return SINE256[p + 1] end --- ProTracker periods, finetune 0, C-0 .. B-4 (60 notes; ProTracker itself uses C-1 .. B-3). Our note numbers: --- 1 = C-0 (FT2 numbering), so ProTracker C-1 (856) = note 37 and C-2 (428) = note 49, the note that plays a sample at --- its base rate (8363 Hz). +-- 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, @@ -51532,12 +50586,10 @@ local PERIODS = { Tables.PERIODS = PERIODS Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1) --- periodToNote(period) -> note (1..120), 0 for period 0 function Tables.periodToNote(period) if period <= 0 then return 0 end - -- exact match first, then the nearest note on a log scale for i = 1, #PERIODS do if PERIODS[i] == period then return i + Tables.PERIOD_FIRST_NOTE - 1 @@ -51547,7 +50599,6 @@ if period <= 0 then return math.clamp(n, 1, 120) end --- noteToPeriod(note) -> ProTracker period (finetune 0) for a note, computed past the table's ends function Tables.noteToPeriod(note) local i = note - Tables.PERIOD_FIRST_NOTE + 1 if i >= 1 and i <= #PERIODS then @@ -51563,14 +50614,12 @@ Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 } 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 } --- the Amiga clock constant: frequency = AMIGA / period, with period 1712 playing an 8363 Hz sample at its base rate --- (FT2 / ST3 period units, 4x ProTracker's) +-- 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 --- st2Tempo(byte) -> speed, tempo: a Scream Tracker 2 tempo byte (high nibble ticks per row, low nibble a fine factor) --- as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at its 23863 Hz mixing rate, as a fractional BPM) +-- Scream Tracker 2 tempo byte as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at 23863 Hz, as a fractional BPM) local ST2_FACTOR = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 } function Tables.st2Tempo(byte) local hi, lo = math.floor(byte / 16), byte % 16 @@ -51586,24 +50635,15 @@ return Tables end __FILES["codecs/audio/Tta"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description --- (the 22-byte header with its CRC-32, the seek table of frame sizes with its CRC-32, frames of 256 / 245 seconds); --- no libtta / ffmpeg code (those are LGPL). The frame decoder is codecs/audio/Tta/Decode. Supports format 1 (plain --- PCM), 8 / 16 / 24 bits, any channel count, the header / seek table / frame CRCs. Not supported: format 2 --- (password-protected: UNSUPPORTED), TTA2. --- --- local info, err = Tta.info(buf, at, limit) -- the header at `at` (after any ID3v2 tag) + the frame table --- local dec = Tta.decoder(info) --- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved integers) --- --- Never throws: bad data returns nil, Err. +-- 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 = {} --- info(buf, at, limit) -> Info | nil, Err: the TTA1 header at byte `at` @@ -51672,7 +50712,6 @@ if at + 22 > limit then end return info, nil end --- ------------------------------------------------------------------------------------------------ decoder @@ -51699,7 +50738,6 @@ local info = self.info return got, nil end --- decoder(info, limit) -> Decoder (limit: the end of the file data) function Tta.decoder(info, limit) return { info = info, @@ -51716,10 +50754,8 @@ __FILES["codecs/audio/Tta/Decode"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/audio/Tta/Decode: one TTA1 frame -> samples. Written from the TTA1 format description (the True Audio --- format notes: adaptive Rice codes with two running sums per channel, the order-8 sign-LMS "hybrid" filter, the --- first-order fixed predictor, inter-channel decorrelation, a CRC-32 per frame); no libtta / ffmpeg code. Checked --- bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). Never throws: returns nil, message. +-- 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 @@ -51731,11 +50767,10 @@ local Decode = {} local TWO31, TWO32 = 2147483648, 4294967296 local INV31 = 1 / TWO31 local PAD = 16 -local P2= table.create(40, 0) -- P2[k + 1] = 2^k +local P2= table.create(40, 0) for i = 0, 39 do P2[i + 1] = 2 ^ i end --- ONES[b + 1]: the trailing 1 bits of the byte b local ONES= table.create(256, 0) for b = 0, 255 do local n, v = 0, b @@ -51746,7 +50781,6 @@ for b = 0, 255 do ONES[b + 1] = n end --- longUnary(S, pos, lim) -> the count of 1 bits from pos, the position after the 0 | nil (past lim) local function longUnary(S, pos, lim) local unary = 0 while pos <= lim do @@ -51774,7 +50808,6 @@ end - function Decode.state(channels, bytes) return { channels = channels, @@ -51790,8 +50823,6 @@ return { } end --- frame(st, buf, o, len, n, P) -> n | nil, message: the frame of len bytes at o (its CRC-32 last) holding n samples per --- channel, into P (interleaved integers) function Decode.frame(st, buf, o, len, n, P) if len < 4 then return nil, "truncated frame" @@ -51820,15 +50851,14 @@ if len < 4 then Q[c * 8 + i], X[c * 8 + i], L[c * 8 + i] = 0, 0, 0 end end - local pos = 0 -- bit position + local pos = 0 local lim = dlen * 8 - local c = 0 -- the channel of the sample at idx + local c = 0 for idx = 1, n * C do do if pos > lim then return nil, "truncated frame" end - -- the unary prefix: 1 bits up to a 0 (a run past one byte goes to longUnary) local unary local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) local ones = ONES[band(w, 255) + 1] @@ -51937,7 +50967,6 @@ if len < 4 then L[fb + 6] = n6 L[fb + 7] = n7 L[fb + 8] = value - -- the fixed predictor value =value+ math.floor((last[c + 1] * (pk - 1)) / pk ) last[c + 1] = value cur[c + 1] = value @@ -51975,10 +51004,8 @@ return Decode end __FILES["codecs/audio/Vorbis"] = function() --!strict --- codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup), --- codebooks (Codebook), audio packets to PCM (Packet: floors 0 / 1, residues 0 / 1 / 2, coupling, the IMDCT through --- codecs/audio/Mdct) and the shared tables. A Luau port of stb_vorbis 1.22 (public domain / MIT, --- licenses/stb_vorbis-LICENSE.txt). Ogg Vorbis (pages, granules, seeking) and the encoder are audio/vorbis. +-- 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"), @@ -51992,14 +51019,9 @@ __FILES["codecs/audio/Vorbis/Codebook"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- codecs/audio/Vorbis/Codebook: the Vorbis LSB-first packet bit reader and codebooks (Vorbis I spec sections 2 and 3): --- reading a codebook from the setup header (ordered / sparse length lists, lookup types 1 and 2, float32_unpack), --- the codeword assignment, and Huffman / VQ decoding. Ported from stb_vorbis 1.22 (public domain / MIT; see --- licenses/stb_vorbis-LICENSE.txt): compute_codewords' lowest-free-leaf assignment, lookup1_values; the decode side --- is a fast table (up to 10 bits) plus a binary tree for longer codes instead of stb's sorted binary search. --- --- Never throws. Reading past the packet end gives zero bits and sets br.eop (the spec's end-of-packet condition); --- an invalid codeword also sets eop and decodes to -1. +-- 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 @@ -52009,7 +51031,6 @@ local POW = table.create(41, 0) for i = 0, 40 do POW[i + 1] = 2 ^ i end --- ------------------------------------------------------------------------------------------------ bit reader @@ -52025,7 +51046,6 @@ function Codebook.reader(buf, offset, size) return { buf = buf, pos = offset, limit = offset + size, acc = 0, cnt = 0, pad = 0, eop = false } end --- bits(br, n) -> the next n (0..32) bits as an unsigned number local function bits(br, n) if n == 0 then return 0 @@ -52057,7 +51077,7 @@ if n == 0 then end Codebook.bits = bits --- ilog(x): the number of bits needed to hold x (0 for x <= 0) +-- ilog (spec 9.2.1) local function ilog(x) local n = 0 while x > 0 do @@ -52076,7 +51096,6 @@ local mantissa = x % 2097152 local v = mantissa * 2 ^ (exp - 788) return (sign and{(-v )}or{v })[1]end --- ------------------------------------------------------------------------------------------------ codebooks @@ -52143,7 +51162,6 @@ if first then available[y + 1] = code + POW[33 - y] + 1 end end - -- walk the MSB-first code into the tree local node = 1 for d = 1, len do local bit = floor(code / POW[33 - d]) % 2 @@ -52180,7 +51198,6 @@ if first then end end book.used = used - -- the fast table: every fastBits-bit prefix (read LSB first) walked down the tree local fb = math.clamp(maxLen, 1, 10) book.fastBits = fb local size = POW[fb + 1] @@ -52196,7 +51213,7 @@ if first then fl[idx + 1], fs[idx + 1] = d, -child - 1 break elseif child == 0 then - break -- invalid (-1) + break end node = child if d == fb then @@ -52208,7 +51225,6 @@ if first then return nil end --- read(br) -> Book | nil, message: one codebook from the setup header function Codebook.read(br) if bits(br, 24) ~= 0x564342 then return nil, "bad codebook sync" @@ -52328,7 +51344,6 @@ if bits(br, 24) ~= 0x564342 then return book, nil end --- decode(br, book) -> entry number | -1 (end of packet / invalid codeword: br.eop is set) local function decode(br, book) local fb = book.fastBits local acc, cnt = br.acc, br.cnt @@ -52388,18 +51403,10 @@ __FILES["codecs/audio/Vorbis/Packet"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --!native --!optimize 2 --- codecs/audio/Vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8): mode and window shape, floor 1 --- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/audio/Mdct), windowing and overlap-add. --- Floors, residues and coupling are ported from stb_vorbis 1.22 vorbis_decode_packet_rest / decode_residue / --- do_floor / draw_line (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). The overlap follows libvorbis: --- each packet after the first returns the n_prev/4 + n_cur/4 samples between the centres of the two windows, so --- granule positions count exactly the samples returned (the first packet returns none). --- --- local st = Packet.new(ident, setup) --- local n = Packet.decode(st, buf, offset, size) -- frames now in st.out[ch][1 .. n]; -1 = not an audio packet --- Packet.reset(st) -- forget the overlap (after a seek / a gap) --- local bs = Packet.blocksize(st, buf, offset, size) -- the packet's block size (0 = not audio), header bits only --- Never throws: a damaged packet decodes as far as its bits go (the spec's end-of-packet rule) or returns -1. +-- 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") @@ -52488,7 +51495,6 @@ function Packet.reset(st) st.tailLen = 0 end --- blocksize(st, buf, off, size) -> the block size of an audio packet (0 if not audio) function Packet.blocksize(st, b, off, size) if size < 1 then return 0 @@ -52505,7 +51511,6 @@ if size < 1 then return (mode.blockflag == 1 and{st.n1 }or{st.n0 })[1]end --- ------------------------------------------------------------------------------------------------ floor 1 local function predict(x, x0, x1, y0, y1) local dy = y1 - y0 local adx = x1 - x0 @@ -52542,7 +51547,6 @@ end x =x+ 1 end end --- decode the floor of one channel into finalY (-1 = unused point); false = this channel is silent local function floorDecode(st, br, g, finalY) if bits(br, 1) == 0 then return false @@ -52646,8 +51650,6 @@ local function floorCurve(g, finalY, target, n2) end end --- ------------------------------------------------------------------------------------------------ residue --- add the vectors of one partition to target at offset (0-based) .. offset + psize (bounded by limit) local function partition(br, book, target, offset, psize, rtype, limit) local vq = book.vq if not vq then @@ -52691,7 +51693,6 @@ end end return true end --- decode residue r for the channels `targets` (nil = do not decode) of length n2 each local function residue(st, br, r, targets, ch, n2) local books = st.setup.books local rtype = r.type @@ -52761,7 +51762,6 @@ local function residue(st, br, r, targets, ch, n2) classSet =classSet+ 1 end end - -- de-interleave into the channels that are decoded for j = 1, ch do local t = targets[j] if t then @@ -52815,8 +51815,6 @@ local v = j end end --- ------------------------------------------------------------------------------------------------ packet --- decode(st, buf, off, size) -> frames returned in st.out (0 for the first packet), -1 for a non-audio / bad packet function Packet.decode(st, b, off, size) if size < 1 then return -1 @@ -52858,7 +51856,6 @@ if size < 1 then local map = setup.mappings[mode.mapping + 1] local ch = st.channels local spec, zero, reallyZero = st.spec, st.zero, st.reallyZero - -- floors for c = 1, ch do local s = map.mux[c] + 1 local g = setup.floors[map.submapFloor[s] + 1] @@ -52873,7 +51870,6 @@ if size < 1 then zero[m], zero[a] = false, false end end - -- residues, per submap for i = 1, map.submaps do local targets= {} local k = 0 @@ -52885,7 +51881,6 @@ if size < 1 then end residue(st, br, setup.residues[map.submapResidue[i] + 1], targets, k, n2) end - -- inverse coupling 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 @@ -52907,7 +51902,6 @@ if size < 1 then m[j], a[j] = m2, a2 end end - -- floor curves, IMDCT, windows local plan = st.plans[n] local lslope = st.slopes[leftEnd - leftStart] local rslope = st.slopes[rightEnd - rightStart] @@ -52957,7 +51951,6 @@ end end end end end - -- the new tail: this frame from its centre to the end of its window local tl = rightEnd - n2 for c = 1, ch do local tail, fr = st.tail[c], st.frame[c] @@ -52975,11 +51968,9 @@ end __FILES["codecs/audio/Vorbis/Setup"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --!native --- codecs/audio/Vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2): identification (channels, rate, --- bitrates, blocksizes), comment (vendor + user comments -> tags) and setup (codebooks, floors, residues, mappings, --- modes). Ported from stb_vorbis 1.22 start_decoder (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). --- Floor 0 is rejected as unsupported, as stb_vorbis does (no encoder has produced it since 2000). --- Never throws: every parser returns nil, message on bad data. +-- 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 = {} @@ -53050,7 +52041,6 @@ return n >= 7 and readu8(b, o) == kind and buffer.readstring(b, o + 1, 6) == "vo end Setup.isVorbis = isVorbis --- ident(buf, offset, size) -> Ident | nil, message function Setup.ident(b, o, n) if not isVorbis(b, o, n, 1) then return nil, "not a Vorbis identification header" @@ -53086,7 +52076,6 @@ if not isVorbis(b, o, n, 1) then nil end --- comment(buf, offset, size) -> vendor, { "KEY=value" } | nil, message function Setup.comment(b, o, n) if not isVorbis(b, o, n, 3) then return nil, nil @@ -53123,14 +52112,12 @@ if not isVorbis(b, o, n, 3) then return vendor, list end --- setup(buf, offset, size, ident) -> Setup | nil, message function Setup.setup(b, o, n, id) if not isVorbis(b, o, n, 5) then return nil, "not a Vorbis setup header" end local br = Codebook.reader(b, o + 7, n - 7) local channels = id.channels - -- codebooks local books= {} local nbooks = bits(br, 8) + 1 for i = 1, nbooks do @@ -53147,7 +52134,6 @@ if not isVorbis(b, o, n, 5) then return nil, "bad time domain transform" end end - -- floors local floors= {} local maxValues = 0 local nfloors = bits(br, 6) + 1 @@ -53247,7 +52233,6 @@ return xlist[a + 1] < xlist[c + 1] maxValues = values end end - -- residues local residues= {} local nres = bits(br, 6) + 1 for i = 1, nres do @@ -53316,7 +52301,6 @@ return xlist[a + 1] < xlist[c + 1] classdata = classdata, } end - -- mappings local mappings= {} local nmaps = bits(br, 6) + 1 local chBits = ilog(channels - 1) @@ -53371,7 +52355,6 @@ return xlist[a + 1] < xlist[c + 1] submapResidue = sr, } end - -- modes local modes= {} local nmodes = bits(br, 6) + 1 for i = 1, nmodes do @@ -53405,8 +52388,8 @@ return Setup end __FILES["codecs/audio/Vorbis/Tables"] = function() --!strict --- codecs/audio/Vorbis/Tables: the floor 1 inverse dB table (Vorbis I specification, section 10.1, as in stb_vorbis 1.22, --- public domain / MIT, licenses/stb_vorbis-LICENSE.txt). 256 values, index = floor value (1-based here). +-- 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, @@ -53444,15 +52427,7 @@ return table.freeze({ end __FILES["codecs/audio/VorbisComment"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags. --- Tag keys are lower case everywhere in rosetta (the same names ID3 / MP4 / RIFF INFO map to): title, artist, --- album, albumartist, date, genre, track, tracktotal, disc, disctotal, comment, composer, ...; TRACKNUMBER becomes --- track, DISCNUMBER disc, DESCRIPTION comment, other fields their lower-cased name. Repeated fields are joined with --- "; " in tags; the raw fields stay available (decoders put them in meta.source.comments). Shared so the three --- formats read and write tags the same way. Never throws. --- --- local tags, raw = VorbisComment.tags({ "TITLE=x", "TRACKNUMBER=3" }) -- { title = "x", track = "3" }, raw list --- local fields = VorbisComment.fields(tags) -- sorted { "TITLE=x", "TRACKNUMBER=3" } +-- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value"; Vorbis, Opus, FLAC) <-> Types.Tags. local VorbisComment = {} @@ -53460,18 +52435,15 @@ local VorbisComment = {} local TO_TAG= { tracknumber = "track", discnumber = "disc", description = "comment" } local TO_FIELD= { track = "TRACKNUMBER", disc = "DISCNUMBER" } --- tagKey(fieldName) -> the Types.Tags key function VorbisComment.tagKey(name) local k = string.lower(name) return TO_TAG[k] or k end --- fieldName(tagKey) -> the Vorbis comment field name function VorbisComment.fieldName(key) return TO_FIELD[key] or string.upper(key) end --- tags(list of "KEY=value") -> Types.Tags, { Field } (entries without "=" are skipped) function VorbisComment.tags(comments) local tags= {} local raw= {} @@ -53488,7 +52460,6 @@ local tags= {} return tags, raw end --- fields(tags) -> "KEY=value" strings in key order (string keys and values only) function VorbisComment.fields(tags) local keys = {} for k, v in __iter(tags) do @@ -53508,20 +52479,9 @@ return VorbisComment end __FILES["codecs/audio/WavPack"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec --- (layer 3). Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt); the hot code is in --- codecs/audio/WavPack/Block. Lossless and hybrid (lossy, and lossless with the .wvc correction blocks), integer 8 - 32 --- bit (with the extended int32 modes) and 32-bit float, mono / stereo / multichannel (one block per mono or stereo --- stream, INITIAL .. FINAL), every decorrelation pass (terms 1 - 8, 17, 18, -1 .. -3), joint stereo, cross --- decorrelation, noise shaping, block CRCs and block checksums. Not supported: DSD, pre-4.0 streams (version < 0x402). --- --- local h, err = WavPack.header(buf, at, limit) -- the 32-byte block header at `at` (nil, message if none) --- local info, err = WavPack.info(buf, at, limit) -- stream facts from the first audio block (channels, rate, ...) --- local dec = WavPack.decoder(info.channels) --- local frames, err = dec:frame(buf, blocks, cbuf?, cblocks?) -- blocks = { offset, ... } of one frame (+ wvc) --- -- dec.pcm: interleaved samples (integers in the container range, or float values), WAV channel order --- --- Never throws: bad data returns nil, Err. +-- 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") @@ -53541,7 +52501,6 @@ local RATES = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 4410 WavPack.MONO, WavPack.HYBRID, WavPack.FLOAT, WavPack.INITIAL, WavPack.FINAL = 4, 8, 0x80, 0x800, 0x1000 WavPack.DSD = 0x80000000 --- header(buf, at, limit?) -> Header | nil, message: a valid "wvpk" block header at byte `at` whose block ends by limit function WavPack.header(buf, at, limit) local lim = math.min(limit or buffer.len(buf), buffer.len(buf)) if at < 0 or at + 32 > lim then @@ -53575,7 +52534,6 @@ local lim = math.min(limit or buffer.len(buf), buffer.len(buf)) return h, nil end --- info(buf, at, limit?) -> Info | nil, Err: the facts of the stream whose first audio block is at `at` @@ -53655,7 +52613,6 @@ local h, herr = WavPack.header(buf, at, limit) return info, nil end --- md5(buf, at, limit?) -> 32 hex digits | nil: an ID_MD5_CHECKSUM in the block at `at` function WavPack.md5(buf, at, limit) local h = WavPack.header(buf, at, limit) if not h then @@ -53675,9 +52632,6 @@ local h = WavPack.header(buf, at, limit) end return table.concat(hex) end --- ------------------------------------------------------------------------------------------------ decoder --- frame(buf, blocks, cbuf?, cblocks?) -> frames | nil, Err: decode one frame (the blocks of one sample range, one per --- mono / stereo stream, in channel order) into dec.pcm; cblocks are the matching .wvc blocks (hybrid lossless) @@ -53731,7 +52685,6 @@ local C = self.channels return n, nil end --- decoder(channels) -> Decoder function WavPack.decoder(channels) return { channels = channels, @@ -53750,13 +52703,9 @@ __FILES["codecs/audio/WavPack/Block"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/audio/WavPack/Block: one WavPack 4 / 5 block (one mono or stereo stream of a frame) -> samples. Ported from --- WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt): unpack.c (the decorrelation passes, joint --- stereo, the hybrid lossy and hybrid lossless (+ wvc) paths with noise shaping and cross decorrelation, fixup_samples), --- read_words.c (the median-adaptive entropy decoder: get_words_lossless, get_word, read_code), unpack_floats.c, --- decorr_utils.c / entropy_utils.c (the metadata) and open_utils.c (metadata parsing, the block checksum). The block --- CRC (and the wvx CRC) is checked. Not ported: DSD blocks (UNSUPPORTED), pre-4.0 streams, the lossy "mute" heuristics. --- Never throws: returns nil, message. +-- 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 @@ -53768,11 +52717,10 @@ local sign, clamp = math.sign, math.clamp local Block = {} local TWO32 = 4294967296 -local P2= table.create(34, 0) -- P2[k + 1] = 2^k +local P2= table.create(34, 0) for i = 0, 33 do P2[i + 1] = 2 ^ i end --- ONES[b + 1]: the number of trailing 1 bits of the byte b local ONES= table.create(256, 0) for b = 0, 255 do local n, v = 0, b @@ -53783,15 +52731,12 @@ for b = 0, 255 do ONES[b + 1] = n end --- header flags 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 -- per block +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 --- ------------------------------------------------------------------------------------------------ metadata --- meta(buf, p, size) -> Meta | nil, message: the metadata sub-blocks of the block at p (header included in size) @@ -53829,7 +52774,6 @@ local m= {} return m, nil end --- checksum(buf, p, size, m) -> true | false: the ID_BLOCK_CHECKSUM (when there is one) matches function Block.checksum(buf, p, m) local o = m[0x2F] if not o then @@ -53850,7 +52794,6 @@ local o = m[0x2F] csum = bit32.bxor(csum, rshift(csum, 16)) return readu16(buf, o) == band(csum, 0xFFFF) end --- ------------------------------------------------------------------------------------------------ state @@ -53879,7 +52822,6 @@ return { } end --- open a bitstream: the bytes [o, o + len) copied with PAD zero bytes after them local function openReader(R, buf, o, len) if buffer.len(R.b) < len + PAD then R.b = buffer.create(len + PAD + 1024) @@ -53892,8 +52834,6 @@ local function openReader(R, buf, o, len) R.n = len + PAD end --- ------------------------------------------------------------------------------------------------ bit reading --- bits(R, n) -> the next n (<= 32) bits, LSB first local function bits(R, n) if n <= 0 then return 0 @@ -53901,7 +52841,7 @@ if n <= 0 then local p = R.p local byte = rshift(p, 3) if byte + 8 > R.n then - R.p = R.e + 1 -- overrun: the caller's end check fails + R.p = R.e + 1 return 0 end local b = R.b @@ -53919,8 +52859,6 @@ local function bit(R) return bits(R, 1) end --- trailing(R, max) -> the number of 1 bits from the read position (up to max; a byte at a time), consumed with the 0 --- after them when fewer than max local function trailing(R, max) local c = 0 while c < max do @@ -53942,7 +52880,6 @@ local c = 0 c =c+ 8 R.p = p + 8 end - -- (max reached inside a run of 8: give back the extra ones) R.p =R.p- (c - max ) return max end @@ -53959,7 +52896,7 @@ local c = trailing(R, 33) return bits(R, c - 1) + P2[c] end --- readCode(R, maxcode) -> 0 .. maxcode (read_code) +-- read_code local function readCode(R, maxcode) if maxcode < 2 then return (maxcode == 1 and{(bits(R, 1) )}or{0 @@ -53989,16 +52926,13 @@ local c = trailing(R, 17) return c end --- ------------------------------------------------------------------------------------------------ lossless entropy --- wordsLossless(st, n, stereo) -> true | nil: n samples (n * 2 when stereo) into st.W from the data index (the hot --- loop of get_words_lossless, with the bit reader in locals) +-- get_words_lossless local function wordsLossless(st, count, d) local R= st.R1 local b, pos, lim = R.b, R.p, R.e local W = st.W local med = st.med local stereo = d == D2 - -- (a0, a1, a2): the current channel's medians, (c0, c1, c2) the other's; swapped every sample when stereo 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 @@ -54157,7 +53091,6 @@ __DARKLUA_CONTINUE_7=true break return pos <= lim end --- ------------------------------------------------------------------------------------------------ hybrid entropy local function updateErrorLimit(st, flags, mono) local bacc, bdelta, slow, limit = st.bacc, st.bdelta, st.slow, st.limit bacc[1] = (bacc[1] + bdelta[1]) % TWO32 @@ -54197,7 +53130,7 @@ local function updateErrorLimit(st, flags, mono) end end --- getWord(st, chan, flags, mono) -> value, correction | nil (get_word; chan 0 / 1) +-- get_word local function getWord(st, chan, flags, mono) local R= st.R1 local med = st.med @@ -54313,7 +53246,6 @@ do local __DARKLUA_VAR=chan + 1 s[__DARKLUA_VAR]=s[__DARKLUA_VAR]- math.floor return (sign == 1 and((-mid - 1 ))or(mid)), correction end --- ------------------------------------------------------------------------------------------------ decorrelation -- the decorrelation passes over the whole block (stereo, from W[D2]): unpack.c decorr_stereo_pass local function passesStereo(st, n) local W = st.W @@ -54428,7 +53360,6 @@ local function passesMono(st, n) end end --- ------------------------------------------------------------------------------------------------ hybrid lossless local function shaped(st, c, flags, correction) -- returns the value to subtract (temp) and updates the error state (noise shaping, unpack.c) local sacc, sdelta, err = st.sacc, st.sdelta, st.err @@ -54621,7 +53552,6 @@ local W = st.W return true end --- ------------------------------------------------------------------------------------------------ metadata -> state local function readMeta(st, buf, m, flags, version) local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 local o = m[2] @@ -54807,8 +53737,7 @@ local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 return nil end --- ------------------------------------------------------------------------------------------------ fixup + output --- the float conversion of one value (float_values; R = the wvx stream or nil) +-- float_values (R = the wvx stream or nil) local function floatValue(st, v, R) local fflags, exp = st.fflags, st.fmaxexp local mant, e, sign = 0, 0, 0 @@ -54909,7 +53838,7 @@ local fflags, exp = st.fflags, st.fmaxexp return readf32(sc, 0) end --- emit: fixup_samples + false stereo + interleave into P (stride C, first channel c0 0-based) +-- fixup_samples + false stereo + interleave local function emit(st, flags, n, d, P, c0, C, lossy) local W = st.W local s = d == D2 and 2 or 1 @@ -55012,7 +53941,6 @@ local function emit(st, flags, n, d, P, c0, C, lossy) end end end - -- interleave if s == 2 then if c0 == 0 and C == 2 then for k = 0, count - 1 do @@ -55045,9 +53973,6 @@ local function emit(st, flags, n, d, P, c0, C, lossy) end end --- ------------------------------------------------------------------------------------------------ decode --- decode(st, buf, p, size, P, c0, C, cbuf?, cp?, csize?) -> channels written (1 / 2) | nil, message: the block at p --- (header included in size) into P (interleaved, stride C, from channel c0), with its correction block if given function Block.decode(st, buf, p, size, P, c0, C, cbuf, cp, csize) local version = readu16(buf, p + 8) local n = readu32(buf, p + 20) @@ -55081,7 +54006,6 @@ local version = readu16(buf, p + 8) cm, cb, hasC = cmeta, cbuf, true crcWant = readu32(cbuf, cp + 28) end - -- reset st.nterms = 0 local sA, sB, wA, wB = st.sA, st.sB, st.wA, st.wB for k = 1, 128 do @@ -55117,7 +54041,6 @@ local version = readu16(buf, p + 8) if n == 0 then return out, nil end - -- bitstreams local o = m[0xA] if not o or m[0xA + 256] == 0 or m[0xA + 256] % 2 == 1 then return nil, "no audio bitstream" @@ -55235,13 +54158,12 @@ __FILES["codecs/audio/WavPack/Tables"] = function() local __compat = __compat local bit32 = __compat.bit32 --!strict --!native --!optimize 2 --- codecs/audio/WavPack/Tables: the WavPack log2 / exp2 tables and the conversions built on them (wp_log2, wp_exp2s, --- restore_weight). Ported from WavPack 5.9.0 entropy_utils.c (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). +-- 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 = {} --- LOG2[x + 1], EXP2[x + 1] for x = 0 .. 255 local LOG2= { 0, 1, 3, 4, 6, 7, 9, 10, 11, 13, 14, 16, 17, 18, 20, 21, 22, 24, 25, 26, 28, 29, 30, 32, 33, 34, 36, 37, 38, 40, 41, 42, 44, 45, 46, 47, 49, 50, 51, 52, 54, 55, 56, 57, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 77, 78, 79, 80, 81, @@ -55263,7 +54185,6 @@ local EXP2= { 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, } --- exp2s(log) -> the int32 the signed log stands for (wp_exp2s) function Tables.exp2s(lg) if lg < 0 then local v = Tables.exp2s(-lg) @@ -55276,7 +54197,6 @@ if lg < 0 then )})[1] return (r >= 2147483648 and((r - 4294967296 ))or(r ))end --- log2(v) -> wp_log2 of the uint32 v function Tables.log2(v) v = (v + rshift(v, 9)) % 4294967296 if v < 256 then @@ -55287,7 +54207,6 @@ v = (v + rshift(v, 9)) % 4294967296 return dbits * 256 + LOG2[band(rshift(v, dbits - 9), 255) + 1] end --- restoreWeight(signed byte) -> the decorrelation weight (restore_weight) function Tables.restoreWeight(w) local r = w * 8 if r > 0 then @@ -55300,18 +54219,9 @@ return Tables end __FILES["codecs/compress/Brotli"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written --- from the RFC (decoder in codecs/compress/Brotli/Decode); the static dictionary, context table and word transforms come from --- google/brotli (MIT, licenses/brotli-LICENSE.txt) through codecs/compress/Brotli/Static (tools/brotli_static.py). --- Supports every RFC 7932 stream (window sizes 10..24, metadata / uncompressed / compressed meta-blocks, the static --- dictionary with all 121 transforms) and the large-window extension (opts.largeWindow). Not supported: compression, --- shared / compound dictionaries (draft "shared brotli"). --- --- local Brotli = require("rosetta.codecs.compress.Brotli") --- local out, consumedEnd = Brotli.decompress(buf) -- buffer | string --- local out, err = Brotli.decompress(buf, offset, length, { maxBytes = 2^24 }) --- --- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / LIMIT / UNSUPPORTED / ARG). +-- 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") @@ -55322,7 +54232,6 @@ local StaticData = __include("codecs/compress/Brotli/Static") local Brotli = {} --- ------------------------------------------------------------------------------------------------ static data -- the tables are base64 text (trusted, generated by tools/brotli_static.py) @@ -55335,7 +54244,6 @@ end local static= nil --- tables() -> the decoded static data (inflated once, on first use) local function tables() if static then return static, nil @@ -55358,16 +54266,11 @@ if static then return static, nil end --- dictionary() -> the 122784-byte RFC 7932 static dictionary (for tests and encoders) function Brotli.dictionary() local s = tables() return (s and{s.dictionary }or{nil })[1]end --- ------------------------------------------------------------------------------------------------ decompress - --- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. consumedEnd: the input offset just past --- the stream (trailing bytes are ignored). function Brotli.decompress(buf, offset, length, opts) local b, o, l, aerr = Bytes.span("Brotli.decompress", buf, offset, length) if not b then @@ -55405,25 +54308,15 @@ __FILES["codecs/compress/Brotli/Decode"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/compress/Brotli/Decode: a Brotli (RFC 7932) decoder over a whole in-memory stream. Written from the RFC, with the --- reference decoder (google/brotli c/dec/decode.c, MIT) as the authority on edge cases (simple prefix code alphabet --- widths, repeat codes, padding checks, the large-window extension). Supports every meta-block kind (compressed, --- uncompressed, metadata), block types / counts, the four literal context modes, context maps with RLE and inverse --- move-to-front, NPOSTFIX / NDIRECT distances, the static dictionary with all 121 transforms, window sizes 10..24 and --- large windows (10..30). The whole output is kept, so the window is only used to tell copies from dictionary words. --- --- Bits are read LSB first into a bit buffer of up to 32 bits. Prefix codes decode through tables indexed by the next --- 8 bits; entries are symbol * 32 + length (length < 16), or a link offset * 32 + 16 + subtable bits. --- --- Nothing here throws: every buffer access is checked or in range by construction (the output buffer is sized for each --- meta-block before it is decoded); bad data returns nil, message. +-- 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 = {} --- ------------------------------------------------------------------------------------------------ constants @@ -55458,7 +54351,6 @@ end local NTRANSFORMS = 121 local MAX_ALLOWED_DISTANCE = 0x7FFFFFFC --- 8-bit reversal local REV8 = bcreate(256) for i = 0, 255 do local r, v = 0, i @@ -55468,20 +54360,16 @@ for i = 0, 255 do ) end writeu8(REV8, i, r) end -local function reverse(code, len) -- len <= 15 - +local function reverse(code, len) local r = readu8(REV8, band(code, 255)) * 256 + readu8(REV8, band(rshift(code, 8), 255)) return rshift(r, 16 - len) end --- ------------------------------------------------------------------------------------------------ prefix tables local count = table.create(16, 0) local nextc = table.create(16, 0) local subBits = table.create(256, 0) local subOff = table.create(256, 0) --- tableSize(lens, n) -> the entries build() will write (256 + subtables), or -1 for an over-subscribed set. --- Also leaves count / nextc / subBits ready for build(). local function prepare(lens, n) for l = 1, 16 do count[l] = 0 @@ -55539,7 +54427,6 @@ for l = 1, 16 do return size end --- build(lens, n, T, at): the table prepared by prepare() at entry offset `at` of T (T must have room) local function build(lens, n, T, at) local single = -1 local used = 0 @@ -55592,8 +54479,7 @@ local function build(lens, n, T, at) end end --- the largest distance alphabet whose distances stay under MAX_ALLOWED_DISTANCE (large windows); after the reference --- decoder's BrotliCalculateDistanceCodeLimit +-- largest distance alphabet under MAX_ALLOWED_DISTANCE, as the reference's BrotliCalculateDistanceCodeLimit local function distanceLimit(maxDistance, npostfix, ndirect) if maxDistance <= ndirect then return maxDistance + 16 @@ -55617,8 +54503,6 @@ if maxDistance <= ndirect then return bor(lshift(group, npostfix), postfix) + ndirect + 16 + 1 end --- ------------------------------------------------------------------------------------------------ decoder --- decompress(src, off, len, maxBytes, S, largeWindow) -> out, n, consumedEnd | nil, message function Decode.decompress(src, off, len, maxBytes, S, largeWindow) local lim = off + len local ip = off @@ -55655,7 +54539,6 @@ if n <= 24 then return (ip - lim) * 8 > bc end - -- prefix tables of the current meta-block: T (u32 entries), tpos entries used local T = bcreate(4096 * 4) local tpos = 0 local LENS = bcreate(1128) @@ -55677,7 +54560,6 @@ if bc < 15 then return rshift(e, 5) end - -- install(n) -> base: the table for LENS[0 .. n - 1] appended to T, or -1 local function install(n) local size = prepare(LENS, n) if size < 0 then @@ -55695,7 +54577,6 @@ local size = prepare(LENS, n) return base end - -- readCode(alphabetMax, limit) -> table base | -1 (corrupt) local function readCode(alphabetMax, limit) bfill(LENS, 0, 0, limit) local hskip = bits(2) @@ -55851,7 +54732,6 @@ local code = decodeSym(base) return BL_OFF[code + 1] + bits(BL_BITS[code + 1]) end - -- readContextMap(size) -> ntrees, map buffer | -1 local function readContextMap(size) local ntrees = varLen8() + 1 local map = bcreate(size) @@ -55879,7 +54759,7 @@ local ntrees = varLen8() + 1 if i + reps > size then return -1, map end - i =i+ reps -- zeros (map is zero-filled) + i =i+ reps end if overrun() then return -1, map @@ -55903,7 +54783,7 @@ local ntrees = varLen8() + 1 return ntrees, map end - -- ------------------------------------------------------------------ stream header + -- RFC 7932 9.1: stream header fill() local wbits local large = false @@ -55949,7 +54829,7 @@ local ntrees = varLen8() + 1 local d0, d1, d2, d3 = 4, 11, 15, 16 while true do -local __DARKLUA_CONTINUE_26=false repeat -- ---------------------------------------------------------------- meta-block header +local __DARKLUA_CONTINUE_26=false repeat -- RFC 7932 9.2: meta-block header if overrun() then return nil, "truncated stream" end @@ -56030,7 +54910,7 @@ __DARKLUA_CONTINUE_26=true break __DARKLUA_CONTINUE_26=true break end - -- ---------------------------------------------------------------- compressed meta-block + -- 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 @@ -56077,7 +54957,6 @@ __DARKLUA_CONTINUE_26=true break if ntreesD < 0 then return nil, "bad distance context map" end - -- the tree groups local litBase = table.create(ntreesL, 0) for i = 1, ntreesL do local b = readCode(256, 256) @@ -56107,7 +54986,6 @@ __DARKLUA_CONTINUE_26=true break if overrun() then return nil, "truncated meta-block header" end - -- context map slices resolved to table bases local litMap = table.create(64 * nbtL, 0) for i = 0, 64 * nbtL - 1 do litMap[i + 1] = litBase[readu8(cmapL, i) + 1] @@ -56117,7 +54995,6 @@ __DARKLUA_CONTINUE_26=true break distMap[i + 1] = distBase[readu8(cmapD, i) + 1] end - -- block state: current type, previous type local typeL, prevL = 0, 1 local typeI, prevI = 0, 1 local typeD, prevD = 0, 1 @@ -56131,7 +55008,6 @@ __DARKLUA_CONTINUE_26=true break if ip > lim + 4 then return nil, "truncated stream" end - -- command block switch if cntI == 0 then local t = decodeSym(btTreeI) if t == 1 then @@ -56163,7 +55039,6 @@ __DARKLUA_CONTINUE_26=true break if ce > 0 then cpyLen =cpyLen+ bits(ce) end - -- literals if insLen > remaining then return nil, "insert past the meta-block end" end @@ -56219,7 +55094,6 @@ __DARKLUA_CONTINUE_26=true break break end end - -- distance local dist local push = true if cell < 2 then @@ -57269,23 +56143,14 @@ return { end __FILES["codecs/compress/Bzip2"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec --- (layer 3): archive/bz2 and tar.bz2 build on it. Written from the format description (no third-party code). --- Supports: block sizes 1..9, every Huffman group layout, block and stream CRCs, concatenated streams (as bzip2 -d). --- Not supported: randomised blocks (bzip2 0.9.0 and older; Err.UNSUPPORTED), compression. --- --- local Bzip2 = require("rosetta.codecs.compress.Bzip2") --- local out, consumedEnd = Bzip2.decompress(buf) -- | nil, Err --- local out = Bzip2.decompress(buf, offset, length, { maxBytes = 2^24 }) --- --- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / LIMIT / ARG). +-- 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 = {} --- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err @@ -57311,7 +56176,6 @@ local b, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length) return res, consumed end --- crc(buf, offset?, length?) -> the CRC-32/BZIP2 of a range (the block CRC bzip2 stores) function Bzip2.crc(buf, offset, length) local CT = Decode.crcTable local o = offset or 0 @@ -57329,16 +56193,9 @@ __FILES["codecs/compress/Bzip2/Decode"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/compress/Bzip2/Decode: bzip2 stream decoder (Julian Seward's format, as documented by the bzip2 1.0.x sources and --- Joe Tsai's "bzip2 format specification"). Written from the format description; no third-party code. --- Per block: MSB-first bit reader on a local 32-bit bit buffer, Huffman groups (10-bit lookup + canonical fallback for --- codes up to 20 bits), MTF + RUNA/RUNB, inverse BWT through one u32 vector (byte in the low 8 bits, next index --- above), RLE1 undo with the block CRC (CRC-32/BZIP2, MSB first) computed on the way out; the combined stream CRC is --- checked at the end-of-stream marker. Concatenated streams are decoded one after the other. --- Not supported: randomised blocks (written only by bzip2 0.9.0 and older). --- --- Never throws: every buffer access is in range by construction; failures return nil, message, kind --- ("truncated" | "corrupt" | "checksum" | "limit" | "unsupported"). +-- 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 @@ -57355,25 +56212,23 @@ for i = 0, 32 do MASK[i + 1] = i == 32 and 0xFFFFFFFF or 2 ^ i - 1 end -local PBITS = 10 -- primary lookup width +local PBITS = 10 local PSIZE = 1024 local MAXGROUPS = 6 local MAXALPHA = 258 local MAXLEN = 20 --- scratch tables, reused across calls (single-threaded) -local LOOK = bcreate(MAXGROUPS * PSIZE * 4) -- per group: sym * 32 + len (len <= PBITS), 0 = longer code / none +local LOOK = bcreate(MAXGROUPS * PSIZE * 4) local LENS = bcreate(MAXGROUPS * MAXALPHA) -local PERM = table.create(MAXGROUPS * MAXALPHA, 0) -- per group: symbols in canonical order -local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- first code of each length +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) -- index into PERM of the first symbol of each length +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) --- build group g's tables from LENS[g*MAXALPHA .. + n): false when over-subscribed local function buildGroup(g, n) local lbase = g * MAXALPHA local cbase = g * (MAXLEN + 1) @@ -57402,7 +56257,6 @@ end if l > maxLen then end code =code* 2 end - -- perm + lookup local pbase = g * MAXALPHA local tbase = g * PSIZE * 4 bfill(LOOK, tbase, 0, PSIZE * 4) @@ -57434,11 +56288,10 @@ local nb = bcreate(math.max(blen(out) * 2, need, 65536)) return nb end --- decode(b, o, e, maxBytes) -> out, n, consumedEnd | nil, message, kind function Decode.decode(b, o, e, maxBytes) local out = bcreate(math.min(math.max(65536, (e - o) * 4), maxBytes + 1)) local op = 0 - local p = o -- next input byte (may run past e: zeros are fed, and the overrun is detected) + local p = o local bb, bc = 0, 0 local tt= nil local ttSize = 0 @@ -57705,7 +56558,6 @@ p =p+ 4 bc =bc- band(ent, 31) sym = rshift(ent, 5) else - -- a code longer than PBITS: canonical search local v = band(rshift(bb, bc - gmax), MASK[gmax + 1]) sym = -1 for l = PBITS + 1, gmax do @@ -57770,7 +56622,6 @@ end writeu32(T, nblock * 4, ch) return nil, "bad BWT origin pointer", "corrupt" end - -- inverse BWT: T[pos] |= i << 8 at each byte's sorted position local sum = 0 for i = 0, 255 do local c = CFTAB[i + 1] @@ -57784,7 +56635,6 @@ end writeu32(T, nblock * 4, ch) writeu32(T, k * 4, bor(readu32(T, k * 4), lshift(i, 8))) end - -- walk, undo RLE1, CRC if op + nblock + 4096 > blen(out) then out = grow(out, op, op + nblock + 4096) end @@ -57857,21 +56707,8 @@ return Decode end __FILES["codecs/compress/Deflate"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. --- A codec (layer 1), not a format: png, zip, gzip, woff, tiff, ... build on it. Absorbed from deflate-luau 1.0.0 --- (same author; no third-party code); the compressor is new. --- --- local Deflate = require("rosetta.codecs.compress.Deflate") --- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err --- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known --- local out, err = Deflate.inflate(buf, off, len, size, dict) -- with a preset dictionary --- local out, err = Deflate.mszip(buf, { { offset, length, size }, ... }) -- MSZIP blocks ("CK" + deflate, chained) --- local out, err = Deflate.zlib(buf) -- checks the Adler-32 --- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members --- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip --- local head = Deflate.peek(buf, nil, nil, 512) -- the first 512 inflated bytes of gzip / zlib / raw --- --- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG). +-- 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") @@ -57900,11 +56737,6 @@ local code = (string.find(msg, "truncated", 1, true) and{Err.TRUNCATED }or{Err.C })[1] return Err.new(code, "inflate: " .. msg, at) end --- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate. --- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream --- that inflates to a different size is an error. consumedEnd is the input offset just past the final block. --- dict: a preset dictionary (up to 32 KB of data before the stream, as MSZIP's previous block): back references may --- reach into it; the result holds only the new bytes. function Deflate.inflate(buf, offset, length, expectedSize, dict) local b, o, l, aerr = args("Deflate.inflate", buf, offset, length) if not b then @@ -57940,7 +56772,6 @@ local b, o, l, aerr = args("Deflate.inflate", buf, offset, length) return shrink(out, n), consumed end --- zlib(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err function Deflate.zlib(buf, offset, length, expectedSize) local b, o, l, aerr = args("Deflate.zlib", buf, offset, length) if not b then @@ -57974,7 +56805,6 @@ local b, o, l, aerr = args("Deflate.zlib", buf, offset, length) return out, consumed + 4 end --- gzipBody(b, p, e) -> the offset of a gzip member's deflate data (past FEXTRA / FNAME / FCOMMENT / FHCRC) | nil, Err local function gzipBody(b, p, e) local flg = buffer.readu8(b, p + 3) if flg >= 0x20 then @@ -58004,8 +56834,6 @@ local flg = buffer.readu8(b, p + 3) return q, nil end --- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is --- not another gzip member (zero padding, garbage) is ignored, as gzip -d does. function Deflate.gunzip(buf, offset, length) local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length) if not b then @@ -58052,7 +56880,6 @@ local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length) table.insert(parts, out) total =total+ buffer.len(out) p = consumed + 8 - -- skip zero padding local z = p while z < e and buffer.readu8(b, z) == 0 do z =z+ 1 @@ -58073,9 +56900,6 @@ local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length) return res, nil end --- peek(buf, offset?, length?, n) -> buffer | nil, Err: the first n bytes (fewer when the stream is shorter, or up to --- 258 fewer at a match boundary) a gzip member, zlib stream or raw deflate stream inflates to, without inflating --- the rest or checking checksums: for sniffing compressed files cheaply. function Deflate.peek(buf, offset, length, n) local b, o, l, aerr = args("Deflate.peek", buf, offset, length) if not b then @@ -58117,7 +56941,6 @@ local lv = (opts and opts.level ~= nil and{opts.level }or{6 return lv end --- compress(buf, opts?) -> raw deflate buffer | nil, Err function Deflate.compress(buf, opts) local b = toBuffer(buf) local lv = level(opts) @@ -58127,7 +56950,6 @@ local b = toBuffer(buf) return Compress.raw(b, 0, buffer.len(b), lv), nil end --- zlibCompress(buf, opts?) -> zlib stream | nil, Err function Deflate.zlibCompress(buf, opts) local b = toBuffer(buf) local lv = level(opts) @@ -58148,7 +56970,6 @@ local b = toBuffer(buf) return out, nil end --- gzip(buf, opts?) -> gzip member (no name, mtime 0) | nil, Err function Deflate.gzip(buf, opts) local b = toBuffer(buf) local lv = level(opts) @@ -58167,10 +56988,8 @@ local b = toBuffer(buf) return out, nil end --- mszip(buf, blocks) -> buffer | nil, Err: MSZIP data (Microsoft's blocked deflate, as in CAB folders and DirectX .x --- files): blocks = { { offset, length, size } }, each buf[offset, offset + length) = "CK" + a raw deflate stream that --- inflates to exactly size bytes using the previous block's output (up to 32 KB) as its dictionary. Returns the --- blocks' output concatenated. +-- MSZIP (CAB folders, DirectX .x): each block is "CK" + a raw deflate stream using the previous block's output (up to +-- 32 KB) as its dictionary. function Deflate.mszip(buf, blocks) local total = 0 for _, b in __iter(blocks) do @@ -58201,7 +57020,6 @@ local total = 0 return out, nil end --- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of) Deflate.crc32 = function(buf, offset, length, crc) local b = toBuffer(buf) or buffer.create(0) return Crc32.of(b, offset, length, crc) @@ -58217,11 +57035,8 @@ __FILES["codecs/compress/Deflate/Compress"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 --- codecs/compress/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth --- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (codecs/entropy/Huffman --- length-limited codes). Level 0 = stored blocks only. --- --- raw(buf, off, len, level) -> buffer. Never throws (the caller validated the arguments). +-- 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 @@ -58231,11 +57046,10 @@ local floor = math.floor local WSIZE = 32768 local HSIZE = 65536 local MAXMATCH = 258 -local BLOCKSYMS = 16384 -- symbols per block +local BLOCKSYMS = 16384 --- per level (zlib's configuration_table): GOOD = a match this long 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 (no lazy matching). +-- 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 } @@ -58282,14 +57096,12 @@ end local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } --- fixed codes local FIXLEN = table.create(288, 0) for i = 1, 288 do FIXLEN[i] = i <= 144 and 8 or(i <= 256 and 9 or(i <= 280 and 7 or 8 ))end local FIXDLEN = table.create(30, 5) --- reversed (LSB-first) canonical codes for lengths local function revCodes(lens) local codes = Huffman.codes(lens) for i, l in __iter(lens) do @@ -58306,7 +57118,6 @@ local POW = table.create(33, 0) for i = 0, 32 do POW[i + 1] = 2 ^ i end --- ------------------------------------------------------------------------------------------------ bit output @@ -58318,7 +57129,6 @@ local function ensure(o, n) end end --- put(v, n): n <= 24 bits, LSB first local function put(o, v, n) local acc = o.acc + v * POW[o.cnt + 1] local cnt = o.cnt + n @@ -58343,8 +57153,6 @@ local function alignOut(o) end end --- ------------------------------------------------------------------------------------------------ blocks --- syms: L[i] = literal 0..255 or 256 + match length; D[i] = distance (0 for literals) local function storedBlock(o, src, s, e, final) local p = s repeat @@ -58425,7 +57233,7 @@ end extra =extra+ DEXT[dc + 1] for i = 1, hdist do all[hlit + i] = dlen[i] end - local cs, cx = {}, {} -- symbol, extra value + local cs, cx = {}, {} local cf = table.create(19, 0) local i = 1 local total = hlit + hdist @@ -58468,7 +57276,6 @@ end i =i+ 1 while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do hclen =hclen- 1 end - -- costs in bits local dyn = 17 + 3 * hclen + extra for k = 1, 19 do dyn =dyn+ cf[k] * clen[k] @@ -58515,7 +57322,6 @@ end i =i+ 1 emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen) end --- ------------------------------------------------------------------------------------------------ LZ77 local Compress = {} function Compress.raw(src, off, len, level) @@ -58552,7 +57358,6 @@ return ((readu8(src, p) * 251 + readu8(src, p + 1)) * 251 + readu8(src, p + 2)) prev[p % WSIZE + 1] = head[h] head[h] = p end - -- longest match at p among earlier positions: len (0 if < 3), dist local function find(p, steps) local maxLen = math.min(MAXMATCH, e - p) if maxLen < 3 then @@ -58576,7 +57381,7 @@ local maxLen = math.min(MAXMATCH, e - p) end local nc = prev[c % WSIZE + 1] if nc >= c then - break -- the slot was reused by a newer position: the chain ends here + break end c = nc steps =steps- 1 @@ -58593,7 +57398,7 @@ local maxLen = math.min(MAXMATCH, e - p) end local p = off - local stop3 = e - 3 -- positions with 3 bytes ahead can be hashed + local stop3 = e - 3 while p < e do local mlen, mdist = 0, 0 if p <= stop3 then @@ -58602,7 +57407,6 @@ local maxLen = math.min(MAXMATCH, e - p) if mlen >= 3 and mlen < lazyMax and p + 1 <= stop3 then local l2, d2 = find(p + 1, (mlen >= good and{(math.floor(maxChain / 4 ))}or{maxChain})[1]) if l2 > mlen then - -- a literal now, the longer match from p + 1 nsym =nsym+ 1 L[nsym] = readu8(src, p) D[nsym] = 0 @@ -58652,15 +57456,7 @@ local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!native --!optimize 2 -- codecs/compress/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks. --- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to codecs/entropy/Huffman, whose --- entries are symbol * 32 + length (5 length bits instead of 4). --- --- Bits are read LSB first into a 32-bit bit buffer (refilled 4 bytes at a time with one readu32 while the input --- lasts). Huffman codes decode through a codecs/entropy/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer --- code's primary slot links to a subtable, so a symbol is one or two table reads. --- --- Nothing in this module throws on any input: every buffer read and write is bounds-checked, and corrupt data --- returns nil, message. (Native code must never throw: it crashes Roblox Studio.) +-- 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 @@ -58670,7 +57466,7 @@ local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buf local LITBITS, DISTBITS, CLBITS = 10, 8, 7 local LITMASK, DISTMASK, CLMASK = 1023, 255, 127 --- length codes 257..285 and distance codes 0..29: base value, extra bits +-- 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 = { @@ -58678,15 +57474,13 @@ local DBASE = { 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 } --- the order code-length code lengths are sent in +-- 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 } --- table capacities (entries): primary + one subtable per code longer than the primary width, worst case local LITCAP = Huffman.capacity(288, LITBITS, 15) local DISTCAP = Huffman.capacity(32, DISTBITS, 15) local CLCAP = Huffman.capacity(19, CLBITS, 7) --- fixed Huffman tables local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) local FLITS, FDISTS do @@ -58703,7 +57497,6 @@ end local Inflate = {} --- Grow out (capacity cap) to hold at least need bytes. Returns the new buffer and capacity. local function grow(out, op, need) local cap = math.max(blen(out) * 2, need, 1024) local nb = bcreate(cap) @@ -58711,12 +57504,6 @@ local cap = math.max(blen(out) * 2, need, 1024) return nb, cap end --- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in --- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and --- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing). --- dict: a preset dictionary (the data before the stream, e.g. MSZIP's previous block): out starts with a copy of it, --- distances may reach into it, and outLen includes it (cap does not). --- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message. function Inflate.raw(src, start, endpos, cap, exact, prefix, dict) local op = 0 if dict then @@ -58917,7 +57704,6 @@ end end local lsmask = lshift(1, lsub) - 1 local dsmask = lshift(1, dsub) - 1 - -- the symbol loop while true do if bitcnt < 15 then if pos + 4 <= endpos then @@ -58974,7 +57760,6 @@ end if sym > 29 then return nil, "invalid literal/length code" end - -- up to 5 length extra bits + a 15-bit distance code if bitcnt < 20 then if pos + 4 <= endpos then bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) @@ -59064,8 +57849,7 @@ end local s = op - dist if dist >= len then if len <= 16 and op + 16 <= cap then - -- straight-line 16-byte copy (the bytes past len are rewritten later): no inner loop, which - -- keeps LuaJIT's traces simple; chunks read only bytes before op or already copied ones + -- 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)) @@ -59082,7 +57866,6 @@ end bfill(out, op, readu8(out, s), len) op =op+ len else - -- overlapping: the pattern of period dist, copied in growing non-overlapping chunks local rem = len while rem > 0 do local k = math.min(op - s, rem) @@ -59107,17 +57890,9 @@ __FILES["codecs/compress/Explode"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --!native --!optimize 2 --- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ --- archive sectors, old installers, some game data files). A codec (layer 3). Written after the format as documented --- by Mark Adler's blast.c (zlib licence, licenses/blast-LICENSE.txt): the same constant code tables (run-length --- coded Huffman code lengths, length bases / extra bits), the bit order (LSB first, Huffman codes inverted); the --- decoder itself is new code. --- Supports: literal coding off (raw bytes) and on (Huffman coded), 1 / 2 / 4 KB dictionaries, the end code; stops --- early at maxOut bytes (MPQ sectors whose stream has no end code). --- --- local out, err = Explode.decompress(buf, offset?, length?, maxOut?) -- buffer | nil, Err --- --- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / ARG / LIMIT). +-- 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") @@ -59137,7 +57912,6 @@ 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 } --- canonical code from run-length coded lengths local function construct(rep) @@ -59170,7 +57944,6 @@ local LIT = construct(LITLEN) local LEN = construct(LENLEN) local DIST = construct(DISTLEN) --- decompress(buf, offset?, length?, maxOut?) -> buffer | nil, Err function Explode.decompress(buf, offset, length, maxOut) local b, o, l, aerr = Bytes.span("Explode.decompress", buf, offset, length) if not b then @@ -59313,19 +58086,7 @@ __FILES["codecs/compress/Lz4"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --!native --!optimize 2 --- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder --- (the reference "fast" strategy: one 4-byte hash table, 64 KB window). A codec (layer 3): model/rbxm chunk bodies, --- and the LZ4 frame format (archive) builds on it. New code, written from the specification. Never throws. --- --- local out, err = Lz4.decompress(src, offset?, length?, outSize?, opts?) -- a block -> buffer | nil, Err --- local packed = Lz4.compress(src, offset?, length?) -- -> buffer (a block) | nil, Err --- local dEnd, msg = Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart?) -- low level (linked blocks) --- local n = Lz4.encodeInto(src, p, n, dst, d) -- low level; dst has bound(n) room --- Lz4.bound(n) -- worst-case block size for n bytes --- --- decodeInto decodes one block from src[p, limit) to dst[d, dstLimit): matches may reach back to histStart (default --- d), so a frame decoder with linked blocks keeps the previous output in front of d. It returns the output end, or --- nil and a message ("truncated", "corrupt: ...", "limit: output ...") for the caller's Err.from. +-- 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") @@ -59346,7 +58107,6 @@ local MAX_OFFSET = 65535 local HASH_BITS = 13 local HASH_SIZE = 2 ^ HASH_BITS --- ------------------------------------------------------------------------------------------------ decode function Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart) local lo = histStart or d if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then @@ -59419,7 +58179,6 @@ local lo = histStart or d buffer.fill(dst, d, readu8(dst, s), ml) d =d+ ml else - -- an overlapping match repeats the off-byte pattern: copy what is already there, doubling each time local n = ml while n > 0 do local c = d - s @@ -59434,8 +58193,6 @@ local lo = histStart or d end end --- decompress(src, offset?, length?, outSize?, opts?) -> buffer | nil, Err: one block. With outSize the output must be --- exactly that long (CORRUPT otherwise); without it the output grows up to opts.maxBytes. function Lz4.decompress(src, offset, length, outSize, opts) local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length) if not b then @@ -59475,13 +58232,10 @@ local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length) end end --- ------------------------------------------------------------------------------------------------ encode --- bound(n) -> the largest block n input bytes can produce function Lz4.bound(n) return n + math.floor(n / 255 )+ 16 end --- writes a length's 255-run extension at o; returns the next offset local function extend(dst, o, n) while n >= 255 do writeu8(dst, o, 255) @@ -59492,7 +58246,7 @@ while n >= 255 do return o + 1 end --- hash(v) -> 1 .. HASH_SIZE: Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles +-- Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles local function hash(v) local vl, vh = band(v, 0xFFFF), rshift(v, 16) local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536 @@ -59501,7 +58255,6 @@ end local hashTable= table.create(HASH_SIZE, -1e9) --- encodeInto(src, p, n, dst, d) -> the block's length: src[p, p + n) compressed to dst[d ..] (room for bound(n)) function Lz4.encodeInto(src, p, n, dst, d) local op = d local anchor = p @@ -59521,7 +58274,6 @@ local op = d local ref = ht[h] ht[h] = ip if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then - -- back over equal bytes before the match (into the pending literals) while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do ip =ip- 1 ref =ref- 1 @@ -59559,7 +58311,6 @@ local op = d ip = a anchor = ip skip = 64 - -- index the position just before the next one (better ratio at no cost) if ip - 2 >= p and ip - 2 < mflimit then local w = readu32(src, ip - 2) ht[hash(w)] = ip - 2 @@ -59570,7 +58321,6 @@ local op = d end end end - -- the last literals local lit = iend - anchor local tok = op op =op+ 1 @@ -59587,7 +58337,6 @@ local op = d return op - d end --- compress(src, offset?, length?) -> buffer (one block) | nil, Err function Lz4.compress(src, offset, length) local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length) if not b then @@ -59606,23 +58355,9 @@ __FILES["codecs/compress/Lzh"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo: --- lh4 / lh5 / lh6 / lh7 / lhx static Huffman blocks (code-length "temp" table, 510 literal / length codes, offset --- bit-length codes); also ARJ methods 1..3 (= "lh6") and Zoo method 2 (= "lh5") --- lh1 adaptive Huffman (LHarc 1.x: 314 codes, grouped frequency tree) with fixed-length --- offset prefixes, 4 KB window --- lzs / lz5 LArc's plain LZSS (2 KB / 4 KB windows, flag bits / flag bytes) --- arj4 ARJ method 4 (unary-prefixed lengths and offsets, no Huffman) --- Every method decodes into a buffer of the known output size; the windows start filled as the original tools fill --- them (spaces; lz5's pattern), and offsets before the start of the output read that fill. --- Ported from lhasa 0.6.0 (Simon Howard, ISC licence: licenses/lhasa-LICENSE.txt): lh_new_decoder.c, lh1_decoder.c, --- lzs_decoder.c, lz5_decoder.c; the static Huffman tables are canonical codes built with codecs/entropy/Huffman instead --- of lhasa's trees. ARJ method 4 is written from the ARJ technical notes (unarj's decode_f description). --- --- local out, err = Lzh.decode(src, off, len, outSize, "lh5") -- buffer | nil, message --- --- Never throws: bad codes / truncated input return nil, message (truncated input: "truncated ..." after the bytes --- decoded so far would be useless, so nothing partial is returned). Not supported: pm0 / pm1 / pm2 (PMarc), lk7. +-- 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 = {} @@ -59630,9 +58365,6 @@ 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 --- ------------------------------------------------------------------------------------------------ bit reader --- an MSB-first bit reader over src[pos, limit): acc holds cnt bits (cnt <= 32); past the end, zero bits are read and --- over counts them @@ -59677,7 +58409,6 @@ if n == 0 then skip(r, n) return v end --- ------------------------------------------------------------------------------------------------ static Huffman @@ -59750,7 +58481,7 @@ local n = bits(r, nbits) writeu8(lens, i, l) if i == special then local z = bits(r, 2) - i =i+ z -- zeros (already zero) + i =i+ z end i =i+ 1 end @@ -59840,7 +58571,6 @@ local r = reader(src, off, len) return nil end --- ------------------------------------------------------------------------------------------------ lh1 local NUM_CODES = 314 local NUM_NODES = NUM_CODES * 2 - 1 local REORDER = 32 * 1024 @@ -59866,7 +58596,6 @@ end local function decodeLh1(src, off, len, out, n) local r = reader(src, off, len) - -- node arrays (0-based indexes stored at [i + 1]) local leaf = table.create(NUM_NODES, false) local child = table.create(NUM_NODES, 0) local parent = table.create(NUM_NODES, 0) @@ -60006,7 +58735,7 @@ end if freq[ni + 1] == freq[ni] then end end local code = child[ni + 1] - -- increment_for_code + -- lhasa's increment_for_code if freq[1] >= REORDER then reconstruct() end @@ -60043,8 +58772,7 @@ end if freq[ni + 1] == freq[ni] then return nil end --- ------------------------------------------------------------------------------------------------ LArc lzs / lz5 --- the ring of a 2 KB / 4 KB window (positions are absolute ring positions, not distances) +-- LArc lzs / lz5: a 2 KB / 4 KB ring (absolute ring positions, not distances) local function decodeLzs(src, off, len, out, n) local r = reader(src, off, len) local ring = buffer.create(2048) @@ -60154,7 +58882,6 @@ local ring = buffer.create(4096) return nil end --- ------------------------------------------------------------------------------------------------ ARJ method 4 local function decodeArj4(src, off, len, out, n) local r = reader(src, off, len) local function prefixed(start, stop) @@ -60196,10 +58923,8 @@ local plus, pwr = 0, lshift(1, start) return nil end --- ------------------------------------------------------------------------------------------------ api Lzh.METHODS = { "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "arj4" } --- decode(src, off, len, outSize, method) -> buffer | nil, message function Lzh.decode(src, off, len, outSize, method) if off < 0 or len < 0 or off > buffer.len(src) or outSize < 0 or outSize ~= outSize then return nil, "bad arguments" @@ -60232,23 +58957,9 @@ return Lzh end __FILES["codecs/compress/Lzma"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): --- archive/xz, archive/7z (and anything else holding LZMA data) build on it. Decode only. --- Written from the LZMA specification (LzmaSpec.cpp, Igor Pavlov, public domain) and the xz file format specification --- 1.2 (Lasse Collin / Igor Pavlov, public domain); the BCJ filters follow xz-embedded (public domain). --- --- local Lzma = require("rosetta.codecs.compress.Lzma") --- local out, e = Lzma.lzma(buf, off, len, props, unpackSize?, opts?) -- raw LZMA; props = 5-byte buffer / string --- -- or { lc, lp, pb, dictSize } --- local out, e = Lzma.lzma2(buf, off, len, dictSize?, unpackSize?, opts?) -- raw LZMA2 chunks --- local out, e = Lzma.alone(buf, off?, len?, opts?) -- a .lzma file (13-byte header) --- local out, e = Lzma.xz(buf, off?, len?, opts?) -- a .xz file (all streams concatenated) --- Lzma.filter(id, buf, off, len, props?) -- BCJ / delta decode in place (7z) --- --- Each returns buffer, consumedEnd (the input offset just past what was decoded) | nil, Err. opts.maxBytes (default --- 2^30) bounds the output (Err.LIMIT). xz: every stream, block, index and footer is parsed and checked; check types --- none / CRC-32 / CRC-64 are verified, SHA-256 is skipped (not verified). xz filters: LZMA2, delta, x86, PowerPC, --- ARM, ARM-Thumb, SPARC, ARM64; IA-64 and RISC-V are Err.UNSUPPORTED. Never throws. +-- 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") @@ -60275,7 +58986,6 @@ local m = opts and opts.maxBytes return (type(m) == "number" and m >= 0 and{m }or{DEFAULT_MAX })[1]end --- a decoder message -> Err local function fail(msg, at) local s = tostring(msg) local code = Err.CORRUPT @@ -60287,7 +58997,6 @@ local s = tostring(msg) return Err.new(code, s, at) end --- props byte -> lc, lp, pb | nil local function propsByte(d) if d >= 225 then return nil, 0, 0 @@ -60296,8 +59005,6 @@ if d >= 225 then )end Lzma.propsByte = propsByte --- ------------------------------------------------------------------------------------------------ LZMA --- decodeLzma(st, b, o, e, unpackSize?) -> consumedEnd | nil, Err: one raw LZMA stream into st (props set) local function decodeLzma(st, b, o, e, unpackSize) local ip, ierr = Decode.rcInit(st, b, o, e) if not ip then @@ -60320,7 +59027,6 @@ local ip, ierr = Decode.rcInit(st, b, o, e) return res , nil end --- lzma(buf, offset, length, props, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err function Lzma.lzma(buf, offset, length, props, unpackSize, opts) local b, o, l, aerr = args("Lzma.lzma", buf, offset, length) if not b then @@ -60358,7 +59064,7 @@ local b, o, l, aerr = args("Lzma.lzma", buf, offset, length) return Decode.finish(st), consumed end --- alone(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: a .lzma file (props, dict size, u64 size) +-- .lzma file: props byte, dict size, u64 unpacked size function Lzma.alone(buf, offset, length, opts) local b, o, l, aerr = args("Lzma.alone", buf, offset, length) if not b then @@ -60378,8 +59084,6 @@ local b, o, l, aerr = args("Lzma.alone", buf, offset, length) return Lzma.lzma(b, o + 13, l - 13, buffer.fromstring(buffer.readstring(b, o, 1)), size, opts) end --- ------------------------------------------------------------------------------------------------ LZMA2 --- decodeLzma2(st, b, o, e) -> consumedEnd | nil, Err: LZMA2 chunks up to the end-of-stream byte local function decodeLzma2(st, b, o, e) local p = o local needDict, needProps = true, true @@ -60467,7 +59171,6 @@ local p = o end end --- lzma2(buf, offset?, length?, dictSize?, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err function Lzma.lzma2(buf, offset, length, _dictSize, unpackSize, opts) local b, o, l, aerr = args("Lzma.lzma2", buf, offset, length) if not b then @@ -60485,7 +59188,6 @@ local b, o, l, aerr = args("Lzma.lzma2", buf, offset, length) return Decode.finish(st), consumed end --- ------------------------------------------------------------------------------------------------ filters -- filter ids (xz numbering; 7z's method ids map onto these in archive/7z) Lzma.FILTER = table.freeze({ delta = 0x03, @@ -60508,8 +59210,7 @@ local BCJ= { [0x0A] = Filters.arm64, } --- filter(id, buf, offset, length, props?) -> true | nil, Err: decode a BCJ / delta filter in place. props: the --- filter's property bytes (a string or buffer: BCJ start offset u32le, delta distance - 1) +-- filter properties: BCJ start offset u32le, delta distance - 1 function Lzma.filter(id, b, o, n, props) local pb = toBuffer(props) local plen = (pb and{(buffer.len(pb) )}or{0 @@ -60534,11 +59235,9 @@ local pb = toBuffer(props) return true, nil end --- ------------------------------------------------------------------------------------------------ xz 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 } --- vli(b, p, e) -> value, next | nil local function vli(b, p, e) local v, mul = 0, 1 for i = 0, 8 do @@ -60563,7 +59262,6 @@ local function crc(b, o, n) return Crc32.raw(b, o, n) end --- one xz stream at o -> next offset | nil, Err (blocks appended to st) local function xzStream(st, b, o, e) if o + 12 > e then return nil, Err.new(Err.TRUNCATED, "truncated xz stream header", o) @@ -60754,7 +59452,6 @@ if o + 12 > e then return q + 12, nil end --- xz(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: every stream (and stream padding) in the range function Lzma.xz(buf, offset, length, opts) local b, o, l, aerr = args("Lzma.xz", buf, offset, length) if not b then @@ -60791,7 +59488,6 @@ local b, o, l, aerr = args("Lzma.xz", buf, offset, length) return Decode.finish(st), p end --- isXz(buf, offset?) -> true when the bytes start an xz stream function Lzma.isXz(b, o) local off = o or 0 return off + 6 <= buffer.len(b) and buffer.readstring(b, off, 6) == XZ_MAGIC @@ -60803,8 +59499,8 @@ __FILES["codecs/compress/Lzma/Crc64"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/compress/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit --- value is kept as two u32 halves (hi, lo). Written from the xz file format specification. Never throws. +-- 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 @@ -60825,7 +59521,6 @@ end local Crc64 = {} --- of(buf, offset, length) -> hi, lo function Crc64.of(b, o, n) local hi, lo = 0xFFFFFFFF, 0xFFFFFFFF for i = o, o + n - 1 do @@ -60842,17 +59537,9 @@ __FILES["codecs/compress/Lzma/Decode"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/compress/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z). --- Written from the LZMA specification and its reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain); the --- structure (probability model layout, state transitions, distance / length decoding) follows that document. --- --- The output buffer is also the dictionary: everything decoded stays in memory, so a match may reach back to the last --- dictionary reset (st.dictStart). A decoder state (new) carries the probabilities, the LZ state, the four rep --- distances, a pending match remainder (st.remLen) and the range coder across calls, so LZMA2 can feed it chunk by --- chunk. run() decodes until st.op reaches outEnd, an end marker, or an error. --- --- Never throws: every input read is bounds-checked (a read past the end counts in `over` and fails the call as --- "truncated"), every output write is preceded by a capacity check, and errors return nil, message. +-- 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 @@ -60875,7 +59562,6 @@ local TOP = 16777216 -- 2^24 local Decode = {} --- new(cap, maxBytes) -> a decoder state with an empty output buffer of capacity cap @@ -60921,7 +59607,6 @@ local c = math.max(64, math.min(cap, maxBytes)) } end --- setProps(st, lc, lp, pb) -> ok, message?: new literal / position parameters (resets the probabilities) function Decode.setProps(st, lc, lp, pb) if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then return false, "bad lc / lp / pb" @@ -60936,7 +59621,6 @@ if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then return true, nil end --- resetState(st): probabilities to 1/2, LZ state and reps to 0 function Decode.resetState(st) local p = st.probs for i = 0, st.nprobs - 1 do @@ -60947,13 +59631,11 @@ function Decode.resetState(st) st.remLen = 0 end --- resetDict(st): matches may no longer reach before the current position function Decode.resetDict(st) st.dictStart = st.op st.remLen = 0 end --- rcInit(st, buf, ip, iend) -> next ip | nil, message: the 5 range coder init bytes function Decode.rcInit(st, b, ip, iend) if ip + 5 > iend then return nil, "truncated range coder init" @@ -60969,7 +59651,6 @@ if ip + 5 > iend then return ip + 5, nil end --- ensure(st, need) -> ok: grow the output to hold need bytes (bounded by maxBytes) local function ensure(st, need) if need <= st.cap then return true @@ -60986,7 +59667,6 @@ if need <= st.cap then end Decode.ensure = ensure --- copy(st, n, b, ip): append n stored bytes (LZMA2 uncompressed chunks); the caller checked the input range function Decode.copy(st, n, b, ip) if not ensure(st, st.op + n) then return false, "limit: output over maxBytes" @@ -60996,14 +59676,12 @@ if not ensure(st, st.op + n) then return true, nil end --- the range decoder state while run() executes (module upvalues: the helpers below are created once, so LuaJIT --- traces stay valid across calls; run() is not re-entrant, and never yields) +-- module upvalues, so LuaJIT traces stay valid across calls (run() is not re-entrant) local EMPTY = bcreate(2) local probs= EMPTY local inb= EMPTY local range, code, ip, iend, over = 0, 0, 0, 0, 0 --- decode one bit with the probability at index i local function bit(i) local p = i * 2 local prob = readu16(probs, p) @@ -61085,8 +59763,6 @@ if bit(base) == 0 then return 16 + tree(base + 258, 8) end --- run(st, buf, ip, iend, outEnd) -> status, ip | nil, message. status: "full" (st.op reached outEnd) or "eos" (end --- marker). The range coder must have been initialised (rcInit). function Decode.run(st, inb0, ip0, iend0, outEnd) probs = st.probs inb = inb0 @@ -61109,7 +59785,6 @@ probs = st.probs local status= nil local msg= nil - -- a pending match from the previous call local remLen = st.remLen if remLen > 0 then local n = math.min(remLen, outEnd - op) @@ -61310,7 +59985,7 @@ __DARKLUA_CONTINUE_6=true until true if not __DARKLUA_CONTINUE_6 then break end st.state = state st.rep0, st.rep1, st.rep2, st.rep3 = rep0, rep1, rep2, rep3 st.remLen = remLen - probs, inb = EMPTY, EMPTY -- do not keep the caller's buffers alive + probs, inb = EMPTY, EMPTY if msg then return nil, msg end @@ -61320,7 +59995,6 @@ __DARKLUA_CONTINUE_6=true until true if not __DARKLUA_CONTINUE_6 then break end return status, ip end --- finish(st) -> a buffer of exactly the decoded bytes function Decode.finish(st) if st.cap == st.op then return st.out @@ -61336,10 +60010,8 @@ __FILES["codecs/compress/Lzma/Filters"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/compress/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole --- decoded buffer range. Written from the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin, --- public domain): x86, ARM, ARM-Thumb, PowerPC, SPARC, ARM64 and delta. Not supported: IA-64, RISC-V. --- Never throws: every access is inside [o, o + n). +-- 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 @@ -61354,7 +60026,6 @@ local function msbyte(b) return b == 0 or b == 0xFF end --- x86(b, o, n, start): BCJ x86 decode; start = the stream position of b[o] (the filter's start offset) function Filters.x86(b, o, n, start) if n <= 4 then return @@ -61502,7 +60173,7 @@ function Filters.arm64(b, o, n, start) end end --- delta(b, o, n, dist): b[i] += b[i - dist] (1 <= dist <= 256) +-- delta filter: b[i] += b[i - dist] (1 <= dist <= 256) function Filters.delta(b, o, n, dist) for i = dist, n - 1 do writeu8(b, o + i, band(readu8(b, o + i) + readu8(b, o + i - dist), 255)) @@ -61515,25 +60186,9 @@ __FILES["codecs/compress/Lzw"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and --- image/tiff build on it. New code (no port), written from the GIF89a spec (appendix F) and TIFF 6.0 section 13. --- gif LSB-first codes, a minimum code size 1..11 (2..8 in GIF), clear = 2^min, EOI = clear + 1, the code width --- grows when the next free code reaches 2^width (max 12 bits; a full table stays frozen until a clear). --- tiff MSB-first codes, 8-bit symbols, clear = 256, EOI = 257, "early change": the width grows one code --- earlier (next free code = 2^width - 1). Old-style (pre-6.0, LSB-first, no early change) TIFF LZW is --- detected by its first bytes (0x00 then an odd byte) and decoded too. --- zoo the gif layout with 8-bit symbols and codes up to 13 bits (Zoo archives' method 1; decode only). --- --- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "gif", minCodeSize) -- bytes written --- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "tiff") --- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "zoo") --- local codes = Lzw.encode(data, off, len, "gif", minCodeSize) -- buffer --- local codes = Lzw.encode(data, off, len, "tiff") --- --- decode writes at most maxOut bytes at out[outOff ..] and returns how many it wrote; it stops at EOI, at the end of --- the input or when out is full. err is nil for a clean stream, "truncated" when the input ended without EOI, or --- "corrupt" for an impossible code (everything decoded up to it is kept). Never throws; the caller checks that --- [outOff, outOff + maxOut) lies inside out and [off, off + len) inside src (decode clamps both anyway). +-- 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 @@ -61543,14 +60198,11 @@ local Lzw = {} local MAX_CODES = 4096 -- 12-bit codes (GIF, TIFF) local TABLE = 8192 -- the tables hold 13-bit codes (Zoo) --- per-call tables (allocated once: decode / encode are not re-entrant across coroutines, but never yield) -local prefix = buffer.create(TABLE * 2) -- u16: the code this entry extends -local suffix = buffer.create(TABLE) -- u8: its last byte -local first = buffer.create(TABLE) -- u8: its first byte -local length = buffer.create(TABLE * 2) -- u16: its length +local prefix = buffer.create(TABLE * 2) +local suffix = buffer.create(TABLE) +local first = buffer.create(TABLE) +local length = buffer.create(TABLE * 2) --- ------------------------------------------------------------------------------------------------ decode --- writes the string of code c (length l) ending at out[o + l - 1]; clipped to [o, lim) local function emit(out, o, c, l, lim) local p = o + l - 1 if p < lim then @@ -61581,7 +60233,7 @@ local n = blen(src) return 0, "corrupt" end local msb = variant == "tiff" - local early = 0 -- 1 for TIFF's early change + local early = 0 local min = minCodeSize or 8 local maxCodes, maxBits = MAX_CODES, 12 if variant == "zoo" then @@ -61615,7 +60267,6 @@ local n = blen(src) local p = off local acc, nb = 0, 0 while true do - -- refill (at most 13 + 7 bits held: below 2^21) while nb < size do if p >= e then return o - outOff, "truncated" @@ -61647,7 +60298,7 @@ local n = blen(src) return o - outOff, nil else if o >= lim then - return o - outOff, nil -- full: the rest (normally just EOI) is ignored + return o - outOff, nil end if prev < 0 then if c >= clear then @@ -61692,13 +60343,10 @@ local n = blen(src) end end --- ------------------------------------------------------------------------------------------------ encode -local HASH = 8192 -- open addressing over (prefix << 8 | byte) keys: a power of two above 4096 entries -local hkey = buffer.create(HASH * 4) -- i32 key + 1 (0 = empty) -local hval = buffer.create(HASH * 2) -- u16 code +local HASH = 8192 +local hkey = buffer.create(HASH * 4) +local hval = buffer.create(HASH * 2) --- encode(data, off, len, variant, minCodeSize?) -> the code stream (GIF: without the sub-block framing). Symbols in --- data must be below 2^minCodeSize (GIF; larger ones are masked) or bytes (TIFF). function Lzw.encode(data, off, len, variant, minCodeSize) local msb = variant == "tiff" local min = msb and 8 or math.clamp(minCodeSize or 8, 1, 11) @@ -61806,19 +60454,9 @@ __FILES["codecs/compress/Lzx"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes, --- verbatim, aligned offset and uncompressed blocks (block sizes of 24 bits, blocks spanning frames), the main and --- length trees sent as deltas of the previous block's code lengths through a 20-symbol pre-tree (runs 17 / 18 / 19), --- the three repeated offsets R0..R2, the Intel E8 call translation header (applied to the first 32768 frames, on the --- output only), and the stream cut into frames of 32768 output bytes, each 16-bit aligned at its end; trees, offsets --- and the window persist across the frames (the CFDATA blocks) of a folder. Written from the specification --- (Microsoft's LZX data format documentation in the Cabinet SDK and the LZX sections of [MS-PATCH]); no code from --- libmspack. Not supported: LZX DELTA reference data and reset intervals (CHM / WIM variants). --- --- local out, err = Lzx.decode(src, offset, length, outSize, windowBits) -- buffer | nil, message --- --- src[offset, offset + length) is the folder's compressed data (the CFDATA payloads concatenated), outSize its exact --- uncompressed size. Never throws: bad or truncated data returns nil, message. +-- 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 @@ -61847,9 +60485,7 @@ do end end local SLOTS= { [15] = 30, [16] = 32, [17] = 34, [18] = 36, [19] = 38, [20] = 42, [21] = 50 } --- ------------------------------------------------------------------------------------------------ bit reader --- 16-bit little-endian words read most significant bit first; bb holds cnt bits left aligned (cnt <= 32). Past the --- end, zero words are read and over counts their bits. +-- 16-bit little-endian words, read most significant bit first @@ -61872,7 +60508,6 @@ local function refill(s) end end --- bits(s, n) -> the next n (1..17) bits local function bits(s, n) if s.cnt < n then refill(s) @@ -61883,7 +60518,6 @@ if s.cnt < n then return v end --- sym(s, tab, P, S) -> the next symbol of an MSB Huffman table, -1 for an invalid code local function sym(s, tab, P, S) if s.cnt < 16 then refill(s) @@ -61905,7 +60539,7 @@ if s.cnt < 16 then return rshift(e, 5) end --- readLens: the code lengths lens[first, last) as deltas of their previous values, through a fresh pre-tree +-- code lengths as deltas of their previous values, through a fresh 20-symbol pre-tree (runs 17 / 18 / 19) local function readLens(s, lens, first, last, pre, preLens) for i = 0, 19 do writeu8(preLens, i, bits(s, 4)) @@ -61950,8 +60584,7 @@ for i = 0, 19 do return true end --- ------------------------------------------------------------------------------------------------ decode --- E8 translation of the decoded output, frame by frame (absolute call targets back to relative) +-- E8 translation, frame by frame: absolute call targets back to relative local function translate(out, n, size) local base = 0 local frame = 0 @@ -62004,7 +60637,6 @@ local nslots = SLOTS[windowBits] local frameEnd = math.min(op + FRAME, outSize) while op < frameEnd do if bremain == 0 then - -- a new block if btype == 3 and band(bsize, 1) == 1 then s.pos =s.pos+ 1 end @@ -62088,7 +60720,6 @@ local nslots = SLOTS[windowBits] local aligned = btype == 2 local start = op while op < runEnd do - -- refill to at least 17 bits while cnt <= 16 do local w = 0 if pos + 2 <= stop then @@ -62257,18 +60888,12 @@ __FILES["codecs/compress/PackBits"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF --- ByteRun1, ...): a header byte n < 128 copies n + 1 literal bytes, n > 128 repeats the next byte 257 - n times, --- 128 is a no-op. Decode and encode; moved here from image/tiff (TIFF and PSD both carried a decoder). Never throws. --- --- local written, srcEnd, clean = PackBits.decode(src, p, limit, dst, d, n) -- up to n bytes into dst at d --- local packed = PackBits.encode(src, offset, length) -- a buffer (one row at a time) +-- 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 --- decode(src, p, limit, dst, d, n) -> bytes written (<= n), the source offset after the codes used, clean (false when --- the source ran out before n bytes or a run overflowed n: lenient callers keep what was written, strict ones fail) function PackBits.decode(src, p, limit, dst, d, n) local o, lim = d, d + n local clean = true @@ -62312,7 +60937,6 @@ local o, lim = d, d + n return o - d, p, clean end --- encode(src, offset, length) -> buffer: runs of 3+ equal bytes as repeats, the rest as literals (at most 128 each) function PackBits.encode(src, off, len) local out = buffer.create(len + math.floor((len + 127) / 128 )+ 8) local o = 0 @@ -62354,20 +60978,9 @@ __FILES["codecs/compress/Quantum"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --!native --!optimize 2 --- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft --- Cabinet folders use it: windows of 2^10 .. 2^21 bytes; a 16-bit arithmetic decoder (H / L / C registers with --- underflow handling) over a most-significant-bit-first byte stream; eight adaptive frequency models (the --- 7-symbol selector, four 64-symbol literal models, the offset models for matches of 3, 4 and 5..259 bytes and the --- 27-symbol length model) whose cumulative frequencies grow by 8 per symbol and are rescaled above 3800 (halved, and --- every 50th time rebuilt from the frequencies and re-sorted); position and length footers read as raw bits from the --- same stream. Each CFDATA block is one frame (at most 32768 output bytes) that restarts the arithmetic coder; the --- models and the window persist across the frames of a folder. Written from the public descriptions of the format --- (the Quantum notes by Matthew Russotto and the cabinet documentation); no code from libmspack. --- --- local out, err = Quantum.decode(src, blocks, outSize, windowBits) -- buffer | nil, message --- --- blocks = { { at, len, size } }: each block's compressed bytes src[at, at + len) and its output size; outSize is --- their total. Never throws: bad or truncated data returns nil, message. +-- 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 @@ -62397,8 +61010,7 @@ do b =b+ lshift(1, LEXTRA[i]) end end --- ------------------------------------------------------------------------------------------------ models --- an adaptive model: symbols sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0) +-- model: sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0) @@ -62444,8 +61056,6 @@ local function rescale(m) cum[i]=cum[i]+ cum[i + 1] end end --- ------------------------------------------------------------------------------------------------ decode --- the coder and bit reader of one frame @@ -62465,7 +61075,6 @@ if c.cnt == 0 then return band(rshift(c.acc, c.cnt), 1) end --- raw(c, n) -> the next n (0..19) bits, most significant first local function raw(c, n) local v = 0 for _ = 1, n do @@ -62480,7 +61089,6 @@ local cum = m.cum local range = H - L + 1 local total = cum[1] if range <= 0 or C < L or C > H then - -- only corrupt registers get here (the decoder keeps L <= C <= H) c.bad = true return 0 end @@ -62607,17 +61215,9 @@ __FILES["codecs/compress/UnixCompress"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --!native --!optimize 2 --- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code --- width 9..16 and the block mode bit), decode and encode. A codec (layer 3): archive/z builds on it. Codes are --- LSB-first, 9 bits wide at the start; the width grows when the next free code passes 2^width - 1 (up to the --- maximum), and in block mode code 256 clears the table. compress writes codes in groups of eight: when the width --- changes or a CLEAR is read, the rest of the current group (counted from the previous change) is skipped. The encoder --- reproduces ncompress 5.0 bit for bit: greedy longest match, a full table frozen until the compression ratio checked --- every 10000 input bytes drops, then a CLEAR. Written from the ncompress sources (public domain, The Unlicense: read --- for the format and the encoder's ratio check; licenses/ncompress-UNLICENSE.txt). Never throws. --- --- local out, err = UnixCompress.decompress(buf, offset?, length?, { maxBytes = 2^28 }) -- a whole .Z file --- local z = UnixCompress.compress(buf, offset?, length?, { maxBits = 16 }) -- -> a .Z file +-- 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") @@ -62633,14 +61233,11 @@ local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local MAXCODES = 65536 local CHECK_GAP = 10000 --- decoder tables (per call state lives in locals; the tables are reused: decode never yields) -local prefix = bcreate(MAXCODES * 4) -- u32: the code an entry extends -local suffix = bcreate(MAXCODES) -- u8: its last byte -local first = bcreate(MAXCODES) -- u8: its first byte -local length = bcreate(MAXCODES * 4) -- u32: its length +local prefix = bcreate(MAXCODES * 4) +local suffix = bcreate(MAXCODES) +local first = bcreate(MAXCODES) +local length = bcreate(MAXCODES * 4) --- ------------------------------------------------------------------------------------------------ decode --- decompress(buf, offset?, length?, opts?) -> buffer | nil, Err function UnixCompress.decompress(buf, offset, len, opts) local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len) if not b then @@ -62674,8 +61271,8 @@ local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len) local op = 0 local totalBits = (n - 3) * 8 local base = o + 3 - local pos = 0 -- bit position from the first code - local gbase = 0 -- where the current group sequence starts + local pos = 0 + local gbase = 0 local nbits = 9 local mask = 511 local maxcode = 511 @@ -62691,7 +61288,6 @@ local __DARKLUA_CONTINUE_2=false repeat if freeEnt > maxcode then )})[1] mask = lshift(1, nbits) - 1 __DARKLUA_CONTINUE_2=true break end - -- the code: up to 23 bits from three bytes local q = base + rshift(pos, 3) local acc = readu8(b, q) if q + 1 < o + n then @@ -62763,12 +61359,10 @@ __DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end return res, nil end --- ------------------------------------------------------------------------------------------------ encode -local HSIZE = 1 * 131072 -- open addressing over (prefix << 8 | byte) + 1 keys: twice the 65536 entries +local HSIZE = 1 * 131072 local hkey = bcreate(HSIZE * 4) local hval = bcreate(HSIZE * 4) --- compress(buf, offset?, length?, opts?) -> a .Z file (block mode) | nil, Err function UnixCompress.compress(buf, offset, len, opts) local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len) if not b then @@ -62778,7 +61372,6 @@ local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len) 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 - -- at most 17 bits per input byte, plus group padding (< one group per width change / clear) local cap = 3 + n * 2 + 64 local out = bcreate(cap) writeu8(out, 0, 0x1F) @@ -62786,7 +61379,7 @@ local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len) writeu8(out, 2, bor(maxbits, 0x80)) local outbits = 24 local boff = 24 - local acc, nb = 0, 0 -- pending bits not yet written (below 2^24) + local acc, nb = 0, 0 local nbits = 9 local extcode = 513 local maxmax = lshift(1, maxbits) @@ -62896,7 +61489,6 @@ local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len) checks(i - o) end if rshift(outbits, 3) + 8 > cap then - -- grow (rare: only incompressible input passes 2 bytes per byte) local ncap = cap * 2 local nbuf = bcreate(ncap) bcopy(nbuf, 0, out, 0, cap) @@ -62916,7 +61508,6 @@ local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len) return res, nil end --- isCompress(buf, offset?) -> true when the bytes at offset start a .Z file function UnixCompress.isCompress(b, o) local p = o or 0 return p + 3 <= blen(b) and readu8(b, p) == 0x1F and readu8(b, p + 1) == 0x9D @@ -62928,11 +61519,8 @@ __FILES["codecs/compress/Xxh32"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content --- checksums. 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double. --- From the xxHash specification (Yann Collet, BSD-2); no code copied. Never throws (the range is clamped to the buffer). --- --- local h = Xxh32.hash(buf, offset?, length?, seed?) -- a number in 0 .. 2^32 - 1 +-- 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 @@ -62941,7 +61529,6 @@ local readu8, readu32 = buffer.readu8, buffer.readu32 local T32 = 4294967296 local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1 --- a * b mod 2^32 (a, b below 2^32) local function mul(a, b) local a0 = a % 65536 local a1 = (a - a0) / 65536 @@ -62956,7 +61543,6 @@ local function round(acc, lane) return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1) end --- hash(buf, offset?, length?, seed?) -> XXH32 function Xxh32.hash(b, offset, length, seed) local n0 = buffer.len(b) local o = math.clamp(offset or 0, 0, n0) @@ -63000,17 +61586,7 @@ return Xxh32 end __FILES["codecs/compress/Zstd"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict --- codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd --- data build on it. Written from the specification. Supports every frame feature a dictionary-less stream uses: --- concatenated and skippable frames, raw / RLE / compressed blocks, Huffman literals (1 / 4 streams, repeated tables), --- predefined / RLE / compressed / repeated FSE tables, repeat offsets, the XXH64 content checksum (verified). --- Not supported: dictionaries (Err.UNSUPPORTED), compression. --- --- local Zstd = require("rosetta.codecs.compress.Zstd") --- local out, err = Zstd.decompress(buf) -- -> buffer, consumedEnd | nil, Err --- local out, err = Zstd.decompress(buf, off, len, { maxBytes = 2^24, verify = false }) --- --- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / UNSUPPORTED / LIMIT / ARG). +-- 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") @@ -63025,7 +61601,6 @@ local Zstd = {} Zstd.MAGIC = "\40\181\47\253" --- isFrame(buf, offset?) -> true when a zstd (or skippable) frame starts there function Zstd.isFrame(buf, offset) local o = offset or 0 if type(buf) ~= "buffer" or o < 0 or o + 4 > buffer.len(buf) then @@ -63035,8 +61610,7 @@ local o = offset or 0 return m == 0xFD2FB528 or bit32.band(m, 0xFFFFFFF0) == 0x184D2A50 end --- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. Every frame in the range is decoded --- and the outputs concatenated; data after the last frame that is not a frame is an error (as zstd -d does). +-- data after the last frame that is not a frame is an error, as zstd -d does function Zstd.decompress(buf, offset, length, opts) local b, o, l, aerr = Bytes.span("Zstd.decompress", buf, offset, length) if not b then @@ -63059,7 +61633,6 @@ local b, o, l, aerr = Bytes.span("Zstd.decompress", buf, offset, length) return out, consumed end --- xxh64(buf, offset?, length?) -> hi, lo: the XXH64 hash (seed 0) as two unsigned 32-bit halves function Zstd.xxh64(buf, offset, length) local o = math.clamp(offset or 0, 0, buffer.len(buf)) local l = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o) @@ -63072,16 +61645,8 @@ __FILES["codecs/compress/Zstd/Decode"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/compress/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the --- BSD reference implementation). Frames (any number, concatenated), skippable frames, raw / RLE / compressed blocks, --- Huffman literals (1 or 4 streams, new or repeated table), FSE sequence tables (predefined / RLE / compressed / --- repeat), repeat offsets, the XXH64 content checksum. Not supported: dictionaries (a non-zero dictionary ID). --- --- The whole output lives in one buffer, so the window is the output itself (offsets are checked against the frame's --- start). Backward bitstreams are read through bit offsets: bits [o - n, o) of a stream come from one readu32 at --- byte (o - n) / 8, bits before the stream start read as zeros. --- --- Nothing here throws on any input: every read is bounds-checked; failures return nil, code, message, offset. +-- 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 @@ -63093,7 +61658,6 @@ local BLOCK_MAX = 131072 local Decode = {} --- ------------------------------------------------------------------------------------------------ tables -- 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 } @@ -63112,7 +61676,6 @@ local ML_DEFAULT = { } 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 } --- highest set bit of 1..2048 local HB = table.create(2048, 0) do local v = 0 @@ -63124,8 +61687,6 @@ do end end --- ------------------------------------------------------------------------------------------------ bit readers --- backward stream starting at byte s: bits [o - n, o) (n <= 25), bits below 0 are zeros local function peek(b, s, o, n) if n <= 0 then return 0 @@ -63153,7 +61714,6 @@ if n <= 0 then return lshift(peek(b, s, o, o), -lo) end --- the bit length of a backward stream [s, e) (up to its end marker), or -1 when the last byte is 0 / it is empty local function streamBits(b, s, e) if e <= s then return -1 @@ -63165,7 +61725,6 @@ if e <= s then return (e - 1 - s) * 8 + HB[last] end --- forward stream: n (<= 24) bits at bit position bp from byte p; bytes at or past e read as zeros local function getF(b, p, e, bp, n) local byte = p + rshift(bp, 3) local v = 0 @@ -63179,11 +61738,10 @@ local byte = p + rshift(bp, 3) return band(rshift(v, band(bp, 7)), lshift(1, n) - 1) end --- ------------------------------------------------------------------------------------------------ FSE -- FSE decoding table entries (u32): symbol | nbBits << 8 | newStateBase << 16 local symTmp = bcreate(512) --- build(norm, nsym, al, t) -> true | nil, message. norm: { [symbol + 1] = normalized count (-1 = "less than 1") } +-- normalized counts: { [symbol + 1] = count }, -1 = "less than 1" probability local function buildFse(norm, nsym, al, t) local size = lshift(1, al) local high = size - 1 @@ -63237,7 +61795,6 @@ local size = lshift(1, al) return true, nil end --- ncount(b, p, e, maxSym, maxAL, norm) -> al, bytesUsed, nsym | nil, message: an FSE table description local function ncount(b, p, e, maxSym, maxAL, norm) if p >= e then return nil, "truncated FSE table" @@ -63322,8 +61879,7 @@ local t = bcreate(lshift(1, al) * 4) end local LL_PRE, ML_PRE, OF_PRE = predefined(LL_DEFAULT, 6), predefined(ML_DEFAULT, 6), predefined(OF_DEFAULT, 5) --- ------------------------------------------------------------------------------------------------ Huffman --- hufTable(b, p, e, st) -> bytesUsed | nil, message: a Huffman tree description into st.huf (u16: sym | nbBits << 8) +-- Huffman table entry (u16): sym | nbBits << 8 local weights = bcreate(256) local wfse = bcreate(64 * 4) local function hufTable(b, p, e, st) @@ -63451,7 +62007,6 @@ end end return used, nil end --- one Huffman stream [s, e) -> cnt literals at lit[dp] | nil, message local function hufStream(b, s, e, t, mb, lit, dp, cnt) local off = streamBits(b, s, e) if off < 0 then @@ -63482,8 +62037,6 @@ local off = streamBits(b, s, e) return nil end --- ------------------------------------------------------------------------------------------------ frames --- grow st.out to hold need bytes (doubling, capped at st.maxBytes): true | false (over the limit) local function grow(st, need) if need > st.maxBytes then return false @@ -63495,7 +62048,6 @@ if need > st.maxBytes then return true end --- a compressed block [p, e): nil (ok) | code, message local function block(b, p, e, st) -- literals section local b0 = readu8(b, p) @@ -63830,7 +62382,6 @@ local s = p bfill(out, op, readu8(out, from), ml) op =op+ ml else - -- overlapping: copy in chunks of `offset` bytes (each chunk's source precedes its destination) local left = ml while left > 0 do local n = (left < offset and{left }or{offset @@ -63861,7 +62412,6 @@ local s = p return nil, nil end --- decompress(b, start, stop, maxBytes, verify) -> out, length, consumedEnd | nil, code, message, offset function Decode.decompress(b, start, stop, maxBytes, verify) local st= { out = bcreate(math.min(maxBytes, math.max(4096, (stop - start) * 3))), @@ -63974,7 +62524,6 @@ __DARKLUA_CONTINUE_25=true break st.rep1, st.rep2, st.rep3 = 1, 4, 8 st.hufBits = nil table.clear(st.tabs) - -- blocks local last = false repeat if pos + 3 > stop then @@ -64054,10 +62603,8 @@ __FILES["codecs/compress/Zstd/Xxh64"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/compress/Zstd/Xxh64: XXH64 (seed 0) of a buffer range, computed on 32-bit halves held in doubles (Luau and LuaJIT have --- no 64-bit integers). 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is --- exact below 2^53. From the xxHash specification (Yann Collet, BSD-2); no code copied. zstd stores the low 32 bits --- of the hash as the frame content checksum. Never throws (the caller passes an in-range buffer slice). +-- 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 @@ -64069,7 +62616,6 @@ local P3H, P3L = 0x165667B1, 0x9E3779F9 local P4H, P4L = 0x85EBCA77, 0xC2B2AE63 local P5H, P5L = 0x27D4EB2F, 0x165667C5 --- (ah, al) * (bh, bl) mod 2^64 local function mul(ah, al, bh, bl) local a0 = al % 65536 local a1 = (al - a0) / 65536 @@ -64094,7 +62640,6 @@ local l = al + bl return h % T32, l end --- rotl by r in 1..31 local function rotl(h, l, r) return bor(lshift(h, r), rshift(l, 32 - r)), bor(lshift(l, r), rshift(h, 32 - r)) end @@ -64102,7 +62647,7 @@ end local P1L0, P1L1 = P1L % 65536, math.floor(P1L / 65536 )local P2L0, P2L1 = P2L % 65536, math.floor(P2L / 65536 ) --- acc = rotl(acc + input * P2, 31) * P1, with both products written out (the hot path: 4 per 32 input bytes) +-- round: acc = rotl(acc + input * P2, 31) * P1 local function round(ah, al, ih, il) local a0 = il % 65536 local a1 = (il - a0) / 65536 @@ -64140,7 +62685,6 @@ end local Xxh64 = {} --- hash(b, offset, length) -> hi, lo (the 64-bit hash as two unsigned 32-bit halves) function Xxh64.hash(b, offset, length) local p = offset local e = offset + length @@ -64210,19 +62754,11 @@ end __FILES["codecs/entropy/Huffman"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. --- --- Decoding tables (built by buildLsb / buildMsb) are u32 buffers, indexed by the next P bits of the stream: --- entry = symbol * 32 + length a code of `length` <= P bits --- entry = offset * 32 (length 0) a link: index offset + the following S bits (subtable of 2^S entries) --- entry = 0 no code (incomplete code set): the stream is corrupt --- so a symbol is one or two table reads. LSB tables (DEFLATE, VP8L) are indexed by bit-reversed codes, MSB tables --- (JPEG, MPEG) by the code itself. Code lengths are 1..MAXLEN (16), symbols < 2^27. --- The hot loops (codecs/compress/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a --- core/Bits reader. --- --- Encoding: lengths(freqs, maxLen) -> length-limited code lengths; codes(lengths) -> canonical code values. --- Never throws: bad code sets return -1 / nil. +-- 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 @@ -64234,7 +62770,6 @@ local MAXLEN = 16 local Huffman = {} Huffman.MAXLEN = MAXLEN --- 8-bit reversal local REV = table.create(256, 0) for i = 0, 255 do local r, v = 0, i @@ -64245,13 +62780,11 @@ for i = 0, 255 do REV[i + 1] = r end --- reverse(code, len) -> the low len bits of code reversed (len <= 16) local function reverse(code, len) return rshift(bor(lshift(REV[band(code, 255) + 1], 8), REV[band(rshift(code, 8), 255) + 1]), 16 - len) end Huffman.reverse = reverse --- capacity(nsym, P, maxLen) -> the table entries (u32) needed for nsym symbols, primary width P, codes up to maxLen function Huffman.capacity(nsym, P, maxLen) return 2 ^ P + ((maxLen > P and((nsym * 2 ^ (maxLen - P) ))or(0))) end @@ -64300,7 +62833,6 @@ end end local entry = s * 32 + l if l <= P then if msb then - -- the code is the top l bits of the P-bit index: fill every completion of the low bits local first = lshift(c, P - l) local last = first + lshift(1, P - l) - 1 for i = first, last do @@ -64334,7 +62866,7 @@ end end else sub = rshift(e, 5) end - local k = l - P -- bits of the code in the subtable index + local k = l - P if msb then local first = lshift(rest, S - k) for i = first, first + lshift(1, S - k) - 1 do @@ -64354,19 +62886,14 @@ end end return S end --- buildLsb(lens, off, n, tab, P) -> S: a table for the code lengths lens[off .. off + n - 1] (u8), indexed by the next --- P bits LSB-first (bit-reversed codes). S = the subtable width (0 when no code is longer than P), -1 = an --- over-subscribed or invalid code set. tab must hold capacity(n, P, maxLen) u32 entries. function Huffman.buildLsb(lens, off, n, tab, P) return build(lens, off, n, tab, P, false) end --- buildMsb(lens, off, n, tab, P) -> S: the same, indexed by the next P bits MSB-first function Huffman.buildMsb(lens, off, n, tab, P) return build(lens, off, n, tab, P, true) end --- decodeLsb(br, tab, P, S) -> symbol, or -1 for an invalid code (br: a core/Bits LSB reader) function Huffman.decodeLsb(br, tab, P, S) local e = readu32(tab, br:peek(P) * 4) local l = band(e, 31) @@ -64385,7 +62912,6 @@ local e = readu32(tab, br:peek(P) * 4) return rshift(e, 5) end --- decodeMsb(br, tab, P, S) -> symbol, or -1 (br: a core/Bits MSB reader) function Huffman.decodeMsb(br, tab, P, S) local e = readu32(tab, br:peek(P) * 4) local l = band(e, 31) @@ -64404,8 +62930,6 @@ local e = readu32(tab, br:peek(P) * 4) return rshift(e, 5) end --- codes(lengths) -> canonical code values (MSB-first, as written by an MSB writer; reverse() them for LSB streams). --- lengths: { number } indexed 1..n (symbol + 1), 0 = unused. function Huffman.codes(lengths) local cnt = table.create(MAXLEN + 1, 0) for _, l in __iter(lengths) do @@ -64429,12 +62953,9 @@ end end return out end --- lengths(freqs, maxLen) -> code lengths ({ number }, same indexing as freqs), at most maxLen bits, optimal without --- the limit; over the limit, the JPEG Annex K.3 adjustment. A single used symbol gets length 1. function Huffman.lengths(freqs, maxLen) local n = #freqs local out = table.create(n, 0) - -- leaves sorted by frequency (ties by symbol, for determinism) local syms = {} for i = 1, n do if freqs[i] > 0 then @@ -64454,14 +62975,13 @@ if freqs[a] ~= freqs[b] then end return a < b end) - -- two-queue Huffman: leaves (sorted) and internal nodes (created in increasing weight order) 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 -- next leaf, next internal node to take, next free node + local li, ni, nn = 1, m + 1, m + 1 local function take() if li <= m and (ni >= nn or weight[li] <= weight[ni]) then li =li+ 1 @@ -64478,12 +62998,11 @@ if li <= m and (ni >= nn or weight[li] <= weight[ni]) then parent[b] = nn nn =nn+ 1 end - -- depths: the root is nn - 1 local depth = table.create(2 * m, 0) for i = nn - 2, 1, -1 do depth[i] = depth[parent[i] ] + 1 end - -- count codes per length; limit (JPEG K.3: move pairs from the deepest level up) + -- 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 @@ -64502,7 +63021,6 @@ end do local __DARKLUA_VAR0=j + 1 bl[__DARKLUA_VAR0]=bl[__DARKLUA_VAR0]+ 2 end bl[j]=bl[j]- 1 end end - -- the longest codes go to the least frequent symbols (syms is sorted ascending) local k = 1 for l = math.min(deepest, maxLen), 1, -1 do for _ = 1, bl[l] do @@ -64517,12 +63035,8 @@ return Huffman end __FILES["codecs/entropy/RangeCoder"] = function() --!strict --- codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt): --- symbols range-coded from the front of a frame, raw bits from its back. Opus (CELT and SILK) uses it; LZMA, VP8 and --- CABAC have their own (different) binary coders. Moved here from audio/opus by the cleanup pass (same code). --- --- local RD = require("rosetta.codecs.entropy.RangeCoder.Decoder") -- RD.new(buf, base, size), RD.icdf / bits / uint ... --- local RE = require("rosetta.codecs.entropy.RangeCoder.Encoder") -- RE.new(size), RE.icdf / bits / uint, RE.done +-- 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"), @@ -64534,10 +63048,9 @@ __FILES["codecs/entropy/RangeCoder/Decoder"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/entropy/RangeCoder/Decoder: the Opus range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus --- frame from a `buffer` slice [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice --- backwards. --- All values stay below 2^32, so plain Luau numbers hold them exactly; floor division is exact below 2^52. +-- 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 = {} @@ -64587,7 +63100,7 @@ local function normalize(d) else rem = 0 end - sym = rshift(bor(lshift(sym, 8), rem), SYM_BITS - CODE_EXTRA) -- (sym << 8 | rem) >> 1 + 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 @@ -64620,7 +63133,6 @@ local d= { return d end --- ec_decode: the cumulative frequency of the next symbol, for a total of ft function RangeDecoder.decode(d, ft) local ext = math.floor(d.rng / ft ) d.ext = ext @@ -64662,7 +63174,6 @@ local r = d.rng return ret end --- ec_dec_icdf over a Luau array (1-based) starting at index `off` (icdf[off] is entry 0) function RangeDecoder.icdf(d, icdf, off, ftb) local s = d.rng local v = d.val @@ -64751,10 +63262,8 @@ __FILES["codecs/entropy/RangeCoder/Encoder"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/entropy/RangeCoder/Encoder: the Opus range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD: --- licenses/libopus-BSD.txt), the mirror of codecs/entropy/RangeCoder/Decoder. Writes one fixed-size frame: the range-coded --- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain --- numbers. Never throws: running out of room sets `error`. +-- 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 = {} @@ -64787,7 +63296,6 @@ return 32 - countlz(x) end RangeEncoder.ilog = ilog --- new(storage) -> Enc over a fresh zeroed buffer of storage bytes function RangeEncoder.new(storage) return { buf = buffer.create(math.max(storage, 1)), @@ -64851,7 +63359,6 @@ local function normalize(e) end end --- encode(fl, fh, ft): the symbol [fl, fh) of ft function RangeEncoder.encode(e, fl, fh, ft) local r = floor(e.rng / ft) if fl > 0 then @@ -64863,7 +63370,6 @@ function RangeEncoder.encode(e, fl, fh, ft) normalize(e) end --- encodeBin(fl, fh, bits): ft = 2^bits function RangeEncoder.encodeBin(e, fl, fh, bits) local ft = 2 ^ bits local r = floor(e.rng / ft) @@ -64876,7 +63382,6 @@ function RangeEncoder.encodeBin(e, fl, fh, bits) normalize(e) end --- bitLogp(v, logp): a bit whose probability of being 1 is 2^-logp function RangeEncoder.bitLogp(e, v, logp) local r = e.rng local s = floor(r / 2 ^ logp) @@ -64890,7 +63395,6 @@ function RangeEncoder.bitLogp(e, v, logp) normalize(e) end --- icdf(s, icdf, ftb): symbol s (0-based) of an inverse CDF table (1-based Luau array) with 2^ftb total function RangeEncoder.icdf(e, s, icdf, ftb) local r = floor(e.rng / 2 ^ ftb) if s > 0 then @@ -64902,7 +63406,6 @@ function RangeEncoder.icdf(e, s, icdf, ftb) normalize(e) end --- bits(fl, n): n raw bits (n <= 25), written from the end of the frame function RangeEncoder.bits(e, fl, n) local window = e.end_window local used = e.nend_bits @@ -64920,7 +63423,6 @@ function RangeEncoder.bits(e, fl, n) e.nbits_total =e.nbits_total+ n end --- uint(fl, ft): fl uniformly in [0, ft), ft up to 2^32 function RangeEncoder.uint(e, fl, ft) ft =ft- 1 local ftb = ilog(ft) @@ -64952,7 +63454,6 @@ local nbits = e.nbits_total * 8 return nbits - (l * 8 + b) end --- done(): flush; the frame is e.buf (storage bytes) function RangeEncoder.done(e) local l = 32 - ilog(e.rng) local msk = floor((CODE_TOP - 1) / 2 ^ l) @@ -65003,20 +63504,8 @@ return RangeEncoder end __FILES["codecs/font/Bitmap"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict --- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike --- (one pixel size, glyphs as u8 bitmaps, 0 = off / 255 = on) wrapped as a Types.Font whose units are pixels --- (unitsPerEm = the pixel size), glyphIndex / advance / kern work, outline is nil, and rasterize(g) returns the glyph's --- bitmap as an alpha8 Image (img.meta.left / top / advance, as codecs/font/TrueType does; the px argument is ignored, --- img.meta.scale = px / size tells the caller how much to scale). Also: the strike of any Font (its own bitmap, or an --- outline font rasterized at a pixel size and thresholded), which the bitmap font encoders write, and the bit-row --- packing every bitmap font format shares. New code. --- --- local font = Bitmap.font(strike, { family = "Fixed" }, { source = { format = "bdf" } }) --- local strike, err = Bitmap.strike(anyFont, { px = 16, chars = "abc" }) -- font.bitmap, or rasterized --- local pixels = Bitmap.unpack(buf, off, w, h, stride) -- MSB-first 1-bit rows -> u8 0 / 255 --- local bytes = Bitmap.pack(pixels, w, h, stride) -- u8 -> MSB-first rows (buffer) --- --- Never throws: rasterize of a bad glyph index returns nil; unpack reads only inside the buffer (missing bits are 0). +-- 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") @@ -65024,9 +63513,6 @@ local Bitmap = {} local readu8, writeu8 = buffer.readu8, buffer.writeu8 --- ------------------------------------------------------------------------------------------------ bits --- unpack(buf, off, w, h, stride, lsbFirst?) -> u8 pixels (w * h, 0 / 255) from 1-bit rows of stride bytes (MSB = left --- pixel unless lsbFirst); bytes past the end of buf read as 0 function Bitmap.unpack(b, off, w, h, stride, lsbFirst) local out = buffer.create(math.max(0, w * h)) local n = buffer.len(b) @@ -65046,7 +63532,6 @@ local out = buffer.create(math.max(0, w * h)) return out end --- pack(pixels, w, h, stride?, lsbFirst?) -> 1-bit rows (stride bytes each, default ceil(w / 8)); a pixel >= 128 is on function Bitmap.pack(px, w, h, stride, lsbFirst) local s = stride or math.ceil(w / 8) local out = buffer.create(math.max(0, s * h)) @@ -65064,7 +63549,6 @@ local s = stride or math.ceil(w / 8) return out end --- ------------------------------------------------------------------------------------------------ font local Face = {} Face.__index = Face @@ -65085,7 +63569,6 @@ function Face.outline(_self, _g) return nil end --- rasterize(g, px?) -> the glyph as an alpha8 Image (px is ignored: meta.scale = px / size) function Face.rasterize(self, g, px) local gl= self.bitmap.glyphs[g + 1] if not gl or gl.width < 0 or gl.height < 0 then @@ -65104,7 +63587,6 @@ local gl= self.bitmap.glyphs[g + 1] )) return img end --- font(strike, info?, meta?) -> a Types.Font over the strike (font.bitmap = strike) function Bitmap.font(strike, info, meta) local index= {} for i, gl in __iter(strike.glyphs) do @@ -65139,7 +63621,6 @@ local index= {} end return f end --- ------------------------------------------------------------------------------------------------ strike @@ -65164,7 +63645,6 @@ if type(chars) == "table" then return out end --- strike(font, opts?) -> the font's BitmapStrike: font.bitmap, else the outline font rasterized at opts.px function Bitmap.strike(font, opts) if type(font) ~= "table" or font.kind ~= "font" then return nil, Err.new(Err.ARG, "expected a Font") @@ -65225,19 +63705,9 @@ return Bitmap end __FILES["codecs/font/Cff"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts --- with a "CFF " table (.otf). Parses the header, the INDEXes, the Top / Private DICTs (name-keyed and CID-keyed --- fonts with FDArray / FDSelect formats 0 and 3), local and global subroutines, and runs charstrings to path commands --- (moveTo / lineTo / cubicTo / close, font units, y up). The charstring interpreter is ported from stb_truetype 1.26 --- (public domain / MIT; Dougall Johnson's Type 2 support) through imgui-luau's imstb_truetype.lua, bounds-checked, --- with fixes: flex1's last delta, an operation budget against subroutine bombs, and the arithmetic / storage --- operators (TN #5177 4.4: and or not abs add sub div neg eq drop put get ifelse random mul sqrt dup exch index roll). --- Not supported: CFF2 (variable fonts), seac accented glyphs in endchar (deprecated in OpenType), hinting. --- --- local cff, err = Cff.parse(buf, offset, length) --- local cmds, err = Cff.outline(cff, glyphIndex) --- --- Never throws: malformed data returns nil, message. +-- 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 @@ -65257,7 +63727,6 @@ local v = 0 return v end --- INDEX at absolute offset p (within [base, limit)) -> Index | nil @@ -65297,7 +63766,6 @@ if p + 2 > limit then return { count = count, offSize = offSize, offsets = offsets, data = data, next = data + last } end --- item(idx, i) -> absolute start, length (nil when out of range / corrupt) local function item(b, idx, i) if i < 0 or i >= idx.count then return nil, 0 @@ -65311,7 +63779,7 @@ if i < 0 or i >= idx.count then end Cff.item = item --- DICT at [p, p + n) -> { [op] = { operands } } (two-byte ops are 1200 + second byte) +-- DICT operators: two-byte ops (12 x) are keyed 1200 + x local function dict(b, p, n) local out= {} local ops= {} @@ -65397,7 +63865,6 @@ local pr = d[18] return index(b, ps + s[1], limit) end --- parse(buf, offset, length) -> Font | nil, message function Cff.parse(b, offset, length) local base, limit = offset, math.min(offset + length, blen(b)) if limit - base < 4 then @@ -65482,7 +63949,6 @@ local function bias(count) return count < 1240 and 107 or(count < 33900 and 1131 or 32768 )end --- the local subrs of glyph g (CID fonts: through FDSelect) local function localSubrs(f, g) if not f.cid then return f.subrs @@ -65512,7 +63978,6 @@ end local BUDGET = 200000 -- operators per glyph (subroutine bombs) --- outline(f, g) -> path commands | nil, message function Cff.outline(f, g) local b = f.buf local p, len = item(b, f.charStrings, g) @@ -65521,14 +63986,14 @@ local b = f.buf end local e = p + len local cmds= {} - local s= table.create(48, 0) -- operand stack, 1-based; sp = count + local s= table.create(48, 0) local sp = 0 local trans = (table.create(32, 0) ) local x, y = 0, 0 local open = false local maskbits = 0 local inHeader = true - local stack= {} -- return addresses { p, e } + local stack= {} local subrs= nil local haveSubrs = false local ops = 0 @@ -65566,7 +64031,6 @@ return s[i + 1] or 0 while true do local __DARKLUA_CONTINUE_7=false repeat if p >= e then - -- the end of a subroutine without return, or of the charstring without endchar if #stack > 0 then local r = (table.remove(stack) ) p, e = r[1], r[2] @@ -65761,12 +64225,10 @@ p, e = r[1], r[2] 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 - -- arithmetic and storage operators: they leave results on the stack clear = false local top = sp local a, c = S(top - 2), S(top - 1) local function set(n, v) - -- pop n operands, push v sp = math.max(0, sp - n) sp =sp+ 1 s[sp] = v @@ -65884,14 +64346,9 @@ return Cff end __FILES["codecs/font/GlyphNames"] = function() local __compat = __compat local __iter = __compat.__iter --!strict --- codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a --- cmap, PCF / BDF glyph names): the Adobe Glyph List For New Fonts (AGLFN 1.7, Adobe, BSD-3-Clause: --- licenses/agl-LICENSE.txt; the f-ligatures and dotlessj added), the uniXXXX / uXXXX[XX] conventions and --- name.suffix variants ("a.sc" -> a) per the AGL specification; and Adobe StandardEncoding (code -> glyph name). --- Generated once from fontTools.agl / fontTools.encodings.StandardEncoding. --- --- GlyphNames.unicode("Aacute") -> 0xC1 GlyphNames.unicode("uni20AC") -> 0x20AC (nil when unknown) --- GlyphNames.STANDARD[65] -> "A" (StandardEncoding, codes 0..255; nil for .notdef) +-- 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 @@ -66011,7 +64468,6 @@ do end GlyphNames.STANDARD = STANDARD --- unicode(name) -> the code point of a glyph name (the first one for ligature names like "f_i"), or nil function GlyphNames.unicode(name) local base = string.match(name, "^([^%.]+)") or name local t = byName or load() @@ -66040,22 +64496,8 @@ return GlyphNames end __FILES["codecs/font/TrueType"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed --- into the standard Font value (Types.Font): metrics (head / hhea / hmtx / OS/2 / post), cmap lookups, glyph outlines --- (codecs/font/TrueType/Glyf for glyf, codecs/font/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments), --- names, and rasterize(glyph, px) through codecs/image/Raster. A codec, not a format: font/ttf, font/woff and font/woff2 all --- build an sfnt and call TrueType.font(). Ported and modernised from stb_truetype 1.26 (public domain / MIT, Sean --- Barrett and contributors) through imgui-luau's imstb_truetype.lua; the rasterizer is codecs/image/Raster instead of stb's. --- Not supported: hinting, variable fonts (fvar / gvar / CFF2), vertical metrics, bitmap strikes (EBDT / CBDT / sbix), --- colour layers (COLR), GSUB substitutions. --- --- local font, err = TrueType.font(buf, offset?, length?, { index = 0 }) -- Types.Font | nil, Err --- local g = font:glyphIndex(0x41) local adv = font:advance(g) -- font units --- local k = font:kern(g1, g2) local cmds = font:outline(g) -- moveTo / lineTo / quadTo / cubicTo --- local img = font:rasterize(g, 32) -- alpha8 Image, 32 px per em; img.meta.left / top / advance (px) --- local n = TrueType.count(buf) -- fonts in a collection (1 for a plain sfnt) --- --- Never throws: malformed fonts return nil, Err from font(), and nil from the per-glyph methods. +-- 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") @@ -66074,7 +64516,6 @@ if o < 0 or o + 4 > buffer.len(b) then return buffer.readstring(b, o, 4) end --- count(buf, offset?) -> the number of fonts (a collection's count, 1 for an sfnt, 0 for neither) function TrueType.count(b, offset) local o = offset or 0 local t = tag(b, o) @@ -66087,7 +64528,6 @@ local o = offset or 0 return 0 end --- tables(buf, file, dir) -> { [tag] = { offset (absolute), length } } of the table directory at dir function TrueType.tables(b, file, dir, limit) local n = u16(b, dir + 4) if dir + 12 + n * 16 > limit then @@ -66105,7 +64545,6 @@ local n = u16(b, dir + 4) return out, nil end --- ------------------------------------------------------------------------------------------------ the Font value local Face = {} Face.__index = Face @@ -66157,7 +64596,6 @@ if type(a) ~= "number" or type(b) ~= "number" then return v end --- kernCodepoints(a, b) -> kern between two code points function Face.kernCodepoints(self, a, b) return self:kern(self:glyphIndex(a), self:glyphIndex(b)) end @@ -66182,7 +64620,6 @@ if type(g) ~= "number" or g < 0 or g >= self.numGlyphs or g % 1 ~= 0 then return cmds end --- bounds(g) -> xMin, yMin, xMax, yMax of the outline's points (font units), nil for an empty / bad glyph function Face.bounds(self, g) local cmds = self:outline(g) if not cmds then @@ -66201,14 +64638,11 @@ local cmds = self:outline(g) return x0, y0, x1, y1 end --- scale(px) -> pixels per font unit for an em of px pixels function Face.scale(self, px) return px / self.unitsPerEm end --- rasterize(g, px, opts?) -> alpha8 Image (meta.left / meta.top: the bitmap's offset from the pen position, pixels; --- top counts up from the baseline as FreeType's bitmap_top; meta.advance in pixels) | nil for a bad glyph. Empty --- glyphs give a 0 x 0 image. +-- meta.top counts up from the baseline, as FreeType's bitmap_top @@ -66244,8 +64678,6 @@ if type(px) ~= "number" or not (px > 0) or px > 4096 then img.meta.glyph = g return img end --- ------------------------------------------------------------------------------------------------ parsing --- font(buf, offset?, length?, opts?) -> Types.Font | nil, Err @@ -66312,7 +64744,6 @@ local b = buf _numHMetrics = nh, _kernCache = {}, }, Face) - -- outlines if t.glyf and t.loca then font._glyf = { buf = b, @@ -66337,7 +64768,6 @@ local b = buf else return nil, Err.new(Err.UNSUPPORTED, "no glyf or CFF outlines (bitmap-only font?)", dir) end - -- cmap, kerning, names, OS/2, post if t.cmap then font._cmap = Tables.cmap(b, t.cmap[1], t.cmap[2]) end @@ -66380,14 +64810,9 @@ return TrueType end __FILES["codecs/font/TrueType/Glyf"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- codecs/font/TrueType/Glyf: TrueType glyph outlines (the glyf / loca tables): simple glyphs (contours of on- and --- off-curve points, with the implied on-curve midpoints) and composite glyphs (offsets or point matching, scale / --- x-y scale / 2x2 transforms, SCALED_COMPONENT_OFFSET, nesting up to 8 levels). Ported from stb_truetype 1.26 --- (public domain / MIT, Sean Barrett) through imgui-luau's imstb_truetype.lua, made bounds-checked, with point --- matching and the FreeType component transform (stb scales the offsets of transformed components; FreeType and the --- spec do not). No hinting. --- --- Never throws: every read is range-checked (out of range reads as 0) and malformed glyphs return nil, message. +-- 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 @@ -66414,7 +64839,6 @@ local function u32(b, o) return u16(b, o) * 65536 + u16(b, o + 2) end --- (start, length) of glyph g in the glyf table, or nil for an empty glyph / bad index @@ -66448,7 +64872,6 @@ else return f.glyf + a, z - a end --- bounds(f, g) -> xMin, yMin, xMax, yMax from the glyph header (nil for empty glyphs) function Glyf.bounds(f, g) local o, n = Glyf.range(f, g) if not o or n < 10 then @@ -66457,7 +64880,6 @@ local o, n = Glyf.range(f, g) local b = f.buf return i16(b, o + 2), i16(b, o + 4), i16(b, o + 6), i16(b, o + 8) end --- contours: { { xs, ys, on } } point lists in font units @@ -66489,7 +64911,6 @@ local p = o + 10 ) if p > e then return nil, "instructions past the end" end - -- flags local flags = table.create(n, 0) local i = 1 while i <= n do @@ -66515,7 +64936,6 @@ local p = o + 10 end end end - -- coordinates local xs = table.create(n, 0) local x = 0 for k = 1, n do @@ -66628,7 +65048,6 @@ end if not child then return nil, err end - -- transform the child's points local tc = (table.create(#child) ) for i, c in __iter(child) do local nx, ny = (table.create(#c.x) ), (table.create(#c.x) ) @@ -66689,7 +65108,7 @@ if depth > 8 then end local o, len = Glyf.range(f, g) if not o then - return {}, nil -- empty glyph (space) + return {}, nil end if len < 10 then return nil, "glyph header past the end" @@ -66701,7 +65120,6 @@ if depth > 8 then return composite(f, o, len, depth) end --- outline(f, g) -> path commands (codecs/image/Raster format, font units, y up) | nil, message function Glyf.outline(f, g) local cs, err = contours(f, g, 0) if not cs then @@ -66746,7 +65164,7 @@ __DARKLUA_CONTINUE_14=true break 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 -- back to the start + x, y, isOn = sx, sy, true end if isOn then if off then @@ -66768,7 +65186,6 @@ __DARKLUA_CONTINUE_14=true until true if not __DARKLUA_CONTINUE_14 then break en return cmds, nil end --- points(f, g) -> the number of points and contours (for tests) function Glyf.counts(f, g) local cs = contours(f, g, 0) if not cs then @@ -66785,13 +65202,8 @@ return Glyf end __FILES["codecs/font/TrueType/Tables"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict --- codecs/font/TrueType/Tables: the sfnt tables besides the outlines: cmap (formats 0, 4, 6, 10, 12, 13; the best Unicode --- subtable, symbol fonts through U+F000), kern (Microsoft version 0 and Apple version 1, format 0 pairs), GPOS pair --- kerning (lookup type 2 formats 1 and 2, reached through the 'kern' feature, including extension lookups, type 9), --- name (UTF-16BE and Mac Roman strings) and OS/2. Written from the OpenType spec, with stb_truetype 1.26 (public --- domain / MIT) as a reference for cmap 4 and the GPOS walk. --- --- Never throws: every read is range-checked (out of range reads as 0). +-- 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 = {} @@ -66819,9 +65231,8 @@ local function u32(b, o) return u16(b, o) * 65536 + u16(b, o + 2) end Tables.u8, Tables.u16, Tables.i16, Tables.u32 = u8, u16, i16, u32 --- ------------------------------------------------------------------------------------------------ cmap --- pick the best subtable of the cmap table at [o, o + n): Unicode full repertoire, then BMP, then symbol, then Mac +-- cmap subtable preference: Unicode full repertoire, then BMP, then symbol, then Mac function Tables.cmap(b, o, n) @@ -66888,7 +65299,6 @@ local b, t, fmt = c.buf, c.at, c.format local segX2 = u16(b, t + 6) local segs = math.floor(segX2 / 2 ) local ends = t + 14 - -- binary search for the first segment whose end >= cp local lo, hi = 0, segs - 1 while lo < hi do local mid = math.floor((lo + hi) / 2 @@ -66939,7 +65349,6 @@ local b, t, fmt = c.buf, c.at, c.format return 0 end --- glyph(cmap, codepoint) -> glyph index (0 = .notdef) function Tables.glyph(c, cp) if not c or type(cp) ~= "number" or cp < 0 or cp > 0x10FFFF or cp % 1 ~= 0 then return 0 @@ -66951,8 +65360,6 @@ if not c or type(cp) ~= "number" or cp < 0 or cp > 0x10FFFF or cp % 1 ~= 0 then return g end --- ------------------------------------------------------------------------------------------------ kern --- the 'kern' table's horizontal format 0 pairs -> { [left * 65536 + right] = value } function Tables.kern(b, o, n) local pairs= {} local e = o + n @@ -67005,7 +65412,6 @@ local pairs= {} return pairs end --- ------------------------------------------------------------------------------------------------ GPOS local function popcount(v) local c = 0 while v ~= 0 do @@ -67015,7 +65421,6 @@ local c = 0 return c end --- coverage index of glyph g in the Coverage table at t, or -1 local function coverage(b, t, g) local fmt = u16(b, t) if fmt == 1 then @@ -67077,7 +65482,6 @@ local fmt = u16(b, t) return 0 end --- the x advance adjustment in a value record with format vf at r local function xAdvance(b, r, vf) if band(vf, 4) == 0 then return 0 @@ -67085,7 +65489,6 @@ if band(vf, 4) == 0 then return i16(b, r + 2 * popcount(band(vf, 3))) end --- one PairPos subtable: (applies, value) local function pairPos(b, t, l, r) local fmt = u16(b, t) local ci = coverage(b, t + u16(b, t + 2), l) @@ -67129,7 +65532,6 @@ local fmt = u16(b, t) return false, 0 end --- the pair-adjustment lookups of the 'kern' feature (any script / language) of the GPOS table at [o, o + n) function Tables.gpos(b, o, n) @@ -67182,7 +65584,6 @@ if n < 10 or u16(b, o) ~= 1 then return { buf = b, subtables = lookups } end --- gposKern(gpos, left, right) -> the summed x advance adjustment of the first glyph (font units) function Tables.gposKern(g, l, r) local total = 0 for _, subs in __iter(g.subtables) do @@ -67197,7 +65598,6 @@ local total = 0 return total end --- ------------------------------------------------------------------------------------------------ name, OS/2 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, @@ -67242,7 +65642,6 @@ local NAME_IDS= { [17] = "typographicStyle", } --- names(name table) -> { family, style, fullName, ... } (English Windows names first, then Unicode, then Mac Roman) function Tables.names(b, o, n) local out= {} local rank= {} @@ -67276,7 +65675,6 @@ local out= {} return out end --- os2(OS/2 table) -> the commonly used fields function Tables.os2(b, o, n) local t= { version = u16(b, o), @@ -67308,26 +65706,14 @@ __FILES["codecs/image/Bcn"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --!native --!optimize 2 --- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...): --- decode of BC1 (DXT1, with the 3-colour + transparent mode), BC2 (DXT3), BC3 (DXT5), BC4 / BC5 (RGTC / ATI1 / ATI2, --- UNORM and SNORM), BC6H (UF16 / SF16, to rgbaf32) and BC7 (all 8 modes); encode of BC1 / BC3 / BC4 / BC5 (UNORM). --- Decoders ported from Pillow's BcnDecode.c (CC0) with the D3D11 rules; encoders new (stb_dxt-style). Never throws. --- --- local px, err = Bcn.decode("bc7", buf, offset, w, h) -- rgba8 pixels (rgbaf32 for bc6h / bc6hs) --- local blocks = Bcn.encode("bc1", rgba8Pixels, w, h) -- the block data (row-major blocks) --- Bcn.size("bc3", w, h) -- bytes of a w x h image (whole 4x4 blocks) --- --- Channels: BC4 decodes to grey (r = g = b, opaque), BC5 to red + green (blue 0, opaque); SNORM values are biased by --- 128 into rgba8 (-127 -> 1, 0 -> 128, 127 -> 255). BC1 / BC3 / BC5 encode reads R / G (BC4: R), BC1 alpha below --- opts.alphaThreshold (default 128) selects the transparent 3-colour mode. +-- 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 = {} --- kind -> bytes per 4x4 block -Bcn.BLOCK = (table.freeze({ bc1 = 8, bc2 = 16, bc3 = 16, bc4 = 8, bc4s = 8, bc5 = 16, bc5s = 16, bc6h = 16, bc6hs = 16, bc7 = 16 }) )-- kinds that decode to rgbaf32 - +Bcn.BLOCK = (table.freeze({ bc1 = 8, bc2 = 16, bc3 = 16, bc4 = 8, bc4s = 8, bc5 = 16, bc5s = 16, bc6h = 16, bc6hs = 16, bc7 = 16 }) ) Bcn.FLOAT = (table.freeze({ bc6h = true, bc6hs = true }) ) local readu32, writeu32 = buffer.readu32, buffer.writeu32 @@ -67349,7 +65735,6 @@ local BLOCKS= { end, } --- size(kind, w, h) -> bytes of the block data (nil for an unknown kind) function Bcn.size(kind, w, h) local b = Bcn.BLOCK[kind] if not b then @@ -67358,8 +65743,6 @@ local b = Bcn.BLOCK[kind] return (math.floor((w + 3) / 4)) * (math.floor((h + 3) / 4)) * b end --- decode(kind, src, offset, w, h, out?, outOffset?) -> pixels (rgba8, or rgbaf32 for BC6H) | nil, message. --- out (optional) receives the pixels at outOffset (default 0) instead of a new buffer. function Bcn.decode(kind, src, offset, w, h, out, outOffset) local fn = BLOCKS[kind] if not fn then @@ -67409,7 +65792,6 @@ if offset < 0 or offset + need > buffer.len(src) then return dst, nil end --- encode(kind, pixels, w, h, opts?) -> block data | nil, message. pixels: rgba8, w x h; kind = bc1 / bc3 / bc4 / bc5. @@ -67431,12 +65813,9 @@ __FILES["codecs/image/Bcn/Decode"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/image/Bcn/Decode: the BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC). Ported from Pillow's --- src/libImaging/BcnDecode.c (CC0, licenses/pillow-bcn-CC0.txt) and changed to follow the D3D11 functional spec where --- Pillow does not: BC6H interpolation rounds ((a * (64 - w) + b * w + 32) >> 6), BC6H keeps its float values (no 8-bit --- clamp), BC7's reserved mode 8 and BC6H's reserved modes decode to transparent / zero, BC4 / BC5 SNORM interpolate --- the signed values (-128 reads as -127). Each decoder writes one 4x4 block into a 64-byte (rgba8) or 256-byte --- (rgbaf32) scratch block; the caller clips it into the image. Never throws: the caller checks the source size. +-- 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 = {} @@ -67445,8 +65824,7 @@ local readu8, readu16, readu32, writeu8, writeu32, writef32 = buffer.readu8, buf local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift local HALF = Half.TABLE --- ------------------------------------------------------------------------------------------------ BC1 / BC2 / BC3 -local pal = buffer.create(16) -- 4 rgba8 colours +local pal = buffer.create(16) local function c565(c) local r = rshift(band(c, 0xF800), 8) @@ -67455,7 +65833,7 @@ local r = rshift(band(c, 0xF800), 8) return bor(r, rshift(r, 5)), bor(g, rshift(g, 6)), bor(b, rshift(b, 5)) end --- the BC1 colour block at p into blk (64 bytes); fourColour = BC2 / BC3 (always the 4-colour palette) +-- BC2 / BC3 colour blocks always use the 4-colour palette local function colour(src, p, blk, fourColour) local c0, c1 = readu16(src, p), readu16(src, p + 2) local r0, g0, b0 = c565(c0) @@ -67475,7 +65853,6 @@ local function colour(src, p, blk, fourColour) end end --- the 8 values of a BC3 alpha / BC4 block (unsigned) into vals local vals = table.create(8, 0) local function ramp8(a0, a1) vals[1], vals[2] = a0, a1 @@ -67508,7 +65885,6 @@ local function ramp8s(u0, u1) end end --- one 8-byte BC3 alpha / BC4 block at p into byte `channel` of every blk pixel (and the next ones when spread) local function single(src, p, blk, channel, signed, spread) if signed then ramp8s(readu8(src, p), readu8(src, p + 1)) @@ -67568,7 +65944,6 @@ function Decode.bc5s(src, p, blk) bc5(src, p, blk, true) end --- ------------------------------------------------------------------------------------------------ BPTC tables -- 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, @@ -67612,7 +65987,6 @@ if ns == 2 then return 0 end --- the 128-bit block as four u32 words: bits(at, n) for n <= 16 local w0, w1, w2, w3 = 0, 0, 0, 0 local function load(src, p) w0, w1, w2, w3 = readu32(src, p), readu32(src, p + 4), readu32(src, p + 8), readu32(src, p + 12) @@ -67632,7 +66006,6 @@ if n == 0 then return band(v, lshift(1, n) - 1) end --- ------------------------------------------------------------------------------------------------ BC7 -- ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 local MODES7 = { { 3, 4, 0, 0, 4, 0, 1, 0, 3, 0 }, @@ -67771,7 +66144,6 @@ function Decode.bc7(src, p, blk) end end --- ------------------------------------------------------------------------------------------------ BC6H -- ns, transformed, pb, epb, rb, gb, bb local MODES6 = { { 2, 1, 5, 10, 5, 5, 5 }, @@ -67850,7 +66222,6 @@ if signed then return HALF[math.floor((v * 31) / 64)] end --- one BC6H block into blk as rgbaf32 (256 bytes, alpha 1) function Decode.bc6h(src, p, blk, signed) load(src, p) local m = band(w0, 31) @@ -67931,11 +66302,8 @@ __FILES["codecs/image/Bcn/Encode"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/image/Bcn/Encode: BC1 / BC3 / BC4 / BC5 block encoders (new in rosetta; the approach follows stb_dxt by --- Fabian Giesen / Sean Barrett, public domain: the principal axis of the block's colours by power iteration, the --- extreme pixels along it as endpoints, then least-squares refinement of the endpoints for the chosen indices, keeping --- the best; single-colour blocks use exact endpoint tables). Indices are chosen against the palette exactly as --- Bcn/Decode rebuilds it. BC4 / BC5 channels try both the 8-value and the 6-value (+ 0 / 255) ramps. Never throws. +-- 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 @@ -67948,7 +66316,6 @@ local function exp6(v) return bor(lshift(v, 2), rshift(v, 4)) end --- ------------------------------------------------------------------------------------------------ single colours -- OM[k][v + 1] = e0 * 256 + e1 (quantized) whose colour-2 value (4-colour: (2 e0 + e1) // 3; 3-colour: (e0 + e1) -- // 2) is closest to v; k = 1 / 2 for 5-bit (4 / 3 colour), 3 / 4 for 6-bit local OM= nil @@ -67986,7 +66353,6 @@ local om = OM return t end --- ------------------------------------------------------------------------------------------------ BC1 colour 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) @@ -68007,7 +66373,6 @@ local function palette(c0, c1, four) end end --- indices for the palette into IDX (0-based); returns the squared error of the used pixels local function assign(four) local n = four and 4 or 3 local total = 0 @@ -68038,11 +66403,9 @@ local qr = math.clamp(math.floor(r * 31 / 255 + 0.5), 0, 31) return qr * 2048 + qg * 32 + qb end --- the endpoint weights of index k (the e0 share) local W4 = { 1, 0, 2 / 3, 1 / 3 } local W3 = { 1, 0, 0.5, 0 } --- least squares endpoints for the current IDX: c0, c1 or nil when degenerate local function refine(four) local W = (four and{W4 }or{W3 })[1] local aa, bb, ab = 0, 0, 0 @@ -68072,8 +66435,6 @@ local W = (four and{W4 }or{W3 return q565(r0, g0, b0), q565(r1, g1, b1) end --- encodes R / G / B (USE marks the pixels that count) as a BC1 colour block at out[o]; four = 4-colour mode --- (opaque), else the 3-colour mode with index 3 for the unused (transparent) pixels local function colourBlock(out, o, four) local n, mr, mg, mb = 0, 0, 0, 0 for i = 1, 16 do @@ -68206,7 +66567,6 @@ local function colourBlock(out, o, four) writeu32(out, o + 4, bitsv) end --- ------------------------------------------------------------------------------------------------ BC4 channel local V = table.create(16, 0) local RAMP = table.create(8, 0) local SEL = table.create(16, 0) @@ -68244,7 +66604,6 @@ local total = 0 return total end --- encodes V[1..16] (0..255) as an 8-byte BC4 block at out[o] local function channelBlock(out, o) local lo, hi = 255, 0 local lo2, hi2 = 255, 0 @@ -68310,8 +66669,6 @@ local function channelBlock(out, o) writeu8(out, o + 7, rshift(hi24, 16)) end --- ------------------------------------------------------------------------------------------------ whole images --- the 4x4 block at bx, by of an rgba8 image into R / G / B / A (edge pixels repeat) local function gather(px, w, h, bx, by) for y = 0, 3 do local sy = math.min(by * 4 + y, h - 1) @@ -68324,7 +66681,6 @@ local function gather(px, w, h, bx, by) end end --- encode(kind, rgba8 pixels, w, h, alphaThreshold) -> the block data (kind = bc1 / bc3 / bc4 / bc5) function Encode.run(kind, px, w, h, threshold) local bw, bh = math.floor((w + 3) / 4), math.floor((h + 3) / 4 ) local bytes = (kind == "bc1" or kind == "bc4" )and 8 or 16 @@ -68374,17 +66730,8 @@ end __FILES["codecs/image/Blend"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native --- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable --- blend modes of the W3C Compositing and Blending Level 1 spec (the Photoshop / Aseprite set), opacity, a grey layer --- mask, clipping (source-atop: the backdrop keeps its alpha) and dissolve. Shared by ops/LayerOps (flatten) and the --- layered formats that must write a composite (layered/psd). Never throws: rectangles are clipped to both buffers. --- --- Blend.composite(dst, dw, dh, src, sw, sh, x, y, opacity, "multiply", { clip = false, mask = m }) --- Blend.MODES.multiply -> true --- --- Mode names: normal dissolve darken multiply colorBurn linearBurn darkerColor lighten screen colorDodge linearDodge --- (= add) lighterColor overlay softLight hardLight vividLight linearLight pinLight hardMix difference exclusion --- subtract divide hue saturation color luminosity. Unknown names composite as normal. +-- 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 @@ -68538,9 +66885,6 @@ local mx = max(r, g, b) return (r - mn) * k, (g - mn) * k, (b - mn) * k end --- composite(dst, dw, dh, src, sw, sh, x, y, opacity, mode, opts?): blends the sw x sh rgba8 src onto the dw x dh rgba8 --- dst with its top-left at (x, y). opacity 0..1. opts.clip: keep the backdrop's alpha (clipping masks). opts.mask: --- { pixels: buffer (1 byte per pixel), width, height, x, y, default: 0..255 } in dst coordinates (outside it: default). local function composite(dst, dw, dh, src, sw, sh, x, y, opacity, mode, opts) x, y = floor(x), floor(y) if opacity <= 0 or dw <= 0 or dh <= 0 or sw <= 0 or sh <= 0 then @@ -68590,7 +66934,6 @@ mdef = (tonumber(mask.default) or 255) / 255 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 - -- empty backdrop: the source as it is (alpha scaled) writeu32(dst, do_, readu32(src, so)) writeu8(dst, do_ + 3, floor(sa * 255 + 0.5)) else @@ -68647,9 +66990,6 @@ elseif m == 6 then end end --- lerp(dst, from, t, n, w?, mask?): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity); --- with a mask ({ pixels, width, height, x, y, default } as for composite, in the coordinates of a w-wide canvas) t is --- also scaled by the mask value of each pixel local function lerp(dst, from, t, n, w, mask) if blen(dst) < n * 4 or blen(from) < n * 4 then return @@ -68686,7 +67026,6 @@ end Blend.composite = composite Blend.lerp = lerp --- ------------------------------------------------------------------------------------------------ layer trees local function isImage(v) return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and buffer.len(v.pixels) >= v.width * v.height * 4 end @@ -68698,7 +67037,7 @@ local m = l.mask end local img = m.image local px = img.pixels - if img.format == "rgba8" then -- use the red channel + if img.format == "rgba8" then local n = img.width * img.height local g = buffer.create(n) for i = 0, n - 1 do @@ -68723,8 +67062,7 @@ __DARKLUA_CONTINUE_8=true break end local opacity = (tonumber(l.opacity) or 1) * (tonumber(l.fillOpacity) or 1) local mode = (type(l.blend) == "string" and{l.blend }or{"normal" -})[1] -- the layer's own pixels, as an isolated w x h buffer - local src= nil +})[1] local src= nil if type(l.children) == "table" then if mode == "passThrough" then local before = buffer.create(w * h * 4) @@ -68760,10 +67098,6 @@ __DARKLUA_CONTINUE_8=true break __DARKLUA_CONTINUE_8=true until true if not __DARKLUA_CONTINUE_8 then break end end end --- flatten(layers, canvas, w, h, hidden): composites a Types.Layer tree (bottom to top) onto the w x h rgba8 canvas: --- blend modes, opacity x fillOpacity, groups (isolated, or "passThrough": blended straight onto the canvas, the group --- opacity and mask then mixing before / after), clipping layers (clip = true: source-atop onto the layer below), grey masks. --- hidden = true includes invisible layers. function Blend.flatten(layers, canvas, w, h, hidden) if blen(canvas) >= w * h * 4 then compose(layers, canvas, w, h, hidden) @@ -68777,16 +67111,8 @@ local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 -- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). --- Inverse: libjpeg's islow (jidctint.c: the Loeffler-Ligtenberg-Moschytz algorithm, 13-bit constants, two passes with --- PASS1_BITS of scaling between them), plus the reduced 4x4 / 2x2 / 1x1 IDCTs for scaled decodes (jidctred.c); the --- results match libjpeg-turbo's djpeg bit for bit. Absorbed from jpeg-luau 1.0 src/Jpeg/Idct.luau (same author). --- Forward: libjpeg's islow (jfdctint.c) with jcdctmgr.c's rounding quantiser, so an encoder built on it produces --- the same coefficients as cjpeg. Both are Luau translations of IJG code (licenses/libjpeg-turbo-LICENSE.md). --- Values are exact integers in doubles: no overflow even on corrupt coefficients; outputs are clamped to 0..maxv. --- --- Dct.idctComponent(coef, q, bpl, bpc, size, plane, p1, center, maxv) -- every block of a component --- Dct.idctBlock(coef, off, q, plane, out, stride, p1, center, maxv) -- one 8x8 block (u16 samples) --- Dct.fdctQuantize(src, stride, x, y, w, h, div, coef, off) -- one block from u8 samples +-- 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 @@ -69018,10 +67344,7 @@ local function idct2(coef, off, q, plane, out, stride, p1, center, maxv) end end --- Inverse-transforms every block of a component: coef (i16, 64 per block, natural order) on a bpl x bpc block --- grid, quantisation table q (64 u16, natural order), into plane (u16 samples, (bpl * size) per row) at size x --- size samples per block. p1 is PASS1_BITS (2 for 8-bit, 1 for 12-bit), center the level shift, maxv the top. --- hook (optional): a cooperative yield point after every block row (pcall'ed: it can't throw through here). +-- p1 = PASS1_BITS (2 for 8-bit, 1 for 12-bit) function Dct.idctComponent(coef, q, bpl, bpc, size, plane, p1, center, maxv, hook) local stride = bpl * size for by = 0, bpc - 1 do @@ -69045,13 +67368,10 @@ function Dct.idctComponent(coef, q, bpl, bpc, size, plane, p1, center, maxv, hoo end end --- idctBlock(coef, off, q, plane, out, stride, p1, center, maxv): one 8x8 block, coef (i16, natural order) at byte --- offset off, dequantised by q (64 u16), into the u16 plane at sample index out with stride samples per row function Dct.idctBlock(coef, off, q, plane, out, stride, p1, center, maxv) idct8(coef, off, q, plane, out, stride, p1, center, maxv) end --- ------------------------------------------------------------------------------------------------ forward local fw = table.create(64, 0) local function quant(coef, off, div, v, i) @@ -69064,10 +67384,7 @@ local function quant(coef, off, div, v, i) end end --- fdctQuantize(src, stride, x, y, w, h, div, coef, off): the 8x8 block of u8 samples at (x, y) in src (stride bytes --- per row; samples past w - 1 / h - 1 repeat the edge), level-shifted by 128, forward DCT (jfdctint.c islow), then --- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored, q = div (64 u16, natural order). Writes --- 64 i16 at coef[off] (natural order). The caller keeps x < w, y < h and the src range valid. +-- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored function Dct.fdctQuantize(src, stride, x, y, w, h, div, coef, off) local lastX, lastY = w - 1, h - 1 for r = 0, 7 do @@ -69174,17 +67491,8 @@ __FILES["codecs/image/Etc"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar --- modes), ETC2 RGBA (an EAC alpha block + ETC2 colour), ETC2 RGB A1 (punch-through alpha) and EAC R11 / RG11 --- (unsigned and signed). Written from the Khronos Data Format Specification 1.3, section 21 (ETC1 / ETC2 / EAC); new --- in rosetta. Shared by the texture formats (KTX, PVR, ...). Never throws: the caller gets a message instead. --- --- local px, err = Etc.decode("etc2_rgba", buf, offset, w, h) -- rgba8 pixels --- local px16 = Etc.decode("eac_rg11", buf, offset, w, h, nil, 0, true) -- rgba16 (EAC keeps its 11 bits) --- Etc.size("etc1", w, h) -- bytes of the block data --- --- Kinds: etc1, etc2_rgb, etc2_rgba, etc2_rgba1, eac_r11, eac_r11s, eac_rg11, eac_rg11s. R11 decodes to grey (r = g = b), --- RG11 to red + green (blue 0); signed values are biased (-1 -> 1, 0 -> 128, +1 -> 255; rgba16: 0 / 32768 / 65535). +-- 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 }) ) @@ -69192,7 +67500,6 @@ Etc.BLOCK = (table.freeze({ etc1 = 8, etc2_rgb = 8, etc2_rgba = 16, etc2_rgba1 = 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 --- ------------------------------------------------------------------------------------------------ tables local MOD = { -- the ETC1 intensity modifiers per table: index (msb * 2 + lsb) -> a, b, -a, -b { 2, 8, -2, -8 }, { 5, 17, -5, -17 }, @@ -69230,9 +67537,8 @@ local function rgb(r, g, b) return clamp8(r) + clamp8(g) * 256 + clamp8(b) * 65536 + 0xFF000000 end --- ------------------------------------------------------------------------------------------------ colour blocks -- blk: 16 u32 rgba8 pixels in raster order (y * 4 + x) -local P = table.create(4, 0) -- T / H paint colours (rgba8 u32) +local P = table.create(4, 0) local function be32(src, p) return byteswap(readu32(src, p)) @@ -69243,7 +67549,7 @@ local function pix(lo, i) return band(rshift(lo, i + 15), 2) + band(rshift(lo, i), 1) end --- ETC1 / ETC2 colour block at p into blk. etc2: T / H / planar modes; punch: the RGB A1 variant (bit 33 = opaque). +-- ETC1 / ETC2 colour block; the RGB A1 variant: bit 33 = opaque local function colour(src, p, blk, etc2, punch) local hi, lo = be32(src, p), be32(src, p + 4) local diffBit = band(rshift(hi, 1), 1) @@ -69315,7 +67621,6 @@ local function colour(src, p, blk, etc2, punch) r2, g2, b2 = R2 * 8 + rshift(R2, 2), G2 * 8 + rshift(G2, 2), B2 * 8 + rshift(B2, 2) end if not r1 then - -- T / H: the paint colours by index for i = 0, 15 do local x, y = rshift(i, 2), band(i, 3) local idx = pix(lo, i) @@ -69348,10 +67653,8 @@ local function colour(src, p, blk, etc2, punch) end end --- ------------------------------------------------------------------------------------------------ EAC local VALS = table.create(16, 0) --- the 16 values of the EAC block at p into VALS (raster order): mode "alpha" (8-bit), "u11" / "s11" (11-bit) local function eac(src, p, mode) local base = readu8(src, p) local b1 = readu8(src, p + 1) @@ -69384,7 +67687,6 @@ local function eac(src, p, mode) end end --- 11-bit values -> 8 / 16 bits local function to8(v, signed) if signed then return math.floor(v * 127 / 1023 + 0.5) + 128 @@ -69398,15 +67700,11 @@ if signed then return v * 32 + rshift(v, 6) end --- ------------------------------------------------------------------------------------------------ decode --- size(kind, w, h) -> bytes of the block data | nil for an unknown kind function Etc.size(kind, w, h) local b = Etc.BLOCK[kind] return (b and(((math.floor((w + 3) / 4)) * (math.floor((h + 3) / 4)) * b ))or(nil ))end --- decode(kind, src, offset, w, h, out?, outOffset?, wide?) -> pixels | nil, message. rgba8, or rgba16 for the EAC --- kinds when wide is true. function Etc.decode(kind, src, offset, w, h, out, outOffset, wide) local bytes = Etc.BLOCK[kind] if not bytes then @@ -69491,17 +67789,11 @@ __FILES["codecs/image/Half"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H, --- OpenEXR HALF channels). New in rosetta. Never throws. --- --- local f = Half.TABLE[h] -- the number of every half bit pattern 0..65535 (a 65536-entry table) --- local f = Half.toFloat(h) -- the same, computed --- local h = Half.fromFloat(f) -- round to nearest even; overflow -> infinity, NaN -> a quiet NaN +-- 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 --- toFloat(h) -> number (h a 16-bit pattern) local function toFloat(h) local s = h >= 32768 and-1 or 1 local e = band(rshift(h, 10), 31) @@ -69523,7 +67815,6 @@ Half.TABLE = TABLE local scratch = buffer.create(4) --- fromFloat(f) -> the nearest half bit pattern (ties to even) function Half.fromFloat(f) if f ~= f then return 0x7E00 @@ -69565,36 +67856,9 @@ return Half end __FILES["codecs/image/Jpeg"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG --- video tracks (AVI / Matroska / QuickTime) decode and encode their frames with it. The engine (Huffman and --- arithmetic scan decoding, IDCTs through codecs/image/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder) --- was absorbed from jpeg-luau 1.0 (same author) into image/jpeg and moved down here; it is bit-exact with libjpeg-turbo's --- djpeg and byte-identical with cjpeg. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md. --- --- local img, err = Jpeg.decode(buf, off?, len?, opts?) -- one JPEG -> rgba8 (or gray8 / yuv420p) Types.Image --- local img = Jpeg.decode(frame, 0, n, { yuv = true }) -- video: yuv420p straight from the IDCT planes --- local out, err = Jpeg.encode(img, opts?) -- rgba8 / rgb8 / gray8 / yuv420p Image -> buffer --- local info, err = Jpeg.info(buf, off?, len?) -- the headers up to the frame header --- --- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit --- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt --- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8), EXIF orientation --- (meta.orientation, applied with opts.orient). Truncated or corrupt scans decode as far as they go --- (meta.truncated = true). --- Motion-JPEG: frames without DHT segments use the T.81 annex K tables; the AVI1 APP0 segment is read (its field --- polarity) and data after EOI is ignored. Two fields back to back (AVI1 interlaced: two JPEGs of half the frame --- height, polarity 1 or 2, or opts.fields = true) are decoded and woven into one frame, the first field on the even --- rows (top field first, as ffmpeg, which ignores the polarity value); a missing or different-sized second field --- leaves the first field alone (meta.source.fields = 1). --- opts.yuv: 8-bit YCbCr frames come out as yuv420p (full-range BT.601, meta.source.range = "full") without colour --- conversion or upsampling: 4:2:0 (2x2 luma) as the planes are; 4:2:2 (2x1 luma, the usual Motion-JPEG camera --- layout) with each pair of chroma rows averaged; 4:4:4 with 2 x 2 chroma averages; grey with chroma 128. Other --- layouts (RGB, CMYK, 4:1:1, 4:4:0, 12-bit) and scaled decodes fall back to rgba8 (check img.format). --- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or --- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, extra APPn / COM segments --- (opts.segments); yuv420p input is coded from its planes as they are (4:2:0, no colour conversion). --- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, 12-bit or CMYK encoding. --- Never throws: bad data or arguments return nil, Err. +-- 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") @@ -69636,9 +67900,6 @@ local Jpeg = {} - - - @@ -69649,7 +67910,6 @@ local n = buffer.len(buf) return o, math.clamp(math.floor(tonumber(len) or (n - o)), 0, n - o) end --- the marker parser over [o, o + l): State | nil, Err local function parse(buf, o, l, opts, headerOnly) local ok, st, code, msg = pcall(Decode.parse, buf, o, o + l, opts, headerOnly) if not ok then @@ -69669,7 +67929,6 @@ local sampling = {} return sampling end --- info(buf, off?, len?) -> Info | nil, Err (reads the headers up to the frame header) function Jpeg.info(buf, off, len) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "expected a buffer") @@ -69697,7 +67956,6 @@ if type(buf) ~= "buffer" then nil end --- the EXIF orientation applied to rgba8 pixels: buffer, width, height local function orient(px, w, h, o) if o <= 1 or o > 8 then return px, w, h @@ -69730,7 +67988,6 @@ if o <= 1 or o > 8 then return out, ow, oh end --- one JPEG at [o, o + l): Image, State | nil, Err local function decodeOne(buf, o, l, opts) local st, err = parse(buf, o, l, opts, false) if not st then @@ -69797,14 +68054,14 @@ local img = Types.Image.new(0, 0) adobe = s.adobe, jfif = s.jfif, avi1 = s.avi1, - yuv = mode, -- "420" | "422" | "444" | "gray": how the yuv420p planes were made (opts.yuv) + yuv = mode, range = mode and"full" or nil, fields = 1, } return img, s end --- the start of a second JPEG (FF D8 FF) at or after p, before e; -1 if none +-- the start of a second JPEG: FF D8 FF local function nextSoi(buf, p, e) local readu8 = buffer.readu8 while p + 3 <= e do @@ -69816,7 +68073,6 @@ local readu8 = buffer.readu8 return -1 end --- two fields (same size and format) -> one frame of twice the height, field a on the even rows local function weave(a, b) local w, hf = a.width, a.height local h = hf * 2 @@ -69824,7 +68080,7 @@ local w, hf = a.width, a.height local dst = out.pixels if a.format == "yuv420p" then local cw, chf = math.floor((w + 1) / 2), math.floor((hf + 1) / 2 -) local ch = math.floor((h + 1) / 2 -- = hf +) local ch = math.floor((h + 1) / 2 ) Yuv.weave(a.pixels, 0, b.pixels, 0, w, h, dst, 0) for k = 0, 1 do Yuv.weave(a.pixels, w * hf + k * cw * chf, b.pixels, w * hf + k * cw * chf, cw, ch, dst, w * h + k * cw * ch) @@ -69837,7 +68093,6 @@ local w, hf = a.width, a.height return out end --- decode(buf, off?, len?, opts?) -> Image | nil, Err: one JPEG (or one interlaced Motion-JPEG frame) in [off, off + len) function Jpeg.decode(buf, off, len, opts) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "expected a buffer") @@ -69873,10 +68128,8 @@ if o2.maxPixels then return img, nil end --- ------------------------------------------------------------------------------------------------ encode local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, yuv420p = 0 } --- encode(img, opts?) -> buffer | nil, Err: an rgba8 / rgb8 / gray8 / yuv420p Image as a baseline or progressive JPEG function Jpeg.encode(img, opts) if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then return nil, Err.new(Err.ARG, "needs an Image") @@ -69959,15 +68212,9 @@ __FILES["codecs/image/Jpeg/Arith"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/image/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised --- DCT coefficients (native; never throws). A Luau translation of libjpeg-turbo's jdarith.c (Guido Vollbeding's --- decoder, IJG licence: licenses/libjpeg-turbo-LICENSE.md) and the jaricom.c probability table. --- --- It reads the destuffed scan data that Scan.destuff produces (0xFF 0x00 already removed, RSTn positions recorded); --- past the end of a restart segment it reads zero bytes, the convention libjpeg follows when the decoder runs into a --- marker (libjpeg's encoder also drops trailing zero bytes, so reading past the end is normal and not a sign of --- truncation: the caller flags a scan that runs into the end of the file instead). Statistics bins live in one buffer: DC tables at [t * 64], AC tables at [256 + t * 256], the fixed 0.5 --- bin at [1280]. +-- 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 @@ -70008,7 +68255,7 @@ do end end -local ZZ= buffer.create(80) -- set by Arith.init (Scan.ZIGZAG) +local ZZ= buffer.create(80) local STATS = 1281 local POW2 = buffer.create(8) @@ -70017,11 +68264,10 @@ for i = 0, 7 do end local FIXED = 1280 --- decoder state (one scan at a time; never yields) local D= buffer.create(0) -local P = 0 -- next byte -local SEGEND = 0 -- reads at or past this return 0 -local OVER = 0 -- zero bytes supplied past the end +local P = 0 +local SEGEND = 0 +local OVER = 0 local C, A, CT = 0, 0, -16 local st= buffer.create(STATS) @@ -70081,7 +68327,7 @@ v = band(v, 0xFFFF) return (v >= 0x8000 and((v - 0x10000 ))or(v ))end --- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24); returns the new predictor or nil on a bad code +-- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24) @@ -70152,7 +68398,7 @@ local base = c.dcTbl * 64 return band(c.pred + v, 0xFFFF) end --- AC coefficients k = ss..se of one block (figure F.20); false on a bad code +-- AC coefficients k = ss..se of one block (figure F.20) local function acFirst(coef, off, tbl, ss, se, K, mul) local base = 256 + tbl * 256 local k = ss @@ -70250,7 +68496,6 @@ function Arith.init(zigzag) ZZ = zigzag end --- run(d, cleanLen, rst, nrst, P) -> truncated: decodes one scan (see Scan.run for the data layout) function Arith.run(d, cleanLen, rst, nrst, Pm) local comps = Pm.comps local nc = #comps @@ -70375,19 +68620,9 @@ __FILES["codecs/image/Jpeg/Color"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- codecs/image/Jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never --- throws). Absorbed from jpeg-luau 1.0 src/Jpeg/Color.luau (same author); a Luau translation of libjpeg-turbo's --- jdsample.c / jdcolor.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md). --- --- Upsampling follows libjpeg-turbo's jdsample.c, so the output matches djpeg's defaults: --- FULL the component is at output resolution --- H2V1 "fancy" triangle filter, 3/4 nearer + 1/4 further sample, alternating rounding (1, 2) / 4 --- H2V2 fancy in both directions: vertical 3:1 column sums, then horizontal 3:1, rounding (8, 7) / 16 --- H1V2 fancy vertical only, rounding 1 (upper row) / 2 (lower row) --- REPLICATE any other ratio (or no fancy upsampling): nearest sample, as int_upsample --- Edges replicate the last real sample (downW x downH), as libjpeg does with its context rows. --- Colour conversion is jdcolor.c's table-driven YCbCr -> RGB (16-bit fixed point), plus grey, RGB, CMYK and --- YCCK (Adobe inverted CMYK: R = C * K / 255). +-- 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 @@ -70405,7 +68640,7 @@ Color.RGB = 2 Color.CMYK = 3 Color.YCCK = 4 Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted -Color.RAW = 6 -- no conversion: components 1..4 as R, G, B, A (opts.raw: BLP1's BGRA JPEGs, ...) +Color.RAW = 6 -- jdcolor.c build_ycc_rgb_table @@ -70435,7 +68670,6 @@ Color.RAW = 6 -- no conversion: components 1..4 as R, G, B, A (opts.raw: BLP1's - function Color.tables(maxv) @@ -70455,7 +68689,6 @@ return math.floor(x * 65536 + 0.5) return crr, cbb, crg, cbg end --- fills c.row with output row y; returns the buffer and byte offset of the row's samples local function fetch(c, y, outW) local method = c.method local plane, stride, row = c.plane, c.stride, c.row @@ -70571,7 +68804,6 @@ local __DARKLUA_CONTINUE_6=false repeat if hook and y > 0 and y % 8 == 0 then __DARKLUA_CONTINUE_6=true break end if space == 1 and not toByte then - -- the common case: 8-bit YCbCr 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) @@ -70623,12 +68855,9 @@ return Color end __FILES["codecs/image/Jpeg/Decode"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- codecs/image/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan / --- Arith / Dct / Color / Yuv loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended: --- arithmetic-coded frames (SOF9 / SOF10, DAC), a byte range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM --- / JFIF density collected for meta, the AVI1 APP0 field polarity and the end of the image (Motion-JPEG), and a --- yuv420p output straight from the IDCT planes (outputYuv). The IDCT size choice for scaled decodes follows --- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/image/Jpeg/Decode for the video formats. +-- 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") @@ -70660,7 +68889,7 @@ local key = class .. slot return stdBuilt[key] end --- the EXIF TIFF block (after "Exif\0\0") and its orientation tag, from an APP1 segment at [p, e) +-- the EXIF TIFF block (after "Exif\0\0") and its orientation tag local function exif(b, p, e) if e - p < 14 or buffer.readstring(b, p, 6) ~= "Exif\0\0" then return nil, nil @@ -70748,7 +68977,6 @@ local SOF_REFUSED = { [0xCF] = "hierarchical arithmetic-coded", } --- failures carry a code: "corrupt" | "unsupported" | "limit" | "truncated" local function parseSof(b, p, e, m) if e - p < 6 then return nil, "corrupt", "short SOF" @@ -70842,8 +69070,6 @@ local minSize = math.floor(8 / scale return ssize end --- parse(b, base, limit, opts, headerOnly) -> State | nil, code, message. Walks the markers in b[base, limit); with --- headerOnly it stops at the frame header, otherwise it decodes every scan into the components' coefficients. @@ -71211,7 +69437,6 @@ end local toByte12= nil --- output(st) -> width, height, rgba8 pixels, colour space | nil, code, message function Decode.output(st) local f= st.frame local scale = st.scale @@ -71266,7 +69491,7 @@ local f= st.frame vOut = vOut, row = buffer.create((math.max(outW, 2 * stride) + 8) * 2), }) - c.coef = nil -- free the coefficients early + c.coef = nil end local space = colorSpaceOf(f, st.adobe, st.jfif) local spaceId = SPACE_IDS[space] @@ -71306,14 +69531,8 @@ local f= st.frame return outW, outH, pixels, space end --- outputYuv(st) -> width, height, yuv420p pixels, sampling | nil when the frame has no direct yuv420p form (the --- caller falls back to output). The IDCT output planes as they are, cropped to the image, without colour conversion --- or upsampling: 8-bit YCbCr whose chroma is sampled at half the luma rate both ways ("420", 2x2 / 1x1); half --- horizontally ("422", 2x1 / 1x1 or ffmpeg's 2x2 / 1x2: each pair of chroma rows averaged, rounding up); at the luma --- rate ("444", 1x1 or ffmpeg's 1x2 everywhere: each 2 x 2 chroma block averaged, rounding to nearest); grey ("gray": --- chroma 128). Full scale only (opts.scale = 1). --- one IDCT plane at a time is live (each is cropped into the output before the next component): frame-sized planes --- (up to 4 MB) are kept between calls, so a stream of video frames does not allocate them per frame +-- outputYuv: 4:2:0, 4:2:2 (chroma row pairs averaged, rounding up), 4:4:4 (2 x 2 averaged, rounding to nearest) or grey +-- (chroma 128) straight from the IDCT planes; full scale only local scratch= nil local function scratchPlane(n) local sc = scratch @@ -71358,7 +69577,7 @@ local f= st.frame end for _, c in __iter(comps) do if c.coef and not c.quant then - return nil, nil, nil, nil -- output() reports the missing table + return nil, nil, nil, nil end end local w, h = f.width, f.height @@ -71398,14 +69617,9 @@ __FILES["codecs/image/Jpeg/Encode"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/image/Jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman --- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr --- 4:4:4 / 4:2:2 / 4:2:0, or yuv420p planes coded as they are (4:2:0, no colour conversion: the Motion-JPEG --- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/image/Jpeg/Encode. It follows libjpeg-turbo's --- encoder step for step so that its output is byte-identical to cjpeg's for the same settings: jccolor.c --- (fixed-point RGB -> YCbCr), jcsample.c (box downsampling with alternating rounding bias, right-edge replication), --- jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c (codecs/image/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs, --- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md. +-- 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") @@ -71435,7 +69649,6 @@ do end Encode.ZIGZAG = ZZ --- ------------------------------------------------------------------------------------------------ output local OUT = buffer.create(0) local OP = 0 local CAP = 0 @@ -71496,7 +69709,6 @@ end local function nbits(v) return v == 0 and 0 or 32 - countlz(v) end --- ------------------------------------------------------------------------------------------------ Huffman tables -- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl) @@ -71619,7 +69831,6 @@ end end end Encode.optimal = optimal --- ------------------------------------------------------------------------------------------------ entropy coding state local dcTab= {} local acTab= {} local dcFreq= {} @@ -71776,7 +69987,7 @@ local function blockAcRefine(c, off, ss, se, al) end end local r = 0 - local br = 0 -- correction bits added in this block, at CORR[brStart + 1 ..] + local br = 0 local brStart = BE for k = ss, se do local __DARKLUA_CONTINUE_28=false repeat local t = absv[k + 1] @@ -71821,8 +70032,6 @@ __DARKLUA_CONTINUE_28=true until true if not __DARKLUA_CONTINUE_28 then break en end end end --- ------------------------------------------------------------------------------------------------ scans --- iterate the scan's MCUs (or blocks, for one component), calling fn(c, off) per block; restart markers when ri > 0 @@ -71887,7 +70096,6 @@ local function sos(comps, ss, se, ah, al, dcOnly, acOnly) byte(ah * 16 + al) end --- ------------------------------------------------------------------------------------------------ planes -- jccolor.c rgb_ycc_start tables (16-bit fixed point) local function fix(x) return math.floor(x * 65536 + 0.5) @@ -71897,7 +70105,6 @@ 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 --- pixels (rgba8 / rgb8 / gray8) -> Y, Cb, Cr planes (w * h bytes each; Cb / Cr nil for grey output) local function planes(px, w, h, bpp, gray) local n = w * h local Y = buffer.create(n) @@ -71931,8 +70138,7 @@ local n = w * h return Y, Cb, Cr end --- jcsample.c: a full-resolution plane (w x h) -> the component's samples, (bw * 8) x ch, for factors hf x vf --- (1 or 2 each); full-resolution columns past w - 1 repeat the last one, rows past h - 1 the last row +-- jcsample.c downsampling: columns past w - 1 repeat the last one, rows past h - 1 the last row local function downsample(src, w, h, hf, vf, outW, outH) local out = buffer.create(outW * outH) for oy = 0, outH - 1 do @@ -71958,10 +70164,6 @@ local out = buffer.create(outW * outH) end return out end --- ------------------------------------------------------------------------------------------------ encode --- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8), or bpp 0: --- yuv420p (w * h luma, then ceil(w / 2) * ceil(h / 2) Cb and Cr; opts.sampling must be "420" unless opts.gray). The --- caller validated sizes (1..65535), the buffer length and options. @@ -72016,7 +70218,6 @@ OUT = buffer.create(math.max(1024, math.floor(w * h / 2))) qdiv[t] = b end - -- components and their quantised coefficients local comps= {} local srcs = o.gray and{ Y } or{ Y, Cb , Cr } for i, src in __iter(srcs) do @@ -72065,7 +70266,6 @@ OUT = buffer.create(math.max(1024, math.floor(w * h / 2))) comps[i] = c end - -- headers byte(0xFF) byte(0xD8) if o.jfif then @@ -72242,7 +70442,6 @@ if isDc and ah == 0 then walk(sComps, mcusX, mcusY, o.restart, onRestart, blockFn) emitEobrun() end - -- gather statistics, then emit the optimal tables this scan uses if not (isDc and ah > 0) then GATHER = true for t = 1, ntab do @@ -72299,16 +70498,8 @@ __FILES["codecs/image/Jpeg/Scan"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/image/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from --- jpeg-luau 1.0 src/Jpeg/Scan.luau (same author); unchanged but for this header. --- --- `destuff` copies one scan's entropy-coded bytes into a clean buffer: it drops the stuffed 0x00 after each 0xFF, --- records where each RSTn marker fell, and stops at any other marker. The clean buffer is followed by at least --- PAD zero bytes, so the bit reader can read 32 bits at any position up to PAD bytes past the end without a --- bounds check. `run` checks the position once per MCU, and no MCU (at most 10 blocks, enforced by the parser) --- can consume PAD bytes. So every buffer index stays in range, even on garbage data. --- --- The bit reader keeps no state but a bit position: `peek` reads the big-endian 32-bit word that holds it. +-- 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 @@ -72356,8 +70547,7 @@ do end Scan.ZIGZAG = ZZ --- Builds a Huffman table from the 16 code-length counts and the symbols (Luau arrays, 1-based). An --- over-subscribed table keeps the codes that fit; the rest decode as invalid. +-- an over-subscribed table keeps the codes that fit; the rest decode as invalid function Scan.buildTable(counts, symbols) local t = buffer.create(Scan.TABLE_SIZE) local code, k = 0, 0 @@ -72385,7 +70575,6 @@ local t = buffer.create(Scan.TABLE_SIZE) writeu8(t, T_VAL + i - 1, symbols[i]) end writeu16(t, T_COUNT, k) - -- fast lookups for i = 1, k do local l = sizes[i] if l <= 9 then @@ -72408,9 +70597,6 @@ local t = buffer.create(Scan.TABLE_SIZE) return t end --- Copies the entropy-coded data at src[pos..n) into dst (at least n - pos + PAD bytes): byte stuffing removed, --- RSTn offsets (in dst) stored in rst[1..]. Returns the source position of the marker that ended the scan (or n), --- the clean length, and the RST count. The PAD bytes after the clean data are zeroed. function Scan.destuff(src, pos, n, dst, rst) local o, nr = 0, 0 while pos < n do @@ -72468,7 +70654,6 @@ local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) return readu8(t, T_VAL + idx), pos + l end --- the next s bits (1 <= s <= 16) as an unsigned number local function bits(d, pos, s) return rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 32 - s) end @@ -72480,7 +70665,6 @@ if v < lshift(1, s - 1) then return v end --- sequential (baseline / extended) block: returns pos, DC predictor local function blockSeq(d, pos, coef, off, dct, act, pred) local s s, pos = huff(d, pos, dct) @@ -72651,8 +70835,6 @@ local bit = lshift(1, al) return pos, eobrun end --- Decodes one scan from the clean data d (cleanLen bytes, then PAD zeros). Returns the final bit position and --- whether the data ran out (or overran) before the last MCU. @@ -72824,7 +71006,6 @@ Tables.CHROMA = { 99, 99, 99, 99, 99, 99, 99, 99, } --- quant(base, quality) -> 64 values (natural order) for quality 1..100, clamped to 1..255 (baseline) function Tables.quant(base, quality) local q = math.clamp(math.floor(quality), 1, 100) local scale = (q < 50 and{(math.floor(5000 / q ))}or{(200 - q * 2 @@ -72841,23 +71022,18 @@ __FILES["codecs/image/Jpeg/Yuv"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- codecs/image/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16 --- samples, block-padded) cropped into u8 yuv420p planes without colour conversion or upsampling, 4:2:2 / 4:4:4 --- chroma reduced to 4:2:0 by averaging, and the interleaving of two fields (AVI1 interlaced Motion-JPEG). --- The callers (codecs/image/Jpeg/Decode, codecs/image/Jpeg) size every buffer; each loop reads and writes inside those sizes. +-- 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 = {} --- crop(src, stride, w, h, dst, doff): the top-left w x h samples of a u16 plane (stride samples per row) into u8 --- samples at dst[doff], w per row function Yuv.crop(src, stride, w, h, dst, doff) local quads = math.floor(w / 4 ) local rest = w - quads * 4 for y = 0, h - 1 do local s = y * stride * 2 local d = doff + y * w - -- four samples (two u32 reads of two u16 samples, each 0..255) per u32 write for _ = 1, quads do local a, b = readu32(src, s), readu32(src, s + 4) writeu32(dst, d, a % 65536 + (math.floor(a / 65536)) * 256 + (b % 65536) * 65536 + (math.floor(b / 65536)) * 16777216) @@ -72870,8 +71046,6 @@ function Yuv.crop(src, stride, w, h, dst, doff) end end --- rows(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:2:2 chroma) -> u8 w x ceil(h / 2), each output --- row the rounded mean of two source rows (the last row alone when h is odd) function Yuv.rows(src, stride, w, h, dst, doff) local oh = math.floor((h + 1) / 2 ) for y = 0, oh - 1 do @@ -72884,8 +71058,6 @@ function Yuv.rows(src, stride, w, h, dst, doff) end end --- box(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:4:4 chroma) -> u8 ceil(w / 2) x ceil(h / 2), --- each output sample the rounded mean of a 2 x 2 block (edges repeat the last row / column) function Yuv.box(src, stride, w, h, dst, doff) local ow, oh = math.floor((w + 1) / 2), math.floor((h + 1) / 2 ) for y = 0, oh - 1 do @@ -72900,8 +71072,6 @@ function Yuv.box(src, stride, w, h, dst, doff) end end --- weave(top, toff, bottom, boff, rowBytes, rows, dst, doff): interleave rows of two planes (field 1 on the even rows, field --- 2 on the odd rows) into rows output rows at dst[doff]; top holds ceil(rows / 2) rows, bottom floor(rows / 2) function Yuv.weave(top, toff, bottom, boff, rowBytes, rows, dst, doff) for y = 0, rows - 1 do local k = math.floor(y / 2 @@ -72919,21 +71089,13 @@ __FILES["codecs/image/Pixels"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP, --- the DIBs inside ICO / CUR, ...): 1 / 2 / 4 / 8-bit indexes through a palette, BGR / BGRA, 5-5-5, bit-masked 16 / --- 24 / 32-bit pixels, RLE4 / RLE8, rows bottom-up or top-down; and the encoder direction (rgba8 -> BGR / BGRA / --- 8-bit indexes, bottom-up). Absorbed from bmp-luau b86aed6 (same author, no third-party code); the encoder loops --- are new. They never throw: the caller validates every size first and hands in a source buffer that holds every --- byte an uncompressed loop can read (a truncated file is copied into a zero-padded buffer); the RLE loop checks each --- read against its end offset. Output: rgba8, top-down rows, one u32 per pixel (bytes R, G, B, A). +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. +-- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8. From bmp-luau b86aed6 (same author); the encoder loops are new. local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift local Pixels = {} --- palette(src, base, n, bgr?) -> a 256-entry u32 palette for indexed(): n RGB triples (BGR when bgr) at src[base..], --- opaque; entries past n (or past the end of src) are opaque black. The game formats' 768-byte palettes (PLAYPAL, --- Quake palette.lmp, Half-Life MDL / WAD3 / BSP 30 textures). function Pixels.palette(src, base, n, bgr) local pal = buffer.create(1024) local m = (base >= 0 and{(math.clamp(math.min(n, math.floor((buffer.len(src) - base) / 3)), 0, 256) )}or{0 @@ -72952,7 +71114,6 @@ local pal = buffer.create(1024) return pal end --- 1, 2, 4 and 8 bpp through a 256-entry u32 palette (pal) function Pixels.indexed(src, base, stride, bpp, dst, w, h, topDown, pal) local mask = lshift(1, bpp) - 1 @@ -73006,7 +71167,7 @@ function Pixels.bgr24(src, base, stride, dst, w, h, topDown) end end --- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks). Returns the OR of every alpha byte. +-- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks) function Pixels.bgra32(src, base, stride, dst, w, h, topDown) local aor = 0 @@ -73015,7 +71176,6 @@ local aor = 0 local d = ((topDown and{r }or{(h - 1 - r)})[1]) * w * 4 for x = 0, w - 1 do local p = readu32(src, so + x * 4) - -- swap R and B: B G R A -> R G B A writeu32(dst, d + x * 4, bor(band(p, 0xFF00FF00), band(rshift(p, 16), 0xFF), lshift(band(p, 0xFF), 16))) aor = bor(aor, p) end @@ -73023,9 +71183,6 @@ local aor = 0 return rshift(aor, 24) end --- 16 / 24 / 32 bpp through bit masks. sh* = shift of each mask, m* = mask >> shift, t* = scale tables (u8, one entry --- per masked value). A channel without a mask has m = 0 and a 1-entry table (0 for colour, 255 for alpha). --- Returns the OR of every masked alpha value (before scaling). function Pixels.masked(src, base, stride, bpp, dst, w, h, topDown, shr, mr, tr, shg, mg, tg, shb, mb, tb, sha, ma, ta) @@ -73056,16 +71213,14 @@ local bytes = rshift(bpp, 3) return aor end --- Sets every alpha byte to 255 (32-bit images whose alpha channel is all zero are opaque). +-- 32-bit images whose alpha channel is all zero are opaque function Pixels.opaque(dst, n) for i = 0, n - 1 do writeu8(dst, i * 4 + 3, 255) end end --- RLE8 / RLE4 from src[pos, stop) into dst (pre-filled with transparent black; pixels the stream skips with a --- delta, an early end of line or an early end of bitmap stay transparent). Malformed or truncated data stops the --- decode and keeps what was drawn. Returns the number of pixels written. +-- RLE8 / RLE4: pixels skipped by a delta or an early end of line / bitmap stay transparent function Pixels.rle(src, pos, stop, rle4, dst, w, h, topDown, pal) local x, y = 0, 0 @@ -73139,7 +71294,6 @@ local x, y = 0, 0 return written end --- Encoder: rgba8 (top-down) -> 24 bpp BGR rows, bottom-up, each padded to stride (dst is zero-filled) function Pixels.encode24(src, w, h, dst, base, stride) for y = 0, h - 1 do local s = y * w * 4 @@ -73154,20 +71308,17 @@ function Pixels.encode24(src, w, h, dst, base, stride) end end --- rgba8 -> 32 bpp BGRA, bottom-up function Pixels.encode32(src, w, h, dst, base) for y = 0, h - 1 do local s = y * w * 4 local d = base + (h - 1 - y) * w * 4 for x = 0, w - 1 do local v = readu32(src, s + x * 4) - -- R G B A (little-endian u32: R | G << 8 | B << 16 | A << 24) -> B G R A writeu32(dst, d + x * 4, bor(band(v, 0xFF00FF00), band(rshift(v, 16), 255), lshift(band(v, 255), 16))) end end end --- rgba8 -> 8 bpp indexes through idx (a table colour -> index, colours as R | G << 8 | B << 16), bottom-up function Pixels.encode8(src, w, h, dst, base, stride, idx) for y = 0, h - 1 do local s = y * w * 4 @@ -73178,8 +71329,6 @@ function Pixels.encode8(src, w, h, dst, base, stride, idx) end end --- colours(src, n, max) -> the distinct RGB colours in first-appearance order (R | G << 8 | B << 16), whether any --- alpha is below 255; stops counting at max + 1 colours function Pixels.colours(src, n, max) local seen= {} local list= {} @@ -73204,20 +71353,9 @@ __FILES["codecs/image/Quantize"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native --!optimize 2 --- codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette --- writer) builds on it. New code: Heckbert's median cut and Gervautz-Purgathofer octree, both over a 5-bit-per-channel --- weighted histogram (palette colours are the exact means of the pixels they cover), nearest-colour mapping with --- optional Floyd-Steinberg error diffusion. Deterministic: the same palette and indexes on every runtime (no table --- iteration order is ever relied on). --- --- local pal, exact = Quantize.palette(pixels, w, h, 256, { method = "mediancut" }) -- { {r, g, b, 255} }, boolean --- local idx = Quantize.map(pixels, w, h, pal, { dither = true, transparentIndex = 255 }) -- buffer of w * h u8 --- --- Pixels with alpha < 128 are "transparent": palette() ignores them, map() gives them opts.transparentIndex (0-based) --- when set (otherwise they map like opaque pixels). When the opaque pixels have at most maxColors distinct colours, --- palette() returns exactly those (in first-seen order) and exact = true, and map() is then lossless. The octree --- folds whole nodes, so it may return fewer than maxColors entries; below 8 colours median cut is used instead. --- Never throws: bad arguments give an empty palette / a zero-filled index buffer. +-- 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 @@ -73236,7 +71374,6 @@ local Quantize = {} local BINS = 32768 -- 5 bits per channel --- ------------------------------------------------------------------------------------------------ helpers local function count(pixels, n) -- per bin: u32 count; f64 sums of r, g, b local cnt = buffer.create(BINS * 4) @@ -73271,7 +71408,6 @@ local n, r, g, b = 0, 0, 0, 0 return { floor(r / n + 0.5), floor(g / n + 0.5), floor(b / n + 0.5), 255 } end --- ------------------------------------------------------------------------------------------------ median cut local function medianCut(cnt, sums, maxColors) local bins= {} for bin = 0, BINS - 1 do @@ -73282,7 +71418,6 @@ local bins= {} if #bins == 0 then return {} end - -- boxes: { lo, hi } ranges of the bins array local boxes= {} local function channel(bin, c) if c == 0 then @@ -73292,8 +71427,7 @@ if c == 0 then end return bin % 32 end - local function stats(box) -- returns the widest channel, its range, the pixel count - + local function stats(box) local mins, maxs = { 31, 31, 31 }, { 0, 0, 0 } local n = 0 for i = box[1], box[2] do @@ -73367,11 +71501,10 @@ for i, box in __iter(boxes) do return pal end --- ------------------------------------------------------------------------------------------------ octree --- over the histogram bins: 5 levels (one bit of each channel per level). Nodes are array slots. +-- octree over the histogram bins: 5 levels, one bit of each channel per level local function octree(cnt, sums, maxColors) local child= {} -- node * 8 + k -> node (0 = none) - local n= {} -- pixel count + local n= {} local sr, sg, sb= {}, {}, {} local leaf= {} local level= {} @@ -73380,7 +71513,7 @@ local child= {} -- node * 8 + k -> node (0 = none) for k = 1, 8 do child[k] = 0 end - local byLevel= { {}, {}, {}, {}, {} } -- inner nodes per level 0..4, creation order + local byLevel= { {}, {}, {}, {}, {} } table.insert(byLevel[1], 1) local leaves = 0 for bin = 0, BINS - 1 do @@ -73417,8 +71550,7 @@ local child= {} -- node * 8 + k -> node (0 = none) end end -- fold the deepest inner nodes (fewest pixels first, ties by creation order) until few enough leaves remain - local function fold(node) -- merges the children (all leaves) into node; returns how many leaves disappeared - + local function fold(node) local merged = 0 for k = 1, 8 do local slot = (node - 1) * 8 + k @@ -73467,7 +71599,6 @@ if a[2] ~= b[2] then leaves =leaves- fold(e[1]) end end - -- collect leaves depth first in child order local pal= {} local function walk(node) if leaf[node] then @@ -73492,15 +71623,12 @@ if a[2] ~= b[2] then return pal end --- ------------------------------------------------------------------------------------------------ palette --- palette(pixels, w, h, maxColors, opts?) -> palette, exact function Quantize.palette(pixels, w, h, maxColors, opts) if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 then return {}, false end local maxc = math.clamp(floor(tonumber(maxColors) or 256), 1, 65536) local npx = w * h - -- exact colours, in first-seen order (stops counting past maxColors) local seen= {} local exact= {} local over = false @@ -73530,8 +71658,6 @@ if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < return medianCut(cnt, sums, maxc), false end --- ------------------------------------------------------------------------------------------------ map --- map(pixels, w, h, palette, opts?) -> buffer of w * h palette indexes (0-based) function Quantize.map(pixels, w, h, palette, opts) if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 or type(palette) ~= "table" then return buffer.create(0) @@ -73540,7 +71666,6 @@ if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < local out = buffer.create(npx) local dither = opts and opts.dither or false local tidx = opts and opts.transparentIndex - -- the searchable entries (the transparent slot is excluded) local pr, pg, pb, pi= {}, {}, {}, {} for i, c in __iter(palette) do if tidx == nil or i - 1 ~= tidx then @@ -73565,7 +71690,7 @@ for k = 1, np do end pr, pg, pb, pi = r2, g2, b2, i2 end - local startAt = table.create(256, np) -- the first entry with green >= g (1-based), np + 1 past the end + local startAt = table.create(256, np) do local k = 1 for g = 0, 255 do @@ -73634,7 +71759,6 @@ local key = r * 65536 + g * 256 + b end return out end - -- Floyd-Steinberg: error rows (f64 r, g, b per pixel, one extra pixel each side) local rowLen = (w + 2) * 24 local cur, nxt = buffer.create(rowLen), buffer.create(rowLen) for y = 0, h - 1 do @@ -73672,13 +71796,12 @@ local key = r * 65536 + g * 256 + b return out end --- quantize(pixels, w, h, maxColors, opts?) -> indexes, palette, exact: palette() then map() (opts of both) function Quantize.quantize(pixels, w, h, maxColors, opts) local pal, exact = Quantize.palette(pixels, w, h, maxColors, opts) local mo = opts if exact and opts and opts.dither then mo = table.clone(opts) - mo.dither = false -- nothing to diffuse + mo.dither = false end return Quantize.map(pixels, w, h, pal, mo), pal, exact end @@ -73689,29 +71812,9 @@ __FILES["codecs/image/Raster"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native --!optimize 2 --- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine --- transform, with the nonzero and even-odd fill rules, plus a polygon stroker. Used by the fonts (glyph outlines) and --- by vector/svg. New code; the coverage accumulation is the signed-area method of font-rs (Raph Levien, Apache-2.0 / --- MIT, an algorithm description, no code copied) and of stb_truetype v2: every edge adds its exact signed area to an --- accumulation row; a running sum along the row gives the winding coverage of each pixel. The rules map the summed --- coverage a as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2. --- --- local R = require("rosetta.codecs.image.Raster") --- local p = R.path():moveTo(0, 0):lineTo(10, 0):quadTo(10, 10, 0, 10):close() -- or a plain command list: --- local cmds = { { op = "moveTo", 0, 0 }, { op = "lineTo", 10, 0 }, { op = "cubicTo", 12, 2, 12, 8, 10, 10 }, --- { op = "close" } } -- (the Font:outline() format) --- local m = R.mask(cmds, { transform = { 2, 0, 0, 2, 5, 5 }, rule = "evenodd", clip = { 0, 0, 64, 64 } }) --- -- m = { x, y, width, height, coverage: buffer (u8, width * height) } in device pixels, or nil when empty --- R.fill(img, cmds, { 255, 0, 0, 255 }, { transform = t }) -- composite onto an rgba8 Image (source over) --- R.fill(img, cmds, function(x, y) return r, g, b, a end) -- a paint function per covered pixel (gradients) --- local outline = R.stroke(cmds, { width = 2, join = "round", cap = "butt" }) -- a path to fill (nonzero) --- --- Transforms are { a, b, c, d, e, f } (SVG matrix order): x' = a x + c y + e, y' = b x + d y + f. Coordinates are --- pixels with y down; a pixel (i, j) covers [i, i+1) x [j, j+1). Curves are flattened in device space to --- opts.tolerance (default 0.1 px). Subpaths are implicitly closed for filling. --- --- Never throws: malformed commands (missing or non-number operands) are skipped, non-finite coordinates drop the --- edge, sizes are bounded by opts.maxPixels (default 2^26), so it is safe for native code and untrusted paths. +-- 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 @@ -73733,10 +71836,9 @@ local bcreate = buffer.create local LIMIT = 1e7 -- coordinates beyond this (device pixels) are treated as broken --- ------------------------------------------------------------------------------------------------ transforms +-- 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 }) --- multiply(m, n) -> m * n (apply n first, then m) function Raster.multiply(m, n) return { m[1] * n[1] + m[3] * n[2], @@ -73757,7 +71859,6 @@ function Raster.rotate(radians) local c, s = math.cos(radians), math.sin(radians) return { c, s, -s, c, 0, 0 } end --- invert(m) -> m^-1 | nil (singular) function Raster.invert(m) local det = m[1] * m[4] - m[2] * m[3] if det == 0 or det ~= det then @@ -73767,17 +71868,13 @@ local det = m[1] * m[4] - m[2] * m[3] 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 --- apply(m, x, y) -> x', y' function Raster.apply(m, x, y) return m[1] * x + m[3] * y + m[5], m[2] * x + m[4] * y + m[6] end --- ------------------------------------------------------------------------------------------------ path builder local Builder = {} Builder.__index = Builder --- path() -> a Builder; every method returns the builder; builder.cmds is the command list (any API taking a path --- takes a builder too) function Raster.path() return setmetatable({ cmds = {} }, Builder) @@ -73802,7 +71899,6 @@ function Builder.close(self) table.insert(self.cmds, { op = "close" } ) return self end --- rect(x, y, w, h), ellipse(cx, cy, rx, ry): closed subpaths function Builder.rect(self, x, y, w, h) return self:moveTo(x, y):lineTo(x + w, y):lineTo(x + w, y + h):lineTo(x, y + h):close() end @@ -73826,7 +71922,6 @@ if type(path) ~= "table" then return path end --- n numeric operands of a command, or nil local function operands(c, n) if type(c) ~= "table" then return false @@ -73840,9 +71935,6 @@ if type(c) ~= "table" then return true end --- ------------------------------------------------------------------------------------------------ flattening --- flatten(path, transform?, tolerance?) -> polylines: { { x1, y1, x2, y2, ... } } in device space, one per subpath --- (closed implicitly; the closing point is not repeated), and the bounds x0, y0, x1, y1 (nil when empty) local function flatten(path, transform, tolerance, minLen) local cmds = commands(path) local polys= {} @@ -73859,8 +71951,8 @@ local cmds = commands(path) tol = 0.1 end local cur= nil - local px, py = 0, 0 -- current point (device) - local sx, sy = 0, 0 -- subpath start (device) + local px, py = 0, 0 + local sx, sy = 0, 0 local bx0, by0, bx1, by1 = math.huge, math.huge, -math.huge, -math.huge local function point(x, y) local poly = cur @@ -73968,9 +72060,7 @@ function Raster.flatten(path, transform, tolerance) return flatten(path, transform, tolerance, 6) end --- ------------------------------------------------------------------------------------------------ accumulation --- one edge (x0, y0) -> (x1, y1), already inside [0, W] horizontally, into acc (stride S, H rows): the signed area --- each pixel gains (font-rs's draw_line) +-- the signed area each pixel gains from one edge (font-rs draw_line) local function line(acc, S, H, x0, y0, x1, y1) if y0 == y1 then return @@ -74050,9 +72140,7 @@ local function line(acc, S, H, x0, y0, x1, y1) end end --- an edge in mask coordinates, split where it crosses x = 0 and x = W (in its own order: the direction is the --- winding sign); the parts outside are pushed onto the border (their area lies outside the mask, their cover still --- applies to the row) +-- edges split at x = 0 / x = W: the parts outside go onto the border, whose cover still applies to the row local function clampx(x, W) return x < 0 and 0 or(x > W and{W }or{x })[1]end @@ -74064,7 +72152,7 @@ local function edge(acc, S, W, H, x0, y0, x1, y1) return end local dx = x1 - x0 - local ta, tb = 2, 2 -- parameters of the crossings with x = 0 and x = W (2 = none) + local ta, tb = 2, 2 if dx ~= 0 then local t0 = (0 - x0) / dx local tw = (W - x0) / dx @@ -74093,8 +72181,6 @@ local function edge(acc, S, W, H, x0, y0, x1, y1) line(acc, S, H, clampx(px, W), py, clampx(x1, W), y1) end --- ------------------------------------------------------------------------------------------------ masks --- mask(path, opts?) -> Mask | nil (empty, or over the size limit: then the second result is "limit") function Raster.mask(path, opts) local o= opts or {} local polys, bx0, by0, bx1, by1 = Raster.flatten(path, o.transform, o.tolerance) @@ -74155,11 +72241,6 @@ local o= opts or {} return { x = X0, y = Y0, width = W, height = H, coverage = cov }, nil end --- ------------------------------------------------------------------------------------------------ filling --- fill(img, path, paint, opts?) -> true | false, message. img: an rgba8 Image ({ width, height, pixels }); paint: an --- { r, g, b, a } colour (0..255) or a function(x, y) -> r, g, b, a called per covered pixel (pixel centres in --- device space: x + 0.5, y + 0.5). Composites source-over onto the straight-alpha pixels. opts.clip defaults to the --- image; opts.opacity scales the coverage. function Raster.fill(img, path, paint, opts) if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then return false, "fill: expected an rgba8 image" @@ -74223,7 +72304,7 @@ if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "n end return true, nil end --- ------------------------------------------------------------------------------------------------ stroking + -- push a polygon (flat x, y list) as a closed subpath with positive orientation, so overlapping pieces add up -- under the nonzero rule @@ -74235,7 +72316,6 @@ end - local function polygon(out, pts) local n = #pts if n < 6 then @@ -74274,8 +72354,6 @@ local function arcPoints(cx, cy, r, a0, a1, tol, pts) end end --- stroke(path, opts?) -> Path: the outline of the stroke as pieces to fill with the nonzero rule (in the path's own --- coordinate space: transform it like the path). Dashes are the caller's job (split the path first). function Raster.stroke(path, opts) local o= opts or {} local hw = ((type(o.width) == "number" and o.width > 0 and{o.width }or{1})[1]) / 2 @@ -74328,7 +72406,6 @@ local __DARKLUA_CONTINUE_18=false repeat local polys = flatten(sub.cmds, nil, t end __DARKLUA_CONTINUE_18=true break end - -- drop repeated points local p= { pts[1], pts[2] } for i = 3, #pts - 1, 2 do if abs(pts[i] - p[#p - 1]) > 1e-9 or abs(pts[i + 1] - p[#p]) > 1e-9 then @@ -74346,8 +72423,7 @@ __DARKLUA_CONTINUE_18=true break __DARKLUA_CONTINUE_18=true break end local segs = (closed and{n }or{(n - 1 -)})[1] -- segment bodies - local dirs= {} +)})[1] local dirs= {} for s = 0, segs - 1 do local i, j = s, (s + 1) % n local x0, y0, x1, y1 = p[2 * i + 1], p[2 * i + 2], p[2 * j + 1], p[2 * j + 2] @@ -74358,7 +72434,6 @@ __DARKLUA_CONTINUE_18=true break 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 - -- joins local function joinAt(k, s0, s1) local x, y = p[2 * k + 1], p[2 * k + 2] local ax, ay = dirs[2 * s0 + 1], dirs[2 * s0 + 2] @@ -74385,7 +72460,7 @@ __DARKLUA_CONTINUE_18=true break arcPoints(x, y, hw, a0, a0 + da, tol, d) polygon(out, d) else - local cosT = ax * bx + ay * by -- angle between directions + local cosT = ax * bx + ay * by local miter = (join == "miter" and{(1 / sqrt(max(1e-12, (1 + cosT) / 2)) )}or{math.huge })[1] if join == "miter" and miter <= miterLimit then local mx, my = n0x + n1x, n0y + n1y @@ -74407,12 +72482,11 @@ __DARKLUA_CONTINUE_18=true break for k = 1, n - 2 do joinAt(k, k - 1, k) end - -- caps if cap ~= "butt" then for _, endInfo in __iter({ { 0, 0, -1 }, { n - 1, segs - 1, 1 } }) do local k, s, sgn = endInfo[1], endInfo[2], endInfo[3] local x, y = p[2 * k + 1], p[2 * k + 2] - local ux, uy = dirs[2 * s + 1] * sgn, dirs[2 * s + 2] * sgn -- pointing outwards + 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 }) @@ -74435,21 +72509,8 @@ __FILES["codecs/image/Texel"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --!native --!optimize 2 --- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers --- (DDS's DXGI and legacy bit-mask formats, KTX's Vulkan / OpenGL formats, ...). New in rosetta. Formats are named --- lower case, channels from the lowest address / bit up (DXGI order): r8, rg8, rgb8, bgr8, rgba8, bgra8, bgrx8, a8, --- l8, la8, r16, rgba16, *s (snorm), *ui / *i (integers), *f (half / float: r16f ... rgba32f), and the packed ones: --- b5g6r5, r5g6b5, b5g5r5a1, a1b5g5r5, b4g4r4a4, a4b4g4r4, a4r4g4b4, rgb10a2, bgr10a2, r11g11b10f, rgb9e5; any other --- bit-mask layout through Texel.masked(bytes, rMask, gMask, bMask, aMask, luminance?). Never throws. --- --- local px, fmt = Texel.decode("bgra8", buf, offset, w, h) -- rgba8 pixels --- local px, fmt = Texel.decode("rgba16f", buf, offset, w, h, true) -- native: rgbaf32 (float) / rgba16 (16-bit) --- local desc = Texel.masked(2, 0xF800, 0x07E0, 0x001F, 0) -- a descriptor, accepted by decode --- --- Channels: one-channel formats (r*, l*) are grey (r = g = b), two-channel ones red + green; missing alpha is opaque. --- rgba8 output: unorm rescaled with rounding, snorm biased (8-bit: s + 128), floats clamped to 0..1, integers clamped --- to 0..255. Native output: rgba8 when every channel fits 8 bits unsigned, rgba16 for 9..16-bit unorm, else rgbaf32 --- (snorm -> -1..1, integers as their values). +-- 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 = {} @@ -74469,7 +72530,6 @@ local writeu8, writeu16, writeu32, writef32 = buffer.writeu8, buffer.writeu16, b local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local HALF = Half.TABLE --- ------------------------------------------------------------------------------------------------ formats local FORMATS= {} local function array(name, size, typ, order) FORMATS[name] = { bytes = size * #order, kind = "array", size = size, type = typ, order = order } @@ -74529,8 +72589,6 @@ FORMATS.grgb = { bytes = 2, kind = "pair", order = "grgb" } FORMATS.ayuv = { bytes = 4, kind = "ayuv" } Texel.FORMATS = FORMATS --- masked(bytes, r, g, b, a, luminance?) -> a packed descriptor from bit masks (DDS legacy pixel formats); luminance: --- the r mask is a luminance channel function Texel.masked(bytes, r, g, b, a, luminance) if bytes < 1 or bytes > 4 then return nil @@ -74556,7 +72614,6 @@ if bytes < 1 or bytes > 4 then return { bytes = bytes, kind = "packed", channels = ch } end --- size(fmt, w, h) -> bytes (rows tightly packed) | nil function Texel.size(fmt, w, h) local d = (type(fmt) == "string" and{FORMATS[fmt] }or{fmt })[1] if not d then @@ -74565,8 +72622,6 @@ local d = (type(fmt) == "string" and{FORMATS[fmt] }or{fmt return (d.kind == "pair" and(((math.floor((w + 1) / 2)) * 4 * h ))or((d.bytes * w * h )))end --- ------------------------------------------------------------------------------------------------ helpers --- the native output of a descriptor: rgba8 / rgba16 / rgbaf32 local function nativeOf(d) if d.kind == "array" then local t, s = d.type, d.size @@ -74604,7 +72659,6 @@ local e, m = rshift(v, 5), band(v, 31) return (1 + m / 32) * 2 ^ (e - 15) end --- one component at q of an array format -> a float (native meaning) and its rgba8 byte local function component(src, q, size, typ) if typ == "unorm" then if size == 1 then @@ -74638,7 +72692,6 @@ if typ == "unorm" then )})[1]})[1] return v, math.clamp(v, 0, 255) end --- BT.601 limited-range Y'CbCr -> an rgba8 u32 local function ycc(y, u, v, a) local c, d, e = 1.164 * (y - 16), u - 128, v - 128 local r = math.clamp(math.floor(c + 1.596 * e + 0.5), 0, 255) @@ -74647,7 +72700,6 @@ local c, d, e = 1.164 * (y - 16), u - 128, v - 128 return r + g * 256 + b * 65536 + a * 16777216 end --- the 4:2:2 pair formats and AYUV -> rgba8 (out is always rgba8: 8-bit sources) local function yuv(d, src, offset, w, h, pitch, dst) local n = 0 local order = d.order or "" @@ -74677,9 +72729,6 @@ local n = 0 return dst end --- ------------------------------------------------------------------------------------------------ decode --- decode(fmt, src, offset, w, h, native?, rowPitch?) -> pixels, pixel format ("rgba8" / "rgba16" / "rgbaf32") | nil, --- message. rowPitch: bytes per source row (default tight). function Texel.decode(fmt, src, offset, w, h, native, rowPitch) local d = (type(fmt) == "string" and{FORMATS[fmt] }or{fmt })[1] if not d then @@ -74699,8 +72748,7 @@ local d = (type(fmt) == "string" and{FORMATS[fmt] }or{fmt ) local dst = buffer.create(w * h * bpp) local n = 0 if d.kind == "array" then - local order, size, typ = d.order , d.size , d.type -- fast paths - + local order, size, typ = d.order , d.size , d.type if size == 1 and typ == "unorm" and out == "rgba8" and (order == "rgba" or order == "bgra" or order == "bgrx" or order == "rgbx") then local swap = order == "bgra" or order == "bgrx" local opaque = order == "bgrx" or order == "rgbx" @@ -74721,7 +72769,7 @@ if size == 1 and typ == "unorm" and out == "rgba8" and (order == "rgba" or order return dst, out end local nc = #order - local map = table.create(nc, 0) -- component -> output channel 0..3, 4 = grey, -1 = skip + local map = table.create(nc, 0) for i = 1, nc do local c = string.sub(order, i, i) map[i] = (c == "r" and{(nc == 1 and 4 or 0) }or{c == "g" and 1 or(c == "b" and 2 or(c == "a" and 3 or(c == "l" and 4 or-1 @@ -74801,7 +72849,6 @@ for y = 0, h - 1 do if d.kind == "pair" or d.kind == "ayuv" then return yuv(d, src, offset, w, h, pitch, dst), out end - -- shared-exponent / packed floats local nine = d.kind == "rgb9e5" for y = 0, h - 1 do local s = offset + y * pitch @@ -74833,15 +72880,7 @@ return Texel end __FILES["codecs/image/Texture"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...): --- a format name is a BCn kind (codecs/image/Bcn), an ETC / EAC kind (codecs/image/Etc) or a texel format --- (codecs/image/Texel); decode / size dispatch on it, surfaces() assembles mip levels / faces / layers into one --- Types.Image, halve() makes the next mip level of an image for writers. New in rosetta. Never throws. --- --- local px, pf = Texture.decode("bc7", buf, offset, w, h, native) -- pixels + their pixel format --- Texture.size("etc2_rgb", w, h) -- bytes of one surface --- local img = Texture.image(px, pf, w, h) -- a Types.Image around them --- local smaller = Texture.halve(img) -- box-filtered next mip level +-- 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") @@ -74850,7 +72889,6 @@ local Half = __include("codecs/image/Half") local Texture = {} --- known(name) -> "bcn" | "etc" | "texel" | nil function Texture.known(name) if Bcn.BLOCK[name] then return "bcn" @@ -74862,12 +72900,10 @@ if Bcn.BLOCK[name] then return nil end --- size(name, w, h) -> bytes of a w x h surface | nil function Texture.size(name, w, h) return Bcn.size(name, w, h) or Etc.size(name, w, h) or Texel.size(name, w, h) end --- block(name) -> block width, height, bytes (1, 1, texel bytes for texel formats) | nil function Texture.block(name) local b = Bcn.BLOCK[name] or Etc.BLOCK[name] if b then @@ -74880,8 +72916,6 @@ local b = Bcn.BLOCK[name] or Etc.BLOCK[name] return nil, nil, nil end --- decode(name, src, offset, w, h, native?) -> pixels, pixel format | nil, message. Without native the result is --- rgba8 (BC6H and float texels clamped to 0..1); native keeps rgbaf32 (BC6H, floats) / rgba16 (EAC, 16-bit unorm). function Texture.decode(name, src, offset, w, h, native) if Bcn.BLOCK[name] then local px, err = Bcn.decode(name, src, offset, w, h) @@ -74913,15 +72947,12 @@ if Bcn.BLOCK[name] then return Texel.decode(name, src, offset, w, h, native) end --- image(pixels, pixel format, w, h) -> Types.Image function Texture.image(px, pf, w, h) local img = Types.Image.new(0, 0, pf ) img.width, img.height, img.pixels = w, h, px return img end --- assemble(surfaces, layout) -> the Image of the first surface with img.frames = every level-0 surface (faces / --- layers / depth slices in order, when more than one) and img.meta.mipmaps = the smaller levels of the first surface function Texture.assemble(list, layout) @@ -74951,8 +72982,6 @@ local first= nil return img end --- halve(img) -> the next mip level (each dimension halved, at least 1; 2 x 2 box filter), same pixel format --- (rgba8 / rgba16 / rgbaf32) function Texture.halve(img) local w, h = img.width, img.height local nw, nh = math.max(1, math.floor(w / 2)), math.max(1, math.floor(h / 2)) @@ -74983,7 +73012,6 @@ local o = ((math.min(y, h - 1) * w + math.min(x, w - 1)) * 4 + c) * cs return out end --- toHalf(rgbaf32 pixels, n) -> rgba16f texels (for writers) function Texture.toHalf(px, n) local out = buffer.create(n * 8) local from = Half.fromFloat @@ -74997,27 +73025,9 @@ return Texture end __FILES["codecs/image/Vp8"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the --- WebM / Matroska and IVF video tracks use its decoder object. Key frames are a port of libwebp 1.6 (BSD-3-Clause, --- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals --- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. Inter frames follow libvpx 1.17 (BSD-3-Clause, --- licenses/libvpx-LICENSE.txt), bit-exact with libvpx / ffmpeg on the official test vectors and libvpx streams. --- Supports: key and inter frames of every version / profile (0: six-tap filters, normal loop filter; 1-2: bilinear; --- 3: bilinear with full pixel chroma; the loop filter type is the header's), last / golden / altref references with --- sign bias, hidden (altref) frames, token partitions, segments, loop filter deltas, probability context save / --- restore. Not supported: the horizontal / vertical scale bits (ignored, as libwebp and ffmpeg do), error --- concealment (a damaged frame returns an Err). --- Speed (one Zen 5 core): 640x480 inter frames ~190 fps under luau --codegen, ~220 fps under LuaJIT with the trace --- limits the host module sets (maxtrace=8000; with LuaJIT's default 1000 traces the decoder thrashes: ~70 fps). --- --- local Vp8 = require("rosetta.codecs.image.Vp8") --- local frame, err = Vp8.decodeFrame(buf, off, len) -- one key frame: a yuv420p Types.Image --- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling) --- local dec = Vp8.newDecoder() -- a stream (WebM, IVF): key and inter frames --- local img, err = dec:decodeFrame(buf, off, len) -- img.meta.source.show == false: a hidden frame --- dec:reset() -- after a seek: the next frame must be a key frame --- --- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG). +-- 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") @@ -75049,7 +73059,6 @@ local n = buffer.len(buf) return o, math.clamp(len or (n - o), 0, n - o) end --- info(buf, off?, len?) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, Err function Vp8.info(buf, off, len) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "info: expected a buffer") @@ -75065,16 +73074,12 @@ end local DecoderMeta = {} DecoderMeta.__index = DecoderMeta --- newDecoder() -> Decoder: decodes successive frames of one stream function Vp8.newDecoder() return setmetatable({ state = Decode.new() }, DecoderMeta) end --- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image (a fresh buffer) | nil, Err. Key and inter frames; --- meta.source = { format = "vp8", keyFrame, show (false: a hidden frame, decoded as a reference but not displayed), --- profile, width, height }. An inter frame before the first key frame (or after reset) returns CORRUPT. function DecoderMeta.decodeFrame(self, buf, off, len, opts) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer") @@ -75093,17 +73098,14 @@ if type(buf) ~= "buffer" then return img, nil end --- decoder:reset(): drops the reference frames (after a seek); the next frame must be a key frame function DecoderMeta.reset(self) Decode.reset(self.state) end --- decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err (one key frame) function Vp8.decodeFrame(buf, off, len, opts) return Vp8.newDecoder():decodeFrame(buf, off, len, opts) end --- decodePlanes(buf, off?, len?, opts?) -> y, u, v, width, height | nil, Err: one key frame as separate planes function Vp8.decodePlanes(buf, off, len, opts) if type(buf) ~= "buffer" then return nil, Err.new(Err.ARG, "decodePlanes: expected a buffer") @@ -75119,15 +73121,12 @@ if type(buf) ~= "buffer" then return y, u, v, f.width, f.height end --- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height function Vp8.planes(img) local cw, ch = math.floor((img.width + 1) / 2), math.floor((img.height + 1) / 2 ) local ny = img.width * img.height return 0, ny, ny + cw * ch, cw, ch end --- toRgba(yuvImage, fancy?) -> rgba8 Image. fancy (default true): libwebp's bilinear chroma upsampling; false: point --- sampling (dwebp -nofancy) function Vp8.toRgba(img, fancy) if type(img) ~= "table" or img.format ~= "yuv420p" then return nil, Err.new(Err.ARG, "toRgba: needs a yuv420p Image") @@ -75146,7 +73145,6 @@ if type(img) ~= "table" or img.format ~= "yuv420p" then return out, nil end --- yuvToRgba(y, u, v, w, h, fancy?) -> rgba8 pixels from separate planes (alpha 255) function Vp8.yuvToRgba(y, u, v, w, h, fancy) return Yuv.toRgba(y, u, v, w, h, fancy ~= false) end @@ -75159,21 +73157,9 @@ __FILES["codecs/image/Vp8/Decode"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/image/Vp8/Decode: the VP8 frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter / --- quantizer headers, token probability updates, intra modes, residual tokens, the inverse WHT and DCT, intra --- prediction (16x16, 4x4, chroma), and the normal and simple loop filters: a port of libwebp 1.6 src/dec/vp8_dec.c, --- tree_dec.c, quant_dec.c, frame_dec.c, src/dsp/dec.c and src/utils/bit_reader* (BSD-3-Clause, --- licenses/libwebp-LICENSE.txt). Inter frames after libvpx 1.17 vp8/decoder/decodeframe.c, decodemv.c and --- vp8/common/findnearmv.c, vp8_loopfilter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt): reference updates and sign --- bias, the frame context saved around frames that do not refresh it, persistent segment maps and loop filter deltas, --- inter modes from the near vectors, motion vectors, split macroblocks, intra macroblocks in inter frames, per --- reference / mode loop filter levels; the prediction itself is codecs/image/Vp8/Predict. Bit-exact with libvpx / ffmpeg --- (and with libwebp on key frames). Where libvpx and ffmpeg disagree on streams no encoder writes (an intermediate --- clamp of segment filter levels, copying golden to altref and altref to golden in one frame), this follows ffmpeg. --- --- The decoder state (Decode.new) keeps what persists between frames: the frame context, segment / filter headers, the --- segment map, the last / golden / altref frames. Never throws: bad data returns nil, "message" ("truncated: ..." when --- the data ends early). +-- 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") @@ -75191,7 +73177,6 @@ local BANDS, ZIGZAG = Tables.BANDS, Tables.ZIGZAG local CAT = { Tables.CAT3, Tables.CAT4, Tables.CAT5, Tables.CAT6 } local Decode = {} --- ------------------------------------------------------------------------------------------------ boolean decoder -- libwebp's VP8BitReader: `range` is the range minus one (127..254), `value` holds the unread bits, `bits` is the -- position of the 8-bit window in `value` (< 0: load more). Bytes past the end read as zero once and set eof. -- SHIFT[r + 1]: the normalisation shift of a range r (1..255) = 7 - floor(log2 r) @@ -75234,8 +73219,8 @@ local br = { buf = buf, pos = off, limit = off + len, value = 0, bits = -8, rang return br end --- getBit without a branch on the decoded bit (one inlined copy per call site keeps LuaJIT's trace count down): --- bit = 1 when value >> bits > split, then range = bit ? range - split : split + 1, value -= bit * (split + 1) << bits +-- branchless getBit: bit = value >> bits > split; range = bit ? range - split : split + 1; +-- value -= bit * (split + 1) << bits local function getBit(br, prob) if br.bits < 0 then load(br) @@ -75264,11 +73249,9 @@ local function getSignedValue(br, n) local v = getValue(br, n) return (getBit(br, 0x80) == 1 and{(-v )}or{v })[1]end --- ------------------------------------------------------------------------------------------------ state --- a decoded frame / reference: the macroblock aligned planes with a Predict.BORDER pixel border @@ -75344,13 +73327,11 @@ return { } end --- reset(state): drops the references; the next frame must be a key frame function Decode.reset(st) st.hasKey = false st.last, st.golden, st.alt = nil, nil, nil end --- header(buf, off, len) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, msg function Decode.header(buf, off, len) if len < 3 then return nil, "truncated: frame tag" @@ -75384,7 +73365,6 @@ if len < 3 then return h, nil end --- ------------------------------------------------------------------------------------------------ residuals local function getLargeValue(br, P, p) local v if getBit(br, P[p + 4]) == 0 then @@ -75415,9 +73395,7 @@ local v return v end --- getCoeffs(br, P, t, ctx, dqDc, dqAc, n, out, o) -> the position of the last non-zero coefficient + 1. Writes the --- dequantized coefficients (int16, as libwebp stores them) into out at byte offset o, in raster order. The boolean --- decoder is inlined (the hot loop of lossy decoding); getLargeValue goes through br. +-- coefficients are dequantized to int16 as libwebp stores them, in raster order local function getCoeffs(br, P, t, ctx, dqDc, dqAc, n, out, o) local tb = t * 8 local p = ((tb + BANDS[n + 1]) * 3 + ctx) * 11 @@ -75590,7 +73568,6 @@ local function transformWHT(inp, out, o) end end --- ------------------------------------------------------------------------------------------------ reconstruction -- 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 @@ -75930,13 +73907,11 @@ if mode == 0 then return mode end --- ------------------------------------------------------------------------------------------------ loop filter -- 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. --- simpleFilter(b, p, step, along, thresh): SimpleVFilter16 / SimpleHFilter16 (16 positions). A position whose filter --- value a is 0 changes nothing and is skipped before the mask (flat areas). +-- SimpleVFilter16 / SimpleHFilter16; a position whose filter value a is 0 changes nothing (skipped before the mask) local function simpleFilter(b, p, step, along, thresh) local t2 = 2 * thresh + 1 for _ = 1, 16 do @@ -75965,7 +73940,7 @@ local function simpleFilter(b, p, step, along, thresh) end end --- filterEdge(b, p, hs, vs, size, thresh, it, hevT): the macroblock edge filter (FilterLoop26) +-- the macroblock edge filter (FilterLoop26) local function filterEdge(b, p, hs, vs, size, thresh, it, hevT) local t2 = 2 * thresh + 1 for _ = 1, size do @@ -76024,8 +73999,7 @@ local function filterEdge(b, p, hs, vs, size, thresh, it, hevT) end end --- filterInner(b, p, hs, vs, size, thresh, it, hevT): the inner edge filter (FilterLoop24); nothing changes when --- q0 == p0 and p1 == q1 +-- the inner edge filter (FilterLoop24); nothing changes when q0 == p0 and p1 == q1 local function filterInner(b, p, hs, vs, size, thresh, it, hevT) local t2 = 2 * thresh + 1 for _ = 1, size do @@ -76072,7 +74046,6 @@ local function filterInner(b, p, hs, vs, size, thresh, it, hevT) end end --- ------------------------------------------------------------------------------------------------ inter modes 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 @@ -76143,8 +74116,7 @@ end local nr, nc, cnt = table.create(4, 0), table.create(4, 0), table.create(4, 0) --- readInterMb(st, br, probs, mi, mbx, mby, rows): the modes and motion vectors of one inter frame macroblock (libvpx --- read_mb_modes_mv with vp8_find_near_mvs); mi: its 1-based index in the mode info arrays +-- libvpx read_mb_modes_mv with vp8_find_near_mvs local function readInterMb(st, br, probIntra, probLast, probGf, mi, mbx, mby, rows) local miRef, miMode, miMvR, miMvC = st.miRef, st.miMode, st.miMvR, st.miMvC local x1 = mbx + 1 @@ -76344,7 +74316,6 @@ local function readInterMb(st, br, probIntra, probLast, probGf, mi, mbx, mby, ro rows.part[x1] = part miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = ref, mode, mvr, mvc end --- ------------------------------------------------------------------------------------------------ frame @@ -76371,7 +74342,6 @@ local ys, uvs = mbw * 16 + 2 * BORDER, mbw * 8 + 2 * BORDER } end --- a frame buffer no reference uses local function freeRef(st) for _, r in __iter(st.pool) do if r ~= st.last and r ~= st.golden and r ~= st.alt then @@ -76383,7 +74353,6 @@ for _, r in __iter(st.pool) do return r end --- cropTo(frame, dy, oy, du, ou, dv, ov): copies the visible planes out (luma stride width, chroma ceil(width / 2)) function Decode.cropTo(f, dy, oy, du, ou, dv, ov) local r = f.ref local w, h = f.width, f.height @@ -76398,7 +74367,6 @@ function Decode.cropTo(f, dy, oy, du, ou, dv, ov) end end --- decodeFrame(state, buf, off, len, maxPixels) -> Frame | nil, message: one key or inter frame of the stream function Decode.decodeFrame(st, buf, off, len, maxPixels) local hdr, herr = Decode.header(buf, off, len) if not hdr then @@ -76660,7 +74628,6 @@ if saved then end end - -- the frame buffer (macroblock aligned, with a border) and the references 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 @@ -76694,7 +74661,6 @@ refs[1], refs[2], refs[3] = rl, rg, ra end local coeffs = bcreate(mbw * 768) local dcb = bcreate(32) - -- per macroblock column / row state local intraT = table.create(mbw * 4, 0) local intraL = table.create(4, 0) local topNz = table.create(mbw, 0) @@ -76712,7 +74678,6 @@ end local mbSkip = table.create(mbw, 0) local mbNzY = table.create(mbw, 0) local mbNzUv = table.create(mbw, 0) - -- filter info for the whole frame: limit, ilevel, inner, hev per macroblock local fLimit = table.create(mbw * mbh, 0) local fIlevel = table.create(mbw * mbh, 0) local fInner = table.create(mbw * mbh, 0) @@ -77148,13 +75113,9 @@ __FILES["codecs/image/Vp8/Predict"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/image/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the --- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the --- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and --- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels --- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the --- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a --- block whose taps leave it is first copied with clamped coordinates. Never throws. +-- 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 @@ -77167,14 +75128,12 @@ local Predict = {} local BORDER = 32 Predict.BORDER = BORDER --- the work buffer stride (codecs/image/Vp8/Decode: BPS) local BPS = 32 -local emu = bcreate(32 * 32) -- a block with its taps, edges replicated -local tmp = bcreate(32 * 32) -- the first (horizontal) pass of a two-dimensional filter +local emu = bcreate(32 * 32) +local tmp = bcreate(32 * 32) --- the six-tap filter along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7). Each output reads --- its six pixels (a sliding window of locals is no faster in Luau and stops LuaJIT's register allocator). +-- six-tap along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7) local function sixH(src, so, ss, dst, d, ds, w, h, f) local k = f * 6 local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] @@ -77189,7 +75148,6 @@ local function sixH(src, so, ss, dst, d, ds, w, h, f) end end --- the six-tap filter along columns local function sixV(src, so, ss, dst, d, ds, w, h, f) local k = f * 6 local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] @@ -77230,9 +75188,6 @@ local function bilV(src, so, ss, dst, d, ds, w, h, f) end end --- block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil): predicts the w x h block at plane pixel --- (x, y) moved by (mvx, mvy) eighth pixels into dst at d (stride BPS). base: the offset of plane pixel (0, 0); wmax, --- hmax: the last pixel column / row of the (macroblock aligned) plane. local function block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil) local fx, fy = band(mvx, 7), band(mvy, 7) local px, py = x + math.floor((mvx - fx) / 8), y + math.floor((mvy - fy) / 8 @@ -77306,9 +75261,6 @@ if s < 0 then return math.floor((s + 4) / 8 )end --- mb(ref, mbx, mby, mvr, mvc, split, subR, subC, sb, dst, yo, uo, vo, bil, full): the prediction of one inter --- macroblock into the work buffer (luma at yo, chroma at uo / vo). Not split: one vector (mvr, mvc) in eighth pixels; --- split: the 16 block vectors subR / subC[sb + 1 .. sb + 16] (part < 3: the four 8x8 quarters share them). @@ -77383,9 +75335,6 @@ function Predict.mb(ref, mbx, mby, mvr, mvc, part, subR, subC, sb, dst, yo, uo, end end --- row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full): predicts the --- inter macroblocks of a row (ref[mbx + 1] > 0: refs[ref]) into pred, macroblock mbx at mbx * chunk + yo / uo / vo; --- mi0 + mbx + 1: the mode info index of macroblock mbx. A loop of its own (LuaJIT traces it apart from the decoder). function Predict.row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full) for mbx = 0, mbw - 1 do local rf = ref[mbx + 1] @@ -77397,7 +75346,6 @@ function Predict.row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi end end --- extend(P, stride, base, w, h): fills the BORDER pixels around a w x h plane with its edge pixels local function extend(P, stride, base, w, h) for r = 0, h - 1 do local o = base + r * stride @@ -77422,11 +75370,9 @@ return Predict end __FILES["codecs/image/Vp8/Tables"] = function() --!strict --- codecs/image/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6 --- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); the inter frame tables --- (sections 16-18: mode / motion vector probabilities, mode contexts, split partitions, sub-pixel filters) from --- libvpx 1.17 vp8/common (entropymode.c, vp8_entropymodedata.h, entropymv.c, modecont.c, decodemv.c, filter.c; --- BSD-3-Clause, licenses/libvpx-LICENSE.txt). Flat 1-based arrays. +-- 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 @@ -77675,9 +75621,8 @@ __FILES["codecs/image/Vp8/Yuv"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/image/Vp8/Yuv: 4:2:0 Y'CbCr (BT.601, limited range) to rgba8 the way libwebp's decoder does it, bit-exact: the --- 14-bit fixed-point VP8YuvToRgb of src/dsp/yuv.h, with either the "fancy" upsampler (src/dsp/upsampling.c: a 9-3-3-1 --- bilinear filter on the chroma, libwebp's default) or point sampling (dwebp -nofancy). A port of libwebp 1.6 +-- 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 @@ -77693,12 +75638,10 @@ if v >= 0 and v < 16384 then return v < 0 and 0 or 255 end --- (v * coeff) >> 8 for non-negative v local function mulHi(v, c) return rshift(v * c, 8) end --- rgba(y, u, v) -> the pixel as a little-endian u32 (bytes R G B 255) local function rgba(y, u, v) local yy = mulHi(y, 19077) local r = clip(yy + mulHi(v, 26149) - 14234) @@ -77708,8 +75651,7 @@ local yy = mulHi(y, 19077) end Yuv.rgba = rgba --- upsamplePair: libwebp UPSAMPLE_FUNC for one or two output rows. ty / by: offsets of the top / bottom luma rows --- (by < 0: no bottom row), tu / cu: offsets of the top / current chroma rows; dt / db: output row offsets. +-- libwebp UPSAMPLE_FUNC for one or two output rows (by < 0: no bottom row) local function upsamplePair(Y, U, V, ty, by, tu, cu, out, dt, db, len) local last = rshift(len - 1, 1) local tlu, tlv = readu8(U, tu), readu8(V, tu) @@ -77754,7 +75696,6 @@ local function upsamplePair(Y, U, V, ty, by, tu, cu, out, dt, db, len) end end --- toRgba(y, u, v, w, h, fancy, out?) -> rgba8 (alpha 255). Planes are tightly packed (chroma ceil(w / 2) wide). function Yuv.toRgba(Y, U, V, w, h, fancy, out) local o = out or bcreate(w * h * 4) local cw = math.floor((w + 1) / 2 @@ -77787,7 +75728,6 @@ local o = out or bcreate(w * h * 4) return o end --- setAlpha(rgba, a8, n): copy an alpha plane into the A bytes function Yuv.setAlpha(o, a, n) for i = 0, n - 1 do writeu8(o, i * 4 + 3, readu8(a, i)) @@ -77798,19 +75738,8 @@ return Yuv end __FILES["codecs/image/Vp8L"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): --- image/webp uses it for VP8L frames and for compressed ALPH planes; other containers may carry it too. --- Decoder: a port of libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it. Encoder: new --- (subtract green, predictor and cross-colour transforms with per-tile mode search, colour indexing with pixel --- bundling for <= 256 colours, LZ77 with hash chains and the 2-D distance codes, a colour cache chosen by entropy, --- one prefix code group per image or meta codes for big images). --- --- local Vp8L = require("rosetta.codecs.image.Vp8L") --- local rgba, w, h, alpha = Vp8L.decode(buf, off, len) -- a VP8L bitstream (0x2f signature) -> rgba8 --- local a8 = Vp8L.decodeAlpha(buf, off, len, w, h) -- a headerless stream's green channel (ALPH) --- local bits = Vp8L.encode(rgba, w, h, { effort = 4 }) -- rgba8 -> a VP8L bitstream --- --- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / LIMIT / ARG). +-- 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") @@ -77836,7 +75765,6 @@ local n = buffer.len(buf) return o, math.clamp(len or (n - o), 0, n - o) end --- info(buf, off?, len?) -> { width, height, alpha } | nil, Err: the 5-byte header function Vp8L.info(buf, off, len) local o, l = range(buf, off, len) local w, h, alpha, err = Decode.header(buf, o, l) @@ -77846,7 +75774,6 @@ local o, l = range(buf, off, len) return { width = w, height = h, alpha = alpha }, nil end --- decodeArgb(buf, off?, len?, maxPixels?) -> ARGB u32 pixels (0xAARRGGBB), width, height, alphaHint | nil, Err function Vp8L.decodeArgb(buf, off, len, maxPixels) local o, l = range(buf, off, len) local px, w, h, alpha, err = Decode.argb(buf, o, l, maxPixels or DEFAULT_MAX_PIXELS) @@ -77856,7 +75783,6 @@ local o, l = range(buf, off, len) return px, w, h, alpha end --- decode(buf, off?, len?, maxPixels?) -> rgba8 pixels, width, height, alphaHint | nil, Err function Vp8L.decode(buf, off, len, maxPixels) local px, w, h, alpha = Vp8L.decodeArgb(buf, off, len, maxPixels) if not px then @@ -77865,7 +75791,6 @@ local px, w, h, alpha = Vp8L.decodeArgb(buf, off, len, maxPixels) return Decode.toRgba(px, w * (h )), w, h, alpha end --- decodeAlpha(buf, off, len, width, height) -> width * height bytes (the green channel) | nil, Err function Vp8L.decodeAlpha(buf, off, len, width, height) local o, l = range(buf, off, len) local px, err = Decode.stream(buf, o, l, width, height) @@ -77875,10 +75800,8 @@ local o, l = range(buf, off, len) return Decode.green(px, width * height), nil end --- toRgba(argb, n) -> rgba8 bytes of n ARGB pixels Vp8L.toRgba = Decode.toRgba --- encode(rgba, width, height, opts?) -> a VP8L bitstream (signature + header + image stream) | nil, Err @@ -77903,7 +75826,6 @@ local effort = o.effort or 5 return Encode.encode(rgba, width, height, effort, o.exact == true, o.alphaHint, false), nil end --- encodeAlpha(a8, width, height, opts?) -> a headerless stream of the plane in green (an ALPH payload) function Vp8L.encodeAlpha(a8, width, height, opts) if type(a8) ~= "buffer" or buffer.len(a8) < width * height then return nil, Err.new(Err.ARG, "encodeAlpha: plane too small") @@ -77922,13 +75844,9 @@ __FILES["codecs/image/Vp8L/Decode"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder: prefix codes (two-level tables), meta prefix codes, --- LZ77 backward references with the 2-D distance map, the colour cache, and the four inverse transforms (predictor, --- cross colour, subtract green, colour indexing with pixel bundling). A port of libwebp 1.6 src/dec/vp8l_dec.c, +-- 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) in a buffer, 4 bytes each, rows top to bottom. Never throws: every --- function returns nil, "message" (prefixed "truncated: " when the data ends early) on bad data. +-- 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 @@ -77955,9 +75873,7 @@ local CODE_TO_PLANE = { } -- 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 --- ------------------------------------------------------------------------------------------------ bit reader --- LSB-first; bytes past the end read as zero and are counted in `over`: the stream is overrun when fewer bits are --- left in the buffer than phantom bits were added (bitcnt < over * 8). +-- LSB-first; bytes past the end read as zero and count in `over`: the stream is overrun when bitcnt < over * 8 @@ -77989,7 +75905,6 @@ local function fill(d) d.bitbuf, d.bitcnt = bitbuf, bitcnt end --- readBits(d, n) n <= 24 local function readBits(d, n) if d.bitcnt < n then fill(d) @@ -78004,7 +75919,6 @@ local function eos(d) return d.bitcnt < d.over * 8 end --- ------------------------------------------------------------------------------------------------ prefix codes local count = table.create(MAX_LEN + 1, 0) local offset = table.create(MAX_LEN + 2, 0) @@ -78033,8 +75947,7 @@ local step = lshift(1, len - 1) return (step ~= 0 and{(band(key, step - 1) + step )}or{key })[1]end --- build(d, lens (0-based Lua array), n) -> table offset in d.tab, or -1 for an invalid code set (libwebp --- BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits) +-- libwebp BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits; -1 when invalid local sorted = table.create(2400, 0) local function build(d, lens, n) for l = 0, MAX_LEN do @@ -78143,7 +76056,6 @@ end end return root end --- readSymbol(d, at) -> symbol (the reader is refilled to >= 15 bits first) local function readSymbol(d, at) if d.bitcnt < MAX_LEN then fill(d) @@ -78167,7 +76079,6 @@ end local codeLengths = table.create(2400, 0) local clLens = table.create(19, 0) --- readCode(d, alphabetSize) -> table offset, or -1 local function readCode(d, size) for i = 1, size do codeLengths[i] = 0 @@ -78246,7 +76157,6 @@ for i = 1, size do return build(d, codeLengths, size) end --- ------------------------------------------------------------------------------------------------ pixel data local function subSample(size, bits) return rshift(size + lshift(1, bits) - 1, bits) end @@ -78261,7 +76171,6 @@ local lo = argb % 65536 end Decode.cacheKey = cacheKey --- decodeData: the entropy-coded pixels of one level into `data` (w * h u32) local function decodeData(d, data, w, h, cacheBits, groups, himg, hbits, hxs) local total = w * h local cache= (cacheBits > 0 and{(bcreate(lshift(1, cacheBits) * 4) )}or{nil @@ -78378,7 +76287,6 @@ local total = w * h return true, nil end --- ------------------------------------------------------------------------------------------------ transforms local function addPixels(a, b) return band(band(a, 0xff00ff00) + band(b, 0xff00ff00), 0xff00ff00) + band(band(a, 0x00ff00ff) + band(b, 0x00ff00ff), 0x00ff00ff) end @@ -78431,7 +76339,7 @@ local ave = average2(c0, c1) return a * 16777216 + r * 65536 + g * 256 + b end --- predict(mode, L, T, TR, TL) -> the predicted pixel (libwebp VP8LPredictors; 14 and 15 are black) +-- libwebp VP8LPredictors; modes 14 and 15 are black local function predict(mode, L, T, TR, TL) if mode == 0 then return ARGB_BLACK @@ -78539,7 +76447,6 @@ local function inverseSubtractGreen(data, n) end end --- inverseColorIndexing(src (sw x h), w, h, bits, map (2^(8 >> bits) u32)) -> w x h local function inverseColorIndexing(src, sw, w, h, bits, map) local out = bcreate(w * h * 4) if bits == 0 then @@ -78566,12 +76473,10 @@ local out = bcreate(w * h * 4) end return out end --- ------------------------------------------------------------------------------------------------ image stream local decodeStream --- readCodes(d, xs, ys, cacheBits, level0) -> groups (5 table offsets each), huffman image, bits, image width local function readCodes(d, xs, ys, cacheBits, level0) local himg= nil @@ -78729,7 +76634,6 @@ return { } end --- header(buf, off, len) -> width, height, alphaHint | nil, message function Decode.header(buf, off, len) if len < 5 then return nil, 0, false, "truncated: header" @@ -78747,7 +76651,6 @@ if len < 5 then return w, h, alpha, nil end --- argb(buf, off, len, maxPixels) -> ARGB pixels, width, height, alphaHint | nil, message function Decode.argb(buf, off, len, maxPixels) local w, h, alpha, err = Decode.header(buf, off, len) if not w then @@ -78764,13 +76667,11 @@ local w, h, alpha, err = Decode.header(buf, off, len) return data, w, h, alpha, nil end --- stream(buf, off, len, w, h) -> ARGB pixels | nil, message: a headerless image stream (the ALPH chunk's payload) function Decode.stream(buf, off, len, w, h) local d = newState(buf, off, len, w * h) return decodeStream(d, w, h, true) end --- toRgba(argb, n, out?, outOff?) -> rgba8 bytes function Decode.toRgba(argb, n, out, outOff) local o = out or bcreate(n * 4) local base = outOff or 0 @@ -78782,7 +76683,6 @@ local o = out or bcreate(n * 4) return o end --- green(argb, n) -> the green channel as bytes (alpha planes) function Decode.green(argb, n) local o = bcreate(n) for k = 0, n - 1 do @@ -78797,12 +76697,7 @@ __FILES["codecs/image/Vp8L/Encode"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --!native --!optimize 2 --- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from the specification (RFC 9649 section 3). --- Transforms: colour indexing with pixel bundling (<= 256 colours), else subtract green + predictor (per-tile mode --- chosen from a residual cost) + cross colour (per-tile least-squares multipliers). Entropy coding: LZ77 with hash --- chains, the left / up run candidates and the 2-D distance codes, a colour cache whose size is chosen by an entropy --- estimate, one prefix code group per image, code lengths limited to 15 bits (codecs/entropy/Huffman) and run-length coded. --- Never throws (the init module validates the arguments). +-- 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 @@ -78834,7 +76729,6 @@ local PLANE_TO_CODE = table.create(128, 0) for i, v in __iter(CODE_TO_PLANE) do PLANE_TO_CODE[v + 1] = i end --- ------------------------------------------------------------------------------------------------ bit writer @@ -78842,7 +76736,7 @@ local function newWriter(cap) return { buf = bcreate(math.max(64, cap)), pos = 0, acc = 0, cnt = 0 } end --- put(w, v, n): the n <= 24 low bits of v, LSB first +-- the n <= 24 low bits of v, LSB first local function put(w, v, n) local acc = w.acc + v * 2 ^ w.cnt local cnt = w.cnt + n @@ -78876,7 +76770,6 @@ if w.cnt > 0 then return out end --- ------------------------------------------------------------------------------------------------ helpers local function subSample(size, bits) return rshift(size + lshift(1, bits) - 1, bits) end @@ -78888,7 +76781,6 @@ local lo = v % 65536 return (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 end --- prefix(v) -> code, extra bits, extra value of a length or distance code value v >= 1 local function prefix(v) local d = v - 1 if d < 4 then @@ -78905,7 +76797,7 @@ local d = v - 1 return 2 * hb + second, eb, band(d, lshift(1, eb) - 1) end --- distCode(xs, dist) -> the distance code value (1..120 for the 2-D plane offsets, else dist + 120) +-- distance code value: 1..120 for the 2-D plane offsets, else dist + 120 local function distCode(xs, dist) local yo = math.floor(dist / xs ) local xo = dist - yo * xs @@ -78939,7 +76831,6 @@ local dd = x - y return clip255(x + ((dd >= 0 and{(rshift(dd, 1) )}or{(-rshift(-dd, 1))})[1])) end --- predict(mode, L, T, TR, TL): the decoder's predictors (codecs/image/Vp8L/Decode) local function predict(mode, L, T, TR, TL) if mode == 1 then return L @@ -78984,7 +76875,6 @@ if mode == 1 then return ARGB_BLACK end --- COST[v + 1]: an estimate of the bits of a residual byte v (small magnitudes, mod 256, are cheap) local COST = table.create(256, 0) for v = 0, 255 do local m = math.min(v, 256 - v) @@ -78995,12 +76885,10 @@ local function residualCost(r) return COST[band(r, 255) + 1] + COST[band(rshift(r, 8), 255) + 1] + COST[band(rshift(r, 16), 255) + 1] + COST[rshift(r, 24) + 1] end --- ------------------------------------------------------------------------------------------------ transforms 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 } --- predictorTransform(px, w, h, bits, effort) -> the modes sub-image; px becomes the residuals local function predictorTransform(px, w, h, bits, effort) local tw, th = subSample(w, bits), subSample(h, bits) local modesImg = bcreate(tw * th * 4) @@ -79063,8 +76951,7 @@ local m = math.floor(v + 0.5) return m < -128 and-128 or(m > 127 and 127 or m )end --- crossColorTransform(px, w, h, bits) -> the multipliers sub-image; px is transformed in place. Per tile: the --- least-squares multipliers (r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32), kept when they lower the cost +-- cross colour per tile: least-squares r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32, kept when they lower the cost local function crossColorTransform(px, w, h, bits) local tw, th = subSample(w, bits), subSample(h, bits) local img = bcreate(tw * th * 4) @@ -79138,7 +77025,6 @@ local c = 0 return img end --- ------------------------------------------------------------------------------------------------ LZ77 -- 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 @@ -79174,7 +77060,6 @@ local L= {} head[h] = i end end - -- best(i) -> length, distance (0, 0 when no useful match) local function best(i) local max = math.min(MAX_LENGTH, n - i) if max < 2 then @@ -79278,7 +77163,6 @@ local max = math.min(MAX_LENGTH, n - i) return L, D end --- ------------------------------------------------------------------------------------------------ prefix codes local function entropy(h) local total = 0 for _, c in __iter(h) do @@ -79297,7 +77181,6 @@ local total = 0 return bits / log(2) end --- chooseCache(px, L, effort) -> the colour cache bits (0..10) with the smallest estimated literal cost local function chooseCache(px, L, effort) if effort < 2 then return 0 @@ -79359,7 +77242,6 @@ end end return bestBits end --- buildCode(freqs, maxLen) -> code lengths, reversed (LSB-first) codes, single (<= 1 used symbol: 0 bits each) local function buildCode(freqs, maxLen) @@ -79405,7 +77287,6 @@ local function zeroRun(tok, ext, run) end end --- writeCode(w, code, alphabetSize): the code lengths (a simple code when possible, else run-length coded) local function writeCode(w, c, size) local syms= {} for s = 0, size - 1 do @@ -79443,7 +77324,7 @@ local function writeCode(w, c, size) -- decoder's "previous" starts at 8), 17 zeros (3..10), 18 zeros (11..138) local tok= {} local ext= {} - local keep = 0 -- tokens up to the last non-zero length + local keep = 0 local prev = 8 local s = 1 while s <= size do @@ -79523,8 +77404,7 @@ end end end end --- ------------------------------------------------------------------------------------------------ image data --- writeImage(w, px, xs, n, effort, level0): colour cache bits, [the meta-code bit], the five codes, the pixels +-- colour cache bits, [the meta-code bit], the five codes, the pixels local function writeImage(w, px, xs, n, effort, level0) local L, D = lz77(px, xs, n, effort) local cacheBits = (level0 and{(chooseCache(px, L, effort) )}or{0 @@ -79611,8 +77491,6 @@ end if cache then end end --- ------------------------------------------------------------------------------------------------ encode --- toArgb(rgba, n, exact) -> ARGB pixels, any alpha < 255. Without exact, fully transparent pixels become 0. local function toArgb(rgba, n, exact) local px = bcreate(n * 4) local alpha = false @@ -79631,7 +77509,6 @@ local px = bcreate(n * 4) return px, alpha end --- palette(px, n) -> the sorted colours when there are at most 256, else nil local function palette(px, n) local seen= {} local list= {} @@ -79649,7 +77526,6 @@ local seen= {} return list end --- stream(px, w, h, effort, cfg, bw): the transforms and the main image of one configuration (px is consumed) local function stream(px, w, h, effort, cfg, bw) @@ -79719,8 +77595,6 @@ local function stream(px, w, h, effort, cfg, bw) writeImage(bw, px, xs, xs * h, effort, true) end --- encode(rgba, w, h, effort, exact, alphaHint?, headerless) -> the VP8L bitstream (headerless: the image stream only, --- as an ALPH chunk stores it). Efforts 6+ try several transform configurations and keep the smallest. function Encode.encode(rgba, w, h, effort, exact, alphaHint, headerless) local n = w * h local px, usesAlpha = toArgb(rgba, n, exact) @@ -79775,17 +77649,9 @@ __FILES["codecs/image/Yuv"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --!native --!optimize 2 --- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or --- BT.709 matrices, limited ("tv", 16..235 / 16..240: VP8, MPEG-1, H.264) or full ("pc", 0..255: MJPEG / JPEG) range. --- yuv -> rgb uses nearest chroma and 16-bit fixed point with swscale's default (non-accurate) coefficients, so the --- result is within about one level of `ffmpeg -pix_fmt rgba`; rgb -> yuv averages each 2x2 block for the chroma --- (ffmpeg's default rgb -> yuv420p chroma siting is close to this). --- --- Yuv.toRgba(planes, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 buffer (alpha 255) --- Yuv.fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p buffer (Y, then U, then V; ceil(w/2) x ceil(h/2)) --- Yuv.imageToRgba(img) / Yuv.imageFromRgba(img, range?, matrix?) -> Types.Image --- Yuv.scale(src, w, h, dw, dh, out?) -> yuv420p buffer of dw x dh (each plane bilinear; for shrinking by up to 2x per --- axis, larger factors skip source samples); Yuv.imageScale(img, dw, dh) -> Types.Image (yuv420p in and out) +-- 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 @@ -79829,14 +77695,11 @@ local key = (range or "limited") .. (matrix or "bt601") return c end --- CLIP[v + 1024] = clamp(v, 0, 255) for v in -1024..1279 local CLIP = bcreate(2304) for i = 0, 2303 do writeu8(CLIP, i, math.clamp(i - 1024, 0, 255)) end --- toRgba(src, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 (w * h * 4) from planes in one buffer: Y at 0 with --- stride w, U at uo and V at vo with stride cw (ceil(w/2) rows of ceil(h/2)) function Yuv.toRgba(src, w, h, uo, vo, cw, range, matrix, out) local dst = out or bcreate(w * h * 4) local c = coeffs(range, matrix) @@ -79868,7 +77731,6 @@ local dst = out or bcreate(w * h * 4) return dst end --- fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p function Yuv.fromRgba(src, w, h, range, matrix, out) local cw, ch = math.floor((w + 1) / 2), math.floor((h + 1) / 2 ) local uo, vo = w * h, w * h + cw * ch @@ -79883,7 +77745,6 @@ local cw, ch = math.floor((w + 1) / 2), math.floor((h + 1) / 2 local ysc = full and 1 or 219 / 255 local csc = full and 1 or 224 / 255 local yof = full and 0.5 or 16.5 - -- fixed point x 65536 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) @@ -79916,7 +77777,6 @@ local cw, ch = math.floor((w + 1) / 2), math.floor((h + 1) / 2 return dst end --- the range / matrix an Image's meta records (meta.yuv = { range, matrix }); limited BT.601 when absent local function info(img) local m = img.meta local y = m and m.yuv @@ -79931,13 +77791,11 @@ local m = img.meta end Yuv.info = info --- planes(w, h) -> uo, vo, cw, ch of a yuv420p buffer function Yuv.planes(w, h) local cw, ch = math.floor((w + 1) / 2), math.floor((h + 1) / 2 ) return w * h, w * h + cw * ch, cw, ch end --- FULL_Y / FULL_C: limited -> full range sample maps local FULL_Y = bcreate(256) local FULL_C = bcreate(256) for v = 0, 255 do @@ -79945,7 +77803,6 @@ for v = 0, 255 do writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255)) end --- toFullRange(img) -> a yuv420p Image in full range (a limited-range one remapped; a full-range one returned) function Yuv.toFullRange(img) if img.format ~= "yuv420p" or info(img) == "full" then return img @@ -79966,7 +77823,6 @@ if img.format ~= "yuv420p" or info(img) == "full" then return out end --- imageToRgba(img) -> an rgba8 Image (yuv420p converted; rgba8 returned as is; nil for other formats) function Yuv.imageToRgba(img) if img.format == "rgba8" then return img @@ -79983,7 +77839,6 @@ if img.format == "rgba8" then return out end --- imageFromRgba(img, range?, matrix?) -> a yuv420p Image (meta.yuv records the range / matrix) function Yuv.imageFromRgba(img, range, matrix) if img.format == "yuv420p" then return img @@ -79998,7 +77853,6 @@ if img.format == "yuv420p" then return out end --- one plane (sw x sh bytes at so) -> (dw x dh at do), bilinear in 8-bit fixed point (source sample centres) local function scalePlane(src, so, sw, sh, dst, d0, dw, dh) local fx, fy = sw / dw, sh / dh for y = 0, dh - 1 do @@ -80032,8 +77886,6 @@ local function scalePlane(src, so, sw, sh, dst, d0, dw, dh) end end --- scale(src, w, h, dw, dh, out?) -> a yuv420p buffer of dw x dh (planes Y, U, V; chroma ceil(dw / 2) x ceil(dh / 2)). --- src must hold w x h yuv420p (checked: a short buffer or bad sizes return a zero-filled result of the right size). function Yuv.scale(src, w, h, width, height, out) local dw= math.max(1, floor(width)) local dh= math.max(1, floor(height)) @@ -80064,26 +77916,8 @@ end __FILES["codecs/model/Draco"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). --- A codec, not a format: model/gltf (and any format carrying Draco data) calls it on a byte range. --- Ported from Google's Draco 1.5.7 (Apache-2.0, licenses/draco-LICENSE.txt): the decoder only, bitstream versions --- 1.0 - 2.2 for meshes (sequential and Edgebreaker connectivity: standard, predictive and valence traversals; topology --- splits, attribute seams), sequential point clouds and kd-tree point clouds (2.3); attribute decoders generic / --- integer / quantization / octahedral normals; prediction schemes difference, parallelogram, multi-parallelogram, --- constrained multi-parallelogram, tex coords (deprecated and portable), geometric normal, with the wrap and normal --- octahedron transforms; metadata. Values match draco_decoder bit for bit (f32 rounding at every step of the --- dequantization). --- Not supported: the pre-2.3 kd-tree point cloud layouts (Err.UNSUPPORTED). --- --- local Draco = require("rosetta.codecs.model.Draco") --- local g, err = Draco.decode(buf, off?, len?, opts?) -- buffer | string --- g.kind ("mesh" | "points"), g.numPoints, g.numFaces, g.indices (u32 x 3 per face, or nil for points) --- g.attributes[i] = { name = "POSITION" | "NORMAL" | "COLOR" | "TEX_COORD" | "GENERIC" | ..., uniqueId, --- components, type = "f32" | "u8" | "i16" | ..., normalized, data (per point, packed) } --- Draco.attribute(g, uniqueId) -> the attribute with that unique id (glTF's attribute map) --- g.metadata = { entries = { [name] = buffer }, children = { [name] = Metadata }, attributes = { [uniqueId] = Metadata } } --- --- Options: maxPoints (default 2^24), maxFaces (default 2^24): larger geometry returns Err.LIMIT. --- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT). +-- 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") @@ -80097,7 +77931,6 @@ local TYPES = { "i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "f32", "f6 Draco.ATTRIBUTE_NAMES = NAMES Draco.DATA_TYPES = TYPES --- sniff(buf, off?) -> whether the bytes start with "DRACO" @@ -80141,7 +77974,6 @@ if Reader.remaining(d) < 11 then return { major = major, minor = minor, kind = kind == 0 and"points" or"mesh", method = method, flags = flags }, nil end --- info(buf, off?, len?) -> the header function Draco.info(src, off, len) local buf, o, l, aerr = Bytes.span("draco", src, off, len) if not buf then @@ -80233,7 +78065,6 @@ local WRITE= { [11] = buffer.writeu8, } --- per point output buffer of an attribute local function expand(a, numPoints) local size = Attributes.DT_LENGTH[a.dataType] local comps = a.comps @@ -80388,7 +78219,6 @@ if m.numFaces > maxFaces then return g, nil, nil end --- decode(src, off?, len?, opts?) -> Geometry | nil, Err function Draco.decode(src, off, len, opts) local buf, o, l, aerr = Bytes.span("draco", src, off, len) if not buf then @@ -80404,7 +78234,6 @@ local buf, o, l, aerr = Bytes.span("draco", src, off, len) return g, nil end --- attribute(g, uniqueId) -> the attribute with that unique id function Draco.attribute(g, uniqueId) for _, a in __iter(g.attributes) do if a.uniqueId == uniqueId then @@ -80418,13 +78247,9 @@ return Draco end __FILES["codecs/model/Draco/Attributes"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/model/Draco/Attributes: Draco attribute decoding. The attributes decoders (one per connectivity: linear --- sequencer for sequential meshes and point clouds, traversal sequencers for Edgebreaker), their attribute --- descriptors, and the sequential attribute decoders: generic (raw values), integer, quantization (dequantized to --- f32 exactly like the C++) and octahedral normals; prediction through codecs/model/Draco/Predict. Bitstream --- versions 1.0 - 2.2. Ported from Google's Draco 1.5.7 (compression/attributes/*, compression/point_cloud/ --- point_cloud_decoder.cc, attributes/attribute_quantization_transform.cc, attribute_octahedron_transform.cc; --- Apache-2.0, licenses/draco-LICENSE.txt). +-- 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") @@ -80437,7 +78262,6 @@ local Attributes = {} 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 --- the geometry the attributes decode against @@ -80473,8 +78297,7 @@ if v % 2 == 1 then return math.floor(v / 2 )end --- the parent (position) getter for a scheme: portable integers from 2.0 on, the final values before (truncated to --- integers unless the scheme works in floats) +-- parent getter: portable integers from 2.0 on, the final values before (truncated unless the scheme uses floats) local function parentGetter(ver, pos, floats) local old = ver < 0x0200 local vals = (old and{pos.values }or{pos.portable @@ -80647,7 +78470,6 @@ local n = a.numValues return true, nil end --- decodes every attribute; returns them in attribute id order function Attributes.decode(d, g) local ver = d.ver local numDecoders = Reader.u8(d) @@ -80702,13 +78524,11 @@ end enc = cad.enc dec.traversal = { ct = cad.ct , enc = enc, method = 0 } end - -- prediction data: the attribute's own corner table when its seams are in use local pct = (ad and ad.used and{ad.ct }or{ct })[1] dec.md = { ct = pct, e2c = enc.e2c, v2e = enc.v2e } end decoders[i + 1] = dec end - -- the attribute descriptors local all= {} for _, dec in __iter(decoders) do local n = Reader.count(d, 0x0200) @@ -80769,7 +78589,6 @@ for _, a in __iter(all) do end return nil end - -- decode for _, dec in __iter(decoders) do local __DARKLUA_CONTINUE_17=false repeat if g.kdTree then local ok, err = KdTree.decode(d, dec.attrs, g.numPoints) @@ -80802,7 +78621,6 @@ local trav = dec.traversal end end dec.points = points - -- portable values for _, a in __iter(dec.attrs) do local __DARKLUA_CONTINUE_20=false repeat if a.seqType == 0 then local stride = DT_LENGTH[a.dataType] * a.comps @@ -80868,7 +78686,6 @@ __DARKLUA_CONTINUE_20=true break end end __DARKLUA_CONTINUE_20=true until true if not __DARKLUA_CONTINUE_20 then break end end - -- data needed by the transforms if ver >= 0x0200 then for _, a in __iter(dec.attrs) do if a.seqType == 2 then @@ -80899,20 +78716,14 @@ return Attributes end __FILES["codecs/model/Draco/Connectivity"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- codecs/model/Draco/Connectivity: Draco mesh connectivity. The sequential decoder (raw or rANS delta-coded indices) --- and the Edgebreaker decoder (standard, predictive and valence traversals, topology splits, start faces, attribute --- seams), the corner tables they build (the mesh's and one per attribute seam set), and the traversal sequencers --- (depth first and max prediction degree) that order attribute values. Ported from Google's Draco 1.5.7 --- (compression/mesh/mesh_sequential_decoder.cc, mesh_edgebreaker_decoder_impl.cc, mesh_edgebreaker_traversal_*, --- mesh/corner_table, mesh/mesh_attribute_corner_table, compression/mesh/traverser/*; Apache-2.0, --- licenses/draco-LICENSE.txt). Corners, vertices and faces are 0-based values stored at [i + 1]; -1 is invalid. +-- 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 = {} --- a corner table: corner -> vertex, corner -> opposite corner, vertex -> left-most corner --- encoding data of one attribute connectivity: vertex -> value index, value index -> corner @@ -80949,7 +78760,6 @@ local function newEnc(nv) return { v2e = table.create(nv, 0), e2c = {}, numValues = 0 } end --- ------------------------------------------------------------------------------------------------ sequential function Connectivity.sequential(d) local numFaces, numPoints if d.ver < 0x0202 then @@ -81023,11 +78833,8 @@ local numFaces, numPoints end return { faces = faces, numFaces = numFaces, numPoints = numPoints, ct = nil, attrData = {}, posEnc = nil, posDecoderId = -1 }, nil end --- ------------------------------------------------------------------------------------------------ edgebreaker --- the traversal decoders: symbols, start face configurations, attribute seam bits --- MeshEdgebreakerTraversalDecoder::Start (the standard parts): symbols (bits), start faces, seam decoders. --- Returns the decoder state and the buffer after them. +-- MeshEdgebreakerTraversalDecoder::Start @@ -81095,7 +78902,7 @@ local s = Reader.bits(sym, 1) return s + Reader.bits(sym, 2) * 2 end --- builds the traversal decoder for `kind` (0 standard, 1 predictive, 2 valence); returns it and the buffer after its data +-- traversal decoder kind: 0 standard, 1 predictive, 2 valence local function makeTraversal(kind, buf, numAttributeData, numVertices, numFaces, ct) local ver = buf.ver local st, out = standardStart(buf, numAttributeData, kind ~= 2 or ver < 0x0202) @@ -81272,7 +79079,6 @@ if active ~= -1 then }, out end --- hole and topology split events; returns the split stack (source / split symbol ids, edges) or nil local function splitEvents(eb, numFaces) local ver = eb.ver local n = Reader.count(eb, 0x0200) @@ -81459,7 +79265,6 @@ local ver = d.ver end local maxVertices = numEncodedVertices + numSplitSymbols - -- the corner table (filled lazily: nil = invalid) local c2v= {} local opp= {} local lmc= {} @@ -81530,7 +79335,6 @@ return nextC(O(nextC(c))) return prevC(O(prevC(c))) end - -- the symbols local stack= {} local sp = 0 local splitActive= {} @@ -81769,7 +79573,6 @@ return prevC(O(prevC(c))) d.pos =d.pos+ splitBytes end - -- attribute seams local attrData= {} for i = 1, numAttributeData do attrData[i] = { decoderId = -1, used = true, seams = {}, ct = nil, enc = newEnc(0) } @@ -81890,9 +79693,7 @@ if act.vertSeam[V(c)] then }, nil end --- ------------------------------------------------------------------------------------------------ traversal --- MeshTraversalSequencer::GenerateSequence: the point ids in value order; fills enc (v2e, e2c, numValues). --- method 0 = depth first, 1 = max prediction degree. +-- MeshTraversalSequencer::GenerateSequence: method 0 depth first, 1 max prediction degree function Connectivity.traverse(ct, faces, enc, method) local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc local nf, nvt = ct.nf, ct.nv @@ -81993,7 +79794,6 @@ __DARKLUA_CONTINUE_41=true until true if not __DARKLUA_CONTINUE_41 then break en end return points end - -- max prediction degree if nvt == 0 then return points end @@ -82082,7 +79882,7 @@ until true if not __DARKLUA_CONTINUE_47 then break end end return points end --- MeshTraversalSequencer::UpdatePointToAttributeIndexMapping: point -> value index (1-based table of 0-based values) +-- MeshTraversalSequencer::UpdatePointToAttributeIndexMapping function Connectivity.mapping(ct, faces, enc, numPoints) local map = table.create(numPoints, 0) local c2v, v2e = ct.c2v, enc.v2e @@ -82105,9 +79905,8 @@ return Connectivity end __FILES["codecs/model/Draco/Int64"] = function() --!strict --- codecs/model/Draco/Int64: the 64-bit integer arithmetic Draco's portable tex coord predictor relies on (int64 / --- uint64 with wrap-around, truncating division, IntSqrt), on (hi, lo) pairs of 32-bit halves held in numbers (both --- runtimes: no native 64-bit integers). Two's complement: hi >= 2^31 is negative when read as signed. +-- 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 @@ -82143,7 +79942,6 @@ local nh, nl = Int64.neg(bh, bl) return Int64.add(ah, al, nh, nl) end --- the product mod 2^64 (the same bits for signed and unsigned operands) function Int64.mul(ah, al, bh, bl) local a0, a1, a2, a3 = al % 65536, math.floor(al / 65536), ah % 65536, math.floor(ah / 65536 ) local b0, b1, b2, b3 = bl % 65536, math.floor(bl / 65536), bh % 65536, math.floor(bh / 65536 @@ -82162,7 +79960,6 @@ function Int64.isNeg(h) return h >= P31 end --- the signed value as a number (exact below 2^53 in magnitude) function Int64.signed(h, l) if h >= P31 then return (h - P32) * P32 + l @@ -82170,12 +79967,10 @@ if h >= P31 then return h * P32 + l end --- the unsigned value as a number (rounded past 2^53) function Int64.unsigned(h, l) return h * P32 + l end --- unsigned compare: -1, 0, 1 function Int64.ucmp(ah, al, bh, bl) if ah ~= bh then return ah < bh and-1 or 1 @@ -82186,7 +79981,6 @@ if ah ~= bh then return 0 end --- signed compare: -1, 0, 1 function Int64.cmp(ah, al, bh, bl) local sa = (ah >= P31 and((ah - P32 ))or(ah )) local sb = (bh >= P31 and((bh - P32 ))or(bh @@ -82196,14 +79990,12 @@ local sa = (ah >= P31 and((ah - P32 ))or(ah return Int64.ucmp(0, al, 0, bl) end --- unsigned division (b ~= 0): quotient, remainder function Int64.udivmod(ah, al, bh, bl) if ah == 0 and bh == 0 then return 0, math.floor(al / bl), 0, al % bl end local qh, ql, rh, rl = 0, 0, 0, 0 for i = 63, 0, -1 do - -- r = r * 2 + bit i of a local bit = (i >= 32 and(((math.floor(ah / 2 ^ (i - 32))) % 2 ))or(((math.floor(al / 2 ^ i)) % 2 ))) local over = rh >= P31 rh = (rh * 2 + math.floor(rl / P31)) % P32 @@ -82220,7 +80012,6 @@ if ah == 0 and bh == 0 then return qh, ql, rh, rl end --- signed division truncating toward zero (b ~= 0) function Int64.div(ah, al, bh, bl) local na, nb = ah >= P31, bh >= P31 if na then @@ -82263,17 +80054,14 @@ return Int64 end __FILES["codecs/model/Draco/KdTree"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- codecs/model/Draco/KdTree: kd-tree coded point cloud attributes (bitstream 2.3): DynamicIntegerPointsKdTreeDecoder --- at compression levels 0 - 6 (direct bits, rANS bits, folded 32-bit rANS numbers, selected axes) over all the --- attributes of a decoder at once, then the signed offsets and the dequantization of f32 attributes. Ported from --- Google's Draco 1.5.7 (compression/attributes/kd_tree_attributes_decoder.cc, compression/point_cloud/algorithms/ --- dynamic_integer_points_kd_tree_decoder.h, compression/bit_coders/{direct,folded_integer}_bit_decoder; Apache-2.0, --- licenses/draco-LICENSE.txt). The pre-2.3 kd-tree layouts are not supported. +-- 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 = {} --- a bit source: next() -> 0 / 1, bits(n) -> value (MSB first); bits returns nil when a direct decoder runs out +-- bits(n) reads MSB first @@ -82386,7 +80174,7 @@ local k = -1 return k end --- DynamicIntegerPointsKdTreeDecoder::DecodePoints -> points (each a table of `dim` u32 values), or nil +-- DynamicIntegerPointsKdTreeDecoder::DecodePoints local function decodePoints(d, level, dim, expected) local bitLength = Reader.u32(d) local numPoints = Reader.u32(d) @@ -82514,7 +80302,6 @@ end local SIGNED = { [1] = 8, [3] = 16, [5] = 32 } --- decodes the attributes of one kd-tree decoder (Attributes.Attr records: dataType, comps; sets values / numValues) function KdTree.decode(d, attrs, numPoints) if d.ver < 0x0203 then return false, "unsupported: kd-tree point clouds before bitstream 2.3" @@ -82557,7 +80344,6 @@ if d.ver < 0x0203 then a.map = nil off =off+ comps end - -- the data needed by the transforms: f32 quantization, then the signed minima for _, a in __iter(attrs) do if a.dataType == 9 then local mins = table.create(a.comps, 0) @@ -82585,7 +80371,6 @@ if d.ver < 0x0203 then a.signedMin = mins end end - -- back to the original values local fround = Predict.fround for _, a in __iter(attrs) do local vals = a.portable @@ -82628,13 +80413,9 @@ return KdTree end __FILES["codecs/model/Draco/Predict"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms. Schemes: difference --- (delta), parallelogram, multi-parallelogram, constrained multi-parallelogram, tex coords (deprecated, float) and --- portable tex coords, geometric normal; transforms: wrap, normal octahedron and canonicalized normal octahedron. --- Integer semantics follow the C++ (int32 wrap, truncating division, exact 64-bit products where they can pass 2^53; --- float math rounded to f32 at every step). Ported from Google's Draco 1.5.7 --- (compression/attributes/prediction_schemes/*, compression/attributes/normal_compression_utils.h; Apache-2.0, --- licenses/draco-LICENSE.txt). +-- 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") @@ -82731,7 +80512,6 @@ local xh, xl = twoProd(x, x) end return s end --- ------------------------------------------------------------------------------------------------ octahedron toolbox @@ -82835,8 +80615,6 @@ local y = fround(fround(fround(s) * o.scale) - 1) local dd = fround(1 / fround(math.sqrt(n2))) return fround(x * dd), fround(y * dd), fround(z * dd) end --- ------------------------------------------------------------------------------------------------ transforms --- tr.apply(pred, data, off): data[off + 1 ..] holds the corrections and receives the original values @@ -82883,7 +80661,6 @@ if tr.kind == 1 then return true end --- the original values from a prediction (pred[1 .. comps]) and the corrections at data[off + 1 ..] local function apply(tr, pred, data, off, comps) if tr.kind == 1 then local mn, mx, dif = tr.min, tr.max, tr.maxDif @@ -82952,12 +80729,8 @@ if r == 1 then data[off + 2] = ot + center end Predict.apply = apply --- ------------------------------------------------------------------------------------------------ schemes --- the mesh data of a scheme: corner table, value -> corner, vertex -> value --- the parent position attribute: pos(point) -> x, y, z (portable integers, or floats before 2.0) - @@ -82975,7 +80748,6 @@ Predict.apply = apply local DELTA, PARALLELOGRAM, MULTI, TEXDEP, CONSTRAINED, TEXPORT, GEONORMAL = 0, 1, 2, 3, 4, 5, 6 Predict.GEOMETRIC_NORMAL = GEONORMAL --- whether the scheme needs the position attribute function Predict.needsParent(s) return s.md ~= nil and (s.method == TEXDEP or s.method == TEXPORT or s.method == GEONORMAL) end @@ -83118,9 +80890,7 @@ local n = nextC(c) return nextC(o) end --- the portable tex coord prediction when both neighbours are decoded (MeshPredictionSchemeTexCoordsPortablePredictor --- ::ComputePredictedValue), in int64 / uint64 arithmetic like the C++. Returns "ok", u, v; "fallback" (degenerate --- edge: predict from a neighbour); or "fail", message. +-- MeshPredictionSchemeTexCoordsPortablePredictor::ComputePredictedValue in int64 / uint64 like the C++ local function texPortable(nu, nv, pu, pv, tx, ty, tz, nx, ny, nz, qx, qy, qz, pop) local pnx, pny, pnz = qx - nx, qy - ny, qz - nz local cnx, cny, cnz = tx - nx, ty - ny, tz - nz @@ -83153,7 +80923,6 @@ local pnx, pny, pnz = qx - nx, qy - ny, qz - nz end end end - -- the general case: int64 local from, add, sub, mul, div = Int64.from, Int64.add, Int64.sub, Int64.mul, Int64.div local function dot3(ax, ay, az, bx, by, bz) local xh, xl = from(ax) @@ -83265,7 +81034,7 @@ local ph, pl = from(pc) return "ok", i32(ul), i32(vl) end --- ComputeOriginalValues over data (corrections in, values out, in place); points = the entry -> point map +-- ComputeOriginalValues (in place); points = the entry -> point map function Predict.compute(s, data, numEntries, comps, points) local tr = s.tr local m = s.method @@ -83541,7 +81310,6 @@ local r = math.floor(x + 0.5) end return true, nil end - -- geometric normal local o = tr.oct local flips = s.flips if not o or not flips or comps ~= 2 then @@ -83607,12 +81375,9 @@ return Predict end __FILES["codecs/model/Draco/Reader"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --- codecs/model/Draco/Reader: the Draco decoder buffer (little-endian fields, LEB128 varints, LSB-first bit runs) and --- its entropy decoders: rANS symbol coding (tagged and raw schemes, DecodeSymbols) and the binary rANS / rABS bit --- decoder. Ported from Google's Draco 1.5.7 (core/decoder_buffer, core/varint_decoding, compression/entropy/ans.h, --- rans_symbol_decoder.h, symbol_decoding.cc, compression/bit_coders/rans_bit_decoder.cc; Apache-2.0, --- licenses/draco-LICENSE.txt). Bitstream versions 1.0 - 2.2 (fixed-width counts before 2.0 / 2.2). --- A failed read sets the sticky d.bad message and returns 0; callers check d.bad at their boundaries. +-- 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 @@ -83690,7 +81455,6 @@ local p = d.pos return readi32(d.b, p) end --- u64 as a number (exact below 2^53; sizes beyond that fail the bounds checks anyway) function Reader.u64(d) local p = d.pos if p + 8 > d.limit then @@ -83740,7 +81504,6 @@ if d.ver < fixedBefore then return Reader.varint(d) end --- ------------------------------------------------------------------------------------------------ bit runs -- StartBitDecoding(decodeSize): an optional size (u64 before 2.2, varint64 after), then LSB-first bits up to the end -- of the buffer; EndBitDecoding moves pos past the whole bytes consumed. function Reader.startBits(d, decodeSize) @@ -83787,7 +81550,6 @@ function Reader.endBits(d) d.pos = d.bitStart + math.floor((d.bitOff + 7) / 8 )end --- ------------------------------------------------------------------------------------------------ rANS symbols -- the precision for a symbol alphabet of `bitLength`-bit symbols: (3 * bits) / 2 clamped to 12..20 local function precisionBits(bitLength) local p = math.floor((3 * bitLength) / 2 @@ -83945,7 +81707,6 @@ d.pos =d.pos+ size return true end --- decodes n symbols into out[first .. first + n - 1] (0-based symbol values) local function ransRead(r, n, out, first) local b, base, off, state = r.b, r.base, r.off, r.state local lBase, bits = r.lBase, r.precBits @@ -84020,7 +81781,7 @@ local maxBitLength = Reader.u8(d) return true end --- DecodeSymbols(n, components) -> { u32 } (1-based) | nil (d.bad set) +-- DecodeSymbols function Reader.symbols(d, n, comps) local out = table.create(n, 0) if n == 0 then @@ -84041,9 +81802,8 @@ local out = table.create(n, 0) end return (ok and{out }or{nil })[1]end --- ------------------------------------------------------------------------------------------------ binary rANS --- RAnsBitDecoder::StartDecoding: prob_zero, the size (u32 before 2.2), the bytes +-- RAnsBitDecoder::StartDecoding: prob_zero, the size (u32 before 2.2), the bytes function Reader.bitDecoder(d) @@ -84089,16 +81849,7 @@ return Reader end __FILES["codecs/model/Mat4"] = function() --!strict --- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 --- (glTF / FBX / Types.Scene layout: translation at 13..15), quaternions { x, y, z, w }, angles in degrees where a --- format stores degrees. Shared by FBX, Collada, USD and MeshOps instead of a copy in each. New in rosetta (the --- functions come from the former model/fbx/Xform, model/dae/Math and model/usda/Build helpers). --- --- local m = Mat4.compose({ 1, 2, 3 }, quat, { 2, 2, 2 }) -- T * R * S --- local t, r, s = Mat4.decompose(m) -- (decomposeStrict: nil for shear / projective / singular) --- local w = Mat4.mul(parent, m) -- = Types.Scene.mul --- local inv = Mat4.inverse(m) -- affine inverse | nil --- local x, y, z = Mat4.point(m, px, py, pz) +-- codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers. local Types = __include("Types") local Mat4 = {} @@ -84111,7 +81862,6 @@ function Mat4.identity() return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } end --- mul(a, b) -> a * b Mat4.mul = Types.Scene.mul function Mat4.translation(x, y, z) @@ -84122,7 +81872,6 @@ function Mat4.scaling(x, y, z) return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } end --- rotation(axis, degrees) -> the rotation about axis 1 (X), 2 (Y) or 3 (Z) function Mat4.rotation(axis, degrees) local a = rad(degrees) local c, s = cos(a), sin(a) @@ -84135,7 +81884,6 @@ local a = rad(degrees) end local AXIS = { x = 1, y = 2, z = 3 } --- euler(x, y, z, order?) -> the rotation applying the axes in order (default "xyz": R = Rz * Ry * Rx), degrees function Mat4.euler(x, y, z, order) local o = order or "xyz" local deg = { x = x, y = y, z = z } @@ -84147,7 +81895,6 @@ local o = order or "xyz" return m end --- axisAngle(x, y, z, degrees) -> quaternion function Mat4.axisAngle(x, y, z, degrees) local l = sqrt(x * x + y * y + z * z) if l < 1e-12 then @@ -84158,7 +81905,6 @@ local l = sqrt(x * x + y * y + z * z) return { x * s, y * s, z * s, cos(h) } end --- fromQuat(q) -> the rotation matrix of a quaternion function Mat4.fromQuat(q) local x, y, z, w = q[1], q[2], q[3], q[4] local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z @@ -84170,7 +81916,6 @@ local x, y, z, w = q[1], q[2], q[3], q[4] } end --- quat(m) -> the unit quaternion of the rotation in m's upper 3x3 (columns assumed orthonormal) function Mat4.quat(m) local m00, m01, m02 = m[1], m[5], m[9] local m10, m11, m12 = m[2], m[6], m[10] @@ -84197,7 +81942,6 @@ local m00, m01, m02 = m[1], m[5], m[9] return { x / n, y / n, z / n, w / n } end --- eulerXYZ(q) -> Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion function Mat4.eulerXYZ(q) local m = Mat4.fromQuat(q) local sy = math.clamp(-m[3], -1, 1) -- m[3] = r20 = -sin(y) @@ -84213,7 +81957,7 @@ local m = Mat4.fromQuat(q) return { math.deg(x), math.deg(y), math.deg(z) } end --- compose(t?, r?, s?) -> T * R * S (glTF node semantics) +-- T * R * S (glTF 2.0 node transform) function Mat4.compose(t, r, s) local m = (r and{(Mat4.fromQuat(r) )}or{(Mat4.identity() )})[1] if s then @@ -84261,19 +82005,16 @@ if strict and (abs(m[4]) > 1e-6 or abs(m[8]) > 1e-6 or abs(m[12]) > 1e-6 or abs( return { m[13], m[14], m[15] }, Mat4.quat(r), { sx, sy, sz } end --- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale; shear is lost) +-- a negative determinant flips the x scale; shear is lost function Mat4.decompose(m) local t, r, s = split(m, false) return t , r , s end --- decomposeStrict(m) -> translation, rotation, scale | nil for matrices TRS cannot express (a projective row, shear, --- a zero scale) function Mat4.decomposeStrict(m) return split(m, true) end --- inverse(m) -> the inverse of an affine matrix (general upper 3x3) | nil when singular function Mat4.inverse(m) local a, b, c = m[1], m[5], m[9] local d, e, f = m[2], m[6], m[10] @@ -84297,7 +82038,6 @@ local a, b, c = m[1], m[5], m[9] return r end --- inverseFull(m) -> the inverse of any invertible 4x4 (projective rows too) | nil when singular function Mat4.inverseFull(m) local a = m local inv = table.create(16, 0) @@ -84327,12 +82067,10 @@ local a = m return inv end --- transpose3(m) -> m with its upper 3x3 transposed and no translation (the inverse of a pure rotation) function Mat4.transpose3(m) return { m[1], m[5], m[9], 0, m[2], m[6], m[10], 0, m[3], m[7], m[11], 0, 0, 0, 0, 1 } end --- fromRows(v, at?) -> column-major from 16 row-major values at v[at] (default 1; missing values: identity) function Mat4.fromRows(v, at) local o = (at or 1) - 1 local m = table.create(16, 0) @@ -84344,7 +82082,6 @@ local o = (at or 1) - 1 return m end --- toRows(m) -> the 16 values row-major function Mat4.toRows(m) local v = table.create(16, 0) for r = 0, 3 do @@ -84355,12 +82092,10 @@ local v = table.create(16, 0) return v end --- point(m, x, y, z) -> m * (x, y, z, 1) function Mat4.point(m, x, y, z) return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] end --- normalMatrix(m) -> the inverse transpose of the upper 3x3 (for normals) as a 4x4 (identity when singular) function Mat4.normalMatrix(m) local inv = Mat4.inverse({ m[1], m[2], m[3], 0, m[5], m[6], m[7], 0, m[9], m[10], m[11], 0, 0, 0, 0, 1 }) if not inv then @@ -84373,13 +82108,7 @@ return Mat4 end __FILES["codecs/model/MeshFlatten"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks --- scene.roots recursively (TRS or column-major `matrix` per node; a scene without nodes uses its meshes as they are), --- applies the transforms to POSITION (and the inverse transpose to NORMAL), reverses the winding under mirroring --- transforms, reads every accessor type to numbers and concatenates all primitives (triangles with or without indices, --- polygons, strips, fans, points; lines are skipped). Shared here because a format cannot require another one --- (ops/MeshOps.merge is the editing-side equivalent). --- Never throws: bad input returns nil, message. +-- 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 = {} @@ -84392,8 +82121,6 @@ local SIZE = Types.COMPONENT_SIZE -- normalized integer types: their scale (raw / scale = the normalized value) local NORM= { unorm8 = 255, unorm16 = 65535, snorm8 = 127, snorm16 = 32767 } --- ------------------------------------------------------------------------------------------------ accessors --- numbers(acc, raw) -> the accessor's count * components values (normalized types divided out unless raw), or nil, msg @@ -84480,10 +82207,9 @@ if t == "f32" then return out, nil end --- ------------------------------------------------------------------------------------------------ transforms local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } -local mul = Types.Scene.mul -- column-major 4x4 product a * b +local mul = Types.Scene.mul local function numList(v, n) if type(v) ~= "table" then @@ -84497,7 +82223,6 @@ if type(v) ~= "table" then return true end --- a node's local matrix (nil: none), or nil, message local function localMatrix(node) if node.matrix ~= nil then if not numList(node.matrix, 16) then @@ -84558,7 +82283,6 @@ for i = 1, 16 do return true end --- the primitive instances of a scene in traversal order, or nil, message local function instances(scene) @@ -84648,8 +82372,6 @@ local node = nodes[ni] return out, nil end --- ------------------------------------------------------------------------------------------------ faces --- the faces of a primitive: sizes (nil = all triangles), corners (0-based), or "points" / "skip", or nil, message local function faces(prim, nv) local mode = prim.mode or "triangles" if mode == "points" then @@ -84726,7 +82448,6 @@ table.move(idx, 1, n, 1, c) return nil, nil, "unknown primitive mode " .. tostring(mode) end --- ------------------------------------------------------------------------------------------------ merge -- the fill value of a missing attribute component: colours default to opaque white, everything else to 0 local function fill(name, t, raw) if string.sub(name, 1, 6) ~= "COLOR_" then @@ -84741,8 +82462,6 @@ local b = buffer.create(4) return buffer.readf32(b, 0) end --- merge(scene, keep, opts) -> Merged | nil, message. keep(name) says which attributes to carry (POSITION always). --- opts.triangulate fan-triangulates polygons (faces of fewer than 3 vertices are dropped then). function Flatten.merge(scene, keep, opts) if type(scene) ~= "table" then return nil, "not a scene" @@ -84752,7 +82471,6 @@ if type(scene) ~= "table" then return nil, lerr end local triangulate = opts and opts.triangulate or false - -- the attribute set: union over parts, a type every part agrees on (else f32), the widest component count local types= {} local comps= {} local used= {} @@ -84919,17 +82637,6 @@ end __FILES["codecs/model/Minecraft"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. --- Block states ("minecraft:oak_stairs[facing=east,half=bottom]": parse / format / NBT compound form), the default --- block colour table (codecs/model/Minecraft/Colors, hand-made) with fallbacks by family, the pre-1.13 numeric ids --- (codecs/model/Minecraft/Legacy), packed index arrays (codecs/model/Minecraft/Packed), and the bridge between block --- grids and Types.Voxels: voxels.blocks holds the exact states (u16 indices into a state palette), voxels.data / --- palette their colours; writing a grid without blocks picks the block nearest in colour for each palette colour. --- --- local Mc = require("rosetta.codecs.model.Minecraft") --- local name, props = Mc.parseState("minecraft:oak_log[axis=y]") -- "minecraft:oak_log", { { "axis", "y" } } --- local rgba = Mc.color("minecraft:red_wool") -- { r, g, b, a } | nil for air --- local v = Mc.voxels(sx, sy, sz, states, indices) -- a Types.Voxels with .blocks --- local states, indices = Mc.blocksOf(v) -- back (or chosen by colour) local Types = __include("Types") local Nbt = __include("codecs/text/Nbt") local Colors = __include("codecs/model/Minecraft/Colors") @@ -84941,8 +82648,6 @@ local Minecraft = {} Minecraft.Packed = Packed Minecraft.Legacy = Legacy --- ------------------------------------------------------------------------------------------------ block states --- parseState(s) -> name (namespace added when missing), props { { key, value } } in their order function Minecraft.parseState(s) local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$") local n = name or "" @@ -84962,7 +82667,6 @@ local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$") return n, props end --- stateString(name, props?) -> "name[k=v,...]" (props { { k, v } } in order, or a map: keys sorted) function Minecraft.stateString(name, props) if not props or next(props) == nil then return name @@ -84980,7 +82684,6 @@ if not props or next(props) == nil then return name .. "[" .. table.concat(parts, ",") .. "]" end --- stateFromNbt(compound) -> the state string of a palette entry { Name, Properties? } (litematic, chunk sections) function Minecraft.stateFromNbt(c) if type(c) ~= "table" or type(c.Name) ~= "string" then return nil @@ -84995,7 +82698,6 @@ if type(c) ~= "table" or type(c.Name) ~= "string" then return Minecraft.stateString(c.Name, props) end --- stateToNbt(state) -> { Name, Properties? } (a Types.object; Properties in the state's order) function Minecraft.stateToNbt(s) local name, props = Minecraft.parseState(s) local c = Types.object({ Name = name }, { "Name" }) @@ -85010,19 +82712,16 @@ local name, props = Minecraft.parseState(s) return c end --- baseName(state) -> the name without namespace and properties ("minecraft:oak_log[axis=y]" -> "oak_log") function Minecraft.baseName(s) local name = string.match(s, "^%s*([^%[%s]*)") or "" return string.match(name, ":(.*)$") or name end local AIR = { air = true, cave_air = true, void_air = true, structure_void = true, light = true, barrier = true, moving_piston = true } --- isAir(state) -> true for blocks that are not drawn (air, cave_air, void_air, structure_void, light, barrier) function Minecraft.isAir(s) return AIR[Minecraft.baseName(s)] == true end --- ------------------------------------------------------------------------------------------------ colours local function hex(h) local c = { tonumber(string.sub(h, 1, 2), 16) or 0, tonumber(string.sub(h, 3, 4), 16) or 0, tonumber(string.sub(h, 5, 6), 16) or 0, 255 } if #h >= 8 then @@ -85178,7 +82877,6 @@ if depth > 4 then end local cache= {} --- color(state) -> { r, g, b, a } (0..255) | nil for air-like blocks: the default colour table, families, keywords function Minecraft.color(s) local hit = cache[s] if hit ~= nil then @@ -85188,7 +82886,6 @@ local hit = cache[s] local n = string.match(name, ":(.*)$") or name local res= nil if not AIR[n] then - -- pre-1.13 names whose data value picks the variant local variants = Legacy.VARIANTS[n] or ((n == "double_wooden_slab" and{Legacy.VARIANTS.planks }or{nil})[1]) if variants then local data = 0 @@ -85206,7 +82903,6 @@ local hit = cache[s] return res end --- ------------------------------------------------------------------------------------------------ legacy ids local REVERSE= nil local function reverse() if REVERSE then @@ -85238,8 +82934,7 @@ if REVERSE then return r end --- legacyState(id, data) -> the state string for a pre-1.13 block (variant names where the data value picks one, the --- rest of the data value kept as [data=N] so legacyId gives it back exactly) +-- the rest of the data value stays as [data=N], so legacyId gives it back exactly function Minecraft.legacyState(id, data) local n = Legacy.NAMES[id + 1] if n == nil or n == "-" then @@ -85256,8 +82951,6 @@ local n = Legacy.NAMES[id + 1] return "minecraft:" .. (Legacy.RENAMED[n] or n) .. ((data ~= 0 and(("[data=" .. data .. "]" ))or(""))) end --- legacyId(state) -> id, data | nil: the inverse of legacyState (modern names that exist before 1.13 too; their --- properties are not converted to data values) function Minecraft.legacyId(s) local name, props = Minecraft.parseState(s) local n = string.match(name, ":(.*)$") or name @@ -85282,10 +82975,6 @@ local name, props = Minecraft.parseState(s) return id, data end --- ------------------------------------------------------------------------------------------------ voxels --- voxels(sx, sy, sz, states, indices, opts?) -> Types.Voxels: indices (u16 LE per cell in Voxels order: x fastest, --- then y, then z) into states; data / palette from the block colours (air -> 0; up to 255 colours, more merge into --- the nearest one) function Minecraft.voxels(sx, sy, sz, states, indices) local v = Types.Voxels.new(sx, sy, sz) local lut = buffer.create(#states) @@ -85328,7 +83017,6 @@ local v = Types.Voxels.new(sx, sy, sz) return v end --- the blocks a colour grid is written with: full blocks of distinct colours (and stained glass for translucent ones) local CANDIDATES= nil local function candidates() if CANDIDATES then @@ -85353,7 +83041,6 @@ if CANDIDATES then return out end --- nearestBlock(rgba) -> the block state whose default colour is nearest (translucent colours -> stained glass) function Minecraft.nearestBlock(c) local a = c[4] or 255 if a < 200 then @@ -85378,8 +83065,6 @@ local a = c[4] or 255 return best end --- blocksOf(voxels) -> states, indices (u16 LE per cell): voxels.blocks when present (checked), else a block per --- palette colour (nearestBlock; cell 0 -> "minecraft:air" at index 0) | nil, message function Minecraft.blocksOf(v) local n = v.size[1] * v.size[2] * v.size[3] local b = v.blocks @@ -85416,9 +83101,8 @@ local n = v.size[1] * v.size[2] * v.size[3] return states, out end --- ------------------------------------------------------------------------------------------------ block entities --- Block entity records in one shape, { pos = { x, y, z }, id, data } (Sponge v3's), from / to the flat --- { x, y, z, id, ... } of MCEdit, Litematica and chunks, and Sponge v1 / v2's { Pos, Id, ... }. +-- block entities: Sponge v3 { pos = { x, y, z }, id, data } <-> flat { x, y, z, id, ... } (MCEdit, Litematica, +-- chunks) / Sponge v1 / v2 { Pos, Id, ... } local function int(v) local n = Nbt.number(v) if n == nil or n ~= n or n % 1 ~= 0 then @@ -85438,8 +83122,8 @@ if Nbt.isTag(v) and v.type == "intArray" then end return nil end -Minecraft.int = int -- the integer value of an NBT number | nil -Minecraft.ints = ints -- the numbers of an intArray or a list | nil +Minecraft.int = int +Minecraft.ints = ints local function rest(c, skip) local out, keys = {}, {} @@ -85455,8 +83139,6 @@ end local FLAT_SKIP = { x = true, y = true, z = true, id = true } local POS_SKIP = { Pos = true, Id = true } --- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2), --- "data" (Sponge v3) function Minecraft.blockEntity(c, style) if type(c) ~= "table" or Nbt.isTag(c) then return nil @@ -85469,7 +83151,6 @@ if type(c) ~= "table" or Nbt.isTag(c) then )})[1] return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = (type(c.Id) == "string" and{c.Id }or{nil})[1], data = data } end --- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity) function Minecraft.flatBlockEntity(be, style) local o = Types.object() local data = (type(be.data) == "table" and{be.data }or{(Types.object() @@ -85507,10 +83188,8 @@ return Minecraft end __FILES["codecs/model/Minecraft/Colors"] = function() --!strict --- codecs/model/Minecraft/Colors: the built-in default colour of Minecraft blocks, for showing block grids as coloured --- voxels. Hand-made for this library (approximate average colours picked by eye; no game assets or wiki tables were --- copied): exact block names, then families by dye colour and wood type; codecs/model/Minecraft resolves stairs / --- slabs / walls / ... to their base block and falls back to keywords. Format: name=rrggbb or name=rrggbbaa. +-- 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 = [[ @@ -85574,13 +83253,11 @@ muddy_mangrove_roots=46413a ochre_froglight=f6e8a6 verdant_froglight=dcf0d6 pear creaking_heart=5a4a3c resin_block=d9661c resin_bricks=ce5a1a ]] --- wool-like colour of each dye, then concrete and terracotta (same order as Colors.DYES) 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" --- wood types: planks, bark (log / wood), leaves 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" @@ -85590,10 +83267,8 @@ return Colors end __FILES["codecs/model/Minecraft/Legacy"] = function() local __compat = __compat local __iter = __compat.__iter --!strict --- codecs/model/Minecraft/Legacy: numeric block ids of Minecraft before 1.13 (the .schematic format, Anvil chunks with --- Blocks / Data arrays), from the Minecraft wiki "Java Edition data values/Pre-flattening" page (facts, not code): --- the 1.12 name of every id, and how the data value picks a variant for the blocks whose colour or wood depends on it --- (the modern name of that variant: wool 14 -> red_wool, planks 2 -> birch_planks). +-- 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) @@ -85637,8 +83312,7 @@ gray_glazed_terracotta silver_glazed_terracotta cyan_glazed_terracotta purple_gl blue_glazed_terracotta brown_glazed_terracotta green_glazed_terracotta red_glazed_terracotta black_glazed_terracotta concrete concrete_powder - - structure_block]]) --- legacy names whose modern name differs (data value not involved; only one-to-one renames, so the way back is exact: --- lit_furnace, powered_repeater, ... keep their legacy names) +-- 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", @@ -85702,18 +83376,15 @@ __FILES["codecs/model/Minecraft/Packed"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code, from the Minecraft wiki "Chunk format" and --- the Sponge / Litematica schematic specs: long arrays (little-endian int64s as codecs/text/Nbt keeps them) holding --- bits-wide indices either spanning long boundaries (Litematica, chunks before 1.16) or not (chunks since 1.16: --- floor(64 / bits) per long, the rest padding), and the varint byte arrays of Sponge schematics. Indices are written --- to / read from u16 little-endian buffers. Every access is bounds-checked first; never throws. +-- 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 --- longsNeeded(count, bits, spanning) -> the number of longs a packed array of count indices takes function Packed.longsNeeded(count, bits, spanning) if spanning then return math.floor((count * bits + 63) / 64 @@ -85722,8 +83393,6 @@ if spanning then ) return math.floor((count + per - 1) / per )end --- unpack(longs, bits, count, spanning, out, max) -> true | false, message: count indices into out (u16 LE, from byte --- 0); an index >= max is an error. bits 1 .. 16. function Packed.unpack(longs, bits, count, spanning, out, max) if bits < 1 or bits > 16 then return false, "unsupported: " .. bits .. "-bit packed indices" @@ -85735,7 +83404,6 @@ if bits < 1 or bits > 16 then if buffer.len(out) < count * 2 then return false, "output too small" end - -- a copy with 4 bytes of padding, so every 32-bit read stays in range local n = need * 8 local src = buffer.create(n + 4) buffer.copy(src, 0, longs, 0, n) @@ -85773,7 +83441,6 @@ if bits < 1 or bits > 16 then return true, nil end --- pack(indices, count, bits, spanning) -> longs buffer (little-endian int64s): the inverse of unpack function Packed.pack(indices, count, bits, spanning) local need = Packed.longsNeeded(count, bits, spanning) local out = buffer.create(need * 8 + 4) @@ -85783,7 +83450,6 @@ local need = Packed.longsNeeded(count, bits, spanning) local p = (spanning and((i * bits ))or(((math.floor(i / per)) * 64 + (i % per) * bits ))) local at = rshift(p, 3) local sh = band(p, 7) - -- OR the value in byte by byte (up to 3 bytes for 16 bits at a shift of 7) local x = lshift(v, sh) for k = 0, 2 do local bits8 = band(rshift(x, k * 8), 0xff) @@ -85797,7 +83463,6 @@ local need = Packed.longsNeeded(count, bits, spanning) return res end --- bitsFor(n, min) -> bits for indices 0 .. n - 1 (at least min) function Packed.bitsFor(n, min) local b = min while lshift(1, b) < n and b < 31 do @@ -85806,8 +83471,7 @@ local b = min return b end --- varints(src, offset, length, count, out, max) -> true | false, message: count unsigned LEB128 varints (Sponge --- BlockData) into out (u16 LE) +-- Sponge BlockData: unsigned LEB128 varints function Packed.varints(src, offset, length, count, out, max) if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then return false, "bad varint array arguments" @@ -85838,7 +83502,6 @@ if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then return true, nil end --- toVarints(indices, count) -> buffer: count u16 indices as unsigned LEB128 varints function Packed.toVarints(indices, count) local out = buffer.create(count * 3) local p = 0 @@ -85857,8 +83520,7 @@ local out = buffer.create(count * 3) return res end --- nibble(src, offset, i, highFirst) -> the 4-bit value i of a nibble array (Minecraft: low nibble first; WorldEdit's --- AddBlocks: high nibble first) +-- nibble arrays: Minecraft low nibble first; WorldEdit AddBlocks high nibble first function Packed.nibble(src, offset, i, highFirst) local b = readu8(src, offset + rshift(i, 1)) local odd = band(i, 1) == 1 @@ -85868,7 +83530,6 @@ local b = readu8(src, offset + rshift(i, 1)) return rshift(b, 4) end --- setNibble(dst, offset, i, v, highFirst) function Packed.setNibble(dst, offset, i, v, highFirst) local at = offset + rshift(i, 1) local b = readu8(dst, at) @@ -85880,9 +83541,7 @@ function Packed.setNibble(dst, offset, i, v, highFirst) end end --- fromYzx(src, sx, sy, sz, dst?, ox?, oy?, oz?, dsx?, dsy?) -> dst: u16 cells in Minecraft's order (x fastest, then --- z, then y: schematics, chunk sections) to Types.Voxels order (x, then y, then z), into dst (default a new --- sx * sy * sz grid) at cell offset (ox, oy, oz) of a dsx * dsy * ... grid. The caller checks the ranges. +-- Minecraft order: x fastest, then z, then y (schematics, chunk sections) function Packed.fromYzx(src, sx, sy, sz, dst, ox, oy, oz, dsx, dsy) local out = dst or buffer.create(sx * sy * sz * 2) local bx, by, bz = ox or 0, oy or 0, oz or 0 @@ -85901,7 +83560,6 @@ local out = dst or buffer.create(sx * sy * sz * 2) return out end --- toYzx(src, sx, sy, sz) -> buffer: Types.Voxels order to Minecraft's (the inverse of fromYzx) function Packed.toYzx(src, sx, sy, sz) local out = buffer.create(sx * sy * sz * 2) local i = 0 @@ -85922,18 +83580,8 @@ return Packed end __FILES["codecs/model/Polygon"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map --- sectors, ...). Loops are classified by nesting (a loop inside an odd number of other loops is a hole of the --- smallest loop around it), oriented, each hole bridged to its outer loop at a mutually visible vertex, then the --- result is ear-clipped (reflex-vertex test; a polygon that never yields a clean ear clips its least bad corner so --- every input terminates). New in rosetta, after the classic "ear clipping with hole bridging" method --- (D. Eberly, Triangulation by Ear Clipping); no code taken. --- --- local tris = Polygon.triangulate({ { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 } }) --- -- tris = { loop, index, loop, index, loop, index, ... }: three corners per triangle, each a (loop, vertex) pair --- -- (1-based), counter-clockwise --- --- Never throws; degenerate loops (fewer than 3 points, zero area) are ignored. +-- 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 = {} @@ -85966,7 +83614,6 @@ local function cross(o, a, b) return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) end --- segments p1-p2 and q1-q2 cross properly (touching at an endpoint does not count) local function crosses(p1, p2, q1, q2) if (p1.x == q1.x and p1.y == q1.y) or (p1.x == q2.x and p1.y == q2.y) or (p2.x == q1.x and p2.y == q1.y) or (p2.x == q2.x and p2.y == q2.y) then return false @@ -85988,8 +83635,6 @@ for _, r in __iter(rings) do return true end --- splice hole h into ring outer (both oriented: outer counter-clockwise, hole clockwise) at mutually visible --- vertices; others = every ring the bridge must not cross local function bridge(outer, h, others) local mi = 1 for i, p in __iter(h) do @@ -86033,7 +83678,6 @@ local function inTri(a, b, c, p) return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0 end --- ear clipping of one counter-clockwise ring local function clip(ring, out) local pts = table.clone(ring) local guard = #pts * #pts + 16 @@ -86082,7 +83726,6 @@ local function clip(ring, out) end end --- triangulate(loops) -> { loop, index, ... }: loops[i] = { x1, y1, x2, y2, ... } (closed implicitly) function Polygon.triangulate(loops) local rings= {} local areas= {} @@ -86107,7 +83750,6 @@ local rings= {} end end end - -- nesting: the parent of a ring is the smallest ring containing its first point local n = #rings local depth, parent = table.create(n, 0), table.create(n, 0) for i = 1, n do @@ -86172,46 +83814,14 @@ return Polygon end __FILES["codecs/model/Rbx"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl, --- model/rbxmx XML rbxmx / rbxlx), the typed property values, the CFrame rotation IDs, and (codecs/model/Rbx/Binary) the --- binary format's property column codecs. Shared here because a format cannot require another one. Written from the --- rbx-dom format notes (docs/binary.md, docs/xml.md) and checked against rbx-dom through rojo / lune. A file library, --- not a Roblox runtime: nothing here creates Instances; a Roblox game reads the tree itself. --- --- local tree = Rbx.tree() -- { kind = "rbxtree", roots = {}, place = false, ... } --- local part = Rbx.instance("Part", "Floor") -- { className, name, properties = {}, children = {} } --- Rbx.set(part, "Size", "Vector3", { 64, 1, 64 }) -- properties.Size = { type = "Vector3", value = {...} } --- Rbx.add(tree, part) -- a root; Rbx.add(parentInstance, child) nests --- for inst, depth in Rbx.descendants(tree) do ... end --- --- Property values are { type = , value = } with these value forms (arrays follow the Roblox constructor --- argument order, so Vector3.new(table.unpack(v.value)) / CFrame.new(table.unpack(v.value)) rebuild them in Roblox): --- String, BinaryString, ProtectedString, ContentId, Bytecode string (bytes) --- SharedString string (the content; writers deduplicate) --- Bool boolean --- Int32, Int64, Float32, Float64 number (Int64 exact to 2^53) --- Enum, BrickColor, SecurityCapabilities number --- Faces number: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32 --- Axes number: bits X 1, Y 2, Z 4 --- UDim { scale, offset } UDim2 { xScale, xOffset, yScale, yOffset } NumberRange { min, max } --- Vector2 / Vector2int16 { x, y } Vector3 / Vector3int16 { x, y, z } Color3 { r, g, b } (0..1) --- Color3uint8 { r, g, b } (0..255) Rect { minX, minY, maxX, maxY } Ray { ox, oy, oz, dx, dy, dz } --- CFrame { x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 } OptionalCFrame: the same, or nil (none) --- NumberSequence { { time, value, envelope } ... } ColorSequence { { time, r, g, b, envelope } ... } --- PhysicalProperties nil (default) | { density, friction, elasticity, frictionWeight, elasticityWeight, --- acousticAbsorption } (decoders fill acousticAbsorption = 1 when the file leaves it out) --- Ref an Instance of the tree, or nil --- UniqueId 32 hex digits: random (16), time (8), index (8) --- Font { family, weight (100..900), style ("Normal" | "Italic"), cachedFaceId? } --- Content nil (none) | string (a URI) | an Instance (object) --- Raw a binary property of a type this library does not know: { typeId, data (the class's whole column), --- index, count }; written back verbatim while the class keeps the same instances in the same order --- XmlRaw an XML property of an unknown type: value = the element (codecs/text/Xml node), written back as it is --- Name is not a property here: it is inst.name. Never throws. +-- 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 = {} --- ------------------------------------------------------------------------------------------------ tree @@ -86239,7 +83849,6 @@ function Rbx.instance(className, name) return { className = className, name = name or className, properties = {}, children = {} } end --- add(parent, child) -> child: parent is a Tree (child becomes a root) or an Instance function Rbx.add(parent, child) if parent.kind == "rbxtree" then child.parent = nil @@ -86251,19 +83860,15 @@ if parent.kind == "rbxtree" then return child end --- set(inst, name, type, value): a property (value nil = the type's nil form: Ref none, OptionalCFrame none, ...) function Rbx.set(inst, name, typ, value) inst.properties[name] = { type = typ, value = value } end --- get(inst, name) -> the property's value (not the Value table), nil when absent function Rbx.get(inst, name) local v = inst.properties[name] return (v and{v.value }or{nil })[1]end --- descendants(treeOrInstance) -> iterator over (instance, depth) in depth-first order (roots / the instance's children --- at depth 1) function Rbx.descendants(root) local stack= {} local list = (root.kind == "rbxtree" and{root.roots }or{root.children @@ -86283,7 +83888,6 @@ local top = table.remove(stack) end end --- list(tree) -> every instance, depth first function Rbx.list(tree) local out = {} for inst in __iter(Rbx.descendants(tree)) do @@ -86292,7 +83896,6 @@ local out = {} return out end --- find(treeOrInstance, path) -> the instance at a "/"-separated path of names ("Workspace/Baseplate"), or nil function Rbx.find(root, path) local cur= root for part in __iter(string.gmatch(path, "[^/]+")) do @@ -86312,7 +83915,6 @@ local cur= root return (cur.kind == "rbxtree" and{nil }or{cur })[1]end --- fullName(inst) -> "Workspace.Model.Part" (names joined up to the root) function Rbx.fullName(inst) local parts = {} local cur= inst @@ -86323,12 +83925,10 @@ local parts = {} return table.concat(parts, ".") end --- ------------------------------------------------------------------------------------------------ CFrame rotation ids -- 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 } } --- the rotation of an id as { r00 .. r22 } (row major), or nil for an id that is not a rotation local ROTATIONS= {} for a = 0, 5 do for b = 0, 5 do @@ -86351,7 +83951,6 @@ for i, a in __iter(AXES) do return nil end --- rotationId(cf) -> the id of the CFrame's rotation (cf = { x, y, z, r00 .. r22 }), or 0 when it is not axis aligned function Rbx.rotationId(cf) local a = axisIndex(cf[4], cf[7], cf[10]) local b = axisIndex(cf[5], cf[8], cf[11]) @@ -86366,7 +83965,6 @@ local a = axisIndex(cf[4], cf[7], cf[10]) return id end --- ------------------------------------------------------------------------------------------------ values -- binary type ids (rbx-dom docs/binary.md) by type name, and back Rbx.TYPE_IDS = table.freeze({ String = 0x01, @@ -86414,8 +84012,7 @@ for name, id in __iter(Rbx.TYPE_IDS) do end Rbx.TYPE_NAMES = table.freeze(NAMES) --- the value a binary writer uses for an instance without the property (zero / empty / identity; BrickColor 194, the --- Medium stone grey Roblox defaults to; sequences of two keypoints at times 0 and 1) +-- BrickColor 194 (Medium stone grey) is Roblox's default local IDENTITY_CF = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } function Rbx.default(typ) if typ == "String" or typ == "BinaryString" or typ == "ProtectedString" or typ == "ContentId" or typ == "Bytecode" or typ == "SharedString" then @@ -86448,7 +84045,6 @@ if typ == "String" or typ == "BinaryString" or typ == "ProtectedString" or typ = return 0 end --- STRINGS: the string-valued types (one binary type, several XML tags) Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString = true, ContentId = true, Bytecode = true } ) return Rbx @@ -86457,19 +84053,8 @@ __FILES["codecs/model/Rbx/Binary"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native --!optimize 2 --- codecs/model/Rbx/Binary: the property columns of the Roblox binary format (rbx-dom docs/binary.md): one PROP chunk --- holds a property's values for every instance of a class, by type id, with the format's array transforms: byte --- interleaving (all first bytes, then all second bytes, ...), big-endian integers, zigzag signed integers, "rotated" --- floats (sign bit moved to bit 0), delta-coded referents, and CFrame rotation ids (codecs/model/Rbx). Never throws. --- --- local values, pEnd = Binary.decode(typeId, buf, p, limit, n, ctx) -- n plain values (codecs/model/Rbx forms) --- local err = Binary.encode(typeId, values, n, writer, ctx) -- nil, or a message --- Binary.readRefs(buf, p, limit, n) / Binary.writeRefs(writer, refs) -- referent arrays (INST, PRNT) --- --- ctx: { ref = function(referent) -> Instance? (decode), refOf = function(Instance?) -> referent (-1 = none), --- shared = { string } (SSTR entries, 1-based, decode), sharedIndex = function(string) -> 0-based index (encode) }. --- decode returns nil, message on bad data ("truncated", "corrupt: ...", "unknown" for a type id it does not know / --- a layout it cannot read, which the format keeps raw). +-- 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") @@ -86484,7 +84069,6 @@ local floor = math.floor local scratch = buffer.create(8) local TWO32 = 4294967296 --- ------------------------------------------------------------------------------------------------ transforms -- the rotated float encoding: bits rotated left by one (sign in bit 0) local function unrotate(x) writeu32(scratch, 0, math.floor(x / 2 )+ (x % 2) * 2147483648) @@ -86503,7 +84087,6 @@ v = floor(v) return ((v >= 0 and((v * 2 ))or((-v * 2 - 1)))) % TWO32 end --- n big-endian u32 values interleaved at p (4n bytes) local function u32s(b, p, n) local out = table.create(n, 0) local n2, n3 = n * 2, n * 3 @@ -86526,7 +84109,6 @@ local out = u32s(b, p, n) end return out end --- n zigzag i64 values (8n interleaved bytes), as doubles local function i64s(b, p, n) local out = table.create(n, 0) for i = 0, n - 1 do @@ -86538,7 +84120,6 @@ local out = table.create(n, 0) return out end --- writers: n values interleaved as big-endian u32 / zigzag i32 / rotated f32 / zigzag i64 local function putU32s(w, vals) local n = #vals local p = w:reserve(4 * n) @@ -86608,8 +84189,6 @@ function Binary.writeRefs(w, refs) end putI32s(w, d) end --- ------------------------------------------------------------------------------------------------ decode --- a length-prefixed string at p: string, next p (nil when it runs past limit) @@ -86667,7 +84246,7 @@ for i = 1, n do return out, p + 12 * n end -local FIXED= { -- bytes per value of the fixed-size types +local FIXED= { [0x02] = 1, [0x03] = 4, [0x04] = 4, @@ -86694,7 +84273,6 @@ local FIXED= { -- bytes per value of the fixed-size types [0x21] = 8, } --- decode(typeId, b, p, limit, n, ctx) -> n values, the end offset | nil, message function Binary.decode(t, b, p, limit, n, ctx) if limit > buffer.len(b) or p < 0 or n < 0 then return nil, "corrupt: bad ranges" @@ -86987,11 +84565,9 @@ for c = 1, k do return nil, "unknown" end --- ------------------------------------------------------------------------------------------------ encode local function num(v) return (type(v) == "number" and v == v and{v }or{0 })[1]end --- column c of n array values (missing components 0) local function column(vals, n, c) local out = table.create(n, 0) for i = 1, n do @@ -87027,8 +84603,6 @@ local function hexByte(s, i) return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0 end --- encode(typeId, values, n, w, ctx) -> nil | message: values[1 .. n] in the codecs/model/Rbx forms (nil entries are --- the type's none / default) function Binary.encode(t, vals, n, w, ctx) if t == 0x01 or t == 0x1D then for i = 1, n do @@ -87231,18 +84805,7 @@ return Binary end __FILES["codecs/model/Rig"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each --- format only parses its file: vertex-animation frames as morph targets plus "weights" animations, joint hierarchies --- as Scene nodes plus a Skin (inverse bind matrices), per-vertex joint influences as JOINTS_0 / WEIGHTS_0, and --- keyframed joint TRS tracks as animation channels. New in rosetta. --- --- Rig.morph(prim, frames) -- frames[k] = f32 x3 positions: targets[k] = frame k - base --- Rig.morphAnimation(scene, node, #frames, { { name = "run", first = 41, last = 46, fps = 10 } }, "LINEAR") --- local nodes, skin = Rig.skeleton(scene, joints, "world") -- joints = { { name, parent (0 = root), t, r, s? } } --- prim.attributes.JOINTS_0, prim.attributes.WEIGHTS_0 = Rig.influences(lists) -- lists[v] = { j1, w1, j2, w2, ... } --- Rig.animation(scene, "idle", nodes, times, tracks) -- tracks[j] = { translation = {...}, rotation = {...} } --- --- Frames, joints and tracks come from parsed files: the helpers check every count they rely on and never throw. +-- 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") @@ -87251,10 +84814,6 @@ local Rig = {} local Scene = Types.Scene local readf32, writef32, writeu16 = buffer.readf32, buffer.writef32, buffer.writeu16 --- ------------------------------------------------------------------------------------------------ morph targets --- morph(prim, frames, normals?, base?) -> (): prim.targets[k] = { POSITION = frames[k] - base positions } (and NORMAL --- deltas when normals[k] is given), base = prim.attributes.POSITION (and NORMAL). Every frame buffer must hold as --- many f32 x3 as the base; shorter ones are skipped (false is returned). @@ -87302,9 +84861,6 @@ local pos = prim.attributes.POSITION return ok end --- morphAnimation(scene, node, targets, ranges, interpolation?) -> (): one animation per range, a "weights" channel on --- scene.nodes[node] whose key k (at (k - first) / fps seconds) sets target k to 1 and the others to 0 (LINEAR --- blends neighbouring frames, as the games do; default "LINEAR"). Ranges out of 1..targets are clamped / skipped. function Rig.morphAnimation(scene, node, targets, ranges, interpolation) for _, rg in __iter(ranges) do local first, last = math.max(1, math.floor(rg.first)), math.min(targets, math.floor(rg.last)) @@ -87333,9 +84889,7 @@ function Rig.morphAnimation(scene, node, targets, ranges, interpolation) end end --- normals(pos, count, indices) -> f32 x3 buffer: smooth vertex normals (area-weighted face normals, normalised) of a --- triangle list (indices: 0-based, three per triangle; out-of-range triangles are skipped). For formats whose stored --- normals cannot be used (Quake's precomputed normal table is not redistributable here). +-- Quake's precomputed normal table is not redistributable here function Rig.normals(pos, count, indices) local out = buffer.create(count * 12) local acc = table.create(count * 3, 0) @@ -87366,13 +84920,11 @@ end end return out end --- ------------------------------------------------------------------------------------------------ skeletons local function trs(j) return Mat4.compose(j.translation, j.rotation, j.scale) end --- angles(x, y, z) -> quaternion { x, y, z, w } of the Euler angles in radians applied x first, then y, then z --- (R = Rz * Ry * Rx: the Quake / Half-Life "AngleQuaternion" convention of MDL bones and SMD skeletons) +-- R = Rz * Ry * Rx: the Quake / Half-Life AngleQuaternion convention of MDL bones and SMD skeletons function Rig.angles(x, y, z) local sy, cy = math.sin(z / 2), math.cos(z / 2) local sp, cp = math.sin(y / 2), math.cos(y / 2) @@ -87380,10 +84932,6 @@ local sy, cy = math.sin(z / 2), math.cos(z / 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 --- skeleton(scene, joints, space, root?) -> (joint node indices, skin index, world matrices): one node per joint (TRS relative to its --- parent), parented as listed, roots added to scene.roots (or as children of node `root`); a Skin with the inverse --- bind matrices. space "local": joint TRS are relative to the parent (SMD, MDL); "world": in model space (MD5's --- bind pose), converted to local here. A parent index that does not come earlier makes the joint a root. function Rig.skeleton(scene, joints, space, root) local n = #joints local world= {} @@ -87429,9 +84977,6 @@ local n = #joints return nodes, #scene.skins, world end --- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with --- 0-based joint indices (into the skin's joints; a joint listed twice adds up); the four largest weights are kept --- and normalised to sum 1. function Rig.influences(lists) local n = #lists local jb, wb = buffer.create(n * 8), buffer.create(n * 16) @@ -87442,7 +84987,7 @@ local n = #lists if l[k + 1] > 0 then local same = at[l[k] ] if same then - same[2]=same[2]+ l[k + 1] -- the same joint twice: one influence + same[2]=same[2]+ l[k + 1] else local e = { l[k], l[k + 1] } at[l[k] ] = e @@ -87465,7 +85010,6 @@ return a[2] > b[2] return Scene.accessor(jb, "u16", 4, n), Scene.accessor(wb, "f32", 4, n) end --- ------------------------------------------------------------------------------------------------ animations local function floats(t, count, comps) if #t < count * comps then return nil @@ -87477,9 +85021,6 @@ if #t < count * comps then return Scene.accessor(b, "f32", comps, count) end --- animation(scene, name, nodes, times, tracks, interpolation?) -> the animation index: tracks[j] (j = index into --- nodes) holds flat translation (x3) / rotation (quaternion x4) / scale (x3) keys, one per time (seconds); tracks --- with too few keys are skipped. Default interpolation "LINEAR". function Rig.animation(scene, name, nodes, times, tracks, interpolation) local count = #times local input = floats(times, count, 1) @@ -87507,17 +85048,7 @@ return Rig end __FILES["codecs/model/Sampler"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for --- rotations, CUBICSPLINE Hermite splines as glTF 2.0 defines them; times before the first / after the last key hold --- the end values), and the node poses of an animation at a time, for writers of formats that store sampled frames --- (IQM, MD5, BVH, ...). New in rosetta. --- --- local sample = Sampler.channel(ch) -- nil for an unreadable channel --- local v = sample(0.5) -- { x, y, z } / { x, y, z, w } / the morph weights --- local times = Sampler.times(anim) -- every key time of the animation, sorted, unique --- local pose = Sampler.pose(scene, anim, 0.5) -- pose[node] = { translation?, rotation?, scale?, weights? } --- --- Never throws on bad data: unreadable channels are skipped. +-- codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 animations. New code. local Types = __include("Types") local Sampler = {} @@ -87550,7 +85081,6 @@ local d = a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] return normalize({ a[1] * wa + bx * wb, a[2] * wa + by * wb, a[3] * wa + bz * wb, a[4] * wa + bw * wb }) end --- channel(ch) -> sample(t) | nil function Sampler.channel(ch) local inp, out = ch.input, ch.output if type(inp) ~= "table" or type(out) ~= "table" then @@ -87577,7 +85107,6 @@ for k = 1, n do times[k] = IN(k - 1, 0) end local oc = out.components - -- element e (0-based, of comps values) of the flat output local function get(e) local v = (table.create(comps) ) for c = 0, comps - 1 do @@ -87635,7 +85164,6 @@ for c = 1, comps do end end --- times(anim) -> every key time, sorted and unique function Sampler.times(anim) local seen= {} local out= {} @@ -87656,8 +85184,6 @@ local seen= {} return out end --- pose(scene, anim, t, samplers?) -> pose[node] = { [path] = values } for the animated nodes. samplers: a cache table --- (reuse it across calls for the same animation) function Sampler.pose(_scene, anim, t, samplers) local cache= samplers or {} local pose= {} @@ -87682,14 +85208,8 @@ return Sampler end __FILES["codecs/model/Vrml"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML, --- .x3dv classic): one parser for the classic encoding (codecs/model/Vrml/Parse), one for the XML encoding --- (codecs/model/Vrml/Xml over codecs/text/Xml), both into the same node graph, and one builder from the graph to a --- Scene (codecs/model/Vrml/Build, codecs/model/Vrml/Geometry). Gzipped files (.wrz / .x3dz / .x3dvz) are inflated --- first. New code, written from ISO/IEC 14772-1 (VRML97), ISO/IEC 19775-1 (X3D) and its encodings 19776-1 / -2. --- --- local graph, err = Vrml.graph(bytes) -- classic or XML, by content --- local scene, err2 = Vrml.decode(bytes, { format = "vrml", files = { ["tex.png"] = png } }) +-- 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") @@ -87701,7 +85221,6 @@ local Write = __include("codecs/model/Vrml/Write") local Vrml = {} --- the bytes as text: gzip inflated, UTF-8 BOM dropped @@ -87740,7 +85259,6 @@ if string.find(msg, "unsupported", 1, true) then return Err.CORRUPT end --- parse(text) -> the graph of a classic-encoding file (VRML97 / .x3dv) function Vrml.parse(s) local g, msg = Parse.parse(s) if not g then @@ -87749,7 +85267,6 @@ local g, msg = Parse.parse(s) return g, nil end --- parseXml(text | XML document) -> the graph of an X3D XML file function Vrml.parseXml(src) local doc = src if type(src) == "string" then @@ -87770,7 +85287,6 @@ local doc = src return g, nil end --- graph(bytes, opts?) -> the graph of either encoding (XML when the text starts with "<"); binary X3D is UNSUPPORTED function Vrml.graph(data, opts) local s, err = text(data, opts and opts.maxBytes) if not s then @@ -87786,7 +85302,6 @@ local s, err = text(data, opts and opts.maxBytes) return Vrml.parse(s) end --- fetcher(opts) -> fetch(uri) -> buffer?: opts.files (uri or base name) / opts.resolve function Vrml.fetcher(opts) return function(uri) if not opts then @@ -87804,7 +85319,6 @@ if not opts then })[1]})[1] end end --- build(graph, opts?) -> Scene function Vrml.build(graph, opts) local o= table.clone(opts or {}) o.fetch = o.fetch or Vrml.fetcher(opts) @@ -87819,7 +85333,6 @@ local g, err = Vrml.graph(data, opts) return scene, nil end --- decode(bytes, opts?) -> Scene: graph + build function Vrml.decode(data, opts) local g, err = Vrml.graph(data, opts) if not g then @@ -87828,7 +85341,6 @@ local g, err = Vrml.graph(data, opts) return Vrml.build(g, opts) end --- encode(scene, opts?) -> text: opts.encoding "vrml97" (default) / "x3dv" / "xml"; texture bytes go into opts.files function Vrml.encode(scene, opts) if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then return nil, Err.new(Err.ARG, "needs a Scene") @@ -87844,18 +85356,9 @@ return Vrml end __FILES["codecs/model/Vrml/Build"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/model/Vrml/Build: the VRML97 / X3D node graph (codecs/model/Vrml/Parse, codecs/model/Vrml/Xml) to a Scene. --- Written from the specifications; no third-party code. Grouping nodes (Group, Transform with center / scaleOrientation, --- Anchor, Billboard, Collision, StaticGroup, Switch whichChoice, LOD first level, CAD and HAnim groups, Inline through --- the fetch callback) become nodes; a Transform is one TRS node (translation T + C, rotation R * SR, scale S) and, when --- it has a center or scale orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children. --- Shapes become meshes (shared by USE), Appearance / Material / PhysicalMaterial / UnlitMaterial / TwoSidedMaterial --- materials (Phong terms in material.extras.vrml; solid FALSE -> doubleSided), ImageTexture / MovieTexture --- (uri, data through fetch, repeatS / repeatT), PixelTexture (texture.image), TextureTransform (KHR transform: --- translation / scale / rotation; the center in extras); Viewpoint / OrthoViewpoint -> cameras, DirectionalLight / --- PointLight / SpotLight -> lights; ROUTEs from a TimeSensor through Position- / OrientationInterpolators to a --- Transform's translation / rotation / scale -> animations (key times x cycleInterval). Other nodes are counted in --- meta.source.skipped. Never throws: bad data returns nil, message. +-- 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") @@ -87877,7 +85380,6 @@ local deg = math.deg local GROUP = { Group = true, Anchor = true, Billboard = true, Collision = true, StaticGroup = true, CADAssembly = true, CADLayer = true, LayerSet = true, Layer = true, HAnimSegment = true, HAnimSite = true, LOD = true, Switch = true } local TRANSFORM = { Transform = true, CADPart = true, HAnimHumanoid = true, HAnimJoint = true } local CHILDREN = { "children", "skeleton", "segments", "sites", "layers" } --- nodes with nothing to show (not counted as skipped) local QUIET = { WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true, PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true, @@ -87912,7 +85414,6 @@ end local function isIdentityQ(q) return q[1] == 0 and q[2] == 0 and q[3] == 0 end --- the rotation taking unit vector a onto b local function between(a, b) local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3]) if l < 1e-12 then @@ -87921,7 +85422,6 @@ local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3]) 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 - -- opposite: half a turn about any perpendicular axis return math.abs(a[1]) < 0.9 and{ 0, a[3], -a[2], 0 } or{ -a[3], 0, a[1], 0 } end local cx, cy, cz = a[2] * bz - a[3] * by, a[3] * bx - a[1] * bz, a[1] * by - a[2] * bx @@ -87955,7 +85455,6 @@ local nodes_ = ctx.scene.nodes return i end --- ------------------------------------------------------------------------------------------------ materials local function texture(ctx, t) if not t then return nil @@ -88127,7 +85626,6 @@ if not app and solid then return idx end --- ------------------------------------------------------------------------------------------------ nodes local walk local function shape(ctx, n, parent) @@ -88149,7 +85647,6 @@ return end local count = (prim.indices and{prim.indices.count }or{prim.attributes.POSITION.count })[1] if count == 0 then - -- nothing to draw (no valid faces / points) ctx.meshes[n] = false return end @@ -88336,11 +85833,9 @@ src.title = str(n, "title") ctx.depth =ctx.depth- 1 end --- ------------------------------------------------------------------------------------------------ animation local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" } local function animations(ctx, routes) - -- interpolator -> its TimeSensor local timer= {} for _, r in __iter(routes) do if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then @@ -88409,7 +85904,6 @@ __DARKLUA_CONTINUE_11=true until true if not __DARKLUA_CONTINUE_11 then break en end end --- ------------------------------------------------------------------------------------------------ scene function Build.scene(graph, opts) local scene = S.new() scene.meta.up = "y" @@ -88436,15 +85930,11 @@ return Build end __FILES["codecs/model/Vrml/Fields"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- codecs/model/Vrml/Fields: typed reads of node fields for codecs/model/Vrml/Build and Geometry. A classic-encoding --- value is a flat array (numbers, strings, booleans, nodes); an X3D XML value is the raw attribute string, parsed here --- on first use (numbers split on blanks / commas, MFString as quoted strings or one unquoted string, booleans --- true / false). Never throws. +-- 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 --- quoted strings of an MFString attribute ("a" "b \"c\""), or the text itself when it is not quoted local function mfString(s) local out = {} local p = find(s, "[^%s,]") @@ -88480,7 +85970,6 @@ local out = {} return out end --- nums(node, name) -> the numbers of a field (booleans as 1 / 0), or nil when absent function Fields.nums(node, name) local v = node.fields[name] if v == nil then @@ -88530,7 +86019,6 @@ local v = Fields.nums(node, name) return (v and type(v[1]) == "number" and{v[1] }or{default })[1]end --- vec(node, name, default) -> the first #default numbers of a field (the default when the field is shorter) function Fields.vec(node, name, default) local v = Fields.nums(node, name) if not v or #v < #default then @@ -88584,7 +86072,6 @@ local v = node.fields[name] return default end --- nodes(node, name) -> the nodes of an SFNode / MFNode field function Fields.nodes(node, name) local v = node.fields[name] local out = {} @@ -88606,14 +86093,8 @@ return Fields end __FILES["codecs/model/Vrml/Geometry"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. Written from the specifications; no --- third-party code. IndexedFaceSet (coord / normal / color / texCoord with their own indices, per-vertex or per-face --- normals and colours, ccw, convex polygons fan-triangulated or kept as "polygons"), the X3D triangle / quad sets --- (IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, TriangleFanSet, IndexedTriangleStripSet, --- TriangleStripSet, IndexedQuadSet, QuadSet), ElevationGrid, Extrusion (spine-aligned cross sections, scale, --- orientation, caps), IndexedLineSet / LineSet ("lines"), PointSet ("points"), and the primitives Box, Sphere, Cone, --- Cylinder tessellated with normals and the specification's texture mapping. Texture coordinates get t flipped to --- glTF's top-left origin unless flipV = false. Never throws: returns nil, message for bad data. +-- 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") @@ -88642,7 +86123,6 @@ local a = S.accessor(nil, "u32", 1, #list) return a end --- the colour node's values and component count (Color: 3, ColorRGBA: 4) local function colors(n) local c = node(n, "color") if not c then @@ -88656,9 +86136,6 @@ local function points(n, field, sub) local c = node(n, field) return (c and{nums(c, sub) or {} }or{nil })[1]end --- ------------------------------------------------------------------------------------------------ polygon meshes --- Mesh input: faces as corner lists of coordinate indices (0-based) plus, per attribute, a per-corner index list (nil: --- the coordinate index) or per-face indices. @@ -88675,7 +86152,6 @@ local P, corners, sizes = m.P, m.corners, m.sizes local np = math.floor(#P / 3 ) local N, C, T = m.N, m.C, m.T local cc = m.cComps or 3 - -- the attribute index of corner k (1-based) in face f (1-based) local function idx(list, perFace, f, k, c) if perFace then return (list and #list > 0 and{(list[f] or 0) }or{(f - 1 @@ -88684,7 +86160,7 @@ if perFace then })[1] end local simple = (N == nil or (not m.nFace and (m.nIdx == nil or #m.nIdx == 0))) and (C == nil or (not m.cFace and (m.cIdx == nil or #m.cIdx == 0))) and (T == nil or m.tIdx == nil or #m.tIdx == 0) local vkey= {} - local vsrc= {} -- per output vertex: coord, normal, colour, texcoord indices + local vsrc= {} local out= {} local outSizes= {} local k = 0 @@ -88786,7 +86262,6 @@ if perFace then return prim end --- split a -1 separated index list into corners + sizes local function split(list) local corners, sizes = {}, {} local run = 0 @@ -88837,7 +86312,6 @@ local P = points(n, "coord", "point") or {} return polyMesh(m, o, maxV) end --- the X3D triangle / quad sets: faces from index (or vertex order) and fan / strip counts local function triSet(n, o, maxV) local t = n.type local P = points(n, "coord", "point") or {} @@ -88966,7 +86440,6 @@ local nx, nz = math.floor(num(n, "xDimension", 0)), math.floor(num(n, "zDimensio return polyMesh(m, o, maxV) end --- ------------------------------------------------------------------------------------------------ Extrusion local function cross(a, b) return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } end @@ -89096,7 +86569,6 @@ return ((i - 1) % nr) * nring + (j - 1) % nring return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV) end --- ------------------------------------------------------------------------------------------------ lines, points local function lines(n, maxV) local P = points(n, "coord", "point") or {} local np = math.floor(#P / 3 @@ -89190,8 +86662,6 @@ local P = points(n, "coord", "point") or {} return { attributes = attrs, mode = "points" } end --- ------------------------------------------------------------------------------------------------ primitives --- a primitive from flat arrays (positions, normals, uvs with the specification's bottom-left origin, triangles) local function direct(P, N, T, I, o) local nv = math.floor(#P / 3 ) if o.flipV ~= false then @@ -89235,8 +86705,7 @@ local s = vec(n, "size", { 2, 2, 2 }) return direct(P, N, T, I, o) end --- a ring of segs + 1 vertices (the seam doubled for the texture) at height y, radius r; s starts at the back (-z) --- and runs counter-clockwise seen from +y +-- a ring of segs + 1 vertices (seam doubled); s starts at the back (-z) and runs counter-clockwise seen from +y local function ring(P, N, T, segs, y, r, t, ny, nr) for i = 0, segs do local a = 2 * pi * i / segs @@ -89256,7 +86725,6 @@ local function ring(P, N, T, segs, y, r, t, ny, nr) end end --- a cap disc at height y facing ny (+1 / -1) local function cap(P, N, T, I, segs, y, r, ny) local b = math.floor(#P / 3 ) for i = 0, segs - 1 do @@ -89286,7 +86754,6 @@ local function cap(P, N, T, I, segs, y, r, ny) end end --- quads between two rings of segs + 1 vertices starting at a (lower) and b (upper) local function band(I, a, b, segs) for i = 0, segs - 1 do table.insert(I, a + i) @@ -89334,9 +86801,6 @@ local r = num(n, cone and"bottomRadius" or"radius", 1) return direct(P, N, T, I, o) end --- ------------------------------------------------------------------------------------------------ dispatch --- primitive(geometryNode, opts) -> Primitive | nil, message | nil, nil (a node type without geometry here); --- the second value of a success is the node's solid flag function Geometry.primitive(n, o) local t = n.type local maxV = o.maxVertices or 2 ^ 24 @@ -89378,16 +86842,9 @@ return Geometry end __FILES["codecs/model/Vrml/Parse"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic VRML encoding (ISO/IEC 19776-2) parser, into --- the node graph codecs/model/Vrml/Build reads. Written from the specifications; no third-party code. Field types are --- not known without the node schemas, so a field value is kept as a flat array of what the file wrote (numbers, --- strings, booleans, nodes) and the builder reads it as the type it expects. Handles comments, DEF / USE, PROTO --- (instances are expanded: IS fields take the instance's values or the declared defaults; nested PROTOs, ROUTEs inside --- bodies), EXTERNPROTO (instances stay nodes of that type, without a body), Script / shader interface declarations, --- ROUTE, and the X3D header statements (PROFILE, COMPONENT, META, UNIT, IMPORT, EXPORT). Never throws: errors are --- returned as nil, message ("line N: ..."). +-- 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 = {} --- an IS reference in a PROTO body: fields[name] = { is = "protoField" } @@ -89410,7 +86867,6 @@ 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 } --- copy(node, values, defaults, memo) -> a PROTO body node with its IS fields replaced (shared nodes stay shared) local function copy(node, values, defaults, memo) local done = memo[node] if done then @@ -89439,7 +86895,6 @@ local done = memo[node] return out end --- expand(proto, values, def, routes) -> the instance's node (the body's first node), or nil for an EXTERNPROTO function Parse.expand(proto, values, def, routes) if proto.extern or #proto.body == 0 then return nil @@ -89504,8 +86959,6 @@ local l = 1 end end - -- the lexer: skip blanks, commas and comments; returns the next token kind and value - -- kinds: "num", "str", "id", "{", "}", "[", "]", ".", "eof" local function skip() while true do local q = find(text, "[^%s,]", p) @@ -89568,7 +87021,6 @@ skip() p =p+ 1 return ".", nil end - -- +inf / -nan style words: read the word local _, we = find(text, "^[^%s,%[%]{}#\"]+", p) local w = sub(text, p, we) p = (we ) + 1 @@ -89599,13 +87051,11 @@ local save = p local parseNode local parseProto local parseRoute - -- a field value (after its name): an array of numbers / strings / booleans / nodes local function value() local k, val = token() if k == "[" then local out = {} - -- fast path: a bracket of plain numbers (big coordinate arrays) local close = find(text, "]", p, true) if close then local seg = sub(text, p, close - 1) @@ -89677,7 +87127,6 @@ __DARKLUA_CONTINUE_9=true until true if not __DARKLUA_CONTINUE_9 then break end return {} end - -- the fields of a node body, up to its "}" local function body(node) while not failure do local k, name = token() @@ -89824,7 +87273,7 @@ local k1, a = token() end end if extern then - value() -- the url list + value() protos[name] = proto return end @@ -89857,7 +87306,6 @@ local k1, a = token() protos[name] = proto end - -- statements while not failure do local k, w = token() if k == "eof" then @@ -89916,25 +87364,13 @@ return Parse end __FILES["codecs/model/Vrml/Write"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML text, --- for model/vrml and model/x3d. New code. Every node becomes a DEF'd Transform (a matrix is decomposed into TRS; --- shear is lost), each primitive a Shape: triangles / polygons / strips / fans -> IndexedFaceSet (coord, normal, --- texCoord with t flipped back unless flipV = false, color; per-vertex, ccw, solid = not doubleSided), lines -> --- IndexedLineSet, points -> PointSet; a mesh used twice is written once and USE'd. Materials -> Appearance / Material --- (diffuse = baseColor, transparency = 1 - alpha, emissive, shininess from roughness, the Phong terms of --- material.extras.vrml when present) with an ImageTexture (the texture bytes go into opts.files named after the uri or --- opts.name, else url = texture.uri). Cameras -> Viewpoint (X3D: OrthoViewpoint for orthographic ones), lights -> --- Directional / Point / SpotLight, animations (translation / rotation / scale channels) -> a TimeSensor and --- Position / OrientationInterpolators with ROUTEs (cubic splines keep their values, weights channels are dropped). --- Never throws: returns nil, message. +-- 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 = {} --- a written node: fields in order, each { name, kind, value }; kinds: "sf" / "mf" (numbers; mf groups `per` numbers --- per line), "bool", "str", "mstr" (MFString), "node", "nodes" @@ -89962,7 +87398,6 @@ local function F(n, name, kind, value, per) table.insert(n.fields, { name, kind, value, per }) end --- names: valid, unique DEF names local function namer() local used= {} return function(name, fallback) @@ -89980,7 +87415,6 @@ local s = string.gsub(name or "", "[^%w_]", "_") end end --- axis-angle of a quaternion (x, y, z, w) local function axisAngle(q) local x, y, z, w = q[1], q[2], q[3], q[4] local l = math.sqrt(x * x + y * y + z * z + w * w) @@ -89994,7 +87428,6 @@ local x, y, z, w = q[1], q[2], q[3], q[4] return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) } end --- ------------------------------------------------------------------------------------------------ geometry local function values(acc) return (Flatten.numbers(acc)) end @@ -90062,7 +87495,6 @@ return n == "NORMAL" or n == "TEXCOORD_0" or n == "COLOR_0" return g, nil end --- Coordinate from POSITION, Color / ColorRGBA from COLOR_0 (lines and points) local function coordNode(prim) local pos = values(prim.attributes.POSITION) if not pos then @@ -90158,7 +87590,6 @@ local coord, nv = coordNode(prim) return g, nil end --- ------------------------------------------------------------------------------------------------ materials local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2" } local function textureUrl(scene, i, o, written) @@ -90264,7 +87695,6 @@ local m = scene.materials[mi] return app end --- ------------------------------------------------------------------------------------------------ the tree function Write.graph(scene, o) local x3d = o.encoding == "x3dv" or o.encoding == "xml" local name = namer() @@ -90277,7 +87707,6 @@ local x3d = o.encoding == "x3dv" or o.encoding == "xml" local function shapes(mi) local done = meshShapes[mi] if done then - -- USE the shapes written before local out = {} for _, s in __iter(done) do table.insert(out, { type = "Shape", use = s.def, fields = {} }) @@ -90406,7 +87835,6 @@ local n = scene.nodes[ni] local roots= {} local list = scene.roots if type(list) ~= "table" or #list == 0 then - -- no roots: every node without a parent local child = {} for _, n in __iter(scene.nodes) do for _, c in __iter(n.children or {}) do @@ -90434,7 +87862,6 @@ local n = scene.nodes[ni] end end - -- animations: a TimeSensor per animation, an interpolator per channel local routes= {} for ai, anim in __iter(scene.animations or {}) do local tmax = 0 @@ -90494,14 +87921,12 @@ local n = scene.nodes[ni] return roots, routes, nil end --- ------------------------------------------------------------------------------------------------ serializers local function numbers(vals, per, indent) local out = table.create(#vals) for i, v in __iter(vals) do out[i] = fmt(v) end if per == 0 then - -- index lists: one face per line local lines, cur = {}, {} for i, v in __iter(vals) do table.insert(cur, out[i]) @@ -90582,7 +88007,6 @@ if n.use then return concat(out, "\n") .. "\n" end --- the containerField a child element needs when it is not its type's default local DEFAULT = { Appearance = "appearance", Material = "material", ImageTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", IndexedFaceSet = "geometry", IndexedLineSet = "geometry", PointSet = "geometry" } local function xml(roots, routes) @@ -90652,7 +88076,6 @@ local attrs = Types.object() return s, nil end --- text(scene, opts) -> the file text function Write.text(scene, o) local roots, routes, err = Write.graph(scene, o) if not roots or not routes then @@ -90668,13 +88091,7 @@ return Write end __FILES["codecs/model/Vrml/Xml"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the node graph of codecs/model/Vrml/Parse, so one --- builder serves .wrl, .x3dv and .x3d. Written from the specification; no third-party code. Elements are nodes; --- attributes stay raw strings (the builder parses them as the type it expects); child nodes go into their --- containerField (or the default field of their type: geometry, appearance, material, coord, ...); DEF / USE; ROUTE; --- ProtoDeclare (ProtoInterface fields with value attributes or child nodes, ProtoBody, IS / connect) and --- ProtoInstance (fieldValue) are expanded through Parse.expand; ExternProtoDeclare instances stay plain nodes; head / --- meta, UNIT, component and the profile go into the graph header. Never throws. +-- 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") @@ -90733,7 +88150,6 @@ local function route(el) end end local declare - -- the child elements of a node into its fields local function children(el, node) for _, ch in __iter(el.children) do @@ -90769,7 +88185,6 @@ __DARKLUA_CONTINUE_2=true break -- Script / shader interfaces __DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end end end - -- a field value of ProtoInterface / fieldValue: the value attribute, or the child nodes local function fieldValue(el) if el.attrs.value ~= nil then return el.attrs.value @@ -90909,19 +88324,6 @@ end __FILES["codecs/text/Json"] = function() local __compat = __compat local buffer, typeof, type = __compat.buffer, __compat.typeof, __compat.type --!strict -- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. --- Values are plain Luau: objects -> tables (string keys), arrays -> arrays, null -> Types.null (opts.null), numbers --- -> doubles (opts.bigInts = "string" keeps integers past 2^53 as their text). Empty objects are Types.object() so --- they write back as {}; opts.ordered makes every object a Types.object with its key order. --- --- local Json = require("rosetta.codecs.text.Json") --- local v, err = Json.decode('{"a": [1, 2, null]}') -- string | buffer; nil, Err on bad input --- local s = Json.encode(v, { indent = 2 }) -- string | nil, Err --- for ev, x in Json.events(text) do ... end -- pull events without building the tree --- for i, v, err in Json.lines(ndjson) do ... end -- JSON Lines / concatenated JSON values --- local w = Json.writer({ indent = 2 }); w:beginObject(); w:key("a"); w:value(1); w:endObject(); w:tostring() --- --- Streaming: decodeAt(src, pos) parses one value and returns where the next begins; events() is a pull tokenizer; --- writer() builds output incrementally and flush() hands back the text so far. Never throws. local Err = __include("core/Err") local Types = __include("Types") local Decode = __include("codecs/text/Json/Decode") @@ -90955,8 +88357,6 @@ local m = tostring(msg) })[1]})[1] return Err.new(code, m, at) end --- decode(src, opts?) -> value | nil, Err. One JSON text: a value with optional whitespace around it (a UTF-8 BOM is --- skipped). Note a JSON null top-level value decodes to opts.null (Types.null by default), never nil. function Json.decode(src, opts) local s, terr = text(src) if not s then @@ -90974,8 +88374,6 @@ if e <= #s then return v, nil end --- decodeAt(src, pos?, opts?) -> value, nextPos | nil, Err. One value starting at pos (1-based, default 1; leading --- whitespace skipped); nextPos is just past it. nil, nil when only whitespace is left. function Json.decodeAt(src, pos, opts) local s, terr = text(src) if not s then @@ -90992,8 +88390,6 @@ if i > #s then return v, ni end --- lines(src, opts?) -> iterator: index, value (JSON Lines, or any whitespace-separated sequence of JSON values). A --- bad value gives a last index, nil, Err: for i, v, err in Json.lines(s) do if err then ... end end function Json.lines(src, opts) local s, terr = text(src) local pos = 1 @@ -91021,8 +88417,6 @@ if dead then end end --- events(src, opts?) -> iterator: event, value. Events: "object", "endObject", "array", "endArray", "key" (the key), --- "value" (a scalar), and on bad input one final "error", Err. function Json.events(src, opts) local s, terr = text(src) if not s then @@ -91047,7 +88441,6 @@ local ev, v, at = nextEv() end end --- encode(value, opts?) -> string | nil, Err function Json.encode(value, opts) local s, msg = Encode.encode(value, opts) if not s then @@ -91056,12 +88449,8 @@ local s, msg = Encode.encode(value, opts) return s, nil end -Json.quote = Encode.quote -- quote(s) -> '"..."' with JSON escapes -Json.number = Encode.number -- number(x) -> the shortest round-trip text (nil for NaN / inf) --- ------------------------------------------------------------------------------------------------ writer --- writer(opts?) -> a streaming Writer: beginObject / endObject / beginArray / endArray / key(k) / value(v) (any --- value, encoded whole), then tostring() for everything or flush() for the text since the last flush. Misuse (a key --- outside an object, a value where a key is due, unbalanced ends) is recorded in w.err and later calls do nothing. +Json.quote = Encode.quote +Json.number = Encode.number @@ -91078,10 +88467,10 @@ Json.number = Encode.number -- number(x) -> the shortest round-trip text (nil fo function Json.writer(opts) local st = Encode.state(opts) local ind = st.indent - local kinds= {} -- true = object + local kinds= {} local counts= {} local depth = 0 - local keyDone = false -- an object's key written, its value due + local keyDone = false local flushed= {} local w= { err = nil } local function bad(msg) @@ -91089,7 +88478,6 @@ local st = Encode.state(opts) w.err = Err.new(Err.ARG, msg) end end - -- before an element: a comma / newline as needed; false when the position is wrong local function slot(isKey) if w.err then return false @@ -91205,10 +88593,8 @@ end __FILES["codecs/text/Json/Decode"] = function() --!strict --!native --- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json. Iterative (an explicit container stack, so deep nesting --- is a LIMIT error, never a stack overflow), strict grammar (no comments, trailing commas, leading zeros, NaN, single --- quotes or raw control characters), \u escapes with surrogate pairs (lone surrogates become WTF-8 bytes). Also the --- pull tokenizer behind Json.events. Never throws: failures return nil, message, offset (0-based byte offset). +-- 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") @@ -91236,7 +88622,6 @@ local ESC= { [116] = "\t", } --- utf8 bytes of a code point (surrogates too: WTF-8) local utf8char = Text.utf8char Decode.utf8char = utf8char @@ -91248,7 +88633,6 @@ local h = match(s, "^%x%x%x%x", i) return tonumber(h, 16) end --- string(s, i) -> value, next | nil, message, offset. i is at the opening quote. local function str(s, i) local j = find(s, '[%z\1-\31"\\]', i + 1) if not j then @@ -91307,7 +88691,6 @@ local j = find(s, '[%z\1-\31"\\]', i + 1) end Decode.string = str --- number(s, i) -> value, next | nil, message, offset local function num(s, i, bigStrings) local p = i if byte(s, p) == 45 then @@ -91358,8 +88741,6 @@ if n == nil then -- LuaJIT: absurd exponents (1e0066999...) -> nil; they overflo end Decode.number = num --- decode(s, i, opts) -> value, next | nil, message, offset. Parses one value starting at i (leading whitespace --- skipped); next is the position after the value (trailing whitespace not skipped). function Decode.value(s, i, opts) local o= opts or {} local ordered = o.ordered == true @@ -91368,9 +88749,9 @@ local o= opts or {} })[1] local maxDepth = o.maxDepth or 1000 local object = Types.object - local stackT= {} -- containers - local stackK= {} -- object: the pending key; array: the count - local stackO= {} -- object: its key order (or true); array: false + local stackT= {} + local stackK= {} + local stackO= {} local depth = 0 local n = #s local value @@ -91451,7 +88832,6 @@ if byte(s, i) == 93 then end value, i = v, ni end - -- attach the value to the open containers, closing them as their ends come while haveValue do if depth == 0 then return value, i @@ -91508,17 +88888,13 @@ if byte(s, i) ~= 58 then end end --- events: a pull tokenizer. next() -> event, value | nil at the end | "error", message, offset. Events: "object", --- "endObject", "array", "endArray", "key" (string), "value" (scalar). The grammar is checked as it goes. function Decode.events(s, i, opts) local o= opts or {} local bigStrings = o.bigInts == "string" local nullv = (o.null ~= nil and{o.null }or{Types.null })[1] local maxDepth = o.maxDepth or 1000 - local stack= {} -- true = object + local stack= {} local depth = 0 - -- state: "value" (a value expected), "first" (after { or [: value / key or close), "after" (after a value), - -- "key" (a key expected), "done", "dead" local state = "value" local n = #s local function fail(msg, at) @@ -91583,7 +88959,6 @@ if byte(s, i) ~= 58 then state = "value" return "key", k end - -- a value local after = depth == 0 and"done" or"after" if c == 123 or c == 91 then depth =depth+ 1 @@ -91632,10 +89007,7 @@ end __FILES["codecs/text/Json/Encode"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict --!native --- codecs/text/Json/Encode: the serializer behind codecs/text/Json. Compact or pretty (indent), objects in their Types.object key --- order (plain tables: sorted keys), arrays for tables with keys 1..n, shortest round-trip number text, optional --- ASCII-only output. Never throws: bad values (cycles, NaN / inf, functions, non-string keys that are not numbers) --- return nil, message. +-- codecs/text/Json/Encode: the RFC 8259 serializer behind codecs/text/Json. local Types = __include("Types") local Encode = {} @@ -91679,7 +89051,6 @@ if cp < 0x10000 then return format("\\u%04x\\u%04x", 0xD800 + math.floor(cp / 1024), 0xDC00 + cp % 1024) end --- asciify a UTF-8 string's non-ASCII sequences (invalid bytes become \u00XX of the byte: lossy but never throws) local function asciiSeq(seq) local out = {} local i, n = 1, #seq @@ -91701,7 +89072,7 @@ local out = {} return concat(out) end --- string(s, ascii, slash) -> the quoted JSON string (ascii: DEL too, like Python's ensure_ascii) +-- ascii escapes DEL too, like Python's ensure_ascii local function quote(s, ascii, slash) local pat = slash and'[%z\1-\31"\\/]' or'[%z\1-\31"\\]' if string.find(s, pat) then @@ -91717,7 +89088,6 @@ end Encode.quote = quote local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" } --- number(x) -> the shortest text that reads back as x | nil for NaN / inf local function number(x) if x ~= x or x == huge or x == -huge then return nil @@ -91746,7 +89116,6 @@ local ta, tb = type(a), type(b) return a < b end --- kind(t, emptyObject) -> "array" (keys exactly 1..n) | "object" local function kind(t, emptyObject) if Types.isObject(t) then return "object" @@ -91927,7 +89296,6 @@ end Encode.state = state Encode.write = value --- encode(v, opts) -> text | nil, message function Encode.encode(v, opts, nullv) local st = state(opts, nullv) if not value(st, v, 0) then @@ -91940,24 +89308,8 @@ return Encode end __FILES["codecs/text/Nbt"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, --- model/schematic and model/mca use. New code (Minecraft wiki "NBT format", wiki.vg "NBT"). --- Binary: Java big-endian (modified UTF-8 strings), Bedrock little-endian (with or without the 8-byte level.dat --- header) and Bedrock network NBT (varints), every tag type; files may be gzip or zlib compressed (codecs/compress/ --- Deflate). SNBT: parse and print (codecs/text/Nbt/Snbt). Values are plain Luau with typed numbers --- (codecs/text/Nbt/Value): int -> number, string -> string, byteArray -> buffer, compound -> Types.object (key order --- kept), list -> array, the other numeric and array tags -> { type, value } tags, so round trips are exact. --- --- local Nbt = require("rosetta.codecs.text.Nbt") --- local v, info = Nbt.decode(buf) -- a file: compression and edition detected; info = how it was stored --- print(v.Data.LevelName, v.Data.Time.value) -- int / string plain; long / byte / ... tags have .value --- v.Data.Difficulty = Nbt.byte(2) --- local out = Nbt.encode(v) -- written the way it was read (Nbt.info(v)), or opts --- local text = Nbt.print(v) -- SNBT: {Data:{Difficulty:2b,...}} --- local w = Nbt.parse('{pos:[I;1,2,3],name:"x"}') --- local raw, name, endPos = Nbt.read(buf, 0, nil, { endian = "little" }) -- one uncompressed tag --- --- Never throws: bad data and bad values return nil, Err. +-- 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") @@ -91993,8 +89345,8 @@ local Nbt = {} -Nbt.TAG = Value.IDS -- name -> id -Nbt.TAG_NAMES = Value.NAMES -- id -> name +Nbt.TAG = Value.IDS +Nbt.TAG_NAMES = Value.NAMES Nbt.byte = Value.byte Nbt.short = Value.short Nbt.int = Value.int @@ -92014,19 +89366,16 @@ Nbt.fromHiLo = Value.fromHiLo Nbt.toHiLo = Value.toHiLo local infos= (setmetatable({}, { __mode = "k" }) ) --- info(value) -> how a decoded root was stored (nil for values not from decode) function Nbt.info(v) return (type(v) == "table" and{infos[v] }or{nil })[1]end --- setInfo(value, info): what encode uses as defaults function Nbt.setInfo(v, info) if type(v) == "table" then infos[v] = info end end --- read(buf, offset?, length?, opts?) -> value, rootName, endOffset | nil, Err: one uncompressed root tag function Nbt.read(buf, offset, length, opts) local b, o, l, aerr = Bytes.span("Nbt.read", buf, offset, length) if not b then @@ -92039,7 +89388,6 @@ local b, o, l, aerr = Bytes.span("Nbt.read", buf, offset, length) return v, name, at end --- write(value, opts?) -> buffer | nil, Err: one uncompressed root tag function Nbt.write(v, opts) local out, e = Binary.write(v, opts ) if not out then @@ -92048,7 +89396,6 @@ local out, e = Binary.write(v, opts ) return out, nil end --- unwrap(buf, offset?, length?, maxBytes?) -> data, start, end, compression | nil, Err: gzip / zlib detected by magic function Nbt.unwrap(buf, offset, length, maxBytes) local b, o, l, aerr = Bytes.span("Nbt.unwrap", buf, offset, length) if not b then @@ -92097,8 +89444,6 @@ if p + n > buffer.len(b) or n > 256 then return s end --- peek(buf, offset?, length?) -> Peek | nil: whether the bytes look like an NBT file (inflating at most 1 KiB of a --- gzip / zlib stream), and its root's name and first child: what format sniffs look at. Never fails loudly. function Nbt.peek(buf, offset, length) local o = offset or 0 local l = length or (buffer.len(buf) - o) @@ -92145,7 +89490,7 @@ local a, b = buffer.readu8(head, q), buffer.readu8(head, q + 1) return nil end if ft == 0 then - res.firstType = "end" -- an empty root compound + 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 @@ -92165,8 +89510,6 @@ local a, b = buffer.readu8(head, q), buffer.readu8(head, q + 1) return at(0, "big", false) or at(0, "little", false) end --- decode(buf | string, opts?, offset?, length?) -> value, Info | nil, Err: a whole NBT file (gzip / zlib / raw; Java --- or Bedrock) function Nbt.decode(buf, opts, offset, length) local o= opts or {} local b, s, e, comp = Nbt.unwrap(buf, offset, length, o.maxBytes) @@ -92232,7 +89575,6 @@ return Binary.read(data, from, stop, { endian = endian , varint = varint, namele return v, info end --- encode(value, opts?) -> buffer | nil, Err: a whole NBT file function Nbt.encode(v, opts) local o= opts or {} local info = Nbt.info(v) @@ -92266,7 +89608,6 @@ local o= opts or {} return raw, nil end --- parse(text, opts?) -> value | nil, Err: SNBT function Nbt.parse(text, opts) local s = (type(text) == "buffer" and{(buffer.tostring(text) )}or{text })[1] if type(s) ~= "string" then @@ -92279,7 +89620,6 @@ local s = (type(text) == "buffer" and{(buffer.tostring(text) )}or{text return v, nil end --- print(value, opts?) -> text | nil, Err: SNBT (compact, or opts.indent) function Nbt.print(v, opts) local s, e = Snbt.print(v, opts) if not s then @@ -92288,7 +89628,6 @@ local s, e = Snbt.print(v, opts) return s, nil end --- get(value, path) -> the value at a dotted path ("Data.Player.Pos[1]"; list indices 0-based like Minecraft's) function Nbt.get(v, path) local cur = v for part in __iter(string.gmatch(path, "[^%.]+")) do @@ -92323,10 +89662,8 @@ end __FILES["codecs/text/Nbt/Binary"] = function() local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict -- codecs/text/Nbt/Binary: binary NBT read and write, from the Minecraft wiki "NBT format" page and wiki.vg "NBT". --- New code. Three encodings: big-endian (Java Edition files; strings in Java's modified UTF-8, converted to and from --- UTF-8), little-endian (Bedrock files; UTF-8) and Bedrock's network form (little-endian with zigzag varints for int / --- long and varint lengths). All thirteen tag types; values per codecs/text/Nbt/Value. Lengths are checked against --- the bytes left before anything is allocated, and nesting is limited (opts.maxDepth, default 512 like Minecraft). +-- 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") @@ -92348,7 +89685,6 @@ local TWO32 = 4294967296 local NAMES, IDS = Value.NAMES, Value.IDS local newTag = Value.TagMeta --- ------------------------------------------------------------------------------------------------ modified UTF-8 -- Java's DataOutput strings: U+0000 as C0 80, supplementary characters as two 3-byte surrogates (CESU-8) @@ -92412,7 +89748,6 @@ end Binary.fromModified = fromModified Binary.toModified = toModified --- ------------------------------------------------------------------------------------------------ read local function fail(s, msg) if not s.err then s.err = msg @@ -92571,7 +89906,6 @@ local function tag(name, v) return setmetatable({ type = name, value = v }, newTag) end --- the smallest encoded size of one element, to bound list lengths before allocating 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 } @@ -92716,7 +90050,6 @@ if id == 3 then return fail(s, "bad tag type " .. id) end --- read(buf, pos, limit, opts?) -> value, rootName, endPos | nil, message, at function Binary.read(b, pos, limit, opts) local o= opts or {} local net = o.varint == true @@ -92747,7 +90080,6 @@ local o= opts or {} end return v, name, s.p end --- ------------------------------------------------------------------------------------------------ write @@ -92761,7 +90093,7 @@ local function wvaruint(w, v) end local function wi32(ws, v) - v =v% TWO32 -- two's complement + v =v% TWO32 if ws.net then local sv = (v >= 0x80000000 and((v - TWO32 ))or(v )) wvaruint(ws.w, (sv >= 0 and((sv * 2 ))or((-sv * 2 - 1)))) @@ -92994,7 +90326,6 @@ local w = ws.w return nil end --- write(value, opts?) -> buffer | nil, message function Binary.write(v, opts) local o= opts or {} local net = o.varint == true @@ -93022,13 +90353,8 @@ return Binary end __FILES["codecs/text/Nbt/Snbt"] = function() local __compat = __compat local buffer, utf8, type, __iter = __compat.buffer, __compat.utf8, __compat.type, __compat.__iter --!strict --- codecs/text/Nbt/Snbt: stringified NBT (the text form of /data and /give), parse and print. New code, from the --- Minecraft wiki "NBT format" SNBT section (Java 1.21.5 grammar). Parses: compounds, lists, [B; ...] [I; ...] [L; ...] --- arrays, quoted strings ('...' / "..." with \\ \' \" \n \t \r \b \f \s \xNN \uNNNN \UNNNNNNNN escapes) and unquoted --- strings, numbers with b / s / i / l / f / d suffixes (any case, signed / unsigned s / u prefix), underscores, hex --- 0x and binary 0b integers, exponents, true / false (bytes 1 / 0), NaN / Infinity with a float suffix, trailing --- commas. Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. Prints Minecraft's --- compact form (or indented); floats print as the shortest text that reads back to the same value. +-- 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") @@ -93046,7 +90372,6 @@ local TWO32 = 4294967296 local function tag(name, v) return setmetatable({ type = name, value = v }, Value.TagMeta) end --- ------------------------------------------------------------------------------------------------ parse @@ -93108,7 +90433,6 @@ if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then end end --- number text -> a value, or nil when it is not a number (then it is an unquoted string) local INT_RANGE= { b = { -128, 127, 255 }, s = { -32768, 32767, 65535 }, @@ -93158,7 +90482,6 @@ local radix, digits, suffix = 10, body, "" if unsigned and sign == "-" then return nil end - -- the magnitude as (hi, lo) local hi, lo = 0, 0 for k = 1, #digits do local c = byte(digits, k) @@ -93460,7 +90783,6 @@ ws(p) return v end --- parse(text, opts?) -> value | nil, message, position (1-based) function Snbt.parse(s, opts) local p= { s = s, i = 1, n = #s, err = nil, at = 1, depth = 0, maxDepth = (opts and opts.maxDepth) or 512 } local v = parseValue(p) @@ -93474,7 +90796,6 @@ local p= { s = s, i = 1, n = #s, err = nil, at = 1, depth = 0, maxDepth = (opts return v, nil, nil end --- ------------------------------------------------------------------------------------------------ print local function shortest(v, single) if v ~= v then return "NaN" @@ -93648,7 +90969,6 @@ end return nil end --- print(value, opts?) -> text | nil, message function Snbt.print(v, opts) local o= opts or {} local ind = o.indent @@ -93674,14 +90994,8 @@ end __FILES["codecs/text/Nbt/Value"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- codecs/text/Nbt/Value: the NBT value model shared by the binary and SNBT codecs. New code. --- Plain Luau values with typed numbers, so a decode / encode round trip is exact: --- int -> number string -> string byteArray -> buffer --- compound -> Types.object (key order kept) list -> array (element type in Value.listType) --- byte / short / long / float / double / intArray / longArray -> a tag { type = "", value = ... } with a --- metatable (tostring gives SNBT): long values are numbers when exact (|v| <= 2^53), else their exact decimal --- text; intArray value = { numbers }; longArray value = a buffer of little-endian two's complement int64s. --- Inputs are lenient: a plain number writes as int when integral and in int range, else double; true / false as --- byte 1 / 0; a plain table with string keys as a compound. +-- 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 = {} @@ -93711,7 +91025,6 @@ end local TagMeta= {} Value.TagMeta = TagMeta --- the SNBT printer, filled in by codecs/text/Nbt (Value is below the printer) Value.print = function(v) return tostring(v.value) end @@ -93740,12 +91053,9 @@ if a.type ~= b.type then end local listTypes= (setmetatable({}, { __mode = "k" }) ) --- ------------------------------------------------------------------------------------------------ 64-bit integers local TWO32 = 4294967296 --- fromHiLo(hi, lo) -> a long value: a number when exact, else the exact decimal text (hi, lo: u32 halves of the --- two's complement int64) function Value.fromHiLo(hi, lo) local s = (hi >= 0x80000000 and((hi - TWO32 ))or(hi )) if s >= -0x200000 and s < 0x200000 then @@ -93768,7 +91078,6 @@ local s = (hi >= 0x80000000 and((hi - TWO32 ))or(hi return (neg and"-" or"") .. table.concat(parts) end --- toHiLo(v) -> hi, lo (u32 halves) | nil: v a whole number in int64 range or its decimal text function Value.toHiLo(v) if type(v) == "number" then if v % 1 ~= 0 or v < -9223372036854775808 or v >= 9223372036854775808 then @@ -93801,7 +91110,6 @@ if type(v) == "number" then return nil, nil end --- ------------------------------------------------------------------------------------------------ constructors local function tag(name, v) return (setmetatable({ type = name, value = v }, TagMeta) ) end @@ -93814,7 +91122,6 @@ end function Value.int(n) return n end --- long(n | "decimal") -> a long tag (decimal text within 2^53 becomes a number) function Value.long(v) if type(v) == "string" then local hi, lo = Value.toHiLo(v) @@ -93825,7 +91132,6 @@ if type(v) == "string" then return tag("long", v) end local f32 = buffer.create(4) --- float(n) -> a float tag holding n rounded to single precision function Value.float(n) buffer.writef32(f32, 0, n) return tag("float", buffer.readf32(f32, 0)) @@ -93836,7 +91142,6 @@ end function Value.intArray(t) return tag("intArray", t or {}) end --- longArray(values | buffer) -> a longArray tag (values: numbers / decimal texts; a buffer: 8 bytes each, LE) function Value.longArray(t) if type(t) == "buffer" then return tag("longArray", t) @@ -93850,7 +91155,6 @@ local b = buffer.create(#list * 8) end return tag("longArray", b) end --- longs(longArray) -> { number | string }: the elements as long values function Value.longs(a) local b= a.value local out = (table.create(math.floor(buffer.len(b) / 8)) ) @@ -93859,7 +91163,6 @@ for i = 0, math.floor(buffer.len(b) / 8 )- 1 do end return out end --- list(typeName, items?) -> items marked as a list of that element type (an empty list keeps its type) function Value.list(name, items) local t = items or {} listTypes[t] = name @@ -93868,7 +91171,6 @@ end function Value.compound(t, keys) return Types.object(t, keys) end --- listType(t) -> the element type name recorded for a list (decoded, or made by Value.list) function Value.listType(t) return listTypes[t] end @@ -93879,7 +91181,6 @@ function Value.isTag(v) return type(v) == "table" and getmetatable(v) == TagMeta end --- typeOf(v) -> the tag name v writes as, or nil + why function Value.typeOf(v) local tv = type(v) if tv == "number" then @@ -93910,7 +91211,6 @@ local tv = type(v) return nil, "cannot write a " .. tv .. " as NBT" end --- number(v) -> the numeric value of a number or numeric tag (long texts through tonumber: approximate) function Value.number(v) if type(v) == "number" then return v @@ -93932,12 +91232,10 @@ end __FILES["codecs/text/Text"] = function() local __compat = __compat local buffer, utf8, __iter = __compat.buffer, __compat.utf8, __compat.__iter --!strict --!optimize 2 --- codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is --- read as Windows-1252 (classic .m3u / .pls / .ini / .srt files), lines split on CRLF / CR / LF, trim. Absorbed from --- playlist-luau 3fc7fd3 (same author, no third-party code). Never throws. +-- 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 = {} --- utf8char(codepoint) -> its UTF-8 bytes (no validation: the parsers check ranges first; utf8.char would throw) function Text.utf8char(c) local char = string.char if c < 0x80 then @@ -93963,8 +91261,6 @@ function Text.trim(s) return ((string.match(s, "^%s*(.-)%s*$") )) end --- utf16(buf, offset, length, bigEndian?) -> UTF-8 text of UTF-16 code units (surrogate pairs joined, lone surrogates --- become U+FFFD; an odd last byte is ignored). Font names, 7z / PSD / Windows strings, XML in UTF-16. function Text.utf16(b, o, n, bigEndian) local out = {} local k = 0 @@ -93991,7 +91287,6 @@ local v = readu16(b, at) return table.concat(out) end --- toUtf8(text, warnings?) -> text as UTF-8: strips a BOM; text that is not valid UTF-8 is read as Windows-1252 function Text.toUtf8(text, warnings) if string.sub(text, 1, 3) == "\239\187\191" then text = string.sub(text, 4) @@ -94028,14 +91323,11 @@ end __FILES["codecs/text/Url"] = function() local __compat = __compat local type = __compat.type --!strict --!optimize 2 --- codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, --- Windows / UNC / POSIX local path, relative reference) and percent-encoding of bytes that may not appear in a URI --- (raw spaces and UTF-8 in playlists). Shared by the playlist formats (m3u / HLS, pls, xspf); later DASH / glTF URIs. --- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code): Url.luau, plus locate / base from its --- init.luau. Never throws. +-- 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 = {} --- Splits a URI reference into its five components (RFC 3986 appendix B). +-- RFC 3986 appendix B: the five components of a URI reference @@ -94076,7 +91368,7 @@ local fragment, query, authority return { scheme = scheme, authority = authority, path = s, query = query, fragment = fragment } end --- Recomposes components (RFC 3986 section 5.3). +-- RFC 3986 section 5.3 function Url.join(p) local out = {} if p.scheme then @@ -94127,7 +91419,7 @@ local input = path return table.concat(output) end --- Resolves a reference against an absolute base URI (RFC 3986 section 5.2.2, strict). +-- RFC 3986 section 5.2.2 (strict) function Url.resolve(ref, base) local r, b = Url.split(ref), Url.split(base) local t= { path = "" } @@ -94164,15 +91456,13 @@ local r, b = Url.split(ref), Url.split(base) return Url.join(t) end --- Percent-encodes the bytes that may not appear in a URI (controls, space, non-ASCII, "<>\"^`{|}" and "\\"), --- leaving existing %XX escapes and the reserved delimiters alone. +-- percent-encoded: controls, space, non-ASCII, "<>\"^`{|}" and "\\"; existing %XX escapes and reserved delimiters stay function Url.encodeUnsafe(s) return (string.gsub(s, "[%z\1-\32\127-\255<>\"%^`{|}\\]", function(c) return string.format("%%%02X", string.byte(c)) end)) end --- Is a location a local Windows path ("C:\x", "C:/x", "\\server\share", "\x")? function Url.isWindowsPath(s) return string.match(s, "^%a:[\\/]") ~= nil or string.match(s, "^%a:$") ~= nil @@ -94180,7 +91470,6 @@ return string.match(s, "^%a:[\\/]") ~= nil or string.sub(s, 1, 1) == "\\" end --- The scheme of an absolute URI (lower case), or nil. Windows drive letters are not schemes. function Url.scheme(s) if Url.isWindowsPath(s) then return nil @@ -94189,9 +91478,6 @@ if Url.isWindowsPath(s) then return (scheme and{(string.lower(scheme) )}or{nil })[1]end --- locate(raw, base?, baseScheme?) -> { url, playable, reason? }: an entry location resolved against the playlist's --- base (from Url.base). Windows paths stay as they are and are local; relative paths without a base, file: URLs and --- schemes other than http(s) are not playable (reason says why). function Url.locate(raw, base, baseScheme) local loc = ((string.match(raw, "^%s*(.-)%s*$") )) if Url.isWindowsPath(loc) then @@ -94200,7 +91486,6 @@ local loc = ((string.match(raw, "^%s*(.-)%s*$") )) local scheme = Url.scheme(loc) local url = loc if not scheme and baseScheme == "windows" and base then - -- a playlist on a Windows disk: relative entries are paths next to it local dir = string.match(base, "^(.*[\\/])") or "" return { url = dir .. loc, playable = false, reason = "local path" } end @@ -94209,7 +91494,6 @@ local loc = ((string.match(raw, "^%s*(.-)%s*$") )) url = Url.encodeUnsafe(Url.resolve(loc, loc)) end elseif base and baseScheme then - -- a relative reference: Windows separators become URL ones url = Url.resolve(Url.encodeUnsafe((string.gsub(loc, "\\", "/"))), base) scheme = baseScheme else @@ -94223,8 +91507,6 @@ local loc = ((string.match(raw, "^%s*(.-)%s*$") )) return { url = url, playable = false, reason = "scheme " .. tostring(scheme) } end --- base(baseUrl?, warnings?) -> base, baseScheme: the base for Url.locate from the playlist's own URL or path ("windows" --- for a Windows path); a non-absolute base is ignored (with a warning) function Url.base(baseUrl, warnings) if type(baseUrl) ~= "string" or baseUrl == "" then return nil, nil @@ -94245,23 +91527,8 @@ return Url end __FILES["codecs/text/Xml"] = function() local __compat = __compat local buffer, typeof, type, __iter = __compat.buffer, __compat.typeof, __compat.type, __compat.__iter --!strict --- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... --- use. New code. Supports: UTF-8 / UTF-16 / Latin-1 input, the predefined entities, character references, internal --- DOCTYPE entities (expansion limited), CDATA, comments, processing instructions, the XML declaration, namespaces --- (names stay qualified "prefix:local"; opts.namespaces adds each element's URI as node.ns; Xml.clark gives --- "{uri}local"), xml:space. Not supported: external entities / DTDs, validation, entity values containing markup. --- --- local Xml = require("rosetta.codecs.text.Xml") --- local doc, err = Xml.decode(text) -- a "#document" node; doc.root is the root element --- for _, item in Xml.children(doc.root, "item") do print(item.attrs.id, Xml.text(item)) end --- for ev, a, b in Xml.events(text) do ... end -- "start" name attrs / "end" name / "text" s / ... (SAX-like) --- local s = Xml.encode(doc, { indent = 2 }) --- local e = Xml.element("svg", { width = "10" }, { Xml.element("rect") }) -- build trees --- --- Nodes (Types.XmlNode): { name, attrs (a Types.object: attribute order kept), children = { node | string }, --- parent }. Text children are strings. With opts.comments / opts.cdata / opts.pi, comments, CDATA sections and --- processing instructions are kept as "#comment" / "#cdata" / "#pi" nodes (text = the content, target = the PI --- target); otherwise CDATA merges into the text and the others are dropped. Never throws. +-- 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") @@ -94303,8 +91570,6 @@ if find(msg, "unterminated", 1, true) or find(msg, "truncated", 1, true) or find return Err.CORRUPT end --- events(src, opts?) -> iterator: event, a, b, c (see codecs/text/Xml/Parse: "decl", "doctype", "start" name attrs ns, --- "end" name, "text" s, "cdata" s, "comment" s, "pi" target data, and on bad input "error" Err as the last event) function Xml.events(src, opts) local s, terr = text(src) local u, enc = nil, "" @@ -94333,9 +91598,6 @@ local ev, a, b, c = nextEv() end end --- decode(src, opts?) -> the "#document" node | nil, Err. doc.root = the root element; doc.declaration = { version, --- encoding, standalone }?; doc.doctype = { raw, name, publicId, systemId, entities }?; doc.children = the root plus --- any kept comments / PIs around it. function Xml.decode(src, opts) local o= opts or {} local keepComments, keepCdata, keepPi = o.comments == true, o.cdata == true, o.pi == true @@ -94390,9 +91652,6 @@ local o= opts or {} return doc, nil end --- ------------------------------------------------------------------------------------------------ tree helpers --- element(name, attrs?, children?) -> a new element (attrs: a plain table (written sorted) or a Types.object; --- children: nodes or strings; their parent is set) function Xml.element(name, attrs, children) local a = attrs or Types.object() if not Types.isObject(a) then @@ -94412,14 +91671,12 @@ local a = attrs or Types.object() return node end --- document(root, declaration?) -> a "#document" node around root function Xml.document(root, declaration) local doc= { name = "#document", attrs = Types.object(), children = { root }, root = root, declaration = declaration } root.parent = doc return doc end --- append(parent, child) -> child (a node or a string), parent link set function Xml.append(parent, child) table.insert(parent.children, child) if type(child) == "table" then @@ -94428,13 +91685,10 @@ table.insert(parent.children, child) return child end --- setAttr(node, name, value): set (or with nil remove) an attribute, keeping the order function Xml.setAttr(node, name, value) Types.set(node.attrs, name, value) end --- children(node, name?) -> the element children (with that qualified name, or local name when name has no prefix and --- the child's does), in order function Xml.children(node, name) local out = {} for _, ch in __iter(node.children) do @@ -94447,7 +91701,6 @@ local out = {} return out end --- child(node, name?) -> the first matching element child, or nil function Xml.child(node, name) for _, ch in __iter(node.children) do if type(ch) == "table" and string.byte(ch.name) ~= 35 then @@ -94459,7 +91712,6 @@ for _, ch in __iter(node.children) do return nil end --- descendants(node, name?) -> every element below node (document order), optionally filtered as children() does function Xml.descendants(node, name) local out = {} local function walk(n) @@ -94476,7 +91728,6 @@ local out = {} return out end --- text(node) -> all the character data below node, concatenated (CDATA included, comments / PIs not) function Xml.text(node) if type(node) == "string" then return node @@ -94500,7 +91751,6 @@ if type(node) == "string" then return table.concat(parts) end --- prefix(name) / localName(name): the parts of a qualified name ("svg:rect" -> "svg", "rect"; "rect" -> "", "rect") function Xml.prefix(name) return match(name, "^([^:]*):") or "" end @@ -94508,14 +91758,10 @@ function Xml.localName(name) return match(name, ":(.*)$") or name end --- namespace(node, prefix?) -> the URI bound to prefix (default: the node's own prefix) at node, through its --- ancestors' xmlns attributes (needs parent links) function Xml.namespace(node, prefix) return Parse.resolve(node, prefix or Xml.prefix(node.name)) end --- clark(node, attrName?) -> "{uri}local" (ElementTree's notation) for the element, or for one of its attributes --- (unprefixed attributes have no namespace) function Xml.clark(node, attrName) local name = attrName or node.name local prefix = Xml.prefix(name) @@ -94529,11 +91775,9 @@ local name = attrName or node.name return name end --- ------------------------------------------------------------------------------------------------ encode local TEXT_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ["\r"] = " " } local ATTR_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """, ["\t"] = " ", ["\n"] = " ", ["\r"] = " " } --- escape(s) / escapeAttr(s): text / attribute-value escaping function Xml.escape(s) return (gsub(s, "[&<>\r]", TEXT_ESC)) end @@ -94545,7 +91789,6 @@ local function badName(name) return type(name) ~= "string" or not match(name, "^[%a_:\128-\255][%w_:%.%-\128-\255]*$") end --- encode(node, opts?) -> string | nil, Err. node: a "#document" or any node (an element, a comment, ...) function Xml.encode(node, opts) local o= opts or {} local ind= nil @@ -94688,13 +91931,8 @@ end __FILES["codecs/text/Xml/Parse"] = function() local __compat = __compat local utf8, __iter = __compat.utf8, __compat.__iter --!strict --!native --- codecs/text/Xml/Parse: the XML 1.0 pull parser behind codecs/text/Xml. Input decoding (UTF-8, UTF-16 LE / BE by BOM or --- by the first bytes, ISO-8859-1 / US-ASCII / Windows-1252 by the declaration), line-ending normalization, the --- well-formedness rules that matter (one root, matched tags, unique attributes, quoted values, no '<' in values, --- legal names, character references in range, no "--" in comments, no "]]>" in text), the five predefined entities, --- character references and internal general entities from the DOCTYPE (with an expansion limit). Not supported: --- external entities / DTDs (references to them are errors), entity values containing markup (taken as text), --- validation. Never throws: errors are events. +-- 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") @@ -94756,7 +91994,6 @@ local out = table.create(math.floor(#s / 2)) return table.concat(out), nil end --- toUtf8(s) -> UTF-8 text (BOM removed), the encoding name | nil, message function Parse.toUtf8(s) local b1, b2, b3 = byte(s, 1, 3) if b1 == 0xEF and b2 == 0xBB and b3 == 0xBF then @@ -94809,7 +92046,7 @@ local p = 1 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 -- no whitespace before + return nil end if (key == "version" and not match(v, "^1%.%d+$")) or (key == "encoding" and not match(v, "^%a[%w%._%-]*$")) @@ -94829,17 +92066,6 @@ local q, v, e = match(data, "^" .. key .. "[ \t\n]*=[ \t\n]*([\"'])(.-)%1()", ws return out end --- the events iterator: next() -> event, a, b, c --- "decl", { version, encoding, standalone } the declaration --- "doctype", raw, info raw = the text between ""; info = { name, --- publicId, systemId, entities } --- "start", name, attrs (Types.object), ns ns: the element's namespace URI (opts.namespaces) or nil --- "end", name --- "text", s character data, entities decoded (whitespace-only dropped --- unless opts.whitespace) --- "cdata", s "comment", s "pi", target, data --- "error", message, offset then the iterator ends --- nil at the end of the document. function Parse.events(s, opts) local o= opts or {} local keepWs = o.whitespace == true @@ -94866,7 +92092,7 @@ local o= opts or {} local rootSeen = false local rootDone = false local dead = false - local pending= nil -- an "end" queued after a self-closing start + local pending= nil local errMsg= nil local errAt = 0 @@ -94875,7 +92101,6 @@ dead = true return "error", msg, at - 1 end - -- decode entity / character references in raw text; nil on error (errMsg set) local decode function decode(raw, at, level) if not find(raw, "&", 1, true) then @@ -94953,7 +92178,6 @@ for d = depth, 1, -1 do return nil end - -- a quoted literal at p -> its content, the position after it | nil local function literal(p) local q = byte(s, p) if q ~= 34 and q ~= 39 then @@ -94965,7 +92189,7 @@ local q = byte(s, p) end return sub(s, p + 1, e - 1), e + 1 end - -- an ExternalID (SYSTEM "sys" | PUBLIC "pub" "sys") at p -> publicId, systemId, next | nil + -- ExternalID: SYSTEM "sys" | PUBLIC "pub" "sys" local function externalId(p) local kw = sub(s, p, p + 5) if kw == "SYSTEM" then @@ -94999,7 +92223,6 @@ if not r then end return nil, nil, nil end - -- check an entity value's references and expand its character references (the rest expand when used) local function entityValue(v) if find(v, "%", 1, true) then return nil -- parameter-entity references are not allowed in the internal subset's markup @@ -95033,8 +92256,6 @@ if cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= end return table.concat(parts) end - -- the DOCTYPE at i (just past "' outside quotes while true do local c2 = byte(s, r) if c2 == nil then @@ -95319,7 +92539,6 @@ local at = i end return "pi", target, data end - -- a start tag local name = match(s, NAME, i + 1) if not name then return fail(i + 1 > n and"truncated tag" or"bad tag name", i + 1) @@ -95380,7 +92599,7 @@ if not r then return fail(errMsg , errAt) end if find(raw, "[\t\n]") then - -- attribute-value normalization: literal tab / newline become spaces (references stay) + -- XML 1.0 3.3.3 attribute-value normalization: literal tab / newline become spaces (references stay) v = (decode((gsub(raw, "[\t\n]", " ")), r + 1, 0) ) end if attrs[an] ~= nil then @@ -95423,14 +92642,13 @@ local sp = attrs["xml:space"] stack[depth] = nil nsStack[depth] = nil preserve[depth] = nil - pending = { name } -- depth goes down when the queued "end" is returned + pending = { name } end return "start", name, attrs, uri until true if not __DARKLUA_CONTINUE_9 then break end end end end --- lookup(nsMaps...) helper for the DOM: the namespace URI of prefix, walking an element's ancestors function Parse.resolve(node, prefix) local p = node local key = prefix == "" and"xmlns" or"xmlns:" .. prefix @@ -95455,23 +92673,9 @@ local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!native --!optimize 2 -- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. --- Block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the IDCT put or added --- into 8-bit planes, constant (DC-only) blocks, half-pel motion compensation four samples at a time. Native, never --- throws (the caller keeps offsets in range). --- --- The IDCT is the Independent JPEG Group's jrevdct.c (the LL&M integer IDCT, CONST_BITS 13, PASS1_BITS 2) as ffmpeg --- ships it (libavcodec/jrevdct.c, IJG licence: licenses/libjpeg-README.ijg), translated mechanically: rows first, then --- columns, with every sparse-input special case of the original kept, because several of them use merged constants --- (FIX_1_306562965 for FIX_0_541196100 - FIX_1_847759065, ...) that round differently from the general case; that --- is what makes ffmpeg's `-idct int` output reproducible here. Changes: Luau, i32 coefficients in natural order --- (ffmpeg's LIBMPEG2 permutation is only a storage order), no int16 wrap of the intermediate values (identical for --- coefficients in the MPEG range), and the put / add clamping fused into the last pass. --- --- Dsp.idct(blk, dst, off, stride, add) -- blk: 64 i32 (256 bytes, row-major), left holding garbage: clear it --- Dsp.fill(dst, off, stride, v, add) -- an 8x8 block of constant v (a DC-only block: v = (dc + 4) >> 3) --- Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) -- half-pel prediction of a w x h block --- Dsp.mcNoRound(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy) -- the same, averages rounded down (H.263+) --- Dsp.edge(src, stride, base, x, y, w, h, pw, ph, out) -- a block with edge samples repeated (EDGE_STRIDE) +-- The IDCT is IJG's jrevdct.c (LL&M, CONST_BITS 13, PASS1_BITS 2) as ffmpeg ships it (libavcodec/jrevdct.c, IJG +-- licence: licenses/libjpeg-README.ijg), translated mechanically: its sparse-input special cases stay because their +-- merged constants round differently. Natural-order i32 coefficients, no int16 wrap, put / add clamping in pass 2. local Dsp = {} local readu8 = buffer.readu8 @@ -95495,7 +92699,6 @@ end Dsp.CLAMP = CLAMP Dsp.COFF = COFF --- ------------------------------------------------------------------------------------------------ IDCT function Dsp.idct(blk, dst, off, stride, add) local tmp0, tmp1, tmp2, tmp3 = 0, 0, 0, 0 local tmp10, tmp11, tmp12, tmp13 = 0, 0, 0, 0 @@ -96087,9 +93290,7 @@ function Dsp.idct(blk, dst, off, stride, add) end end --- ------------------------------------------------------------------------------------------------ blocks --- an 8x8 block of the constant v put into dst (add = false) or added to it, clamped (a DC-only block: the IDCT --- of a lone DC coefficient dc is (dc + 4) >> 3 everywhere) +-- the IDCT of a lone DC coefficient dc is (dc + 4) >> 3 everywhere function Dsp.fill(dst, off, stride, v, add) if not add then local c = readu8(CLAMP, v + COFF) * 0x01010101 @@ -96108,12 +93309,9 @@ function Dsp.fill(dst, off, stride, v, add) end end --- ------------------------------------------------------------------------------------------------ motion --- Motion-compensated prediction of a w x h block (w a multiple of 4) from src (rows sStride apart, from sOff) to dst --- (dStride, dOff): half-pel flags hx / hy, rounding up (MPEG-1 / 2, H.263 rounding_type 0); avg averages into what --- dst holds (the second prediction of a bidirectional block, rounding up). Strides are twice the plane width for --- field prediction. Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits --- each byte into its low 2 bits and high 6 bits so no lane overflows. +-- rounding up (MPEG-1 / 2, H.263 rounding_type 0); strides are twice the plane width for field prediction. +-- Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits each byte into its +-- low 2 bits and high 6 bits so no lane overflows. function Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) for _ = 1, h do for i = 0, w - 4, 4 do @@ -96146,8 +93344,7 @@ function Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) end end --- Dsp.mc with the half-sample averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1: --- RTYPE of an H.263+ picture header, MPEG-4 rounding_control). No averaging into dst. +-- averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1, MPEG-4 rounding_control) function Dsp.mcNoRound(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy) if hx == 0 and hy == 0 then Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, 0, 0, false) @@ -96174,9 +93371,8 @@ function Dsp.mcNoRound(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy) end end --- Edge emulation: the (w + 1) x (h + 1) samples at (x, y) of a pw x ph plane (row r at base + r * stride) copied to --- out (rows EDGE_STRIDE apart), coordinates clamped into the plane, so a vector pointing outside the picture --- predicts from repeated edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33; out holds EDGE_SIZE bytes). +-- edge emulation: coordinates clamped into the plane, so a vector pointing outside the picture predicts from repeated +-- edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33) Dsp.EDGE_STRIDE = 32 Dsp.EDGE_SIZE = 32 * 34 + 4 function Dsp.edge(src, stride, base, x, y, w, h, pw, ph, out) @@ -96198,21 +93394,8 @@ end __FILES["codecs/video/H263"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int. --- ITU-T H.263 baseline and the H.263+ picture header. Written from ITU-T H.263 (01/2005) and Adobe's Video File Format Specification v10; the decoding core is --- H263/Decoder.luau (native), the IDCT and motion compensation codecs/video/Dsp, so the output planes equal --- `ffmpeg -idct int` (tests/codecs/h263.luau). Supports sub-QCIF .. 16CIF and H.263+ custom sizes, I and P pictures, --- GOB headers, the rounding type, unrestricted motion vectors (Annex D), Sorenson's escape codes and disposable inter --- pictures. Not supported (UNSUPPORTED): arithmetic coding, advanced prediction / four vectors, PB / B / EI / EP --- pictures and the other H.263+ coding options (advanced intra coding, deblocking filter, slices, ...). --- --- local dec = H263.new({ flv = false }) -- flv = true: Sorenson Spark (FLV1) --- local frame, err = dec:decode(packetData, off?, len?) -- one picture -> Frame (planes decoder-owned) --- local img = H263.frameImage(frame) -- a fresh yuv420p Types.Image (limited range, BT.601) --- local img, err = dec:image(packetData) -- both at once --- local info = H263.header(data, off?, len?, flv?) -- the picture header: width, height, ptype, ... --- dec:reset() -- after a seek: wait for the next I picture --- --- Nothing here throws: bad arguments and bad data come back as nil, Err. +-- From ITU-T H.263 (01/2005) and Adobe's Video File Format Specification v10. Annex D UMV, GOB headers and Sorenson +-- escapes are supported; arithmetic coding, advanced prediction, PB / B / EI / EP and other H.263+ options are not. local Err = __include("core/Err") local Types = __include("Types") local D = __include("codecs/video/H263/Decoder") @@ -96242,7 +93425,6 @@ H263.PICTURE_P = 2 - local Decoder = {} @@ -96278,8 +93460,6 @@ if type(data) == "string" then return b, o, n end --- Decodes one picture (a container packet or one picture of an elementary stream). A picture with damaged --- macroblock data still comes back (the damaged part copied from the reference; stats.errors counts them). function Decoder.decode(self, data, off, len) local b, o, n = span(data, off, len) if not b then @@ -96309,7 +93489,6 @@ local b, o, n = span(data, off, len) }, nil end --- decode + frameImage function Decoder.image(self, data, off, len) local f, err = self:decode(data, off, len) if not f then @@ -96318,13 +93497,10 @@ local f, err = self:decode(data, off, len) return H263.frameImage(f), nil end --- Forgets the reference picture (after a seek: P pictures fail until the next I picture). function Decoder.reset(self) self._core.reset() end --- frameImage(frame) -> a fresh yuv420p Types.Image of the frame, cropped to width x height (chroma ceil(w / 2) x --- ceil(h / 2)), meta.yuv = limited range BT.601; nil for a value that is not a Frame function H263.frameImage(frame) if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then return nil @@ -96357,8 +93533,6 @@ if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buf return img end --- header(data, off?, len?, flv?) -> Header (width, height, ptype 1 I / 2 P, quant, tr, plus, umv, ...) | nil, Err: --- the first picture header in the data, without decoding (containers use it for the track size) function H263.header(data, off, len, flv) local b, o, n = span(data, off, len) if not b then @@ -96377,30 +93551,9 @@ __FILES["codecs/video/H263/Decoder"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/video/H263/Decoder: the H.263 / Sorenson Spark decoding core (native, never throws). Written from ITU-T --- H.263 (01/2005) and Adobe's Video File Format Specification v10 (the H.263VIDEOPACKET of Sorenson Spark). --- --- H.263: picture headers with PTYPE (sub-QCIF .. 16CIF) and PLUSPTYPE (H.263+: standard and custom picture formats, --- custom pixel aspect ratios and picture clock frequencies, the rounding type RTYPE), I and P pictures, GOB headers --- (with or without stuffing), MCBPC / CBPY / MVD / TCOEF VLCs, DQUANT, the H.263 dequantiser, half-sample motion --- compensation with the H.263 chroma vector rounding, unrestricted motion vectors (Annex D in both header forms, the --- PLUSPTYPE form with its reversible MVD codes and unlimited range), slice structure (Annex K, without rectangular --- slices) and the extended escape of Annex T. Sorenson Spark --- (FLV1): its picture header (sizes, disposable inter pictures, which never become the reference), its 7 / 11-bit --- escape codes (version 1), unrestricted vectors. Not supported (the picture is refused with an "unsupported:" message): --- syntax-based arithmetic coding, advanced prediction (Annex F: four vectors and OBMC), PB / B / EI / EP pictures, --- advanced intra coding, the deblocking filter, rectangular slices, reference picture selection / resampling, reduced --- resolution update, independent segments, the alternative inter VLC, modified quantisation (other than the escape). --- --- The IDCT and motion compensation are codecs/video/Dsp, the dequantiser is the H.263 one (|REC| = QUANT * (2 |LEVEL| --- + 1), minus 1 for an even QUANT, as ffmpeg without the -2048..2047 saturation), and vectors pointing outside the reference read --- repeated edge samples of the macroblock-aligned picture, so valid streams decode exactly as `ffmpeg -idct int` --- (tests/codecs/h263.luau). Corrupt data ends the picture: the rest is copied from the reference (state.errors). --- --- local core = D.new(flv, maxPixels) --- local hdr, msg = D.header(buf, off, len, flv, core.state.opp) -- the picture header (no decoding) --- local store, msg = core.decode(buf, off, len) -- one picture -> the Store decoded into (decoder-owned) --- core.reset() -- forget the reference (after a seek) +-- codecs/video/H263/Decoder: the H.263 / Sorenson Spark decoding core, from ITU-T H.263 (01/2005) and Adobe's Video +-- File Format Specification v10 (H.263VIDEOPACKET). Dequantiser |REC| = QUANT * (2 |LEVEL| + 1), minus 1 for an even +-- QUANT; vectors outside the reference read repeated edge samples of the macroblock-aligned picture, as ffmpeg. local Tb = __include("codecs/video/H263/Tables") local Dsp = __include("codecs/video/Dsp") @@ -96437,7 +93590,6 @@ local D = {} D.PICTURE_I = 1 D.PICTURE_P = 2 -- the PLUSPTYPE options that persist while UFEP = 0 --- ------------------------------------------------------------------------------------------------ header -- the length of a slice's MBA field for a picture of n macroblocks (table K.2) @@ -96489,7 +93641,6 @@ function D.mbaBits(n) return n <= 48 and 6 or(n <= 99 and 7 or(n <= 396 and 9 or(n <= 1584 and 11 or(n <= 6336 and 13 or 14 ))))end --- n (<= 24) bits at bit position p of buf, zeros past endByte local function bitsAt(buf, endByte, p, n) local v = 0 for k = p, p + n - 1 do @@ -96500,8 +93651,7 @@ local v = 0 return v end --- the byte offset of the first picture start code in buf[off, off + len) (H.263: 22 bits 0..01 00000; Sorenson: --- 17 bits 0..01 and version 0 / 1), or -1 +-- picture start code: H.263 22 bits 0..01 00000; Sorenson 17 bits 0..01, then version 0 / 1 local function findStart(buf, off, len, flv) local mask = flv and 0xF8 or 0xFC for i = off, off + len - 3 do @@ -96512,8 +93662,7 @@ local mask = flv and 0xF8 or 0xFC return -1 end --- header(buf, off, len, flv, opp?) -> Header | nil, message: the picture header of the first picture in --- buf[off, off + len); opp: the PLUSPTYPE options of the previous picture (pictures with UFEP = 0 keep them) +-- pictures with UFEP = 0 keep the previous picture's PLUSPTYPE options (opp) function D.header(buf, off, len, flv, opp) if off < 0 or len < 0 or off + len > buffer.len(buf) then return nil, "bad range" @@ -96715,7 +93864,6 @@ if ufep == 1 then h.bitPos = p return h, nil end --- ------------------------------------------------------------------------------------------------ decoder @@ -96741,12 +93889,10 @@ local state = { opp = nil , maxPixels = maxPixels or 4096 * 2304, } - -- bitstream local data = buffer.create(64 * 1024 + PAD) local endBits = 0 local pos = 0 local err = false - -- picture local W, H = 0, 0 local mbW, mbH = 0, 0 local ls, cs, lh, chh = 0, 0, 0, 0 -- luma / chroma strides, plane heights @@ -96814,8 +93960,7 @@ local e = readu32(lut, rshift(peek32(), 32 - k) * 4) state.width, state.height = w, h end - -- one 8x8 block: intra (INTRADC, then the coded coefficients from position 1) put into dst, or an inter block's - -- coefficients added to the prediction already in dst + -- intra blocks: INTRADC, then the coded coefficients from position 1 local function block(intra, coded, dst, off, stride) local i = 0 local dcOnly = true @@ -96927,7 +94072,6 @@ local i = 0 return true end - -- one motion vector component from its prediction (half samples) local function motion(pred) if umvPlus then -- reversible codes (Annex D.2): "1" = 0, else 0 x0 (1 x)* 0, the last x the sign @@ -96967,7 +94111,6 @@ if umvPlus then return (v + 32) % 64 - 32 -- the code pair's value in -16 .. 15.5 end - -- the prediction of macroblock (col, row) from the reference, vector (mx, my) in half samples local function predict(col, row, mx, my) local hx, hy = mx % 2, my % 2 local sx, sy = col * 16 + math.floor((mx - hx) / 2), row * 16 + math.floor((my - hy) / 2 @@ -96995,7 +94138,6 @@ if umvPlus then end end - -- a macroblock copied from the reference (not coded, or concealed); mid-grey without one local function copyMb(col, row) local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8 if ref then @@ -97012,9 +94154,6 @@ if umvPlus then end end - -- macroblock (col, row) of a picture (P: an inter picture; top: within the first macroblock columns' worth of - -- the picture / a GOB or slice with a header, whose vector predictions do not look up; first: the first - -- macroblock of a slice, whose left neighbour is outside). false on bad data. local function macroblock(col, row, P, top, first) if pos > endBits then return false @@ -97108,7 +94247,6 @@ local w = peek32() return true end - -- an optional GOB header at a GOB boundary: its GN and GQUANT, or nil local function gobHeader(cpm) if not startCode() then return nil, nil @@ -97121,7 +94259,6 @@ if not startCode() then return gn, read(5) end - -- an optional slice header (Annex K, no rectangular slices): its MBA and SQUANT, or nil local function sliceHeader(cpm, mbaBits, sepb2) if not startCode() then return nil, nil @@ -97245,7 +94382,6 @@ local hdr, herr = D.header(buf, off, len, flv, state.opp) if hdr.opp then state.opp = hdr.opp end - -- the data from the header on, with zero padding local need = len + PAD if buffer.len(data) < need then data = buffer.create(need) @@ -97271,22 +94407,17 @@ return D end __FILES["codecs/video/H263/Tables"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- codecs/video/H263/Tables: the H.263 variable-length codes (ITU-T H.263 (01/2005): table 7 MCBPC for I-pictures, --- table 8 MCBPC for P-pictures, table 12 DQUANT, table 13 CBPY, table 14 MVD, table 16 TCOEF, the zigzag scan of --- figure 14), written from the specification as bit strings and turned into flat lookup tables at load time. --- --- A flat table is indexed by the next K bits of the stream and holds len * 65536 + value (len 0: not a code). --- MCBPC_I / MCBPC_P (K = 9): value = macroblock type * 4 + CBPC (types 0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA, --- 4 INTRA+Q), STUFFING for the stuffing code --- CBPY (K = 6): the intra CBPY (Y1 the most significant bit; inter macroblocks use 15 - value) --- MVD (K = 12): the magnitude 0..32 in half samples (a sign bit follows every code but "1", which is 0) --- TCOEF (K = 12): last * 1024 + run * 16 + level (a sign bit follows), ESCAPE for the escape code +-- codecs/video/H263/Tables: the H.263 variable-length codes (ITU-T H.263 (01/2005) tables 7 / 8 MCBPC, 12 DQUANT, +-- 13 CBPY, 14 MVD, 16 TCOEF, figure 14 zigzag). Flat tables indexed by the next K bits: len * 65536 + value (len 0: none). +-- MCBPC_I / MCBPC_P (K = 9): type * 4 + CBPC (0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA, 4 INTRA+Q), STUFFING +-- CBPY (K = 6): the intra CBPY, Y1 the MSB (inter macroblocks use 15 - value) +-- MVD (K = 12): magnitude 0..32 in half samples (a sign bit follows every code but "1") +-- TCOEF (K = 12): last * 1024 + run * 16 + level (a sign bit follows), ESCAPE local T = {} T.STUFFING = 255 T.ESCAPE = 0xFFFF --- builds a K-bit flat table from { bits, value } pairs local function flat(codes, k) local lut = buffer.create(4 * 2 ^ k) for _, c in __iter(codes) do @@ -97479,34 +94610,10 @@ return T end __FILES["codecs/video/H264"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the --- video/h264 format (raw Annex B streams) and the MP4 / MKV / AVI / TS video tracks use it. Clean-room, written from the --- spec; constant tables taken from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). Bit-exact with the --- reference decoder (checked against ffmpeg per frame). --- Supports: Annex B and AVCC (length-prefixed, with avcC extradata) input; SPS / PPS / slices; CAVLC and CABAC; I, P and --- B slices; every intra mode (4x4, 8x8, 16x16, chroma), quarter-sample luma / eighth-sample chroma motion --- compensation, explicit and implicit weighted prediction, direct spatial and temporal prediction; the 4x4 and 8x8 --- transforms with scaling matrices; the deblocking filter; multiple reference frames, long-term references, MMCO and --- the sliding window, frame_num gaps; POC types 0 / 1 / 2 and output reordering; 8-bit 4:2:0 Constrained Baseline, --- Main, Extended-without-SP/data-partitioning and High profiles; cropping. Corrupt slices are skipped and their --- macroblocks concealed (copied from the latest reference picture). --- Not supported (UNSUPPORTED): interlaced coding (field pictures, MBAFF), 4:0:0 / 4:2:2 / 4:4:4, bit depths above 8, --- lossless (transform bypass), FMO / ASO slice groups, SP / SI slices, data partitioning, SVC / MVC enhancement layers --- (their NAL units are ignored). --- --- local H264 = require("rosetta.codecs.video.H264") --- local dec = H264.newDecoder() -- or { avcC = buffer } for MP4 samples (length-prefixed) --- for _, au in accessUnits do --- local frames, err = dec:decode(au, pts) -- frames: { { image (yuv420p Types.Image), pts, poc, keyframe } } --- end --- local rest = dec:flush() -- the frames still held for reordering --- --- Speed (one Zen 5 core, tools/bench.luau, libx264 crf 23 clips): Luau --codegen ~220-425 fps at 320x240 and ~75-135 --- fps at 640x360; LuaJIT with the api's trace limits (host/init.luau) about the same or faster, but with LuaJIT's default --- limits (maxtrace=1000) the trace cache thrashes and it drops to ~30-190 fps. Real-time is comfortable at 320x240 and --- feasible at 640x360 for typical bitrates; high-bitrate CIF conformance streams run ~100-150 fps (Luau). --- Never throws: bad data returns nil, Err (core/Err codes ARG / UNSUPPORTED / LIMIT), or frames with the bad slices --- concealed (dec.errors counts them, dec.lastError says why). +-- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau, bit-exact with ffmpeg. +-- Clean-room from the spec; constant tables from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). 8-bit 4:2:0 +-- Constrained Baseline, Main and High. UNSUPPORTED: interlaced coding (field pictures, MBAFF), 4:0:0 / 4:2:2 / 4:4:4, +-- bit depths above 8, lossless, FMO / ASO, SP / SI slices, data partitioning, SVC / MVC (their NAL units are ignored). local Err = __include("core/Err") local Types = __include("Types") local Bitstream = __include("codecs/video/H264/Bitstream") @@ -97563,7 +94670,6 @@ local st = self.state return nil end --- newDecoder(opts?) -> H264Decoder | nil, Err function H264.newDecoder(opts) local o = opts or {} if type(o) ~= "table" then @@ -97580,8 +94686,6 @@ local o = opts or {} return self, nil end --- decoder:configure(avcC) -> true | nil, Err: reads an AVCDecoderConfigurationRecord (its SPS / PPS) and switches to --- length-prefixed input function DecoderMeta.configure(self, avcC) local b = toBuffer(avcC) if not b then @@ -97607,8 +94711,6 @@ local b = toBuffer(avcC) return true, nil end --- decoder:decode(data, pts?, off?, len?) -> { Frame } | nil, Err. data: an access unit or any run of NAL units: --- length-prefixed (after configure / with opts.lengthSize), else Annex B (start codes) or one bare NAL unit. function DecoderMeta.decode(self, data, pts, off, len) local b = toBuffer(data) if not b then @@ -97645,14 +94747,12 @@ local b = toBuffer(data) return frames, nil end --- decoder:flush() -> { Frame }: ends the stream (the current picture and every picture held for reordering) function DecoderMeta.flush(self) Decoder.flush(self.state) status(self) return Decoder.take(self.state) end --- decodeAll(data, opts?) -> { Frame } | nil, Err: a whole Annex B (or length-prefixed with opts.avcC) stream function H264.decodeAll(data, opts) local dec, err = H264.newDecoder(opts) if not dec then @@ -97668,7 +94768,6 @@ local dec, err = H264.newDecoder(opts) return frames, nil end --- parseAvcC(buf) -> { lengthSize, profile, level, nals } | nil, Err function H264.parseAvcC(data) local b = toBuffer(data) if not b then @@ -97681,11 +94780,6 @@ local b = toBuffer(data) return cfg, nil end --- ------------------------------------------------------------------------------------------------ video layer --- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video registry entry for "h264"): --- track.config = avcC (MP4 / Matroska; packets length-prefixed) or nil (Annex B packets: MPEG-TS, AVI, raw .h264). --- Pictures come out in display order with the packet timestamps sorted (display order); a track with --- `ptsInOutputOrder` (raw Annex B, no timestamps) numbers them in output order instead. function H264.newVideoDecoder(track, opts) local o= { maxPixels = opts and opts.maxPixels, deblock = opts and opts.deblock, lowDelay = opts and opts.lowDelay, yield = opts and opts.yield } @@ -97714,8 +94808,7 @@ local d, err = H264.newDecoder(o) pts = outIndex or 0 outIndex = pts + 1 elseif #pool > 0 then - -- pictures leave in display order: they take the packet timestamps in increasing order (right for - -- MP4 / MKV / TS pts, and for AVI whose packets only carry decode-order times) + -- pictures take the packet timestamps in increasing order (right for MP4 / MKV / TS pts and AVI's decode-order times) pts = table.remove(pool, 1) end table.insert(queue, { f.image, pts, f.keyframe }) @@ -97765,9 +94858,8 @@ local q = table.remove(queue, 1) return self, nil end --- accessUnits(buf, off?, len?) -> { off, len, keyframe, ... } (triples): an Annex B stream cut into access units --- (7.4.1.2.3: a new unit starts at an AUD, SPS, PPS or SEI after a slice, or at a slice with first_mb_in_slice 0 --- after a slice). keyframe: the unit holds an IDR slice. +-- 7.4.1.2.3: a new access unit starts at an AUD, SPS, PPS or SEI after a slice, or at a slice with first_mb_in_slice 0 +-- after a slice function H264.accessUnits(data, off, len) local b = toBuffer(data) local out = {} @@ -97792,7 +94884,6 @@ local b = toBuffer(data) end end if boundary then - -- the unit ends where this NAL's start code begins local s = p while s > start and buffer.readu8(b, s - 1) ~= 1 do s =s- 1 @@ -97821,8 +94912,6 @@ local b = toBuffer(data) return out end --- toAnnexB(config, sample) -> buffer: a length-prefixed sample (MP4 / Matroska) as Annex B; with config (avcC) the --- parameter sets are prepended (pass it for the first sample / keyframes). nil, Err on a bad avcC / sample function H264.toAnnexB(config, sample) local parts = {} local lengthSize = 4 @@ -97846,7 +94935,6 @@ local parts = {} return buffer.fromstring(table.concat(parts)), nil end --- info(data) -> { width, height, profile, level, frameRate?, ... } of the first SPS of an Annex B stream or avcC | nil function H264.info(data) local b = toBuffer(data) if not b then @@ -97885,7 +94973,6 @@ local b = toBuffer(data) return nil end --- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height function H264.planes(img) local cw, ch = math.floor((img.width + 1) / 2), math.floor((img.height + 1) / 2 ) local ny = img.width * img.height @@ -97898,19 +94985,14 @@ __FILES["codecs/video/H264/Bitstream"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/video/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B start --- code splitting, AVCC length-prefixed samples, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3) --- parsing, emulation-prevention removal, and the u(n) / ue(v) / se(v) / te(v) readers. Written from the spec. --- Never throws: reads past the end of an RBSP return zero bits (the buffer carries 8 zero bytes of padding and every --- read is range-checked), and callers check `r.pos > r.size` once per syntax structure. +-- codecs/video/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B, +-- AVCC, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3), emulation prevention, u(n) / ue(v) / se(v) / te(v). local Bitstream = {} local readu8 = buffer.readu8 local band, lshift = bit32.band, bit32.lshift --- ------------------------------------------------------------------------------------------------ framing --- splitAnnexB(buf, off, len) -> { off1, len1, off2, len2, ... }: NAL unit payload ranges between start codes --- (00 00 01, with any leading zero bytes); trailing zero bytes of a NAL are dropped. +-- start codes are 00 00 01 with any leading zero bytes; trailing zero bytes of a NAL are dropped @@ -97960,7 +95042,6 @@ local out = {} return out end --- isAnnexB(buf, off, len) -> true when the data starts with a start code (00 00 01 or 00 00 00 01) function Bitstream.isAnnexB(buf, off, len) if len >= 3 and readu8(buf, off) == 0 and readu8(buf, off + 1) == 0 then local b2 = readu8(buf, off + 2) @@ -97972,8 +95053,6 @@ if len >= 3 and readu8(buf, off) == 0 and readu8(buf, off + 1) == 0 then return false end --- splitLength(buf, off, len, size) -> NAL ranges of a length-prefixed (AVCC / MP4 sample) buffer, or nil when a --- length runs past the end (the NALs before it are kept in the second result) function Bitstream.splitLength(buf, off, len, size) local out = {} local e = off + len @@ -97996,8 +95075,6 @@ local out = {} return out, out end --- parseAvcC(buf, off, len) -> { lengthSize, profile, level, nals = { off, len, ... } (SPS then PPS, + SPS ext) } | --- nil, message function Bitstream.parseAvcC(buf, off, len) if len < 7 then return nil, "truncated: avcC shorter than 7 bytes" @@ -98037,9 +95114,7 @@ if len < 7 then return cfg, nil end --- ------------------------------------------------------------------------------------------------ rbsp --- reader(buf, off, len, skip) -> Reader over the RBSP of a NAL unit's bytes [off, off + len), the first `skip` --- bytes (the NAL header) left out; emulation_prevention_three_byte (00 00 03) removed. +-- emulation_prevention_three_byte (00 00 03) is removed function Bitstream.reader(buf, off, len, skip) local out = buffer.create(len + 8) local o = 0 @@ -98075,7 +95150,6 @@ local out = buffer.create(len + 8) return { buf = out, pos = 0, size = o * 8, stop = stop, n = o + 8 } end --- ------------------------------------------------------------------------------------------------ bits -- Plain arithmetic instead of bit32 (LuaJIT runs bit32 through compat wrappers whose sign fix-ups split traces). local P2 = table.create(33, 1) -- P2[k + 1] = 2^k for k = 0, 32 do @@ -98093,7 +95167,6 @@ for x = 0, 255 do end Bitstream.LZ8 = LZ8 --- clz32(v) -> leading zero bits of a 32-bit value local function clz32(v) if v >= 16777216 then return LZ8[math.floor(v / 16777216 )+ 1] @@ -98106,7 +95179,6 @@ if v >= 16777216 then end Bitstream.clz32 = clz32 --- peekAt(b, n, pos) -> the 32 bits at bit position pos of buffer b (n bytes), zeros past the end local function peekAt(b, n, pos) local p = math.floor(pos / 8 ) if p + 5 > n then @@ -98121,20 +95193,17 @@ local p = math.floor(pos / 8 )end Bitstream.peekAt = peekAt --- peek32(r) -> the next 32 bits (zeros past the end) local function peek32(r) return peekAt(r.buf, r.n, r.pos) end Bitstream.peek32 = peek32 --- u(r, n) -> n bits (n 1..32) as an unsigned number function Bitstream.u(r, n) local v = peekAt(r.buf, r.n, r.pos) r.pos =r.pos+ n return math.floor(v / P2[33 - n] )end --- u1(r) -> one bit function Bitstream.u1(r) local pos = r.pos r.pos = pos + 1 @@ -98145,7 +95214,7 @@ local pos = r.pos return (math.floor(readu8(r.buf, p) / P2[8 - (pos - p * 8)])) % 2 end --- ue(r) -> ue(v); a code with more than 31 leading zeros returns 2^32 (out of range for every syntax element) +-- more than 31 leading zeros returns 2^32 (out of range for every syntax element) local function ue(r) local v = peekAt(r.buf, r.n, r.pos) if v == 0 then @@ -98165,7 +95234,6 @@ local v = peekAt(r.buf, r.n, r.pos) end Bitstream.ue = ue --- se(r) -> se(v) function Bitstream.se(r) local k = ue(r) if k % 2 == 1 then @@ -98174,7 +95242,6 @@ local k = ue(r) return -(math.floor(k / 2)) end --- te(r, range) -> te(v) with the given range (max value) function Bitstream.te(r, range) if range == 1 then return 1 - Bitstream.u1(r) @@ -98182,7 +95249,7 @@ if range == 1 then return ue(r) end --- moreData(r) -> more_rbsp_data() +-- more_rbsp_data() function Bitstream.moreData(r) return r.pos < r.stop end @@ -98193,12 +95260,9 @@ __FILES["codecs/video/H264/Cabac"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --!native --!optimize 2 --- codecs/video/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3): the --- arithmetic decoding engine (9.3.1.2 / 9.3.3.2), context initialisation (9.3.1.1), the binarizations and context --- index increments of every syntax element (9.3.2 / 9.3.3.1) and residual_block_cabac for 4x4, 8x8 and DC blocks. --- Coefficients are dequantised as they are placed. Written from the spec; tables from Tables. --- The engine keeps codIOffset with `nb` look-ahead bits (low = offset * 2^nb + next bits), so renormalisation is one --- multiply and bytes are fetched one at a time. Never throws: returns false, "message" on bad data. +-- codecs/video/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3): +-- engine (9.3.1.2 / 9.3.3.2), context init (9.3.1.1), binarizations and ctxIdxInc (9.3.2 / 9.3.3.1), residual_block_cabac. +-- codIOffset is kept with `nb` look-ahead bits (low = offset * 2^nb + next bits), so renormalisation is one multiply. local Bitstream = __include("codecs/video/H264/Bitstream") local Tables = __include("codecs/video/H264/Tables") local Mb = __include("codecs/video/H264/Mb") @@ -98211,7 +95275,6 @@ local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y local Cabac = {} --- ------------------------------------------------------------------------------------------------ engine local RANGE_LPS = Tables.RANGE_LPS local TRANS = Tables.TRANS local POW2 = table.create(40, 1) @@ -98243,7 +95306,6 @@ for st = 0, 127 do end end --- the engine (one slice at a time) local ebuf= buffer.create(1) local epos, elimit = 0, 0 local erange, elow, enb = 510, 0, 0 @@ -98258,8 +95320,7 @@ local function refill() enb =enb+ 8 end --- decision(ctx) -> bin (9.3.3.2.1), branch-free apart from the byte refill: the LPS test is min(1, low // scaled) --- (low < 2.5 * scaled always), the state step and the bin come from tables +-- decision (9.3.3.2.1): the LPS test is min(1, low // scaled) (low < 2.5 * scaled always) local function decision(ctx) local s = ST[ctx + 1] local range = erange @@ -98309,7 +95370,6 @@ local r = erange - 2 return 0 end --- start the engine at byte p of the rbsp local function engineInit(b, p, limit) ebuf, epos, elimit = b, p, limit elow, enb = 0, -9 @@ -98339,7 +95399,6 @@ local function initContexts(sliceQp, model) end end --- ------------------------------------------------------------------------------------------------ residual local ZZ4, ZZ8 = Tables.ZIGZAG4, Tables.ZIGZAG8 local SIG8, LAST8 = Tables.SIG8, Tables.LAST8 local CAT_CBF = { 0, 4, 8, 12, 16 } @@ -98348,8 +95407,7 @@ local CAT_ABS = { 0, 10, 20, 30, 39 } local MAXC = { 16, 15, 16, 4, 15, 64 } local SIGPOS = table.create(64, 0) --- block(cat, out, base, mul, div) -> number of coefficients (cat 0..5); coded_block_flag is decoded by the caller. --- Positions: cat 0 / 2 zig-zag, 1 / 4 zig-zag from 1, 3 raster 0..3, 5 the 8x8 zig-zag +-- positions: cat 0 / 2 zig-zag, 1 / 4 zig-zag from 1, 3 raster 0..3, 5 the 8x8 zig-zag local SCAN = {} do local ac = table.create(15, 0) @@ -98458,7 +95516,6 @@ local maxc = MAXC[cat + 1] return n end --- ------------------------------------------------------------------------------------------------ syntax elements -- condition helpers on neighbouring macroblocks (addresses are 1-based here) local function leftAddr(S, M) return ((M.aL) and (M.addr) or (0)) @@ -98597,7 +95654,6 @@ if decision(36) == 0 then return t end --- ref_idx for the partition whose top-left 4x4 is (x, y); rgt: the ref > 0 grid of the list local function refIdx(S, M, rgt, x, y) local g = M.g0 + y * S.w4 + x local inc = 0 @@ -98622,7 +95678,7 @@ local g = M.g0 + y * S.w4 + x return v end --- mvd component (comp 0 x, 1 y) for the partition at (x, y); grid holds |mvd| (2 per 4x4) +-- the mvd grid holds |mvd| (2 per 4x4) local function mvd(S, M, grid, x, y, comp) local g = M.g0 + y * S.w4 + x local sum = 0 @@ -98843,7 +95899,6 @@ local dc = S.dcTab return ca, cb end --- ------------------------------------------------------------------------------------------------ residual local function residuals(S, M) local kind = M.kind local cbp = M.cbp @@ -98968,7 +96023,6 @@ local function clearCounts(M) end end --- ------------------------------------------------------------------------------------------------ macroblock local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } local SUB_N = { 1, 2, 2, 4 } @@ -99288,7 +96342,6 @@ local st = S.type return interMb(S, M, r, t, true) end --- slice(S, M, r) -> true | false, message function Cabac.slice(S, M, r) local p = math.floor((r.pos + 7) / 8 ) local limit = math.floor(r.size / 8 @@ -99338,11 +96391,8 @@ __FILES["codecs/video/H264/Cavlc"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --!native --!optimize 2 --- codecs/video/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2): --- mb_skip_run, mb_type / sub_mb_type, intra modes, ref_idx (te), mvd, coded_block_pattern (me), mb_qp_delta and --- residual_block_cavlc (coeff_token, level_prefix / suffix, total_zeros, run_before) with the 8x8 interleaving. --- Coefficients are dequantised as they are placed. Written from the spec; VLC tables from Tables. --- Never throws: returns false, "message" on bad data. +-- codecs/video/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2), +-- residual_block_cavlc with the 8x8 interleaving; coefficients are dequantised as they are placed. local Bitstream = __include("codecs/video/H264/Bitstream") local Tables = __include("codecs/video/H264/Tables") local Mb = __include("codecs/video/H264/Mb") @@ -99354,7 +96404,6 @@ local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y local Cavlc = {} --- ------------------------------------------------------------------------------------------------ vlc tables -- build(entries) -> l1, l2: a two-level lookup on 16 peeked bits. l1[(v >> 8) + 1] = value * 32 + length, or -- -(base) of a second-level block l2[base + (v & 255)]; 0 = no code local function build(entries) @@ -99437,7 +96486,6 @@ local IDENT = { 0, 1, 2, 3 } local INTRA_CBP, INTER_CBP = Tables.INTRA_CBP, Tables.INTER_CBP --- ------------------------------------------------------------------------------------------------ residual local LEVEL = table.create(16, 0) local RUN = table.create(16, 0) @@ -99445,8 +96493,7 @@ local peek = Bitstream.peekAt local clz32 = Bitstream.clz32 local P2 = Bitstream.P2 --- residual(r, nC, maxCoeff, out, base, scan, mul, div) -> TotalCoeff, or -1 on a bad code. Levels go to --- out[base + scan[i] + 1] dequantised as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels) +-- levels go to out[base + scan[i] + 1] as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels) local function residual(r, nC, maxCoeff, out, base, scan, mul, div) local b, n = r.buf, r.n local pos = r.pos @@ -99593,7 +96640,6 @@ local b, n = r.buf, r.n end Cavlc.residual = residual --- ------------------------------------------------------------------------------------------------ macroblock local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } local SUB_N = { 1, 2, 2, 4 } @@ -99616,7 +96662,6 @@ if n <= 1 then return v end --- the residual of the parsed macroblock local function residuals(S, M, r) local kind = M.kind local cbp = M.cbp @@ -99741,7 +96786,7 @@ local function clearLumaGrids(S, M, intra) end end --- intra(S, M, r, t): the intra macroblock types 0..25 (table 7-11) +-- intra macroblock types 0..25 (table 7-11) local function intraMb(S, M, r, t) local addr = M.addr + 1 if t == 25 then @@ -99852,7 +96897,7 @@ local addr = M.addr + 1 return true end --- inter(S, M, r, t, isB): the P (0..4) and B (0..22) inter macroblock types +-- the P (0..4) and B (0..22) inter macroblock types local function interMb(S, M, r, t, isB) clearLumaGrids(S, M, false) local n0, n1 = S.n0, S.n1 @@ -100046,7 +97091,6 @@ clearLumaGrids(S, M, false) return true end --- macroblock(S, M, r) -> true | false, message local function macroblock(S, M, r) local t = ue(r) local st = S.type @@ -100064,8 +97108,6 @@ local t = ue(r) return interMb(S, M, r, t, true) end --- ------------------------------------------------------------------------------------------------ slice data --- slice(S, M, r) -> true | false, message: decodes macroblocks from S.firstMb until the end of the slice data function Cavlc.slice(S, M, r) local addr = S.firstMb local total = S.mbW * S.mbH @@ -100117,12 +97159,9 @@ __FILES["codecs/video/H264/Deblock"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- codecs/video/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0: --- boundary strengths (8.7.2.1, from the per-4x4 intra / coefficient / reference / motion grids), alpha / beta / tC0 --- (tables 8-16 / 8-17), the bS < 4 and bS = 4 luma and chroma filters, disable_deblocking_filter_idc 0 / 1 / 2 and the --- slice alpha / beta offsets. Written from the spec. Runs over the whole picture in macroblock order once all its --- slices are decoded (the result equals filtering each macroblock as it is decoded). --- Never throws. +-- codecs/video/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0 +-- (bS 8.7.2.1, alpha / beta / tC0 tables 8-16 / 8-17). Runs over the whole picture once its slices are decoded, which +-- equals filtering each macroblock as it is decoded. local Tables = __include("codecs/video/H264/Tables") local readu8, writeu8 = buffer.readu8, buffer.writeu8 @@ -100139,9 +97178,6 @@ end local abs = math.abs --- luma(b, o, across, along, qp, aOff, bOff): filters the 16 samples of one luma edge; `across` steps from q0 to q1 --- (1 for vertical edges, the stride for horizontal ones), `along` to the next sample of the edge; BS holds the four --- strengths local function luma(b, o, across, along, qp, aOff, bOff) local indexA = clip3(0, 51, qp + aOff) local alpha = ALPHA[indexA + 13] @@ -100200,7 +97236,7 @@ local function luma(b, o, across, along, qp, aOff, bOff) end end --- chroma(b, o, across, along, qp, aOff, bOff): the 8 samples of one chroma edge (bS of luma segment i // 2) +-- chroma: bS of luma segment i // 2 local function chroma(b, o, across, along, qp, aOff, bOff) local indexA = clip3(0, 51, qp + aOff) local alpha = ALPHA[indexA + 13] @@ -100231,7 +97267,7 @@ local function chroma(b, o, across, along, qp, aOff, bOff) end end --- motionDiffers(pic, p, q) -> true when the 4x4 blocks p and q (grid indices) need bS 1 (8.7.2.1) +-- the bS 1 motion test of 8.7.2.1 local function mvDiff(mvA, a, mvB, b) return abs(mvA[2 * a - 1] - mvB[2 * b - 1]) >= 4 or abs(mvA[2 * a] - mvB[2 * b]) >= 4 end @@ -100272,7 +97308,6 @@ local uid0, uid1, mv0, mv1 = pic.uid0, pic.uid1, pic.mv0, pic.mv1 return (mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q)) and (mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q)) end --- picture(S, pic, params): deblocks the whole picture. params[sliceNum] = { idc, alphaOffset, betaOffset } function Deblock.picture(S, pic, params) local mbW, mbH = S.mbW, S.mbH local w4 = S.w4 @@ -100319,7 +97354,6 @@ __DARKLUA_CONTINUE_7=true break if t8 and (e == 1 or e == 3) then __DARKLUA_CONTINUE_7=true break end - -- strengths of the four segments local intraP = intraQ local qpP, qpcP, qpc2P = qpQ, qpcQ, qpc2Q if e == 0 then @@ -100381,12 +97415,9 @@ return Deblock end __FILES["codecs/video/H264/Decoder"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict --- codecs/video/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): NAL unit --- dispatch, picture boundaries (7.4.1.2.4), picture order count types 0 / 1 / 2 (8.2.1), frame_num gaps (8.2.5.2), --- reference picture lists with modification (8.2.4), sliding window and adaptive (MMCO 1-6) marking (8.2.5), output --- in POC order through a reorder buffer (num_reorder_frames, else the DPB size), concealment of lost macroblocks, --- deblocking and border extension. Written from the spec. --- Never throws: errors are returned (a corrupt slice is skipped and its macroblocks concealed). +-- codecs/video/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): picture +-- boundaries (7.4.1.2.4), POC types 0 / 1 / 2 (8.2.1), frame_num gaps (8.2.5.2), list modification (8.2.4), marking +-- (8.2.5), output in POC order (num_reorder_frames, else the DPB size). local Bitstream = __include("codecs/video/H264/Bitstream") local Params = __include("codecs/video/H264/Params") local Slice = __include("codecs/video/H264/Slice") @@ -100404,9 +97435,6 @@ local CHROMA_QP = Tables.CHROMA_QP local Decoder = {} Decoder.__index = Decoder --- new(opts) -> decoder state - - @@ -100440,7 +97468,7 @@ local o = opts or {} maxLongTermIdx = -1, pool = {}, gray = nil, - frames = 0, -- pictures decoded + frames = 0, errors = 0, lastError = nil, fatal = nil, @@ -100449,7 +97477,6 @@ local o = opts or {} }, Decoder) end --- ------------------------------------------------------------------------------------------------ pictures local function newPicture(self, sps) local mbW, mbH = sps.mbWidth, sps.mbHeight local pool = self.pool @@ -100518,7 +97545,6 @@ local g = self.gray return g end --- ------------------------------------------------------------------------------------------------ output local function emit(self, p) p.waiting = false local sps = p.sps @@ -100571,7 +97597,6 @@ if self.opts.lowDelay then return sps.maxDecFrameBuffering or sps.maxDpbFrames end --- ------------------------------------------------------------------------------------------------ reference lists local function shortRefs(self) local t = {} for _, p in __iter(self.refs) do @@ -100670,7 +97695,6 @@ if #ops == 0 then return true end --- buildLists(self, sh, cur) -> list0, list1 (arrays of pictures, truncated to num_ref_idx_active) local function buildLists(self, sh, cur) picNums(self, sh) local list0, list1 = {}, {} @@ -100750,7 +97774,6 @@ picNums(self, sh) return list0, list1, ok end --- ------------------------------------------------------------------------------------------------ marking local function unmark(self, p) p.short = false p.long = false @@ -100793,7 +97816,7 @@ local function addRef(self, p) table.insert(self.refs, p) end --- mark(self, cur, sh): 8.2.5 after decoding the current (reference) picture; returns true when MMCO 5 was present +-- 8.2.5 marking after a reference picture; true when MMCO 5 was present local function mark(self, cur, sh) local sps = sh.sps if sh.idr then @@ -100893,7 +97916,6 @@ local sps = sh.sps return mmco5 end --- ------------------------------------------------------------------------------------------------ poc local function computePoc(self, sh) local sps = sh.sps local maxFrameNum = 2 ^ sps.log2MaxFrameNum @@ -100959,7 +97981,6 @@ local sps = sh.sps return t, t end --- ------------------------------------------------------------------------------------------------ picture decode local function setupGrids(self, sps) local mbW, mbH = sps.mbWidth, sps.mbHeight if self.S and self.S.mbW == mbW and self.S.mbH == mbH then @@ -101142,7 +98163,6 @@ local function finishPicture(self) p.poc = 0 p.frameNum = 0 end - -- POC / frame_num state for the next pictures if sh.nalRefIdc ~= 0 then if mmco5 then self.prevPocMsb = 0 @@ -101299,7 +98319,6 @@ local function decodeSlice(self, sh, r) end end --- nal(self, buf, off, len, pts): one NAL unit (no start code) function Decoder.nal(self, buf, off, len, pts) if len < 1 then return @@ -101390,13 +98409,11 @@ function Decoder.nal(self, buf, off, len, pts) -- SEI (6), filler (12), SPS extension (13), prefix / SVC / MVC (14, 15, 20) and reserved types are ignored end --- flush(self): finish the current picture and output every waiting picture function Decoder.flush(self) finishPicture(self) bump(self, 0) end --- take(self) -> the frames output since the last call function Decoder.take(self) local out = self.out self.out = {} @@ -101409,12 +98426,8 @@ __FILES["codecs/video/H264/Inter"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- codecs/video/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3): the 6-tap --- quarter-sample luma filter, eighth-sample bilinear chroma, default / explicit / implicit weighted sample --- prediction, and the picture border extension that makes out-of-picture reference reads equal to the clamped --- sample positions of 8.4.2.2.1. Written from the spec. --- Reference planes carry a border of PAD (luma) / PADC (chroma) replicated samples; callers clamp block positions --- with Inter.clampLuma / clampChroma so every read is inside the buffer. Never throws. +-- codecs/video/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3). +-- Reference planes carry a border of PAD / PADC replicated samples, so reads equal the clamped positions of 8.4.2.2.1. local readu8, writeu8 = buffer.readu8, buffer.writeu8 local Inter = {} @@ -101427,11 +98440,9 @@ local function clip(v) return min(max(v, 0), 255) end --- scratch rows of horizontal 6-tap intermediates (unrounded), 21 rows x 16 (+1) columns local B1 = table.create(24 * 17, 0) --- the six-tap filter cases, each a small function (LuaJIT keeps small loops in one trace); sliding windows read each --- sample once per row / column +-- one small function per six-tap case: LuaJIT keeps each loop in one trace local function lumaCopy(ref, s, base, w, h, P) for r = 0, h - 1 do local o = base + r * s @@ -101549,8 +98560,6 @@ local function lumaDiag(ref, s, base, w, h, P, ro, co) end end --- luma(ref, s, base, fx, fy, w, h, P): the w x h luma prediction for a block whose integer sample (0, 0) is at --- ref[base] and whose fractional offset is (fx, fy) quarter samples; P[r * 16 + c + 1] receives the samples function Inter.luma(ref, s, base, fx, fy, w, h, P) if fy == 0 then if fx == 0 then @@ -101569,7 +98578,6 @@ function Inter.luma(ref, s, base, fx, fy, w, h, P) end end --- chroma(ref, s, base, fx, fy, w, h, P): eighth-sample bilinear chroma prediction function Inter.chroma(ref, s, base, fx, fy, w, h, P) if fx == 0 and fy == 0 then for r = 0, h - 1 do @@ -101595,8 +98603,6 @@ function Inter.chroma(ref, s, base, fx, fy, w, h, P) end end --- ------------------------------------------------------------------------------------------------ weighting --- put(P, w, h, b, o, s): P into the picture function Inter.put(P, w, h, b, o, s) for r = 0, h - 1 do local d = r * 16 + 1 @@ -101607,7 +98613,7 @@ function Inter.put(P, w, h, b, o, s) end end --- avg(P0, P1, w, h, b, o, s): default bi-prediction (P0 + P1 + 1) >> 1 +-- default bi-prediction (P0 + P1 + 1) >> 1 function Inter.avg(P0, P1, w, h, b, o, s) for r = 0, h - 1 do local d = r * 16 + 1 @@ -101618,7 +98624,7 @@ function Inter.avg(P0, P1, w, h, b, o, s) end end --- weight1(P, w, h, b, o, s, logWD, wt, off): explicit single-list weighting (8-270 / 8-271) +-- explicit single-list weighting (8-270 / 8-271) function Inter.weight1(P, w, h, b, o, s, logWD, wt, off) if logWD >= 1 then local rnd = 2 ^ (logWD - 1) @@ -101641,8 +98647,7 @@ function Inter.weight1(P, w, h, b, o, s, logWD, wt, off) end end --- weight2(P0, P1, w, h, b, o, s, logWD, w0, w1, off): explicit / implicit bi-prediction weighting (8-272); --- off = (o0 + o1 + 1) >> 1 +-- explicit / implicit bi-prediction weighting (8-272); off = (o0 + o1 + 1) >> 1 function Inter.weight2(P0, P1, w, h, b, o, s, logWD, w0, w1, off) local rnd = 2 ^ logWD local div = 2 ^ (logWD + 1) @@ -101655,8 +98660,6 @@ function Inter.weight2(P0, P1, w, h, b, o, s, logWD, w0, w1, off) end end --- ------------------------------------------------------------------------------------------------ borders --- extend(b, o, s, w, h, pad): replicate the edge samples of the w x h plane at b[o] (stride s) into its border function Inter.extend(b, o, s, w, h, pad) for y = 0, h - 1 do local r = o + y * s @@ -101677,10 +98680,8 @@ __FILES["codecs/video/H264/Intra"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- codecs/video/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (nine directional modes, with the --- 8x8 reference sample filter of 8.3.2.2.1), Intra_16x16 and chroma (DC / horizontal / vertical / plane), 8-bit. --- Written from the spec. Predictions are written straight into the picture plane (row stride `s`, block origin `o`). --- Never throws: every sample read is inside the padded plane (callers pass availability for the edges). +-- codecs/video/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (with the 8x8 reference sample +-- filter of 8.3.2.2.1), Intra_16x16 and chroma, 8-bit. local readu8, writeu8 = buffer.readu8, buffer.writeu8 local Intra = {} @@ -101770,8 +98771,7 @@ local function directional(R, N, mode, b, o, s) end end --- pred4x4(b, o, s, mode, left, top, topRight, topLeft): Intra_4x4 at plane offset o. Unavailable top-right samples --- repeat p[3, -1]. +-- unavailable top-right samples repeat p[3, -1] function Intra.pred4x4(b, o, s, mode, left, top, topRight, topLeft) if mode == 0 then local t = o - s @@ -101846,7 +98846,6 @@ function Intra.pred4x4(b, o, s, mode, left, top, topRight, topLeft) directional(E, 4, mode, b, o, s) end --- pred8x8(b, o, s, mode, left, top, topRight, topLeft): Intra_8x8 with the reference sample filter function Intra.pred8x8(b, o, s, mode, left, top, topRight, topLeft) -- unfiltered edges into E: E[1..8] = p[-1, 7..0], E[9] = p[-1, -1], E[10..25] = p[0..15, -1] if left then @@ -101953,7 +98952,6 @@ function Intra.pred8x8(b, o, s, mode, left, top, topRight, topLeft) end end --- pred16x16(b, o, s, mode, left, top, topLeft) function Intra.pred16x16(b, o, s, mode, left, top, topLeft) if mode == 0 then local t = o - s @@ -102019,7 +99017,7 @@ local function fill4(b, o, s, v) end end --- predChroma(b, o, s, mode, left, top, topLeft): 8x8 chroma (4:2:0); mode 0 DC, 1 horizontal, 2 vertical, 3 plane +-- 8x8 chroma (4:2:0): mode 0 DC, 1 horizontal, 2 vertical, 3 plane function Intra.predChroma(b, o, s, mode, left, top, topLeft) if mode == 0 then local t = o - s @@ -102090,11 +99088,8 @@ local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 -- codecs/video/H264/Mb: macroblock reconstruction shared by the CAVLC and CABAC parsers (ITU-T H.264 8.3 - 8.5): --- neighbour availability (6.4.11), Intra4x4 / Intra8x8 mode prediction (8.3.1.1 / 8.3.2.1), motion vector prediction --- (8.4.1.3), P_Skip (8.4.1.1), B direct spatial and temporal (8.4.1.2), motion compensation with weighting, intra --- prediction and the residual. Written from the spec; the per-4x4 motion / mode grids follow the usual decoder layout --- (picture-wide arrays, one entry per 4x4 luma block, 1-based). --- Never throws: every index is in range by construction; reference indices past the list use the first entry. +-- neighbour availability (6.4.11), intra mode prediction (8.3.1.1 / 8.3.2.1), motion vector prediction (8.4.1.3), +-- P_Skip (8.4.1.1), B direct (8.4.1.2). Reference indices past the list use the first entry. local Intra = __include("codecs/video/H264/Intra") local Transform = __include("codecs/video/H264/Transform") local Inter = __include("codecs/video/H264/Inter") @@ -102117,7 +99112,6 @@ local BLK_X = { 0, 1, 0, 1, 2, 3, 2, 3, 0, 1, 0, 1, 2, 3, 2, 3 } local BLK_Y = { 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 3, 3 } Mb.BLK_X, Mb.BLK_Y = BLK_X, BLK_Y --- new() -> M, the per-macroblock scratch state function Mb.new() return { addr = 0, @@ -102167,7 +99161,6 @@ return { } end --- grids(mbW, mbH) -> the per-picture decoding grids (shared by the slices of one picture) function Mb.grids(mbW, mbH) local n = mbW * mbH local n4 = n * 16 @@ -102195,8 +99188,6 @@ local n = mbW * mbH } end --- ------------------------------------------------------------------------------------------------ neighbours --- start(S, M, addr): position and neighbour availability of macroblock addr function Mb.start(S, M, addr) local mbW = S.mbW local x, y = addr % mbW, math.floor(addr / mbW @@ -102229,7 +99220,7 @@ function Mb.start(S, M, addr) M.qpd = 0 end --- nC(S, M, bx, by) -> nC of luma block (bx, by) (9.2.1) +-- nC of luma block (bx, by) (9.2.1) function Mb.nC(S, M, bx, by) local g = M.g0 + by * S.w4 + bx local nzc = S.nzc @@ -102245,7 +99236,6 @@ local g = M.g0 + by * S.w4 + bx return 0 end --- nCc(S, M, tab, bx, by) -> nC of chroma AC block (bx, by) of the plane whose counts are in tab function Mb.nCc(S, M, tab, bx, by) local cw = S.cw4 local g = M.c0 + by * cw + bx @@ -102261,7 +99251,7 @@ local cw = S.cw4 return 0 end --- predMode(S, M, bx, by) -> predIntra4x4PredMode / predIntra8x8PredMode of the block whose top-left 4x4 is (bx, by) +-- predIntra4x4PredMode / predIntra8x8PredMode (8.3.1.1 / 8.3.2.1) function Mb.predMode(S, M, bx, by) local la = bx > 0 or M.iL local ta = by > 0 or M.iT @@ -102274,9 +99264,6 @@ local la = bx > 0 or M.iL return ((a < b) and (a) or (b)) end --- ------------------------------------------------------------------------------------------------ motion vectors --- neighbour(S, M, list, nx, ny) -> ref (UNAVAIL when not available), mvx, mvy of the 4x4 at (nx, ny) relative to the --- macroblock (nx, ny in -1 .. 4) local function neighbour(S, M, refs, mvs, nx, ny) local ok if ny < 0 then @@ -102309,8 +99296,7 @@ local function median(a, b, c) return max(min(a, b), min(max(a, b), c)) end --- mvp(S, M, list, x, y, w, ref, shape) -> mvpLX for the partition at (x, y) (4x4 units) of width w with reference --- index ref. shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right +-- shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right (8.4.1.3) local function mvp(S, M, list, x, y, w, ref, shape) local pic = S.pic local refs = ((list == 0) and (pic.ref0) or (pic.ref1)) @@ -102363,7 +99349,6 @@ local pic = S.pic end Mb.mvp = mvp --- set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y): motion data of a region into the picture grids local function set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y) local pic = S.pic local ref0, ref1, mv0, mv1, uid0, uid1 = pic.ref0, pic.ref1, pic.mv0, pic.mv1, pic.uid0, pic.uid1 @@ -102390,7 +99375,6 @@ local function set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y) M.nreg =M.nreg+ 1 end --- clipping helpers local function clip3(lo, hi, v) return min(max(v, lo), hi) end @@ -102403,7 +99387,7 @@ local q = a / b return -math.floor(-q) end --- distScale(cur, poc0, poc1) -> DistScaleFactor (8-195 .. 8-198), or nil when td is 0 +-- DistScaleFactor (8-195 .. 8-198), nil when td is 0 function Mb.distScale(cur, poc0, poc1) local tb = clip3(-128, 127, cur - poc0) local td = clip3(-128, 127, poc1 - poc0) @@ -102414,7 +99398,7 @@ local tb = clip3(-128, 127, cur - poc0) return clip3(-1024, 1023, math.floor((tb * tx + 32) / 64)) end --- pskip(S, M): P_Skip motion (8.4.1.1) +-- P_Skip motion (8.4.1.1) local function pskip(S, M) local mx, my = 0, 0 if M.aL and M.aT then @@ -102428,7 +99412,7 @@ local function pskip(S, M) set(S, M, 0, 0, 4, 4, 0, mx, my, -1, 0, 0) end --- colocated(S, M, bx, by) -> refIdxCol (-1: intra / none), mvCol x, y, uid of the referenced picture (8.4.1.2.1) +-- refIdxCol (-1: intra / none), mvCol (8.4.1.2.1) local function colocated(S, M, bx, by) local col = S.colPic if S.direct8x8 then @@ -102457,7 +99441,7 @@ if a >= 0 and b >= 0 then return ((a > b) and (a) or (b)) end --- spatialRefs(S, M): the macroblock-level references and predictors of spatial direct (8.4.1.2.2), cached in M +-- spatial direct references and predictors (8.4.1.2.2) local function spatialRefs(S, M) local pic = S.pic local r0, r1 = -1, -1 @@ -102498,7 +99482,6 @@ local function spatialRefs(S, M) M.dReady = true end --- direct8(S, M, i8): direct motion of 8x8 quadrant i8 (B_Skip, B_Direct_16x16, B_Direct_8x8) local function direct8(S, M, i8) local x0, y0 = (i8 % 2) * 2, (math.floor(i8 / 2)) * 2 local step = ((S.direct8x8) and (2) or (1)) @@ -102547,12 +99530,10 @@ local function direct8(S, M, i8) end end --- partition geometry (4x4 units) of the sub-macroblock shapes local SUB_N = { 1, 2, 2, 4 } local SUB_W = { 2, 2, 1, 1 } local SUB_H = { 2, 1, 2, 1 } --- motion(S, M): motion vectors of an inter macroblock into the grids, and its MC regions local function motion(S, M) local kind = M.kind M.dReady = false @@ -102639,8 +99620,6 @@ local function motion(S, M) end Mb.motion = motion --- ------------------------------------------------------------------------------------------------ motion compensation --- predict(S, M, pic, P, list, x, y, w, h, mvx, mvy, plane): one list's prediction samples of a region into P local function predLuma(S, ref, P, px, py, w, h, mvx, mvy) local W, H = S.mbW * 16, S.mbH * 16 local ix = px + math.floor(mvx / 4 @@ -102665,7 +99644,6 @@ local function refPic(list, r) return list[r + 1] or list[1] end --- mc(S, M): inter prediction of every region of the macroblock into the current picture local function mc(S, M) local pic = S.pic local reg = M.reg @@ -102692,7 +99670,6 @@ __DARKLUA_CONTINUE_13=true break local lo = pic.yo + py * ys + px local cx, cy, cw, ch = M.x * 8 + x * 2, M.y * 8 + y * 2, w * 2, h * 2 local co = pic.co + cy * cs + cx - -- weights for this pair local bi = ref0 ~= nil and ref1 ~= nil local explicit = wm == 1 local implicitW0, implicitW1 = 32, 32 @@ -102752,7 +99729,6 @@ __DARKLUA_CONTINUE_13=true break __DARKLUA_CONTINUE_13=true until true if not __DARKLUA_CONTINUE_13 then break end end end --- ------------------------------------------------------------------------------------------------ residual local function lumaResidual(S, M) local pic = S.pic local b, s = pic.y, pic.ys @@ -102804,7 +99780,6 @@ local function chromaResidual(S, M) end end --- ------------------------------------------------------------------------------------------------ intra local function intraLuma(S, M) local pic = S.pic local b, s = pic.y, pic.ys @@ -102909,8 +99884,6 @@ local function pcm(S, M) end end --- ------------------------------------------------------------------------------------------------ macroblock --- recon(S, M): reconstruct the parsed macroblock and store what later macroblocks / deblocking need function Mb.recon(S, M) local kind = M.kind local addr = M.addr + 1 @@ -102926,7 +99899,6 @@ function Mb.recon(S, M) local nzDb = S.nzDb local g0 = M.g0 if kind <= K_PCM then - -- intra: no motion local ref0, ref1, uid0, uid1 = pic.ref0, pic.ref1, pic.uid0, pic.uid1 for j = 0, 3 do local g = g0 + j * w4 @@ -102976,7 +99948,6 @@ function Mb.recon(S, M) chromaResidual(S, M) end --- skip(S, M, kind): a P_Skip / B_Skip macroblock (no residual) function Mb.skip(S, M, kind) M.kind = kind M.cbp = 0 @@ -103021,10 +99992,9 @@ end __FILES["codecs/video/H264/Params"] = function() --!strict --!native --- codecs/video/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists with --- the fall-back rules A and B (7.4.2.1.1 / table 7-2), and the dequantisation tables built from them (8.5.9: the --- LevelScale4x4 / LevelScale8x8 functions, premultiplied by 2^(qP / 6)). Written from the spec. --- Never throws: parse functions return nil, "message". +-- codecs/video/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists +-- with the fall-back rules A and B (7.4.2.1.1 / table 7-2), and the dequantisation tables built from them (8.5.9: the +-- LevelScale4x4 / LevelScale8x8 functions, premultiplied by 2^(qP / 6)). local Bitstream = __include("codecs/video/H264/Bitstream") local Tables = __include("codecs/video/H264/Tables") @@ -103039,7 +100009,7 @@ local MAX_DPB_MBS = { [9] = 396, [10] = 396, [11] = 900, [12] = 2376, [13] = 237 local ZIGZAG4, ZIGZAG8 = Tables.ZIGZAG4, Tables.ZIGZAG8 --- scaling_list(): returns the list in raster order, or "default" (useDefaultScalingMatrixFlag) +-- scaling_list(): raster order, or "default" (useDefaultScalingMatrixFlag) local function scalingList(r, size) local list = table.create(size, 0) local last, nxt = 8, 8 @@ -103095,7 +100065,7 @@ end local FLAT16, FLAT64 = table.create(16, 16), table.create(64, 16) --- resolve(lists, fallback) -> 12 raster lists. fallback: nil = rule A (defaults), else the 12 lists of the SPS (rule B) +-- fallback nil = rule A (defaults), else the SPS's 12 lists (rule B) local function resolve(lists, fallback) local out = {} for i = 1, 12 do @@ -103115,7 +100085,6 @@ local out = {} return out end --- ------------------------------------------------------------------------------------------------ vui local function hrd(r) local cnt = ue(r) if cnt > 31 then @@ -103188,8 +100157,6 @@ local function vui(r, sps) end end --- ------------------------------------------------------------------------------------------------ sps --- sps(r) -> the SPS table | nil, message. r is positioned after the NAL header. function Params.sps(r) local sps= {} sps.profile = u(r, 8) @@ -103310,8 +100277,6 @@ local sps= {} return sps, nil end --- ------------------------------------------------------------------------------------------------ pps --- pps(r, spsTable) -> the PPS | nil, message. spsTable: id -> SPS (needed for the scaling list count) function Params.pps(r, spsTable) local pps= {} pps.id = ue(r) @@ -103372,7 +100337,6 @@ local pps= {} return pps, nil end --- ------------------------------------------------------------------------------------------------ dequantisation local V4 = { { 10, 16, 13 }, { 11, 18, 14 }, { 13, 20, 16 }, { 14, 23, 18 }, { 16, 25, 20 }, { 18, 29, 23 } } local V8 = { { 20, 18, 32, 19, 25, 24 }, @@ -103445,7 +100409,6 @@ local d4, d8 = {}, {} return { d4 = d4, d8 = d8 } end --- dequant(sps, pps, cache) -> the dequant tables for this pair (cache: a table kept by the decoder, by content) function Params.dequant(sps, pps, cache) local lists if pps.scalingLists then @@ -103477,9 +100440,8 @@ __FILES["codecs/video/H264/Slice"] = function() local __compat = __compat local type = __compat.type --!strict --!native -- codecs/video/H264/Slice: the slice header (ITU-T H.264 7.3.3): ref_pic_list_modification, pred_weight_table and --- dec_ref_pic_marking. Written from the spec. Frame coding only: field pictures (field_pic_flag = 1), MBAFF, --- SP / SI slices, separate colour planes and redundant pictures return "unsupported: ...". --- Never throws: header() returns nil, "message". +-- dec_ref_pic_marking. Frame coding only: field pictures, MBAFF, SP / SI, separate colour planes and redundant +-- pictures return "unsupported: ...". local Bitstream = __include("codecs/video/H264/Bitstream") local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se @@ -103538,7 +100500,6 @@ local t = table.create(n * 8, 0) return t end --- header(r, nalType, nalRefIdc, spsTable, ppsTable) -> sh | nil, message function Slice.header(r, nalType, nalRefIdc, spsTable, ppsTable) local sh= {} sh.nalType = nalType @@ -103729,12 +100690,9 @@ end __FILES["codecs/video/H264/Tables"] = function() --!strict --!native --- codecs/video/H264/Tables: the constant tables of ITU-T H.264 (CAVLC code tables 9-5, 9-7, 9-8, 9-9, 9-10; CABAC context --- initialisation tables 9-12..9-24, rangeTabLPS 9-44 and the state transitions 9-45; the chroma QP table 8-15; the --- me(v) coded_block_pattern mapping 9-4; default scaling lists 7-3 / 7-4; zig-zag scans 8-12 / 8-13; table 9-43; the --- deblocking alpha / beta / tC0 tables 8-16 / 8-17). Values extracted from openh264 2.x (BSD-2-Clause, --- licenses/openh264-LICENSE.txt): encoder_data_tables.cpp, common_tables.cpp, decoder_data_tables.cpp, --- wels_common_basis.h, deblocking.cpp. Flat 1-based arrays; the layouts are noted at each table. +-- codecs/video/H264/Tables: the constant tables of ITU-T H.264 (CAVLC 9-5, 9-7..9-10; CABAC init 9-12..9-24, +-- rangeTabLPS 9-44, transitions 9-45; chroma QP 8-15; me(v) CBP 9-4; scaling lists 7-3 / 7-4; zig-zag 8-12 / 8-13; +-- 9-43; deblocking 8-16 / 8-17). Values from openh264 2.x (BSD-2-Clause, licenses/openh264-LICENSE.txt). local T = {} -- coeff_token per nC class (0: 0<=nC<2, 1: 2<=nC<4, 2: 4<=nC<8, 3: 8<=nC, 4: nC=-1 chroma DC): { code, len, TotalCoeff, @@ -103774,11 +100732,8 @@ __FILES["codecs/video/H264/Transform"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- codecs/video/H264/Transform: the inverse transforms of ITU-T H.264 8.5: the 4x4 and 8x8 integer IDCTs with the residual --- added to the prediction in the plane (8.5.12.2 / 8.5.13.2 / 8.5.14), the 4x4 luma DC and 2x2 chroma DC Hadamard --- transforms with their scaling (8.5.10 / 8.5.11.2). Written from the spec. Coefficients are dequantised already --- (Params.dequant), raster order, in a 1-based table at `base + 1 ...`; the functions zero what they read. --- Never throws. +-- codecs/video/H264/Transform: the inverse transforms of ITU-T H.264 8.5 (4x4 / 8x8 IDCT 8.5.12.2 / 8.5.13.2 / 8.5.14, +-- luma DC / chroma DC Hadamard 8.5.10 / 8.5.11.2). Coefficients come dequantised, raster order, at base + 1; zeroed after use. local readu8, writeu8 = buffer.readu8, buffer.writeu8 local Transform = {} @@ -103788,9 +100743,7 @@ local function clip(v) return min(max(v, 0), 255) end --- add4(c, base, b, o, s): inverse 4x4 transform of c[base + 1 .. base + 16], added to the 4x4 block at b[o] (stride s) function Transform.add4(c, base, b, o, s) - -- rows for i = 0, 3 do local k = base + i * 4 local d0, d1, d2, d3 = c[k + 1], c[k + 2], c[k + 3], c[k + 4] @@ -103803,7 +100756,6 @@ function Transform.add4(c, base, b, o, s) c[k + 3] = f - g c[k + 4] = e - h end - -- columns for j = 0, 3 do local k = base + j local d0, d1, d2, d3 = c[k + 1], c[k + 5], c[k + 9], c[k + 13] @@ -103823,7 +100775,6 @@ function Transform.add4(c, base, b, o, s) end end --- addDc4(dc, b, o, s): a 4x4 block whose only coefficient is the (dequantised) DC function Transform.addDc4(dc, b, o, s) local v = math.floor((dc + 32) / 64 ) if v == 0 then @@ -103840,11 +100791,9 @@ end local T8 = table.create(64, 0) --- add8(c, base, b, o, s): inverse 8x8 transform of c[base + 1 .. base + 64] added to the 8x8 block at b[o] function Transform.add8(c, base, b, o, s) for pass = 0, 1 do for i = 0, 7 do - -- pass 0: rows of c into T8; pass 1: columns of T8 local d0, d1, d2, d3, d4, d5, d6, d7 if pass == 0 then local k = base + i * 8 @@ -103901,8 +100850,7 @@ function Transform.add8(c, base, b, o, s) end end --- lumaDc(dc, m, c): the Intra_16x16 DC levels dc[1..16] (raster 4x4 matrix) -> inverse Hadamard, scaled with the --- DC multiplier m (LevelScale4x4(qP % 6, 0, 0) * 2^(qP / 6)), stored at c[blk * 16 + 1] (blk = raster block index) +-- m = LevelScale4x4(qP % 6, 0, 0) * 2^(qP / 6) function Transform.lumaDc(dc, m, c) for i = 0, 3 do local k = i * 4 @@ -103930,7 +100878,6 @@ function Transform.lumaDc(dc, m, c) ) end end --- chromaDc(dc, base, m, c, cbase): the 2x2 chroma DC levels dc[base + 1 .. base + 4] -> c[cbase + blk * 16 + 1] function Transform.chromaDc(dc, base, m, c, cbase) local c0, c1, c2, c3 = dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] = 0, 0, 0, 0 @@ -103949,23 +100896,8 @@ end __FILES["codecs/video/Legacy"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. --- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk --- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak", --- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation --- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey), QuickTime Graphics ("smc", 'smc ') and Smacker --- video ("smackvid", the frames of video/smk: track.config = the header's tree sizes and trees, codecTag SMK2 / SMK4). --- New in rosetta, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's --- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns --- a fresh copy. --- --- Palettes come from the Track: track.palette (256 u32 entries, bytes R, G, B, A: the AVI BITMAPINFO palette, the --- QuickTime sample description's colour table, ...) and a packet's own `palette` (same layout) replaces it from that --- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth). --- --- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder --- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } --- --- Never throws: bad tracks return nil, Err; bad packets return Err from decode(). +-- From the format descriptions (see each submodule), bit-exact with ffmpeg. Palette: track.palette, replaced by a +-- packet's palette (256 u32 entries R, G, B, A); depth: track.bitsPerPixel (AVI biBitCount, QuickTime depth). local Err = __include("core/Err") local Types = __include("Types") local Picture = __include("codecs/video/Legacy/Picture") @@ -103986,7 +100918,6 @@ Legacy.QtRle = QtRle Legacy.Smc = Smc Legacy.Smacker = Smacker Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } --- the per-codec pieces: make(track) -> state, step(state, data, packet) -> image? | nil, Err? @@ -104114,7 +101045,6 @@ local CODECS= { }, } --- newDecoder(id, track, opts?) -> a Types.VideoCodecDecoder | nil, Err function Legacy.newDecoder(id, track, opts) local codec = CODECS[id] if not codec then @@ -104132,7 +101062,6 @@ local codec = CODECS[id] if not st then return nil, fail(msg) end - -- Video.simpleDecoder, without requiring the registry (which requires this module) local queue= {} local self = {} function self.decode(_, packet) @@ -104155,7 +101084,7 @@ local q = table.remove(queue, 1) function self.flush(_) end function self.reset(_) table.clear(queue) - st = codec.make(track) or st -- back to a black picture with the track's palette (decoding restarts at a keyframe) + st = codec.make(track) or st end return self , nil end @@ -104166,14 +101095,10 @@ __FILES["codecs/video/Legacy/Cinepak"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames: 24-bit colour (codebook entries of 4 luma + 2 chroma, or 4 --- luma for grey), and 8-bit palettised streams (entries are palette indexes). Written from the format description --- (MultimediaWiki "Cinepak"): a frame header (flags, size, width, height, strip count), strips with their own V1 / V4 --- codebooks (full or partial updates, kept per strip between frames, inherited from the strip above unless the frame --- flags say otherwise) and the vector chunks (intra, inter with skip flags, V1-only). Colour codebook entries are --- converted once with the Cinepak YUV formula (r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped). Sega FILM's extra --- header bytes are detected on the first frame. Paints over the previous picture. Bit-exact with ffmpeg's cinepak --- decoder. Never throws: every read is range-checked against its chunk. +-- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames, 24-bit colour and 8-bit palettised. +-- From MultimediaWiki "Cinepak", bit-exact with ffmpeg: a frame header (flags, size, width, height, strip count), strips +-- with V1 / V4 codebooks (inherited from the strip above unless the flags say otherwise) and vector chunks. +-- Colour entries: r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped. local Picture = __include("codecs/video/Legacy/Picture") local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 @@ -104258,7 +101183,7 @@ local function codebook(books, book, id, d, p, stop) end end --- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only); false on truncated data +-- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only) local function vectors(pic, books, v4, v1, id, d, p, stop, x1, y1, x2, y2) local stride = pic.stride @@ -104359,8 +101284,6 @@ local flag, mask = 0, 0 return true end --- decode(pic, data, state, hasPalette) -> picture?, message: true = a picture; false + nil = no picture for this --- packet (an empty frame); false + message = an error function Cinepak.decode(pic, d, st, newPalette) local n = buffer.len(d) if n < 10 then @@ -104403,7 +101326,6 @@ local n = buffer.len(d) local p = 10 + skip strips = math.min(strips, MAX_STRIPS) local books = st.books - -- the coded area: the size rounded up to whole blocks (the picture's plane) local cw, ch = pic.stride, pic.rows local y0 = 0 for i = 0, strips - 1 do @@ -104428,7 +101350,6 @@ local n = buffer.len(d) if i > 0 and band(flags, 1) == 0 then buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK) end - -- the strip's chunks: codebooks, then one vector chunk -- (strips start on block boundaries in every known stream: the plane holds whole blocks only) if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then return true, nil @@ -104471,15 +101392,12 @@ __FILES["codecs/video/Legacy/Flic"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is --- video/fli). Written from the FLIC file format description (Jim Kent's "FLC - Animator Pro Flic Files", Dr. Dobb's --- 1993; MultimediaWiki "Flic Video"). 8-bit palettised: COLOR_256 (4), COLOR_64 (11, 6-bit entries widened by bit --- replication), DELTA_FLC / SS2 (7: word runs, line skips, last-byte opcode), DELTA_FLI / LC (12: byte runs), BLACK --- (13), BYTE_RUN / BRUN (15), FLI_COPY (16, rows padded to 4), PSTAMP (18, skipped). 15 / 16 / 24-bit FLC and FLX --- (DTA): DELTA / DTA_LC (pixel runs), BLACK, BRUN (byte runs), DTA_BRUN (25, pixel runs), COPY / DTA_COPY (16 / 26); --- pixels are 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. Not supported: 1-bit FLICs, the Magic Carpet --- 6-bit COLOR_256 variant. Paints over the previous picture. Bit-exact with ffmpeg's flic decoder on valid frames. --- Never throws: reads past the frame give zeros, every write is range-checked (a damaged frame gives no picture). +-- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is video/fli). +-- From Jim Kent's "FLC - Animator Pro Flic Files" (Dr. Dobb's 1993) and MultimediaWiki "Flic Video", bit-exact with +-- ffmpeg. 8-bit: COLOR_256 (4), COLOR_64 (11), DELTA_FLC / SS2 (7), DELTA_FLI / LC (12), BLACK (13), BYTE_RUN / BRUN +-- (15), FLI_COPY (16, rows padded to 4), PSTAMP (18). 15 / 16 / 24-bit FLC and FLX (DTA): DELTA / DTA_LC, BLACK, BRUN, +-- DTA_BRUN (25), COPY / DTA_COPY (16 / 26); 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. +-- Not supported: 1-bit FLICs, the Magic Carpet 6-bit COLOR_256 variant. local Types = __include("Types") local Picture = __include("codecs/video/Legacy/Picture") @@ -104487,8 +101405,6 @@ local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer local bfill = buffer.fill local Flic = {} --- the decoding state of one stream: a byte plane (stride = width * bytes per pixel) and the palette --- state(w, h, depth) -> State | nil, message @@ -104510,7 +101426,6 @@ local function s8(v) return (v >= 128 and((v - 256 ))or(v ))end --- decode(st, data) -> true | false, message function Flic.decode(st, d) local pic = st.pic local px = pic.idx @@ -104806,7 +101721,6 @@ __DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end return true, nil end --- image(st) -> a fresh rgba8 Image function Flic.image(st) local pic = st.pic if st.bpp == 1 then @@ -104845,12 +101759,10 @@ __FILES["codecs/video/Legacy/Msvideo1"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM) frames, 8-bit palettised and 16-bit --- X-R-G-B 1-5-5-5. Written from the format description (MultimediaWiki "Microsoft Video 1"): 4x4 blocks, block rows --- bottom-up (rows of a block bottom-up too), each block a 16-bit code: a skip count (0x84xx - 0x87xx), a 2-colour --- block (16 flag bits + 2 colours; at 16 bits a first colour with bit 15 set makes it an 8-colour block, one colour --- pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), or a 1-colour block. Paints over the previous picture. --- Bit-exact with ffmpeg's msvideo1 decoder. Never throws: every read is range-checked (a damaged frame stops there). +-- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM), 8-bit palettised and 16-bit X-R-G-B 1-5-5-5. +-- From MultimediaWiki "Microsoft Video 1", bit-exact with ffmpeg: 4x4 blocks, block rows (and rows in a block) bottom-up; +-- a 16-bit code per block: skip (0x84xx - 0x87xx), 2-colour (16 flag bits + 2 colours; at 16 bits c0 bit 15 set = 8-colour, +-- a pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), else 1-colour. local Picture = __include("codecs/video/Legacy/Picture") local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 @@ -104858,13 +101770,11 @@ local band = bit32.band local Msvideo1 = {} --- the colour of pixel (x, y) of a block (y = 0 is the block's bottom row) for flag bit f: 2-colour c0 / c1 --- (bit set = c0), 8-colour: colours[quadrant * 2 + (bit clear)] +-- 2-colour: bit set = c0; 8-colour: colours[quadrant * 2 + (bit clear)] local function quadrant(x, y) return (y >= 2 and 4 or 0) + (x >= 2 and 2 or 0) end --- decode(pic, data, bits) -> true | false, message (bits = 8: palettised, else 16-bit) function Msvideo1.decode(pic, d, bits) local n = buffer.len(d) local bw, bh = math.floor(pic.w / 4), math.floor(pic.h / 4 @@ -104894,7 +101804,6 @@ __DARKLUA_CONTINUE_2=true break if a == 0 and b == 0 and total == 0 then return true, nil end - -- the block's bottom-left pixel; its rows go up local o = (by * 4 + 3) * stride + bx * 4 if band(b, 0xFC) == 0x84 then skip = (b - 0x84) * 256 + a - 1 @@ -104968,11 +101877,8 @@ __FILES["codecs/video/Legacy/Picture"] = function() local __compat = __compat local buffer = __compat.buffer --!strict --!native --!optimize 2 --- codecs/video/Legacy/Picture: the picture every legacy decoder keeps between frames (they are all inter-frame --- codecs: a packet paints over the previous picture). Palettised codecs keep a u8 index plane and a 256-entry palette, --- direct-colour ones an rgba8 plane; both planes are padded (stride / rows) so the codecs' block and run writes past --- the visible edge land in range. Also the 5-5-5 / 5-6-5 to 8-bit tables: channels are widened by bit replication --- (c << 3 | c >> 2), as ffmpeg's swscale does, so the output equals ffmpeg's rgba conversion. New in rosetta. +-- codecs/video/Legacy/Picture: the picture the legacy inter-frame decoders paint over (u8 index plane + palette or rgba8). +-- 5-5-5 / 5-6-5 widen by bit replication (c << 3 | c >> 2), as ffmpeg's swscale does. local Types = __include("Types") local Pixels = __include("codecs/image/Pixels") @@ -104980,7 +101886,6 @@ local readu32, writeu32 = buffer.readu32, buffer.writeu32 local Picture = {} --- new(w, h, palettised, padW?, padH?, palette?) -> a black picture; padW / padH round the plane up (blocks of 4, ...) @@ -105008,7 +101913,6 @@ local pw, ph = padW or 1, padH or 1 return p end --- image(p) -> a fresh rgba8 Image of the visible w x h function Picture.image(p) local w, h = p.w, p.h local img = Types.Image.new(w, h, "rgba8") @@ -105027,7 +101931,6 @@ local w, h = p.w, p.h return img end --- setPalette(p, src): a 1024-byte palette (u32 R, G, B, A entries) from a packet or the track function Picture.setPalette(p, src) if buffer.len(src) >= 1024 then buffer.copy(p.pal, 0, src, 0, 1024) @@ -105037,7 +101940,6 @@ end local lut555= nil local lut565= nil --- rgb555() -> u32 table: X-R-G-B 1-5-5-5 value -> rgba8 pixel (opaque); 32768 entries function Picture.rgb555() local t = lut555 if t then @@ -105053,7 +101955,6 @@ local t = lut555 return b end --- rgb565() -> u32 table: R-G-B 5-6-5 value -> rgba8 pixel; 65536 entries function Picture.rgb565() local t = lut565 if t then @@ -105069,7 +101970,6 @@ local t = lut565 return b end --- copy of a picture's plane (for decoders that read the previous picture while writing the next) function Picture.clonePlane(p) local src = (p.idx or p.rgba) local c = buffer.create(buffer.len(src)) @@ -105085,14 +101985,11 @@ __FILES["codecs/video/Legacy/QtRle"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey) and --- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). Written from the format description (Apple QuickTime File --- Format; MultimediaWiki "Apple QuickTime RLE"): a chunk size, a header (0x0008: start line + line count), then per --- line a skip byte and run codes until -1 (0: another skip; < 0: one pixel group repeated; > 0: literal groups). --- Groups are 4 pixels at 8 bits, 8 at 4 bits, 16 at 2 bits, 1 pixel at 16 / 24 / 32 bits; the 1-bit layout has its --- own (skip, code) pairs where a skip with bit 7 set moves to the next line. Paints over the previous picture; frames --- shorter than 8 bytes repeat it. Bit-exact with ffmpeg's qtrle decoder on valid streams. Never throws: every read --- and write is range-checked (a damaged frame stops where the damage is). +-- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey), +-- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). From Apple QuickTime File Format and MultimediaWiki "Apple +-- QuickTime RLE", bit-exact with ffmpeg on valid streams: chunk size, header (0x0008: start line + line count), per line +-- a skip byte and codes until -1 (0: another skip; < 0: one group repeated; > 0: literal groups). Groups are 4 pixels at +-- 8 bits, 8 at 4, 16 at 2, 1 at 16 / 24 / 32. Frames shorter than 8 bytes repeat the picture. local Picture = __include("codecs/video/Legacy/Picture") local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 @@ -105167,8 +102064,8 @@ end -- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups local function decodeIdx(px, stride, limit, d, p, n, row, lines, bpp) - local group = math.floor(32 / bpp -- pixels per 4 bytes -) local per = math.floor(8 / bpp -- pixels per byte + local group = math.floor(32 / bpp +) local per = math.floor(8 / bpp ) local mask = 2 ^ bpp - 1 for _ = 1, lines do if p >= n then @@ -105308,11 +102205,10 @@ local function decodeRgb(px, stride, limit, d, p, n, row, lines, depth) end end --- decode(pic, data, depth) -> true (a picture, possibly the previous one again) | false, message function QtRle.decode(pic, d, depth) local n = buffer.len(d) if n < 8 then - return true, nil -- no change + return true, nil end local p = 4 local header = readu8(d, p) * 256 + readu8(d, p + 1) @@ -105348,7 +102244,6 @@ local n = buffer.len(d) return true, nil end --- palettised(depth) -> whether the depth uses a palette; pad(depth) -> the row padding the plane needs function QtRle.palettised(depth) return depth <= 8 or depth > 32 end @@ -105364,17 +102259,12 @@ local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, _ --!native --!optimize 2 -- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and --- the Huffman trees Smacker audio shares. Written from the format description (MultimediaWiki "Smacker"). Bits are --- read LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf with its value); --- an 8-bit tree's leaves hold bytes, a "big" tree's leaves hold 16-bit values made of a low-byte and a high-byte --- 8-bit tree, three of them being escape leaves that return the three most recently decoded values instead (a --- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header; --- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a --- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour). --- Trees are flat arrays (a node stores the size of its left subtree, as a negative number); the frame decoder reads --- 10 bits at a time through a lookup table into them. --- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give --- zero bits, a frame whose codes run out of bits gives no picture. +-- the Huffman trees Smacker audio shares. From MultimediaWiki "Smacker", bit-exact with ffmpeg's smackvid. +-- Bits LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf). A big tree's 16-bit +-- leaves pair a low-byte and a high-byte 8-bit tree; three escape leaves return the three most recently decoded values +-- (reset each frame). The header holds the MMAP, MCLR, FULL and TYPE big trees; a frame is 4x4 blocks in raster order, +-- each TYPE code a block type and run length: MONO (two colours + 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds +-- 2x2- and 2x1-doubled modes), SKIP, FILL. local Picture = __include("codecs/video/Legacy/Picture") local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 @@ -105391,7 +102281,6 @@ for i = 1, 59 do RUNS[i] = i end RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048 --- a bit position over buf[0, nbits / 8) @@ -105409,7 +102298,6 @@ local p = br.pos end Smacker.bit = bit --- read(br, n) -> n bits (LSB first; zeros past the end) function Smacker.read(br, n) local v, m = 0, 1 for _ = 1, n do @@ -105420,7 +102308,7 @@ local v, m = 0, 1 end local readBits = Smacker.read --- walk(tree, br) -> the leaf value (no end-of-data check: 8-bit trees, as the reference's table lookups) +-- no end-of-data check for 8-bit trees, as the reference's table lookups local function walk(tree, br) local i = 1 local e = tree[1] @@ -105435,7 +102323,6 @@ local i = 1 end Smacker.walk = walk --- the pre-order tree reader: leaf(index) -> value | nil, message; returns the flat tree (1-based) local function build(br, maxDepth, maxEntries, leaf, bigChecks) local vals= {} local n = 0 @@ -105482,7 +102369,6 @@ local vals= {} end end --- tree8(br) -> an 8-bit tree (leaves are bytes) | nil, message function Smacker.tree8(br) local leaves = 0 return build(br, MAX_DEPTH8, 511, function(_) @@ -105498,7 +102384,6 @@ if leaves >= 256 then end local tree8 = Smacker.tree8 --- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries) local function bigTree(br, size) @@ -105544,7 +102429,7 @@ local v = walk(lo, br) + walk(hi, br) * 256 return { vals = vals, last = last }, nil end --- trees(config) -> the four header trees | nil, message. config = the four u32 tree sizes then the tree bits +-- config = the four u32 tree sizes, then the tree bits function Smacker.trees(config) @@ -105603,7 +102488,6 @@ local function reset(t) vals[last[1] ], vals[last[2] ], vals[last[3] ] = 0, 0, 0 end --- decode(pic, data, trees, v4) -> true | false, message. pic: palettised, padded to blocks of 4 function Smacker.decode(pic, d, trees, v4) local px = pic.idx local stride = pic.stride @@ -105617,7 +102501,6 @@ local stride = pic.stride local n = buffer.len(d) local nbits = n * 8 local pos = 0 - -- the next value of a tree (updating its recent-value cache) | -1 when the bits run out inside the tree local function code(t) local vals = t.vals local i, p @@ -105770,13 +102653,9 @@ __FILES["codecs/video/Legacy/Smc"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised. Written from the format description --- (MultimediaWiki "Apple SMC"): 4x4 blocks in raster order, opcodes in the high nibble with a block count (low nibble --- + 1, or the next byte + 1 when bit 4 is set): skip, repeat the last block, repeat the last pair of blocks, 1-colour --- fill, 2 / 4 / 8-colour blocks (the colour groups go into 256-entry rotating tables, or come from them by index: --- the tables restart every frame) and 16-colour blocks. Paints over the previous picture. Bit-exact with ffmpeg's smc --- decoder (for widths whose rows are not padded: the previous block of a row start is the last block of the row --- above). Never throws: reads past the data give zeros, the block count bounds every write. +-- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised; from MultimediaWiki "Apple SMC", +-- bit-exact with ffmpeg. 4x4 blocks in raster order; opcode in the high nibble, count = low nibble + 1 (bit 4: next +-- byte + 1); the colour-group tables restart every frame. As ffmpeg: a row start's previous block ends the row above. local Picture = __include("codecs/video/Legacy/Picture") local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 @@ -105784,7 +102663,6 @@ local band, rshift = bit32.band, bit32.rshift local Smc = {} --- decode(pic, data, tables) -> true | false, message. tables = Smc.tables() (scratch, reused between frames) function Smc.decode(pic, d, tables) local px = pic.idx local n = buffer.len(d) @@ -105796,7 +102674,6 @@ local n = buffer.len(d) end local blocksWide = math.floor((pic.w + 3) / 4 ) local p = 4 -- flags byte + 24-bit chunk size - -- block position: bx, by (blocks) local bx, by = 0, 0 local pairI, quadI, octI = 0, 0, 0 -- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8) @@ -105928,7 +102805,6 @@ if kind % 2 == 0 then advance() end else - -- 16-colour blocks for _ = 1, count do if total <= 0 or by >= bh then break @@ -105944,7 +102820,6 @@ if kind % 2 == 0 then return true, nil end --- tables() -> the colour group scratch (pairs, quads, octets) function Smc.tables() return buffer.create(512 + 1024 + 2048) end @@ -105953,9 +102828,8 @@ return Smc end __FILES["codecs/video/Mpeg1"] = function() --!strict --- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder --- decodes MPEG-1 streams): this module keeps the old name and API (Mpeg1.new, frameImage, PICTURE_*, the Frame / --- Options / Decoder types). Absorbed from mpeg1-luau e2e2898 (same author); see codecs/video/Mpeg2. +-- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), the old name and API over codecs/video/Mpeg2. +-- From mpeg1-luau e2e2898 (same author). local Mpeg2 = __include("codecs/video/Mpeg2") @@ -105967,24 +102841,9 @@ end __FILES["codecs/video/Mpeg2"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict -- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile). --- Progressive and interlaced (frame and field pictures, field / dual-prime prediction, field DCT), 4:2:0 and 4:2:2, I / --- P / B pictures with display reordering, every MPEG-2 coding tool of Main profile (Mpeg2/Decoder.luau). Output planes --- are bit-exact with `ffmpeg -idct int` (codecs/video/Dsp; tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Grown from --- the MPEG-1 decoder absorbed from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder --- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). codecs/video/Mpeg1 is this --- module under its old name. Frames come out woven (both fields of an interlaced frame, top field on even lines); --- frame.fields / topFieldFirst / repeatFirstField / progressive say how they were coded. --- Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped). --- --- local dec = Mpeg2.new({ reorder = true, rgba = false }) --- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts --- local img = Mpeg2.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true)) --- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces --- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek --- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, chroma, ... } --- local vdec = Mpeg2.newVideoDecoder(track, opts) -- a Types.VideoCodecDecoder (codecs/video/Video: mpeg1, mpeg2) --- --- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). +-- Bit-exact with `ffmpeg -idct int`. Grown from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder +-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). Frames come out woven (top +-- field on even lines). Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped). local Types = __include("Types") local Err = __include("core/Err") local D = __include("codecs/video/Mpeg2/Decoder") @@ -106017,13 +102876,6 @@ Mpeg2.PICTURE_B = 3 - - - - - - - @@ -106121,7 +102973,6 @@ local function sync(self) self.stats.skipped = st.skipped end --- a decoded picture -> the frame to return now (nil while reordering holds it) local function handle(self, s) if not self._reorder or s.ptype == D.PICTURE_B then return emit(self, s) @@ -106172,19 +103023,14 @@ if type(data) == "string" then return true end --- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument. function Decoder.write(self, data, offset, len) return append(self, data, offset, len) end --- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is --- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one). function Decoder.decodeFrame(self) return run(self, false, nil) end --- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data). --- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag. function Decoder.decode(self, data, offset, len, tag) if not append(self, data, offset, len) then return nil @@ -106192,8 +103038,6 @@ if not append(self, data, offset, len) then return run(self, true, tag) end --- At the end of the stream: decodes what is left of the written data, then returns the reference picture held --- for reordering. Call until it returns nil. function Decoder.flush(self) local f = run(self, true, nil) if f then @@ -106207,24 +103051,15 @@ local f = run(self, true, nil) return nil end --- Sets (or clears, nil) the cooperative yield hook (Options.yield). function Decoder.setYield(self, hook) self._core.setYield((type(hook) == "function" and{hook }or{nil})[1]) end --- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture). function Decoder.reset(self) self._core.reset() self._held = nil end --- YCbCr 4:2:0 planes (a frame's y / cb / cr / codedWidth, or copies of them) -> RGBA8 rows row0 .. row1 - 1 of a --- width x height picture, written to out from byte outOffset (default 0) as (row1 - row0) rows of width * 4 bytes. --- row0 is rounded down to even (rows share chroma in pairs); defaults 0 and height. Lets the conversion run in --- bands (on several threads) or only for the frames that are shown. The planes may hold only rows planeRow0 .. --- (planeRow0 even, default 0; their row 0 is picture row planeRow0). hook: a cooperative yield point every 16 rows. --- Returns false (writing nothing) when an argument is out of range. (4:2:0 only: a 4:2:2 frame's chroma has as many --- rows as its luma; use frameImage(frame, true) for those.) function Mpeg2.toRgba(y, cb, cr, codedWidth, width, height, out, row0, row1, outOffset, planeRow0, hook) if type(y) ~= "buffer" or type(cb) ~= "buffer" or type(cr) ~= "buffer" or type(out) ~= "buffer" then return false @@ -106241,7 +103076,6 @@ if type(y) ~= "buffer" or type(cb) ~= "buffer" or type(cr) ~= "buffer" or type(o if r0 < 0 or r1 > h or r1 <= r0 or pr < 0 or pr % 2 ~= 0 or pr > r0 or oo < 0 or oo % 4 ~= 0 then return false end - -- the planes must cover rows pr .. r1 - 1 (luma) and their chroma rows; out the band local lumaRows = r1 - pr local chromaRows = math.floor((r1 + 1) / 2 )- math.floor(pr / 2 ) if buffer.len(y) < lumaRows * cw or buffer.len(cb) < chromaRows * (math.floor(cw / 2)) or buffer.len(cr) < chromaRows * (math.floor(cw / 2)) then @@ -106250,15 +103084,10 @@ if type(y) ~= "buffer" or type(cb) ~= "buffer" or type(cr) ~= "buffer" or type(o if buffer.len(out) < oo + (r1 - r0) * w * 4 then return false end - -- rows relative to the planes' first row D.toRgba(y, cb, cr, cw, w, h, out, r0 - pr, r1 - pr, oo, (type(hook) == "function" and{hook }or{nil})[1]) return true end --- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to --- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"; 4:2:2 chroma --- averaged over line pairs of the same field), or rgba8 (the decoder's BT.601 conversion) when rgba is true. nil for --- a value that is not a Frame. function Mpeg2.frameImage(frame, rgba) if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then return nil @@ -106327,10 +103156,6 @@ if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buf return img end --- ------------------------------------------------------------------------------------------------ VideoCodecDecoder --- newVideoDecoder(track, opts) -> a Types.VideoCodecDecoder (codecs/video/Video's mpeg1 and mpeg2 entries): pictures in --- decode order, reordered for display; the packet's pts travels with its picture. A packet may hold any number of --- pictures (MPEG-PS / TS units, AVI chunks) or part of one (written as a stream). function Mpeg2.newVideoDecoder(_track, opts) local dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) local queue= {} @@ -106349,7 +103174,7 @@ local tag = { packet.pts } if not ok then return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f)) end - while f do -- more pictures in the packet + while f do push(f) f = dec:decode(packet.data, 0, 0, tag) end @@ -106383,25 +103208,10 @@ end __FILES["codecs/video/Mpeg2/Decoder"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (native, never throws). --- ISO/IEC 11172-2 and ISO/IEC 13818-2 Main profile: I, P and B pictures; progressive and interlaced sequences; frame --- pictures (frame / field motion compensation, frame / field DCT) and field pictures (field and 16x8 motion --- compensation, the second field predicted from the first); dual-prime; 4:2:0 and 4:2:2; intra DC precision 8..11; --- linear and non-linear quantiser scales; Table B-15 intra VLCs; the alternate scan; custom (and chroma) quantiser --- matrices; mismatch control; concealment motion vectors; sequence headers anywhere (size changes). Not supported: --- 4:4:4, the scalable / multiview extensions, D-pictures (skipped). --- --- Grown from the MPEG-1 core absorbed from mpeg1-luau e2e2898 (same author; a port of jsmpeg's decoder, src/mpeg1.js --- by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt, with table-driven VLCs, B-pictures and SWAR motion --- compensation). The IDCT and motion compensation are codecs/video/Dsp (the IDCT bit-exact with ffmpeg's -idct int), --- and dequantisation follows ffmpeg's arithmetic, so the output planes equal `ffmpeg -idct int` decoding for valid --- streams (tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Coefficients are saturated to -2048..2047 (13818-2 --- 7.4.3; ffmpeg omits it, valid streams never reach it) and motion vectors pointing outside the reference are --- clamped (ffmpeg skips the prediction): both only matter for corrupt data. --- --- Everything works on flat buffers allocated per sequence size: no allocation per block, macroblock or picture. --- Every read position is checked against the data end (plus a zero pad that bounds the overrun of one macroblock), --- motion vectors are clamped to the reference picture, and bad data ends the slice instead of raising. +-- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (ISO/IEC 11172-2, 13818-2 Main profile). +-- From mpeg1-luau e2e2898 (same author; a port of jsmpeg's src/mpeg1.js by Dominic Szablewski, MIT, +-- licenses/jsmpeg-MIT.txt). Dequantisation follows ffmpeg's arithmetic; coefficients are saturated to -2048..2047 +-- (13818-2 7.4.3; ffmpeg omits it) and vectors outside the reference are clamped (ffmpeg skips the prediction). local V = __include("codecs/video/Mpeg2/Vlc") local T = __include("codecs/video/Mpeg2/Tables") local Dsp = __include("codecs/video/Dsp") @@ -106466,17 +103276,13 @@ local RBIAS = COFF * 256 - 298 * 16 - 409 * 128 - 128 local GBIAS = COFF * 256 - 298 * 16 + 100 * 128 + 208 * 128 - 160 local BBIAS = COFF * 256 - 298 * 16 - 516 * 128 - 72 --- clamp to 0..255 by lookup: RGB_CLAMP[v + COFF] = clamp(v, 0, 255) for v in [-COFF, COFF + 255] (the colour biases --- include COFF * 256, so the shifted sums below are indices): the same values as math.clamp, 2-3x faster natively +-- clamp by lookup: RGB_CLAMP[v + COFF] for v in [-COFF, COFF + 255]; the colour biases include COFF * 256 local RGB_CLAMP = buffer.create(2 * COFF + 256) for i = 0, 2 * COFF + 255 do buffer.writeu8(RGB_CLAMP, i, math.clamp(i - COFF, 0, 255)) end --- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path. --- Rows row0 .. row1 - 1 of the planes (row0 even; default 0 .. h) into out from byte oo (default 0). hook (optional) --- runs every 16 rows (a cooperative yield point; it is pcall'ed, so it can't throw through here). (From mpeg1-luau's --- later banded conversion.) +-- 4:2:0 -> RGBA8 with nearest chroma, like ffmpeg's default swscale path; hook is pcall'ed (can't throw through here) local function toRgba(Y, Cb, Cr, cw, w, h, out, row0, row1, oo, hook) -- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four local r0= row0 or 0 @@ -106591,12 +103397,6 @@ D.toRgba422 = toRgba422 - - - - - - @@ -106627,7 +103427,6 @@ local state = { refNew = nil , } - -- bitstream local data = buffer.create(64 * 1024 + PAD) local dataLen = 0 local readByte = 0 -- next byte to look at for a start code @@ -106635,7 +103434,6 @@ local state = { local pos = 0 -- bit position inside data local err = false - -- sequence local hasSeq = false local mpeg2 = false local chroma = 1 -- 1 = 4:2:0, 2 = 4:2:2 @@ -106656,7 +103454,6 @@ local state = { -- the sequence header's values, applied (and the stores allocated) once its extension has been seen local seqW, seqH = 0, 0 - -- picture local ptype = 0 local fc00, fc01, fc10, fc11 = 1, 1, 1, 1 -- f_code[s][t] local fullPelFw, fullPelBw = false, false @@ -106682,7 +103479,6 @@ local state = { local pendingFw= nil local pendingBw= nil - -- slice / macroblock local qscale = 2 local mbAddr, mbRow, mbCol = 0, 0, 0 local dcY, dcCb, dcCr = 128, 128, 128 @@ -106725,7 +103521,6 @@ local e = readu32(lut, rshift(peek32(), 32 - k) * 4) return band(e, 0xFFFF) - 32768 end - -- byte offset of the next 00 00 01 xx at or after from (with xx before to), or -1 local function findStart(from, to) local i = from while i + 3 < to do @@ -106779,7 +103574,6 @@ local y = buffer.create(cw * lumaH) end end - -- the sequence (header + extension) takes effect: sizes and stores local function applySequence() local w, h = seqW, seqH if w == 0 or h == 0 or w * h > state.maxPixels then @@ -106811,7 +103605,6 @@ local w, h = seqW, seqH return true end - -- sequence header at byte p (after the start code); false when invalid local function sequenceHeader(p) pos = p * 8 local w = read(12) @@ -106928,11 +103721,6 @@ local code = vlc(MOTION, MOTION_BITS) return (pred + d + range) % (2 * range) - range end - -- ------------------------------------------------------------------------------------------------ prediction - -- One prediction of the current macroblock part from the reference planes rY / rCb / rCr: field-based (sp >= 0: - -- source field sp, destination field dp of the frame, line stride 2 * cw) or frame-based (sp < 0); rowY / h: the - -- first luma line of the part in those lines and its height; (mvx, mvy) in half samples; avg averages into the - -- first prediction. local EDGE = buffer.create(Dsp.EDGE_SIZE) local function mcPart(rY, rCb, rCr, sp, dp, rowY, h, mvx, mvy, avg) local stride, sb, db, ph = cw, 0, 0, lumaH @@ -106941,7 +103729,6 @@ local code = vlc(MOTION, MOTION_BITS) stride, sb, db, ph = 2 * cw, sp * cw, dp * cw, math.floor(lumaH / 2 ) cs, csb, cdb = 2 * chw, sp * chw, dp * chw end - -- luma local hx, hy = band(mvx, 1), band(mvy, 1) local sx = mbCol * 16 + math.floor((mvx - hx) / 2 ) local sy = rowY + math.floor((mvy - hy) / 2 @@ -107006,7 +103793,6 @@ end return (bwS or cur) end - -- the prediction of direction d (0 forward, 1 backward); avg: the second one of a bidirectional macroblock local function predictDir(d, avg) local o = d * 8 if not fieldPic then @@ -107050,7 +103836,6 @@ mcPart(r.y, r.cb, r.cr, parity, parity, mbRow * 16, 16, MV[o + 1], MV[o + 2], av end end - -- the prediction of a non-intra macroblock from the current motion state local function predictMb() if ptype == 2 then predictDir(0, false) @@ -107084,10 +103869,8 @@ mcPart(r.y, r.cb, r.cr, parity, parity, mbRow * 16, 16, MV[o + 1], MV[o + 2], av end end - -- Macroblocks no slice covers. ffmpeg's encoder skips the last macroblock of a row at the end of an MPEG-1 - -- slice (the next slice starts on the next row), and ffmpeg's decoder conceals it as a skipped macroblock; so do - -- we: P (and a damaged I) copies the reference with a zero vector, B repeats the prediction of the macroblock - -- before the gap. + -- macroblocks no slice covers: ffmpeg's encoder skips a row's last macroblock at an MPEG-1 slice end and its decoder + -- conceals it as skipped; so do we (P / damaged I: zero-vector copy, B: the prediction before the gap) local covered = 0 local gapFw, gapBw = false, false local GAP = table.create(16, 0) @@ -107144,9 +103927,7 @@ mcPart(r.y, r.cb, r.cr, parity, parity, mbRow * 16, 16, MV[o + 1], MV[o + 2], av FSEL[1], FSEL[2], FSEL[3], FSEL[4] = f1, f2, f3, f4 end - -- ------------------------------------------------------------------------------------------------ blocks - -- one 8x8 block b (0..3 luma, then Cb / Cr alternating): coefficients, dequantisation, IDCT into the picture. - -- False on a bitstream error. + -- block b: 0..3 luma, then Cb / Cr alternating local function decodeBlock(b) local n = 0 local q @@ -107211,7 +103992,6 @@ local onlyDc = true local qs = qscale local m2 = mpeg2 while true do - -- inline peek local bp = rshift(pos, 3) local w = bswap(readu32(data, bp)) local s = band(pos, 7) @@ -107294,7 +104074,7 @@ local onlyDc = true if m2 then parityOdd = bxor(parityOdd, band(m, 1)) end - -- saturate + -- saturation (13818-2 7.4.3) if m > 2047 then m = 2047 elseif m < -2048 then @@ -107312,7 +104092,6 @@ local onlyDc = true writei32(blk, 252, (v % 2 ~= 0 and((v - 1 ))or((v + 1)))) onlyDc = false end - -- reconstruction local dst, off, stride if luma then dst = curY @@ -107356,7 +104135,6 @@ local onlyDc = true return true end - -- ------------------------------------------------------------------------------------------------ macroblocks local function getQscale(code) if qScaleType == 1 then return readu8(NON_LINEAR, code) @@ -107434,7 +104212,6 @@ if qScaleType == 1 then end end - -- one macroblock (with the skipped ones before it). False on a bitstream error or the end of the slice data. local function decodeMacroblock(first, endBits) local inc = 0 local t = vlc(MBAI, MBAI_BITS) @@ -107636,7 +104413,6 @@ local inc = 0 end end - -- ------------------------------------------------------------------------------------------------ pictures -- the frame a picture completes becomes the newest reference (I / P) local function finishFrame(s) if s.ptype ~= 3 then @@ -107645,8 +104421,7 @@ local inc = 0 end end - -- The picture header at byte p (after 00 00 01 00) and its extensions, up to stop: the byte of the first slice - -- start code (-1: none) and the temporal reference, or nil when the picture is skipped + -- the picture header (after 00 00 01 00) and its extensions local function pictureHeader(p, stop) pos = p * 8 local tref = read(10) @@ -107699,7 +104474,6 @@ pos = p * 8 return at, tref end - -- the frame the picture decodes into (the pending one for a second field) and its references; false: skipped local function selectTarget(tref, tag) fieldPic = picStruct ~= 3 parity = picStruct == 2 and 1 or 0 @@ -107753,7 +104527,6 @@ fwS, bwS = refOld, refNew return true end - -- plane addressing of the current picture local function setAddressing() local target = cur curY, curCb, curCr = target.y, target.cb, target.cr @@ -107773,15 +104546,12 @@ curY, curCb, curCr = target.y, target.cb, target.cr mbIntra = false end - -- The picture whose header starts at byte p (after 00 00 01 00) and ends at byte stop: the decoded frame, or nil - -- (skipped, or the first field of a frame). local function decodePicture(p, stop, tag) local first, tref = pictureHeader(p, stop) if first == nil or not selectTarget(tref, tag) then return nil end setAddressing() - -- slices local at = first while at >= 0 do local code = readu8(data, at + 3) @@ -107826,7 +104596,6 @@ core.state = state if n <= 0 then return end - -- drop consumed bytes, keeping the scan state relative if readByte > 0 then local keep = dataLen - readByte if keep > 0 then @@ -107851,7 +104620,6 @@ core.state = state buffer.fill(data, dataLen, 0, PAD) end - -- the sequence header unit at byte at (up to stop): the header, then its extensions local function sequenceUnit(at, stop) local ok = sequenceHeader(at + 4) local s = findStart(at + 4, stop) @@ -107946,10 +104714,9 @@ return D end __FILES["codecs/video/Mpeg2/Tables"] = function() --!strict --- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. Those of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, --- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from --- mpeg1-luau e2e2898), lists 0-based like the JS arrays; the MPEG-2 ones (DC sizes up to 11, Table B-15, the --- non-linear quantiser scale, the alternate scan) are the tables of ISO/IEC 13818-2 annex B / section 7. +-- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. +-- MPEG-1: jsmpeg's (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), 0-based, via +-- mpeg1-luau e2e2898. MPEG-2 (DC sizes to 11, B-15, non-linear quantiser scale, alternate scan): ISO/IEC 13818-2 annex B / 7. local T = {} T.PICTURE_RATE = { [0] = 0.0, 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, @@ -108087,15 +104854,9 @@ end __FILES["codecs/video/Mpeg2/Vlc"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict -- codecs/video/Mpeg2/Vlc: lookup tables for the MPEG-1 / MPEG-2 variable-length codes, built at load time (Tables.luau). --- --- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds --- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level --- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF, --- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the --- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one --- more bit); DCT_FIRST keeps "1" as run 0 / level 1. DCT_B15 is MPEG-2's Table B-15 (intra_vlc_format = 1), DC_LUMA / --- DC_CHROMA cover sizes up to 11. Absorbed from mpeg1-luau e2e2898 (same author, built from jsmpeg's binary trees); --- the MPEG-2 tables are built from code lists. +-- Flat: indexed by the next K bits, len * 65536 + (value + 32768), len 0 = invalid. DCT: two-level (8 + 8 bits), +-- len * 65536 + run * 256 + level, ESC = 0xFFFF, EOB = 0xFFFE, or SUB + subtable for a long-code prefix. +-- DCT_NEXT: "10" = end_of_block, "11" = run 0 / level 1 (jsmpeg reads "1" + one bit); DCT_FIRST: "1" = run 0 / level 1. local T = __include("codecs/video/Mpeg2/Tables") local V = {} @@ -108140,7 +104901,6 @@ local function flat(tree) return flatLeaves(leaves(tree)) end --- { { code, length } } indexed from 1 -> leaves with value = index - 1 local function codeLeaves(codes) local out= {} for i, c in __iter(codes) do @@ -108153,7 +104913,6 @@ V.SUB = 0x1000000 V.ESC = 0xFFFF V.EOB = 0xFFFE --- two-level table: 256 first-level entries, then 256-entry subtables for prefixes of codes longer than 8 bits local function twoLevel(ls) local subs= {} local nsub = 0 @@ -108232,22 +104991,9 @@ return V end __FILES["codecs/video/Theora"] = function() local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict --- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska --- (V_THEORA). A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt): Header.luau --- (identification / comment / setup headers, dequantisation tables, Huffman trees) and Decoder.luau (native frames). --- Supports: every Theora I stream (bitstream 3.2.x and older 3.x): intra and inter frames, golden frames, 4MV --- macro blocks, all three pixel formats (4:2:0, 4:2:2, 4:4:4), picture regions smaller than the coded frame (odd sizes, --- offsets), empty packets (a repeated frame). Output is bit-exact with libtheora / ffmpeg (tests/codecs/theora.luau); --- yuv420p images average 4:2:2 / 4:4:4 chroma down (planes() keeps the native layout). --- Not supported: libtheora's optional post-processing (deblocking / deringing, off by default there too). --- --- local dec = Theora.new({ idHeader, commentHeader, setupHeader }) -- or the Xiph-laced Matroska CodecPrivate --- local kind = dec:decode(packet) -- "key" | "inter" | "dup" (empty packet / no coded blocks) | nil, Err --- local img = dec:image() -- a fresh yuv420p Types.Image of the picture region --- local y, u, v, cw, ch = dec:planes() -- native planes (chroma cw x ch), top-down --- Theora.granuleFrame(dec.info, granulepos) -- the 0-based frame index of an Ogg granule position --- --- Never throws: bad headers / packets come back as nil, Err (a corrupt frame still updates the picture). +-- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg and Matroska (V_THEORA). +-- A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt), bit-exact with libtheora / +-- ffmpeg; libtheora's optional post-processing is not supported. local Err = __include("core/Err") local Types = __include("Types") local VorbisComment = __include("codecs/audio/VorbisComment") @@ -108264,7 +105010,6 @@ local Theora = {} local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" } --- isHeader(buf, off?, len?) -> 1 / 2 / 3 for the identification / comment / setup header, else nil function Theora.isHeader(b, off, len) local o = off or 0 local n = len or (buffer.len(b) - o) @@ -108278,7 +105023,6 @@ local o = off or 0 return nil end --- splitConfig(config) -> the three header packets from Matroska's Xiph-laced CodecPrivate (or nil) function Theora.splitConfig(c) local n = buffer.len(c) if n < 3 or buffer.readu8(c, 0) ~= 2 then @@ -108310,7 +105054,6 @@ local n = buffer.len(c) return out end --- info(idHeader) -> Header.Info (frame / picture size, frame rate, granule shift, pixel format, ...) | nil, Err function Theora.info(h) local ok, info, err = pcall(Header.info, h, 0, buffer.len(h)) if not ok or not info then @@ -108319,7 +105062,6 @@ local ok, info, err = pcall(Header.info, h, 0, buffer.len(h)) return info, nil end --- comment(commentHeader) -> vendor, { "KEY=value" }, tags (lower-case keys) | nil, nil, nil, Err function Theora.comment(h) local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h)) if not ok or not vendor or not list then @@ -108328,7 +105070,6 @@ local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h)) return vendor, list, (VorbisComment.tags(list)), nil end --- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none) function Theora.granuleFrame(info, g) if g < 0 then return -1 @@ -108344,11 +105085,9 @@ if g < 0 then return f end --- ------------------------------------------------------------------------------------------------ decoder local Dec = {} Dec.__index = Dec --- new(headers, opts?) -> TheoraDecoder | nil, Err: headers = the three header packets, or the Xiph-laced config @@ -108410,7 +105149,6 @@ local list= nil }, Dec), nil end --- decode(data, off?, len?) -> "key" | "inter" | "dup" | nil, Err. Header packets are skipped (nil, nil). function Dec.decode(self, data, off, len) local o = off or 0 local n = len or (buffer.len(data) - o) @@ -108431,7 +105169,6 @@ local o = off or 0 return kind, nil end --- reset(): after a seek (the next frame should be a keyframe; until then inter frames predict from grey / old data) function Dec.reset(self) local st = self._st st.shown = st.prev @@ -108443,8 +105180,6 @@ local info = self.info return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight end --- planes() -> y, u, v (fresh top-down buffers of the picture region, chroma in the native layout), chroma width, --- chroma height function Dec.planes(self) local st = self._st local x0, y0, w, h = window(self) @@ -108456,7 +105191,6 @@ local st = self._st return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch end --- image() -> a fresh yuv420p Types.Image of the picture (4:2:2 / 4:4:4 chroma averaged down) function Dec.image(self) local y, u, v, cw, ch = self:planes() local w, h = self.width, self.height @@ -108480,9 +105214,6 @@ local y, u, v, cw, ch = self:planes() return img end --- ------------------------------------------------------------------------------------------------ registry --- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video entry "theora"): track.config --- holds the three headers (Xiph-laced, as Matroska's CodecPrivate); one picture per packet, empty packets repeat function Theora.newVideoDecoder(track, opts) if not track.config then return nil, Err.new(Err.CORRUPT, "Theora track without its headers") @@ -108525,22 +105256,10 @@ __FILES["codecs/video/Theora/Decoder"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7; native, never throws). A --- Luau port of libtheora 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, --- idct.c, fragment.c) with the bit-exact reconstruction of the specification: --- * frame header, coded super block / block flags (the run-length codes), macro block modes (the 8 mode --- alphabets), motion vectors (VLC / fixed length, last / prior vectors, 4MV with the chroma averages of each pixel --- format), per-block qi indices, DC / AC tokens with EOB runs across blocks, planes and coefficients; --- * DC prediction, dequantisation, the spec's 16-bit integer IDCT (DC-only blocks as libtheora: (dc * q + 15) >> 5), --- half-pel motion compensation (two-reference average toward zero), the loop filter, border extension for --- unrestricted motion vectors, golden / previous reference frames; --- * 4:2:0, 4:2:2 and 4:4:4; empty packets repeat the previous frame. --- Differences from libtheora: coefficients are kept per fragment (64 i16 each) instead of libtheora's token lists, --- the frame is reconstructed whole (no MCU pipelining, same result), there is no post-processing (libtheora's default), --- and intermediate IDCT sums are not wrapped to 16 bits (only out-of-range streams differ). --- --- Planes are stored in Theora's own orientation (row 0 is the bottom of the picture) with 16 (luma) / 8 (subsampled --- chroma) pixels of edge padding; output() turns the picture region into top-down planes. +-- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7). A Luau port of libtheora +-- 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, idct.c, fragment.c). +-- DC-only blocks as libtheora: (dc * q + 15) >> 5; IDCT sums are not wrapped to 16 bits (only out-of-range streams differ). +-- Planes are in Theora's orientation (row 0 = bottom) with 16 (luma) / 8 (subsampled chroma) pixels of edge padding. local Header = __include("codecs/video/Theora/Header") local readu8 = buffer.readu8 @@ -108680,7 +105399,6 @@ end local C1, C2, C3, C4, C5, C6, C7 = 64277, 60547, 54491, 46341, 36410, 25080, 12785 --- new(info, setup) -> State @@ -108906,7 +105624,6 @@ local pf = info.pixelFormat return st end --- ------------------------------------------------------------------------------------------------ reconstruction -- the 8-point IDCT of libtheora's idct8 (the spec's), on 8 values; returns the 8 outputs local function idct8(x0, x1, x2, x3, x4, x5, x6, x7) local t0 = math.floor((C4 * (x0 + x4)) / 65536 @@ -109046,7 +105763,6 @@ local function reconFrag(st, fi, qis, dstPlanes) st.last[fi] = 0 idctRows(blk, st.tmp) end - -- the prediction if ri == SELF then for y = 0, 7 do bfill(dst, pos + y * stride, 128, 8) @@ -109076,7 +105792,6 @@ local function reconFrag(st, fi, qis, dstPlanes) end end end - -- the residual if last ~= 0 then idctAdd(st.tmp, dst, pos, stride) elseif fv ~= 0 then @@ -109089,7 +105804,6 @@ local function reconFrag(st, fi, qis, dstPlanes) end end --- ------------------------------------------------------------------------------------------------ loop filter local function filterH(b, p, stride, bv) p =p- 2 for _ = 0, 7 do @@ -109259,14 +105973,10 @@ if fy == 0 then end end --- ------------------------------------------------------------------------------------------------ frame decode --- decode(st, data, off, len) -> kind ("key" | "inter" | "dup") | nil, message. The picture is then in --- st.refs[st.shown]. function D.decode(st, data, off, len) if len <= 0 then return "dup", nil end - -- a zero-padded copy: reads past the end give zero bits, every read site clamps pos to the end first local bb = buffer.create(len + 24) bcopy(bb, 0, data, off, len) local maxp = len * 8 @@ -109740,7 +106450,6 @@ if tok < 3 then dcPredict(st) - -- reconstruction into a free reference buffer local self = 1 while self == st.gold or self == st.prev do self =self+ 1 @@ -109773,9 +106482,6 @@ if tok < 3 then return intra and"key" or"inter", nil end --- ------------------------------------------------------------------------------------------------ output --- the picture region of the shown frame as top-down planes: plane(st, pli, x0, y0, w, h) copies a w x h window whose --- top-left corner is (x0, y0) counted from the top of the plane function D.plane(st, pli, x0, y0, w, h) local src = st.refs[st.shown][pli + 1] local stride, origin, ph = st.stride[pli + 1], st.origin[pli + 1], st.ph[pli + 1] @@ -109787,8 +106493,7 @@ local src = st.refs[st.shown][pli + 1] return out end --- downsample(src, cw, ch, hdec, dst, off, ow, oh): 4:2:2 (hdec 1: rows averaged in pairs) or 4:4:4 (hdec 0: 2x2 --- averages) chroma of cw x ch into ow x oh 4:2:0 chroma at dst[off] +-- 4:2:2 (rows averaged in pairs) or 4:4:4 (2x2 averages) chroma down to 4:2:0 function D.downsample(src, cw, ch, hdec, dst, off, ow, oh) for r = 0, oh - 1 do local r0 = math.min(2 * r, ch - 1) @@ -109813,13 +106518,9 @@ return D end __FILES["codecs/video/Theora/Header"] = function() local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict --- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6): identification (frame / --- picture size and offsets, frame rate, aspect, colour space, pixel format, keyframe granule shift), comment (Vorbis --- comment layout) and setup (loop-filter limits, quantisation parameters, the 80 DCT token Huffman trees), and the --- tables derived from them: the dequantisation matrices of every qi / plane / intra-inter and the collapsed Huffman --- lookup tables the frame decoder walks. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause: --- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c (the tree unpacking; --- the table layout here is simpler). Never throws: bad headers return nil, message. +-- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6) and the dequantisation and +-- Huffman lookup tables derived from them. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause, +-- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c. local Bits = __include("core/Bits") local H = {} @@ -109867,8 +106568,7 @@ local n = 0 return n end --- ------------------------------------------------------------------------------------------------ identification --- info(buf, off, len) -> Info | nil, message: the packet starting with 0x80 "theora" +-- identification header: 0x80 "theora" function H.info(b, off, len) if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then return nil, "not a Theora identification header" @@ -109913,8 +106613,7 @@ if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) return info, nil end --- ------------------------------------------------------------------------------------------------ comment --- comment(buf, off, len) -> vendor, { "KEY=value" } | nil, message: the packet starting with 0x81 "theora" +-- comment header: 0x81 "theora" function H.comment(b, off, len) if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then return nil, nil, "not a Theora comment header" @@ -109953,7 +106652,6 @@ if p + 4 > e then return vendor, list, nil end --- ------------------------------------------------------------------------------------------------ Huffman trees -- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in -- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf -- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits). @@ -109980,7 +106678,6 @@ local kid0, kid1, tok = { 0 }, { 0 }, { -1 } return nil, nil, nil end local t = br:read(5) - -- insert the leaf local n = 1 for d = 1, len do local k = (math.floor(code / 2 ^ (32 - d))) % 2 @@ -110061,11 +106758,10 @@ local nb = math.clamp(height(n), 1, MAXBITS) return node(1) end --- ------------------------------------------------------------------------------------------------ setup local DC_MIN = { 16, 32 } local AC_MIN = { 8, 16 } --- setup(buf, off, len) -> Setup | nil, message: the packet starting with 0x82 "theora" +-- setup header: 0x82 "theora" function H.setup(b, off, len) if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then return nil, "not a Theora setup header" @@ -110186,30 +106882,13 @@ end __FILES["codecs/video/Video"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in rosetta. --- --- Registry: our codec ids ("vp8", "mjpeg", "mpeg1", "h264", "rawvideo", ...) with the containers' names for them --- (AVI / MOV FourCCs, Matroska CodecIDs, MPEG stream types) and, for the codecs we can decode, a constructor of a --- Types.VideoCodecDecoder (packets in, pictures out). Containers map their own ids through Video.fromFourcc / --- Video.fromMatroska so a track's codec is known even without a decoder (remuxing still works). Another codec plugs --- in with one line in BUILTIN (static: Roblox has no dynamic require) or at run time with Video.register(entry). --- --- local Video = require("rosetta.codecs.video.Video") --- Video.fromFourcc("MJPG") --> "mjpeg" Video.fromMatroska("V_VP8") --> "vp8" --- local dec = Video.decoder(track, opts) -- a VideoCodecDecoder | nil, Err (UNSUPPORTED: no decoder) --- local v = Video.open(demuxer, opts) -- a Types.VideoDecoder over a Types.Demuxer (formats' open()) --- local v = Video.fromFrames(images, delays) -- a frames-backed VideoDecoder (animated GIF / APNG / WebP) --- --- Never throws: bad data / missing codecs come back as nil, Err. local Err = __include("core/Err") local Types = __include("Types") local Yuv = __include("codecs/image/Yuv") local Video = {} --- ------------------------------------------------------------------------------------------------ simple decoders --- one picture per packet, no reordering: decodeOne(data, packet) -> Image | nil, Err (nil, nil: a packet with no --- picture to show, such as a hidden VP8 altref frame) - +-- decodeOne -> nil, nil: a packet with no picture to show (a hidden VP8 altref frame) @@ -110399,8 +107078,7 @@ local img, err = dec:decodeFrame(data, 0, buffer.len(data), o) end), nil end --- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout --- allows, else rgba8 +-- Motion JPEG: yuv420p straight from the planes (full range) when the layout allows, else rgba8 local function mjpegDecoder(_track, opts) local Jpeg = __include("codecs/image/Jpeg") local o= { yuv = true, maxPixels = opts and opts.maxPixels } @@ -110426,20 +107104,16 @@ local Jpeg = __include("codecs/image/Jpeg") return Jpeg.encode(src, { quality = opts and opts.quality or 90 }) end --- MPEG-1 / MPEG-2 video (codecs/video/Mpeg2): pictures in decode order, reordered for display local function mpeg2Decoder(track, opts) local Mpeg2 = __include("codecs/video/Mpeg2") return Mpeg2.newVideoDecoder(track, opts) end --- H.264 / AVC (codecs/video/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264); --- pictures in display order with the pts of their packet local function h264Decoder(track, opts) local H264 = __include("codecs/video/H264") return H264.newVideoDecoder(track, opts) end --- H.263 / Sorenson Spark (codecs/video/H263): one picture per packet, no reordering local function h263Decoder(track, opts) local H263 = __include("codecs/video/H263") local dec = H263.new({ flv = track.codec == "flv1", maxPixels = opts and opts.maxPixels }) @@ -110450,22 +107124,18 @@ return dec:image(data) end), nil end --- Theora (codecs/video/Theora): track.config = the three headers, Xiph-laced (Matroska's CodecPrivate; video/ogv --- builds the same); one picture per packet, empty packets repeat the previous one local function theoraDecoder(track, opts) local Theora = __include("codecs/video/Theora") return Theora.newVideoDecoder(track, opts) end --- FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC, Smacker (codecs/video/Legacy) local function legacyDecoder(id) return function(track, opts) return __include("codecs/video/Legacy").newDecoder(id, track, opts) end end --- ------------------------------------------------------------------------------------------------ registry --- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. +-- FourCCs compare case-sensitively first, then upper-cased local BUILTIN= { { id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder }, { id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" }, new = mjpegDecoder, encode = mjpegEncode }, @@ -110485,7 +107155,6 @@ local BUILTIN= { { id = "flashsv", name = "Flash Screen Video", fourcc = { "FSV1" } }, { id = "flashsv2", name = "Flash Screen Video 2" }, { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, - -- legacy inter-frame codecs (codecs/video/Legacy; rgba8 pictures, palettes from track.palette) { id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") }, { id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") }, { id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") }, @@ -110498,7 +107167,6 @@ local byId= {} local byFourcc= {} local byMatroska= {} --- register(entry): adds or replaces a codec (by id); its fourcc / matroska names map to it function Video.register(entry) if type(entry) ~= "table" or type(entry.id) ~= "string" then return false, Err.new(Err.ARG, "register: needs an entry with an id") @@ -110520,31 +107188,25 @@ for _, e in __iter(BUILTIN) do Video.register(e) end --- the registry (read only by convention): id -> Entry Video.codecs = byId --- fromFourcc(fourcc) -> codec id | nil function Video.fromFourcc(fcc) return byFourcc[fcc] or byFourcc[string.upper(fcc)] or byFourcc[string.lower(fcc)] end --- fromMatroska(codecId) -> codec id | nil (V_MPEG4/ISO/AVC -> h264, ...) function Video.fromMatroska(id) return byMatroska[id] end --- names(codecId) -> the Entry (FourCCs / Matroska ids for writers) | nil function Video.entry(id) return byId[id] end --- canDecode(codecId) -> boolean function Video.canDecode(id) local e = byId[id] return e ~= nil and e.new ~= nil end --- decoder(track, opts?) -> a VideoCodecDecoder for the track's codec | nil, Err (UNSUPPORTED when none is registered) function Video.decoder(track, opts) local e = byId[track.codec] if not e or not e.new then @@ -110557,19 +107219,12 @@ local e = byId[track.codec] return dec, err end --- ------------------------------------------------------------------------------------------------ VideoDecoder local function toRGBA(_self, f) local img = (type(f) == "table" and f.image and{f.image }or{f })[1] local out = Yuv.imageToRgba(img) return out or img end --- open(demuxer, opts?) -> a Types.VideoDecoder over the demuxer's video track (and audio track through --- opts.openAudio). A video track without a decoder still opens: nextFrame returns nil, Err.UNSUPPORTED, and --- the demuxer (remuxing) and audio work. - - - @@ -110621,7 +107276,6 @@ local o= opts or {} if v.frames == 0 and v.frameRate > 0 and v.duration > 0 then v.frames = math.floor(v.duration * v.frameRate + 0.5) end - -- audio if o.audio ~= false then local at = demuxer:track("audio") if at then @@ -110655,8 +107309,7 @@ while true do local t = (pts or 0) / scale - start if t + 1e-9 >= skipUntil then if index < 0 then - -- the first frame after a seek: its position in the stream (constant-rate: round(pts * fps); - -- without a frame rate, counted from the seek) + -- after a seek: constant-rate index = round(pts * fps), else counted from the seek index = (v.frameRate > 0 and{(math.max(0, math.floor(t * v.frameRate + 0.5)) )}or{0 })[1] end index =index+ 1 @@ -110717,9 +107370,6 @@ while true do return v, nil end --- ------------------------------------------------------------------------------------------------ frames-backed --- fromFrames(images, delays, opts?) -> a VideoDecoder over full-canvas images (animated GIF / APNG / WebP after --- coalescing): delays[i] seconds (a number = every frame). opts.format / opts.loops / opts.meta are recorded. function Video.fromFrames(images, delays, opts) if type(images) ~= "table" or #images == 0 or type(images[1]) ~= "table" then return nil, Err.new(Err.ARG, "fromFrames: needs a list of Images") @@ -110788,18 +107438,8 @@ return Video end __FILES["codecs/video/Video/Source"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict --- codecs/video/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given: --- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either --- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM, --- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw --- yuv420p frames, PCM audio from the audio Decoder). New in rosetta. --- --- local streams, err = Source.streams(value, opts, { --- video = { copy = { vp8 = true }, encode = "mjpeg" }, -- copy: codec ids the container takes ("*" = any) --- audio = { copy = { opus = true, vorbis = true }, pcm = true }, --- }) --- -- streams[i] = { kind, codec, copied, width, height, frameRate, sampleRate, channels, bitsPerSample, config, --- -- track, packets = { { pts, duration (seconds), keyframe, data } } } +-- codecs/video/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from a VideoDecoder +-- or a Demuxer: each stream is copied (remuxed) or produced (decoded frames re-encoded, PCM audio). local Err = __include("core/Err") local Types = __include("Types") local Yuv = __include("codecs/image/Yuv") @@ -110830,7 +107470,6 @@ local function allows(set, codec) return set ~= nil and (set[codec] == true or set["*"] == true) end --- the packets of a source track, times in seconds local function copyPackets(dmx, track) local out = {} local scale = (track.timescale and track.timescale > 0 and{track.timescale }or{1 @@ -110861,8 +107500,6 @@ return { } end --- encodeFrames(video, codec, opts) -> the video's frames encoded with the registry's encoder for codec ("rawvideo": --- yuv420p planes) local function encodeFrames(v, codec, opts) local encode= nil if codec ~= "rawvideo" then @@ -110929,7 +107566,6 @@ if codec == "rawvideo" then } , nil end --- pcmFrom(decoder, opts) -> an s16le stream from an audio Decoder (chunks of opts.audioChunk frames, default 4096) local function pcmFrom(dec, opts) local ch, rate = dec.channels, dec.sampleRate if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then @@ -110973,7 +107609,6 @@ local ch, rate = dec.channels, dec.sampleRate } , nil end --- streams(value, opts, want) -> { Stream } | nil, Err function Source.streams(value, opts, want) local o = opts or {} if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then @@ -110981,7 +107616,6 @@ local o = opts or {} end local dmx = (value.kind == "demuxer" and{value }or{value.demuxer })[1] local out= {} - -- video local vt= (value.kind == "video" and{value.track }or{(dmx and dmx:track("video")) })[1] local wv = want.video if wv and o.video ~= false then @@ -110997,7 +107631,6 @@ local o = opts or {} return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (wv.encode and"" or" (this container cannot take it and it cannot be re-encoded)")) end end - -- audio local wa = want.audio if wa and o.audio ~= false then local at= dmx and dmx:track("audio") @@ -111021,7 +107654,7 @@ local o = opts or {} return out, nil end --- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond +-- integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond function Source.rational(fps) if fps ~= fps or fps <= 0 then return 25, 1 @@ -111036,9 +107669,6 @@ if fps ~= fps or fps <= 0 then return math.floor(fps * 1000 + 0.5), 1000 end --- constantRate(stream, maxFps?) -> num, den, { OutPacket }: a video stream at a constant frame rate for the --- containers that have one (AVI, Y4M): the rate of the shortest frame (at most maxFps, default 100), each packet --- repeated to fill its duration (a GIF's 100 / 50 / 200 ms frames become 2, 1 and 4 frames at 20 fps) function Source.constantRate(s, maxFps) local fd = math.huge for _, p in __iter(s.packets) do @@ -111066,8 +107696,6 @@ local fd = math.huge return num, den, out end --- interleave(streams) -> { { stream index, packet } } merged by decode time (dts, else pts); each stream keeps its --- own order function Source.interleave(streams) local order = {} local pos = table.create(#streams, 1) diff --git a/build/rosetta.lua.linemap.json b/build/rosetta.lua.linemap.json index e10c8ed..e8c3926 100644 --- a/build/rosetta.lua.linemap.json +++ b/build/rosetta.lua.linemap.json @@ -72,468 +72,468 @@ [22609, "src/Rosetta/cad/step/Parse.luau"], [23184, "src/Rosetta/cad/step/Write.luau"], [23438, "src/Rosetta/codecs/audio/Aac/init.luau"], -[23776, "src/Rosetta/codecs/audio/Aac/Decode.luau"], -[24681, "src/Rosetta/codecs/audio/Aac/Tables.luau"], -[25017, "src/Rosetta/codecs/audio/Ac3/init.luau"], -[25191, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], -[26109, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], -[26213, "src/Rosetta/codecs/audio/Adpcm/init.luau"], -[27033, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], -[27363, "src/Rosetta/codecs/audio/Alac/init.luau"], -[27616, "src/Rosetta/codecs/audio/Alac/Decode.luau"], -[28045, "src/Rosetta/codecs/audio/Alac/Encode.luau"], -[28474, "src/Rosetta/codecs/audio/Ape/init.luau"], -[28705, "src/Rosetta/codecs/audio/Ape/Decode.luau"], -[29485, "src/Rosetta/codecs/audio/ApeTag.luau"], -[29597, "src/Rosetta/codecs/audio/Flac/init.luau"], -[29610, "src/Rosetta/codecs/audio/Flac/Encode.luau"], -[30600, "src/Rosetta/codecs/audio/Flac/Frame.luau"], -[31212, "src/Rosetta/codecs/audio/Hively/init.luau"], -[31423, "src/Rosetta/codecs/audio/Hively/Load.luau"], -[31674, "src/Rosetta/codecs/audio/Hively/Player.luau"], -[32646, "src/Rosetta/codecs/audio/Hively/Tables.luau"], -[32869, "src/Rosetta/codecs/audio/Mdct/init.luau"], -[33074, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], -[33287, "src/Rosetta/codecs/audio/MidiRender.luau"], -[33648, "src/Rosetta/codecs/audio/Mpa/init.luau"], -[33663, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], -[33728, "src/Rosetta/codecs/audio/Mpa/Core.luau"], -[35367, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], -[35661, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], -[36057, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], -[36724, "src/Rosetta/codecs/audio/Mpa/Header.luau"], -[36866, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], -[37092, "src/Rosetta/codecs/audio/Musepack/init.luau"], -[37453, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[38354, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[38735, "src/Rosetta/codecs/audio/Opus/init.luau"], -[38752, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[40618, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[41698, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[41758, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[42226, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[42574, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[42811, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[44883, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[45257, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[45553, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[45863, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[46162, "src/Rosetta/codecs/audio/Resample/init.luau"], -[46541, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[46612, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[46763, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[47288, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[48093, "src/Rosetta/codecs/audio/Stream.luau"], -[48276, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[48830, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[49123, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[49298, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[49432, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[51460, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[51588, "src/Rosetta/codecs/audio/Tta/init.luau"], -[51716, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[51977, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[51992, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[52388, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[52976, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[53407, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[53446, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[53510, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[53750, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[55235, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[55302, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[55405, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[56403, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[57271, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[57329, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[57859, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[58217, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[58651, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[59107, "src/Rosetta/codecs/compress/Explode.luau"], -[59313, "src/Rosetta/codecs/compress/Lz4.luau"], -[59606, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[60234, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[60803, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[60842, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[61336, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[61515, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[61806, "src/Rosetta/codecs/compress/Lzx.luau"], -[62257, "src/Rosetta/codecs/compress/PackBits.luau"], -[62354, "src/Rosetta/codecs/compress/Quantum.luau"], -[62607, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[62928, "src/Rosetta/codecs/compress/Xxh32.luau"], -[63002, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[63072, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[64054, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[64211, "src/Rosetta/codecs/entropy/Huffman.luau"], -[64519, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[64534, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[64751, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[65005, "src/Rosetta/codecs/font/Bitmap.luau"], -[65227, "src/Rosetta/codecs/font/Cff/init.luau"], -[65886, "src/Rosetta/codecs/font/GlyphNames.luau"], -[66042, "src/Rosetta/codecs/font/TrueType/init.luau"], -[66382, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[66787, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[67308, "src/Rosetta/codecs/image/Bcn/init.luau"], -[67431, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[67931, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[68375, "src/Rosetta/codecs/image/Blend.luau"], -[68776, "src/Rosetta/codecs/image/Dct/init.luau"], -[69174, "src/Rosetta/codecs/image/Etc.luau"], -[69491, "src/Rosetta/codecs/image/Half.luau"], -[69567, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[69959, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[70375, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[70625, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[71398, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[72299, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[72762, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[72841, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[72919, "src/Rosetta/codecs/image/Pixels.luau"], -[73204, "src/Rosetta/codecs/image/Quantize/init.luau"], -[73689, "src/Rosetta/codecs/image/Raster.luau"], -[74435, "src/Rosetta/codecs/image/Texel.luau"], -[74835, "src/Rosetta/codecs/image/Texture.luau"], -[74999, "src/Rosetta/codecs/image/Vp8/init.luau"], -[75159, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[77148, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[77424, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[77675, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[77800, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[77922, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[78797, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[79775, "src/Rosetta/codecs/image/Yuv.luau"], -[80065, "src/Rosetta/codecs/model/Draco/init.luau"], -[80420, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[80901, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[82107, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[82265, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[82630, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[83609, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[84091, "src/Rosetta/codecs/model/Mat4.luau"], -[84375, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[84920, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[85509, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[85592, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[85702, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[85924, "src/Rosetta/codecs/model/Polygon.luau"], -[86174, "src/Rosetta/codecs/model/Rbx/init.luau"], -[86457, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[87233, "src/Rosetta/codecs/model/Rig.luau"], -[87509, "src/Rosetta/codecs/model/Sampler.luau"], -[87684, "src/Rosetta/codecs/model/Vrml/init.luau"], -[87846, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[88438, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[88608, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[89380, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[89918, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[90670, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[90910, "src/Rosetta/codecs/text/Json/init.luau"], -[91206, "src/Rosetta/codecs/text/Json/Decode.luau"], -[91633, "src/Rosetta/codecs/text/Json/Encode.luau"], -[91942, "src/Rosetta/codecs/text/Nbt/init.luau"], -[92324, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[93024, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[93675, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[93933, "src/Rosetta/codecs/text/Text/init.luau"], -[94029, "src/Rosetta/codecs/text/Url/init.luau"], -[94247, "src/Rosetta/codecs/text/Xml/init.luau"], -[94689, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[95454, "src/Rosetta/codecs/video/Dsp.luau"], -[96199, "src/Rosetta/codecs/video/H263/init.luau"], -[96377, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[97273, "src/Rosetta/codecs/video/H263/Tables.luau"], -[97481, "src/Rosetta/codecs/video/H264/init.luau"], -[97898, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[98193, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[99338, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[100117, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[100383, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[101409, "src/Rosetta/codecs/video/H264/Inter.luau"], -[101677, "src/Rosetta/codecs/video/H264/Intra.luau"], -[102089, "src/Rosetta/codecs/video/H264/Mb.luau"], -[103022, "src/Rosetta/codecs/video/H264/Params.luau"], -[103477, "src/Rosetta/codecs/video/H264/Slice.luau"], -[103730, "src/Rosetta/codecs/video/H264/Tables.luau"], -[103774, "src/Rosetta/codecs/video/H264/Transform.luau"], -[103950, "src/Rosetta/codecs/video/Legacy/init.luau"], -[104166, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[104471, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[104845, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[104968, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[105085, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[105363, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[105770, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[105955, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[105968, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[106384, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[107948, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[108088, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[108234, "src/Rosetta/codecs/video/Theora/init.luau"], -[108525, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[109815, "src/Rosetta/codecs/video/Theora/Header.luau"], -[110187, "src/Rosetta/codecs/video/Video/init.luau"], -[110790, "src/Rosetta/codecs/video/Video/Source.luau"], -[111097, "src/Rosetta/containers/Archive.luau"], -[111390, "src/Rosetta/containers/AudioWrap.luau"], -[111911, "src/Rosetta/containers/Avi/init.luau"], -[112483, "src/Rosetta/containers/Chunks.luau"], -[112627, "src/Rosetta/containers/Cpio.luau"], -[113069, "src/Rosetta/containers/Demux.luau"], -[113367, "src/Rosetta/containers/Ebml/init.luau"], -[113704, "src/Rosetta/containers/Fat.luau"], -[114413, "src/Rosetta/containers/Iso9660.luau"], -[114940, "src/Rosetta/containers/IsoBmff/init.luau"], -[115130, "src/Rosetta/containers/IsoBmff/Box.luau"], -[115325, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[116189, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[116719, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[117240, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[117362, "src/Rosetta/containers/MacFile.luau"], -[117522, "src/Rosetta/containers/MpegEs.luau"], -[117697, "src/Rosetta/containers/MpegPs/init.luau"], -[117923, "src/Rosetta/containers/MpegTs/init.luau"], -[118740, "src/Rosetta/containers/Ogg/init.luau"], -[119198, "src/Rosetta/containers/Ogg/Mux.luau"], -[119408, "src/Rosetta/containers/Ogg/Page.luau"], -[119585, "src/Rosetta/containers/Riff/init.luau"], -[119930, "src/Rosetta/containers/Tar.luau"], -[120358, "src/Rosetta/containers/Zip/init.luau"], -[121018, "src/Rosetta/core/Adler32.luau"], -[121070, "src/Rosetta/core/Base64.luau"], -[121239, "src/Rosetta/core/Bits.luau"], -[121551, "src/Rosetta/core/Bytes.luau"], -[122120, "src/Rosetta/core/Crc16.luau"], -[122174, "src/Rosetta/core/Crc32.luau"], -[122297, "src/Rosetta/core/Err.luau"], -[122393, "src/Rosetta/core/Input.luau"], -[122477, "src/Rosetta/core/Md5.luau"], -[122643, "src/Rosetta/core/Sniff.luau"], -[122681, "src/Rosetta/data/cbor/init.luau"], -[122783, "src/Rosetta/data/cbor/Codec.luau"], -[123360, "src/Rosetta/data/csv/init.luau"], -[123677, "src/Rosetta/data/ini/init.luau"], -[123928, "src/Rosetta/data/json/init.luau"], -[124021, "src/Rosetta/data/msgpack/init.luau"], -[124113, "src/Rosetta/data/msgpack/Codec.luau"], -[124561, "src/Rosetta/data/nbt/init.luau"], -[124623, "src/Rosetta/data/plist/init.luau"], -[124931, "src/Rosetta/data/plist/Binary.luau"], -[125204, "src/Rosetta/data/snbt/init.luau"], -[125269, "src/Rosetta/data/toml/init.luau"], -[125341, "src/Rosetta/data/toml/Decode.luau"], -[125978, "src/Rosetta/data/toml/Encode.luau"], -[126194, "src/Rosetta/data/xml/init.luau"], -[126251, "src/Rosetta/data/yaml/init.luau"], -[126330, "src/Rosetta/data/yaml/Emit.luau"], -[126631, "src/Rosetta/data/yaml/Parse.luau"], -[127955, "src/Rosetta/font/bdf/init.luau"], -[128252, "src/Rosetta/font/bmfont/init.luau"], -[128694, "src/Rosetta/font/bmfont/Parse.luau"], -[129153, "src/Rosetta/font/eot/init.luau"], -[129388, "src/Rosetta/font/fon/init.luau"], -[129678, "src/Rosetta/font/hershey/init.luau"], -[129880, "src/Rosetta/font/pcf/init.luau"], -[130172, "src/Rosetta/font/psf/init.luau"], -[130502, "src/Rosetta/font/ttf/init.luau"], -[130556, "src/Rosetta/font/type1/init.luau"], -[130926, "src/Rosetta/font/type1/Charstring.luau"], -[131211, "src/Rosetta/font/woff/init.luau"], -[131345, "src/Rosetta/font/woff2/init.luau"], -[131404, "src/Rosetta/font/woff2/Rebuild.luau"], -[131954, "src/Rosetta/host/init.luau"], -[132006, "src/Rosetta/host/Love.luau"], -[132157, "src/Rosetta/host/LuaJIT.luau"], -[132207, "src/Rosetta/host/Luau.luau"], -[132230, "src/Rosetta/host/Roblox.luau"], -[132621, "src/Rosetta/image/ani/init.luau"], -[132806, "src/Rosetta/image/blp/init.luau"], -[133074, "src/Rosetta/image/bmp/init.luau"], -[133505, "src/Rosetta/image/dds/init.luau"], -[134004, "src/Rosetta/image/exr/init.luau"], -[134788, "src/Rosetta/image/exr/Codec.luau"], -[134907, "src/Rosetta/image/exr/Piz.luau"], -[135276, "src/Rosetta/image/gif/init.luau"], -[135812, "src/Rosetta/image/gif/Decode.luau"], -[135882, "src/Rosetta/image/hdr/init.luau"], -[136118, "src/Rosetta/image/hdr/Codec.luau"], -[136339, "src/Rosetta/image/icns/init.luau"], -[136678, "src/Rosetta/image/ico/init.luau"], -[136962, "src/Rosetta/image/ico/Dib.luau"], -[137063, "src/Rosetta/image/ilbm/init.luau"], -[137389, "src/Rosetta/image/jpeg/init.luau"], -[137540, "src/Rosetta/image/ktx/init.luau"], -[138214, "src/Rosetta/image/pcx/init.luau"], -[138482, "src/Rosetta/image/png/init.luau"], -[139080, "src/Rosetta/image/png/Apng.luau"], -[139164, "src/Rosetta/image/png/Decode.luau"], -[139419, "src/Rosetta/image/png/Encode.luau"], -[139583, "src/Rosetta/image/pnm/init.luau"], -[139969, "src/Rosetta/image/pnm/Codec.luau"], -[140260, "src/Rosetta/image/qoi/init.luau"], -[140384, "src/Rosetta/image/qoi/Codec.luau"], -[140538, "src/Rosetta/image/sgi/init.luau"], -[140826, "src/Rosetta/image/sunras/init.luau"], -[141075, "src/Rosetta/image/tga/init.luau"], -[141353, "src/Rosetta/image/tga/Codec.luau"], -[141512, "src/Rosetta/image/tiff/init.luau"], -[142356, "src/Rosetta/image/tiff/Pixels.luau"], -[142757, "src/Rosetta/image/tim/init.luau"], -[143006, "src/Rosetta/image/vtf/init.luau"], -[143253, "src/Rosetta/image/webp/init.luau"], -[143882, "src/Rosetta/image/webp/Alpha.luau"], -[143960, "src/Rosetta/image/webp/Anim.luau"], -[144124, "src/Rosetta/image/xbm/init.luau"], -[144288, "src/Rosetta/image/xpm/init.luau"], -[144562, "src/Rosetta/image/xpm/Names.luau"], -[144621, "src/Rosetta/layered/aseprite/init.luau"], -[145377, "src/Rosetta/layered/ora/init.luau"], -[145672, "src/Rosetta/layered/psd/init.luau"], -[146417, "src/Rosetta/layered/psd/Channels.luau"], -[146788, "src/Rosetta/model/3ds/init.luau"], -[146890, "src/Rosetta/model/3ds/Build.luau"], -[147555, "src/Rosetta/model/3ds/Read.luau"], -[148063, "src/Rosetta/model/3ds/Write.luau"], -[148892, "src/Rosetta/model/3mf/init.luau"], -[148989, "src/Rosetta/model/3mf/Read.luau"], -[149589, "src/Rosetta/model/3mf/Write.luau"], -[150008, "src/Rosetta/model/b3d/init.luau"], -[150078, "src/Rosetta/model/b3d/Read.luau"], -[150656, "src/Rosetta/model/bsp/init.luau"], -[150808, "src/Rosetta/model/bsp/Brush.luau"], -[151101, "src/Rosetta/model/bsp/Quake3.luau"], -[151364, "src/Rosetta/model/dae/init.luau"], -[151572, "src/Rosetta/model/dae/Math.luau"], -[151620, "src/Rosetta/model/dae/Read.luau"], -[153502, "src/Rosetta/model/dae/Write.luau"], -[153880, "src/Rosetta/model/fbx/init.luau"], -[154048, "src/Rosetta/model/fbx/Ascii.luau"], -[154324, "src/Rosetta/model/fbx/Binary.luau"], -[154787, "src/Rosetta/model/fbx/Read.luau"], -[156173, "src/Rosetta/model/fbx/Write.luau"], -[157171, "src/Rosetta/model/fbx/Xform.luau"], -[157215, "src/Rosetta/model/gltf/init.luau"], -[157469, "src/Rosetta/model/gltf/Pack.luau"], -[157545, "src/Rosetta/model/gltf/Read.luau"], -[158294, "src/Rosetta/model/gltf/Write.luau"], -[158992, "src/Rosetta/model/iqm/init.luau"], -[159076, "src/Rosetta/model/iqm/Read.luau"], -[159437, "src/Rosetta/model/iqm/Write.luau"], -[160145, "src/Rosetta/model/ldraw/init.luau"], -[160252, "src/Rosetta/model/ldraw/Colors.luau"], -[160573, "src/Rosetta/model/ldraw/Read.luau"], -[161155, "src/Rosetta/model/lwo/init.luau"], -[161243, "src/Rosetta/model/lwo/Build.luau"], -[161714, "src/Rosetta/model/lwo/Parse.luau"], -[162267, "src/Rosetta/model/mca/init.luau"], -[162624, "src/Rosetta/model/mca/Chunk.luau"], -[162761, "src/Rosetta/model/mca/Lz4Block.luau"], -[162833, "src/Rosetta/model/md2/init.luau"], -[163044, "src/Rosetta/model/md3/init.luau"], -[163280, "src/Rosetta/model/md5/init.luau"], -[163365, "src/Rosetta/model/md5/Read.luau"], -[163807, "src/Rosetta/model/mdl/init.luau"], -[163893, "src/Rosetta/model/mdl/HalfLife.luau"], -[164235, "src/Rosetta/model/mdl/Quake.luau"], -[164459, "src/Rosetta/model/ms3d/init.luau"], -[164543, "src/Rosetta/model/ms3d/Read.luau"], -[165009, "src/Rosetta/model/ms3d/Write.luau"], -[165497, "src/Rosetta/model/obj/init.luau"], -[166262, "src/Rosetta/model/obj/Mtl.luau"], -[166558, "src/Rosetta/model/off/init.luau"], -[167040, "src/Rosetta/model/ply/init.luau"], -[168190, "src/Rosetta/model/ply/Binary.luau"], -[168404, "src/Rosetta/model/pmx/init.luau"], -[168483, "src/Rosetta/model/pmx/Build.luau"], -[168792, "src/Rosetta/model/pmx/Pmd.luau"], -[169133, "src/Rosetta/model/pmx/Read.luau"], -[169546, "src/Rosetta/model/qb/init.luau"], -[169949, "src/Rosetta/model/rbxm/init.luau"], -[170556, "src/Rosetta/model/rbxmx/init.luau"], -[171225, "src/Rosetta/model/robloxmesh/init.luau"], -[171911, "src/Rosetta/model/robloxmesh/Parse.luau"], -[172373, "src/Rosetta/model/robloxmesh/Write.luau"], -[172484, "src/Rosetta/model/schematic/init.luau"], -[172820, "src/Rosetta/model/schematic/Common.luau"], -[172950, "src/Rosetta/model/schematic/Litematic.luau"], -[173167, "src/Rosetta/model/schematic/Mcedit.luau"], -[173418, "src/Rosetta/model/schematic/Sponge.luau"], -[173551, "src/Rosetta/model/smd/init.luau"], -[173622, "src/Rosetta/model/smd/Read.luau"], -[173899, "src/Rosetta/model/smd/Write.luau"], -[174151, "src/Rosetta/model/stl/init.luau"], -[174620, "src/Rosetta/model/stl/Decode.luau"], -[174699, "src/Rosetta/model/usda/init.luau"], -[174922, "src/Rosetta/model/usda/Build.luau"], -[176239, "src/Rosetta/model/usda/Parse.luau"], -[177061, "src/Rosetta/model/usda/Write.luau"], -[177903, "src/Rosetta/model/vox/init.luau"], -[178808, "src/Rosetta/model/vox/Grid.luau"], -[178871, "src/Rosetta/model/vrml/init.luau"], -[178950, "src/Rosetta/model/x/init.luau"], -[179094, "src/Rosetta/model/x/Build.luau"], -[179670, "src/Rosetta/model/x/Parse.luau"], -[179978, "src/Rosetta/model/x3d/init.luau"], -[180065, "src/Rosetta/music/669/init.luau"], -[180276, "src/Rosetta/music/ahx/init.luau"], -[180331, "src/Rosetta/music/far/init.luau"], -[180565, "src/Rosetta/music/hmp/init.luau"], -[180840, "src/Rosetta/music/hvl/init.luau"], -[180895, "src/Rosetta/music/it/init.luau"], -[181324, "src/Rosetta/music/it/Itsex.luau"], -[181446, "src/Rosetta/music/med/init.luau"], -[182109, "src/Rosetta/music/midi/init.luau"], -[182265, "src/Rosetta/music/midi/Smf.luau"], -[182685, "src/Rosetta/music/mod/init.luau"], -[183048, "src/Rosetta/music/mtm/init.luau"], -[183276, "src/Rosetta/music/mus/init.luau"], -[183441, "src/Rosetta/music/okt/init.luau"], -[183729, "src/Rosetta/music/ptm/init.luau"], -[183958, "src/Rosetta/music/s3m/init.luau"], -[184202, "src/Rosetta/music/sf2/init.luau"], -[184248, "src/Rosetta/music/stm/init.luau"], -[184483, "src/Rosetta/music/ult/init.luau"], -[184794, "src/Rosetta/music/umx/init.luau"], -[185018, "src/Rosetta/music/xm/init.luau"], -[185593, "src/Rosetta/music/xmi/init.luau"], -[185810, "src/Rosetta/ops/AudioOps.luau"], -[186294, "src/Rosetta/ops/ImageOps/init.luau"], -[186985, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[187507, "src/Rosetta/ops/LayerOps.luau"], -[187610, "src/Rosetta/ops/MeshOps/init.luau"], -[188699, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[188868, "src/Rosetta/ops/MusicOps.luau"], -[189239, "src/Rosetta/playlist/m3u/init.luau"], -[189608, "src/Rosetta/playlist/pls/init.luau"], -[189795, "src/Rosetta/playlist/xspf/init.luau"], -[190011, "src/Rosetta/subtitle/ass/init.luau"], -[190469, "src/Rosetta/subtitle/srt/init.luau"], -[190649, "src/Rosetta/subtitle/vtt/init.luau"], -[190859, "src/Rosetta/vector/svg/init.luau"], -[190955, "src/Rosetta/vector/svg/Parse.luau"], -[191715, "src/Rosetta/vector/svg/PathData.luau"], -[192094, "src/Rosetta/vector/svg/Render.luau"], -[192523, "src/Rosetta/vector/svg/Style.luau"], -[192906, "src/Rosetta/vector/svg/Write.luau"], -[193111, "src/Rosetta/vector/tiled/init.luau"], -[193300, "src/Rosetta/vector/tiled/Data.luau"], -[193458, "src/Rosetta/vector/tiled/Tmj.luau"], -[194094, "src/Rosetta/vector/tiled/Tmx.luau"], -[194714, "src/Rosetta/video/avi/init.luau"], -[195019, "src/Rosetta/video/fli/init.luau"], -[195178, "src/Rosetta/video/flv/init.luau"], -[195582, "src/Rosetta/video/flv/Amf.luau"], -[195750, "src/Rosetta/video/flv/Mux.luau"], -[196040, "src/Rosetta/video/h264/init.luau"], -[196187, "src/Rosetta/video/mkv/init.luau"], -[196358, "src/Rosetta/video/mkv/Mux.luau"], -[196645, "src/Rosetta/video/mkv/Parse.luau"], -[197377, "src/Rosetta/video/mp4/init.luau"], -[197720, "src/Rosetta/video/mpegps/init.luau"], -[197915, "src/Rosetta/video/mpegts/init.luau"], -[198163, "src/Rosetta/video/ogv/init.luau"], -[198572, "src/Rosetta/video/smk/init.luau"], -[198894, "src/Rosetta/video/smk/Audio.luau"], -[199019, "src/Rosetta/video/y4m/init.luau"] +[23757, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[24640, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[24975, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[25134, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[26019, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[26120, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[26874, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[27176, "src/Rosetta/codecs/audio/Alac/init.luau"], +[27410, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[27829, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[28241, "src/Rosetta/codecs/audio/Ape/init.luau"], +[28456, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[29217, "src/Rosetta/codecs/audio/ApeTag.luau"], +[29314, "src/Rosetta/codecs/audio/Flac/init.luau"], +[29325, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[30274, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[30871, "src/Rosetta/codecs/audio/Hively/init.luau"], +[31067, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[31316, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[32274, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[32493, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[32677, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[32886, "src/Rosetta/codecs/audio/MidiRender.luau"], +[33232, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[33246, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[33305, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[34908, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[35200, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[35585, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[36226, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[36367, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[36593, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[36938, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[37819, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[38197, "src/Rosetta/codecs/audio/Opus/init.luau"], +[38211, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[40058, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[41123, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[41183, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[41643, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[41980, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[42213, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[44249, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[44623, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[44886, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[45183, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[45465, "src/Rosetta/codecs/audio/Resample/init.luau"], +[45824, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[45878, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[46021, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[46534, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[47315, "src/Rosetta/codecs/audio/Stream.luau"], +[47476, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[47958, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[48236, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[48405, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[48533, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[50521, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[50637, "src/Rosetta/codecs/audio/Tta/init.luau"], +[50754, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[51006, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[51019, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[51403, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[51969, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[52390, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[52429, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[52481, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[52703, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[54158, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[54221, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[54308, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[55277, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[56145, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[56193, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[56709, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[57035, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[57455, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[57890, "src/Rosetta/codecs/compress/Explode.luau"], +[58086, "src/Rosetta/codecs/compress/Lz4.luau"], +[58355, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[58959, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[59499, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[59537, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[60010, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[60186, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[60454, "src/Rosetta/codecs/compress/Lzx.luau"], +[60888, "src/Rosetta/codecs/compress/PackBits.luau"], +[60978, "src/Rosetta/codecs/compress/Quantum.luau"], +[61215, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[61519, "src/Rosetta/codecs/compress/Xxh32.luau"], +[61588, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[61645, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[62603, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[62755, "src/Rosetta/codecs/entropy/Huffman.luau"], +[63037, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[63048, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[63262, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[63506, "src/Rosetta/codecs/font/Bitmap.luau"], +[63707, "src/Rosetta/codecs/font/Cff/init.luau"], +[64348, "src/Rosetta/codecs/font/GlyphNames.luau"], +[64498, "src/Rosetta/codecs/font/TrueType/init.luau"], +[64812, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[65204, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[65706, "src/Rosetta/codecs/image/Bcn/init.luau"], +[65813, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[66302, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[66731, "src/Rosetta/codecs/image/Blend.luau"], +[67110, "src/Rosetta/codecs/image/Dct/init.luau"], +[67491, "src/Rosetta/codecs/image/Etc.luau"], +[67789, "src/Rosetta/codecs/image/Half.luau"], +[67858, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[68212, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[68620, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[68857, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[69617, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[70498, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[70944, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[71022, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[71089, "src/Rosetta/codecs/image/Pixels.luau"], +[71353, "src/Rosetta/codecs/image/Quantize/init.luau"], +[71812, "src/Rosetta/codecs/image/Raster.luau"], +[72509, "src/Rosetta/codecs/image/Texel.luau"], +[72882, "src/Rosetta/codecs/image/Texture.luau"], +[73027, "src/Rosetta/codecs/image/Vp8/init.luau"], +[73157, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[75113, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[75372, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[75621, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[75740, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[75844, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[76697, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[77649, "src/Rosetta/codecs/image/Yuv.luau"], +[77917, "src/Rosetta/codecs/model/Draco/init.luau"], +[78249, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[78718, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[79907, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[80056, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[80415, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[81377, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[81851, "src/Rosetta/codecs/model/Mat4.luau"], +[82110, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[82638, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[83190, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[83269, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[83376, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[83582, "src/Rosetta/codecs/model/Polygon.luau"], +[83816, "src/Rosetta/codecs/model/Rbx/init.luau"], +[84053, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[84807, "src/Rosetta/codecs/model/Rig.luau"], +[85050, "src/Rosetta/codecs/model/Sampler.luau"], +[85210, "src/Rosetta/codecs/model/Vrml/init.luau"], +[85358, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[85932, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[86095, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[86844, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[87366, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[88093, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[88325, "src/Rosetta/codecs/text/Json/init.luau"], +[88594, "src/Rosetta/codecs/text/Json/Decode.luau"], +[89008, "src/Rosetta/codecs/text/Json/Encode.luau"], +[89310, "src/Rosetta/codecs/text/Nbt/init.luau"], +[89663, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[90355, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[90995, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[91233, "src/Rosetta/codecs/text/Text/init.luau"], +[91324, "src/Rosetta/codecs/text/Url/init.luau"], +[91529, "src/Rosetta/codecs/text/Xml/init.luau"], +[91932, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[92672, "src/Rosetta/codecs/video/Dsp.luau"], +[93395, "src/Rosetta/codecs/video/H263/init.luau"], +[93551, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[94409, "src/Rosetta/codecs/video/H263/Tables.luau"], +[94612, "src/Rosetta/codecs/video/H264/init.luau"], +[94985, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[95260, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[96391, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[97159, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[97417, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[98426, "src/Rosetta/codecs/video/H264/Inter.luau"], +[98680, "src/Rosetta/codecs/video/H264/Intra.luau"], +[99087, "src/Rosetta/codecs/video/H264/Mb.luau"], +[99993, "src/Rosetta/codecs/video/H264/Params.luau"], +[100440, "src/Rosetta/codecs/video/H264/Slice.luau"], +[100691, "src/Rosetta/codecs/video/H264/Tables.luau"], +[100732, "src/Rosetta/codecs/video/H264/Transform.luau"], +[100897, "src/Rosetta/codecs/video/Legacy/init.luau"], +[101095, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[101392, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[101759, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[101877, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[101985, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[102258, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[102653, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[102830, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[102842, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[103209, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[104716, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[104855, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[104993, "src/Rosetta/codecs/video/Theora/init.luau"], +[105256, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[106520, "src/Rosetta/codecs/video/Theora/Header.luau"], +[106883, "src/Rosetta/codecs/video/Video/init.luau"], +[107440, "src/Rosetta/codecs/video/Video/Source.luau"], +[107725, "src/Rosetta/containers/Archive.luau"], +[108018, "src/Rosetta/containers/AudioWrap.luau"], +[108539, "src/Rosetta/containers/Avi/init.luau"], +[109111, "src/Rosetta/containers/Chunks.luau"], +[109255, "src/Rosetta/containers/Cpio.luau"], +[109697, "src/Rosetta/containers/Demux.luau"], +[109995, "src/Rosetta/containers/Ebml/init.luau"], +[110332, "src/Rosetta/containers/Fat.luau"], +[111041, "src/Rosetta/containers/Iso9660.luau"], +[111568, "src/Rosetta/containers/IsoBmff/init.luau"], +[111758, "src/Rosetta/containers/IsoBmff/Box.luau"], +[111953, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[112817, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[113347, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[113868, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[113990, "src/Rosetta/containers/MacFile.luau"], +[114150, "src/Rosetta/containers/MpegEs.luau"], +[114325, "src/Rosetta/containers/MpegPs/init.luau"], +[114551, "src/Rosetta/containers/MpegTs/init.luau"], +[115368, "src/Rosetta/containers/Ogg/init.luau"], +[115826, "src/Rosetta/containers/Ogg/Mux.luau"], +[116036, "src/Rosetta/containers/Ogg/Page.luau"], +[116213, "src/Rosetta/containers/Riff/init.luau"], +[116558, "src/Rosetta/containers/Tar.luau"], +[116986, "src/Rosetta/containers/Zip/init.luau"], +[117646, "src/Rosetta/core/Adler32.luau"], +[117698, "src/Rosetta/core/Base64.luau"], +[117867, "src/Rosetta/core/Bits.luau"], +[118179, "src/Rosetta/core/Bytes.luau"], +[118748, "src/Rosetta/core/Crc16.luau"], +[118802, "src/Rosetta/core/Crc32.luau"], +[118925, "src/Rosetta/core/Err.luau"], +[119021, "src/Rosetta/core/Input.luau"], +[119105, "src/Rosetta/core/Md5.luau"], +[119271, "src/Rosetta/core/Sniff.luau"], +[119309, "src/Rosetta/data/cbor/init.luau"], +[119411, "src/Rosetta/data/cbor/Codec.luau"], +[119988, "src/Rosetta/data/csv/init.luau"], +[120305, "src/Rosetta/data/ini/init.luau"], +[120556, "src/Rosetta/data/json/init.luau"], +[120649, "src/Rosetta/data/msgpack/init.luau"], +[120741, "src/Rosetta/data/msgpack/Codec.luau"], +[121189, "src/Rosetta/data/nbt/init.luau"], +[121251, "src/Rosetta/data/plist/init.luau"], +[121559, "src/Rosetta/data/plist/Binary.luau"], +[121832, "src/Rosetta/data/snbt/init.luau"], +[121897, "src/Rosetta/data/toml/init.luau"], +[121969, "src/Rosetta/data/toml/Decode.luau"], +[122606, "src/Rosetta/data/toml/Encode.luau"], +[122822, "src/Rosetta/data/xml/init.luau"], +[122879, "src/Rosetta/data/yaml/init.luau"], +[122958, "src/Rosetta/data/yaml/Emit.luau"], +[123259, "src/Rosetta/data/yaml/Parse.luau"], +[124583, "src/Rosetta/font/bdf/init.luau"], +[124880, "src/Rosetta/font/bmfont/init.luau"], +[125322, "src/Rosetta/font/bmfont/Parse.luau"], +[125781, "src/Rosetta/font/eot/init.luau"], +[126016, "src/Rosetta/font/fon/init.luau"], +[126306, "src/Rosetta/font/hershey/init.luau"], +[126508, "src/Rosetta/font/pcf/init.luau"], +[126800, "src/Rosetta/font/psf/init.luau"], +[127130, "src/Rosetta/font/ttf/init.luau"], +[127184, "src/Rosetta/font/type1/init.luau"], +[127554, "src/Rosetta/font/type1/Charstring.luau"], +[127839, "src/Rosetta/font/woff/init.luau"], +[127973, "src/Rosetta/font/woff2/init.luau"], +[128032, "src/Rosetta/font/woff2/Rebuild.luau"], +[128582, "src/Rosetta/host/init.luau"], +[128634, "src/Rosetta/host/Love.luau"], +[128785, "src/Rosetta/host/LuaJIT.luau"], +[128835, "src/Rosetta/host/Luau.luau"], +[128858, "src/Rosetta/host/Roblox.luau"], +[129249, "src/Rosetta/image/ani/init.luau"], +[129434, "src/Rosetta/image/blp/init.luau"], +[129702, "src/Rosetta/image/bmp/init.luau"], +[130133, "src/Rosetta/image/dds/init.luau"], +[130632, "src/Rosetta/image/exr/init.luau"], +[131416, "src/Rosetta/image/exr/Codec.luau"], +[131535, "src/Rosetta/image/exr/Piz.luau"], +[131904, "src/Rosetta/image/gif/init.luau"], +[132440, "src/Rosetta/image/gif/Decode.luau"], +[132510, "src/Rosetta/image/hdr/init.luau"], +[132746, "src/Rosetta/image/hdr/Codec.luau"], +[132967, "src/Rosetta/image/icns/init.luau"], +[133306, "src/Rosetta/image/ico/init.luau"], +[133590, "src/Rosetta/image/ico/Dib.luau"], +[133691, "src/Rosetta/image/ilbm/init.luau"], +[134017, "src/Rosetta/image/jpeg/init.luau"], +[134168, "src/Rosetta/image/ktx/init.luau"], +[134842, "src/Rosetta/image/pcx/init.luau"], +[135110, "src/Rosetta/image/png/init.luau"], +[135708, "src/Rosetta/image/png/Apng.luau"], +[135792, "src/Rosetta/image/png/Decode.luau"], +[136047, "src/Rosetta/image/png/Encode.luau"], +[136211, "src/Rosetta/image/pnm/init.luau"], +[136597, "src/Rosetta/image/pnm/Codec.luau"], +[136888, "src/Rosetta/image/qoi/init.luau"], +[137012, "src/Rosetta/image/qoi/Codec.luau"], +[137166, "src/Rosetta/image/sgi/init.luau"], +[137454, "src/Rosetta/image/sunras/init.luau"], +[137703, "src/Rosetta/image/tga/init.luau"], +[137981, "src/Rosetta/image/tga/Codec.luau"], +[138140, "src/Rosetta/image/tiff/init.luau"], +[138984, "src/Rosetta/image/tiff/Pixels.luau"], +[139385, "src/Rosetta/image/tim/init.luau"], +[139634, "src/Rosetta/image/vtf/init.luau"], +[139881, "src/Rosetta/image/webp/init.luau"], +[140510, "src/Rosetta/image/webp/Alpha.luau"], +[140588, "src/Rosetta/image/webp/Anim.luau"], +[140752, "src/Rosetta/image/xbm/init.luau"], +[140916, "src/Rosetta/image/xpm/init.luau"], +[141190, "src/Rosetta/image/xpm/Names.luau"], +[141249, "src/Rosetta/layered/aseprite/init.luau"], +[142005, "src/Rosetta/layered/ora/init.luau"], +[142300, "src/Rosetta/layered/psd/init.luau"], +[143045, "src/Rosetta/layered/psd/Channels.luau"], +[143416, "src/Rosetta/model/3ds/init.luau"], +[143518, "src/Rosetta/model/3ds/Build.luau"], +[144183, "src/Rosetta/model/3ds/Read.luau"], +[144691, "src/Rosetta/model/3ds/Write.luau"], +[145520, "src/Rosetta/model/3mf/init.luau"], +[145617, "src/Rosetta/model/3mf/Read.luau"], +[146217, "src/Rosetta/model/3mf/Write.luau"], +[146636, "src/Rosetta/model/b3d/init.luau"], +[146706, "src/Rosetta/model/b3d/Read.luau"], +[147284, "src/Rosetta/model/bsp/init.luau"], +[147436, "src/Rosetta/model/bsp/Brush.luau"], +[147729, "src/Rosetta/model/bsp/Quake3.luau"], +[147992, "src/Rosetta/model/dae/init.luau"], +[148200, "src/Rosetta/model/dae/Math.luau"], +[148248, "src/Rosetta/model/dae/Read.luau"], +[150130, "src/Rosetta/model/dae/Write.luau"], +[150508, "src/Rosetta/model/fbx/init.luau"], +[150676, "src/Rosetta/model/fbx/Ascii.luau"], +[150952, "src/Rosetta/model/fbx/Binary.luau"], +[151415, "src/Rosetta/model/fbx/Read.luau"], +[152801, "src/Rosetta/model/fbx/Write.luau"], +[153799, "src/Rosetta/model/fbx/Xform.luau"], +[153843, "src/Rosetta/model/gltf/init.luau"], +[154097, "src/Rosetta/model/gltf/Pack.luau"], +[154173, "src/Rosetta/model/gltf/Read.luau"], +[154922, "src/Rosetta/model/gltf/Write.luau"], +[155620, "src/Rosetta/model/iqm/init.luau"], +[155704, "src/Rosetta/model/iqm/Read.luau"], +[156065, "src/Rosetta/model/iqm/Write.luau"], +[156773, "src/Rosetta/model/ldraw/init.luau"], +[156880, "src/Rosetta/model/ldraw/Colors.luau"], +[157201, "src/Rosetta/model/ldraw/Read.luau"], +[157783, "src/Rosetta/model/lwo/init.luau"], +[157871, "src/Rosetta/model/lwo/Build.luau"], +[158342, "src/Rosetta/model/lwo/Parse.luau"], +[158895, "src/Rosetta/model/mca/init.luau"], +[159252, "src/Rosetta/model/mca/Chunk.luau"], +[159389, "src/Rosetta/model/mca/Lz4Block.luau"], +[159461, "src/Rosetta/model/md2/init.luau"], +[159672, "src/Rosetta/model/md3/init.luau"], +[159908, "src/Rosetta/model/md5/init.luau"], +[159993, "src/Rosetta/model/md5/Read.luau"], +[160435, "src/Rosetta/model/mdl/init.luau"], +[160521, "src/Rosetta/model/mdl/HalfLife.luau"], +[160863, "src/Rosetta/model/mdl/Quake.luau"], +[161087, "src/Rosetta/model/ms3d/init.luau"], +[161171, "src/Rosetta/model/ms3d/Read.luau"], +[161637, "src/Rosetta/model/ms3d/Write.luau"], +[162125, "src/Rosetta/model/obj/init.luau"], +[162890, "src/Rosetta/model/obj/Mtl.luau"], +[163186, "src/Rosetta/model/off/init.luau"], +[163668, "src/Rosetta/model/ply/init.luau"], +[164818, "src/Rosetta/model/ply/Binary.luau"], +[165032, "src/Rosetta/model/pmx/init.luau"], +[165111, "src/Rosetta/model/pmx/Build.luau"], +[165420, "src/Rosetta/model/pmx/Pmd.luau"], +[165761, "src/Rosetta/model/pmx/Read.luau"], +[166174, "src/Rosetta/model/qb/init.luau"], +[166577, "src/Rosetta/model/rbxm/init.luau"], +[167184, "src/Rosetta/model/rbxmx/init.luau"], +[167853, "src/Rosetta/model/robloxmesh/init.luau"], +[168539, "src/Rosetta/model/robloxmesh/Parse.luau"], +[169001, "src/Rosetta/model/robloxmesh/Write.luau"], +[169112, "src/Rosetta/model/schematic/init.luau"], +[169448, "src/Rosetta/model/schematic/Common.luau"], +[169578, "src/Rosetta/model/schematic/Litematic.luau"], +[169795, "src/Rosetta/model/schematic/Mcedit.luau"], +[170046, "src/Rosetta/model/schematic/Sponge.luau"], +[170179, "src/Rosetta/model/smd/init.luau"], +[170250, "src/Rosetta/model/smd/Read.luau"], +[170527, "src/Rosetta/model/smd/Write.luau"], +[170779, "src/Rosetta/model/stl/init.luau"], +[171248, "src/Rosetta/model/stl/Decode.luau"], +[171327, "src/Rosetta/model/usda/init.luau"], +[171550, "src/Rosetta/model/usda/Build.luau"], +[172867, "src/Rosetta/model/usda/Parse.luau"], +[173689, "src/Rosetta/model/usda/Write.luau"], +[174531, "src/Rosetta/model/vox/init.luau"], +[175436, "src/Rosetta/model/vox/Grid.luau"], +[175499, "src/Rosetta/model/vrml/init.luau"], +[175578, "src/Rosetta/model/x/init.luau"], +[175722, "src/Rosetta/model/x/Build.luau"], +[176298, "src/Rosetta/model/x/Parse.luau"], +[176606, "src/Rosetta/model/x3d/init.luau"], +[176693, "src/Rosetta/music/669/init.luau"], +[176904, "src/Rosetta/music/ahx/init.luau"], +[176959, "src/Rosetta/music/far/init.luau"], +[177193, "src/Rosetta/music/hmp/init.luau"], +[177468, "src/Rosetta/music/hvl/init.luau"], +[177523, "src/Rosetta/music/it/init.luau"], +[177952, "src/Rosetta/music/it/Itsex.luau"], +[178074, "src/Rosetta/music/med/init.luau"], +[178737, "src/Rosetta/music/midi/init.luau"], +[178893, "src/Rosetta/music/midi/Smf.luau"], +[179313, "src/Rosetta/music/mod/init.luau"], +[179676, "src/Rosetta/music/mtm/init.luau"], +[179904, "src/Rosetta/music/mus/init.luau"], +[180069, "src/Rosetta/music/okt/init.luau"], +[180357, "src/Rosetta/music/ptm/init.luau"], +[180586, "src/Rosetta/music/s3m/init.luau"], +[180830, "src/Rosetta/music/sf2/init.luau"], +[180876, "src/Rosetta/music/stm/init.luau"], +[181111, "src/Rosetta/music/ult/init.luau"], +[181422, "src/Rosetta/music/umx/init.luau"], +[181646, "src/Rosetta/music/xm/init.luau"], +[182221, "src/Rosetta/music/xmi/init.luau"], +[182438, "src/Rosetta/ops/AudioOps.luau"], +[182922, "src/Rosetta/ops/ImageOps/init.luau"], +[183613, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[184135, "src/Rosetta/ops/LayerOps.luau"], +[184238, "src/Rosetta/ops/MeshOps/init.luau"], +[185327, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[185496, "src/Rosetta/ops/MusicOps.luau"], +[185867, "src/Rosetta/playlist/m3u/init.luau"], +[186236, "src/Rosetta/playlist/pls/init.luau"], +[186423, "src/Rosetta/playlist/xspf/init.luau"], +[186639, "src/Rosetta/subtitle/ass/init.luau"], +[187097, "src/Rosetta/subtitle/srt/init.luau"], +[187277, "src/Rosetta/subtitle/vtt/init.luau"], +[187487, "src/Rosetta/vector/svg/init.luau"], +[187583, "src/Rosetta/vector/svg/Parse.luau"], +[188343, "src/Rosetta/vector/svg/PathData.luau"], +[188722, "src/Rosetta/vector/svg/Render.luau"], +[189151, "src/Rosetta/vector/svg/Style.luau"], +[189534, "src/Rosetta/vector/svg/Write.luau"], +[189739, "src/Rosetta/vector/tiled/init.luau"], +[189928, "src/Rosetta/vector/tiled/Data.luau"], +[190086, "src/Rosetta/vector/tiled/Tmj.luau"], +[190722, "src/Rosetta/vector/tiled/Tmx.luau"], +[191342, "src/Rosetta/video/avi/init.luau"], +[191647, "src/Rosetta/video/fli/init.luau"], +[191806, "src/Rosetta/video/flv/init.luau"], +[192210, "src/Rosetta/video/flv/Amf.luau"], +[192378, "src/Rosetta/video/flv/Mux.luau"], +[192668, "src/Rosetta/video/h264/init.luau"], +[192815, "src/Rosetta/video/mkv/init.luau"], +[192986, "src/Rosetta/video/mkv/Mux.luau"], +[193273, "src/Rosetta/video/mkv/Parse.luau"], +[194005, "src/Rosetta/video/mp4/init.luau"], +[194348, "src/Rosetta/video/mpegps/init.luau"], +[194543, "src/Rosetta/video/mpegts/init.luau"], +[194791, "src/Rosetta/video/ogv/init.luau"], +[195200, "src/Rosetta/video/smk/init.luau"], +[195522, "src/Rosetta/video/smk/Audio.luau"], +[195647, "src/Rosetta/video/y4m/init.luau"] ]