ws-audio: merge ws/absorb (Ogg + muxer, Riff, wav, mp3, opus, apng)

This commit is contained in:
4DBug committed 2026-10-31 08:39:08 -05:00
commit bc061743da
72 files changed
+14343 -56

No files matched your search

+37 -1
View File
@@ -21,7 +21,7 @@ local list: { Entry } = {
extensions = { "png", "apng" },
mime = { "image/png", "image/apng" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" },
caps = { decode = true, encode = true, animation = false, alpha = true, depths = { 1, 2, 4, 8, 16 } },
caps = { decode = true, encode = true, animation = true, alpha = true, depths = { 1, 2, 4, 8, 16 } },
load = function()
return require("@formats/image/png")
end,
@@ -50,6 +50,30 @@ local list: { Entry } = {
return require("@formats/audio/au")
end,
},
{
name = "mp3",
category = "audio",
path = "audio/mp3",
extensions = { "mp3", "mp2", "mp1", "mpga" },
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 },
load = function()
return require("@formats/audio/mp3")
end,
},
{
name = "opus",
category = "audio",
path = "audio/opus",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } },
load = function()
return require("@formats/audio/opus")
end,
},
{
name = "voc",
category = "audio",
@@ -62,6 +86,18 @@ local list: { Entry } = {
return require("@formats/audio/voc")
end,
},
{
name = "wav",
category = "audio",
path = "audio/wav",
extensions = { "wav", "wave", "rf64", "bw64" },
mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
load = function()
return require("@formats/audio/wav")
end,
},
}
return list
File diff suppressed because it is too large. Load diff
+140
View File
@@ -0,0 +1,140 @@
--!strict
--!native
--!optimize 2
-- audio/mp3/Header: MPEG audio frame headers (minimp3's hdr_* macros and functions), frame sync (mp3d_find_frame /
-- mp3d_match_frame). Every function reads 4 header bytes at a byte offset of a buffer; callers keep offset + 4
-- inside the buffer. Never throws.
local T = require("@formats/audio/mp3/Tables")
local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift
local ru8 = buffer.readu8
local HALFRATE = T.halfrate
local HZ = { [0] = 44100, 48000, 32000 }
local H = {}
H.MAX_FREE_FORMAT_FRAME_SIZE = 2304
H.MAX_FRAME_SYNC_MATCHES = 10
-- hdr_valid
function H.valid(b: buffer, o: number): boolean
if ru8(b, o) ~= 0xFF then
return false
end
local h1, h2 = ru8(b, o + 1), ru8(b, o + 2)
return (band(h1, 0xF0) == 0xF0 or band(h1, 0xFE) == 0xE2)
and band(rshift(h1, 1), 3) ~= 0
and rshift(h2, 4) ~= 15
and band(rshift(h2, 2), 3) ~= 3
end
local valid = H.valid
-- hdr_compare: h2 is a valid header of the same version / layer / sample rate / free-format-ness as h1
function H.compare(b: buffer, o1: number, o2: number): boolean
if not valid(b, o2) then
return false
end
local a1, a2 = ru8(b, o1 + 1), ru8(b, o1 + 2)
local c1, c2 = ru8(b, o2 + 1), ru8(b, o2 + 2)
return band(bxor(a1, c1), 0xFE) == 0
and band(bxor(a2, c2), 0x0C) == 0
and (band(a2, 0xF0) == 0) == (band(c2, 0xF0) == 0)
end
local compare = H.compare
-- from the header bytes h1 = byte 1, h2 = byte 2
function H.bitrateKbps(h1: number, h2: number): number
local mpeg1 = if band(h1, 8) ~= 0 then 1 else 0
local layer = band(rshift(h1, 1), 3)
return 2 * HALFRATE[mpeg1 * 45 + (layer - 1) * 15 + rshift(h2, 4)]
end
local bitrateKbps = H.bitrateKbps
function H.sampleRate(h1: number, h2: number): number
local hz = HZ[band(rshift(h2, 2), 3)]
if band(h1, 8) == 0 then
hz //= 2
end
if band(h1, 0x10) == 0 then
hz //= 2
end
return hz
end
local sampleRate = H.sampleRate
function H.frameSamples(h1: number): number
if band(h1, 6) == 6 then
return 384
elseif band(h1, 14) == 2 then
return 576
end
return 1152
end
local frameSamples = H.frameSamples
-- hdr_frame_bytes (without padding); free format = 0 -> freeSize
function H.frameBytes(b: buffer, o: number, freeSize: number): number
local h1, h2 = ru8(b, o + 1), ru8(b, o + 2)
local hz = sampleRate(h1, h2)
local fb = frameSamples(h1) * bitrateKbps(h1, h2) * 125 // hz
if band(h1, 6) == 6 then
fb = band(fb, 0xFFFFFFFC)
end
return if fb ~= 0 then fb else freeSize
end
local frameBytes = H.frameBytes
function H.padding(b: buffer, o: number): number
if band(ru8(b, o + 2), 2) == 0 then
return 0
end
return if band(ru8(b, o + 1), 6) == 6 then 4 else 1
end
local padding = H.padding
-- mp3d_match_frame: the frames chained after o (n bytes left) keep comparing equal
local function matchFrame(b: buffer, o: number, n: number, fb: number): boolean
local i = 0
for nmatch = 0, H.MAX_FRAME_SYNC_MATCHES - 1 do
i += frameBytes(b, o + i, fb) + padding(b, o + i)
if i + 4 > n then
return nmatch > 0
end
if not compare(b, o, o + i) then
return false
end
end
return true
end
-- mp3d_find_frame over b[base, base + n): returns (skip, frame bytes incl. padding or 0, free format size)
function H.findFrame(b: buffer, base: number, n: number, ffb: number): (number, number, number)
for i = 0, n - 5 do
local o = base + i
if valid(b, o) then
local fb = frameBytes(b, o, ffb)
local fap = fb + padding(b, o)
local k = 4
while fb == 0 and k < H.MAX_FREE_FORMAT_FRAME_SIZE and i + 2 * k < n - 4 do
if compare(b, o, o + k) then
local f = k - padding(b, o)
local nextfb = f + padding(b, o + k)
if not (i + k + nextfb + 4 > n or not compare(b, o, o + k + nextfb)) then
fap = k
fb = f
ffb = f
end
end
k += 1
end
if (fb ~= 0 and i + fap <= n and matchFrame(b, o, n - i, fb)) or (i == 0 and fap == n) then
return i, fap, ffb
end
ffb = 0
end
end
return n, 0, ffb
end
return H
+194
View File
@@ -0,0 +1,194 @@
--!strict
--!native
--!optimize 2
-- audio/mp3/Index: the frame index of a stream, built once on open. It follows minimp3_ex's mp3dec_load_buf frame by frame
-- (same sync, resync and Xing / LAME handling), and simulates the layer III bit reservoir from the side info, so
-- it knows in advance which frames give output and where each one's samples land. That makes the total length
-- exact and seeking sample-accurate. Never throws.
local Header = require("@formats/audio/mp3/Header")
local Core = require("@formats/audio/mp3/Core")
local band, rshift = bit32.band, bit32.rshift
local ru8 = buffer.readu8
local min, max = math.min, math.max
local compare, frameBytes, padding, findFrame =
Header.compare, Header.frameBytes, Header.padding, Header.findFrame
local Index = {}
Index.FLAG_RESET = 1 -- decoder state is zeroed before this frame (minimp3 re-synced here)
Index.FLAG_OUTPUT = 2 -- this frame gives samples in a continuous decode
export type Index = {
n: number, -- frames
off: buffer, -- u32 byte offset per frame
size: buffer, -- u16 byte size per frame (header and padding included)
flags: buffer, -- u8 FLAG_*
out: buffer, -- u32 first output sample (before the encoder delay is cut) per frame
main: buffer, -- u16 layer III main data bytes per frame (0 for layers I / II)
outTotal: number, -- samples (per channel) of a continuous decode, delay not cut
bytes: number, -- audio bytes in indexed frames
-- format of the first frame
sampleRate: number,
channels: number, -- the most channels of any frame
layer: number,
version: number, -- 1, 2 or 2.5
spf: number, -- samples per frame
-- Xing / Info / LAME
vbrTag: number, -- mp3dec_check_vbrtag result of the first frame (0 = none)
tagFrames: number,
delay: number,
padding: number,
skipped: number, -- frames with another sample rate or layer, left out
}
local function grow(b: buffer, n: number): buffer
local nb = buffer.create(n)
buffer.copy(nb, 0, b, 0, math.min(buffer.len(b), n))
return nb
end
function Index.build(b: buffer, start: number, stop: number): Index?
local cap = 1024
local OFF, SIZE, FLAGS, OUT, MAIN = buffer.create(cap * 4), buffer.create(cap * 2), buffer.create(cap), buffer.create(cap * 4), buffer.create(cap * 2)
local n = 0
local pos = start
local prev = -1 -- offset of the last decoded header (dec->header), -1 = none
local ffb = 0 -- free format bytes
local reserv = 0
local outTotal = 0
local bytes = 0
local first = true
local skipped = 0
local outCh = 0 -- the most channels of a frame that gives output
local hz, nch, layer, spf, version = 0, 0, 0, 0, 0
local vbr, tagFrames, delay, pad = 0, 0, 0, 0
while true do
local remaining = stop - pos
if remaining <= 0 then
break
end
local fs = 0
local reset = false
if remaining > 4 and prev >= 0 and compare(b, prev, pos) then
fs = frameBytes(b, pos, ffb) + padding(b, pos)
if fs ~= remaining and (fs + 4 > remaining or not compare(b, pos, pos + fs)) then
fs = 0
end
end
if fs == 0 then
reset = true
reserv = 0
local i
i, fs, ffb = findFrame(b, pos, remaining, 0)
if fs == 0 or i + fs > remaining then
break
end
pos += i
end
if fs < 4 or fs > Core.MAX_FRAME then
-- cannot happen with a well-formed header, but never index an impossible frame
prev = -1
pos += max(fs, 1)
continue
end
local h1, h2, h3 = ru8(b, pos + 1), ru8(b, pos + 2), ru8(b, pos + 3)
local fLayer = 4 - band(rshift(h1, 1), 3)
local fHz = Header.sampleRate(h1, h2)
local fCh = if band(h3, 0xC0) == 0xC0 then 1 else 2
if first then
first = false
hz, nch, layer, spf = fHz, fCh, fLayer, Header.frameSamples(h1)
version = if band(h1, 8) ~= 0 then 1 elseif band(h1, 0x10) ~= 0 then 2 else 2.5
if fLayer == 3 then
local ret, frames, d, p = Core.vbrTag(b, pos, fs)
if ret ~= 0 then
vbr, tagFrames, delay, pad = ret, frames, d, p
if ret < 0 then
delay, pad = 0, 0
end
-- the tag frame is not audio; the next frame is found again from scratch
prev = -1
pos += fs
continue
end
end
elseif fHz ~= hz or fLayer ~= layer then
skipped += 1
prev = pos
pos += fs
continue
end
local output = true
local mainBytes = 0
local nextPrev = pos
if fLayer == 3 then
local mdb, p23, mb = Core.probeL3(b, pos, fs)
if mdb < 0 then
output = false
nextPrev = -1 -- mp3dec_init: the next frame re-syncs
else
mainBytes = mb
local have = min(reserv, mdb)
output = reserv >= mdb
local remains = have + mb - (if output then (p23 + 7) // 8 else 0)
reserv = max(0, min(remains, 511))
end
else
output = Core.probeL12(b, pos, fs)
if not output then
nextPrev = -1
end
end
if output and fCh > outCh then
outCh = fCh -- mono / stereo switches: the stream is stereo, mono frames are duplicated
end
if n == cap then
cap *= 2
OFF, SIZE, FLAGS, OUT, MAIN = grow(OFF, cap * 4), grow(SIZE, cap * 2), grow(FLAGS, cap), grow(OUT, cap * 4), grow(MAIN, cap * 2)
end
buffer.writeu32(OFF, n * 4, pos)
buffer.writeu16(SIZE, n * 2, fs)
buffer.writeu8(FLAGS, n, (if reset then Index.FLAG_RESET else 0) + (if output then Index.FLAG_OUTPUT else 0))
buffer.writeu32(OUT, n * 4, outTotal)
buffer.writeu16(MAIN, n * 2, min(mainBytes, 65535))
n += 1
bytes += fs
if output then
outTotal += spf
end
prev = nextPrev
pos += fs
end
if first then
return nil
end
return {
n = n,
off = OFF,
size = SIZE,
flags = FLAGS,
out = OUT,
main = MAIN,
outTotal = outTotal,
bytes = bytes,
sampleRate = hz,
channels = if outCh > 0 then outCh else nch,
layer = layer,
version = version,
spf = spf,
vbrTag = vbr,
tagFrames = tagFrames,
delay = delay,
padding = pad,
skipped = skipped,
}
end
return Index
+233
View File
@@ -0,0 +1,233 @@
--!strict
--!optimize 2
-- audio/mp3/Stream: the streaming Decoder (Types.Decoder) over a frame index: gapless (LAME delay / padding), exact
-- length, sample-accurate seeking. From mp3-luau's Mp3.open / Decoder (same author). Never throws.
local Core = require("@formats/audio/mp3/Core")
local Index = require("@formats/audio/mp3/Index")
local FLAG_RESET, FLAG_OUTPUT = Index.FLAG_RESET, Index.FLAG_OUTPUT
local ru8, ru16, ru32 = buffer.readu8, buffer.readu16, buffer.readu32
local band = bit32.band
local min, max, floor = math.min, math.max, math.floor
local Stream = {}
local Decoder = {}
Decoder.__index = Decoder
export type Decoder = typeof(setmetatable(
{} :: {
sampleRate: number,
channels: number,
frames: number,
duration: number,
bitrate: number,
tags: { [string]: string },
id3: any,
layer: number,
version: number,
vbr: boolean,
delay: number,
padding: number,
mpegFrames: number,
_buf: buffer,
_idx: any,
_st: any,
_pcm: buffer,
_cur: number,
_pcmPos: number,
_pcmEnd: number,
_minAbs: number,
_endAbs: number,
_pos: number,
},
Decoder
))
-- new(b, idx, tags, id3) -> Decoder over the whole buffer b, with its frame index (Index.build)
function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): Decoder
local spf, hz, nch = idx.spf, idx.sampleRate, idx.channels
-- gapless: minimp3_ex cuts delay samples off the start and caps the length at the Xing / LAME count
local delay = 0
local total = idx.outTotal
if idx.vbrTag > 0 then
delay = idx.delay
local detected = spf * idx.tagFrames
if detected >= delay then
detected -= delay
end
if idx.padding > 0 and detected >= idx.padding then
detected -= idx.padding
end
total = max(0, total - delay)
total = min(total, detected)
end
delay = min(delay, idx.outTotal)
local self = setmetatable({
sampleRate = hz,
channels = nch,
frames = total,
duration = total / hz,
bitrate = if idx.n > 0 then floor(idx.bytes * 8 * hz / (idx.n * spf) / 1000 + 0.5) else 0,
tags = tags,
id3 = id3,
layer = idx.layer,
version = idx.version,
vbr = idx.vbrTag ~= 0,
delay = delay,
padding = if idx.vbrTag > 0 then max(0, idx.padding) else 0,
mpegFrames = idx.n,
_buf = b,
_idx = idx,
_st = Core.newState(),
_pcm = buffer.create(1152 * 2 * 4),
_cur = 0,
_pcmPos = 0,
_pcmEnd = 0,
_minAbs = delay,
_endAbs = delay + total,
_pos = 0,
}, Decoder)
return self
end
-- decodes frames until one has samples inside [minAbs, endAbs); false at the end
local function fill(self: Decoder): boolean
local idx = self._idx
local n = idx.n
local spf = idx.spf
local st = self._st
while self._cur < n do
local f = self._cur
self._cur = f + 1
local flags = ru8(idx.flags, f)
if band(flags, FLAG_RESET) ~= 0 then
Core.reset(st)
end
local a = ru32(idx.out, f * 4)
if a >= self._endAbs then
self._cur = n
return false
end
local got = Core.decodeFrame(st, self._buf, ru32(idx.off, f * 4), ru16(idx.size, f * 2), self._pcm)
if got > 0 and band(flags, FLAG_OUTPUT) ~= 0 then
if Core.lastChannels < self.channels then
Core.upmix(self._pcm, got)
end
local lo = max(a, self._minAbs)
local hi = min(a + spf, self._endAbs)
if hi > lo then
self._pcmPos = lo - a
self._pcmEnd = hi - a
return true
end
end
end
return false
end
-- Reads up to maxFrames sample frames: (buffer of interleaved f32, frames read); 0 frames = end of stream.
-- With out (a buffer of at least maxFrames * channels * 4 bytes) the samples go there and out is returned; a
-- smaller out is ignored.
function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, number)
local ch = self.channels
local want = tonumber(maxFrames) or 4096
if want ~= want then
want = 0
end
want = floor(max(0, min(want, self.frames - self._pos)))
if out and buffer.len(out) < want * ch * 4 then
out = nil -- too small: a new buffer (Types.Decoder: out is reused when big enough)
end
local dst = out or buffer.create(want * ch * 4)
local got = 0
local pcm = self._pcm
while got < want do
if self._pcmPos >= self._pcmEnd then
if not fill(self) then
break
end
end
local k = min(want - got, self._pcmEnd - self._pcmPos)
buffer.copy(dst, got * ch * 4, pcm, self._pcmPos * ch * 4, k * ch * 4)
got += k
self._pcmPos += k
end
self._pos += got
if not out and got < want then
local r = buffer.create(got * ch * 4)
buffer.copy(r, 0, dst, 0, got * ch * 4)
dst = r
end
return dst, got
end
-- Seeks to a time in seconds (clamped to the stream). Sample-accurate: decoding restarts a few frames earlier
-- (enough to refill the bit reservoir and the filter history) and the output before the target is dropped.
function Decoder.seek(self: Decoder, seconds: number)
local hz = self.sampleRate
local target = floor((tonumber(seconds) or 0) * hz + 0.5)
target = max(0, min(target, self.frames))
self:seekFrame(target)
end
-- Seeks to a sample frame (0 .. frames).
function Decoder.seekFrame(self: Decoder, target: number)
target = tonumber(target) or 0
if target ~= target then
target = 0
end
target = max(0, min(floor(target), self.frames))
local idx = self._idx
local abs = self.delay + target
self._pos = target
self._minAbs = abs
self._pcmPos, self._pcmEnd = 0, 0
Core.reset(self._st)
local n = idx.n
if abs >= self._endAbs or n == 0 then
self._cur = n
return
end
-- last frame starting at or before abs
local lo, hi = 0, n - 1
while lo < hi do
local mid = (lo + hi + 1) // 2
if ru32(idx.out, mid * 4) <= abs then
lo = mid
else
hi = mid - 1
end
end
local j = lo
-- go back >= 2 frames (layer I needs 2 for the polyphase history), and for layer III until the main data
-- before frame j - 1 covers the largest reservoir (511 bytes), stopping at a frame where the decoder resets
local need = if idx.layer == 3 then 511 else 0
local s, back, acc = j, 0, 0
while s > 0 and band(ru8(idx.flags, s), FLAG_RESET) == 0 do
if back >= 2 and acc >= need then
break
end
s -= 1
back += 1
if back >= 2 then
acc += ru16(idx.main, s * 2)
end
end
self._cur = s
end
-- Current position: (seconds, sample frame)
function Decoder.position(self: Decoder): (number, number)
return self._pos / self.sampleRate, self._pos
end
-- Decodes everything from the current position to the end: (buffer of interleaved f32, frames)
function Decoder.readAll(self: Decoder): (buffer, number)
return self:read(max(0, self.frames - self._pos))
end
Stream.Decoder = Decoder
return Stream
+224
View File
@@ -0,0 +1,224 @@
--!strict
-- audio/mp3/Tables: constant tables of minimp3 (https://github.com/lieff/minimp3, CC0), generated by tools/gen_tables.py.
-- Every list is flattened row-major and 0-based (t[0] is the first element), like the C arrays.
local T = {}
T.halfrate = { [0] = 0,
4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 72, 80, 0, 4, 8, 12, 16, 20, 24, 28, 32, 40,
48, 56, 64, 72, 80, 0, 16, 24, 28, 32, 40, 48, 56, 64, 72, 80, 88, 96, 112, 128, 0, 16, 20, 24,
28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 0, 16, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128,
160, 192, 0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,
}
T.g_bitalloc_code_tab = { [0] = 0,
17, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0, 17, 18, 3, 19, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 16, 0, 17, 18, 3, 19, 4, 5, 16, 0, 17, 18, 16, 0, 17, 18, 19, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 17, 18, 3, 19, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
}
T.g_scf_long = { [0] = 6,
6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 12, 12,
12, 12, 12, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 76, 90, 2, 2, 2, 2, 2, 0, 6, 6, 6,
6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 6, 6, 6, 6,
6, 6, 8, 10, 12, 14, 16, 18, 22, 26, 32, 38, 46, 54, 62, 70, 76, 36, 0, 6, 6, 6, 6, 6,
6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 4, 4, 4, 4, 4, 4,
6, 6, 8, 8, 10, 12, 16, 20, 24, 28, 34, 42, 50, 54, 76, 158, 0, 4, 4, 4, 4, 4, 4, 6,
6, 6, 8, 10, 12, 16, 18, 22, 28, 34, 40, 46, 54, 54, 192, 0, 4, 4, 4, 4, 4, 4, 6, 6,
8, 10, 12, 16, 20, 24, 30, 38, 46, 56, 68, 84, 102, 26, 0,
}
T.g_scf_short = { [0] = 4,
4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18,
18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8,
12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2,
2, 2, 2, 26, 26, 26, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8,
8, 10, 10, 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 4,
4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18,
18, 18, 24, 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4,
6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30,
40, 40, 40, 18, 18, 18, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8,
8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14,
14, 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34,
42, 42, 42, 12, 12, 12, 0,
}
T.g_scf_mixed = { [0] = 6,
6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24,
24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 0, 0, 0, 12, 12, 12, 4, 4, 4, 8, 8, 8,
12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2,
2, 2, 2, 26, 26, 26, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10,
10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 0, 0, 0, 6,
6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24,
24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6,
8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40,
18, 18, 18, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 8, 8, 8,
10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 0, 4,
4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14, 14,
14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4,
4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, 42,
42, 42, 12, 12, 12, 0, 0,
}
T.g_expfrac = { [0] = 9.31322575e-10,
7.83145814e-10, 6.58544508e-10, 5.53767716e-10,
}
T.g_scf_partitions = { [0] = 6,
5, 5, 5, 6, 5, 5, 5, 6, 5, 7, 3, 11, 10, 0, 0, 7, 7, 7, 0, 6, 6, 6, 3, 8,
8, 5, 0, 8, 9, 6, 12, 6, 9, 9, 9, 6, 9, 12, 6, 15, 18, 0, 0, 6, 15, 12, 0, 6,
12, 9, 6, 6, 18, 9, 0, 9, 9, 6, 12, 9, 9, 9, 9, 9, 9, 12, 6, 18, 18, 0, 0, 12,
12, 12, 0, 12, 9, 9, 6, 15, 12, 9, 0,
}
T.g_scfc_decode = { [0] = 0,
1, 2, 3, 12, 5, 6, 7, 9, 10, 11, 13, 14, 15, 18, 19,
}
T.g_mod = { [0] = 5,
5, 4, 4, 5, 5, 4, 1, 4, 3, 1, 1, 5, 6, 6, 1, 4, 4, 4, 1, 4, 3, 1, 1,
}
T.g_preamp = { [0] = 1,
1, 1, 1, 2, 2, 3, 3, 3, 2,
}
T.g_pow43 = { [0] = 0,
-1, -2.519842, -4.326749, -6.349604, -8.549880, -10.902724, -13.390518, -16.000000, -18.720754, -21.544347, -24.463781, -27.473142, -30.567351, -33.741992, -36.993181, 0, 1, 2.519842, 4.326749, 6.349604, 8.549880, 10.902724, 13.390518, 16.000000,
18.720754, 21.544347, 24.463781, 27.473142, 30.567351, 33.741992, 36.993181, 40.317474, 43.711787, 47.173345, 50.699631, 54.288352, 57.937408, 61.644865, 65.408941, 69.227979, 73.100443, 77.024898, 81.000000, 85.024491, 89.097188, 93.216975, 97.382800, 101.593667,
105.848633, 110.146801, 114.487321, 118.869381, 123.292209, 127.755065, 132.257246, 136.798076, 141.376907, 145.993119, 150.646117, 155.335327, 160.060199, 164.820202, 169.614826, 174.443577, 179.305980, 184.201575, 189.129918, 194.090580, 199.083145, 204.107210, 209.162385, 214.248292,
219.364564, 224.510845, 229.686789, 234.892058, 240.126328, 245.389280, 250.680604, 256.000000, 261.347174, 266.721841, 272.123723, 277.552547, 283.008049, 288.489971, 293.998060, 299.532071, 305.091761, 310.676898, 316.287249, 321.922592, 327.582707, 333.267377, 338.976394, 344.709550,
350.466646, 356.247482, 362.051866, 367.879608, 373.730522, 379.604427, 385.501143, 391.420496, 397.362314, 403.326427, 409.312672, 415.320884, 421.350905, 427.402579, 433.475750, 439.570269, 445.685987, 451.822757, 457.980436, 464.158883, 470.357960, 476.577530, 482.817459, 489.077615,
495.357868, 501.658090, 507.978156, 514.317941, 520.677324, 527.056184, 533.454404, 539.871867, 546.308458, 552.764065, 559.238575, 565.731879, 572.243870, 578.774440, 585.323483, 591.890898, 598.476581, 605.080431, 611.702349, 618.342238, 625.000000, 631.675540, 638.368763, 645.079578,
}
T.tabs = { [0] = 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 785, 785, 785, 785, 784, 784, 784, 784, 513, 513, 513, 513, 513, 513, 513, 513, 256,
256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -255, 1313, 1298, 1282, 785, 785, 785, 785, 784,
784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 290,
288, -255, 1313, 1298, 1282, 769, 769, 769, 769, 529, 529, 529, 529, 529, 529, 529, 529, 528, 528, 528, 528, 528, 528, 528,
528, 512, 512, 512, 512, 512, 512, 512, 512, 290, 288, -253, -318, -351, -367, 785, 785, 785, 785, 784, 784, 784, 784, 769,
769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 819, 818, 547, 547, 275,
275, 275, 275, 561, 560, 515, 546, 289, 274, 288, 258, -254, -287, 1329, 1299, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 784,
784, 784, 784, 529, 529, 529, 529, 529, 529, 529, 529, 769, 769, 769, 769, 768, 768, 768, 768, 563, 560, 306, 306, 291,
259, -252, -413, -477, -542, 1298, -575, 1041, 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256,
256, 256, 256, 256, 256, 256, 256, 256, 256, -383, -399, 1107, 1092, 1106, 1061, 849, 849, 789, 789, 1104, 1091, 773, 773, 1076,
1075, 341, 340, 325, 309, 834, 804, 577, 577, 532, 532, 516, 516, 832, 818, 803, 816, 561, 561, 531, 531, 515, 546, 289,
289, 288, 258, -252, -429, -493, -559, 1057, 1057, 1042, 1042, 529, 529, 529, 529, 529, 529, 529, 529, 784, 784, 784, 784, 769,
769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, -382, 1077, -415, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029,
1075, 834, 834, 597, 581, 340, 340, 339, 324, 804, 833, 532, 532, 832, 772, 818, 803, 817, 787, 816, 771, 290, 290, 290,
290, 288, 258, -253, -349, -414, -447, -463, 1329, 1299, -479, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 785, 785, 785, 785, 784,
784, 784, 784, 769, 769, 769, 769, 768, 768, 768, 768, -319, 851, 821, -335, 836, 850, 805, 849, 341, 340, 325, 336, 533,
533, 579, 579, 564, 564, 773, 832, 578, 548, 563, 516, 321, 276, 306, 291, 304, 259, -251, -572, -733, -830, -863, -879, 1041,
1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
256, -511, -527, -543, 1396, 1351, 1381, 1366, 1395, 1335, 1380, -559, 1334, 1138, 1138, 1063, 1063, 1350, 1392, 1031, 1031, 1062, 1062, 1364,
1363, 1120, 1120, 1333, 1348, 881, 881, 881, 881, 375, 374, 359, 373, 343, 358, 341, 325, 791, 791, 1123, 1122, -703, 1105, 1045,
-719, 865, 865, 790, 790, 774, 774, 1104, 1029, 338, 293, 323, 308, -799, -815, 833, 788, 772, 818, 803, 816, 322, 292, 307,
320, 561, 531, 515, 546, 289, 274, 288, 258, -251, -525, -605, -685, -765, -831, -846, 1298, 1057, 1057, 1312, 1282, 785, 785, 785,
785, 784, 784, 784, 784, 769, 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, 1399, 1398, 1383, 1367, 1382, 1396, 1351,
-511, 1381, 1366, 1139, 1139, 1079, 1079, 1124, 1124, 1364, 1349, 1363, 1333, 882, 882, 882, 882, 807, 807, 807, 807, 1094, 1094, 1136,
1136, 373, 341, 535, 535, 881, 775, 867, 822, 774, -591, 324, 338, -671, 849, 550, 550, 866, 864, 609, 609, 293, 336, 534,
534, 789, 835, 773, -751, 834, 804, 308, 307, 833, 788, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290, 290, -252,
-397, -477, -557, -622, -653, -719, -735, -750, 1329, 1299, 1314, 1057, 1057, 1042, 1042, 1312, 1282, 1024, 1024, 785, 785, 785, 785, 784,
784, 784, 784, 769, 769, 769, 769, -383, 1127, 1141, 1111, 1126, 1140, 1095, 1110, 869, 869, 883, 883, 1079, 1109, 882, 882, 375,
374, 807, 868, 838, 881, 791, -463, 867, 822, 368, 263, 852, 837, 836, -543, 610, 610, 550, 550, 352, 336, 534, 534, 865,
774, 851, 821, 850, 805, 593, 533, 579, 564, 773, 832, 578, 578, 548, 548, 577, 577, 307, 276, 306, 291, 516, 560, 259,
259, -250, -2107, -2507, -2764, -2909, -2974, -3007, -3023, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256,
256, 256, 256, 256, 256, 256, 256, 256, 256, -767, -1052, -1213, -1277, -1358, -1405, -1469, -1535, -1550, -1582, -1614, -1647, -1662, -1694, -1726,
-1759, -1774, -1807, -1822, -1854, -1886, 1565, -1919, -1935, -1951, -1967, 1731, 1730, 1580, 1717, -1983, 1729, 1564, -1999, 1548, -2015, -2031, 1715, 1595,
-2047, 1714, -2063, 1610, -2079, 1609, -2095, 1323, 1323, 1457, 1457, 1307, 1307, 1712, 1547, 1641, 1700, 1699, 1594, 1685, 1625, 1442, 1442, 1322,
1322, -780, -973, -910, 1279, 1278, 1277, 1262, 1276, 1261, 1275, 1215, 1260, 1229, -959, 974, 974, 989, 989, -943, 735, 478, 478, 495,
463, 506, 414, -1039, 1003, 958, 1017, 927, 942, 987, 957, 431, 476, 1272, 1167, 1228, -1183, 1256, -1199, 895, 895, 941, 941, 1242,
1227, 1212, 1135, 1014, 1014, 490, 489, 503, 487, 910, 1013, 985, 925, 863, 894, 970, 955, 1012, 847, -1343, 831, 755, 755, 984,
909, 428, 366, 754, 559, -1391, 752, 486, 457, 924, 997, 698, 698, 983, 893, 740, 740, 908, 877, 739, 739, 667, 667, 953,
938, 497, 287, 271, 271, 683, 606, 590, 712, 726, 574, 302, 302, 738, 736, 481, 286, 526, 725, 605, 711, 636, 724, 696,
651, 589, 681, 666, 710, 364, 467, 573, 695, 466, 466, 301, 465, 379, 379, 709, 604, 665, 679, 316, 316, 634, 633, 436,
436, 464, 269, 424, 394, 452, 332, 438, 363, 347, 408, 393, 448, 331, 422, 362, 407, 392, 421, 346, 406, 391, 376, 375,
359, 1441, 1306, -2367, 1290, -2383, 1337, -2399, -2415, 1426, 1321, -2431, 1411, 1336, -2447, -2463, -2479, 1169, 1169, 1049, 1049, 1424, 1289, 1412,
1352, 1319, -2495, 1154, 1154, 1064, 1064, 1153, 1153, 416, 390, 360, 404, 403, 389, 344, 374, 373, 343, 358, 372, 327, 357, 342,
311, 356, 326, 1395, 1394, 1137, 1137, 1047, 1047, 1365, 1392, 1287, 1379, 1334, 1364, 1349, 1378, 1318, 1363, 792, 792, 792, 792, 1152,
1152, 1032, 1032, 1121, 1121, 1046, 1046, 1120, 1120, 1030, 1030, -2895, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, 1090, 1060,
1075, 833, 833, 309, 324, 532, 532, 832, 772, 818, 803, 561, 561, 531, 560, 515, 546, 289, 274, 288, 258, -250, -1179, -1579,
-1836, -1996, -2124, -2253, -2333, -2413, -2477, -2542, -2574, -2607, -2622, -2655, 1314, 1313, 1298, 1312, 1282, 785, 785, 785, 785, 1040, 1040, 1025,
1025, 768, 768, 768, 768, -766, -798, -830, -862, -895, -911, -927, -943, -959, -975, -991, -1007, -1023, -1039, -1055, -1070, 1724, 1647, -1103,
-1119, 1631, 1767, 1662, 1738, 1708, 1723, -1135, 1780, 1615, 1779, 1599, 1677, 1646, 1778, 1583, -1151, 1777, 1567, 1737, 1692, 1765, 1722, 1707,
1630, 1751, 1661, 1764, 1614, 1736, 1676, 1763, 1750, 1645, 1598, 1721, 1691, 1762, 1706, 1582, 1761, 1566, -1167, 1749, 1629, 767, 766, 751,
765, 494, 494, 735, 764, 719, 749, 734, 763, 447, 447, 748, 718, 477, 506, 431, 491, 446, 476, 461, 505, 415, 430, 475,
445, 504, 399, 460, 489, 414, 503, 383, 474, 429, 459, 502, 502, 746, 752, 488, 398, 501, 473, 413, 472, 486, 271, 480,
270, -1439, -1455, 1357, -1471, -1487, -1503, 1341, 1325, -1519, 1489, 1463, 1403, 1309, -1535, 1372, 1448, 1418, 1476, 1356, 1462, 1387, -1551, 1475,
1340, 1447, 1402, 1386, -1567, 1068, 1068, 1474, 1461, 455, 380, 468, 440, 395, 425, 410, 454, 364, 467, 466, 464, 453, 269, 409,
448, 268, 432, 1371, 1473, 1432, 1417, 1308, 1460, 1355, 1446, 1459, 1431, 1083, 1083, 1401, 1416, 1458, 1445, 1067, 1067, 1370, 1457, 1051,
1051, 1291, 1430, 1385, 1444, 1354, 1415, 1400, 1443, 1082, 1082, 1173, 1113, 1186, 1066, 1185, 1050, -1967, 1158, 1128, 1172, 1097, 1171, 1081,
-1983, 1157, 1112, 416, 266, 375, 400, 1170, 1142, 1127, 1065, 793, 793, 1169, 1033, 1156, 1096, 1141, 1111, 1155, 1080, 1126, 1140, 898,
898, 808, 808, 897, 897, 792, 792, 1095, 1152, 1032, 1125, 1110, 1139, 1079, 1124, 882, 807, 838, 881, 853, 791, -2319, 867, 368,
263, 822, 852, 837, 866, 806, 865, -2399, 851, 352, 262, 534, 534, 821, 836, 594, 594, 549, 549, 593, 593, 533, 533, 848,
773, 579, 579, 564, 578, 548, 563, 276, 276, 577, 576, 306, 291, 516, 560, 305, 305, 275, 259, -251, -892, -2058, -2620, -2828,
-2957, -3023, -3039, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
256, 256, 256, -511, -527, -543, -559, 1530, -575, -591, 1528, 1527, 1407, 1526, 1391, 1023, 1023, 1023, 1023, 1525, 1375, 1268, 1268, 1103,
1103, 1087, 1087, 1039, 1039, 1523, -604, 815, 815, 815, 815, 510, 495, 509, 479, 508, 463, 507, 447, 431, 505, 415, 399, -734,
-782, 1262, -815, 1259, 1244, -831, 1258, 1228, -847, -863, 1196, -879, 1253, 987, 987, 748, -767, 493, 493, 462, 477, 414, 414, 686,
669, 478, 446, 461, 445, 474, 429, 487, 458, 412, 471, 1266, 1264, 1009, 1009, 799, 799, -1019, -1276, -1452, -1581, -1677, -1757, -1821,
-1886, -1933, -1997, 1257, 1257, 1483, 1468, 1512, 1422, 1497, 1406, 1467, 1496, 1421, 1510, 1134, 1134, 1225, 1225, 1466, 1451, 1374, 1405, 1252,
1252, 1358, 1480, 1164, 1164, 1251, 1251, 1238, 1238, 1389, 1465, -1407, 1054, 1101, -1423, 1207, -1439, 830, 830, 1248, 1038, 1237, 1117, 1223,
1148, 1236, 1208, 411, 426, 395, 410, 379, 269, 1193, 1222, 1132, 1235, 1221, 1116, 976, 976, 1192, 1162, 1177, 1220, 1131, 1191, 963,
963, -1647, 961, 780, -1663, 558, 558, 994, 993, 437, 408, 393, 407, 829, 978, 813, 797, 947, -1743, 721, 721, 377, 392, 844,
950, 828, 890, 706, 706, 812, 859, 796, 960, 948, 843, 934, 874, 571, 571, -1919, 690, 555, 689, 421, 346, 539, 539, 944,
779, 918, 873, 932, 842, 903, 888, 570, 570, 931, 917, 674, 674, -2575, 1562, -2591, 1609, -2607, 1654, 1322, 1322, 1441, 1441, 1696,
1546, 1683, 1593, 1669, 1624, 1426, 1426, 1321, 1321, 1639, 1680, 1425, 1425, 1305, 1305, 1545, 1668, 1608, 1623, 1667, 1592, 1638, 1666, 1320,
1320, 1652, 1607, 1409, 1409, 1304, 1304, 1288, 1288, 1664, 1637, 1395, 1395, 1335, 1335, 1622, 1636, 1394, 1394, 1319, 1319, 1606, 1621, 1392,
1392, 1137, 1137, 1137, 1137, 345, 390, 360, 375, 404, 373, 1047, -2751, -2767, -2783, 1062, 1121, 1046, -2799, 1077, -2815, 1106, 1061, 789,
789, 1105, 1104, 263, 355, 310, 340, 325, 354, 352, 262, 339, 324, 1091, 1076, 1029, 1090, 1060, 1075, 833, 833, 788, 788, 1088,
1028, 818, 818, 803, 803, 561, 561, 531, 531, 816, 771, 546, 546, 289, 274, 288, 258, -253, -317, -381, -446, -478, -509, 1279,
1279, -811, -1179, -1451, -1756, -1900, -2028, -2189, -2253, -2333, -2414, -2445, -2511, -2526, 1313, 1298, -2559, 1041, 1041, 1040, 1040, 1025, 1025, 1024,
1024, 1022, 1007, 1021, 991, 1020, 975, 1019, 959, 687, 687, 1018, 1017, 671, 671, 655, 655, 1016, 1015, 639, 639, 758, 758, 623,
623, 757, 607, 756, 591, 755, 575, 754, 559, 543, 543, 1009, 783, -575, -621, -685, -749, 496, -590, 750, 749, 734, 748, 974,
989, 1003, 958, 988, 973, 1002, 942, 987, 957, 972, 1001, 926, 986, 941, 971, 956, 1000, 910, 985, 925, 999, 894, 970, -1071,
-1087, -1102, 1390, -1135, 1436, 1509, 1451, 1374, -1151, 1405, 1358, 1480, 1420, -1167, 1507, 1494, 1389, 1342, 1465, 1435, 1450, 1326, 1505, 1310,
1493, 1373, 1479, 1404, 1492, 1464, 1419, 428, 443, 472, 397, 736, 526, 464, 464, 486, 457, 442, 471, 484, 482, 1357, 1449, 1434,
1478, 1388, 1491, 1341, 1490, 1325, 1489, 1463, 1403, 1309, 1477, 1372, 1448, 1418, 1433, 1476, 1356, 1462, 1387, -1439, 1475, 1340, 1447, 1402,
1474, 1324, 1461, 1371, 1473, 269, 448, 1432, 1417, 1308, 1460, -1711, 1459, -1727, 1441, 1099, 1099, 1446, 1386, 1431, 1401, -1743, 1289, 1083,
1083, 1160, 1160, 1458, 1445, 1067, 1067, 1370, 1457, 1307, 1430, 1129, 1129, 1098, 1098, 268, 432, 267, 416, 266, 400, -1887, 1144, 1187,
1082, 1173, 1113, 1186, 1066, 1050, 1158, 1128, 1143, 1172, 1097, 1171, 1081, 420, 391, 1157, 1112, 1170, 1142, 1127, 1065, 1169, 1049, 1156,
1096, 1141, 1111, 1155, 1080, 1126, 1154, 1064, 1153, 1140, 1095, 1048, -2159, 1125, 1110, 1137, -2175, 823, 823, 1139, 1138, 807, 807, 384,
264, 368, 263, 868, 838, 853, 791, 867, 822, 852, 837, 866, 806, 865, 790, -2319, 851, 821, 836, 352, 262, 850, 805, 849,
-2399, 533, 533, 835, 820, 336, 261, 578, 548, 563, 577, 532, 532, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290,
290, 288, 258,
}
T.tab32 = { [0] = 130,
162, 193, 209, 44, 28, 76, 140, 9, 9, 9, 9, 9, 9, 9, 9, 190, 254, 222, 238, 126, 94, 157, 157, 109,
61, 173, 205,
}
T.tab33 = { [0] = 252,
236, 220, 204, 188, 172, 156, 140, 124, 108, 92, 76, 60, 44, 28, 12,
}
T.tabindex = { [0] = 0,
32, 64, 98, 0, 132, 180, 218, 292, 364, 426, 538, 648, 746, 0, 1126, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1842,
1842, 1842, 1842, 1842, 1842, 1842, 1842,
}
T.g_linbits = { [0] = 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4,
5, 6, 7, 8, 9, 11, 13,
}
T.g_pan = { [0] = 0,
1, 0.21132487, 0.78867513, 0.36602540, 0.63397460, 0.5, 0.5, 0.63397460, 0.36602540, 0.78867513, 0.21132487, 1, 0,
}
T.g_aa = { [0] = 0.85749293,
0.88174200, 0.94962865, 0.98331459, 0.99551782, 0.99916056, 0.99989920, 0.99999316, 0.51449576, 0.47173197, 0.31337745, 0.18191320, 0.09457419, 0.04096558, 0.01419856, 0.00369997,
}
T.g_twid9 = { [0] = 0.73727734,
0.79335334, 0.84339145, 0.88701083, 0.92387953, 0.95371695, 0.97629601, 0.99144486, 0.99904822, 0.67559021, 0.60876143, 0.53729961, 0.46174861, 0.38268343, 0.30070580, 0.21643961, 0.13052619, 0.04361938,
}
T.g_twid3 = { [0] = 0.79335334,
0.92387953, 0.99144486, 0.60876143, 0.38268343, 0.13052619,
}
T.g_mdct_window = { [0] = 0.99904822,
0.99144486, 0.97629601, 0.95371695, 0.92387953, 0.88701083, 0.84339145, 0.79335334, 0.73727734, 0.04361938, 0.13052619, 0.21643961, 0.30070580, 0.38268343, 0.46174861, 0.53729961, 0.60876143, 0.67559021, 1, 1, 1, 1, 1, 1, 0.99144486,
0.92387953, 0.79335334, 0, 0, 0, 0, 0, 0, 0.13052619, 0.38268343, 0.60876143,
}
T.g_sec = { [0] = 10.19000816,
0.50060302, 0.50241929, 3.40760851, 0.50547093, 0.52249861, 2.05778098, 0.51544732, 0.56694406, 1.48416460, 0.53104258, 0.64682180, 1.16943991, 0.55310392, 0.78815460, 0.97256821, 0.58293498, 1.06067765, 0.83934963, 0.62250412, 1.72244716, 0.74453628, 0.67480832, 5.10114861,
}
T.g_win = { [0] = -1,
26, -31, 208, 218, 401, -519, 2063, 2000, 4788, -5517, 7134, 5959, 35640, -39336, 74992, -1, 24, -35, 202, 222, 347, -581, 2080, 1952,
4425, -5879, 7640, 5288, 33791, -41176, 74856, -1, 21, -38, 196, 225, 294, -645, 2087, 1893, 4063, -6237, 8092, 4561, 31947, -43006, 74630, -1,
19, -41, 190, 227, 244, -711, 2085, 1822, 3705, -6589, 8492, 3776, 30112, -44821, 74313, -1, 17, -45, 183, 228, 197, -779, 2075, 1739,
3351, -6935, 8840, 2935, 28289, -46617, 73908, -1, 16, -49, 176, 228, 153, -848, 2057, 1644, 3004, -7271, 9139, 2037, 26482, -48390, 73415, -2,
14, -53, 169, 227, 111, -919, 2032, 1535, 2663, -7597, 9389, 1082, 24694, -50137, 72835, -2, 13, -58, 161, 224, 72, -991, 2001, 1414,
2330, -7910, 9592, 70, 22929, -51853, 72169, -2, 11, -63, 154, 221, 36, -1064, 1962, 1280, 2006, -8209, 9750, -998, 21189, -53534, 71420, -2,
10, -68, 147, 215, 2, -1137, 1919, 1131, 1692, -8491, 9863, -2122, 19478, -55178, 70590, -3, 9, -73, 139, 208, -29, -1210, 1870, 970,
1388, -8755, 9935, -3300, 17799, -56778, 69679, -3, 8, -79, 132, 200, -57, -1283, 1817, 794, 1095, -8998, 9966, -4533, 16155, -58333, 68692, -4,
7, -85, 125, 189, -83, -1356, 1759, 605, 814, -9219, 9959, -5818, 14548, -59838, 67629, -4, 7, -91, 117, 177, -106, -1428, 1698, 402,
545, -9416, 9916, -7154, 12980, -61289, 66494, -5, 6, -97, 111, 163, -127, -1498, 1634, 185, 288, -9585, 9838, -8540, 11455, -62684, 65290,
}
return T
+315
View File
@@ -0,0 +1,315 @@
--!strict
--!optimize 2
-- audio/mp3/Tags: ID3 tags: ID3v2.2 / 2.3 / 2.4 at the start (text frames, COMM, unsynchronisation, extended header) and ID3v1 /
-- ID3v1.1 at the end; APEv2 tags are only skipped. Also finds the byte range that holds the audio, the same way
-- minimp3_ex does (mp3dec_skip_id3). Text is returned as UTF-8. Never throws: malformed tags are cut short.
local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift
local ru8 = buffer.readu8
local Tags = {}
-- ID3v1 genres 0..147 (the original 80 + the Winamp extensions)
local GENRES = {
[0] = "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal",
"New Age", "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative",
"Ska", "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk",
"Fusion", "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise",
"AlternRock", "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic",
"Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock",
"Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret",
"New Wave", "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka",
"Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock", "National Folk", "Swing", "Fast Fusion",
"Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock",
"Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour",
"Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus", "Porn Groove",
"Satire", "Slow Jam", "Club", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul",
"Freestyle", "Duet", "Punk Rock", "Drum Solo", "A capella", "Euro-House", "Dance Hall", "Goa", "Drum & Bass",
"Club-House", "Hardcore", "Terror", "Indie", "BritPop", "Negerpunk", "Polsk Punk", "Beat",
"Christian Gangsta Rap", "Heavy Metal", "Black Metal", "Crossover", "Contemporary Christian", "Christian Rock",
"Merengue", "Salsa", "Thrash Metal", "Anime", "JPop", "Synthpop",
}
Tags.GENRES = GENRES
-- frame id -> field name (v2.3/2.4 ids and their v2.2 equivalents)
local FIELDS = {
TIT2 = "title", TT2 = "title",
TPE1 = "artist", TP1 = "artist",
TALB = "album", TAL = "album",
TPE2 = "albumArtist", TP2 = "albumArtist",
TYER = "year", TYE = "year", TDRC = "year",
TRCK = "track", TRK = "track",
TPOS = "disc", TPA = "disc",
TCON = "genre", TCO = "genre",
TCOM = "composer", TCM = "composer",
COMM = "comment", COM = "comment",
}
local function utf8char(cp: number): string
if cp < 0 or cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then
cp = 0xFFFD
end
return utf8.char(cp)
end
-- bytes [i, j) of b, decoded from ID3 text encoding enc (0 latin-1, 1 UTF-16 + BOM, 2 UTF-16BE, 3 UTF-8)
local function decodeText(b: buffer, i: number, j: number, enc: number): string
local out = {}
if enc == 1 or enc == 2 then
local le = false
if enc == 1 and j - i >= 2 then
local b0, b1 = ru8(b, i), ru8(b, i + 1)
if b0 == 0xFF and b1 == 0xFE then
le = true
i += 2
elseif b0 == 0xFE and b1 == 0xFF then
i += 2
else
le = true -- no BOM: assume little-endian (what most taggers write)
end
end
local pending = 0
while i + 1 < j do
local u = if le then bor(ru8(b, i), lshift(ru8(b, i + 1), 8)) else bor(lshift(ru8(b, i), 8), ru8(b, i + 1))
i += 2
if u >= 0xD800 and u <= 0xDBFF then
pending = u
else
if u >= 0xDC00 and u <= 0xDFFF and pending ~= 0 then
u = 0x10000 + lshift(pending - 0xD800, 10) + (u - 0xDC00)
end
pending = 0
table.insert(out, if u == 0 then "\0" else utf8char(u))
end
end
elseif enc == 3 then
local s = buffer.readstring(b, i, j - i)
if utf8.len(s) then
return s
end
enc = 0 -- invalid UTF-8: fall back to latin-1
end
if enc == 0 then
for k = i, j - 1 do
local c = ru8(b, k)
table.insert(out, if c < 0x80 then string.char(c) else utf8char(c))
end
end
return table.concat(out)
end
-- trim trailing NULs / spaces, join multi-value NUL separators with " / "
local function clean(s: string): string
s = string.gsub(s, "[%z%s]+$", "")
s = string.gsub(s, "%z+", " / ")
return s
end
-- "(17)", "(17)Rock", "17" -> "Rock"
local function genreName(s: string): string
local n = tonumber(string.match(s, "^%((%d+)%)$") or string.match(s, "^(%d+)$"))
if n and GENRES[n] then
return GENRES[n]
end
local rest = string.match(s, "^%(%d+%)(.+)$")
return rest or s
end
local function syncsafe(b: buffer, o: number): number
return bor(lshift(band(ru8(b, o), 0x7F), 21), lshift(band(ru8(b, o + 1), 0x7F), 14), lshift(band(ru8(b, o + 2), 0x7F), 7), band(ru8(b, o + 3), 0x7F))
end
local function be32(b: buffer, o: number): number
return bor(lshift(ru8(b, o), 24), lshift(ru8(b, o + 1), 16), lshift(ru8(b, o + 2), 8), ru8(b, o + 3))
end
-- undo unsynchronisation (FF 00 -> FF) of b[i, j) into a new buffer
local function deunsync(b: buffer, i: number, j: number): buffer
local out = buffer.create(math.max(0, j - i))
local n = 0
local k = i
while k < j do
local c = ru8(b, k)
buffer.writeu8(out, n, c)
n += 1
k += if c == 0xFF and k + 1 < j and ru8(b, k + 1) == 0 then 2 else 1
end
local r = buffer.create(n)
buffer.copy(r, 0, out, 0, n)
return r
end
-- minimp3's ID3v2 detection: total tag size (header + body + footer) or 0
function Tags.id3v2Size(b: buffer, o: number, len: number): number
if len - o < 10 or buffer.readstring(b, o, 3) ~= "ID3" then
return 0
end
if band(ru8(b, o + 5), 15) ~= 0 then
return 0
end
for k = 6, 9 do
if band(ru8(b, o + k), 0x80) ~= 0 then
return 0
end
end
local size = syncsafe(b, o + 6) + 10
if band(ru8(b, o + 5), 16) ~= 0 then
size += 10
end
return size
end
local function setField(tags: any, id: string, text: string)
tags.raw[id] = text
local f = FIELDS[id]
if f and tags[f] == nil and text ~= "" then
tags[f] = if f == "genre" then genreName(text) else text
end
end
-- parse an ID3v2 tag at b[o ..] (o .. o + size within the buffer) into tags
local function parseV2(b: buffer, o: number, size: number, tags: any)
local ver = ru8(b, o + 3)
local flags = ru8(b, o + 5)
if ver < 2 or ver > 4 then
return
end
tags.id3v2 = "2." .. ver
local bodyEnd = math.min(o + 10 + syncsafe(b, o + 6), buffer.len(b))
local body = b
local p, e = o + 10, bodyEnd
if band(flags, 0x80) ~= 0 and ver < 4 then
body = deunsync(b, p, e)
p, e = 0, buffer.len(body)
end
if band(flags, 0x40) ~= 0 and ver >= 3 and p + 4 <= e then
-- extended header: v2.3 size excludes its own 4 bytes, v2.4 includes them (syncsafe)
p += if ver == 3 then be32(body, p) + 4 else syncsafe(body, p)
end
local hdr = if ver == 2 then 6 else 10
while p + hdr <= e do
local c0 = ru8(body, p)
if c0 == 0 then
break -- padding
end
local id, fsize, fflags
if ver == 2 then
id = buffer.readstring(body, p, 3)
fsize = bor(lshift(ru8(body, p + 3), 16), lshift(ru8(body, p + 4), 8), ru8(body, p + 5))
fflags = 0
else
id = buffer.readstring(body, p, 4)
fsize = if ver == 4 then syncsafe(body, p + 4) else be32(body, p + 4)
fflags = bor(lshift(ru8(body, p + 8), 8), ru8(body, p + 9))
end
if not string.match(id, "^[A-Z0-9]+$") or fsize <= 0 or p + hdr + fsize > e then
break
end
local fs, fe = p + hdr, p + hdr + fsize
local fb = body
local skip = false
if ver == 3 then
skip = band(fflags, 0x00C0) ~= 0 -- compressed / encrypted
elseif ver == 4 then
skip = band(fflags, 0x000C) ~= 0
if not skip and band(fflags, 0x0001) ~= 0 then
fs += 4 -- data length indicator
end
if not skip and band(fflags, 0x0002) ~= 0 and fs < fe then
fb = deunsync(body, fs, fe)
fs, fe = 0, buffer.len(fb)
end
end
if not skip and fs < fe then
local first = string.sub(id, 1, 1)
local enc = ru8(fb, fs)
if first == "T" and id ~= "TXXX" and id ~= "TXX" then
setField(tags, id, clean(decodeText(fb, fs + 1, fe, enc)))
elseif (id == "COMM" or id == "COM") and fe - fs >= 4 then
-- encoding, language[3], short description (NUL-terminated in the encoding), text
local q = fs + 4
local wide = enc == 1 or enc == 2
while q < fe do
if wide then
if q + 1 < fe and ru8(fb, q) == 0 and ru8(fb, q + 1) == 0 then
q += 2
break
end
q += 2
else
if ru8(fb, q) == 0 then
q += 1
break
end
q += 1
end
end
if q <= fe then
setField(tags, id, clean(decodeText(fb, q, fe, enc)))
end
end
end
p += hdr + fsize
end
end
local function v1String(b: buffer, o: number, n: number): string
return (string.gsub(decodeText(b, o, o + n, 0), "[%z%s]+$", ""))
end
-- Parses tags and returns (tags, audio start, audio end) for the buffer b.
-- tags = { title?, artist?, album?, albumArtist?, year?, track?, disc?, genre?, composer?, comment?,
-- raw = { [frame id] = text }, id3v2 = "2.3"?, id3v1 = true? }
function Tags.parse(b: buffer): (any, number, number)
local len = buffer.len(b)
local tags: any = { raw = {} }
local start, stop = 0, len
local v2 = Tags.id3v2Size(b, 0, len)
if v2 > 0 then
pcall(parseV2, b, 0, v2, tags)
start = math.min(v2, len)
end
-- mp3dec_skip_id3v1 on what follows the ID3v2 tag
local size = stop - start
if size >= 128 and buffer.readstring(b, start + size - 128, 3) == "TAG" then
local o = start + size - 128
tags.id3v1 = true
local v1 = {
title = v1String(b, o + 3, 30),
artist = v1String(b, o + 33, 30),
album = v1String(b, o + 63, 30),
year = v1String(b, o + 93, 4),
}
if ru8(b, o + 125) == 0 and ru8(b, o + 126) ~= 0 then
v1.comment = v1String(b, o + 97, 28)
v1.track = tostring(ru8(b, o + 126))
else
v1.comment = v1String(b, o + 97, 30)
end
local g = ru8(b, o + 127)
if GENRES[g] then
v1.genre = GENRES[g]
end
for k, v in v1 do
if tags[k] == nil and v ~= "" then
tags[k] = v
end
end
size -= 128
if size >= 227 and buffer.readstring(b, start + size - 227, 4) == "TAG+" then
size -= 227
end
end
if size > 32 and buffer.readstring(b, start + size - 32, 8) == "APETAGEX" then
size -= 32
local t = start + size + 12
local tagSize = bor(ru8(b, t), lshift(ru8(b, t + 1), 8), lshift(ru8(b, t + 2), 16), lshift(ru8(b, t + 3), 24))
if size >= tagSize then
size -= tagSize
end
tags.ape = true
end
stop = start + size
return tags, start, stop
end
return Tags
+130
View File
@@ -0,0 +1,130 @@
--!strict
-- audio/mp3: MPEG audio (ISO/IEC 11172-3, 13818-3; MPEG-2.5), layers I, II and III. Absorbed from mp3-luau c755bbf
-- (same author; a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt). Supports: decode of MPEG-1 / 2 / 2.5
-- layers I / II / III, mono / stereo / joint stereo / dual channel, CBR / VBR / free format, gapless playback (Xing /
-- Info + LAME delay and padding), exact length and sample-accurate seeking from a frame index built on open, resync
-- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped).
-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Not supported: encoding (see the mp3 encoder in the
-- audio workstream), MPEG-2 multichannel extension, CRC checks.
--
-- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay,
-- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll())
-- local audio = Mp3.decode(Bytes.reader(buf)) -- a Types.Audio (the whole file)
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Header = require("@formats/audio/mp3/Header")
local Index = require("@formats/audio/mp3/Index")
local Tags = require("@formats/audio/mp3/Tags")
local Stream = require("@formats/audio/mp3/Stream")
-- ------------------------------------------------------------------------------------------------ contract
local Mp3 = {
name = "mp3",
category = "audio",
extensions = { "mp3", "mp2", "mp1", "mpga" },
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = false, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31)
}
export type Decoder = Stream.Decoder
-- ------------------------------------------------------------------------------------------------ constants
local MAX_FRAMES = 2 ^ 31
-- ------------------------------------------------------------------------------------------------ sniff
-- an ID3v2 tag and / or a valid frame header at the start, more when the next frame chains on
function Mp3.sniff(r: Bytes.Reader): number
local b, p, lim = r.buf, r.pos, r.limit
local id3 = false
for _ = 1, 4 do -- (ffmpeg writes a tag even when the input had one: tags can follow each other)
local n = if p + 3 <= lim and buffer.readstring(b, p, 3) == "ID3" then Tags.id3v2Size(b, p, lim) else 0
if n <= 0 then
break
end
id3 = true
p += n
end
if p + 4 > lim or not Header.valid(b, p) then
return if id3 then 0.5 else 0
end
local fb = Header.frameBytes(b, p, 0)
if fb > 0 then
fb += Header.padding(b, p)
if p + fb + 4 <= lim and Header.compare(b, p, p + fb) then
return 0.9
end
if p + fb == lim then
return 0.6
end
end
return if id3 then 0.7 else 0.25
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts) -> Types.Audio (the whole stream, through open)
function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Mp3.open(r, opts)
if not dec then
return nil, err
end
local a = Types.Audio.new(dec.sampleRate, dec.channels, dec.frames)
local _, n = dec:read(dec.frames, a.samples)
if n < dec.frames then
return nil, Err.new(Err.CORRUPT, string.format("decoded %d of %d frames", n, dec.frames))
end
a.tags = dec.tags
a.meta.source = { format = "mp3", layer = dec.layer, version = dec.version, bitrate = dec.bitrate, vbr = dec.vbr }
return a, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- the string-valued tag fields (title, artist, album, albumArtist, year, track, disc, genre, composer, comment)
local function stringTags(t: any): { [string]: string }
local out: { [string]: string } = {}
for k, v in t do
if type(k) == "string" and type(v) == "string" and k ~= "id3v2" then
out[k] = v
end
end
return out
end
-- open(r, opts) -> the streaming Decoder (Types.Decoder) | nil, Err
function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?)
local b = r.buf
if r.base ~= 0 or r.limit ~= buffer.len(b) then
b = buffer.create(r.limit - r.base) -- the core indexes from offset 0
buffer.copy(b, 0, r.buf, r.base, r.limit - r.base)
end
local okTags, tags, start, stop = pcall(Tags.parse, b)
if not okTags then
tags, start, stop = { raw = {} }, 0, buffer.len(b)
end
local idx = Index.build(b, start, stop)
if not idx then
return nil, Err.new(Err.CORRUPT, "no MPEG audio frames found")
end
local dec = Stream.new(b, idx, stringTags(tags), {
raw = tags.raw,
id3v2 = tags.id3v2,
id3v1 = tags.id3v1 == true,
ape = tags.ape == true,
})
if dec.frames > (opts and opts.maxFrames or MAX_FRAMES) then
return nil, Err.new(Err.LIMIT, string.format("%d sample frames is over the limit", dec.frames))
end
return dec, nil
end
-- ------------------------------------------------------------------------------------------------ extras
Mp3.Tags = Tags -- Tags.parse(buf) -> (tags, audio start, audio end)
return Mp3
File diff suppressed because it is too large. Load diff
+58
View File
@@ -0,0 +1,58 @@
--!strict
-- audio/opus/CeltTables: Generated from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, see licenses/). 1-based arrays.
return {
logN400 = {
0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36,
},
cache_index50 = {
-1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41, 82, 82, 123, 164, 200, 222, 0, 0, 0,
0, 0, 0, 0, 0, 41, 41, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, 41, 41, 41, 41, 41, 41,
41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305, 318, 328, 336, 123, 123, 123, 123, 123, 123, 123, 123, 240,
240, 240, 240, 305, 305, 305, 318, 318, 343, 351, 358, 364, 240, 240, 240, 240, 240, 240, 240, 240, 305, 305, 305, 305,
343, 343, 343, 351, 351, 370, 376, 382, 387,
},
cache_bits50 = {
40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28, 31, 34, 36,
38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50, 51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62,
63, 63, 65, 66, 67, 68, 69, 70, 71, 71, 40, 20, 33, 41, 48, 53, 57, 61, 64, 66, 69, 71, 73, 75,
76, 78, 80, 82, 85, 87, 89, 91, 92, 94, 96, 98, 101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123,
124, 126, 128, 40, 23, 39, 51, 60, 67, 73, 79, 83, 87, 91, 94, 97, 100, 102, 105, 107, 111, 115, 118, 121,
124, 126, 129, 131, 135, 139, 142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35, 28, 49, 65,
78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149, 153, 159, 165, 171, 176, 180, 185, 189, 192, 199, 205, 211,
216, 220, 225, 229, 232, 239, 245, 251, 21, 33, 58, 79, 97, 112, 125, 137, 148, 157, 166, 174, 182, 189, 195, 201,
207, 217, 227, 235, 243, 251, 17, 35, 63, 86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250,
25, 31, 55, 75, 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180, 185, 190, 200, 208, 215, 222, 229, 235, 240,
245, 255, 16, 36, 65, 89, 110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, 11, 41, 74, 103, 128,
151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138, 163, 186, 207, 227, 246, 12, 39, 71, 99, 123, 144, 164,
182, 198, 214, 228, 241, 253, 9, 44, 81, 113, 142, 168, 192, 214, 235, 255, 7, 49, 90, 127, 160, 191, 220, 247,
6, 51, 95, 134, 170, 203, 234, 7, 47, 87, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57,
106, 151, 192, 231, 5, 59, 111, 158, 202, 243, 5, 55, 103, 147, 187, 224, 5, 60, 113, 161, 206, 248, 4, 65,
122, 175, 224, 4, 67, 127, 182, 234,
},
cache_caps50 = {
224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224,
224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, 160, 160, 160, 160, 160, 160,
160, 160, 185, 185, 185, 185, 193, 193, 193, 183, 183, 172, 138, 64, 38, 240, 240, 240, 240, 240, 240, 240, 240, 207,
207, 207, 207, 204, 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185, 185, 185, 193, 193, 193, 193,
193, 193, 193, 183, 183, 172, 138, 65, 39, 207, 207, 207, 207, 207, 207, 207, 207, 204, 204, 204, 204, 201, 201, 201,
188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 194, 194, 194, 184, 184, 173,
139, 65, 39, 204, 204, 204, 204, 204, 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175, 140, 66, 40,
},
e_prob_model = {
72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79, 92, 78, 90, 79,
116, 41, 115, 40, 114, 40, 132, 26, 132, 26, 145, 17, 161, 12, 176, 10, 177, 11, 24, 179, 48, 138, 54, 135,
54, 132, 53, 134, 56, 133, 55, 132, 55, 132, 61, 114, 70, 96, 74, 88, 75, 88, 87, 74, 89, 66, 91, 67,
100, 59, 108, 50, 120, 40, 122, 37, 97, 43, 78, 50, 83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73,
93, 74, 93, 74, 109, 40, 114, 36, 117, 34, 117, 34, 143, 17, 145, 18, 146, 19, 162, 12, 165, 10, 178, 7,
189, 6, 190, 8, 177, 9, 23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, 73, 91, 78, 89,
86, 80, 92, 66, 93, 64, 102, 59, 103, 60, 104, 60, 117, 52, 123, 44, 138, 35, 133, 31, 97, 38, 77, 45,
61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, 112, 38, 124, 26, 132, 27, 136, 19, 140, 20,
155, 14, 159, 16, 158, 18, 170, 13, 177, 10, 187, 8, 192, 6, 175, 9, 159, 10, 21, 178, 59, 110, 71, 86,
75, 85, 84, 83, 91, 66, 88, 73, 87, 72, 92, 75, 98, 72, 105, 58, 107, 54, 115, 52, 114, 55, 112, 56,
129, 51, 132, 40, 150, 33, 140, 29, 98, 35, 77, 42, 42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32,
120, 36, 119, 33, 127, 33, 134, 34, 139, 21, 147, 23, 152, 20, 158, 25, 154, 26, 166, 21, 173, 16, 184, 13,
184, 10, 150, 13, 139, 15, 22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, 96, 67, 101, 73,
107, 72, 113, 55, 118, 52, 125, 52, 118, 52, 117, 55, 135, 49, 137, 39, 157, 32, 145, 29, 97, 33, 77, 40,
},
}
+466
View File
@@ -0,0 +1,466 @@
--!strict
--!native
--!optimize 2
-- audio/opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching
-- between SILK, hybrid and CELT, the redundant CELT frames of mode transitions, cross-fades, PLC fallbacks, the
-- multi-frame packet loop and multistream (channel mapping) decoding. Output is 48 kHz float in Luau arrays.
local RD = require("@formats/audio/opus/RangeDecoder")
local Packet = require("@formats/audio/opus/Packet")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
local Decoder = {}
local MODE_SILK, MODE_HYBRID, MODE_CELT = Packet.MODE_SILK_ONLY, Packet.MODE_HYBRID, Packet.MODE_CELT_ONLY
local BW_NB, BW_MB, BW_WB, BW_SWB = Packet.BW_NB, Packet.BW_MB, Packet.BW_WB, Packet.BW_SWB
local F20, F10, F5, F2_5 = 960, 480, 240, 120
local min, max = math.min, math.max
local readu8 = buffer.readu8
local WINDOW = Celt.window
local TRANS = table.create(F5 * 2, 0)
local REDUND = table.create(F5 * 2, 0)
local SILKTMP = table.create(F10 * 2, 0)
local SILENCE = buffer.create(2)
buffer.writeu8(SILENCE, 0, 0xFF)
buffer.writeu8(SILENCE, 1, 0xFF)
local EMPTY_EC = RD.new(buffer.create(0), 0, 0)
local OFFS = table.create(48, 0)
local SIZES = table.create(48, 0)
export type State = {
channels: number,
celt: any,
silk: any,
ctrl: any,
stream_channels: number,
frame_size: number,
mode: number,
bandwidth: number,
prev_mode: number,
prev_redundancy: boolean,
last_packet_duration: number,
rangeFinal: number,
}
function Decoder.new(channels: number): State
return {
channels = channels,
celt = Celt.new(channels),
silk = Silk.new(channels),
ctrl = {
nChannelsAPI = channels,
nChannelsInternal = channels,
API_sampleRate = 48000,
internalSampleRate = 16000,
payloadSize_ms = 20,
},
stream_channels = channels,
frame_size = 120,
mode = 0,
bandwidth = 0,
prev_mode = 0,
prev_redundancy = false,
last_packet_duration = 0,
rangeFinal = 0,
}
end
function Decoder.reset(st: State)
Celt.reset(st.celt)
Silk.reset(st.silk)
st.stream_channels = st.channels
st.frame_size = 120
st.mode = 0
st.bandwidth = 0
st.prev_mode = 0
st.prev_redundancy = false
st.last_packet_duration = 0
st.rangeFinal = 0
end
-- out = w^2 * in2 + (1 - w^2) * in1 over `overlap` samples per channel
local function smoothFade(in1: { number }, b1: number, in2: { number }, b2: number, out: { number }, bo: number, overlap: number, ch: number)
for c = 0, ch - 1 do
for i = 0, overlap - 1 do
local w = WINDOW[i + 1]
w *= w
local k = i * ch + c
out[bo + k] = w * in2[b2 + k] + (1 - w) * in1[b1 + k]
end
end
end
local function decodeFrame(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number
local ch = st.channels
local celt = st.celt
if frameSize < F2_5 then
return -2
end
frameSize = min(frameSize, 2880)
local data = buf
if len <= 1 then
data = nil
frameSize = min(frameSize, st.frame_size)
end
local audiosize, mode, bandwidth
local dec = EMPTY_EC
if data then
audiosize = st.frame_size
mode = st.mode
bandwidth = st.bandwidth
dec = RD.new(data, off, len)
else
audiosize = frameSize
mode = if st.prev_redundancy then MODE_CELT else st.prev_mode
bandwidth = 0
if mode == 0 then
for i = 0, audiosize * ch - 1 do
pcm[pbase + i] = 0
end
return audiosize
end
if audiosize > F20 then
repeat
local ret = decodeFrame(st, nil, 0, 0, pcm, pbase, min(audiosize, F20))
if ret < 0 then
return ret
end
pbase += ret * ch
audiosize -= ret
until audiosize <= 0
return frameSize
elseif audiosize < F20 then
if audiosize > F10 then
audiosize = F10
elseif mode ~= MODE_SILK and audiosize > F5 and audiosize < F10 then
audiosize = F5
end
end
end
local celtAccum = mode ~= MODE_CELT
local transition = false
if data and st.prev_mode > 0
and ((mode == MODE_CELT and st.prev_mode ~= MODE_CELT and not st.prev_redundancy)
or (mode ~= MODE_CELT and st.prev_mode == MODE_CELT)) then
transition = true
end
if transition and mode == MODE_CELT then
decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize))
end
if audiosize > frameSize then
return -1
end
frameSize = audiosize
-- SILK
if mode ~= MODE_CELT then
local tooSmall = frameSize < F10
local sarr, sbase = pcm, pbase
if tooSmall then
sarr, sbase = SILKTMP, 1
end
if st.prev_mode == MODE_CELT then
Silk.reset(st.silk)
end
local ctrl = st.ctrl
ctrl.payloadSize_ms = max(10, 1000 * audiosize // 48000)
if data then
ctrl.nChannelsInternal = st.stream_channels
if mode == MODE_SILK then
ctrl.internalSampleRate = if bandwidth == BW_NB then 8000 elseif bandwidth == BW_MB then 12000 else 16000
else
ctrl.internalSampleRate = 16000
end
end
local lost = if data == nil then 1 else 0
local decoded = 0
repeat
local ret, n = Silk.decode(st.silk, ctrl, lost, decoded == 0, dec, sarr, sbase + decoded * ch)
if ret ~= 0 or n <= 0 then
if lost ~= 0 or n <= 0 then
n = frameSize - decoded
for i = 0, n * ch - 1 do
sarr[sbase + decoded * ch + i] = 0
end
else
return -3
end
end
decoded += n
until decoded >= frameSize
if tooSmall then
for i = 0, frameSize * ch - 1 do
pcm[pbase + i] = SILKTMP[i + 1]
end
end
end
local startBand = 0
local redundancy, celtToSilk = false, false
local redundancyBytes = 0
if mode ~= MODE_CELT and data and RD.tell(dec) + 17 + (if mode == MODE_HYBRID then 20 else 0) <= 8 * len then
if mode == MODE_HYBRID then
redundancy = RD.bitLogp(dec, 12)
else
redundancy = true
end
if redundancy then
celtToSilk = RD.bitLogp(dec, 1)
redundancyBytes = if mode == MODE_HYBRID then RD.uint(dec, 256) + 2 else len - bit32.rshift(RD.tell(dec) + 7, 3)
len -= redundancyBytes
if len * 8 < RD.tell(dec) then
len = 0
redundancyBytes = 0
redundancy = false
end
dec.storage -= redundancyBytes
end
end
if mode ~= MODE_CELT then
startBand = 17
end
if redundancy then
transition = false
end
if transition and mode ~= MODE_CELT then
decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize))
end
if bandwidth ~= 0 then
celt["end"] = if bandwidth == BW_NB then 13 elseif bandwidth == BW_MB or bandwidth == BW_WB then 17 elseif bandwidth == BW_SWB then 19 else 21
end
celt.stream_channels = st.stream_channels
local redundantRng = 0
if redundancy and celtToSilk then
celt.start = 0
Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false)
redundantRng = celt.rng
end
celt.start = startBand
local celtRet = 0
if mode ~= MODE_SILK then
local celtFrameSize = min(F20, frameSize)
if mode ~= st.prev_mode and st.prev_mode > 0 and not st.prev_redundancy then
Celt.reset(celt)
end
celtRet = Celt.decode(celt, data, off, len, pcm, pbase, celtFrameSize, if data then dec else nil, celtAccum)
st.rangeFinal = celt.rng
else
if st.prev_mode == MODE_HYBRID and not (redundancy and celtToSilk and st.prev_redundancy) then
celt.start = 0
Celt.decode(celt, SILENCE, 0, 2, pcm, pbase, F2_5, nil, celtAccum)
end
st.rangeFinal = if data then dec.rng else 0
end
if redundancy and not celtToSilk then
Celt.reset(celt)
celt.start = 0
Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false)
redundantRng = celt.rng
local b = pbase + ch * (frameSize - F2_5)
smoothFade(pcm, b, REDUND, 1 + ch * F2_5, pcm, b, F2_5, ch)
end
if redundancy and celtToSilk and (st.prev_mode ~= MODE_SILK or st.prev_redundancy) then
for i = 0, F2_5 * ch - 1 do
pcm[pbase + i] = REDUND[1 + i]
end
smoothFade(REDUND, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch)
end
if transition then
if audiosize >= F5 then
for i = 0, ch * F2_5 - 1 do
pcm[pbase + i] = TRANS[1 + i]
end
smoothFade(TRANS, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch)
else
smoothFade(TRANS, 1, pcm, pbase, pcm, pbase, F2_5, ch)
end
end
if len <= 1 then
st.rangeFinal = 0
else
st.rangeFinal = bit32.bxor(st.rangeFinal, redundantRng)
end
st.prev_mode = mode
st.prev_redundancy = redundancy and not celtToSilk
if celtRet < 0 then
return celtRet
end
return audiosize
end
-- opus_decode_native: 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).
function Decoder.decode(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, selfDelimited: boolean?): (number, number)
local ch = st.channels
if buf == nil or len == 0 then
if frameSize % 120 ~= 0 then
return -1, 0
end
local count = 0
repeat
local ret = decodeFrame(st, nil, 0, 0, pcm, pbase + count * ch, frameSize - count)
if ret <= 0 then
return if ret < 0 then ret else -3, 0
end
count += ret
until count >= frameSize
st.last_packet_duration = count
return count, 0
end
local b = buf :: buffer
local toc = readu8(b, off)
local packetMode = Packet.mode(toc)
local packetBandwidth = Packet.bandwidth(toc)
local packetFrameSize = Packet.samplesPerFrame(toc, 48000)
local packetChannels = Packet.channels(toc)
local count, _, packetOffset = Packet.parse(b, off, len, OFFS, SIZES, selfDelimited)
if count < 0 then
return -4, 0
end
if count * packetFrameSize > frameSize then
return -2, 0
end
st.mode = packetMode
st.bandwidth = packetBandwidth
st.frame_size = packetFrameSize
st.stream_channels = packetChannels
local nb = 0
for i = 1, count do
local ret = decodeFrame(st, b, OFFS[i], SIZES[i], pcm, pbase + nb * ch, frameSize - nb)
if ret < 0 then
return ret, 0
end
nb += ret
end
st.last_packet_duration = nb
return nb, packetOffset
end
-- ---------------------------------------------------------------------------------------------------------------
-- multistream (channel mapping families 0 / 1 / 255)
export type MS = {
channels: number,
streams: number,
coupled: number,
mapping: { number },
decoders: { State },
tmp: { number },
}
function Decoder.newMultistream(channels: number, streams: number, coupled: number, mapping: { number }): MS
local decs = {}
for s = 0, streams - 1 do
decs[s + 1] = Decoder.new(if s < coupled then 2 else 1)
end
return {
channels = channels,
streams = streams,
coupled = coupled,
mapping = mapping,
decoders = decs,
tmp = table.create(5760 * 2, 0),
}
end
function Decoder.resetMultistream(ms: MS)
for _, d in ms.decoders do
Decoder.reset(d)
end
end
-- copies channel `sc` of src (stride sstride) into every output channel mapped to stream channel index `id`
local function copyOut(ms: MS, id: number, src: { number }, sc: number, sstride: number, pcm: { number }, pbase: number, n: number)
local nch = ms.channels
for c = 0, nch - 1 do
if ms.mapping[c + 1] == id then
local o = pbase + c
local s = 1 + sc
for _ = 1, n do
pcm[o] = src[s]
o += nch
s += sstride
end
end
end
end
-- opus_multistream_decode_native (float). Returns the samples per channel, or < 0 on error.
function Decoder.decodeMultistream(ms: MS, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number
local doPlc = buf == nil or len == 0
frameSize = min(frameSize, 5760)
if not doPlc and len < 2 * ms.streams - 1 then
return -4
end
local tmp = ms.tmp
for s = 0, ms.streams - 1 do
local d = ms.decoders[s + 1]
if not doPlc and len <= 0 then
return -3
end
local ret, packetOffset = Decoder.decode(d, if doPlc then nil else buf, off, if doPlc then 0 else len, tmp, 1, frameSize, s ~= ms.streams - 1)
if not doPlc then
off += packetOffset
len -= packetOffset
end
if ret <= 0 then
return if ret < 0 then ret else -3
end
frameSize = ret
if s < ms.coupled then
copyOut(ms, s * 2, tmp, 0, 2, pcm, pbase, frameSize)
copyOut(ms, s * 2 + 1, tmp, 1, 2, pcm, pbase, frameSize)
else
copyOut(ms, s + ms.coupled, tmp, 0, 1, pcm, pbase, frameSize)
end
end
local nch = ms.channels
for c = 0, nch - 1 do
if ms.mapping[c + 1] == 255 then
local o = pbase + c
for _ = 1, frameSize do
pcm[o] = 0
o += nch
end
end
end
return frameSize
end
-- writes src[base + 1 .. base + count] * gain to out as f32 from byte offset o
function Decoder.writeF32(src: { number }, base: number, count: number, gain: number, out: buffer, o: number)
local writef32 = buffer.writef32
if gain == 1 then
for i = base + 1, base + count do
writef32(out, o, src[i])
o += 4
end
else
for i = base + 1, base + count do
writef32(out, o, src[i] * gain)
o += 4
end
end
end
-- 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: { number }, base: number, n: number, srcCh: number, matrix: { number }, gain: number, out: buffer, o: number)
local writef32 = buffer.writef32
local p = base
for _ = 1, n do
local l, r = 0, 0
for c = 0, srcCh - 1 do
local v = src[p + c + 1]
l += v * matrix[c * 2 + 1]
r += v * matrix[c * 2 + 2]
end
writef32(out, o, l * gain)
writef32(out, o + 4, r * gain)
o += 8
p += srcCh
end
end
return Decoder
+342
View File
@@ -0,0 +1,342 @@
--!strict
--!native
--!optimize 2
-- audio/opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the
-- 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.
local Mdct = {}
local sin, cos, pi = math.sin, math.cos, math.pi
type Plan = {
n: number, -- FFT size (N / 4)
factors: { number },
bitrev: { number },
twr: { number },
twi: { number },
trig: { number }, -- MDCT twiddles: (-sin, cos) pairs, N / 2 values
fr: { number },
fi: { number },
}
local FACTORS = {
[0] = { 5, 96, 3, 32, 4, 8, 2, 4, 4, 1 },
[1] = { 5, 48, 3, 16, 4, 4, 4, 1 },
[2] = { 5, 24, 3, 8, 2, 4, 4, 1 },
[3] = { 5, 12, 3, 4, 4, 1 },
}
local function bitrevTable(f: { number }, fout: number, fpos: number, fstride: number, factors: { number }, fi: number)
local p = factors[fi]
local m = factors[fi + 1]
if m == 1 then
for j = 0, p - 1 do
f[fpos + 1] = fout + j
fpos += fstride
end
else
for j = 0, p - 1 do
bitrevTable(f, fout, fpos, fstride * p, factors, fi + 2)
fpos += fstride
fout += m
end
end
end
local plans: { Plan } = {}
for shift = 0, 3 do
local N = 1920 // 2 ^ shift
local n = N // 4
local factors = FACTORS[shift]
local bitrev = table.create(n, 0)
bitrevTable(bitrev, 0, 0, 1, factors, 1)
local twr, twi = table.create(n, 0), table.create(n, 0)
for k = 0, n - 1 do
local ph = -2 * pi * k / n
twr[k + 1] = cos(ph)
twi[k + 1] = sin(ph)
end
local N2, N4 = N // 2, N // 4
local trig = table.create(N2, 0)
for i = 0, N4 - 1 do
trig[2 * i + 1] = -sin(2 * pi * (i + 0.125) / N)
trig[2 * i + 2] = cos(2 * pi * (i + 0.125) / N)
end
plans[shift + 1] = {
n = n,
factors = factors,
bitrev = bitrev,
twr = twr,
twi = twi,
trig = trig,
fr = table.create(n, 0),
fi = table.create(n, 0),
}
end
local function bfly2(fr: { number }, fi: { number }, N: number)
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
fr[p + 5] = fr[p + 1] - tr
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
fr[p + 7] = fr[p + 3] - tr
fi[p + 7] = fi[p + 3] - ti
fr[p + 3] += tr
fi[p + 3] += ti
p += 8
end
end
local function bfly4(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number)
if m == 1 then
local p = 1
for _ = 1, N do
local r0, i0 = fr[p], fi[p]
local r1, i1 = fr[p + 1], fi[p + 1]
local r2, i2 = fr[p + 2], fi[p + 2]
local r3, i3 = fr[p + 3], fi[p + 3]
local s0r, s0i = r0 - r2, i0 - i2
r0 += r2
i0 += i2
local s1r, s1i = r1 + r3, i1 + i3
fr[p + 2] = r0 - s1r
fi[p + 2] = i0 - s1i
fr[p] = r0 + s1r
fi[p] = i0 + s1i
s1r, s1i = r1 - r3, i1 - i3
fr[p + 1] = s0r + s1i
fi[p + 1] = s0i - s1r
fr[p + 3] = s0r - s1i
fi[p + 3] = s0i + s1r
p += 4
end
else
local m2, m3 = 2 * m, 3 * m
for i = 0, N - 1 do
local p = i * mm + 1
local t1, t2, t3 = 1, 1, 1
for _ = 0, m - 1 do
local ar, ai = fr[p + m], fi[p + m]
local wr, wi = twr[t1], twi[t1]
local s0r, s0i = ar * wr - ai * wi, ar * wi + ai * wr
ar, ai = fr[p + m2], fi[p + m2]
wr, wi = twr[t2], twi[t2]
local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr
ar, ai = fr[p + m3], fi[p + m3]
wr, wi = twr[t3], twi[t3]
local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr
local f0r, f0i = fr[p], fi[p]
local s5r, s5i = f0r - s1r, f0i - s1i
f0r += s1r
f0i += s1i
local s3r, s3i = s0r + s2r, s0i + s2i
local s4r, s4i = s0r - s2r, s0i - s2i
fr[p + m2] = f0r - s3r
fi[p + m2] = f0i - s3i
t1 += fstride
t2 += fstride * 2
t3 += fstride * 3
fr[p] = f0r + s3r
fi[p] = f0i + s3i
fr[p + m] = s5r + s4i
fi[p + m] = s5i - s4r
fr[p + m3] = s5r - s4i
fi[p + m3] = s5i + s4r
p += 1
end
end
end
end
local function bfly3(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number)
local m2 = 2 * m
local epi3i = twi[fstride * m + 1]
for i = 0, N - 1 do
local p = i * mm + 1
local t1, t2 = 1, 1
for _ = 1, m do
local ar, ai = fr[p + m], fi[p + m]
local wr, wi = twr[t1], twi[t1]
local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr
ar, ai = fr[p + m2], fi[p + m2]
wr, wi = twr[t2], twi[t2]
local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr
local s3r, s3i = s1r + s2r, s1i + s2i
local s0r, s0i = s1r - s2r, s1i - s2i
t1 += fstride
t2 += fstride * 2
local f0r, f0i = fr[p], fi[p]
local fmr, fmi = f0r - s3r * 0.5, f0i - s3i * 0.5
s0r *= epi3i
s0i *= epi3i
fr[p] = f0r + s3r
fi[p] = f0i + s3i
fr[p + m2] = fmr + s0i
fi[p + m2] = fmi - s0r
fr[p + m] = fmr - s0i
fi[p + m] = fmi + s0r
p += 1
end
end
end
local function bfly5(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number)
local yar, yai = twr[fstride * m + 1], twi[fstride * m + 1]
local ybr, ybi = twr[fstride * 2 * m + 1], twi[fstride * 2 * m + 1]
for i = 0, N - 1 do
local p0 = i * mm + 1
local p1, p2, p3, p4 = p0 + m, p0 + 2 * m, p0 + 3 * m, p0 + 4 * m
for u = 0, m - 1 do
local s0r, s0i = fr[p0], fi[p0]
local k = u * fstride
local ar, ai = fr[p1], fi[p1]
local wr, wi = twr[k + 1], twi[k + 1]
local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr
ar, ai = fr[p2], fi[p2]
wr, wi = twr[2 * k + 1], twi[2 * k + 1]
local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr
ar, ai = fr[p3], fi[p3]
wr, wi = twr[3 * k + 1], twi[3 * k + 1]
local s3r, s3i = ar * wr - ai * wi, ar * wi + ai * wr
ar, ai = fr[p4], fi[p4]
wr, wi = twr[4 * k + 1], twi[4 * k + 1]
local s4r, s4i = ar * wr - ai * wi, ar * wi + ai * wr
local s7r, s7i = s1r + s4r, s1i + s4i
local s10r, s10i = s1r - s4r, s1i - s4i
local s8r, s8i = s2r + s3r, s2i + s3i
local s9r, s9i = s2r - s3r, s2i - s3i
fr[p0] = s0r + (s7r + s8r)
fi[p0] = s0i + (s7i + s8i)
local s5r = s0r + (s7r * yar + s8r * ybr)
local s5i = s0i + (s7i * yar + s8i * ybr)
local s6r = s10i * yai + s9i * ybi
local s6i = -(s10r * yai + s9r * ybi)
fr[p1] = s5r - s6r
fi[p1] = s5i - s6i
fr[p4] = s5r + s6r
fi[p4] = s5i + s6i
local s11r = s0r + (s7r * ybr + s8r * yar)
local s11i = s0i + (s7i * ybr + s8i * yar)
local s12r = s9i * yai - s10i * ybi
local s12i = s10r * ybi - s9r * yai
fr[p2] = s11r + s12r
fi[p2] = s11i + s12i
fr[p3] = s11r - s12r
fi[p3] = s11i - s12i
p0 += 1
p1 += 1
p2 += 1
p3 += 1
p4 += 1
end
end
end
-- in-place forward FFT of bit-reversed input (opus_fft_impl)
local function fftImpl(pl: Plan)
local factors = pl.factors
local fr, fi, twr, twi = pl.fr, pl.fi, pl.twr, pl.twi
local fstride = { 1 }
local L = 0
local m
repeat
local p = factors[2 * L + 1]
m = factors[2 * L + 2]
fstride[L + 2] = fstride[L + 1] * p
L += 1
until m == 1
m = factors[2 * L]
for i = L - 1, 0, -1 do
local m2 = if i ~= 0 then factors[2 * i] else 1
local radix = factors[2 * i + 1]
if radix == 2 then
bfly2(fr, fi, fstride[i + 1])
elseif radix == 4 then
bfly4(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2)
elseif radix == 3 then
bfly3(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2)
else
bfly5(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2)
end
m = m2
end
end
-- clt_mdct_backward: 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).
function Mdct.backward(inp: { number }, inBase: number, out: { number }, outBase: number, window: { number }, overlap: number, shift: number, stride: number)
local pl = plans[shift + 1]
local N4 = pl.n
local N2 = N4 * 2
local trig = pl.trig
local bitrev = pl.bitrev
local fr, fi = pl.fr, pl.fi
-- pre-rotate, storing in bit-reversed order (real and imaginary swapped: an FFT is used instead of an IFFT)
local xp1 = inBase
local xp2 = inBase + stride * (N2 - 1)
for i = 0, N4 - 1 do
local x1 = inp[xp1]
local x2 = inp[xp2]
local t0, t1 = trig[2 * i + 1], trig[2 * i + 2]
local rev = bitrev[i + 1] + 1
fi[rev] = x2 * t1 + x1 * t0
fr[rev] = x1 * t1 - x2 * t0
xp1 += 2 * stride
xp2 -= 2 * stride
end
fftImpl(pl)
-- post-rotate
local h = outBase + (overlap // 2)
for k = 0, N4 - 1 do
local re = fi[k + 1]
local im = fr[k + 1]
local t0, t1 = trig[2 * k + 1], trig[2 * k + 2]
out[h + 2 * k] = re * t1 + im * t0
out[h + N2 - 1 - 2 * k] = re * t0 - im * t1
end
-- mirror on both sides for TDAC
local xp = outBase + overlap - 1
local yp = outBase
for i = 0, overlap // 2 - 1 do
local x1 = out[xp]
local x2 = out[yp]
local w1 = window[i + 1]
local w2 = window[overlap - i]
out[yp] = x2 * w2 - x1 * w1
out[xp] = x2 * w1 + x1 * w2
xp -= 1
yp += 1
end
end
return Mdct
+235
View File
@@ -0,0 +1,235 @@
--!strict
--!native
--!optimize 2
-- audio/opus/Packet: Opus packet framing (RFC 6716 section 3): the TOC byte and frame packing codes 0-3, with padding.
local Packet = {}
local readu8 = buffer.readu8
local band, rshift = bit32.band, bit32.rshift
Packet.MODE_SILK_ONLY = 1000
Packet.MODE_HYBRID = 1001
Packet.MODE_CELT_ONLY = 1002
-- bandwidths as in libopus (OPUS_BANDWIDTH_NARROWBAND .. FULLBAND)
Packet.BW_NB = 1101
Packet.BW_MB = 1102
Packet.BW_WB = 1103
Packet.BW_SWB = 1104
Packet.BW_FB = 1105
function Packet.mode(toc: number): number
if band(toc, 0x80) ~= 0 then
return Packet.MODE_CELT_ONLY
elseif band(toc, 0x60) == 0x60 then
return Packet.MODE_HYBRID
else
return Packet.MODE_SILK_ONLY
end
end
function Packet.bandwidth(toc: number): number
if band(toc, 0x80) ~= 0 then
local bw = 1102 + band(rshift(toc, 5), 3)
if bw == 1102 then
bw = 1101
end
return bw
elseif band(toc, 0x60) == 0x60 then
return if band(toc, 0x10) ~= 0 then 1105 else 1104
else
return 1101 + band(rshift(toc, 5), 3)
end
end
function Packet.channels(toc: number): number
return if band(toc, 4) ~= 0 then 2 else 1
end
-- samples per frame at rate Fs
function Packet.samplesPerFrame(toc: number, Fs: number): number
if band(toc, 0x80) ~= 0 then
local a = band(rshift(toc, 3), 3)
return bit32.lshift(Fs, a) // 400
elseif band(toc, 0x60) == 0x60 then
return if band(toc, 0x08) ~= 0 then Fs // 50 else Fs // 100
else
local a = band(rshift(toc, 3), 3)
if a == 3 then
return Fs * 60 // 1000
end
return bit32.lshift(Fs, a) // 100
end
end
-- total samples of a packet at 48 kHz, or -1 if invalid
function Packet.samples(buf: buffer, off: number, len: number): number
if len < 1 then
return -1
end
local toc = readu8(buf, off)
local c = band(toc, 3)
local count
if c == 0 then
count = 1
elseif c ~= 3 then
count = 2
else
if len < 2 then
return -1
end
count = band(readu8(buf, off + 1), 0x3F)
end
local n = count * Packet.samplesPerFrame(toc, 48000)
if n * 25 > 48000 * 3 then
return -1
end
return n
end
local function parseSize(buf: buffer, p: number, len: number): (number, number)
if len < 1 then
return -1, -1
end
local b0 = readu8(buf, p)
if b0 < 252 then
return 1, b0
elseif len < 2 then
return -1, -1
end
return 2, 4 * readu8(buf, p + 1) + b0
end
-- 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.
function Packet.parse(buf: buffer, off: number, len: number, offsets: { number }, sizes: { number }, selfDelimited: boolean?): (number, number, number)
if len < 1 then
return -1, 0, 0
end
local toc = readu8(buf, off)
local framesize = Packet.samplesPerFrame(toc, 48000)
local p = off + 1
len -= 1
local lastSize = len
local count
local cbr = false
local pad = 0
local c = band(toc, 3)
if c == 0 then
count = 1
elseif c == 1 then
count = 2
cbr = true
if not selfDelimited then
if band(len, 1) ~= 0 then
return -1, toc, 0
end
lastSize = len // 2
sizes[1] = lastSize
end
elseif c == 2 then
count = 2
local bytes, s = parseSize(buf, p, len)
if bytes < 0 then
return -1, toc, 0
end
len -= bytes
if s < 0 or s > len then
return -1, toc, 0
end
sizes[1] = s
p += bytes
lastSize = len - s
else
if len < 1 then
return -1, toc, 0
end
local ch = readu8(buf, p)
p += 1
count = band(ch, 0x3F)
if count <= 0 or framesize * count > 5760 then
return -1, toc, 0
end
len -= 1
if band(ch, 0x40) ~= 0 then
local pb
repeat
if len <= 0 then
return -1, toc, 0
end
pb = readu8(buf, p)
p += 1
len -= 1
local tmp = if pb == 255 then 254 else pb
len -= tmp
pad += tmp
until pb ~= 255
end
if len < 0 then
return -1, toc, 0
end
cbr = band(ch, 0x80) == 0
if not cbr then
lastSize = len
for i = 1, count - 1 do
local bytes, s = parseSize(buf, p, len)
if bytes < 0 then
return -1, toc, 0
end
len -= bytes
if s < 0 or s > len then
return -1, toc, 0
end
sizes[i] = s
p += bytes
lastSize -= bytes + s
end
if lastSize < 0 then
return -1, toc, 0
end
elseif not selfDelimited then
lastSize = len // count
if lastSize * count ~= len then
return -1, toc, 0
end
for i = 1, count - 1 do
sizes[i] = lastSize
end
end
end
if selfDelimited then
local bytes, s = parseSize(buf, p, len)
if bytes < 0 then
return -1, toc, 0
end
len -= bytes
if s < 0 or s > len then
return -1, toc, 0
end
p += bytes
sizes[count] = s
if cbr then
if s * count > len then
return -1, toc, 0
end
for i = 1, count - 1 do
sizes[i] = s
end
elseif bytes + s > lastSize then
return -1, toc, 0
end
else
if lastSize > 1275 then
return -1, toc, 0
end
sizes[count] = lastSize
end
for i = 1, count do
offsets[i] = p
p += sizes[i]
end
return count, toc, pad + (p - off)
end
return Packet
+214
View File
@@ -0,0 +1,214 @@
--!strict
--!native
--!optimize 2
-- audio/opus/RangeDecoder: Range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus frame from a `buffer` slice
-- [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice backwards.
-- All values stay below 2^32, so plain Luau numbers hold them exactly; floor division is exact below 2^52.
local RangeDecoder = {}
export type Dec = {
buf: buffer,
base: number,
storage: number,
offs: number,
end_offs: number,
end_window: number,
nend_bits: number,
nbits_total: number,
rng: number,
val: number,
rem: number,
ext: number,
error: number,
}
local SYM_BITS = 8
local CODE_BITS = 32
local CODE_TOP = 2147483648 -- 1 << 31
local CODE_BOT = 8388608 -- CODE_TOP >> 8
local CODE_EXTRA = 7 -- (CODE_BITS - 2) % SYM_BITS + 1
local SYM_MAX = 255
local UINT_BITS = 8
local WINDOW_SIZE = 32
local countlz = bit32.countlz
local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift
local readu8 = buffer.readu8
local function ilog(x: number): number
return 32 - countlz(x)
end
RangeDecoder.ilog = ilog
local function normalize(d: Dec)
local rng, val, rem = d.rng, d.val, d.rem
while rng <= CODE_BOT do
d.nbits_total += SYM_BITS
rng = rng * 256
local sym = rem
local offs = d.offs
if offs < d.storage then
rem = readu8(d.buf, d.base + offs)
d.offs = offs + 1
else
rem = 0
end
sym = rshift(bor(lshift(sym, 8), rem), SYM_BITS - CODE_EXTRA) -- (sym << 8 | rem) >> 1
val = band(val * 256 + band(SYM_MAX, bit32.bnot(sym)), CODE_TOP - 1)
end
d.rng, d.val, d.rem = rng, val, rem
end
function RangeDecoder.new(buf: buffer, base: number, storage: number): Dec
local d: Dec = {
buf = buf,
base = base,
storage = storage,
offs = 0,
end_offs = 0,
end_window = 0,
nend_bits = 0,
nbits_total = CODE_BITS + 1 - ((CODE_BITS - CODE_EXTRA) // SYM_BITS) * SYM_BITS,
rng = 128, -- 1 << CODE_EXTRA
val = 0,
rem = 0,
ext = 0,
error = 0,
}
local rem = 0
if storage > 0 then
rem = readu8(buf, base)
d.offs = 1
end
d.rem = rem
d.val = d.rng - 1 - rshift(rem, SYM_BITS - CODE_EXTRA)
normalize(d)
return d
end
-- ec_decode: the cumulative frequency of the next symbol, for a total of ft
function RangeDecoder.decode(d: Dec, ft: number): number
local ext = d.rng // ft
d.ext = ext
local s = d.val // ext
return ft - math.min(s + 1, ft)
end
function RangeDecoder.decodeBin(d: Dec, bits: number): number
local ext = rshift(d.rng, bits)
d.ext = ext
local s = d.val // ext
local ft = lshift(1, bits)
return ft - math.min(s + 1, ft)
end
function RangeDecoder.update(d: Dec, fl: number, fh: number, ft: number)
local s = d.ext * (ft - fh)
d.val = band(d.val - s, 0xFFFFFFFF) -- uint32 wrap (corrupt streams only)
if fl > 0 then
d.rng = d.ext * (fh - fl)
else
d.rng -= s
end
normalize(d)
end
function RangeDecoder.bitLogp(d: Dec, logp: number): boolean
local r = d.rng
local v = d.val
local s = rshift(r, logp)
local ret = v < s
if ret then
d.rng = s
else
d.val = v - s
d.rng = r - s
end
normalize(d)
return ret
end
-- ec_dec_icdf over a Luau array (1-based) starting at index `off` (icdf[off] is entry 0)
function RangeDecoder.icdf(d: Dec, icdf: { number }, off: number, ftb: number): number
local s = d.rng
local v = d.val
local r = rshift(s, ftb)
local ret = -1
local t
repeat
t = s
ret += 1
s = r * icdf[off + ret]
until v >= s
d.val = v - s
d.rng = t - s
normalize(d)
return ret
end
function RangeDecoder.bits(d: Dec, bits: number): number
local window = d.end_window
local available = d.nend_bits
if available < bits then
repeat
local b = 0
local eo = d.end_offs
if eo < d.storage then
eo += 1
d.end_offs = eo
b = readu8(d.buf, d.base + d.storage - eo)
end
window = bor(window, lshift(b, available))
available += SYM_BITS
until available > WINDOW_SIZE - SYM_BITS
end
local ret = band(window, lshift(1, bits) - 1)
if bits == 32 then
ret = window
end
window = rshift(window, bits)
available -= bits
d.end_window = window
d.nend_bits = available
d.nbits_total += bits
return ret
end
function RangeDecoder.uint(d: Dec, ft0: number): number
local ft = ft0 - 1
local ftb = ilog(ft)
if ftb > UINT_BITS then
ftb -= UINT_BITS
local ft1 = rshift(ft, ftb) + 1
local s = RangeDecoder.decode(d, ft1)
RangeDecoder.update(d, s, s + 1, ft1)
local t = bor(lshift(s, ftb), RangeDecoder.bits(d, ftb))
if t <= ft then
return t
end
d.error = 1
return ft
else
local s = RangeDecoder.decode(d, ft0)
RangeDecoder.update(d, s, s + 1, ft0)
return s
end
end
function RangeDecoder.tell(d: Dec): number
return d.nbits_total - ilog(d.rng)
end
local correction = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 }
function RangeDecoder.tellFrac(d: Dec): number
local nbits = d.nbits_total * 8
local l = ilog(d.rng)
local r = rshift(d.rng, l - 16)
local b = rshift(r, 12) - 8
if r > correction[b + 1] then
b += 1
end
return nbits - (l * 8 + b)
end
return RangeDecoder
File diff suppressed because it is too large. Load diff
+372
View File
@@ -0,0 +1,372 @@
--!strict
--!optimize 2
-- audio/opus/SilkTables: SILK decoder tables (generated from libopus silk/tables_*.c, pitch_est_tables.c, resampler_rom.c; BSD, see
-- licenses/). Multi-dimensional C arrays are flattened row-major; every array is 1-based.
local T = {}
T.LTP_per_index_iCDF = {
179, 99, 0,
}
T.LTP_gain_iCDF_0 = {
71, 56, 43, 30, 21, 12, 6, 0,
}
T.LTP_gain_iCDF_1 = {
199, 165, 144, 124, 109, 96, 84, 71, 61, 51, 42, 32, 23, 15, 8, 0,
}
T.LTP_gain_iCDF_2 = {
241, 225, 211, 199, 187, 175, 164, 153, 142, 132, 123, 114, 105, 96, 88, 80, 72, 64, 57, 50,
44, 38, 33, 29, 24, 20, 16, 12, 9, 5, 2, 0,
}
T.LTP_gain_vq_0 = {
4, 6, 24, 7, 5, 0, 0, 2, 0, 0, 12, 28, 41, 13, -4, -9, 15, 42, 25, 14,
1, -2, 62, 41, -9, -10, 37, 65, -4, 3, -6, 4, 66, 7, -8, 16, 14, 38, -3, 33,
}
T.LTP_gain_vq_1 = {
13, 22, 39, 23, 12, -1, 36, 64, 27, -6, -7, 10, 55, 43, 17, 1, 1, 8, 1, 1,
6, -11, 74, 53, -9, -12, 55, 76, -12, 8, -3, 3, 93, 27, -4, 26, 39, 59, 3, -8,
2, 0, 77, 11, 9, -8, 22, 44, -6, 7, 40, 9, 26, 3, 9, -7, 20, 101, -7, 4,
3, -8, 42, 26, 0, -15, 33, 68, 2, 23, -2, 55, 46, -2, 15, 3, -1, 21, 16, 41,
}
T.LTP_gain_vq_2 = {
-6, 27, 61, 39, 5, -11, 42, 88, 4, 1, -2, 60, 65, 6, -4, -1, -5, 73, 56, 1,
-9, 19, 94, 29, -9, 0, 12, 99, 6, 4, 8, -19, 102, 46, -13, 3, 2, 13, 3, 2,
9, -21, 84, 72, -18, -11, 46, 104, -22, 8, 18, 38, 48, 23, 0, -16, 70, 83, -21, 11,
5, -11, 117, 22, -8, -6, 23, 117, -12, 3, 3, -8, 95, 28, 4, -10, 15, 77, 60, -15,
-1, 4, 124, 2, -4, 3, 38, 84, 24, -25, 2, 13, 42, 13, 31, 21, -4, 56, 46, -1,
-1, 35, 79, -13, 19, -7, 65, 88, -9, -14, 20, 4, 81, 49, -29, 20, 0, 75, 3, -17,
5, -9, 44, 92, -8, 1, -3, 22, 69, 31, -6, 95, 41, -12, 5, 39, 67, 16, -4, 1,
0, -6, 120, 55, -36, -13, 44, 122, 4, -24, 81, 5, 11, 3, 7, 2, 0, 9, 10, 88,
}
T.NLSF_CB1_WB_Q8 = {
7, 23, 38, 54, 69, 85, 100, 116, 131, 147, 162, 178, 193, 208, 223, 239, 13, 25, 41, 55,
69, 83, 98, 112, 127, 142, 157, 171, 187, 203, 220, 236, 15, 21, 34, 51, 61, 78, 92, 106,
126, 136, 152, 167, 185, 205, 225, 240, 10, 21, 36, 50, 63, 79, 95, 110, 126, 141, 157, 173,
189, 205, 221, 237, 17, 20, 37, 51, 59, 78, 89, 107, 123, 134, 150, 164, 184, 205, 224, 240,
10, 15, 32, 51, 67, 81, 96, 112, 129, 142, 158, 173, 189, 204, 220, 236, 8, 21, 37, 51,
65, 79, 98, 113, 126, 138, 155, 168, 179, 192, 209, 218, 12, 15, 34, 55, 63, 78, 87, 108,
118, 131, 148, 167, 185, 203, 219, 236, 16, 19, 32, 36, 56, 79, 91, 108, 118, 136, 154, 171,
186, 204, 220, 237, 11, 28, 43, 58, 74, 89, 105, 120, 135, 150, 165, 180, 196, 211, 226, 241,
6, 16, 33, 46, 60, 75, 92, 107, 123, 137, 156, 169, 185, 199, 214, 225, 11, 19, 30, 44,
57, 74, 89, 105, 121, 135, 152, 169, 186, 202, 218, 234, 12, 19, 29, 46, 57, 71, 88, 100,
120, 132, 148, 165, 182, 199, 216, 233, 17, 23, 35, 46, 56, 77, 92, 106, 123, 134, 152, 167,
185, 204, 222, 237, 14, 17, 45, 53, 63, 75, 89, 107, 115, 132, 151, 171, 188, 206, 221, 240,
9, 16, 29, 40, 56, 71, 88, 103, 119, 137, 154, 171, 189, 205, 222, 237, 16, 19, 36, 48,
57, 76, 87, 105, 118, 132, 150, 167, 185, 202, 218, 236, 12, 17, 29, 54, 71, 81, 94, 104,
126, 136, 149, 164, 182, 201, 221, 237, 15, 28, 47, 62, 79, 97, 115, 129, 142, 155, 168, 180,
194, 208, 223, 238, 8, 14, 30, 45, 62, 78, 94, 111, 127, 143, 159, 175, 192, 207, 223, 239,
17, 30, 49, 62, 79, 92, 107, 119, 132, 145, 160, 174, 190, 204, 220, 235, 14, 19, 36, 45,
61, 76, 91, 108, 121, 138, 154, 172, 189, 205, 222, 238, 12, 18, 31, 45, 60, 76, 91, 107,
123, 138, 154, 171, 187, 204, 221, 236, 13, 17, 31, 43, 53, 70, 83, 103, 114, 131, 149, 167,
185, 203, 220, 237, 17, 22, 35, 42, 58, 78, 93, 110, 125, 139, 155, 170, 188, 206, 224, 240,
8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239, 13, 16, 41, 66,
73, 86, 95, 111, 128, 137, 150, 163, 183, 206, 225, 241, 17, 25, 37, 52, 63, 75, 92, 102,
119, 132, 144, 160, 175, 191, 212, 231, 19, 31, 49, 65, 83, 100, 117, 133, 147, 161, 174, 187,
200, 213, 227, 242, 18, 31, 52, 68, 88, 103, 117, 126, 138, 149, 163, 177, 192, 207, 223, 239,
16, 29, 47, 61, 76, 90, 106, 119, 133, 147, 161, 176, 193, 209, 224, 240, 15, 21, 35, 50,
61, 73, 86, 97, 110, 119, 129, 141, 175, 198, 218, 237,
}
T.NLSF_CB1_WB_Wght_Q9 = {
3657, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2963, 2963, 2925, 2846, 3216, 3085, 2972, 3056,
3056, 3010, 3010, 3010, 2963, 2963, 3010, 2972, 2888, 2846, 2846, 2726, 3920, 4014, 2981, 3207, 3207, 2934, 3056, 2846,
3122, 3244, 2925, 2846, 2620, 2553, 2780, 2925, 3516, 3197, 3010, 3103, 3019, 2888, 2925, 2925, 2925, 2925, 2888, 2888,
2888, 2888, 2888, 2753, 5054, 5054, 2934, 3573, 3385, 3056, 3085, 2793, 3160, 3160, 2972, 2846, 2513, 2540, 2753, 2888,
4428, 4149, 2700, 2753, 2972, 3010, 2925, 2846, 2981, 3019, 2925, 2925, 2925, 2925, 2888, 2726, 3620, 3019, 2972, 3056,
3056, 2873, 2806, 3056, 3216, 3047, 2981, 3291, 3291, 2981, 3310, 2991, 5227, 5014, 2540, 3338, 3526, 3385, 3197, 3094,
3376, 2981, 2700, 2647, 2687, 2793, 2846, 2673, 5081, 5174, 4615, 4428, 2460, 2897, 3047, 3207, 3169, 2687, 2740, 2888,
2846, 2793, 2846, 2700, 3122, 2888, 2963, 2925, 2925, 2925, 2925, 2963, 2963, 2963, 2963, 2925, 2925, 2963, 2963, 2963,
4202, 3207, 2981, 3103, 3010, 2888, 2888, 2925, 2972, 2873, 2916, 3019, 2972, 3010, 3197, 2873, 3760, 3760, 3244, 3103,
2981, 2888, 2925, 2888, 2972, 2934, 2793, 2793, 2846, 2888, 2888, 2660, 3854, 4014, 3207, 3122, 3244, 2934, 3047, 2963,
2963, 3085, 2846, 2793, 2793, 2793, 2793, 2580, 3845, 4080, 3357, 3516, 3094, 2740, 3010, 2934, 3122, 3085, 2846, 2846,
2647, 2647, 2846, 2806, 5147, 4894, 3225, 3845, 3441, 3169, 2897, 3413, 3451, 2700, 2580, 2673, 2740, 2846, 2806, 2753,
4109, 3789, 3291, 3160, 2925, 2888, 2888, 2925, 2793, 2740, 2793, 2740, 2793, 2846, 2888, 2806, 5081, 5054, 3047, 3545,
3244, 3056, 3085, 2944, 3103, 2897, 2740, 2740, 2740, 2846, 2793, 2620, 4309, 4309, 2860, 2527, 3207, 3376, 3376, 3075,
3075, 3376, 3056, 2846, 2647, 2580, 2726, 2753, 3056, 2916, 2806, 2888, 2740, 2687, 2897, 3103, 3150, 3150, 3216, 3169,
3056, 3010, 2963, 2846, 4375, 3882, 2925, 2888, 2846, 2888, 2846, 2846, 2888, 2888, 2888, 2846, 2888, 2925, 2888, 2846,
2981, 2916, 2916, 2981, 2981, 3056, 3122, 3216, 3150, 3056, 3010, 2972, 2972, 2972, 2925, 2740, 4229, 4149, 3310, 3347,
2925, 2963, 2888, 2981, 2981, 2846, 2793, 2740, 2846, 2846, 2846, 2793, 4080, 4014, 3103, 3010, 2925, 2925, 2925, 2888,
2925, 2925, 2846, 2846, 2846, 2793, 2888, 2780, 4615, 4575, 3169, 3441, 3207, 2981, 2897, 3038, 3122, 2740, 2687, 2687,
2687, 2740, 2793, 2700, 4149, 4269, 3789, 3657, 2726, 2780, 2888, 2888, 3010, 2972, 2925, 2846, 2687, 2687, 2793, 2888,
4215, 3554, 2753, 2846, 2846, 2888, 2888, 2888, 2925, 2925, 2888, 2925, 2925, 2925, 2963, 2888, 5174, 4921, 2261, 3432,
3789, 3479, 3347, 2846, 3310, 3479, 3150, 2897, 2460, 2487, 2753, 2925, 3451, 3685, 3122, 3197, 3357, 3047, 3207, 3207,
2981, 3216, 3085, 2925, 2925, 2687, 2540, 2434, 2981, 3010, 2793, 2793, 2740, 2793, 2846, 2972, 3056, 3103, 3150, 3150,
3150, 3103, 3010, 3010, 2944, 2873, 2687, 2726, 2780, 3010, 3432, 3545, 3357, 3244, 3056, 3010, 2963, 2925, 2888, 2846,
3019, 2944, 2897, 3010, 3010, 2972, 3019, 3103, 3056, 3056, 3010, 2888, 2846, 2925, 2925, 2888, 3920, 3967, 3010, 3197,
3357, 3216, 3291, 3291, 3479, 3704, 3441, 2726, 2181, 2460, 2580, 2607,
}
T.NLSF_CB1_iCDF_WB = {
225, 204, 201, 184, 183, 175, 158, 154, 153, 135, 119, 115, 113, 110, 109, 99, 98, 95, 79, 68,
52, 50, 48, 45, 43, 32, 31, 27, 18, 10, 3, 0, 255, 251, 235, 230, 212, 201, 196, 182,
167, 166, 163, 151, 138, 124, 110, 104, 90, 78, 76, 70, 69, 57, 45, 34, 24, 21, 11, 6,
5, 4, 3, 0,
}
T.NLSF_CB2_SELECT_WB = {
0, 0, 0, 0, 0, 0, 0, 1, 100, 102, 102, 68, 68, 36, 34, 96, 164, 107, 158, 185,
180, 185, 139, 102, 64, 66, 36, 34, 34, 0, 1, 32, 208, 139, 141, 191, 152, 185, 155, 104,
96, 171, 104, 166, 102, 102, 102, 132, 1, 0, 0, 0, 0, 16, 16, 0, 80, 109, 78, 107,
185, 139, 103, 101, 208, 212, 141, 139, 173, 153, 123, 103, 36, 0, 0, 0, 0, 0, 0, 1,
48, 0, 0, 0, 0, 0, 0, 32, 68, 135, 123, 119, 119, 103, 69, 98, 68, 103, 120, 118,
118, 102, 71, 98, 134, 136, 157, 184, 182, 153, 139, 134, 208, 168, 248, 75, 189, 143, 121, 107,
32, 49, 34, 34, 34, 0, 17, 2, 210, 235, 139, 123, 185, 137, 105, 134, 98, 135, 104, 182,
100, 183, 171, 134, 100, 70, 68, 70, 66, 66, 34, 131, 64, 166, 102, 68, 36, 2, 1, 0,
134, 166, 102, 68, 34, 34, 66, 132, 212, 246, 158, 139, 107, 107, 87, 102, 100, 219, 125, 122,
137, 118, 103, 132, 114, 135, 137, 105, 171, 106, 50, 34, 164, 214, 141, 143, 185, 151, 121, 103,
192, 34, 0, 0, 0, 0, 0, 1, 208, 109, 74, 187, 134, 249, 159, 137, 102, 110, 154, 118,
87, 101, 119, 101, 0, 2, 0, 36, 36, 66, 68, 35, 96, 164, 102, 100, 36, 0, 2, 33,
167, 138, 174, 102, 100, 84, 2, 2, 100, 107, 120, 119, 36, 197, 24, 0,
}
T.NLSF_CB2_iCDF_WB = {
255, 254, 253, 244, 12, 3, 2, 1, 0, 255, 254, 252, 224, 38, 3, 2, 1, 0, 255, 254,
251, 209, 57, 4, 2, 1, 0, 255, 254, 244, 195, 69, 4, 2, 1, 0, 255, 251, 232, 184,
84, 7, 2, 1, 0, 255, 254, 240, 186, 86, 14, 2, 1, 0, 255, 254, 239, 178, 91, 30,
5, 1, 0, 255, 248, 227, 177, 100, 19, 2, 1, 0,
}
T.NLSF_PRED_WB_Q8 = {
175, 148, 160, 176, 178, 173, 174, 164, 177, 174, 196, 182, 198, 192, 182, 68, 62, 66, 60, 72,
117, 85, 90, 118, 136, 151, 142, 160, 142, 155,
}
T.NLSF_DELTA_MIN_WB_Q15 = {
100, 3, 40, 3, 3, 3, 5, 14, 14, 10, 11, 3, 8, 9, 7, 3, 347,
}
T.NLSF_CB1_NB_MB_Q8 = {
12, 35, 60, 83, 108, 132, 157, 180, 206, 228, 15, 32, 55, 77, 101, 125, 151, 175, 201, 225,
19, 42, 66, 89, 114, 137, 162, 184, 209, 230, 12, 25, 50, 72, 97, 120, 147, 172, 200, 223,
26, 44, 69, 90, 114, 135, 159, 180, 205, 225, 13, 22, 53, 80, 106, 130, 156, 180, 205, 228,
15, 25, 44, 64, 90, 115, 142, 168, 196, 222, 19, 24, 62, 82, 100, 120, 145, 168, 190, 214,
22, 31, 50, 79, 103, 120, 151, 170, 203, 227, 21, 29, 45, 65, 106, 124, 150, 171, 196, 224,
30, 49, 75, 97, 121, 142, 165, 186, 209, 229, 19, 25, 52, 70, 93, 116, 143, 166, 192, 219,
26, 34, 62, 75, 97, 118, 145, 167, 194, 217, 25, 33, 56, 70, 91, 113, 143, 165, 196, 223,
21, 34, 51, 72, 97, 117, 145, 171, 196, 222, 20, 29, 50, 67, 90, 117, 144, 168, 197, 221,
22, 31, 48, 66, 95, 117, 146, 168, 196, 222, 24, 33, 51, 77, 116, 134, 158, 180, 200, 224,
21, 28, 70, 87, 106, 124, 149, 170, 194, 217, 26, 33, 53, 64, 83, 117, 152, 173, 204, 225,
27, 34, 65, 95, 108, 129, 155, 174, 210, 225, 20, 26, 72, 99, 113, 131, 154, 176, 200, 219,
34, 43, 61, 78, 93, 114, 155, 177, 205, 229, 23, 29, 54, 97, 124, 138, 163, 179, 209, 229,
30, 38, 56, 89, 118, 129, 158, 178, 200, 231, 21, 29, 49, 63, 85, 111, 142, 163, 193, 222,
27, 48, 77, 103, 133, 158, 179, 196, 215, 232, 29, 47, 74, 99, 124, 151, 176, 198, 220, 237,
33, 42, 61, 76, 93, 121, 155, 174, 207, 225, 29, 53, 87, 112, 136, 154, 170, 188, 208, 227,
24, 30, 52, 84, 131, 150, 166, 186, 203, 229, 37, 48, 64, 84, 104, 118, 156, 177, 201, 230,
}
T.NLSF_CB1_Wght_Q9 = {
2897, 2314, 2314, 2314, 2287, 2287, 2314, 2300, 2327, 2287, 2888, 2580, 2394, 2367, 2314, 2274, 2274, 2274, 2274, 2194,
2487, 2340, 2340, 2314, 2314, 2314, 2340, 2340, 2367, 2354, 3216, 2766, 2340, 2340, 2314, 2274, 2221, 2207, 2261, 2194,
2460, 2474, 2367, 2394, 2394, 2394, 2394, 2367, 2407, 2314, 3479, 3056, 2127, 2207, 2274, 2274, 2274, 2287, 2314, 2261,
3282, 3141, 2580, 2394, 2247, 2221, 2207, 2194, 2194, 2114, 4096, 3845, 2221, 2620, 2620, 2407, 2314, 2394, 2367, 2074,
3178, 3244, 2367, 2221, 2553, 2434, 2340, 2314, 2167, 2221, 3338, 3488, 2726, 2194, 2261, 2460, 2354, 2367, 2207, 2101,
2354, 2420, 2327, 2367, 2394, 2420, 2420, 2420, 2460, 2367, 3779, 3629, 2434, 2527, 2367, 2274, 2274, 2300, 2207, 2048,
3254, 3225, 2713, 2846, 2447, 2327, 2300, 2300, 2274, 2127, 3263, 3300, 2753, 2806, 2447, 2261, 2261, 2247, 2127, 2101,
2873, 2981, 2633, 2367, 2407, 2354, 2194, 2247, 2247, 2114, 3225, 3197, 2633, 2580, 2274, 2181, 2247, 2221, 2221, 2141,
3178, 3310, 2740, 2407, 2274, 2274, 2274, 2287, 2194, 2114, 3141, 3272, 2460, 2061, 2287, 2500, 2367, 2487, 2434, 2181,
3507, 3282, 2314, 2700, 2647, 2474, 2367, 2394, 2340, 2127, 3423, 3535, 3038, 3056, 2300, 1950, 2221, 2274, 2274, 2274,
3404, 3366, 2087, 2687, 2873, 2354, 2420, 2274, 2474, 2540, 3760, 3488, 1950, 2660, 2897, 2527, 2394, 2367, 2460, 2261,
3028, 3272, 2740, 2888, 2740, 2154, 2127, 2287, 2234, 2247, 3695, 3657, 2025, 1969, 2660, 2700, 2580, 2500, 2327, 2367,
3207, 3413, 2354, 2074, 2888, 2888, 2340, 2487, 2247, 2167, 3338, 3366, 2846, 2780, 2327, 2154, 2274, 2287, 2114, 2061,
2327, 2300, 2181, 2167, 2181, 2367, 2633, 2700, 2700, 2553, 2407, 2434, 2221, 2261, 2221, 2221, 2340, 2420, 2607, 2700,
3038, 3244, 2806, 2888, 2474, 2074, 2300, 2314, 2354, 2380, 2221, 2154, 2127, 2287, 2500, 2793, 2793, 2620, 2580, 2367,
3676, 3713, 2234, 1838, 2181, 2753, 2726, 2673, 2513, 2207, 2793, 3160, 2726, 2553, 2846, 2513, 2181, 2394, 2221, 2181,
}
T.NLSF_CB1_iCDF_NB_MB = {
212, 178, 148, 129, 108, 96, 85, 82, 79, 77, 61, 59, 57, 56, 51, 49, 48, 45, 42, 41,
40, 38, 36, 34, 31, 30, 21, 12, 10, 3, 1, 0, 255, 245, 244, 236, 233, 225, 217, 203,
190, 176, 175, 161, 149, 136, 125, 114, 102, 91, 81, 71, 60, 52, 43, 35, 28, 20, 19, 18,
12, 11, 5, 0,
}
T.NLSF_CB2_SELECT_NB_MB = {
16, 0, 0, 0, 0, 99, 66, 36, 36, 34, 36, 34, 34, 34, 34, 83, 69, 36, 52, 34,
116, 102, 70, 68, 68, 176, 102, 68, 68, 34, 65, 85, 68, 84, 36, 116, 141, 152, 139, 170,
132, 187, 184, 216, 137, 132, 249, 168, 185, 139, 104, 102, 100, 68, 68, 178, 218, 185, 185, 170,
244, 216, 187, 187, 170, 244, 187, 187, 219, 138, 103, 155, 184, 185, 137, 116, 183, 155, 152, 136,
132, 217, 184, 184, 170, 164, 217, 171, 155, 139, 244, 169, 184, 185, 170, 164, 216, 223, 218, 138,
214, 143, 188, 218, 168, 244, 141, 136, 155, 170, 168, 138, 220, 219, 139, 164, 219, 202, 216, 137,
168, 186, 246, 185, 139, 116, 185, 219, 185, 138, 100, 100, 134, 100, 102, 34, 68, 68, 100, 68,
168, 203, 221, 218, 168, 167, 154, 136, 104, 70, 164, 246, 171, 137, 139, 137, 155, 218, 219, 139,
}
T.NLSF_CB2_iCDF_NB_MB = {
255, 254, 253, 238, 14, 3, 2, 1, 0, 255, 254, 252, 218, 35, 3, 2, 1, 0, 255, 254,
250, 208, 59, 4, 2, 1, 0, 255, 254, 246, 194, 71, 10, 2, 1, 0, 255, 252, 236, 183,
82, 8, 2, 1, 0, 255, 252, 235, 180, 90, 17, 2, 1, 0, 255, 248, 224, 171, 97, 30,
4, 1, 0, 255, 254, 236, 173, 95, 37, 7, 1, 0,
}
T.NLSF_PRED_NB_MB_Q8 = {
179, 138, 140, 148, 151, 149, 153, 151, 163, 116, 67, 82, 59, 92, 72, 100, 89, 92,
}
T.NLSF_DELTA_MIN_NB_MB_Q15 = {
250, 3, 6, 3, 3, 3, 4, 3, 3, 3, 461,
}
T.pitch_lag_iCDF = {
253, 250, 244, 233, 212, 182, 150, 131, 120, 110, 98, 85, 72, 60, 49, 40, 32, 25, 19, 15,
13, 11, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
}
T.pitch_delta_iCDF = {
210, 208, 206, 203, 199, 193, 183, 168, 142, 104, 74, 52, 37, 27, 20, 14, 10, 6, 4, 2,
0,
}
T.pitch_contour_iCDF = {
223, 201, 183, 167, 152, 138, 124, 111, 98, 88, 79, 70, 62, 56, 50, 44, 39, 35, 31, 27,
24, 21, 18, 16, 14, 12, 10, 8, 6, 4, 3, 2, 1, 0,
}
T.pitch_contour_NB_iCDF = {
188, 176, 155, 138, 119, 97, 67, 43, 26, 10, 0,
}
T.pitch_contour_10_ms_iCDF = {
165, 119, 80, 61, 47, 35, 27, 20, 14, 9, 4, 0,
}
T.pitch_contour_10_ms_NB_iCDF = {
113, 63, 0,
}
T.stereo_pred_quant_Q13 = {
-13732, -10050, -8266, -7526, -6500, -5000, -2950, -820, 820, 2950, 5000, 6500, 7526, 8266, 10050, 13732,
}
T.stereo_pred_joint_iCDF = {
249, 247, 246, 245, 244, 234, 210, 202, 201, 200, 197, 174, 82, 59, 56, 55, 54, 46, 22, 12,
11, 10, 9, 7, 0,
}
T.stereo_only_code_mid_iCDF = {
64, 0,
}
T.LBRR_flags_2_iCDF = {
203, 150, 0,
}
T.LBRR_flags_3_iCDF = {
215, 195, 166, 125, 110, 82, 0,
}
T.lsb_iCDF = {
120, 0,
}
T.LTPscale_iCDF = {
128, 64, 0,
}
T.type_offset_VAD_iCDF = {
232, 158, 10, 0,
}
T.type_offset_no_VAD_iCDF = {
230, 0,
}
T.NLSF_interpolation_factor_iCDF = {
243, 221, 192, 181, 0,
}
T.LTPScales_table_Q14 = {
15565, 12288, 8192,
}
T.uniform3_iCDF = {
171, 85, 0,
}
T.uniform4_iCDF = {
192, 128, 64, 0,
}
T.uniform5_iCDF = {
205, 154, 102, 51, 0,
}
T.uniform6_iCDF = {
213, 171, 128, 85, 43, 0,
}
T.uniform8_iCDF = {
224, 192, 160, 128, 96, 64, 32, 0,
}
T.NLSF_EXT_iCDF = {
100, 40, 16, 7, 3, 1, 0,
}
T.gain_iCDF = {
224, 112, 44, 15, 3, 2, 1, 0, 254, 237, 192, 132, 70, 23, 4, 0, 255, 252, 226, 155,
61, 11, 2, 0,
}
T.delta_gain_iCDF = {
250, 245, 234, 203, 71, 50, 42, 38, 35, 33, 31, 29, 28, 27, 26, 25, 24, 23, 22, 21,
20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
0,
}
T.LSFCosTab_FIX_Q12 = {
8192, 8190, 8182, 8170, 8152, 8130, 8104, 8072, 8034, 7994, 7946, 7896, 7840, 7778, 7714, 7644, 7568, 7490, 7406, 7318,
7226, 7128, 7026, 6922, 6812, 6698, 6580, 6458, 6332, 6204, 6070, 5934, 5792, 5648, 5502, 5352, 5198, 5040, 4880, 4718,
4552, 4382, 4212, 4038, 3862, 3684, 3502, 3320, 3136, 2948, 2760, 2570, 2378, 2186, 1990, 1794, 1598, 1400, 1202, 1002,
802, 602, 402, 202, 0, -202, -402, -602, -802, -1002, -1202, -1400, -1598, -1794, -1990, -2186, -2378, -2570, -2760, -2948,
-3136, -3320, -3502, -3684, -3862, -4038, -4212, -4382, -4552, -4718, -4880, -5040, -5198, -5352, -5502, -5648, -5792, -5934, -6070, -6204,
-6332, -6458, -6580, -6698, -6812, -6922, -7026, -7128, -7226, -7318, -7406, -7490, -7568, -7644, -7714, -7778, -7840, -7896, -7946, -7994,
-8034, -8072, -8104, -8130, -8152, -8170, -8182, -8190, -8192,
}
T.pulses_per_block_iCDF = {
125, 51, 26, 18, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 198, 105,
45, 22, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 213, 162, 116, 83,
59, 43, 32, 24, 18, 15, 12, 9, 7, 6, 5, 3, 2, 0, 239, 187, 116, 59, 28, 16,
11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 250, 229, 188, 135, 86, 51, 30, 19,
13, 10, 8, 6, 5, 4, 3, 2, 1, 0, 249, 235, 213, 185, 156, 128, 103, 83, 66, 53,
42, 33, 26, 21, 17, 13, 10, 0, 254, 249, 235, 206, 164, 118, 77, 46, 27, 16, 10, 7,
5, 4, 3, 2, 1, 0, 255, 253, 249, 239, 220, 191, 156, 119, 85, 57, 37, 23, 15, 10,
6, 4, 2, 0, 255, 253, 251, 246, 237, 223, 203, 179, 152, 124, 98, 75, 55, 40, 29, 21,
15, 0, 255, 254, 253, 247, 220, 162, 106, 67, 42, 28, 18, 12, 9, 6, 4, 3, 2, 0,
}
T.rate_levels_iCDF = {
241, 190, 178, 132, 87, 74, 41, 14, 0, 223, 193, 157, 140, 106, 57, 39, 18, 0,
}
T.shell_code_table0 = {
128, 0, 214, 42, 0, 235, 128, 21, 0, 244, 184, 72, 11, 0, 248, 214, 128, 42, 7, 0,
248, 225, 170, 80, 25, 5, 0, 251, 236, 198, 126, 54, 18, 3, 0, 250, 238, 211, 159, 82,
35, 15, 5, 0, 250, 231, 203, 168, 128, 88, 53, 25, 6, 0, 252, 238, 216, 185, 148, 108,
71, 40, 18, 4, 0, 253, 243, 225, 199, 166, 128, 90, 57, 31, 13, 3, 0, 254, 246, 233,
212, 183, 147, 109, 73, 44, 23, 10, 2, 0, 255, 250, 240, 223, 198, 166, 128, 90, 58, 33,
16, 6, 1, 0, 255, 251, 244, 231, 210, 181, 146, 110, 75, 46, 25, 12, 5, 1, 0, 255,
253, 248, 238, 221, 196, 164, 128, 92, 60, 35, 18, 8, 3, 1, 0, 255, 253, 249, 242, 229,
208, 180, 146, 110, 76, 48, 27, 14, 7, 3, 1, 0,
}
T.shell_code_table1 = {
129, 0, 207, 50, 0, 236, 129, 20, 0, 245, 185, 72, 10, 0, 249, 213, 129, 42, 6, 0,
250, 226, 169, 87, 27, 4, 0, 251, 233, 194, 130, 62, 20, 4, 0, 250, 236, 207, 160, 99,
47, 17, 3, 0, 255, 240, 217, 182, 131, 81, 41, 11, 1, 0, 255, 254, 233, 201, 159, 107,
61, 20, 2, 1, 0, 255, 249, 233, 206, 170, 128, 86, 50, 23, 7, 1, 0, 255, 250, 238,
217, 186, 148, 108, 70, 39, 18, 6, 1, 0, 255, 252, 243, 226, 200, 166, 128, 90, 56, 30,
13, 4, 1, 0, 255, 252, 245, 231, 209, 180, 146, 110, 76, 47, 25, 11, 4, 1, 0, 255,
253, 248, 237, 219, 194, 163, 128, 93, 62, 37, 19, 8, 3, 1, 0, 255, 254, 250, 241, 226,
205, 177, 145, 111, 79, 51, 30, 15, 6, 2, 1, 0,
}
T.shell_code_table2 = {
129, 0, 203, 54, 0, 234, 129, 23, 0, 245, 184, 73, 10, 0, 250, 215, 129, 41, 5, 0,
252, 232, 173, 86, 24, 3, 0, 253, 240, 200, 129, 56, 15, 2, 0, 253, 244, 217, 164, 94,
38, 10, 1, 0, 253, 245, 226, 189, 132, 71, 27, 7, 1, 0, 253, 246, 231, 203, 159, 105,
56, 23, 6, 1, 0, 255, 248, 235, 213, 179, 133, 85, 47, 19, 5, 1, 0, 255, 254, 243,
221, 194, 159, 117, 70, 37, 12, 2, 1, 0, 255, 254, 248, 234, 208, 171, 128, 85, 48, 22,
8, 2, 1, 0, 255, 254, 250, 240, 220, 189, 149, 107, 67, 36, 16, 6, 2, 1, 0, 255,
254, 251, 243, 227, 201, 166, 128, 90, 55, 29, 13, 5, 2, 1, 0, 255, 254, 252, 246, 234,
213, 183, 147, 109, 73, 43, 22, 10, 4, 2, 1, 0,
}
T.shell_code_table3 = {
130, 0, 200, 58, 0, 231, 130, 26, 0, 244, 184, 76, 12, 0, 249, 214, 130, 43, 6, 0,
252, 232, 173, 87, 24, 3, 0, 253, 241, 203, 131, 56, 14, 2, 0, 254, 246, 221, 167, 94,
35, 8, 1, 0, 254, 249, 232, 193, 130, 65, 23, 5, 1, 0, 255, 251, 239, 211, 162, 99,
45, 15, 4, 1, 0, 255, 251, 243, 223, 186, 131, 74, 33, 11, 3, 1, 0, 255, 252, 245,
230, 202, 158, 105, 57, 24, 8, 2, 1, 0, 255, 253, 247, 235, 214, 179, 132, 84, 44, 19,
7, 2, 1, 0, 255, 254, 250, 240, 223, 196, 159, 112, 69, 36, 15, 6, 2, 1, 0, 255,
254, 253, 245, 231, 209, 176, 136, 93, 55, 27, 11, 3, 2, 1, 0, 255, 254, 253, 252, 239,
221, 194, 158, 117, 76, 42, 18, 4, 3, 2, 1, 0,
}
T.shell_code_table_offsets = {
0, 0, 2, 5, 9, 14, 20, 27, 35, 44, 54, 65, 77, 90, 104, 119, 135,
}
T.sign_iCDF = {
254, 49, 67, 77, 82, 93, 99, 198, 11, 18, 24, 31, 36, 45, 255, 46, 66, 78, 87, 94,
104, 208, 14, 21, 32, 42, 51, 66, 255, 94, 104, 109, 112, 115, 118, 248, 53, 69, 80, 88,
95, 102,
}
T.CB_lags_stage2_10_ms = {
0, 1, 0, 0, 0, 1,
}
T.CB_lags_stage3_10_ms = {
0, 0, 1, -1, 1, -1, 2, -2, 2, -2, 3, -3, 0, 1, 0, 1, -1, 2, -1, 2,
-2, 3, -2, 3,
}
T.CB_lags_stage2 = {
0, 2, -1, -1, -1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 2, 1, 0, 1, 1,
0, 0, -1, -1,
}
T.CB_lags_stage3 = {
0, 0, 1, -1, 0, 1, -1, 0, -1, 1, -2, 2, -2, -2, 2, -3, 2, 3, -3, -4,
3, -4, 4, 4, -5, 5, -6, -5, 6, -7, 6, 5, 8, -9, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0, 1, -1, -1, 1, -1, 2, 1, -1, 2,
-2, -2, 2, -2, 2, 2, 3, -3, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0,
0, 1, -1, 1, 0, 0, 2, 1, -1, 2, -1, -1, 2, -1, 2, 2, -1, 3, -2, -2,
-2, 3, 0, 1, 0, 0, 1, 0, 1, -1, 2, -1, 2, -1, 2, 3, -2, 3, -2, -2,
4, 4, -3, 5, -3, -4, 6, -4, 6, 5, -5, 8, -6, -5, -7, 9,
}
T.resampler_frac_FIR_12 = {
189, -600, 617, 30567, 117, -159, -1070, 29704, 52, 221, -2392, 28276, -4, 529, -3350, 26341, -48, 758, -3956, 23973,
-80, 905, -4235, 21254, -99, 972, -4222, 18278, -107, 967, -3957, 15143, -103, 896, -3487, 11950, -91, 773, -2865, 8798,
-71, 611, -2143, 5784, -46, 425, -1375, 2996,
}
return T
+408
View File
@@ -0,0 +1,408 @@
--!strict
-- audio/opus: Ogg Opus (RFC 6716 codec, RFC 7845 encapsulation). Absorbed from opus-luau dd2b4e5 (same author; a
-- port of the libopus 1.6 decoder, BSD: licenses/libopus-BSD.txt): the range decoder, CELT (float), SILK
-- (bit-exact fixed point), hybrid, mode transitions, PLC, multistream (mapping families 0, 1, 255).
-- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix,
-- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms
-- pre-roll), damaged files (concealment). Output is always 48 kHz f32.
-- Not supported: encoding, mapping family 3 (ambisonics projection), chained streams (the first Opus stream is
-- decoded), CELT pitch PLC (noise PLC only).
-- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an
-- optional output buffer; decode() fully decodes to an Audio.
--
-- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ...
-- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio
-- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Ogg = require("@formats/containers/Ogg")
local Decoder = require("@formats/audio/opus/Decoder")
local Packet = require("@formats/audio/opus/Packet")
local RangeDecoder = require("@formats/audio/opus/RangeDecoder")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
-- ------------------------------------------------------------------------------------------------ contract
local Opus = {
name = "opus",
category = "audio",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type OpenOptions = {
verify: boolean?, -- check the Ogg page CRCs (default true; false decodes damaged files)
stereo: boolean?, -- downmix more than 2 channels to stereo (default false; dec.channels is then 2)
}
-- ------------------------------------------------------------------------------------------------ constants
local SAMPLE_RATE = 48000
-- stereo downmix weights for the Vorbis channel orders of mapping family 1 (3 to 8 channels), as in opusfile
local DOWNMIX = {
[3] = { 0.5858, 0, 0.4142, 0.4142, 0, 0.5858 },
[4] = { 0.4226, 0, 0, 0.4226, 0.366, 0.2114, 0.2114, 0.366 },
[5] = { 0.651, 0, 0.46, 0.46, 0, 0.651, 0.5636, 0.3254, 0.3254, 0.5636 },
[6] = { 0.529, 0, 0.3741, 0.3741, 0, 0.529, 0.4582, 0.2645, 0.2645, 0.4582, 0.3741, 0.3741 },
[7] = { 0.4553, 0, 0.322, 0.322, 0, 0.4553, 0.3943, 0.2277, 0.2277, 0.3943, 0.2788, 0.2788, 0.322, 0.322 },
[8] = { 0.3886, 0, 0.2748, 0.2748, 0, 0.3886, 0.3366, 0.1943, 0.1943, 0.3366, 0.3366, 0.1943, 0.1943, 0.3366, 0.2748, 0.2748 },
}
local PREROLL = 3840 -- 80 ms, RFC 7845 section 4.6
local MAX_PACKET = 5760 -- 120 ms
export type Head = {
version: number,
channels: number,
preSkip: number,
inputSampleRate: number,
outputGain: number, -- Q7.8 dB
mappingFamily: number,
streams: number,
coupled: number,
mapping: { number },
}
-- OpusHead (RFC 7845 section 5.1). Returns the header or nil, message.
local function parseHead(b: buffer, off: number, size: number): (Head?, string?)
if size < 19 or buffer.readstring(b, off, 8) ~= "OpusHead" then
return nil, "not an OpusHead packet"
end
local version = buffer.readu8(b, off + 8)
if bit32.rshift(version, 4) ~= 0 then
return nil, "unsupported OpusHead version " .. version
end
local channels = buffer.readu8(b, off + 9)
if channels < 1 then
return nil, "OpusHead: zero channels"
end
local head: Head = {
version = version,
channels = channels,
preSkip = buffer.readu16(b, off + 10),
inputSampleRate = buffer.readu32(b, off + 12),
outputGain = buffer.readi16(b, off + 16),
mappingFamily = buffer.readu8(b, off + 18),
streams = 1,
coupled = channels - 1,
mapping = {},
}
if head.mappingFamily == 0 then
if channels > 2 then
return nil, "OpusHead: mapping family 0 with more than 2 channels"
end
head.mapping = if channels == 2 then { 0, 1 } else { 0 }
else
if head.mappingFamily == 3 then
return nil, "unsupported channel mapping family 3 (projection)"
end
if size < 21 + channels then
return nil, "OpusHead: truncated channel mapping table"
end
head.streams = buffer.readu8(b, off + 19)
head.coupled = buffer.readu8(b, off + 20)
if head.streams < 1 or head.coupled > head.streams or head.streams + head.coupled > 255 then
return nil, "OpusHead: bad stream counts"
end
for c = 0, channels - 1 do
local m = buffer.readu8(b, off + 21 + c)
if m ~= 255 and m >= head.streams + head.coupled then
return nil, "OpusHead: bad channel mapping"
end
head.mapping[c + 1] = m
end
end
return head, nil
end
-- OpusTags (RFC 7845 section 5.2): vendor string and a table of lower-cased field names to values (repeated
-- fields joined with "; ").
local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string })
local tags = {}
if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then
return "", tags
end
local p = off + 8
local e = off + size
local vlen = buffer.readu32(b, p)
p += 4
if p + vlen > e then
return "", tags
end
local vendor = buffer.readstring(b, p, vlen)
p += vlen
if p + 4 > e then
return vendor, tags
end
local n = buffer.readu32(b, p)
p += 4
for _ = 1, n do
if p + 4 > e then
break
end
local l = buffer.readu32(b, p)
p += 4
if p + l > e then
break
end
local s = buffer.readstring(b, p, l)
p += l
local eq = string.find(s, "=", 1, true)
if eq then
local k = string.lower(string.sub(s, 1, eq - 1))
local v = string.sub(s, eq + 1)
tags[k] = if tags[k] then tags[k] .. "; " .. v else v
end
end
return vendor, tags
end
Opus.Decoder = Decoder
Opus.Packet = Packet
Opus.RangeDecoder = RangeDecoder
Opus.Celt = Celt
Opus.Silk = Silk
Opus.parseHead = parseHead
Opus.parseTags = parseTags
Opus.SAMPLE_RATE = SAMPLE_RATE
-- ------------------------------------------------------------------------------------------------ sniff
-- 1 when the file starts with an Ogg page whose first packet is an OpusHead
function Opus.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "OggS" then
return 0
end
local nseg = r:peekU8(26)
if nseg < 1 then
return 0
end
return if r:peek(8, 27 + nseg) == "OpusHead" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Audio | nil, Err: the whole stream (48 kHz f32)
function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Opus.open(r, opts)
if not dec then
return nil, err
end
local ch = dec.channels
local a = Types.Audio.new(SAMPLE_RATE, ch, dec.frames)
local total = 0
while total < dec.frames do
local pcm, n = dec:read(math.min(65536, dec.frames - total))
if n == 0 then
break
end
buffer.copy(a.samples, total * ch * 4, pcm, 0, n * ch * 4)
total += n
end
if total < dec.frames then -- a truncated file: keep what decoded
local s = buffer.create(total * ch * 4)
buffer.copy(s, 0, a.samples, 0, total * ch * 4)
a.samples = s
a.frames = total
end
a.tags = dec.tags
a.meta.source = { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate }
return a, nil
end
-- ------------------------------------------------------------------------------------------------ open
local Stream = {}
Stream.__index = Stream
-- Decodes the next packet into the pending buffer. Returns false at the end of the stream.
local function decodeNext(self: any): boolean
local p = self.demux:nextPacket(self.serial)
if p == nil then
return false
end
local n
if p.size > 0 then
n = Decoder.decodeMultistream(self.ms, p.data, p.offset, p.size, self.pend, 1, MAX_PACKET)
else
n = -1
end
if n < 0 then
-- corrupt or empty packet: conceal for its nominal duration
local dur = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else -1
if dur <= 0 then
dur = self.lastDuration
end
n = Decoder.decodeMultistream(self.ms, nil, 0, 0, self.pend, 1, dur)
if n < 0 then
n = dur
for i = 1, n * self.channels do
self.pend[i] = 0
end
end
end
self.lastDuration = n
self.pendStart = self.decoded
self.pendLen = n
self.pendPos = 0
self.decoded += n
return true
end
-- dec:read(maxFrames, out?) -> buffer of interleaved f32 samples, frames read (0 at the end of the stream). out (if
-- given and big enough) is filled instead of a new buffer.
function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, number)
local ch = self.channels
local mf = if type(maxFrames) == "number" and maxFrames == maxFrames then maxFrames else 0
local want = math.max(0, math.min(math.floor(mf), self.endSample - self.next))
local reuse = into ~= nil and buffer.len(into) >= want * ch * 4
local out = if reuse then into :: buffer else buffer.create(want * ch * 4)
local got = 0
local gain = self.gain
while got < want do
if self.pendPos >= self.pendLen then
if not decodeNext(self) then
break
end
end
-- skip decoded samples before the next wanted one (pre-skip, seek pre-roll)
local s = self.pendStart + self.pendPos
if s < self.next then
self.pendPos = math.min(self.pendLen, self.pendPos + (self.next - s))
continue
end
local n = math.min(self.pendLen - self.pendPos, want - got)
if self.downmix then
Decoder.writeDownmix(self.pend, self.pendPos * self.sourceChannels, n, self.sourceChannels, self.downmix, gain, out, got * 8)
else
Decoder.writeF32(self.pend, self.pendPos * ch, n * ch, gain, out, got * ch * 4)
end
self.pendPos += n
got += n
self.next += n
end
if got < want then
if not reuse then
local trimmed = buffer.create(got * ch * 4)
buffer.copy(trimmed, 0, out, 0, got * ch * 4)
out = trimmed
end
self.endSample = self.next -- the stream ended early (truncated file)
end
return out, got
end
-- current playback position in seconds
function Stream.position(self: any): number
return (self.next - self.preSkip) / SAMPLE_RATE
end
-- seek to a time in seconds (clamped to the stream): granule bisection with 80 ms pre-roll
function Stream.seek(self: any, seconds: number)
local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0
local p = math.floor(math.max(0, math.min(sec, 1e12)) * SAMPLE_RATE + 0.5)
p = math.min(p, self.frames)
local target = p + self.preSkip -- decoded-sample index of the wanted sample
Decoder.resetMultistream(self.ms)
self.pendLen, self.pendPos = 0, 0
local g = target - PREROLL + self.startGranule
local start = -1
if g > self.startGranule then
start = self.demux:seekGranule(self.serial, g) or -1
end
if start < 0 then
self.demux:rewind(self.serial)
self.demux:nextPacket(self.serial) -- OpusHead
self.demux:nextPacket(self.serial) -- OpusTags
self.decoded = 0
else
self.decoded = start - self.startGranule
end
self.pendStart = self.decoded
self.next = target
end
-- open(r, opts?) -> Decoder | nil, Err (r: a core/Bytes Reader, or a buffer)
function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?)
local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil)
if not demux then
return nil, derr
end
local serial = demux:find("opus")
if serial == nil then
return nil, Err.new(Err.CORRUPT, "no Opus stream in the Ogg file")
end
local hp = demux:nextPacket(serial)
if hp == nil then
return nil, Err.new(Err.TRUNCATED, "missing OpusHead")
end
local head, herr = parseHead(hp.data, hp.offset, hp.size)
if not head then
return nil, Err.new(if string.find(herr or "", "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT, herr or "bad OpusHead")
end
local tp = demux:nextPacket(serial)
if tp == nil then
return nil, Err.new(Err.TRUNCATED, "missing OpusTags")
end
local vendor, tags = parseTags(tp.data, tp.offset, tp.size)
-- granule of the first audio sample: first page granule minus the packets that end on it
local startGranule = 0
local sum = 0
while true do
local p = demux:nextPacket(serial)
if p == nil then
break
end
local d = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else 0
sum += math.max(d, 0)
if p.granule ~= -1 then
startGranule = math.max(0, p.granule - sum)
break
end
end
demux:rewind(serial)
demux:nextPacket(serial)
demux:nextPacket(serial)
local info = demux:stream(serial)
local last = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else startGranule
local frames = math.max(0, last - startGranule - head.preSkip)
local downmix = nil
if opts and opts.stereo and head.channels > 2 then
downmix = DOWNMIX[head.channels]
if downmix == nil or head.mappingFamily ~= 1 then -- unknown layout: every channel to both sides, equally
downmix = table.create(head.channels * 2, 1 / head.channels)
end
end
local self = setmetatable({
demux = demux,
serial = serial,
head = head,
vendor = vendor,
tags = tags,
sampleRate = SAMPLE_RATE,
channels = if downmix then 2 else head.channels,
sourceChannels = head.channels,
downmix = downmix,
frames = frames,
duration = frames / SAMPLE_RATE,
bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / SAMPLE_RATE)) else 0,
preSkip = head.preSkip,
startGranule = startGranule,
gain = 10 ^ (head.outputGain / (20 * 256)),
ms = Decoder.newMultistream(head.channels, head.streams, head.coupled, head.mapping),
pend = table.create(MAX_PACKET * head.channels, 0),
pendStart = 0,
pendLen = 0,
pendPos = 0,
decoded = 0, -- decoded-sample index of the next packet's first sample
next = head.preSkip, -- decoded-sample index of the next sample read() returns
endSample = head.preSkip + frames,
lastDuration = 960,
}, Stream)
return self, nil
end
return Opus
+326
View File
@@ -0,0 +1,326 @@
--!strict
--!native
--!optimize 2
-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers).
-- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau)
-- only calls them with ranges it has checked against the source length and the output size.
local readu8, readi8, readu16, readi16, readu32, readi32 =
buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32
local readf32, readf64, writef32, writeu32 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writeu32
local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap
local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writei16, buffer.writei32
local Codecs = {}
-- Integer PCM: count samples of `bytes` bytes each (1 = unsigned 8-bit, 2 / 3 / 4 = signed), little- or big-endian,
-- from src[off] to dst (f32) starting at sample index d.
function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean)
local o = d * 4
if bytes == 1 then
for i = 0, count - 1 do
writef32(dst, o + i * 4, (readu8(src, off + i) - 128) / 128)
end
elseif bytes == 2 then
if be then
for i = 0, count - 1 do
local s = off + i * 2
local v = readi8(src, s) * 256 + readu8(src, s + 1)
writef32(dst, o + i * 4, v / 32768)
end
else
for i = 0, count - 1 do
writef32(dst, o + i * 4, readi16(src, off + i * 2) / 32768)
end
end
elseif bytes == 3 then
if be then
for i = 0, count - 1 do
local s = off + i * 3
local v = readi8(src, s) * 65536 + readu8(src, s + 1) * 256 + readu8(src, s + 2)
writef32(dst, o + i * 4, v / 8388608)
end
else
for i = 0, count - 1 do
local s = off + i * 3
local v = readi8(src, s + 2) * 65536 + readu16(src, s)
writef32(dst, o + i * 4, v / 8388608)
end
end
else
if be then
for i = 0, count - 1 do
local v = byteswap(readu32(src, off + i * 4))
if v >= 0x80000000 then
v -= 0x100000000
end
writef32(dst, o + i * 4, v / 2147483648)
end
else
for i = 0, count - 1 do
writef32(dst, o + i * 4, readi32(src, off + i * 4) / 2147483648)
end
end
end
end
-- IEEE float, 4 or 8 bytes. tmp: an 8-byte scratch buffer for byte-swapping big-endian values.
function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean,
tmp: buffer)
local o = d * 4
if bytes == 4 then
if be then
for i = 0, count - 1 do
writeu32(tmp, 0, byteswap(readu32(src, off + i * 4)))
writef32(dst, o + i * 4, readf32(tmp, 0))
end
else
for i = 0, count - 1 do
writef32(dst, o + i * 4, readf32(src, off + i * 4))
end
end
else
if be then
for i = 0, count - 1 do
local s = off + i * 8
writeu32(tmp, 0, byteswap(readu32(src, s + 4)))
writeu32(tmp, 4, byteswap(readu32(src, s)))
writef32(dst, o + i * 4, readf64(tmp, 0))
end
else
for i = 0, count - 1 do
writef32(dst, o + i * 4, readf64(src, off + i * 8))
end
end
end
end
-- 8-bit companded (A-law / mu-law) through a 256-entry f32 table
function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: number, tbl: buffer)
local o = d * 4
for i = 0, count - 1 do
writef32(dst, o + i * 4, readf32(tbl, readu8(src, off + i) * 4))
end
end
local IMA_STEP = buffer.create(89 * 4)
do
local steps = {
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97,
107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724,
796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026,
4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500,
20350, 22385, 24623, 27086, 29794, 32767,
}
for i, s in steps do
buffer.writei32(IMA_STEP, (i - 1) * 4, s)
end
end
local IMA_INDEX = buffer.create(16 * 4)
do
local t = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 }
for i, v in t do
buffer.writei32(IMA_INDEX, (i - 1) * 4, v)
end
end
-- IMA ADPCM (Microsoft / WAV layout), one block at src[off] of blockAlign bytes with `avail` bytes present (a
-- truncated last block decodes the whole 8-sample groups it has). Writes interleaved f32 to dst from frame 0 and
-- returns the frame count.
function Codecs.imaBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer): number
if avail < 4 * ch then
return 0
end
-- groups of 8 samples per channel (4 bytes each) after the per-channel headers
local groups = (avail - 4 * ch) // (4 * ch)
local frames = math.min(spb, 1 + groups * 8)
for c = 0, ch - 1 do
local pred = readi16(src, off + c * 4)
local index = readu8(src, off + c * 4 + 2)
if index > 88 then
index = 88
end
writef32(dst, c * 4, pred / 32768)
local f = 1
local g = 0
while f < frames do
local p = off + 4 * ch + (g * ch + c) * 4
for k = 0, 7 do
if f >= frames then
break
end
local b = readu8(src, p + rshift(k, 1))
local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4)
local step = buffer.readi32(IMA_STEP, index * 4)
local diff = rshift(step, 3)
if band(nib, 1) ~= 0 then
diff += rshift(step, 2)
end
if band(nib, 2) ~= 0 then
diff += rshift(step, 1)
end
if band(nib, 4) ~= 0 then
diff += step
end
if band(nib, 8) ~= 0 then
pred -= diff
else
pred += diff
end
if pred > 32767 then
pred = 32767
elseif pred < -32768 then
pred = -32768
end
index += buffer.readi32(IMA_INDEX, nib * 4)
if index < 0 then
index = 0
elseif index > 88 then
index = 88
end
writef32(dst, (f * ch + c) * 4, pred / 32768)
f += 1
end
g += 1
end
end
return frames
end
local MS_ADAPT = buffer.create(16 * 4)
do
local t = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 }
for i, v in t do
buffer.writei32(MS_ADAPT, (i - 1) * 4, v)
end
end
-- MS ADPCM, one block. coefs: i32 pairs (coef1, coef2) x ncoef (256 = 1.0). state: 5 * ch i32 scratch.
-- Returns the frame count (a truncated last block decodes the whole bytes it has).
function Codecs.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer,
coefs: buffer, ncoef: number, state: buffer): number
local hdr = 7 * ch
if avail < hdr or ncoef < 1 then
return 0
end
local frames = math.min(spb, 2 + ((avail - hdr) * 2) // ch)
-- state per channel: c1, c2, idelta, s1, s2 (5 i32)
for c = 0, ch - 1 do
local pi = readu8(src, off + c)
if pi >= ncoef then
pi = ncoef - 1
end
local idelta = readi16(src, off + ch + c * 2)
local s1 = readi16(src, off + 3 * ch + c * 2)
local s2 = readi16(src, off + 5 * ch + c * 2)
local so = c * 20
buffer.writei32(state, so, buffer.readi32(coefs, pi * 8))
buffer.writei32(state, so + 4, buffer.readi32(coefs, pi * 8 + 4))
buffer.writei32(state, so + 8, idelta)
buffer.writei32(state, so + 12, s1)
buffer.writei32(state, so + 16, s2)
writef32(dst, c * 4, s2 / 32768)
if frames > 1 then
writef32(dst, (ch + c) * 4, s1 / 32768)
end
end
-- nibbles, high first, channels interleaved per nibble
local total = (frames - 2) * ch
for k = 0, total - 1 do
local b = readu8(src, off + hdr + rshift(k, 1))
local nib = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15)
local c = k % ch
local so = c * 20
local c1, c2 = buffer.readi32(state, so), buffer.readi32(state, so + 4)
local idelta = buffer.readi32(state, so + 8)
local s1, s2 = buffer.readi32(state, so + 12), buffer.readi32(state, so + 16)
local p = s1 * c1 + s2 * c2
p = if p >= 0 then p // 256 else -((-p) // 256)
local sn = if nib >= 8 then nib - 16 else nib
p += sn * idelta
if p > 32767 then
p = 32767
elseif p < -32768 then
p = -32768
end
idelta = (buffer.readi32(MS_ADAPT, nib * 4) * idelta) // 256
if idelta < 16 then
idelta = 16
elseif idelta > 2796202 then -- INT_MAX / 768, as ffmpeg
idelta = 2796202
end
buffer.writei32(state, so + 8, idelta)
buffer.writei32(state, so + 12, p)
buffer.writei32(state, so + 16, s1)
writef32(dst, (2 * ch + k) * 4, p / 32768)
end
return frames
end
-- copy frames from a block cache into the output: count f32 values
function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number)
buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4)
end
-- Encoder: count f32 samples from src (sample index s) to dst[off] as `kind` ("u8", "s16", "s24", "s32", "f32"),
-- little-endian, rounding to nearest and clamping to the integer range. Ranges are checked by the caller.
function Codecs.quantize(src: buffer, s: number, dst: buffer, off: number, count: number, kind: string)
local so = s * 4
if kind == "f32" then
buffer.copy(dst, off, src, so, count * 4)
elseif kind == "s16" then
for i = 0, count - 1 do
local v = math.floor(readf32(src, so + i * 4) * 32768 + 0.5)
if v > 32767 then
v = 32767
elseif v < -32768 then
v = -32768
elseif v ~= v then
v = 0
end
writei16(dst, off + i * 2, v)
end
elseif kind == "s24" then
for i = 0, count - 1 do
local v = math.floor(readf32(src, so + i * 4) * 8388608 + 0.5)
if v > 8388607 then
v = 8388607
elseif v < -8388608 then
v = -8388608
elseif v ~= v then
v = 0
end
if v < 0 then
v += 16777216
end
local o = off + i * 3
writeu16(dst, o, v % 65536)
writeu8(dst, o + 2, v // 65536)
end
elseif kind == "s32" then
for i = 0, count - 1 do
local v = math.floor(readf32(src, so + i * 4) * 2147483648 + 0.5)
if v > 2147483647 then
v = 2147483647
elseif v < -2147483648 then
v = -2147483648
elseif v ~= v then
v = 0
end
writei32(dst, off + i * 4, v)
end
else -- u8
for i = 0, count - 1 do
local v = math.floor(readf32(src, so + i * 4) * 128 + 0.5)
if v > 127 then
v = 127
elseif v < -128 then
v = -128
elseif v ~= v then
v = 0
end
writeu8(dst, off + i, v + 128)
end
end
end
return Codecs
+650
View File
@@ -0,0 +1,650 @@
--!strict
--!optimize 2
-- audio/wav: WAVE in RIFF / RIFX (big-endian) / RF64 / BW64. Absorbed from wav-luau fd9a909 (same author, no
-- third-party code; the streaming decoder) on the shared containers/Riff, plus a new encoder.
-- Decode: PCM 8 / 16 / 24 / 32 bit, IEEE float 32 / 64, A-law, mu-law, IMA ADPCM, MS ADPCM, WAVE_FORMAT_EXTENSIBLE
-- wrapping any of them; odd-sized chunks with or without the pad byte; LIST/INFO tags; a data size of 0 or 0xFFFFFFFF
-- (streamed output) or past the end means "up to the end of the file" (a truncated file decodes what it has).
-- Encode: PCM u8 / s16 / s24 / s32 and float32 from an Audio or a streaming Decoder, WAVE_FORMAT_EXTENSIBLE when
-- there are more than 2 channels, more than 16 bits or over 48 kHz (as ffmpeg), fact for float, LIST/INFO tags,
-- RF64 (ds64) automatically past 4 GiB (Wav.encodeParts streams files over the 1 GiB buffer limit) or on request.
-- Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output.
--
-- local dec = Wav.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(4096) -> f32 buffer, frames
-- local audio = Wav.decode(Bytes.reader(buf)) -- Types.Audio
-- local file = Wav.encode(audio, { sampleFormat = "s24" })
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Riff = require("@formats/containers/Riff")
local Codecs = require("@formats/audio/wav/Codecs")
-- ------------------------------------------------------------------------------------------------ contract
local Wav = {
name = "wav",
category = "audio",
extensions = { "wav", "wave", "rf64", "bw64" },
mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type Tags = { [string]: string }
export type OpenOptions = {
maxBytes: number?, -- unused (the file is already in memory); kept for symmetry
}
export type EncodeOptions = {
sampleFormat: ("u8" | "s16" | "s24" | "s32" | "f32")?, -- default "s16"
rf64: (boolean | "auto")?, -- default "auto": RF64 only when the file passes 4 GiB
extensible: boolean?, -- force (true) or forbid (false) WAVE_FORMAT_EXTENSIBLE; default as ffmpeg
channelMask: number?, -- the EXTENSIBLE speaker mask (default: ffmpeg's default layout for the channel count)
tags: Tags?, -- default: the Audio's tags (title, artist, album, comment, date, genre, track, ...)
rf64Threshold: number?, -- testing: the RIFF size past which "auto" switches to RF64 (default 0xFFFFFFFF)
}
-- ------------------------------------------------------------------------------------------------ constants
Wav.FORMAT_PCM = 1
Wav.FORMAT_MS_ADPCM = 2
Wav.FORMAT_FLOAT = 3
Wav.FORMAT_ALAW = 6
Wav.FORMAT_MULAW = 7
Wav.FORMAT_IMA_ADPCM = 0x11
Wav.FORMAT_EXTENSIBLE = 0xFFFE
local FORMAT_NAMES = {
[1] = "pcm",
[2] = "ms_adpcm",
[3] = "float",
[6] = "alaw",
[7] = "mulaw",
[0x11] = "ima_adpcm",
}
-- LIST/INFO ids -> tag names
local INFO_TAGS = {
INAM = "title",
IART = "artist",
IPRD = "album",
ICMT = "comment",
ICRD = "date",
IGNR = "genre",
ITRK = "track",
IPRT = "track",
ISFT = "encoder",
ICOP = "copyright",
IENG = "engineer",
ISBJ = "subject",
IKEY = "keywords",
}
-- A-law / mu-law -> f32 tables (G.711, as ffmpeg's alaw2linear / ulaw2linear)
local ALAW, MULAW = buffer.create(1024), buffer.create(1024)
do
for i = 0, 255 do
local a = bit32.bxor(i, 0x55)
local t = bit32.band(a, 15)
local seg = bit32.rshift(bit32.band(a, 0x70), 4)
if seg > 0 then
t = bit32.lshift(t * 2 + 1 + 32, seg + 2)
else
t = bit32.lshift(t * 2 + 1, 3)
end
if bit32.band(a, 0x80) == 0 then
t = -t
end
buffer.writef32(ALAW, i * 4, t / 32768)
local u = bit32.band(bit32.bnot(i), 255)
local m = bit32.lshift(bit32.lshift(bit32.band(u, 15), 3) + 0x84, bit32.rshift(bit32.band(u, 0x70), 4))
local v = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84
buffer.writef32(MULAW, i * 4, v / 32768)
end
end
local Decoder = {}
Decoder.__index = Decoder
export type Decoder = typeof(setmetatable(
{} :: {
sampleRate: number,
channels: number,
frames: number,
duration: number,
bitrate: number,
tags: Tags,
format: string,
formatTag: number,
bitsPerSample: number,
blockAlign: number,
container: string,
dataOffset: number,
dataSize: number,
truncated: boolean,
channelMask: number?,
validBits: number?,
_buf: buffer,
_pos: number,
_be: boolean,
_bytes: number,
_kind: string,
_spb: number,
_cache: buffer?,
_cacheBlock: number,
_cacheFrames: number,
_coefs: buffer?,
_ncoef: number,
_state: buffer?,
_tmp: buffer,
},
Decoder
))
local function trimTag(s: string): string
-- strip trailing NULs / spaces
local e = #s
while e > 0 do
local c = string.byte(s, e)
if c ~= 0 and c ~= 32 then
break
end
e -= 1
end
local z = string.find(s, "\0", 1, true)
if z and z <= e then
e = z - 1
end
return string.sub(s, 1, e)
end
-- ------------------------------------------------------------------------------------------------ sniff
function Wav.sniff(r: Bytes.Reader): number
return if Riff.sniff(r) == "WAVE" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> Types.Audio | nil, Err: the whole file
function Wav.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Wav.open(r, opts)
if not dec then
return nil, err
end
local a = Types.Audio.new(dec.sampleRate, dec.channels, dec.frames)
local _, n = dec:read(dec.frames, a.samples)
if n < dec.frames then
local s = buffer.create(n * dec.channels * 4)
buffer.copy(s, 0, a.samples, 0, n * dec.channels * 4)
a.samples, a.frames = s, n
end
a.tags = dec.tags
a.meta.source = {
format = "wav",
codec = dec.format,
bitDepth = dec.bitsPerSample,
container = dec.container,
channelMask = dec.channelMask,
truncated = dec.truncated,
}
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local SAMPLE_BYTES = { u8 = 1, s16 = 2, s24 = 3, s32 = 4, f32 = 4 }
-- ffmpeg's default speaker masks per channel count (av_channel_layout_default)
local MASKS = { [1] = 0x4, [2] = 0x3, [3] = 0xB, [4] = 0x107, [5] = 0x37, [6] = 0x3F, [7] = 0x70F, [8] = 0x63F }
local GUID_TAIL = "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" -- KSDATAFORMAT_SUBTYPE_* after the 2-byte format tag
-- tags -> LIST/INFO ids (the first id per name)
local TAG_IDS = { title = "INAM", artist = "IART", album = "IPRD", comment = "ICMT", date = "ICRD", genre = "IGNR", track = "ITRK", encoder = "ISFT", copyright = "ICOP", engineer = "IENG", subject = "ISBJ", keywords = "IKEY" }
local BLOCK = 65536 -- frames per data piece when streaming a Decoder
-- the body of the encoder: { buffer } pieces of the file | nil, Err
local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean): (any, Err.Err?)
if type(value) ~= "table" then
return nil, Err.new(Err.ARG, "encode: needs an Audio or a Decoder")
end
local o: EncodeOptions = opts or {}
local kind = o.sampleFormat or "s16"
local bytes: number? = SAMPLE_BYTES[kind]
if not bytes then
return nil, Err.new(Err.ARG, "encode: sampleFormat must be u8, s16, s24, s32 or f32")
end
local rate: number, ch: number = value.sampleRate, value.channels
if type(rate) ~= "number" or rate < 1 or rate > 4294967295 or rate % 1 ~= 0 then
return nil, Err.new(Err.ARG, "encode: bad sample rate")
end
if type(ch) ~= "number" or ch < 1 or ch > 65535 or ch % 1 ~= 0 then
return nil, Err.new(Err.ARG, "encode: bad channel count")
end
local isAudio = type(value.samples) == "buffer"
if not isAudio and type(value.read) ~= "function" then
return nil, Err.new(Err.ARG, "encode: needs an Audio (samples) or a Decoder (read)")
end
local frameBytes = bytes * ch
local pieces: { buffer } = {}
local frames: number = 0
if isAudio then
frames = (value.frames :: number?) or (buffer.len(value.samples) // (ch * 4))
if type(frames) ~= "number" or frames < 0 or buffer.len(value.samples) < frames * ch * 4 then
return nil, Err.new(Err.ARG, "encode: the samples buffer is shorter than frames * channels")
end
if not asParts and frames * frameBytes > 0x3FFFFF00 then
return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)")
end
-- pieces of at most 256 MiB
local per = math.max(1, 0x10000000 // frameBytes)
local f0 = 0
while f0 < frames do
local n = math.min(per, frames - f0)
local b = buffer.create(n * frameBytes)
Codecs.quantize(value.samples, f0 * ch, b, 0, n * ch, kind)
table.insert(pieces, b)
f0 += n
end
else
local tmp = buffer.create(BLOCK * ch * 4)
while true do
local ok, out, n = pcall(value.read, value, BLOCK, tmp)
if not ok then
return nil, Err.new(Err.ARG, "encode: the decoder failed: " .. tostring(out))
end
if type(n) ~= "number" or n <= 0 or type(out) ~= "buffer" then
break
end
n = math.min(n, buffer.len(out) // (ch * 4))
local b = buffer.create(n * frameBytes)
Codecs.quantize(out, 0, b, 0, n * ch, kind)
table.insert(pieces, b)
frames += n
if not asParts and frames * frameBytes > 0x3FFFFF00 then
return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)")
end
end
end
local dataSize = frames * frameBytes
local bits = bytes * 8
local float = kind == "f32"
local tag = if float then 3 else 1
local extensible = ch > 2 or rate > 48000 or (not float and bits > 16)
if o.extensible ~= nil then
extensible = o.extensible
end
local w = Riff.writer("WAVE", { rf64 = if o.rf64 ~= nil then o.rf64 else "auto", sampleCount = frames, rf64Threshold = o.rf64Threshold })
local fmt = Bytes.writer(40)
fmt:u16le(if extensible then 0xFFFE else tag)
fmt:u16le(ch)
fmt:u32le(rate)
fmt:u32le(rate * frameBytes)
fmt:u16le(frameBytes)
fmt:u16le(bits)
if extensible then
fmt:u16le(22)
fmt:u16le(bits)
fmt:u32le(o.channelMask or MASKS[ch] or 0)
fmt:u16le(tag)
fmt:string(GUID_TAIL)
elseif float then
fmt:u16le(0) -- cbSize
end
w:chunk("fmt ", fmt:finish())
if float then
local fact = Bytes.writer(4)
fact:u32le(if w.rf64 == true or frames > 0xFFFFFFFF then 0xFFFFFFFF else frames) -- RF64: in ds64 (as ffmpeg)
w:chunk("fact", fact:finish())
end
local tags = o.tags or value.tags
if type(tags) == "table" then
local items = {}
local keys = {}
for k in tags do
if type(k) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
for _, k in keys do
local v = tags[k]
local id = TAG_IDS[k] or (if #k == 4 and string.upper(k) == k then k else nil)
if id and type(v) == "string" and v ~= "" then
table.insert(items, { id, v })
end
end
if #items > 0 then
w:list("INFO", items)
end
end
w:chunk("data", pieces)
local _ = dataSize
return w:finish({ parts = asParts })
end
-- encode(audio or decoder, opts?) -> buffer | nil, Err
function Wav.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
return encodeParts(value, opts, false)
end
-- encodeParts(audio or decoder, opts?) -> { buffer } | nil, Err: the file as pieces to write one after the other
-- (header, sample blocks, ...), without the 1 GiB single-buffer limit; RF64 past 4 GiB
function Wav.encodeParts(value: any, opts: EncodeOptions?): ({ buffer }?, Err.Err?)
return encodeParts(value, opts, true)
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> Decoder | nil, Err: the streaming decoder (Types.Decoder) over the file in r's range
function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?)
if type(r) == "buffer" or type(r) == "string" then
r = Bytes.reader(if type(r) == "string" then buffer.fromstring(r) else r :: any)
end
local f, ferr = Riff.read(r, { openEnded = { data = true } })
if not f then
return nil, ferr
end
if f.form ~= "WAVE" then
return nil, Err.new(Err.CORRUPT, "not a WAVE file (" .. f.form .. ")", f.base + 8)
end
local buf = f.buf
local magic = f.container
local be = f.bigEndian
local fmt: any = nil
local tags: Tags = {}
local dataOff, dataSize = -1, 0
local truncated = false
local ds64Frames: number? = if f.ds64 and f.ds64.sampleCount > 0 then f.ds64.sampleCount else nil
local factFrames: number? = nil
local function u16(o: number): number
return Riff.u16(f, o)
end
local function u32(o: number): number
return Riff.u32(f, o)
end
local function i16(o: number): number
local v = u16(o)
return if v >= 32768 then v - 65536 else v
end
for _, c in f.chunks do
local id, size, body, avail = c.id, c.size, c.offset, c.avail
if id == "fmt " and avail >= 14 then
fmt = {
tag = u16(body),
channels = u16(body + 2),
rate = u32(body + 4),
byteRate = u32(body + 8),
blockAlign = u16(body + 12),
bits = if avail >= 16 then u16(body + 14) else 8,
body = body,
avail = avail,
}
elseif id == "fact" and avail >= 4 then
factFrames = u32(body)
elseif id == "LIST" and Riff.listType(f, c) == "INFO" then
for _, sc in Riff.list(f, c) do
local name = INFO_TAGS[sc.id]
if sc.avail > 0 then
local v = trimTag(buffer.readstring(buf, sc.offset, sc.avail))
if v ~= "" then
tags[name or sc.id] = v
end
end
end
elseif id == "data" and dataOff < 0 then
dataOff = body
dataSize = avail
truncated = c.truncated
end
local _ = size
end
if not fmt then
return nil, Err.new(Err.CORRUPT, "no fmt chunk")
end
if dataOff < 0 then
return nil, Err.new(Err.CORRUPT, "no data chunk")
end
local tag, ch, rate, bits = fmt.tag, fmt.channels, fmt.rate, fmt.bits
local channelMask: number? = nil
local validBits: number? = nil
if tag == 0xFFFE then
if fmt.avail < 40 then
return nil, Err.new(Err.CORRUPT, "WAVE_FORMAT_EXTENSIBLE without its extension")
end
local valid = u16(fmt.body + 18)
channelMask = u32(fmt.body + 20)
tag = u16(fmt.body + 24) -- the GUID's first two bytes are the format tag
-- valid bits < container bits: the samples are left-justified, so decoding the container is right
validBits = valid
end
if ch < 1 or ch > 255 then
return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch)
end
if rate < 1 or rate > 4000000 then
return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate)
end
local name: string? = FORMAT_NAMES[tag]
if not name then
return nil, Err.new(Err.UNSUPPORTED, string.format("format 0x%04X", tag))
end
local dec = setmetatable({}, Decoder) :: any
dec.sampleRate = rate
dec.channels = ch
dec.tags = tags
dec.format = name
dec.formatTag = tag
dec.bitsPerSample = bits
dec.container = magic
dec.dataOffset = dataOff
dec.dataSize = dataSize
dec.channelMask = channelMask
dec._buf = buf
dec._pos = 0
dec._be = be
dec._tmp = buffer.create(8)
dec._cacheBlock = -1
dec._cacheFrames = 0
dec._ncoef = 0
local blockAlign: number = fmt.blockAlign
local frames: number
if name == "pcm" or name == "float" or name == "alaw" or name == "mulaw" then
local bytes
if name == "alaw" or name == "mulaw" then
bytes = 1
elseif name == "float" then
if bits ~= 32 and bits ~= 64 then
return nil, Err.new(Err.UNSUPPORTED, "float size " .. bits)
end
bytes = bits // 8
else
if bits < 1 or bits > 32 then
return nil, Err.new(Err.UNSUPPORTED, "PCM size " .. bits)
end
-- container: from blockAlign when it is consistent, else from the bit depth
bytes = (bits + 7) // 8
if blockAlign >= ch and blockAlign % ch == 0 and blockAlign // ch >= bytes and blockAlign // ch <= 4 then
bytes = blockAlign // ch
end
end
blockAlign = bytes * ch
dec._bytes = bytes
dec._kind = name
frames = dataSize // blockAlign
dec._spb = 1
elseif name == "ima_adpcm" or name == "ms_adpcm" then
if blockAlign < 1 then
return nil, Err.new(Err.CORRUPT, "ADPCM with blockAlign 0")
end
local spb = if fmt.avail >= 20 then u16(fmt.body + 18) else 0
if name == "ima_adpcm" then
if bits ~= 4 then
return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM size " .. bits)
end
if blockAlign < 4 * ch then
return nil, Err.new(Err.CORRUPT, "IMA ADPCM block too small")
end
local computed = (blockAlign - 4 * ch) * 2 // ch + 1
if spb < 1 or spb > computed then
spb = computed
end
else
if blockAlign < 7 * ch then
return nil, Err.new(Err.CORRUPT, "MS ADPCM block too small")
end
local computed = (blockAlign - 7 * ch) * 2 // ch + 2
if spb < 2 or spb > computed then
spb = computed
end
-- coefficients from the fmt extension, else the 7 standard pairs
local c1 = { 256, 512, 0, 192, 240, 460, 392 }
local c2 = { 0, -256, 0, 64, 0, -208, -232 }
local ncoef = 7
if fmt.avail >= 22 then
local k = u16(fmt.body + 20)
if k >= 1 and k <= 256 and fmt.avail >= 22 + 4 * k then
ncoef = k
c1, c2 = {}, {}
for i = 1, k do
c1[i] = i16(fmt.body + 22 + (i - 1) * 4)
c2[i] = i16(fmt.body + 24 + (i - 1) * 4)
end
end
end
local coefs = buffer.create(ncoef * 8)
for i = 1, ncoef do
buffer.writei32(coefs, (i - 1) * 8, c1[i])
buffer.writei32(coefs, (i - 1) * 8 + 4, c2[i])
end
dec._coefs = coefs
dec._ncoef = ncoef
dec._state = buffer.create(20 * ch)
end
if spb * ch > 2 ^ 20 then
return nil, Err.new(Err.LIMIT, "ADPCM block too large")
end
dec._kind = name
dec._spb = spb
dec._cache = buffer.create(spb * ch * 4)
local full = dataSize // blockAlign
frames = full * spb
local rest = dataSize - full * blockAlign
if rest > 0 then
-- a partial last block: the frames it holds whole
if name == "ima_adpcm" then
if rest >= 4 * ch then
frames += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8)
end
elseif rest >= 7 * ch then
frames += math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch)
end
end
-- fact: the true length (the last block is padded)
if factFrames and factFrames > 0 and factFrames < frames then
frames = factFrames
end
else
return nil, Err.new(Err.UNSUPPORTED, "format " .. name)
end
if ds64Frames and ds64Frames > 0 and ds64Frames < frames then
frames = ds64Frames
end
dec.blockAlign = blockAlign
dec.frames = frames
dec.duration = frames / rate
dec.truncated = truncated
dec.validBits = validBits
dec.bitrate = if fmt.byteRate > 0 then fmt.byteRate * 8 else math.floor(rate * blockAlign * 8 / dec._spb)
return dec, nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- Decodes up to maxFrames frames from the current position. Returns a buffer of interleaved f32 samples
-- (frames * channels values; `out` is reused when given and large enough) and the frame count (0 = end).
function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, number)
local ch = self.channels
local req = math.floor(tonumber(maxFrames) or 0)
if req ~= req then -- NaN (math.min / max treat it differently on LuaJIT)
req = 0
end
local want = math.max(0, math.min(req, self.frames - self._pos))
local dst: buffer = if out and type(out) == "buffer" and buffer.len(out) >= want * ch * 4
then out
else buffer.create(want * ch * 4)
if want == 0 then
return dst, 0
end
local kind = self._kind
if self._spb == 1 then
local off = self.dataOffset + self._pos * self.blockAlign
local count = want * ch
if kind == "pcm" then
Codecs.int(self._buf, off, dst, 0, count, self._bytes, self._be)
elseif kind == "float" then
Codecs.float(self._buf, off, dst, 0, count, self._bytes, self._be, self._tmp)
elseif kind == "alaw" then
Codecs.law(self._buf, off, dst, 0, count, ALAW)
else
Codecs.law(self._buf, off, dst, 0, count, MULAW)
end
self._pos += want
return dst, want
end
-- block formats: decode a block into the cache, copy out of it
local spb, ba = self._spb, self.blockAlign
local cache = self._cache :: buffer
local done = 0
while done < want do
local block = self._pos // spb
if block ~= self._cacheBlock then
local off = self.dataOffset + block * ba
local avail = math.min(ba, self.dataOffset + self.dataSize - off)
local got
if kind == "ima_adpcm" then
got = Codecs.imaBlock(self._buf, off, avail, ch, spb, cache)
else
got = Codecs.msBlock(self._buf, off, avail, ch, spb, cache, self._coefs :: buffer, self._ncoef,
self._state :: buffer)
end
self._cacheBlock = block
self._cacheFrames = got
end
local inBlock = self._pos - block * spb
local k = math.min(want - done, self._cacheFrames - inBlock)
if k <= 0 then
break
end
Codecs.copy(cache, inBlock * ch, dst, done * ch, k * ch)
done += k
self._pos += k
end
return dst, done
end
-- Moves to a time in seconds (clamped to the stream).
function Decoder.seek(self: Decoder, seconds: number)
local f = math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)
if f ~= f then
f = 0
end
self._pos = math.clamp(f, 0, self.frames)
end
-- Moves to a frame index (clamped).
function Decoder.seekFrame(self: Decoder, frame: number)
local f = math.floor(tonumber(frame) or 0)
if f ~= f then
f = 0
end
self._pos = math.clamp(f, 0, self.frames)
end
-- Current position in seconds.
function Decoder.position(self: Decoder): number
return self._pos / self.sampleRate
end
-- Current position in frames.
function Decoder.tell(self: Decoder): number
return self._pos
end
return Wav
+208
View File
@@ -0,0 +1,208 @@
--!strict
--!native
--!optimize 2
-- containers/Ogg/Mux: the Ogg page writer (RFC 3533), for Ogg Opus / Vorbis / FLAC output. New in formats-luau.
-- Packets are laced into pages per logical stream; a page is closed when it reaches opts.pageSize bytes of data (or
-- 255 lacing values), when a packet asks for flush, and at the end (eos). The page granule is the granule of the last
-- packet that finishes on it (-1 when none does). Pages go to the output in the order they close, so the bos pages
-- of a multiplexed file come first when every stream's first packet is written (with flush) before any other.
--
-- local mux = Mux.new({ pageSize = 4096 })
-- local s = mux:stream(0x1234) -- serial (default: 1, 2, ...)
-- s:packet(head, 0, { flush = true }) -- OpusHead / FLAC mapping header: alone on the bos page
-- s:packet(tags, 0, { flush = true })
-- s:packet(audio, granule) -- granule after this packet (samples, at the codec's rate)
-- local out = mux:finish() -- closes every stream with an eos page
--
-- Never throws: a bad argument returns false, Err.
local Err = require("@formats/core/Err")
local Page = require("@formats/containers/Ogg/Page")
local CRC = Page.CRC_TABLE
local readu8, writeu8, writeu32, writei32 = buffer.readu8, buffer.writeu8, buffer.writeu32, buffer.writei32
local bxor, lshift, rshift = bit32.bxor, bit32.lshift, bit32.rshift
local Mux = {}
Mux.__index = Mux
local Stream = {}
Stream.__index = Stream
export type Options = {
pageSize: number?, -- close a page once its data reaches this many bytes (default 4096; at most 255 * 255)
}
export type PacketOptions = {
flush: boolean?, -- close the page after this packet (headers; default false)
eos: boolean?, -- this is the stream's last packet (default false: finish() writes an empty eos page if needed)
}
-- new(opts?) -> Mux
function Mux.new(opts: Options?): any
local size = opts and opts.pageSize or 4096
if type(size) ~= "number" or size < 1 then
size = 4096
end
return setmetatable({
pageSize = math.min(size, 255 * 255),
chunks = {} :: { buffer },
total = 0,
streams = {} :: { any },
nextSerial = 1,
}, Mux)
end
-- stream(serial?) -> Stream (serials must be unique in the file)
function Mux.stream(self: any, serial: number?): any
local sr = serial or self.nextSerial
self.nextSerial = math.max(self.nextSerial, sr + 1)
local s = setmetatable({
mux = self,
serial = sr % 4294967296,
seq = 0,
lacing = {} :: { number },
parts = {} :: { any }, -- buffer, offset, length triples of the page data
dataLen = 0,
granule = -1,
continued = false, -- the page being built starts with the tail of a packet
first = true,
ended = false,
lastGranule = -1,
}, Stream)
table.insert(self.streams, s)
return s
end
-- the CRC of a page (the crc field written as zero)
local function crc(b: buffer, n: number): number
local c = 0
for i = 0, n - 1 do
c = bxor(lshift(c, 8), CRC[bxor(rshift(c, 24), readu8(b, i)) + 1])
end
return c
end
-- close the page being built (also when empty, for eos)
function Stream._flush(self: any, eos: boolean)
local nseg = #self.lacing
local n = 27 + nseg + self.dataLen
local b = buffer.create(n)
buffer.writestring(b, 0, "OggS")
local flags = (if self.continued then 1 else 0) + (if self.first then 2 else 0) + (if eos then 4 else 0)
writeu8(b, 5, flags)
local g = self.granule
if g < 0 then
writeu32(b, 6, 0xFFFFFFFF)
writei32(b, 10, -1)
else
writeu32(b, 6, g % 4294967296)
writeu32(b, 10, (g // 4294967296) % 4294967296)
end
writeu32(b, 14, self.serial)
writeu32(b, 18, self.seq % 4294967296)
writeu8(b, 26, nseg)
for i = 1, nseg do
writeu8(b, 26 + i, self.lacing[i])
end
local o = 27 + nseg
local parts = self.parts
for i = 1, #parts, 3 do
buffer.copy(b, o, parts[i], parts[i + 1], parts[i + 2])
o += parts[i + 2]
end
writeu32(b, 22, crc(b, n))
local m = self.mux
table.insert(m.chunks, b)
m.total += n
self.seq += 1
self.first = false
self.lacing, self.parts, self.dataLen, self.granule = {}, {}, 0, -1
self.continued = false
if eos then
self.ended = true
end
end
-- packet(data, granule, opts?) -> true | false, Err. data: buffer or string; granule: the position after this packet
-- (-1: unknown, not recommended); offset / length select a range of data.
function Stream.packet(self: any, data: any, granule: number, opts: PacketOptions?, offset: number?, length: number?): (boolean, Err.Err?)
if self.ended then
return false, Err.new(Err.ARG, "packet after the end of stream " .. self.serial)
end
local b: buffer
if type(data) == "string" then
b = buffer.fromstring(data)
elseif type(data) == "buffer" then
b = data
else
return false, Err.new(Err.ARG, "packet: data must be a buffer or a string")
end
if type(granule) ~= "number" then
return false, Err.new(Err.ARG, "packet: granule must be a number")
end
local off = offset or 0
local len = length or (buffer.len(b) - off)
if off < 0 or len < 0 or off + len > buffer.len(b) then
return false, Err.new(Err.ARG, "packet: range outside the buffer")
end
local pageSize = self.mux.pageSize
local left = len
local pos = off
-- lacing: 255-byte segments then one < 255 (0 when the size is a multiple of 255)
while true do
if #self.lacing == 255 or (self.dataLen >= pageSize and #self.lacing > 0) then
self:_flush(false)
self.continued = pos > off -- the next page starts inside this packet
end
local seg = math.min(left, 255)
table.insert(self.lacing, seg)
if seg > 0 then
table.insert(self.parts, b)
table.insert(self.parts, pos)
table.insert(self.parts, seg)
end
self.dataLen += seg
pos += seg
left -= seg
if seg < 255 then
break
end
end
if granule >= 0 then -- -1 (unknown) keeps the granule of an earlier packet finishing on this page
self.granule = granule
self.lastGranule = granule
end
local eos = opts and opts.eos or false
if eos then
self:_flush(true)
elseif (opts and opts.flush) or self.dataLen >= pageSize or #self.lacing == 255 then
self:_flush(false)
end
return true, nil
end
-- flush(): close the current page now (if it holds anything)
function Stream.flush(self: any)
if not self.ended and #self.lacing > 0 then
self:_flush(false)
end
end
-- finish() -> the file: closes every stream with an eos page (an empty one when its last page was already written)
function Mux.finish(self: any): buffer
for _, s in self.streams do
if not s.ended then
if #s.lacing == 0 then
s.granule = s.lastGranule
end
s:_flush(true)
end
end
local out = buffer.create(self.total)
local o = 0
for _, c in self.chunks do
buffer.copy(out, o, c, 0, buffer.len(c))
o += buffer.len(c)
end
return out
end
return Mux
+185
View File
@@ -0,0 +1,185 @@
--!strict
--!native
--!optimize 2
-- containers/Ogg/Page: Ogg pages (RFC 3533). Absorbed from ogg-luau be9f604 (same author, no third-party code): the CRC-32 (poly 0x04C11DB7, MSB first, init 0, the CRC field read as zero), header
-- parsing with bounds checks, and the capture-pattern resync (find the next valid page at or after a byte offset,
-- forwards or backwards). Nothing here throws: invalid or truncated data gives nil.
--
-- A page header (27 bytes + segment table):
-- 0 "OggS" | 4 version (0) | 5 flags (1 continued, 2 bos, 4 eos) | 6 granule (i64 LE) | 14 serial (u32)
-- 18 sequence (u32) | 22 crc (u32) | 26 segment count | 27 lacing values | data
local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32
local band, bxor, lshift, rshift = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift
local Page = {}
export type Info = {
offset: number, -- byte offset of "OggS"
size: number, -- header + segment table + data
headerSize: number, -- 27 + segment count
nsegs: number,
flags: number,
continued: boolean,
bos: boolean,
eos: boolean,
granule: number, -- -1 when no packet finishes on this page
serial: number,
sequence: number,
}
-- CRC table, MSB-first
local CRC = table.create(256, 0)
for i = 0, 255 do
local r = lshift(i, 24)
for _ = 1, 8 do
if band(r, 0x80000000) ~= 0 then
r = bxor(lshift(r, 1), 0x04C11DB7)
else
r = lshift(r, 1)
end
end
CRC[i + 1] = r
end
Page.CRC_TABLE = CRC
-- CRC of bytes [from, to) (caller guarantees bounds), continuing from crc
local function crcRange(b: buffer, from: number, to: number, crc: number): number
for i = from, to - 1 do
crc = bxor(lshift(crc, 8), CRC[bxor(rshift(crc, 24), readu8(b, i)) + 1])
end
return crc
end
-- CRC-32 of a byte range, the Ogg way (the crc field is not zeroed: use for arbitrary data)
function Page.crc32(b: buffer, offset: number?, len: number?): number
local o = offset or 0
local n = len or (buffer.len(b) - o)
if o < 0 or n < 0 or o + n > buffer.len(b) then
return 0
end
return crcRange(b, o, o + n, 0)
end
-- Parse the page at pos. Returns Info, or nil + reason ("short" if the buffer ends inside the page, "magic",
-- "version", "crc"). verify = false skips the CRC check.
function Page.parse(b: buffer, pos: number, verify: boolean?): (Info?, string?)
local size = buffer.len(b)
if pos < 0 or pos + 27 > size then
return nil, "short"
end
if readu32(b, pos) ~= 0x5367674F then -- "OggS"
return nil, "magic"
end
if readu8(b, pos + 4) ~= 0 then
return nil, "version"
end
local nsegs = readu8(b, pos + 26)
local hsize = 27 + nsegs
if pos + hsize > size then
return nil, "short"
end
local dlen = 0
for i = pos + 27, pos + hsize - 1 do
dlen += readu8(b, i)
end
local total = hsize + dlen
if pos + total > size then
return nil, "short"
end
if verify ~= false then
local c = crcRange(b, pos, pos + 22, 0)
for _ = 1, 4 do
c = bxor(lshift(c, 8), CRC[rshift(c, 24) + 1])
end
c = crcRange(b, pos + 26, pos + total, c)
if c ~= readu32(b, pos + 22) then
return nil, "crc"
end
end
local flags = readu8(b, pos + 5)
return {
offset = pos,
size = total,
headerSize = hsize,
nsegs = nsegs,
flags = flags,
continued = band(flags, 1) ~= 0,
bos = band(flags, 2) ~= 0,
eos = band(flags, 4) ~= 0,
granule = readi32(b, pos + 10) * 4294967296 + readu32(b, pos + 6),
serial = readu32(b, pos + 14),
sequence = readu32(b, pos + 18),
}, nil
end
-- The first valid page starting at an offset in [pos, limit) (limit defaults to the buffer end). Resyncs on the
-- capture pattern: bytes that are not a valid page (garbage, a bad CRC, a truncated page) are skipped.
function Page.find(b: buffer, pos: number, limit: number?, verify: boolean?): Info?
local size = buffer.len(b)
local lim = math.min(limit or size, size - 27 + 1)
if pos < 0 then
pos = 0
end
while pos < lim do
if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then
local p = Page.parse(b, pos, verify)
if p then
return p
end
end
pos += 1
end
return nil
end
-- The last valid page starting at an offset in [floor, pos] (searching backwards).
function Page.findBack(b: buffer, pos: number, floor: number?, verify: boolean?): Info?
local size = buffer.len(b)
local lo = math.max(floor or 0, 0)
if pos > size - 27 then
pos = size - 27
end
while pos >= lo do
if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then
local p = Page.parse(b, pos, verify)
if p then
return p
end
end
pos -= 1
end
return nil
end
-- The identification of a codec from a stream's first packet (the bos page's packet)
function Page.codec(b: buffer, off: number, len: number): string
local function is(s: string, at: number): boolean
if at + #s > len then
return false
end
for i = 1, #s do
if readu8(b, off + at + i - 1) ~= string.byte(s, i) then
return false
end
end
return true
end
if is("OpusHead", 0) then
return "opus"
elseif len >= 5 and readu8(b, off) == 0x7F and is("FLAC", 1) then
return "flac"
elseif len >= 7 and readu8(b, off) == 1 and is("vorbis", 1) then
return "vorbis"
elseif len >= 7 and readu8(b, off) == 0x80 and is("theora", 1) then
return "theora"
elseif is("Speex ", 0) then
return "speex"
elseif is("fishead", 0) then
return "skeleton"
elseif is("fLaC", 0) then
return "flac-old" -- pre-1.1.1 Ogg FLAC mapping
end
return "unknown"
end
return Page
+456
View File
@@ -0,0 +1,456 @@
--!strict
--!native
--!optimize 2
-- containers/Ogg: the Ogg container (RFC 3533): a demuxer and a muxer (page writer). Absorbed from ogg-luau be9f604
-- (same author, no third-party code; the demuxer), the muxer is new. Used by audio/opus, audio/flac (Ogg FLAC) and
-- the Vorbis decoder / encoders. Pages are CRC-checked and resynced on the capture
-- pattern; packets are reassembled across pages (lacing values, continued packets) per logical stream (serial);
-- seeking bisects byte offsets to the page that holds a granule position. No Roblox APIs; nothing throws (bad
-- input gives nil, err).
--
-- local demux, err = Ogg.open(buf)
-- for _, s in demux:streams() do print(s.serial, s.codec, s.lastGranule) end
-- local r = demux:reader(serial) -- or demux:packets(serial) as a for-iterator
-- local p = r:nextPacket() -- { data, offset, size, granule, eos, bos, ... } / nil
-- local start = r:seekGranule(48000) -- next packet starts at granule `start` (<= target)
--
-- local mux = Ogg.muxer() -- the page writer (Containers/Ogg/Mux)
-- local s = mux:stream(serial?) -- one logical stream
-- s:packet(idHeader, 0, { flush = true }) -- headers on their own pages
-- s:packet(audio, granuleAfterThisPacket) -- pages fill up to opts.pageSize (default 4096) bytes
-- local file = mux:finish() -- every stream ends with an eos page
local Err = require("@formats/core/Err")
local Page = require("@formats/containers/Ogg/Page")
local Mux = require("@formats/containers/Ogg/Mux")
local readu8 = buffer.readu8
type PageInfo = any -- Page.Info (the sibling module is untyped here: required through `script` in Roblox)
local Ogg = {}
Ogg.Page = Page
Ogg.Mux = Mux
Ogg.muxer = Mux.new
export type Packet = {
data: buffer, -- the packet bytes are data[offset .. offset + size - 1]
offset: number,
size: number,
granule: number, -- the page granule if this is the last packet finishing on its page, else -1
pageGranule: number, -- the granule of the page the packet finishes on (may be -1)
bos: boolean, -- first packet of the stream
eos: boolean, -- last packet of the stream (last packet finishing on an eos page)
pageOffset: number, -- byte offset of the page the packet finishes on
gap: boolean, -- data was lost before this packet (a missing page / bad CRC in between)
}
export type Stream = {
serial: number,
codec: string, -- "opus" | "flac" | "vorbis" | "theora" | "speex" | "skeleton" | "flac-old" | "unknown"
firstPacket: buffer, -- a copy of the identification packet
bosOffset: number, -- byte offset of the bos page
lastGranule: number, -- the last known granule of the stream (-1 if none)
}
-- Reader: the packet cursor of one logical stream
local Reader = {}
Reader.__index = Reader
local function newReader(d: any, serial: number, start: number): any
return setmetatable({
demux = d,
buf = d.buf,
serial = serial,
start = start, -- the bos page offset
pagePos = start, -- where to look for the next page
page = nil :: PageInfo?,
seg = 0, -- next segment index on the page
dataPos = 0, -- byte offset of the next segment's data
lastComplete = -1, -- index of the last segment ending a packet on this page
firstPacketOnPage = true,
parts = {} :: { number }, -- pending partial packet: offset, len pairs
partLen = 0,
lastSeq = -1,
gap = false,
ended = false,
total = 0,
}, Reader)
end
-- Load the next page of this serial; false at the end of the data
function Reader._nextPage(self: any): boolean
local b, d = self.buf, self.demux
while true do
local p = Page.find(b, self.pagePos, nil, d.verify)
if not p then
return false
end
self.pagePos = p.offset + p.size
if p.serial == self.serial then
if self.lastSeq >= 0 and p.sequence ~= (self.lastSeq + 1) % 4294967296 then
-- a page is missing: drop the partial packet
self.parts, self.partLen = {}, 0
self.gap = true
end
self.lastSeq = p.sequence
self.page = p
self.seg = 0
self.dataPos = p.offset + p.headerSize
self.firstPacketOnPage = true
local lc = -1
local base = p.offset + 27
for i = 0, p.nsegs - 1 do
if readu8(b, base + i) < 255 then
lc = i
end
end
self.lastComplete = lc
if p.continued then
if self.partLen == 0 and #self.parts == 0 then
-- the start of this packet is not ours (after a seek or a loss): skip its tail
local s = 0
while s < p.nsegs do
local l = readu8(b, base + s)
self.dataPos += l
s += 1
if l < 255 then
break
end
end
self.seg = s
self.firstPacketOnPage = false
end
elseif #self.parts > 0 then
-- a fresh packet while one was pending: the pending one is lost
self.parts, self.partLen = {}, 0
self.gap = true
end
return true
end
end
end
-- The next packet, or nil at the end of the stream
function Reader.nextPacket(self: any): Packet?
if self.ended then
return nil
end
local b = self.buf
while true do
local p = self.page
if p and self.seg < p.nsegs then
local base = p.offset + 27
local start = self.dataPos
local len = 0
local s = self.seg
local complete = false
while s < p.nsegs do
local l = readu8(b, base + s)
s += 1
len += l
if l < 255 then
complete = true
break
end
end
self.seg = s
self.dataPos = start + len
if complete then
local data, off, size = b, start, len
local parts = self.parts
if #parts > 0 then
size = self.partLen + len
data = buffer.create(size)
off = 0
local o = 0
for i = 1, #parts, 2 do
buffer.copy(data, o, b, parts[i], parts[i + 1])
o += parts[i + 1]
end
buffer.copy(data, o, b, start, len)
self.parts, self.partLen = {}, 0
end
local last = (s - 1) == self.lastComplete
local pkt = {
data = data,
offset = off,
size = size,
granule = if last then p.granule else -1,
pageGranule = p.granule,
bos = p.bos and self.firstPacketOnPage,
eos = p.eos and last,
pageOffset = p.offset,
gap = self.gap,
}
self.firstPacketOnPage = false
self.gap = false
self.total += 1
if pkt.eos then
self.ended = true
end
return pkt
else
-- the packet continues on a later page
table.insert(self.parts, start)
table.insert(self.parts, len)
self.partLen += len
end
else
if p and p.eos then
self.ended = true
return nil
end
if not self:_nextPage() then
self.ended = true
return nil
end
end
end
end
-- Back to the start of the stream (the identification packet comes next)
function Reader.rewind(self: any)
self.pagePos = self.start
self.page = nil
self.seg = 0
self.parts, self.partLen = {}, 0
self.lastSeq = -1
self.gap = false
self.ended = false
end
-- Position on page p: the packets finishing on p are skipped; the next packet is the one that starts after them
function Reader._at(self: any, p: PageInfo)
self:rewind()
self.pagePos = p.offset
self:_nextPage() -- loads p (it is a valid page of this serial)
local b = self.buf
local base = p.offset + 27
local dp = p.offset + p.headerSize
for i = 0, self.lastComplete do
dp += readu8(b, base + i)
end
self.seg = self.lastComplete + 1
self.dataPos = dp
self.parts, self.partLen = {}, 0
self.firstPacketOnPage = false
self.gap = false
self.ended = false
end
-- Seek so that the next packet is the first one that starts at or before granule g: positions after the last
-- page whose granule is <= g (found by bisection over byte offsets, then a short linear scan). Returns the
-- granule at the start of that next packet, or nil, err. A g before every granule rewinds to the stream start
-- (headers included) and returns -1. A g past the end leaves the reader at the end (nextPacket gives nil).
function Reader.seekGranule(self: any, g: number): (number?, Err.Err?)
local b, d = self.buf, self.demux
local serial = self.serial
local verify = d.verify
local function nextOf(pos: number, limit: number?): PageInfo?
while true do
local p = Page.find(b, pos, limit, verify)
if not p then
return nil
end
if p.serial == serial and p.granule ~= -1 then
return p
end
pos = p.offset + p.size
end
end
local lo, hi = self.start, buffer.len(b)
local best: PageInfo? = nil
while hi - lo > 65536 do
local mid = (lo + hi) // 2
local p = nextOf(mid, hi)
if p and p.granule <= g then
best = p
lo = p.offset
else
hi = mid
end
end
local pos = lo
while true do
local p = nextOf(pos)
if not p or p.granule > g then
break
end
best = p
pos = p.offset + p.size
end
if not best then
self:rewind()
return -1, nil
end
self:_at(best)
return best.granule, nil
end
-- Demux
local Demux = {}
Demux.__index = Demux
-- open(src, opts?) -> Demux | nil, Err. src: a buffer (the whole file) or a core/Bytes Reader (its range is copied
-- when it is not the whole buffer). opts.verify = false skips CRC checks (faster on trusted data); opts.scanAll =
-- true lists every bos page in the file (chained streams), not just the first group
function Ogg.open(src: any, opts: { verify: boolean?, scanAll: boolean? }?): (any, Err.Err?)
local buf: buffer
if type(src) == "buffer" then
buf = src
elseif type(src) == "table" and type(src.buf) == "buffer" and type(src.base) == "number" and type(src.limit) == "number" then
if src.base == 0 and src.limit == buffer.len(src.buf) then
buf = src.buf
else
local n = math.max(0, src.limit - src.base)
buf = buffer.create(n)
buffer.copy(buf, 0, src.buf, src.base, n)
end
else
return nil, Err.new(Err.ARG, "open: expected a buffer or a Reader")
end
local verify = not (opts and opts.verify == false)
local first = Page.find(buf, 0, nil, verify)
if not first then
return nil, Err.new(Err.CORRUPT, "no Ogg page found")
end
local d = setmetatable({
buf = buf,
size = buffer.len(buf),
verify = verify,
_streams = {} :: { Stream },
_bySerial = {} :: { [number]: Stream },
_readers = {} :: { [number]: any },
_lastDone = false,
}, Demux)
-- the bos pages (at the start of the file, and later ones for chains if scanAll)
local pos = first.offset
local scanAll = opts and opts.scanAll
while true do
local p = Page.find(buf, pos, nil, verify)
if not p then
break
end
if p.bos and not d._bySerial[p.serial] then
local st = {
serial = p.serial,
codec = "unknown",
firstPacket = buffer.create(0),
bosOffset = p.offset,
lastGranule = -1,
}
table.insert(d._streams, st)
d._bySerial[p.serial] = st
local r = newReader(d, p.serial, p.offset)
local pk = r:nextPacket()
if pk then
local c = buffer.create(pk.size)
buffer.copy(c, 0, pk.data, pk.offset, pk.size)
st.firstPacket = c
st.codec = Page.codec(c, 0, pk.size)
end
elseif not p.bos and not scanAll then
break
end
pos = p.offset + p.size
end
if #d._streams == 0 then
return nil, Err.new(Err.CORRUPT, "no beginning-of-stream page")
end
return d, nil
end
-- Scan backwards from the end for each stream's last granule
function Demux._scanLast(self: any)
if self._lastDone then
return
end
self._lastDone = true
local b = self.buf
local need = #self._streams
local pos = self.size - 27
while need > 0 do
local p = Page.findBack(b, pos, 0, self.verify)
if not p then
break
end
local st = self._bySerial[p.serial]
if st and st.lastGranule == -1 and p.granule ~= -1 then
st.lastGranule = p.granule
need -= 1
end
pos = p.offset - 1
end
end
-- Every logical stream: { serial, codec, firstPacket, bosOffset, lastGranule }
function Demux.streams(self: any): { Stream }
self:_scanLast()
return self._streams
end
function Demux.stream(self: any, serial: number): Stream?
self:_scanLast()
return self._bySerial[serial]
end
-- The serial of the first stream of a codec, or nil
function Demux.find(self: any, codec: string): number?
for _, s in self._streams do
if s.codec == codec then
return s.serial
end
end
return nil
end
-- The packet cursor of a stream (one per serial, shared by nextPacket / seekGranule below), or nil, Err
function Demux.reader(self: any, serial: number): (any, Err.Err?)
local r = self._readers[serial]
if r then
return r, nil
end
local st = self._bySerial[serial]
if not st then
return nil, Err.new(Err.ARG, "unknown serial " .. tostring(serial))
end
r = newReader(self, serial, st.bosOffset)
self._readers[serial] = r
return r, nil
end
function Demux.nextPacket(self: any, serial: number): Packet?
local r = self:reader(serial)
return if r then r:nextPacket() else nil
end
function Demux.seekGranule(self: any, serial: number, g: number): (number?, Err.Err?)
local r, err = self:reader(serial)
if not r then
return nil, err
end
return r:seekGranule(g)
end
function Demux.rewind(self: any, serial: number)
local r = self:reader(serial)
if r then
r:rewind()
end
end
-- for p in demux:packets(serial) do ... end (continues from the stream's current position)
function Demux.packets(self: any, serial: number): () -> Packet?
local r = self:reader(serial)
return function()
return if r then r:nextPacket() else nil
end
end
-- Copy a packet's bytes into a fresh buffer of its own
function Ogg.copy(p: Packet): buffer
local c = buffer.create(p.size)
buffer.copy(c, 0, p.data, p.offset, p.size)
return c
end
return Ogg
+372
View File
@@ -0,0 +1,372 @@
--!strict
-- containers/Riff: the RIFF chunk container (RIFF, RIFX big-endian, RF64 / BW64 with the ds64 chunk), read leniently
-- and written. Shared by audio/wav and the other RIFF forms (AVI, WebP, ANI, ...). The chunk walker comes from
-- wav-luau fd9a909 (same author, no third-party code); the writer is new.
--
-- local f, err = Riff.read(r, { openEnded = { data = true } }) -- r: a core/Bytes Reader or a buffer
-- f.container, f.form, f.bigEndian -- "RIFF" | "RIFX" | "RF64", "WAVE", false
-- for _, c in f.chunks do print(c.id, c.offset, c.size, c.avail) end -- offsets are absolute in f.buf
-- local c = Riff.find(f, "fmt ")
-- local subs = Riff.list(f, c) -- the sub-chunks of a LIST body (after its type)
--
-- local w = Riff.writer("WAVE", { rf64 = "auto" }) -- or bigEndian = true (RIFX)
-- w:chunk("fmt ", fmtBody) w:chunk("data", samples) w:list("INFO", { { "INAM", "title" } })
-- local file = w:finish() -- RF64 + ds64 when a size passes 4 GiB
-- local parts = w:finish({ parts = true }) -- { buffer }: no copy, for files over 1 GiB
--
-- Lenient reading (what real files need): an odd-sized chunk without its pad byte is detected; a chunk declared past
-- the end keeps what is there (avail < size, truncated = true) and ends the walk; for the ids in opts.openEnded a
-- size of 0 or 0xFFFFFFFF means "up to the end of the file" (streamed writers) and ends the walk; RF64 sizes of
-- 0xFFFFFFFF come from the ds64 chunk (and its table). Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring
local Riff = {}
export type Chunk = {
id: string,
offset: number, -- absolute offset of the body in the file's buffer
size: number, -- declared size (ds64-resolved), or what is available for open-ended / truncated chunks
declared: number, -- the raw size field
avail: number, -- body bytes present in the file (<= size)
truncated: boolean, -- declared past the end of the file
streamed: boolean, -- an open-ended chunk (size 0 / 0xFFFFFFFF up to the end)
}
export type File = {
container: string, -- "RIFF" | "RIFX" | "RF64" (BW64 reads as RF64)
form: string, -- the form type: "WAVE", "AVI ", "WEBP", ...
bigEndian: boolean,
buf: buffer,
base: number, -- absolute offset of the file's first byte
limit: number, -- absolute offset past its last byte
size: number, -- the RIFF size field (ds64-resolved)
chunks: { Chunk },
ds64: { riffSize: number, dataSize: number, sampleCount: number, table: { [string]: number } }?,
}
export type ReadOptions = {
openEnded: { [string]: boolean }?, -- chunk ids whose size 0 / 0xFFFFFFFF means "to the end" (wav: data)
maxChunks: number?, -- stop after this many chunks (default 100000)
}
-- ------------------------------------------------------------------------------------------------ read
local function printable4(b: buffer, p: number, limit: number): boolean
if p + 4 > limit then
return false
end
for i = 0, 3 do
local c = readu8(b, p + i)
if c < 32 or c > 126 then
return false
end
end
return true
end
local function u32(b: buffer, o: number, be: boolean): number
local v = readu32(b, o)
return if be then bit32.byteswap(v) else v
end
-- sniff(r) -> the form type ("WAVE", ...) when r starts with a RIFF / RIFX / RF64 / BW64 header, else nil
function Riff.sniff(r: any): string?
local magic = r:peek(4)
if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then
return nil
end
local form = r:peek(4, 8)
return if #form == 4 then form else nil
end
-- walk the chunks of [p, limit) into list; returns the list
local function walk(b: buffer, p: number, limit: number, be: boolean, opts: ReadOptions?, ds64: any, list: { Chunk }): { Chunk }
local openEnded = opts and opts.openEnded
local maxChunks = opts and opts.maxChunks or 100000
while p + 8 <= limit and #list < maxChunks do
local id = readstring(b, p, 4)
local declared = u32(b, p + 4, be)
local size = declared
local body = p + 8
local avail = limit - body
if declared == 0xFFFFFFFF and ds64 then
if id == "data" then
size = ds64.dataSize
elseif ds64.table[id] then
size = ds64.table[id]
end
end
local c: Chunk = { id = id, offset = body, size = size, declared = declared, avail = math.min(size, avail), truncated = false, streamed = false }
table.insert(list, c)
if openEnded and openEnded[id] and (size == 0 or size == 0xFFFFFFFF or size > avail) then
c.streamed = size == 0 or size == 0xFFFFFFFF
c.truncated = not c.streamed
c.size, c.avail = avail, avail
break
end
if size > avail then
c.truncated = true
break
end
local nextPos = body + size + size % 2
-- an odd-sized chunk written without its pad byte: the next id starts right after the body
if size % 2 == 1 and not printable4(b, nextPos, limit) and printable4(b, body + size, limit) then
nextPos = body + size
end
p = nextPos
end
return list
end
-- read(src, opts?) -> File | nil, Err. src: a core/Bytes Reader (its range) or a buffer.
function Riff.read(src: any, opts: ReadOptions?): (File?, Err.Err?)
local r = if type(src) == "buffer" then Bytes.reader(src) else src
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "read: expected a buffer or a Reader")
end
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 12 then
return nil, Err.new(Err.TRUNCATED, "file too short for a RIFF header", base)
end
local magic = readstring(b, base, 4)
if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then
return nil, Err.new(Err.CORRUPT, "not a RIFF / RIFX / RF64 file", base)
end
local be = magic == "RIFX"
local f: File = {
container = if magic == "BW64" then "RF64" else magic,
form = readstring(b, base + 8, 4),
bigEndian = be,
buf = b,
base = base,
limit = limit,
size = u32(b, base + 4, be),
chunks = {},
ds64 = nil,
}
-- RF64: the ds64 chunk comes first
if f.container == "RF64" and base + 20 <= limit and readstring(b, base + 12, 4) == "ds64" then
local sz = readu32(b, base + 16)
local o = base + 20
if sz >= 24 and o + 24 <= limit then
local d = {
riffSize = readu32(b, o) + readu32(b, o + 4) * 4294967296,
dataSize = readu32(b, o + 8) + readu32(b, o + 12) * 4294967296,
sampleCount = readu32(b, o + 16) + readu32(b, o + 20) * 4294967296,
table = {} :: { [string]: number },
}
if sz >= 28 and o + 28 <= limit then
local n = readu32(b, o + 24)
local q = o + 28
for _ = 1, math.min(n, 1000) do
if q + 12 > limit or q + 12 > o + sz then
break
end
d.table[readstring(b, q, 4)] = readu32(b, q + 4) + readu32(b, q + 8) * 4294967296
q += 12
end
end
f.ds64 = d
if f.size == 0xFFFFFFFF then
f.size = d.riffSize
end
end
end
walk(b, base + 12, limit, be, opts, f.ds64, f.chunks)
return f, nil
end
-- find(file, id, from?) -> the first chunk with that id (after index from), and its index
function Riff.find(f: File, id: string, from: number?): (Chunk?, number?)
for i = (from or 0) + 1, #f.chunks do
if f.chunks[i].id == id then
return f.chunks[i], i
end
end
return nil, nil
end
-- listType(file, chunk) -> the 4-byte type of a LIST / RIFF chunk ("INFO", "movi", ...) or nil
function Riff.listType(f: File, c: Chunk): string?
if c.avail < 4 then
return nil
end
return readstring(f.buf, c.offset, 4)
end
-- list(file, chunk, opts?) -> the sub-chunks of a LIST body (after its 4-byte type)
function Riff.list(f: File, c: Chunk, opts: ReadOptions?): { Chunk }
if c.avail < 4 then
return {}
end
return walk(f.buf, c.offset + 4, c.offset + c.avail, f.bigEndian, opts, nil, {})
end
-- body(file, chunk) -> a Reader over the chunk's available body
function Riff.body(f: File, c: Chunk): Bytes.Reader
return Bytes.reader(f.buf, c.offset, c.avail)
end
-- u16 / u32 in the file's byte order (for chunk bodies)
function Riff.u16(f: File, o: number): number
if f.bigEndian then
return readu8(f.buf, o) * 256 + readu8(f.buf, o + 1)
end
return readu16(f.buf, o)
end
function Riff.u32(f: File, o: number): number
return u32(f.buf, o, f.bigEndian)
end
-- ------------------------------------------------------------------------------------------------ write
local Writer = {}
Writer.__index = Writer
export type WriteOptions = {
bigEndian: boolean?, -- RIFX (default false)
rf64: (boolean | "auto")?, -- true: always RF64; false: never (sizes over 4 GiB are an error); default "auto"
sampleCount: number?, -- the ds64 sample count (RF64 WAVE: frames)
rf64Threshold: number?, -- "auto" switches to RF64 when the RIFF size would pass this (default 0xFFFFFFFF)
}
-- writer(form, opts?) -> Writer: collects chunks; finish() lays out the file
function Riff.writer(form: string, opts: WriteOptions?): any
return setmetatable({
form = string.sub(form .. " ", 1, 4),
be = opts and opts.bigEndian or false,
rf64 = if opts and opts.rf64 ~= nil then opts.rf64 else "auto",
sampleCount = opts and opts.sampleCount or 0,
threshold = opts and opts.rf64Threshold or 0xFFFFFFFF,
chunks = {} :: { any },
}, Writer)
end
-- chunk(id, body, offset?, length?): body is a buffer or a string (a range of a buffer with offset / length), or a
-- list of buffers written one after the other (a data chunk bigger than one buffer)
function Writer.chunk(self: any, id: string, body: any, offset: number?, length: number?)
local parts = {}
local n = 0
if type(body) == "table" then
for _, b in body do
table.insert(parts, { b, 0, buffer.len(b) })
n += buffer.len(b)
end
else
local b: buffer = if type(body) == "string" then buffer.fromstring(body) else body
local o = offset or 0
n = length or (buffer.len(b) - o)
parts[1] = { b, o, n }
end
table.insert(self.chunks, { id = string.sub(id .. " ", 1, 4), parts = parts, length = n })
end
-- list(type, items): a LIST chunk of { id, string-or-buffer } sub-chunks (strings get a NUL terminator, INFO style)
function Writer.list(self: any, listType: string, items: { { any } })
local w = Bytes.writer()
w:string(string.sub(listType .. " ", 1, 4))
for _, it in items do
local v = it[2]
local data: buffer = if type(v) == "string" then buffer.fromstring(v .. "\0") else v
local n = buffer.len(data)
w:string(string.sub(it[1] .. " ", 1, 4))
if self.be then
w:u32be(n)
else
w:u32le(n)
end
w:bytes(data)
if n % 2 == 1 then
w:u8(0)
end
end
self:chunk("LIST", w:finish())
end
-- finish(opts?) -> buffer | nil, Err; with opts.parts: { buffer } (the header pieces and the chunk bodies, not copied)
function Writer.finish(self: any, opts: { parts: boolean? }?): (any, Err.Err?)
local total = 4 -- the form type
local big = false
local dataSize = 0
for _, c in self.chunks do
total += 8 + c.length + c.length % 2
if c.length > 0xFFFFFFFE then
big = true
end
if c.id == "data" then
dataSize = c.length
end
end
local rf64 = self.rf64 == true or (self.rf64 == "auto" and (big or total > self.threshold))
if not rf64 and (big or total > 0xFFFFFFFF) then
return nil, Err.new(Err.LIMIT, "over 4 GiB without RF64")
end
if rf64 and self.be then
return nil, Err.new(Err.ARG, "RF64 is little-endian only")
end
if rf64 then
total += 36 -- ds64
end
local asParts = opts and opts.parts
if not asParts and total + 8 > 0x40000000 then
return nil, Err.new(Err.LIMIT, "the file would not fit in a buffer (1 GiB): use finish({ parts = true })")
end
local out: { buffer } = {}
local w = Bytes.writer(if asParts then 256 else total + 8)
local function size32(v: number)
if self.be then
w:u32be(v)
else
w:u32le(v)
end
end
if rf64 then
w:string("RF64")
w:u32le(0xFFFFFFFF)
w:string(self.form)
w:string("ds64")
w:u32le(28)
w:u64le(total)
w:u64le(dataSize)
w:u64le(self.sampleCount)
w:u32le(0) -- no table: only data may be over 4 GiB
else
w:string(if self.be then "RIFX" else "RIFF")
size32(total)
w:string(self.form)
end
for _, c in self.chunks do
w:string(c.id)
if rf64 and (c.id == "data" or c.length > 0xFFFFFFFE) then
w:u32le(0xFFFFFFFF)
else
size32(c.length)
end
for _, p in c.parts do
if asParts then
table.insert(out, w:finish())
w = Bytes.writer(64)
if p[2] == 0 and p[3] == buffer.len(p[1]) then
table.insert(out, p[1])
else
local cp = buffer.create(p[3])
buffer.copy(cp, 0, p[1], p[2], p[3])
table.insert(out, cp)
end
else
w:bytes(p[1], p[2], p[3])
end
end
if c.length % 2 == 1 then
w:u8(0)
end
end
if asParts then
if w:tell() > 0 then
table.insert(out, w:finish())
end
return out, nil
end
return w:finish(), nil
end
return Riff
+82
View File
@@ -0,0 +1,82 @@
--!strict
--!native
--!optimize 2
-- image/png/Apng: APNG frame compositing (APNG spec 1.0: dispose_op none / background / previous, blend_op source /
-- over) onto full rgba8 canvases. The "over" blend uses the same integer arithmetic as ffmpeg's pngdec.c, so the
-- canvases match ffmpeg byte for byte. Nothing here throws: the caller (init) validated every frame rectangle.
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill
local Apng = {}
local function div255(x: number): number
return (x + 128) * 257 // 65536
end
-- blend(canvas, cw, src, fw, fh, fx, fy, over): draw an rgba8 rectangle onto the canvas
local function blend(canvas: buffer, cw: number, src: buffer, fw: number, fh: number, fx: number, fy: number, over: boolean)
for y = 0, fh - 1 do
local so = y * fw * 4
local co = ((fy + y) * cw + fx) * 4
if not over then
bcopy(canvas, co, src, so, fw * 4)
else
for x = 0, fw - 1 do
local s, c = so + x * 4, co + x * 4
local fa = readu8(src, s + 3)
if fa == 255 then
writeu32(canvas, c, readu32(src, s))
elseif fa ~= 0 then
local ba = readu8(canvas, c + 3)
local oa = fa + div255((255 - fa) * ba)
if ba == 255 then
for k = 0, 2 do
writeu8(canvas, c + k, div255(fa * readu8(src, s + k) + (255 - fa) * readu8(canvas, c + k)))
end
else
local den = 255 * oa
for k = 0, 2 do
writeu8(canvas, c + k, (255 * fa * readu8(src, s + k) + (255 - fa) * ba * readu8(canvas, c + k)) // den)
end
end
writeu8(canvas, c + 3, oa)
end
end
end
end
end
-- composite(w, h, frames) -> { buffer }: the full canvas after each frame (frames: { image, x, y, dispose, blend })
function Apng.composite(w: number, h: number, frames: { any }): { buffer }
local canvas = bcreate(w * h * 4)
local saved = bcreate(w * h * 4)
local out: { buffer } = {}
for i, f in frames do
local fi = f.image
local fw, fh = fi.width, fi.height
local dispose, over = f.dispose, f.blend == "over"
if i == 1 then
over = false -- the canvas starts transparent black: source and over differ only in hidden colour
if dispose == "previous" then
dispose = "background"
end
end
if dispose == "previous" then
bcopy(saved, 0, canvas, 0)
end
blend(canvas, w, fi.pixels, fw, fh, f.x, f.y, over)
local snap = bcreate(w * h * 4)
bcopy(snap, 0, canvas, 0)
out[i] = snap
if dispose == "background" then
for y = 0, fh - 1 do
bfill(canvas, ((f.y + y) * w + f.x) * 4, 0, fw * 4)
end
elseif dispose == "previous" then
bcopy(canvas, 0, saved, 0)
end
end
return out
end
return Apng
+340 -52
View File
@@ -3,7 +3,11 @@
-- Supports: decode of every colour type (grey, RGB, palette, grey + alpha, RGBA) at every bit depth (1, 2, 4, 8, 16),
-- PLTE / tRNS transparency, the five filters, Adam7, tEXt; encode of rgba8 to RGBA / RGB / grey / grey + alpha
-- (chosen automatically) with adaptive filters. Decodes to rgba8 (16-bit samples keep their high byte).
-- Not supported: APNG animation (the default image is decoded), colour management (gAMA / cHRM / sRGB / iCCP are
-- APNG (APNG 1.0): acTL / fcTL / fdAT decode to img.frames (each frame its own rectangle, delay in seconds, dispose /
-- blend ops), img.loops = num_plays; img.pixels stays the default image (meta.apngDefaultHidden when the IDAT is not
-- part of the animation). Png.composite(img) draws the frames onto full canvases (byte-exact with ffmpeg). Encode
-- writes an APNG when img.frames is a non-empty list (or opts.apng). Sequence numbers and frame rectangles are checked.
-- Not supported: colour management (gAMA / cHRM / sRGB / iCCP are
-- ignored; iCCP is kept raw-compressed in meta.iccCompressed), palette / 16-bit / interlaced output.
-- ------------------------------------------------------------------------------------------------ requires
@@ -14,6 +18,7 @@ local Deflate = require("@formats/codecs/Deflate")
local Types = require("@formats/Types")
local Decode = require("@formats/image/png/Decode")
local Encode = require("@formats/image/png/Encode")
local Apng = require("@formats/image/png/Apng")
-- ------------------------------------------------------------------------------------------------ contract
local Png = {
@@ -22,7 +27,7 @@ local Png = {
extensions = { "png", "apng" },
mime = { "image/png", "image/apng" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" },
caps = { decode = true, encode = true, animation = false, alpha = true, depths = { 1, 2, 4, 8, 16 } },
caps = { decode = true, encode = true, animation = true, alpha = true, depths = { 1, 2, 4, 8, 16 } },
}
export type DecodeOptions = {
@@ -32,6 +37,8 @@ export type DecodeOptions = {
export type EncodeOptions = {
level: number?, -- deflate level 0..9 (default 6)
colorType: ("auto" | "rgba" | "rgb" | "gray" | "graya")?, -- default "auto": the smallest lossless one
apng: boolean?, -- true: an APNG even without img.frames (one frame); false: a still PNG; default: APNG when
-- img.frames is a non-empty list
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -95,6 +102,66 @@ function Png.info(r: Bytes.Reader): (Header?, Err.Err?)
return header(r)
end
type FrameControl = {
width: number,
height: number,
x: number,
y: number,
num: number,
den: number,
dispose: number,
blend: number,
chunks: { { number } }, -- fdAT payloads: offset, length
len: number,
}
local DISPOSE: { [number]: "none" | "background" | "previous" } = { [0] = "none", [1] = "background", [2] = "previous" }
-- pixels(b, chunks, total, w, h, depth, ct, interlace, pal, tr, out) -> nil | Err: inflate the zlib stream split
-- over chunks ({ offset, length } in b), unfilter and expand it to rgba8 in out (w x h)
local function pixels(b: buffer, chunks: { { number } }, total: number, w: number, ht: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): Err.Err?
-- the inflated size: every (pass) row has a filter byte
local channels = Decode.CHANNELS[ct]
local expected = 0
if interlace == 0 then
expected = ht * (Decode.rowBytes(w, channels, depth) + 1)
else
for _, pass in Decode.PASSES do
local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4]
local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0
local ph = if ht > y0 then (ht - y0 + dy - 1) // dy else 0
if pw > 0 and ph > 0 then
expected += ph * (Decode.rowBytes(pw, channels, depth) + 1)
end
end
end
local z: buffer
if #chunks == 1 then
z = b
else
z = buffer.create(total)
local w0 = 0
for _, c in chunks do
buffer.copy(z, w0, b, c[1], c[2])
w0 += c[2]
end
end
local zo = if #chunks == 1 then chunks[1][1] else 0
local raw, zerr = Deflate.zlib(z, zo, total, expected)
if not raw then
-- some encoders leave extra bytes after the rows: inflate without the exact size, keep the rows
local loose = Deflate.zlib(z, zo, total)
if not loose or buffer.len(loose) < expected then
return zerr or Err.new(Err.CORRUPT, "bad image data")
end
raw = loose
end
local ok, derr = Decode.run(raw :: buffer, w, ht, depth, ct, interlace, pal, tr, out)
if not ok then
return Err.new(Err.CORRUPT, tostring(derr))
end
return nil
end
function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local checkCrc = opts and opts.checkCrc or false
local maxPixels = opts and opts.maxPixels or 2 ^ 26
@@ -118,6 +185,12 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
local idatLen = 0
local text: { [string]: string } = {}
local iccCompressed: buffer? = nil
-- APNG: acTL, then fcTL (+ IDAT for frame 1 when it is the default image) / fdAT, one sequence counter
local plays: number? = nil
local fctls: { FrameControl } = {}
local seq = 0
local idatInAnim = false
local animPixels = 0
local p = r.base + 8
local first = true
while p + 12 <= n do
@@ -162,6 +235,9 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
elseif typ == "IDAT" then
table.insert(idat, { d, len })
idatLen += len
if #fctls == 1 and #idat == 1 then
idatInAnim = true
end
elseif typ == "tEXt" then
local s = buffer.readstring(b, d, len)
local z = string.find(s, "\0", 1, true)
@@ -172,6 +248,58 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
local cb = buffer.create(len)
buffer.copy(cb, 0, b, d, len)
iccCompressed = cb
elseif typ == "acTL" then
if len >= 8 and plays == nil and #idat == 0 then
plays = be32(b, d + 4)
end
elseif typ == "fcTL" and plays ~= nil then
if len < 26 then
return nil, Err.new(Err.CORRUPT, "short fcTL", p)
end
if be32(b, d) ~= seq then
return nil, Err.new(Err.CORRUPT, string.format("fcTL sequence %d, expected %d", be32(b, d), seq), p)
end
seq += 1
local f: FrameControl = {
width = be32(b, d + 4),
height = be32(b, d + 8),
x = be32(b, d + 12),
y = be32(b, d + 16),
num = readu8(b, d + 20) * 256 + readu8(b, d + 21),
den = readu8(b, d + 22) * 256 + readu8(b, d + 23),
dispose = readu8(b, d + 24),
blend = readu8(b, d + 25),
chunks = {},
len = 0,
}
if f.width == 0 or f.height == 0 or f.x + f.width > w or f.y + f.height > ht then
return nil, Err.new(Err.CORRUPT, "fcTL frame outside the image", p)
end
if f.dispose > 2 or f.blend > 1 then
return nil, Err.new(Err.CORRUPT, "bad fcTL dispose / blend op", p)
end
if #idat == 0 and (f.width ~= w or f.height ~= ht or f.x ~= 0 or f.y ~= 0) then
return nil, Err.new(Err.CORRUPT, "the fcTL before IDAT must cover the image", p)
end
animPixels += f.width * f.height
if animPixels > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("the animation frames are over the %d pixel limit", maxPixels))
end
table.insert(fctls, f)
elseif typ == "fdAT" and plays ~= nil then
if len < 4 then
return nil, Err.new(Err.CORRUPT, "short fdAT", p)
end
if be32(b, d) ~= seq then
return nil, Err.new(Err.CORRUPT, string.format("fdAT sequence %d, expected %d", be32(b, d), seq), p)
end
seq += 1
local f = fctls[#fctls]
if not f or (#fctls == 1 and idatInAnim) then
return nil, Err.new(Err.CORRUPT, "fdAT without its fcTL", p)
end
table.insert(f.chunks, { d + 4, len - 4 })
f.len += len - 4
elseif typ == "IEND" then
break -- a missing IEND is tolerated (truncated tail after the data)
elseif bit32.band(readu8(b, p + 4), 0x20) == 0 and typ ~= "IHDR" then
@@ -185,46 +313,45 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
if ct == 3 and palCount == 0 then
return nil, Err.new(Err.CORRUPT, "palette image without PLTE")
end
-- the inflated size: every (pass) row has a filter byte
local channels = Decode.CHANNELS[ct]
local expected = 0
if h.interlace == 0 then
expected = ht * (Decode.rowBytes(w, channels, depth) + 1)
else
for _, pass in Decode.PASSES do
local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4]
local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0
local ph = if ht > y0 then (ht - y0 + dy - 1) // dy else 0
if pw > 0 and ph > 0 then
expected += ph * (Decode.rowBytes(pw, channels, depth) + 1)
end
end
end
local z: buffer
if #idat == 1 then
z = b
else
z = buffer.create(idatLen)
local w0 = 0
for _, c in idat do
buffer.copy(z, w0, b, c[1], c[2])
w0 += c[2]
end
end
local zo, zl = if #idat == 1 then idat[1][1] else 0, idatLen
local raw, zerr = Deflate.zlib(z, zo, zl, expected)
if not raw then
-- some encoders leave extra bytes after the rows: inflate without the exact size, keep the rows
local loose = Deflate.zlib(z, zo, zl)
if not loose or buffer.len(loose) < expected then
return nil, zerr
end
raw = loose
end
local img = Types.Image.new(w, ht, "rgba8")
local ok, derr = Decode.run(raw :: buffer, w, ht, depth, ct, h.interlace, pal, tr, img.pixels)
if not ok then
return nil, Err.new(Err.CORRUPT, tostring(derr))
local ierr = pixels(b, idat, idatLen, w, ht, h.bitDepth, ct, h.interlace, pal, tr, img.pixels)
if ierr then
return nil, ierr
end
if plays ~= nil and #fctls > 0 then
local last = fctls[#fctls]
if #fctls > 1 and #last.chunks == 0 then
fctls[#fctls] = nil -- a truncated file: the last frame never got its data
end
local frames: { Types.Frame } = {}
for i, f in fctls do
local fimg: Types.Image
if i == 1 and idatInAnim then
fimg = Types.Image.new(w, ht, "rgba8")
buffer.copy(fimg.pixels, 0, img.pixels)
else
if #f.chunks == 0 then
return nil, Err.new(Err.CORRUPT, "APNG frame " .. i .. " has no data")
end
fimg = Types.Image.new(f.width, f.height, "rgba8")
local ferr = pixels(b, f.chunks, f.len, f.width, f.height, h.bitDepth, ct, h.interlace, pal, tr, fimg.pixels)
if ferr then
ferr.message = "frame " .. i .. ": " .. ferr.message
return nil, ferr
end
end
frames[i] = {
image = fimg,
delay = f.num / (if f.den == 0 then 100 else f.den),
x = f.x,
y = f.y,
dispose = DISPOSE[f.dispose] :: any,
blend = if f.blend == 1 then "over" :: "over" else "source" :: "source",
}
end
img.frames = frames
img.loops = plays
img.meta.apngDefaultHidden = not idatInAnim
end
if ct == 3 then
local palette: { { number } } = {}
@@ -243,37 +370,131 @@ end
-- ------------------------------------------------------------------------------------------------ encode
local CT_CODES = { gray = 0, rgb = 2, graya = 4, rgba = 6 }
local DISPOSE_CODES: { [string]: number } = { none = 0, background = 1, previous = 2 }
local BLEND_CODES: { [string]: number } = { source = 0, over = 1 }
-- a frame delay in seconds -> num, den (u16 each): the smallest exact denominator, else milliseconds
local function delayFraction(delay: number): (number, number)
for den = 1, 1000 do
local num = math.floor(delay * den + 0.5)
if num > 65535 then
break
end
if math.abs(num / den - delay) < 1e-9 then
return num, den
end
end
if delay * 1000 <= 65535 then
return math.floor(delay * 1000 + 0.5), 1000
elseif delay * 100 <= 65535 then
return math.floor(delay * 100 + 0.5), 100
end
return math.min(65535, math.floor(delay + 0.5)), 1
end
local function validImage(im: any): boolean
return type(im) == "table"
and im.format == "rgba8"
and type(im.pixels) == "buffer"
and type(im.width) == "number"
and type(im.height) == "number"
and im.width >= 1
and im.height >= 1
and im.width % 1 == 0
and im.height % 1 == 0
and buffer.len(im.pixels) >= im.width * im.height * 4
end
-- the frames to write as an APNG (nil for a plain PNG), or nil, Err for a bad frame list
local function animationFrames(img: Types.Image, opts: EncodeOptions?): ({ Types.Frame }?, Err.Err?)
local frames = img.frames
local mode = if opts then opts.apng else nil
if mode == false then
return nil, nil
end
if frames ~= nil and type(frames) ~= "table" then
return nil, Err.new(Err.ARG, "png encode: frames must be a list")
end
if frames == nil or #frames == 0 then
if mode then
return { { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: any }, nil
end
return nil, nil
end
for i, f in frames do
local label = "png encode: frame " .. i
if type(f) ~= "table" or not validImage(f.image) then
return nil, Err.new(Err.ARG, label .. ": needs an rgba8 image")
end
local x, y = f.x or 0, f.y or 0
if type(x) ~= "number" or type(y) ~= "number" or x < 0 or y < 0 or x % 1 ~= 0 or y % 1 ~= 0 or x + f.image.width > img.width or y + f.image.height > img.height then
return nil, Err.new(Err.ARG, label .. ": rectangle outside the image")
end
if f.delay ~= nil and (type(f.delay) ~= "number" or not (f.delay >= 0)) then
return nil, Err.new(Err.ARG, label .. ": bad delay")
end
if f.dispose ~= nil and DISPOSE_CODES[f.dispose] == nil then
return nil, Err.new(Err.ARG, label .. ": bad dispose " .. tostring(f.dispose))
end
if f.blend ~= nil and BLEND_CODES[f.blend] == nil then
return nil, Err.new(Err.ARG, label .. ": bad blend " .. tostring(f.blend))
end
end
return frames, nil
end
function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
if not validImage(img) then
return nil, Err.new(Err.ARG, "png encode: needs an rgba8 Image")
end
local w, h = img.width, img.height
if w < 1 or h < 1 or buffer.len(img.pixels) < w * h * 4 then
return nil, Err.new(Err.ARG, "png encode: bad image size or pixel buffer")
end
local level = opts and opts.level or 6
if type(level) ~= "number" or level < 0 or level > 9 then
return nil, Err.new(Err.ARG, "png encode: level must be 0..9")
end
local frames, ferr = animationFrames(img, opts)
if ferr then
return nil, ferr
end
local loops = img.loops or 0
if frames and (type(loops) ~= "number" or loops < 0 or loops > 4294967295 or loops % 1 ~= 0) then
return nil, Err.new(Err.ARG, "png encode: loops must be an integer 0..2^32-1")
end
local want = opts and opts.colorType or "auto"
local ctName: string = want
if want == "auto" then
ctName = Encode.pickColorType(img.pixels, w, h)
-- the smallest colour type that holds the image and every frame
local alpha, color = false, false
local function scan(im: Types.Image)
local c = Encode.pickColorType(im.pixels, im.width, im.height)
alpha = alpha or c == "rgba" or c == "graya"
color = color or c == "rgba" or c == "rgb"
end
scan(img)
if frames then
for _, f in frames do
scan(f.image)
end
end
ctName = if color then (if alpha then "rgba" else "rgb") else (if alpha then "graya" else "gray")
end
local ct = CT_CODES[ctName]
if ct == nil then
return nil, Err.new(Err.ARG, "png encode: unknown colorType " .. tostring(want))
end
local raw = Encode.filter(img.pixels, w, h, ct)
local z = Deflate.zlibCompress(raw, { level = level }) :: buffer
local function zdata(im: Types.Image): buffer
return Deflate.zlibCompress(Encode.filter(im.pixels, im.width, im.height, ct), { level = level }) :: buffer
end
local out = Bytes.writer(buffer.len(z) + 128)
local function chunk(typ: string, data: buffer?)
local len = if data then buffer.len(data) else 0
local out = Bytes.writer(w * h + 128)
local function chunk(typ: string, data: buffer?, prefix: number?)
local len = (if data then buffer.len(data) else 0) + (if prefix then 4 else 0)
out:u32be(len)
local start = out:tell()
out:string(typ)
if prefix then
out:u32be(prefix)
end
if data then
out:bytes(data)
end
@@ -289,6 +510,12 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
ihdr:u8(0)
ihdr:u8(0)
chunk("IHDR", ihdr:finish())
if frames then
local actl = Bytes.writer(8)
actl:u32be(#frames)
actl:u32be(loops)
chunk("acTL", actl:finish())
end
if img.meta and img.meta.text then
for k, v in img.meta.text do
local t = Bytes.writer()
@@ -298,9 +525,70 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
chunk("tEXt", t:finish())
end
end
chunk("IDAT", z)
if not frames then
chunk("IDAT", zdata(img))
chunk("IEND", nil)
return out:finish(), nil
end
-- frame 1 is the default image when it covers the canvas with the same pixels; otherwise the default image is
-- written first, outside the animation
local f1 = frames[1]
local f1i = f1.image
local inAnim = f1i == img
or ((f1.x or 0) == 0 and (f1.y or 0) == 0 and f1i.width == w and f1i.height == h and buffer.len(f1i.pixels) >= w * h * 4 and buffer.readstring(f1i.pixels, 0, w * h * 4) == buffer.readstring(img.pixels, 0, w * h * 4))
local seq = 0
if not inAnim then
chunk("IDAT", zdata(img))
end
for i, f in frames do
local fi = f.image
local num, den = delayFraction(f.delay or 0)
local fc = Bytes.writer(26)
fc:u32be(seq)
fc:u32be(fi.width)
fc:u32be(fi.height)
fc:u32be(f.x or 0)
fc:u32be(f.y or 0)
fc:u16be(num)
fc:u16be(den)
fc:u8(DISPOSE_CODES[f.dispose or "none"])
fc:u8(BLEND_CODES[f.blend or "source"])
chunk("fcTL", fc:finish())
seq += 1
if i == 1 and inAnim then
chunk("IDAT", zdata(img))
else
chunk("fdAT", zdata(fi), seq)
seq += 1
end
end
chunk("IEND", nil)
return out:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- composite(img) -> { Image } | nil, Err: every APNG frame drawn onto a full canvas (dispose / blend applied, as a
-- player shows them; byte-exact with ffmpeg). A still image gives { a copy of img }.
function Png.composite(img: Types.Image): ({ Types.Image }?, Err.Err?)
if not validImage(img) then
return nil, Err.new(Err.ARG, "composite: needs an rgba8 Image")
end
local frames, ferr = animationFrames(img, { apng = true })
if not frames then
return nil, ferr
end
local w, h = img.width, img.height
local list = {}
for i, f in frames do
list[i] = { image = f.image, x = f.x or 0, y = f.y or 0, dispose = f.dispose or "none", blend = f.blend or "source" }
end
local out = {}
for i, b in Apng.composite(w, h, list) do
local im = Types.Image.new(w, h, "rgba8")
im.pixels = b
out[i] = im
end
return out, nil
end
return Png