ws-audio: audio/vorbis decoder: stb_vorbis 1.22 port (setup, codebooks, floor 1, residue 0/1/2, coupling) on containers/Ogg + codecs/Mdct, libvorbis-exact trimming, granule-exact seek, packetDecoder for other containers; tests vs oggdec (counts, 1 LSB) + ffmpeg (SNR 138 dB), seeks, fuzz; bench line

This commit is contained in:
4DBug committed 2026-10-31 08:53:10 -05:00
1 parent aee2d3257e
commit 042a782f2f
13 files changed
+2210 -1

No files matched your search

+12
View File
@@ -86,6 +86,18 @@ local list: { Entry } = {
return require("@formats/audio/voc")
end,
},
{
name = "vorbis",
category = "audio",
path = "audio/vorbis",
extensions = { "ogg", "oga" },
mime = { "audio/ogg", "audio/vorbis" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255 },
load = function()
return require("@formats/audio/vorbis")
end,
},
{
name = "wav",
category = "audio",
+394
View File
@@ -0,0 +1,394 @@
--!strict
--!native
--!optimize 2
-- audio/vorbis/Codebook: the Vorbis LSB-first packet bit reader and codebooks (Vorbis I spec sections 2 and 3):
-- reading a codebook from the setup header (ordered / sparse length lists, lookup types 1 and 2, float32_unpack),
-- the codeword assignment, and Huffman / VQ decoding. Ported from stb_vorbis 1.22 (public domain / MIT; see
-- licenses/stb_vorbis-LICENSE.txt): compute_codewords' lowest-free-leaf assignment, lookup1_values; the decode side
-- is a fast table (up to 10 bits) plus a binary tree for longer codes instead of stb's sorted binary search.
--
-- Never throws. Reading past the packet end gives zero bits and sets br.eop (the spec's end-of-packet condition);
-- an invalid codeword also sets eop and decodes to -1.
local Codebook = {}
local readu8 = buffer.readu8
local floor = math.floor
local POW = table.create(41, 0)
for i = 0, 40 do
POW[i + 1] = 2 ^ i
end
-- ------------------------------------------------------------------------------------------------ bit reader
export type Br = {
buf: buffer,
pos: number, -- next byte to load
limit: number,
acc: number, -- loaded, unread bits (LSB first)
cnt: number,
pad: number, -- how many of the top bits of acc are past the end of the packet
eop: boolean, -- read past the end of the packet
}
function Codebook.reader(buf: buffer, offset: number, size: number): Br
return { buf = buf, pos = offset, limit = offset + size, acc = 0, cnt = 0, pad = 0, eop = false }
end
-- bits(br, n) -> the next n (0..32) bits as an unsigned number
local function bits(br: Br, n: number): number
if n == 0 then
return 0
end
local acc, cnt = br.acc, br.cnt
if cnt < n then
local b, p, lim = br.buf, br.pos, br.limit
repeat
if p < lim then
acc += readu8(b, p) * POW[cnt + 1]
p += 1
else
br.pad += 8
end
cnt += 8
until cnt >= n
br.pos = p
end
local m = POW[n + 1]
local v = acc % m
br.acc = (acc - v) / m
cnt -= n
br.cnt = cnt
if cnt < br.pad then
br.eop = true
br.pad = cnt
end
return v
end
Codebook.bits = bits
-- ilog(x): the number of bits needed to hold x (0 for x <= 0)
local function ilog(x: number): number
local n = 0
while x > 0 do
n += 1
x = floor(x / 2)
end
return n
end
Codebook.ilog = ilog
-- float32_unpack (spec 9.2.2)
local function float32Unpack(x: number): number
local mantissa = x % 2097152
local sign = x >= 2147483648
local exp = floor((x % 2147483648) / 2097152)
local v = mantissa * 2 ^ (exp - 788)
return if sign then -v else v
end
-- ------------------------------------------------------------------------------------------------ codebooks
export type Book = {
dims: number,
entries: number,
fastBits: number,
fastLen: { number }, -- per fastBits-bit prefix: code length (> 0), 0 = continue in the tree, -1 = invalid
fastSym: { number }, -- symbol, or the tree node to continue from
c0: { number }, -- tree: child for bit 0 / 1: > 0 node, < 0 leaf (-symbol - 1), 0 none
c1: { number },
lookup: number, -- 0, 1, 2
vq: { number }?, -- entries * dims values (lookup 1 / 2, expanded)
used: number, -- entries with a codeword
}
local MAX_ENTRIES = 2 ^ 20
local MAX_VQ = 2 ^ 22
-- lookup1_values(entries, dims): the largest r with r^dims <= entries
local function lookup1Values(entries: number, dims: number): number
local r = floor(math.exp(math.log(entries) / dims))
if floor((r + 1) ^ dims) <= entries then
r += 1
end
if (r + 1) ^ dims <= entries then
return -1
end
if floor(r ^ dims) > entries then
return -1
end
return r
end
-- assign codewords (spec 3.2.1: in entry order, the lowest free leaf) and build the decode tree + fast table
local function build(book: Book, lengths: { number }): string?
local n = book.entries
local c0, c1 = book.c0, book.c1
local nodes = 1
c0[1], c1[1] = 0, 0
local available = table.create(33, 0) -- available[l]: the free code at depth l, as a 32-bit left-aligned value + 1 (0 = none)
local first = true
local used = 0
local maxLen = 0
for i = 0, n - 1 do
local len = lengths[i + 1]
if len > 0 then
local code: number
if first then
first = false
code = 0
for l = 1, len do
available[l + 1] = POW[33 - l] + 1
end
else
local z = len
while z > 0 and available[z + 1] == 0 do
z -= 1
end
if z == 0 then
return "over-subscribed codebook"
end
code = available[z + 1] - 1
available[z + 1] = 0
for y = len, z + 1, -1 do
available[y + 1] = code + POW[33 - y] + 1
end
end
-- walk the MSB-first code into the tree
local node = 1
for d = 1, len do
local bit = floor(code / POW[33 - d]) % 2
local child = if bit == 0 then c0[node] else c1[node]
if d == len then
if child ~= 0 then
return "ambiguous codeword"
end
if bit == 0 then
c0[node] = -(i + 1)
else
c1[node] = -(i + 1)
end
else
if child < 0 then
return "ambiguous codeword"
elseif child == 0 then
nodes += 1
c0[nodes], c1[nodes] = 0, 0
child = nodes
if bit == 0 then
c0[node] = child
else
c1[node] = child
end
end
node = child
end
end
used += 1
if len > maxLen then
maxLen = len
end
end
end
book.used = used
-- the fast table: every fastBits-bit prefix (read LSB first) walked down the tree
local fb = math.clamp(maxLen, 1, 10)
book.fastBits = fb
local size = POW[fb + 1]
local fl, fs = table.create(size, -1), table.create(size, 0)
for idx = 0, size - 1 do
local node = 1
local v = idx
for d = 1, fb do
local bit = v % 2
v = (v - bit) / 2
local child = if bit == 0 then c0[node] else c1[node]
if child < 0 then
fl[idx + 1], fs[idx + 1] = d, -child - 1
break
elseif child == 0 then
break -- invalid (-1)
end
node = child
if d == fb then
fl[idx + 1], fs[idx + 1] = 0, node
end
end
end
book.fastLen, book.fastSym = fl, fs
return nil
end
-- read(br) -> Book | nil, message: one codebook from the setup header
function Codebook.read(br: Br): (Book?, string?)
if bits(br, 24) ~= 0x564342 then
return nil, "bad codebook sync"
end
local dims = bits(br, 16)
local entries = bits(br, 24)
local ordered = bits(br, 1)
if br.eop then
return nil, "setup header ends in a codebook"
end
if dims == 0 and entries ~= 0 then
return nil, "codebook with 0 dimensions"
end
if entries > MAX_ENTRIES then
return nil, "codebook with " .. entries .. " entries"
end
local lengths = table.create(entries, 0)
if ordered == 1 then
local cur = 0
local len = bits(br, 5) + 1
while cur < entries do
local num = bits(br, ilog(entries - cur))
if len >= 32 or cur + num > entries or br.eop then
return nil, "bad ordered codebook lengths"
end
for k = cur + 1, cur + num do
lengths[k] = len
end
cur += num
len += 1
end
else
local sparse = bits(br, 1)
for j = 1, entries do
if sparse == 0 or bits(br, 1) == 1 then
local l = bits(br, 5) + 1
if l == 32 then
return nil, "codeword length 32"
end
lengths[j] = l
end
end
end
if br.eop then
return nil, "setup header ends in a codebook"
end
local book: Book = {
dims = dims,
entries = entries,
fastBits = 1,
fastLen = {},
fastSym = {},
c0 = {},
c1 = {},
lookup = 0,
vq = nil,
used = 0,
}
local err = build(book, lengths)
if err then
return nil, err
end
local lookup = bits(br, 4)
if lookup > 2 then
return nil, "lookup type " .. lookup
end
book.lookup = lookup
if lookup > 0 then
local minimum = float32Unpack(bits(br, 32))
local delta = float32Unpack(bits(br, 32))
local valueBits = bits(br, 4) + 1
local seq = bits(br, 1) == 1
local nvalues
if lookup == 1 then
nvalues = lookup1Values(entries, dims)
if nvalues < 0 then
return nil, "bad lookup1 size"
end
else
nvalues = entries * dims
end
if nvalues == 0 then
return nil, "empty lookup table"
end
if entries * dims > MAX_VQ or nvalues > MAX_VQ then
return nil, "lookup table too large"
end
local mults = table.create(nvalues, 0)
for j = 1, nvalues do
mults[j] = bits(br, valueBits)
end
if br.eop then
return nil, "setup header ends in a lookup table"
end
-- expand to one vector per entry (spec 3.2.1, "VQ lookup table vector representation")
local vq = table.create(entries * dims, 0)
for e = 0, entries - 1 do
local last = 0
local div = 1
for k = 0, dims - 1 do
local off
if lookup == 1 then
off = floor(e / div) % nvalues
div *= nvalues
else
off = e * dims + k
end
local v = mults[off + 1] * delta + minimum + last
if seq then
last = v
end
vq[e * dims + k + 1] = v
end
end
book.vq = vq
end
return book, nil
end
-- decode(br, book) -> entry number | -1 (end of packet / invalid codeword: br.eop is set)
local function decode(br: Br, book: Book): number
local fb = book.fastBits
local acc, cnt = br.acc, br.cnt
if cnt < fb then
local b, p, lim = br.buf, br.pos, br.limit
repeat
if p < lim then
acc += readu8(b, p) * POW[cnt + 1]
p += 1
else
br.pad += 8
end
cnt += 8
until cnt >= fb
br.pos = p
br.acc, br.cnt = acc, cnt
end
local idx = acc % POW[fb + 1] + 1
local l = book.fastLen[idx]
if l > 0 then
local m = POW[l + 1]
br.acc = (acc - acc % m) / m
cnt -= l
br.cnt = cnt
if cnt < br.pad then
br.eop = true
br.pad = cnt
return -1
end
return book.fastSym[idx]
elseif l == 0 then
bits(br, fb)
local node = book.fastSym[idx]
local c0, c1 = book.c0, book.c1
while true do
local child = if bits(br, 1) == 0 then c0[node] else c1[node]
if br.eop then
return -1
end
if child < 0 then
return -child - 1
elseif child == 0 then
br.eop = true
return -1
end
node = child
end
end
br.eop = true
return -1
end
Codebook.decode = decode
return Codebook
+586
View File
@@ -0,0 +1,586 @@
--!strict
--!native
--!optimize 2
-- audio/vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8): mode and window shape, floor 1
-- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/Mdct), windowing and overlap-add.
-- Floors, residues and coupling are ported from stb_vorbis 1.22 vorbis_decode_packet_rest / decode_residue /
-- do_floor / draw_line (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). The overlap follows libvorbis:
-- each packet after the first returns the n_prev/4 + n_cur/4 samples between the centres of the two windows, so
-- granule positions count exactly the samples returned (the first packet returns none).
--
-- local st = Packet.new(ident, setup)
-- local n = Packet.decode(st, buf, offset, size) -- frames now in st.out[ch][1 .. n]; -1 = not an audio packet
-- Packet.reset(st) -- forget the overlap (after a seek / a gap)
-- local bs = Packet.blocksize(st, buf, offset, size) -- the packet's block size (0 = not audio), header bits only
-- Never throws: a damaged packet decodes as far as its bits go (the spec's end-of-packet rule) or returns -1.
local Codebook = require("@formats/audio/vorbis/Codebook")
local Setup = require("@formats/audio/vorbis/Setup")
local Tables = require("@formats/audio/vorbis/Tables")
local Mdct = require("@formats/codecs/Mdct")
local Packet = {}
local bits, decode = Codebook.bits, Codebook.decode
local ilog = Codebook.ilog
local INV_DB = Tables
local RANGE = { 256, 128, 86, 64 }
export type State = {
channels: number,
n0: number,
n1: number,
setup: Setup.Setup,
plans: { [number]: Mdct.Plan },
slopes: { [number]: { number } }, -- rising half-window of overlap length L (= blocksize / 2)
spec: { { number } }, -- per channel: n/2 spectral values (residue, then times the floor)
frame: { { number } }, -- per channel: n windowed time samples
tail: { { number } }, -- per channel: the previous frame from its centre on
tailLen: number,
prevN: number, -- the previous block size, 0 = no previous frame
out: { { number } }, -- per channel: the returned samples
finalY: { { number } },
step2: { number },
inter: { number }, -- residue type 2 interleaved scratch
zero: { boolean },
reallyZero: { boolean },
partClass: { { { number } } },
}
function Packet.new(id: Setup.Ident, setup: Setup.Setup): State?
local n0, n1, ch = id.blocksize0, id.blocksize1, id.channels
local plans: { [number]: Mdct.Plan } = {}
local slopes: { [number]: { number } } = {}
for _, n in { n0, n1 } do
local p = Mdct.new(n)
if not p then
return nil
end
plans[n] = p
local w = Mdct.window("vorbis", n) :: { number }
local half = table.create(n // 2, 0)
for i = 1, n // 2 do
half[i] = w[i]
end
slopes[n // 2] = half
end
local function arrays(len: number): { { number } }
local t = table.create(ch)
for c = 1, ch do
t[c] = table.create(len, 0)
end
return t
end
local partClass = table.create(ch)
for c = 1, ch do
partClass[c] = {}
end
return {
channels = ch,
n0 = n0,
n1 = n1,
setup = setup,
plans = plans,
slopes = slopes,
spec = arrays(n1 // 2),
frame = arrays(n1),
tail = arrays(n1 // 2),
tailLen = 0,
prevN = 0,
out = arrays(n1),
finalY = arrays(math.max(2, setup.maxFloorValues)),
step2 = table.create(math.max(2, setup.maxFloorValues), 0),
inter = table.create(n1 // 2 * ch, 0),
zero = table.create(ch, false),
reallyZero = table.create(ch, false),
partClass = partClass,
}
end
function Packet.reset(st: State)
st.prevN = 0
st.tailLen = 0
end
-- blocksize(st, buf, off, size) -> the block size of an audio packet (0 if not audio)
function Packet.blocksize(st: State, b: buffer, off: number, size: number): number
if size < 1 then
return 0
end
local br = Codebook.reader(b, off, size)
if bits(br, 1) ~= 0 then
return 0
end
local m = bits(br, st.setup.modeBits)
local mode = st.setup.modes[m + 1]
if not mode or br.eop then
return 0
end
return if mode.blockflag == 1 then st.n1 else st.n0
end
-- ------------------------------------------------------------------------------------------------ floor 1
local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number
local dy = y1 - y0
local adx = x1 - x0
local off = ((if dy < 0 then -dy else dy) * (x - x0)) // adx
return if dy < 0 then y0 - off else y0 + off
end
-- multiply out[x0 .. x1) by the floor line from (x0, y0) to (x1, y1) (stb draw_line)
local function drawLine(out: { number }, x0: number, y0: number, x1: number, y1: number, n: number)
local dy = y1 - y0
local adx = x1 - x0
local ady = if dy < 0 then -dy else dy
local base = if dy < 0 then -(ady // adx) else ady // adx
local sy = if dy < 0 then base - 1 else base + 1
ady -= (if base < 0 then -base else base) * adx
if x1 > n then
x1 = n
end
local x, y, err = x0, y0, 0
if x < x1 then
out[x + 1] *= INV_DB[y % 256 + 1]
x += 1
while x < x1 do
err += ady
if err >= adx then
err -= adx
y += sy
else
y += base
end
out[x + 1] *= INV_DB[y % 256 + 1]
x += 1
end
end
end
-- decode the floor of one channel into finalY (-1 = unused point); false = this channel is silent
local function floorDecode(st: State, br: Codebook.Br, g: Setup.Floor1, finalY: { number }): boolean
if bits(br, 1) == 0 then
return false
end
local books = st.setup.books
local range = RANGE[g.multiplier]
local yb = ilog(range) - 1
finalY[1] = bits(br, yb)
finalY[2] = bits(br, yb)
local offset = 2
for j = 1, g.partitions do
local pclass = g.partitionClass[j] + 1
local cdim = g.classDims[pclass]
local cbits = g.classSubs[pclass]
local csub = 2 ^ cbits
local cval = 0
if cbits > 0 then
cval = decode(br, books[g.classMaster[pclass] + 1])
if cval < 0 then
return false
end
end
local subs = g.subBooks[pclass]
for _ = 1, cdim do
local book = subs[cval % csub + 1]
cval = cval // csub
if book >= 0 then
local v = decode(br, books[book + 1])
if v < 0 then
return false
end
finalY[offset + 1] = v
else
finalY[offset + 1] = 0
end
offset += 1
end
end
if br.eop then
return false
end
-- step 1: amplitude value synthesis
local step2 = st.step2
step2[1], step2[2] = 1, 1
local xl, low, high = g.xlist, g.low, g.high
for j = 2, g.values - 1 do
local lo, hi = low[j + 1], high[j + 1]
local pred = predict(xl[j + 1], xl[lo + 1], xl[hi + 1], finalY[lo + 1], finalY[hi + 1])
local val = finalY[j + 1]
local highroom = range - pred
local lowroom = pred
local room = if highroom < lowroom then highroom * 2 else lowroom * 2
if val ~= 0 then
step2[lo + 1], step2[hi + 1], step2[j + 1] = 1, 1, 1
if val >= room then
if highroom > lowroom then
finalY[j + 1] = val - lowroom + pred
else
finalY[j + 1] = pred - val + highroom - 1
end
elseif val % 2 == 1 then
finalY[j + 1] = pred - (val + 1) // 2
else
finalY[j + 1] = pred + val // 2
end
else
step2[j + 1] = 0
finalY[j + 1] = pred
end
end
for j = 1, g.values do
if step2[j] == 0 then
finalY[j] = -1
end
end
return true
end
-- multiply target[1 .. n2] by the floor curve (stb do_floor)
local function floorCurve(g: Setup.Floor1, finalY: { number }, target: { number }, n2: number)
local mult = g.multiplier
local lx, ly = 0, finalY[1] * mult
local sorted, xl = g.sorted, g.xlist
for q = 2, g.values do
local j = sorted[q] + 1
local fy = finalY[j]
if fy >= 0 then
local hy = fy * mult
local hx = xl[j]
if lx ~= hx then
drawLine(target, lx, ly, hx, hy, n2)
end
lx, ly = hx, hy
end
end
if lx < n2 then
local v = INV_DB[ly % 256 + 1]
for j = lx + 1, n2 do
target[j] *= v
end
end
end
-- ------------------------------------------------------------------------------------------------ residue
-- add the vectors of one partition to target at offset (0-based) .. offset + psize (bounded by limit)
local function partition(br: Codebook.Br, book: Codebook.Book, target: { number }, offset: number, psize: number, rtype: number, limit: number): boolean
local vq = book.vq
if not vq then
br.eop = true -- a scalar book in a vector context: invalid stream
return false
end
local dims = book.dims
if rtype == 0 then
local step = psize // dims
for k = 0, step - 1 do
local e = decode(br, book)
if e < 0 then
return false
end
local base = e * dims
for i = 0, dims - 1 do
local at = offset + k + i * step
if at < limit then
target[at + 1] += vq[base + i + 1]
end
end
end
else
local k = 0
while k < psize do
local e = decode(br, book)
if e < 0 then
return false
end
local base = e * dims
local len = math.min(dims, psize - k)
local at = offset + k
for i = 0, len - 1 do
if at + i < limit then
target[at + i + 1] += vq[base + i + 1]
end
end
k += dims
end
end
return true
end
-- decode residue r for the channels `targets` (nil = do not decode) of length n2 each
local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: { { number } | false }, ch: number, n2: number)
local books = st.setup.books
local rtype = r.type
local cbook = books[r.classbook + 1]
local classwords = cbook.dims
for j = 1, ch do
local t = targets[j]
if t then
for i = 1, n2 do
(t :: { number })[i] = 0
end
end
end
local any = false
for j = 1, ch do
if targets[j] then
any = true
end
end
if not any then
return
end
local psize = r.partSize
local rb = r.books
local classdata = r.classdata
if rtype == 2 and ch > 1 then
local total = n2 * ch
local inter = st.inter
for i = 1, total do
inter[i] = 0
end
local lb = math.min(r.begin, total)
local le = math.min(r.finish, total)
local partRead = (le - lb) // psize
local pc = st.partClass[1]
local done = false
for pass = 1, 8 do
if done then
break
end
local pcount, classSet = 0, 1
while pcount < partRead do
if pass == 1 then
local q = decode(br, cbook)
if q < 0 then
done = true
break
end
pc[classSet] = classdata[q + 1]
end
local cls = pc[classSet]
local i = 0
while i < classwords and pcount < partRead do
local b = rb[cls[i + 1] + 1][pass]
if b >= 0 then
if not partition(br, books[b + 1], inter, r.begin + pcount * psize, psize, 1, total) then
done = true
break
end
end
i += 1
pcount += 1
end
if done then
break
end
classSet += 1
end
end
-- de-interleave into the channels that are decoded
for j = 1, ch do
local t = targets[j]
if t then
local tt = t :: { number }
local v = j
for i = 1, n2 do
tt[i] = inter[v]
v += ch
end
end
end
return
end
local lb = math.min(r.begin, n2)
local le = math.min(r.finish, n2)
local partRead = (le - lb) // psize
local pcs = st.partClass
for pass = 1, 8 do
local pcount, classSet = 0, 1
while pcount < partRead do
if pass == 1 then
for j = 1, ch do
if targets[j] then
local q = decode(br, cbook)
if q < 0 then
return
end
pcs[j][classSet] = classdata[q + 1]
end
end
end
local i = 0
while i < classwords and pcount < partRead do
for j = 1, ch do
local t = targets[j]
if t then
local c = pcs[j][classSet][i + 1]
local b = rb[c + 1][pass]
if b >= 0 then
if not partition(br, books[b + 1], t :: { number }, r.begin + pcount * psize, psize, rtype, n2) then
return
end
end
end
end
i += 1
pcount += 1
end
classSet += 1
end
end
end
-- ------------------------------------------------------------------------------------------------ packet
-- decode(st, buf, off, size) -> frames returned in st.out (0 for the first packet), -1 for a non-audio / bad packet
function Packet.decode(st: State, b: buffer, off: number, size: number): number
if size < 1 then
return -1
end
local setup = st.setup
local br = Codebook.reader(b, off, size)
if bits(br, 1) ~= 0 then
return -1
end
local mode = setup.modes[bits(br, setup.modeBits) + 1]
if not mode then
return -1
end
local n, prevLong, nextLong
if mode.blockflag == 1 then
n = st.n1
prevLong = bits(br, 1) == 1
nextLong = bits(br, 1) == 1
else
n = st.n0
prevLong, nextLong = false, false
end
if br.eop then
return -1
end
local n2 = n // 2
local n0 = st.n0
local leftStart, leftEnd, rightStart, rightEnd
if mode.blockflag == 1 and not prevLong then
leftStart, leftEnd = (n - n0) // 4, (n + n0) // 4
else
leftStart, leftEnd = 0, n2
end
if mode.blockflag == 1 and not nextLong then
rightStart, rightEnd = (n * 3 - n0) // 4, (n * 3 + n0) // 4
else
rightStart, rightEnd = n2, n
end
local map = setup.mappings[mode.mapping + 1]
local ch = st.channels
local spec, zero, reallyZero = st.spec, st.zero, st.reallyZero
-- floors
for c = 1, ch do
local s = map.mux[c] + 1
local g = setup.floors[map.submapFloor[s] + 1]
local ok = floorDecode(st, br, g, st.finalY[c])
zero[c] = not ok
reallyZero[c] = not ok
end
-- channels coupled to a non-silent channel are decoded too
for i = 1, map.couplingSteps do
local m, a = map.magnitude[i] + 1, map.angle[i] + 1
if not zero[m] or not zero[a] then
zero[m], zero[a] = false, false
end
end
-- residues, per submap
for i = 1, map.submaps do
local targets: { { number } | false } = {}
local k = 0
for c = 1, ch do
if map.mux[c] == i - 1 then
k += 1
targets[k] = if zero[c] then false else spec[c]
end
end
residue(st, br, setup.residues[map.submapResidue[i] + 1], targets, k, n2)
end
-- inverse coupling
for i = map.couplingSteps, 1, -1 do
local m, a = spec[map.magnitude[i] + 1], spec[map.angle[i] + 1]
for j = 1, n2 do
local mv, av = m[j], a[j]
local m2, a2
if mv > 0 then
if av > 0 then
m2, a2 = mv, mv - av
else
a2, m2 = mv, mv + av
end
else
if av > 0 then
m2, a2 = mv, mv + av
else
a2, m2 = mv, mv - av
end
end
m[j], a[j] = m2, a2
end
end
-- floor curves, IMDCT, windows
local plan = st.plans[n]
local lslope = st.slopes[leftEnd - leftStart]
local rslope = st.slopes[rightEnd - rightStart]
for c = 1, ch do
local sp = spec[c]
local fr = st.frame[c]
if reallyZero[c] then
for j = 1, n do
fr[j] = 0
end
else
local s = map.mux[c] + 1
floorCurve(setup.floors[map.submapFloor[s] + 1], st.finalY[c], sp, n2)
Mdct.inverse(plan, sp, 1, 1, fr, 1)
for j = 1, leftStart do
fr[j] = 0
end
local L = leftEnd - leftStart
for j = 0, L - 1 do
fr[leftStart + j + 1] *= lslope[j + 1]
end
local R = rightEnd - rightStart
for j = 0, R - 1 do
fr[rightStart + j + 1] *= rslope[R - j]
end
for j = rightEnd + 1, n do
fr[j] = 0
end
end
end
-- overlap-add with the previous frame; return the samples between the two centres
local prevN = st.prevN
local count = 0
if prevN > 0 then
count = prevN // 4 + n // 4
local o = prevN // 4 - n // 4 -- this frame starts o samples after the previous centre
local tl = st.tailLen
for c = 1, ch do
local out, tail, fr = st.out[c], st.tail[c], st.frame[c]
for j = 0, count - 1 do
local v = if j < tl then tail[j + 1] else 0
local fi = j - o
if fi >= 0 then
v += fr[fi + 1]
end
out[j + 1] = v
end
end
end
-- the new tail: this frame from its centre to the end of its window
local tl = rightEnd - n2
for c = 1, ch do
local tail, fr = st.tail[c], st.frame[c]
for j = 1, tl do
tail[j] = fr[n2 + j]
end
end
st.tailLen = tl
st.prevN = n
return count
end
return Packet
+429
View File
@@ -0,0 +1,429 @@
--!strict
--!native
-- audio/vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2): identification (channels, rate,
-- bitrates, blocksizes), comment (vendor + user comments -> tags) and setup (codebooks, floors, residues, mappings,
-- modes). Ported from stb_vorbis 1.22 start_decoder (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt).
-- Floor 0 is rejected as unsupported, as stb_vorbis does (no encoder has produced it since 2000).
-- Never throws: every parser returns nil, message on bad data.
local Codebook = require("@formats/audio/vorbis/Codebook")
local Setup = {}
local bits, ilog = Codebook.bits, Codebook.ilog
local readu8, readu32 = buffer.readu8, buffer.readu32
export type Ident = {
channels: number,
sampleRate: number,
bitrateMax: number,
bitrateNominal: number,
bitrateMin: number,
blocksize0: number,
blocksize1: number,
}
export type Floor1 = {
partitions: number,
partitionClass: { number }, -- 1-based list of class numbers (0-based values)
classDims: { number }, -- [class + 1]
classSubs: { number },
classMaster: { number },
subBooks: { { number } }, -- [class + 1][sub + 1] = book (0-based) or -1
multiplier: number,
xlist: { number }, -- [j + 1]
values: number,
sorted: { number }, -- point indices (0-based) by increasing x
low: { number }, -- neighbours, [j + 1] (0-based indices)
high: { number },
}
export type Residue = {
type: number,
begin: number,
finish: number,
partSize: number,
classifications: number,
classbook: number,
books: { { number } }, -- [class + 1][pass + 1] = book or -1
classdata: { { number } }, -- [classbook entry + 1][k + 1] = class
}
export type Mapping = {
submaps: number,
couplingSteps: number,
magnitude: { number }, -- [step + 1] channel (0-based)
angle: { number },
mux: { number }, -- [channel + 1] submap (0-based)
submapFloor: { number },
submapResidue: { number },
}
export type Mode = { blockflag: number, mapping: number }
export type Setup = {
books: { Codebook.Book },
floors: { Floor1 },
residues: { Residue },
mappings: { Mapping },
modes: { Mode },
modeBits: number,
maxFloorValues: number,
}
local function isVorbis(b: buffer, o: number, n: number, kind: number): boolean
return n >= 7 and readu8(b, o) == kind and buffer.readstring(b, o + 1, 6) == "vorbis"
end
Setup.isVorbis = isVorbis
-- ident(buf, offset, size) -> Ident | nil, message
function Setup.ident(b: buffer, o: number, n: number): (Ident?, string?)
if not isVorbis(b, o, n, 1) then
return nil, "not a Vorbis identification header"
end
if n < 30 then
return nil, "short identification header"
end
if readu32(b, o + 7) ~= 0 then
return nil, "Vorbis version " .. readu32(b, o + 7)
end
local ch = readu8(b, o + 11)
local rate = readu32(b, o + 12)
local bs = readu8(b, o + 28)
local l0, l1 = bs % 16, bs // 16
if ch == 0 or rate == 0 then
return nil, "no channels or no sample rate"
end
if l0 < 6 or l0 > 13 or l1 < 6 or l1 > 13 or l0 > l1 then
return nil, "bad blocksizes"
end
if readu8(b, o + 29) % 2 == 0 then
return nil, "identification header framing bit not set"
end
return {
channels = ch,
sampleRate = rate,
bitrateMax = buffer.readi32(b, o + 16),
bitrateNominal = buffer.readi32(b, o + 20),
bitrateMin = buffer.readi32(b, o + 24),
blocksize0 = 2 ^ l0,
blocksize1 = 2 ^ l1,
},
nil
end
-- comment(buf, offset, size) -> vendor, { "KEY=value" } | nil, message
function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?)
if not isVorbis(b, o, n, 3) then
return nil, nil
end
local p, e = o + 7, o + n
if p + 4 > e then
return nil, nil
end
local vlen = readu32(b, p)
p += 4
if vlen > e - p then
return nil, nil
end
local vendor = buffer.readstring(b, p, vlen)
p += vlen
local list = {}
if p + 4 > e then
return vendor, list
end
local count = readu32(b, p)
p += 4
for _ = 1, count do
if p + 4 > e then
break
end
local len = readu32(b, p)
p += 4
if len > e - p then
break
end
table.insert(list, buffer.readstring(b, p, len))
p += len
end
return vendor, list
end
-- setup(buf, offset, size, ident) -> Setup | nil, message
function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, string?)
if not isVorbis(b, o, n, 5) then
return nil, "not a Vorbis setup header"
end
local br = Codebook.reader(b, o + 7, n - 7)
local channels = id.channels
-- codebooks
local books: { Codebook.Book } = {}
local nbooks = bits(br, 8) + 1
for i = 1, nbooks do
local book, err = Codebook.read(br)
if not book then
return nil, "codebook " .. (i - 1) .. ": " .. tostring(err)
end
books[i] = book
end
-- time domain transforms (placeholders)
local ntimes = bits(br, 6) + 1
for _ = 1, ntimes do
if bits(br, 16) ~= 0 then
return nil, "bad time domain transform"
end
end
-- floors
local floors: { Floor1 } = {}
local maxValues = 0
local nfloors = bits(br, 6) + 1
for i = 1, nfloors do
local ftype = bits(br, 16)
if ftype == 0 then
return nil, "floor 0"
elseif ftype ~= 1 then
return nil, "bad floor type " .. ftype
end
local parts = bits(br, 5)
local pclass = table.create(parts, 0)
local maxClass = -1
for j = 1, parts do
pclass[j] = bits(br, 4)
if pclass[j] > maxClass then
maxClass = pclass[j]
end
end
local cdims, csubs, cmaster, subBooks = {}, {}, {}, {}
for j = 1, maxClass + 1 do
cdims[j] = bits(br, 3) + 1
csubs[j] = bits(br, 2)
cmaster[j] = -1
if csubs[j] > 0 then
cmaster[j] = bits(br, 8)
if cmaster[j] >= nbooks then
return nil, "bad floor master book"
end
end
local sb = {}
for k = 1, 2 ^ csubs[j] do
sb[k] = bits(br, 8) - 1
if sb[k] >= nbooks then
return nil, "bad floor subclass book"
end
end
subBooks[j] = sb
end
local mult = bits(br, 2) + 1
local rangebits = bits(br, 4)
local xlist = { 0, 2 ^ rangebits }
for j = 1, parts do
local c = pclass[j]
for _ = 1, cdims[c + 1] do
table.insert(xlist, bits(br, rangebits))
end
end
local values = #xlist
if values > 65 * 8 then
return nil, "too many floor points"
end
if br.eop then
return nil, "setup header ends in a floor"
end
local order = table.create(values, 0)
for j = 1, values do
order[j] = j - 1
end
table.sort(order, function(a: number, c: number): boolean
return xlist[a + 1] < xlist[c + 1]
end)
for j = 1, values - 1 do
if xlist[order[j] + 1] == xlist[order[j + 1] + 1] then
return nil, "duplicate floor x"
end
end
local low, high = table.create(values, 0), table.create(values, 0)
for j = 2, values - 1 do
local lo, hi = -1, 65536
local x = xlist[j + 1]
for k = 0, j - 1 do
local xv = xlist[k + 1]
if xv > lo and xv < x then
low[j + 1], lo = k, xv
end
if xv < hi and xv > x then
high[j + 1], hi = k, xv
end
end
end
floors[i] = {
partitions = parts,
partitionClass = pclass,
classDims = cdims,
classSubs = csubs,
classMaster = cmaster,
subBooks = subBooks,
multiplier = mult,
xlist = xlist,
values = values,
sorted = order,
low = low,
high = high,
}
if values > maxValues then
maxValues = values
end
end
-- residues
local residues: { Residue } = {}
local nres = bits(br, 6) + 1
for i = 1, nres do
local rtype = bits(br, 16)
if rtype > 2 then
return nil, "bad residue type " .. rtype
end
local rbegin, rend = bits(br, 24), bits(br, 24)
local psize = bits(br, 24) + 1
local ncls = bits(br, 6) + 1
local cbook = bits(br, 8)
if rend < rbegin then
return nil, "residue end before begin"
end
if cbook >= nbooks then
return nil, "bad residue classbook"
end
local cascade = table.create(ncls, 0)
for j = 1, ncls do
local lowBits = bits(br, 3)
local highBits = if bits(br, 1) == 1 then bits(br, 5) else 0
cascade[j] = highBits * 8 + lowBits
end
local rbooks = {}
for j = 1, ncls do
local row = table.create(8, -1)
local c = cascade[j]
for k = 1, 8 do
if c % 2 == 1 then
row[k] = bits(br, 8)
if row[k] >= nbooks then
return nil, "bad residue book"
end
end
c = c // 2
end
rbooks[j] = row
end
if br.eop then
return nil, "setup header ends in a residue"
end
-- class numbers of each classbook entry (stb's classdata)
local cb = books[cbook + 1]
local cw = cb.dims
if cb.entries * cw > 2 ^ 22 then
return nil, "residue classbook too large"
end
local classdata = table.create(cb.entries)
for j = 0, cb.entries - 1 do
local row = table.create(cw, 0)
local tmp = j
for k = cw, 1, -1 do
row[k] = tmp % ncls
tmp = tmp // ncls
end
classdata[j + 1] = row
end
residues[i] = {
type = rtype,
begin = rbegin,
finish = rend,
partSize = psize,
classifications = ncls,
classbook = cbook,
books = rbooks,
classdata = classdata,
}
end
-- mappings
local mappings: { Mapping } = {}
local nmaps = bits(br, 6) + 1
local chBits = ilog(channels - 1)
for i = 1, nmaps do
if bits(br, 16) ~= 0 then
return nil, "bad mapping type"
end
local submaps = if bits(br, 1) == 1 then bits(br, 4) + 1 else 1
local steps = 0
local mag, ang = {}, {}
if bits(br, 1) == 1 then
steps = bits(br, 8) + 1
if steps > channels then
return nil, "too many coupling steps"
end
for k = 1, steps do
mag[k] = bits(br, chBits)
ang[k] = bits(br, chBits)
if mag[k] >= channels or ang[k] >= channels or mag[k] == ang[k] then
return nil, "bad coupling channels"
end
end
end
if bits(br, 2) ~= 0 then
return nil, "mapping reserved bits set"
end
local mux = table.create(channels, 0)
if submaps > 1 then
for j = 1, channels do
mux[j] = bits(br, 4)
if mux[j] >= submaps then
return nil, "bad channel mux"
end
end
end
local sf, sr = {}, {}
for j = 1, submaps do
bits(br, 8)
sf[j] = bits(br, 8)
sr[j] = bits(br, 8)
if sf[j] >= nfloors or sr[j] >= nres then
return nil, "bad submap floor / residue"
end
end
mappings[i] = {
submaps = submaps,
couplingSteps = steps,
magnitude = mag,
angle = ang,
mux = mux,
submapFloor = sf,
submapResidue = sr,
}
end
-- modes
local modes: { Mode } = {}
local nmodes = bits(br, 6) + 1
for i = 1, nmodes do
local bf = bits(br, 1)
local wt, tt = bits(br, 16), bits(br, 16)
local m = bits(br, 8)
if wt ~= 0 or tt ~= 0 or m >= nmaps then
return nil, "bad mode"
end
modes[i] = { blockflag = bf, mapping = m }
end
if br.eop then
return nil, "setup header truncated"
end
if bits(br, 1) ~= 1 then
return nil, "setup header framing bit not set"
end
return {
books = books,
floors = floors,
residues = residues,
mappings = mappings,
modes = modes,
modeBits = ilog(nmodes - 1),
maxFloorValues = maxValues,
},
nil
end
return Setup
+37
View File
@@ -0,0 +1,37 @@
--!strict
-- audio/vorbis/Tables: the floor 1 inverse dB table (Vorbis I specification, section 10.1, as in stb_vorbis 1.22,
-- public domain / MIT, licenses/stb_vorbis-LICENSE.txt). 256 values, index = floor value (1-based here).
return table.freeze({
1.0649863e-07, 1.1341951e-07, 1.2079015e-07, 1.2863978e-07, 1.3699951e-07, 1.4590251e-07, 1.5538408e-07, 1.6548181e-07,
1.7623575e-07, 1.8768855e-07, 1.9988561e-07, 2.1287530e-07, 2.2670913e-07, 2.4144197e-07, 2.5713223e-07, 2.7384213e-07,
2.9163793e-07, 3.1059021e-07, 3.3077411e-07, 3.5226968e-07, 3.7516214e-07, 3.9954229e-07, 4.2550680e-07, 4.5315863e-07,
4.8260743e-07, 5.1396998e-07, 5.4737065e-07, 5.8294187e-07, 6.2082472e-07, 6.6116941e-07, 7.0413592e-07, 7.4989464e-07,
7.9862701e-07, 8.5052630e-07, 9.0579828e-07, 9.6466216e-07, 1.0273513e-06, 1.0941144e-06, 1.1652161e-06, 1.2409384e-06,
1.3215816e-06, 1.4074654e-06, 1.4989305e-06, 1.5963394e-06, 1.7000785e-06, 1.8105592e-06, 1.9282195e-06, 2.0535261e-06,
2.1869758e-06, 2.3290978e-06, 2.4804557e-06, 2.6416497e-06, 2.8133190e-06, 2.9961443e-06, 3.1908506e-06, 3.3982101e-06,
3.6190449e-06, 3.8542308e-06, 4.1047004e-06, 4.3714470e-06, 4.6555282e-06, 4.9580707e-06, 5.2802740e-06, 5.6234160e-06,
5.9888572e-06, 6.3780469e-06, 6.7925283e-06, 7.2339451e-06, 7.7040476e-06, 8.2047000e-06, 8.7378876e-06, 9.3057248e-06,
9.9104632e-06, 1.0554501e-05, 1.1240392e-05, 1.1970856e-05, 1.2748789e-05, 1.3577278e-05, 1.4459606e-05, 1.5399272e-05,
1.6400004e-05, 1.7465768e-05, 1.8600792e-05, 1.9809576e-05, 2.1096914e-05, 2.2467911e-05, 2.3928002e-05, 2.5482978e-05,
2.7139006e-05, 2.8902651e-05, 3.0780908e-05, 3.2781225e-05, 3.4911534e-05, 3.7180282e-05, 3.9596466e-05, 4.2169667e-05,
4.4910090e-05, 4.7828601e-05, 5.0936773e-05, 5.4246931e-05, 5.7772202e-05, 6.1526565e-05, 6.5524908e-05, 6.9783085e-05,
7.4317983e-05, 7.9147585e-05, 8.4291040e-05, 8.9768747e-05, 9.5602426e-05, 0.00010181521, 0.00010843174, 0.00011547824,
0.00012298267, 0.00013097477, 0.00013948625, 0.00014855085, 0.00015820453, 0.00016848555, 0.00017943469, 0.00019109536,
0.00020351382, 0.00021673929, 0.00023082423, 0.00024582449, 0.00026179955, 0.00027881276, 0.00029693158, 0.00031622787,
0.00033677814, 0.00035866388, 0.00038197188, 0.00040679456, 0.00043323036, 0.00046138411, 0.00049136745, 0.00052329927,
0.00055730621, 0.00059352311, 0.00063209358, 0.00067317058, 0.00071691700, 0.00076350630, 0.00081312324, 0.00086596457,
0.00092223983, 0.00098217216, 0.0010459992, 0.0011139742, 0.0011863665, 0.0012634633, 0.0013455702, 0.0014330129,
0.0015261382, 0.0016253153, 0.0017309374, 0.0018434235, 0.0019632195, 0.0020908006, 0.0022266726, 0.0023713743,
0.0025254795, 0.0026895994, 0.0028643847, 0.0030505286, 0.0032487691, 0.0034598925, 0.0036847358, 0.0039241906,
0.0041792066, 0.0044507950, 0.0047400328, 0.0050480668, 0.0053761186, 0.0057254891, 0.0060975636, 0.0064938176,
0.0069158225, 0.0073652516, 0.0078438871, 0.0083536271, 0.0088964928, 0.009474637, 0.010090352, 0.010746080,
0.011444421, 0.012188144, 0.012980198, 0.013823725, 0.014722068, 0.015678791, 0.016697687, 0.017782797,
0.018938423, 0.020169149, 0.021479854, 0.022875735, 0.024362330, 0.025945531, 0.027631618, 0.029427276,
0.031339626, 0.033376252, 0.035545228, 0.037855157, 0.040315199, 0.042935108, 0.045725273, 0.048696758,
0.051861348, 0.055231591, 0.058820850, 0.062643361, 0.066714279, 0.071049749, 0.075666962, 0.080584227,
0.085821044, 0.091398179, 0.097337747, 0.10366330, 0.11039993, 0.11757434, 0.12521498, 0.13335215,
0.14201813, 0.15124727, 0.16107617, 0.17154380, 0.18269168, 0.19456402, 0.20720788, 0.22067342,
0.23501402, 0.25028656, 0.26655159, 0.28387361, 0.30232132, 0.32196786, 0.34289114, 0.36517414,
0.38890521, 0.41417847, 0.44109412, 0.46975890, 0.50028648, 0.53279791, 0.56742212, 0.60429640,
0.64356699, 0.68538959, 0.72993007, 0.77736504, 0.82788260, 0.88168307, 0.9389798, 1.0,
})
+448
View File
@@ -0,0 +1,448 @@
--!strict
-- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau
-- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/Mdct,
-- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last
-- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position).
-- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2,
-- coupling, sparse / ordered codebooks, lookup types 1 / 2; comment-header tags (lower-cased keys); a packet-level
-- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Not supported: floor 0 (Err.UNSUPPORTED, as in
-- stb_vorbis; no encoder has produced it since 2000), chained streams (the first logical Vorbis stream is decoded).
-- ------------------------------------------------------------------------------------------------ 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 Setup = require("@formats/audio/vorbis/Setup")
local Packet = require("@formats/audio/vorbis/Packet")
-- ------------------------------------------------------------------------------------------------ contract
local Vorbis = {
name = "vorbis",
category = "audio",
extensions = { "ogg", "oga" },
mime = { "audio/ogg", "audio/vorbis" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255 },
}
export type OpenOptions = {
verify: boolean?, -- check the Ogg page CRCs (default true)
}
-- ------------------------------------------------------------------------------------------------ constants
local TAG_KEYS = { tracknumber = "track", description = "comment" }
local function tagsOf(comments: { string }): Types.Tags
local tags: Types.Tags = {}
for _, s in comments do
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)
k = TAG_KEYS[k] or k
tags[k] = if tags[k] then tags[k] .. "; " .. v else v
end
end
return tags
end
-- the three headers -> ident, setup, vendor, tags | nil, Err
local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, Err.Err?)
local id, ierr = Setup.ident(h1.data, h1.offset, h1.size)
if not id then
return nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header")
end
local vendor, comments = Setup.comment(h2.data, h2.offset, h2.size)
if not vendor then
return nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header")
end
local setup, serr = Setup.setup(h3.data, h3.offset, h3.size, id)
if not setup then
local code = if serr == "floor 0" then Err.UNSUPPORTED else Err.CORRUPT
return nil, nil, nil, nil, Err.new(code, serr or "bad setup header")
end
return id, setup, vendor, tagsOf(comments or {}), nil
end
-- ------------------------------------------------------------------------------------------------ sniff
function Vorbis.sniff(r: Bytes.Reader): number
if r:remaining() < 35 or r:peek(4) ~= "OggS" then
return 0
end
local b, p = r.buf, r.pos
local nseg = buffer.readu8(b, p + 26)
local d = p + 27 + nseg
if d + 7 > r.limit then
return 0
end
return if buffer.readu8(b, d) == 1 and buffer.readstring(b, d + 1, 6) == "vorbis" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?)
local dec, err = Vorbis.open(r, opts)
if not dec then
return nil, err
end
local d = dec :: any
local ch = d.channels
local parts, total = {}, 0
while true do
local b, n = d:read(65536)
if n == 0 then
break
end
local copy = buffer.create(n * ch * 4)
buffer.copy(copy, 0, b, 0, n * ch * 4)
table.insert(parts, copy)
total += n
end
local a = Types.Audio.new(d.sampleRate, ch, total)
local o = 0
for _, p in parts do
buffer.copy(a.samples, o, p)
o += buffer.len(p)
end
a.tags = d.tags
a.meta.source = d.source
return a, nil
end
-- ------------------------------------------------------------------------------------------------ open
local Stream = {}
Stream.__index = Stream
-- queue the chunk arrays[first .. first + count - 1] whose first sample has granule g0, trimmed to [lo, hi)
local function push(self: any, arrays: { { number } }, g0: number, count: number, hi: number)
local lo = math.max(g0, self.startG, self.skipTo)
if hi > g0 + count then
hi = g0 + count
end
if hi > lo then
table.insert(self.queue, { arrays, lo - g0 + 1, hi - g0, lo })
end
end
local function copyOut(self: any, count: number): { { number } }
local t = table.create(self.channels)
for c = 1, self.channels do
local src = self.st.out[c]
local a = table.create(count, 0)
table.move(src, 1, count, 1, a)
t[c] = a
end
return t
end
-- decode packets until something is queued; false at the end of the stream
local function decodeMore(self: any): boolean
local reader, st = self.reader, self.st
while not self.ended do
local p = reader:nextPacket()
if p == nil then
self.ended = true
break
end
if p.gap then
Packet.reset(st)
self.syncing, self.pend, self.pendCount = true, {}, 0
end
local count = Packet.decode(st, p.data, p.offset, p.size)
if count >= 0 then
local endG = if p.eos and p.granule >= 0 then p.granule else math.huge
if self.syncing then
if count > 0 then
table.insert(self.pend, { copyOut(self, count), count })
self.pendCount += count
end
if p.granule >= 0 then
-- the position is known again: this packet's output ends at its granule
local g = p.granule - self.pendCount
if p.eos and self.pendCount > 0 then
g = math.max(g, self.pos) -- an end-trimmed last page: keep the running position
end
for _, c in self.pend do
push(self, c[1], g, c[2], endG)
g += c[2]
end
self.pos = g
self.syncing, self.pend, self.pendCount = false, {}, 0
end
else
local g0 = self.pos
self.pos += count
if count > 0 then
push(self, st.out, g0, count, endG)
end
if p.granule >= 0 and not p.eos then
self.pos = p.granule
end
end
if p.eos then
self.ended = true
end
if #self.queue > 0 then
return true
end
end
end
return #self.queue > 0
end
function Stream.read(self: any, n: number, out: buffer?): (buffer, number)
local ch = self.channels
n = math.max(0, math.floor(n))
local b = if out and buffer.len(out) >= n * ch * 4 then out else buffer.create(n * ch * 4)
local got = 0
local writef32 = buffer.writef32
while got < n do
local q = self.queue[1]
if q == nil then
if not decodeMore(self) then
break
end
q = self.queue[1]
end
local arrays, first, last = q[1], q[2], q[3]
local take = math.min(n - got, last - first + 1)
for c = 1, ch do
local a = arrays[c]
local o = got * ch * 4 + (c - 1) * 4
for i = first, first + take - 1 do
writef32(b, o, a[i])
o += ch * 4
end
end
got += take
self.next = q[4] + take
if first + take > last then
table.remove(self.queue, 1)
else
q[2] = first + take
q[4] += take
end
end
if got > 0 then
self.skipTo = -math.huge
end
return b, got
end
function Stream.position(self: any): number
return (self.next - self.startG) / self.sampleRate
end
-- back to the first audio packet
local function restart(self: any)
local r = self.reader
r:rewind()
for _ = 1, 3 do
r:nextPacket()
end
Packet.reset(self.st)
self.pos = self.base
self.syncing, self.pend, self.pendCount = false, {}, 0
self.ended = false
self.queue = {}
end
function Stream.seek(self: any, seconds: number)
local target = self.startG + math.floor(math.max(0, seconds) * self.sampleRate + 0.5)
if target ~= target then
target = self.startG
end
if self.lastG >= 0 and target > self.lastG then
target = self.lastG
end
self.skipTo = target
self.next = target
local r = self.reader
local g = target - self.st.n1
for _ = 1, 16 do
if g <= self.startG then
break
end
local G = r:seekGranule(g)
if G == nil or G < 0 then
break
end
-- decode forward to the next page boundary to learn the exact position
Packet.reset(self.st)
self.queue = {}
self.ended = false
self.syncing, self.pend, self.pendCount = true, {}, 0
self.pos = G
local ok = false
while true do
local p = r:nextPacket()
if p == nil then
break
end
local count = Packet.decode(self.st, p.data, p.offset, p.size)
if count > 0 then
table.insert(self.pend, { copyOut(self, count), count })
self.pendCount += count
end
if p.granule >= 0 then
if not p.eos then
local g0 = p.granule - self.pendCount
for _, c in self.pend do
push(self, c[1], g0, c[2], math.huge)
g0 += c[2]
end
self.pos = p.granule
self.syncing, self.pend, self.pendCount = false, {}, 0
ok = true
end
break
end
end
if ok then
return
end
g = G - 1 -- the last page: start one page earlier
end
restart(self)
self.skipTo = target
self.next = target
end
function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil)
if not demux then
return nil, derr
end
local serial = demux:find("vorbis")
if serial == nil then
return nil, Err.new(Err.CORRUPT, "no Vorbis stream in the Ogg file")
end
local reader = demux:reader(serial)
local h1 = reader:nextPacket()
if h1 == nil then
return nil, Err.new(Err.TRUNCATED, "missing identification header")
end
local id0, ierr = Setup.ident(h1.data, h1.offset, h1.size)
if not id0 then
return nil, Err.new(Err.CORRUPT, ierr or "bad identification header")
end
local h2 = reader:nextPacket()
if h2 == nil then
return nil, Err.new(Err.TRUNCATED, "missing comment header")
end
local h2copy = { data = Ogg.copy(h2), offset = 0, size = h2.size }
local h3 = reader:nextPacket()
if h3 == nil then
return nil, Err.new(Err.TRUNCATED, "missing setup header")
end
local id, setup, vendor, tags, herr = headers(h1, h2copy, h3)
if not id then
return nil, herr
end
local st = Packet.new(id, setup)
if not st then
return nil, Err.new(Err.CORRUPT, "bad block sizes")
end
-- the granule of the first returned sample: the first granule page minus what its packets return
local base = 0
do
local prev, sum = 0, 0
while true do
local p = reader:nextPacket()
if p == nil then
break
end
local bs = Packet.blocksize(st, p.data, p.offset, p.size)
if bs > 0 then
if prev > 0 then
sum += prev // 4 + bs // 4
end
prev = bs
end
if p.granule >= 0 then
base = p.granule - sum
if p.eos then
base = 0 -- one page holds the whole stream: the spec trims its end, not its start
end
break
end
end
end
local info = demux:stream(serial)
local lastG = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else -1
local startG = math.max(base, 0)
local frames = if lastG >= 0 then math.max(0, lastG - startG) else 0
local rate = id.sampleRate
local self = setmetatable({
sampleRate = rate,
channels = id.channels,
frames = frames,
duration = frames / rate,
bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / rate)) else id.bitrateNominal,
tags = tags,
vendor = vendor,
ident = id,
source = {
format = "vorbis",
codec = "vorbis",
vendor = vendor,
blocksizes = { id.blocksize0, id.blocksize1 },
nominalBitrate = id.bitrateNominal,
},
demux = demux,
reader = reader,
st = st,
base = base,
startG = startG,
lastG = lastG,
pos = base,
next = startG,
skipTo = -math.huge,
queue = {},
syncing = false,
pend = {},
pendCount = 0,
ended = false,
}, Stream)
restart(self)
return self :: any, nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- packetDecoder(ident, comment, setup) -> a decoder of raw Vorbis packets (Matroska / WebM / MP4 carry the three
-- headers in their codec private data) | nil, Err. Each argument is a buffer holding one header packet.
-- local pd = Vorbis.packetDecoder(h1, h2, h3)
-- local n = pd:decode(buf, offset, size) -- frames returned (first packet 0; -1 = not audio); pd.out[ch][1 .. n]
-- pd:reset() -- after a seek
function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err?)
local function pk(b: buffer): any
return { data = b, offset = 0, size = buffer.len(b) }
end
local id, setup, vendor, tags, err = headers(pk(h1), pk(h2), pk(h3))
if not id then
return nil, err
end
local st = Packet.new(id, setup)
if not st then
return nil, Err.new(Err.CORRUPT, "bad block sizes")
end
return {
sampleRate = id.sampleRate,
channels = id.channels,
vendor = vendor,
tags = tags,
out = st.out,
decode = function(_self: any, b: buffer, offset: number, size: number): number
if offset < 0 or size < 0 or offset + size > buffer.len(b) then
return -1
end
return Packet.decode(st, b, offset, size)
end,
reset = function(_self: any)
Packet.reset(st)
end,
},
nil
end
return Vorbis