Files
rosetta/src/Formats/codecs/audio/Vorbis/Codebook.luau
T
4DBug 9941113b7b ws-cleanup: audio codecs out of the format folders (codecs/audio/Opus, Vorbis, Flac, Mpa)
The decoders / encoders are libraries, not the file format: audio/opus/{Celt, CeltTables, CeltEncoder, Mdct, Packet,
Silk, SilkTables, Decoder} -> codecs/audio/Opus; audio/vorbis/{Codebook, Packet, Setup, Tables} ->
codecs/audio/Vorbis; audio/flac/{Frame, Encode} -> codecs/audio/Flac; audio/mp3/{Core, Tables, Header, Encode2,
Encode3, EncTables, Analysis} -> codecs/audio/Mpa (tools/move.py; code unchanged). Each gets an index init.luau.
The format folders keep the file mapping: Ogg Opus / Ogg Vorbis (headers, granules, seeking, the Vorbis encoder's
Ogg writer), native / Ogg FLAC streams and metadata, ID3 / Xing / the MP3 frame index. docs: STYLE says a codec is
not the format. Full suite: 248 runs pass on both runtimes, lint green.
2026-10-31 12:47:02 -05:00

395 lines
9.7 KiB
Luau

--!strict
--!native
--!optimize 2
-- codecs/audio/Vorbis/Codebook: the Vorbis LSB-first packet bit reader and codebooks (Vorbis I spec sections 2 and 3):
-- reading a codebook from the setup header (ordered / sparse length lists, lookup types 1 and 2, float32_unpack),
-- the codeword assignment, and Huffman / VQ decoding. Ported from stb_vorbis 1.22 (public domain / MIT; see
-- licenses/stb_vorbis-LICENSE.txt): compute_codewords' lowest-free-leaf assignment, lookup1_values; the decode side
-- is a fast table (up to 10 bits) plus a binary tree for longer codes instead of stb's sorted binary search.
--
-- Never throws. Reading past the packet end gives zero bits and sets br.eop (the spec's end-of-packet condition);
-- an invalid codeword also sets eop and decodes to -1.
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