ws-audio: Vorbis encoder (audio/vorbis/Encode: long blocks, floor 1 fit to the envelope, square-polar coupling, residue 2 with 6 classes + cascades, fixed Laplacian-Huffman codebooks, exact granules, Ogg via containers/Ogg Mux) wired into audio/vorbis encode; fixtures: ogginfo clean, oggdec exact lengths + SNR floors, ffmpeg; bench line

This commit is contained in:
4DBug committed 2026-10-31 09:29:09 -05:00
1 parent 929b5d6d53
commit cb05744367
7 files changed
+1068 -7

No files matched your search

+1 -1
View File
@@ -13,7 +13,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` |
| audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` |
| audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` |
| audio | vorbis | .ogg .oga | yes | - | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` |
| audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` |
| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` |
| archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` |
+2 -2
View File
@@ -116,8 +116,8 @@ local list: { Entry } = {
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 },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 },
load = function()
return require("@formats/audio/vorbis")
end,
+825
View File
@@ -0,0 +1,825 @@
--!strict
--!native
--!optimize 2
-- audio/vorbis/Encode: a basic but valid Vorbis I encoder in Ogg. New code written from the Vorbis I specification
-- (no libvorbis code). Design: long blocks only (2048 samples; blocksize 0 is declared as 256 but never used), the
-- Vorbis window, the MDCT (codecs/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a
-- fixed post list of 30 points (bisection order, multiplier 2) fitted to the spectral envelope minus a quality-
-- dependent SNR, so the residue is quantized in steps of the floor; stereo square-polar coupling of the integer
-- residues (lossless); residue type 2 with 16-values-per-channel partitions and six classes (silent, |v| <= 1, 4, 15, then
-- cascades of x16 / x256 books for larger values); a fixed codebook set whose Huffman lengths come from Laplacian
-- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact
-- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws.
local Mdct = require("@formats/codecs/Mdct")
local Ogg = require("@formats/containers/Ogg")
local Tables = require("@formats/audio/vorbis/Tables")
local Encode = {}
local floor, log, exp, abs = math.floor, math.log, math.exp, math.abs
local writeu8 = buffer.writeu8
local POW = table.create(40, 0)
for i = 0, 39 do
POW[i + 1] = 2 ^ i
end
local N = 2048
local N2 = 1024
local PSIZE_PER_CHANNEL = 16 -- residue partitions hold 16 values per channel (libvorbis needs a multiple of ch)
local MULT = 2 -- floor1 multiplier (range 128)
local RANGE = 128
local NCLASS = 6
-- ------------------------------------------------------------------------------------------------ LSB-first bit writer
type W = { buf: buffer, pos: number, acc: number, cnt: number }
local function newW(size: number): W
return { buf = buffer.create(size), pos = 0, acc = 0, cnt = 0 }
end
local function put(w: W, v: number, n: number)
if n == 0 then
return
end
local acc = w.acc + v * POW[w.cnt + 1]
local cnt = w.cnt + n
local b, p = w.buf, w.pos
if p + 8 > buffer.len(b) then
local nb = buffer.create(buffer.len(b) * 2 + 64)
buffer.copy(nb, 0, b, 0, p)
b = nb
w.buf = nb
end
while cnt >= 8 do
local byte = acc % 256
writeu8(b, p, byte)
p += 1
acc = (acc - byte) / 256
cnt -= 8
end
w.acc, w.cnt, w.pos = acc, cnt, p
end
local function finish(w: W): buffer
if w.cnt > 0 then
put(w, 0, 8 - w.cnt)
end
local out = buffer.create(w.pos)
buffer.copy(out, 0, w.buf, 0, w.pos)
return out
end
local function putString(w: W, s: string)
for i = 1, #s do
put(w, string.byte(s, i), 8)
end
end
local function ilog(x: number): number
local n = 0
while x > 0 do
n += 1
x = floor(x / 2)
end
return n
end
-- ------------------------------------------------------------------------------------------------ codebooks
type Book = {
dims: number,
entries: number,
lengths: { number },
codes: { number }, -- bit-reversed codewords (ready for the LSB-first writer)
lookup: number, -- 0 or 1
minimum: number,
delta: number,
values: number, -- lookup1 values per dimension
}
-- Huffman code lengths for weights w[1..n] (all > 0), at most 24 bits long (weights are floored to keep it so)
local function huffmanLengths(w: { number }): { number }
local n = #w
local total = 0
for i = 1, n do
total += w[i]
end
local lens = table.create(n, 0)
if n == 1 then
lens[1] = 1
return lens
end
local minw = total * 2 ^ -20
-- nodes: leaves 1..n then internal; a simple O(n^2)-free approach with two sorted queues
local order = table.create(n, 0)
for i = 1, n do
order[i] = i
end
local weight = table.create(2 * n, 0)
local parent = table.create(2 * n, 0)
for i = 1, n do
weight[i] = math.max(w[i], minw)
end
table.sort(order, function(a: number, b: number): boolean
if weight[a] ~= weight[b] then
return weight[a] < weight[b]
end
return a < b
end)
local q1, h1 = order, 1 -- leaves, ascending
local q2, h2, t2 = table.create(n, 0), 1, 0 -- internal nodes, created in ascending weight order
local nextId = n
local function pop(): number
local a = if h1 <= n then q1[h1] else nil
local b = if h2 <= t2 then q2[h2] else nil
if a and (not b or weight[a] <= weight[b]) then
h1 += 1
return a
end
h2 += 1
return b :: number
end
for _ = 1, n - 1 do
local a = pop()
local b = pop()
nextId += 1
weight[nextId] = weight[a] + weight[b]
parent[a], parent[b] = nextId, nextId
t2 += 1
q2[t2] = nextId
end
for i = 1, n do
local d, x = 0, i
while parent[x] ~= 0 do
x = parent[x]
d += 1
end
lens[i] = d
end
return lens
end
-- the spec's codeword assignment (lowest free leaf, in entry order); returns bit-reversed codes
local function assign(lens: { number }): { number }
local codes = table.create(#lens, 0)
local available = table.create(33, 0)
local first = true
for i, len in lens do
if len > 0 then
local code
if first then
first = false
code = 0
for l = 1, len do
available[l + 1] = POW[33 - l] + 1
end
else
local z = len
while z > 0 and available[z + 1] == 0 do
z -= 1
end
code = available[z + 1] - 1
available[z + 1] = 0
for y = len, z + 1, -1 do
available[y + 1] = code + POW[33 - y] + 1
end
end
-- the top len bits of the 32-bit left-aligned code, MSB first, reversed for the LSB-first writer
local msb = floor(code / POW[33 - len])
local rev = 0
for _ = 1, len do
rev = rev * 2 + msb % 2
msb = floor(msb / 2)
end
codes[i] = rev
end
end
return codes
end
local function makeBook(dims: number, entries: number, weight: (number) -> number, lookup: number, minimum: number, delta: number, values: number): Book
local w = table.create(entries, 0)
for e = 0, entries - 1 do
w[e + 1] = weight(e)
end
local lens = huffmanLengths(w)
return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values }
end
-- a VQ book of `dims` dimensions over integer values -h .. h times `scale`, Laplacian weights exp(-|v| / s)
local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book
local values = 2 * h + 1
local entries = values ^ dims
return makeBook(dims, entries, function(e: number): number
local wt = 1
local x = e
for _ = 1, dims do
local v = x % values - h
x = x // values
wt *= exp(-abs(v) / s) * (if v == 0 then zeroBoost else 1)
end
return wt
end, 1, -h * scale, scale, values)
end
local BOOK_FLOOR = makeBook(1, RANGE, function(e: number): number
return exp(-e / 7) + 0.002
end, 0, 0, 0, 0)
local CLASS_W = { 0.30, 0.30, 0.20, 0.12, 0.06, 0.02 }
local BOOK_CLASS = makeBook(2, NCLASS * NCLASS, function(e: number): number
return CLASS_W[e % NCLASS + 1] * CLASS_W[e // NCLASS + 1]
end, 0, 0, 0, 0)
local BOOK_A = vqBook(4, 1, 1, 0.6, 2.5) -- |v| <= 1, 4 at a time (mostly zeros)
local BOOK_B = vqBook(2, 4, 1, 1.4, 1) -- |v| <= 4
local BOOK_C = vqBook(2, 15, 1, 4, 1) -- |v| <= 15
local BOOK_D = vqBook(2, 15, 16, 3, 1) -- multiples of 16 up to 240
local BOOK_E = vqBook(2, 15, 256, 3, 1) -- multiples of 256 up to 3840
local BOOKS = { BOOK_FLOOR, BOOK_CLASS, BOOK_A, BOOK_B, BOOK_C, BOOK_D, BOOK_E }
local FLOOR_BOOK, CLASS_BOOK, A_BOOK, B_BOOK, C_BOOK, D_BOOK, E_BOOK = 0, 1, 2, 3, 4, 5, 6
-- the books of each residue class per pass (book numbers; -1 = none)
local CLASS_BOOKS = {
{ -1, -1, -1 },
{ A_BOOK, -1, -1 },
{ B_BOOK, -1, -1 },
{ C_BOOK, -1, -1 },
{ D_BOOK, C_BOOK, -1 },
{ E_BOOK, D_BOOK, C_BOOK },
}
local CLASS_MAX = { 0, 1, 4, 15, 255, 4095 }
-- float32_pack (spec 9.2.2) of an integer-valued x
local function float32Pack(x: number): number
local sign = if x < 0 then 2147483648 else 0
local m = abs(x)
local e = 788
while m >= 2097152 do
m /= 2
e += 1
end
return sign + e * 2097152 + floor(m)
end
local function writeBook(w: W, b: Book)
put(w, 0x564342, 24)
put(w, b.dims, 16)
put(w, b.entries, 24)
put(w, 0, 1) -- not ordered
put(w, 0, 1) -- not sparse
for i = 1, b.entries do
put(w, b.lengths[i] - 1, 5)
end
put(w, b.lookup, 4)
if b.lookup == 1 then
put(w, float32Pack(b.minimum), 32)
put(w, float32Pack(b.delta), 32)
local vb = ilog(b.values - 1)
put(w, vb - 1, 4)
put(w, 0, 1) -- sequence_p
for j = 0, b.values - 1 do
put(w, j, vb)
end
end
end
local function putEntry(w: W, b: Book, e: number)
put(w, b.codes[e + 1], b.lengths[e + 1])
end
-- ------------------------------------------------------------------------------------------------ floor posts
-- x positions: 0, 1024, then 28 log-spaced points in bisection order (coarse first) so predictions are good
local POSTS: { number } = { 0, N2 }
do
local xs = {}
local seen = { [0] = true, [N2] = true }
for j = 0, 27 do
local x = floor(3 + 957 * (j / 27) ^ 2.2 + 0.5) -- 3 .. 960, denser at low frequencies
while seen[x] do
x += 1
end
seen[x] = true
table.insert(xs, x)
end
table.sort(xs)
-- bisection order over the sorted list
local queue = { { 1, #xs } }
local qh = 1
while qh <= #queue do
local r = queue[qh]
qh += 1
if r[1] <= r[2] then
local m = (r[1] + r[2]) // 2
table.insert(POSTS, xs[m])
table.insert(queue, { r[1], m - 1 })
table.insert(queue, { m + 1, r[2] })
end
end
end
local NPOSTS = #POSTS -- 30
local FLOOR_PARTS = (NPOSTS - 2) // 4 -- 7 partitions of one class with 4 dimensions
local SORTED: { number } = table.create(NPOSTS, 0) -- post indices (1-based) by increasing x
for i = 1, NPOSTS do
SORTED[i] = i
end
table.sort(SORTED, function(a: number, b: number): boolean
return POSTS[a] < POSTS[b]
end)
local LOW, HIGH = table.create(NPOSTS, 0), table.create(NPOSTS, 0)
for j = 3, NPOSTS do
local lo, hi = -1, 65536
local x = POSTS[j]
for k = 1, j - 1 do
local xv = POSTS[k]
if xv > lo and xv < x then
LOW[j], lo = k, xv
end
if xv < hi and xv > x then
HIGH[j], hi = k, xv
end
end
end
-- the floor value (0..127) closest to an amplitude, through the spec's inverse dB table
local DB = table.create(RANGE, 0)
for y = 0, RANGE - 1 do
DB[y + 1] = 20 * math.log10(Tables[y * MULT + 1])
end
local function yOf(db: number): number
local y = floor((db - DB[1]) / (DB[RANGE] - DB[1]) * (RANGE - 1) + 0.5)
return math.clamp(y, 0, RANGE - 1)
end
local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number
local dy = y1 - y0
local adx = x1 - x0
local off = (abs(dy) * (x - x0)) // adx
return if dy < 0 then y0 - off else y0 + off
end
-- render the decoder's floor curve for final Y values into F[1..N2] (only the posts the decoder marks used)
local function renderFloor(Y: { number }, used: { boolean }, F: { number })
local lx, ly = 0, Y[1] * MULT
for q = 2, NPOSTS do
local j = SORTED[q]
if not used[j] then
continue
end
local hx, hy = POSTS[j], Y[j] * MULT
-- draw_line(lx, ly, hx, hy)
local dy = hy - ly
local adx = hx - lx
local ady = abs(dy)
local base = if dy < 0 then -(ady // adx) else ady // adx
local sy = if dy < 0 then base - 1 else base + 1
ady -= abs(base) * adx
local x, y, err = lx, ly, 0
local x1 = math.min(hx, N2)
if x < x1 then
F[x + 1] = Tables[y % 256 + 1]
x += 1
while x < x1 do
err += ady
if err >= adx then
err -= adx
y += sy
else
y += base
end
F[x + 1] = Tables[y % 256 + 1]
x += 1
end
end
lx, ly = hx, hy
end
for x = lx + 1, N2 do
F[x] = Tables[ly % 256 + 1]
end
end
-- the coded value for target t at post j given the final values of its neighbours (spec 7.2.4 step 1, inverted)
local function floorVal(Y: { number }, j: number): number
local lo, hi = LOW[j], HIGH[j]
local pred = predict(POSTS[j], POSTS[lo], POSTS[hi], Y[lo], Y[hi])
local t = Y[j]
local d = t - pred
if d == 0 then
return 0
end
local highroom = RANGE - pred
local lowroom = pred
local room = if highroom < lowroom then highroom * 2 else lowroom * 2
local cands = { if d > 0 then 2 * d else -2 * d - 1, d + lowroom, -d + highroom - 1 }
for _, v in cands do
if v > 0 and v < RANGE then
local got
if v >= room then
got = if highroom > lowroom then v - lowroom + pred else pred - v + highroom - 1
elseif v % 2 == 1 then
got = pred - (v + 1) // 2
else
got = pred + v // 2
end
if got == t then
return v
end
end
end
return 0 -- unreachable for t in range; fall back to the prediction
end
-- ------------------------------------------------------------------------------------------------ headers
local function identHeader(ch: number, rate: number, nominal: number): buffer
local w = newW(64)
put(w, 1, 8)
putString(w, "vorbis")
put(w, 0, 32)
put(w, ch, 8)
put(w, rate, 32)
put(w, 0, 32)
put(w, nominal, 32)
put(w, 0, 32)
put(w, 8, 4) -- blocksize 0: 256
put(w, 11, 4) -- blocksize 1: 2048
put(w, 1, 1)
return finish(w)
end
local function commentHeader(vendor: string, tags: { [string]: string }): buffer
local w = newW(256)
put(w, 3, 8)
putString(w, "vorbis")
put(w, #vendor, 32)
putString(w, vendor)
local keys = {}
for k, v in tags do
if type(k) == "string" and type(v) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
put(w, #keys, 32)
for _, k in keys do
local name = if k == "track" then "TRACKNUMBER" else string.upper(k)
local s = name .. "=" .. tags[k]
put(w, #s, 32)
putString(w, s)
end
put(w, 1, 1)
return finish(w)
end
local function setupHeader(ch: number): buffer
local w = newW(8192)
put(w, 5, 8)
putString(w, "vorbis")
-- codebooks
put(w, #BOOKS - 1, 8)
for _, b in BOOKS do
writeBook(w, b)
end
-- time domain placeholders
put(w, 0, 6)
put(w, 0, 16)
-- one floor 1
put(w, 0, 6)
put(w, 1, 16)
put(w, FLOOR_PARTS, 5)
for _ = 1, FLOOR_PARTS do
put(w, 0, 4) -- class 0
end
put(w, 3, 3) -- class 0: 4 dimensions
put(w, 0, 2) -- no subclasses
put(w, FLOOR_BOOK + 1, 8) -- its one subclass book (+1)
put(w, MULT - 1, 2)
put(w, 10, 4) -- rangebits: x in 0 .. 1024
for j = 3, NPOSTS do
put(w, POSTS[j], 10)
end
-- one residue 2
put(w, 0, 6)
put(w, 2, 16)
put(w, 0, 24) -- begin
put(w, N2 * ch, 24) -- end
put(w, PSIZE_PER_CHANNEL * ch - 1, 24)
put(w, NCLASS - 1, 6)
put(w, CLASS_BOOK, 8)
for c = 1, NCLASS do
local bits = 0
for pass = 1, 3 do
if CLASS_BOOKS[c][pass] >= 0 then
bits += POW[pass]
end
end
put(w, bits % 8, 3)
if bits >= 8 then
put(w, 1, 1)
put(w, bits // 8, 5)
else
put(w, 0, 1)
end
end
for c = 1, NCLASS do
for pass = 1, 3 do
local b = CLASS_BOOKS[c][pass]
if b >= 0 then
put(w, b, 8)
end
end
end
-- one mapping
put(w, 0, 6)
put(w, 0, 16)
put(w, 0, 1) -- one submap
if ch == 2 then
put(w, 1, 1)
put(w, 0, 8) -- one coupling step
put(w, 0, 1) -- magnitude: channel 0
put(w, 1, 1) -- angle: channel 1
else
put(w, 0, 1)
end
put(w, 0, 2)
put(w, 0, 8) -- submap 0: time (unused)
put(w, 0, 8) -- floor 0
put(w, 0, 8) -- residue 0
-- one mode: long blocks
put(w, 0, 6)
put(w, 1, 1)
put(w, 0, 16)
put(w, 0, 16)
put(w, 0, 8)
put(w, 1, 1) -- framing
return finish(w)
end
-- ------------------------------------------------------------------------------------------------ encoder
export type Source = {
sampleRate: number,
channels: number,
frames: number,
tags: { [string]: string },
read: (self: any, n: number, out: buffer?) -> (buffer, number),
err: any,
}
export type Options = {
quality: number, -- -1 .. 10
vendor: string,
serial: number,
}
-- the residue of one partition: vectors of each pass for class c
local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number)
local b = CLASS_BOOKS[c][pass]
if b < 0 then
return
end
local book = BOOKS[b + 1]
local dims, h = book.dims, (book.values - 1) // 2
local scale = book.delta
local values = book.values
local i = 0
while i < psize do
local e = 0
local m = 1
for k = 0, dims - 1 do
local x = v[o + i + k + 1]
-- the part of x this pass carries (coarse passes take the rounded multiple of their scale)
local q
if pass < 3 and CLASS_BOOKS[c][pass + 1] >= 0 then
q = math.clamp(floor(x / scale + 0.5), -h, h)
else
q = math.clamp(x // scale, -h, h)
end
v[o + i + k + 1] = x - q * scale
e += (q + h) * m
m *= values
end
putEntry(w, book, e)
i += dims
end
end
function Encode.encode(src: Source, opts: Options): (buffer?, string?)
local ch, rate = src.channels, src.sampleRate
local q = math.clamp(opts.quality, -1, 10)
local snrDb = 2 * q - 1 -- floor level below the band energy (at low frequencies; 8 dB less at the top)
local mux = Ogg.muxer({ pageSize = 4096 })
local stream = mux:stream(opts.serial)
local nominal = floor(math.clamp(rate * ch * (0.6 + 0.12 * q), 32000, 500000))
stream:packet(identHeader(ch, rate, nominal), 0, { flush = true })
stream:packet(commentHeader(opts.vendor, src.tags), 0)
stream:packet(setupHeader(ch), 0, { flush = true })
local plan = Mdct.new(N) :: Mdct.Plan
local win = Mdct.window("vorbis", N) :: { number }
-- input ring: per channel the samples of the current frame [k*1024 - 1024, k*1024 + 1024)
local frame = table.create(ch)
for c = 1, ch do
frame[c] = table.create(N, 0)
end
local blk = table.create(N, 0)
local X = table.create(ch)
local R = table.create(ch)
for c = 1, ch do
X[c] = table.create(N2, 0)
R[c] = table.create(N2, 0)
end
local F = table.create(N2, 0)
local Y = table.create(NPOSTS, 0)
local vals = table.create(NPOSTS, 0)
local used = table.create(NPOSTS, false)
local inter = table.create(N2 * ch, 0)
local psize = PSIZE_PER_CHANNEL * ch
local npart = N2 * ch // psize
local classes = table.create(npart + 2, 0)
local total = 0
local srcDone = false
local tmp: buffer? = nil
local pending: buffer? = nil
local pendN, pendOff = 0, 0
local k = 0
local lastWanted = -1 -- the last packet index needed (known once the input ends)
while true do
-- shift in the next 1024 input samples (zeros past the end)
for c = 1, ch do
local fr = frame[c]
table.move(fr, N2 + 1, N, 1)
end
local got = 0
while got < N2 and not srcDone do
if pendN == 0 then
local b, n = src:read(4096, tmp)
if n <= 0 then
srcDone = true
break
end
tmp = b
pending, pendN, pendOff = b, n, 0
end
local take = math.min(N2 - got, pendN)
local pb = pending :: buffer
for i = 0, take - 1 do
local base = (pendOff + i) * ch * 4
for c = 1, ch do
frame[c][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4)
end
end
got += take
pendN -= take
pendOff += take
end
for c = 1, ch do
local fr = frame[c]
for i = N2 + got + 1, N do
fr[i] = 0
end
end
total += got
if srcDone and lastWanted < 0 then
lastWanted = (total + N2 - 1) // N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024))
end
-- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024)
-- (frame k holds input [(k - 1) * 1024, (k + 1) * 1024): the shift above moved the window by 1024)
-- MDCT per channel
local energy = 0
for c = 1, ch do
local fr = frame[c]
for i = 1, N do
blk[i] = fr[i] * win[i]
end
Mdct.forward(plan, blk, 1, X[c], 1, 1, 4 / N)
local xc = X[c]
for i = 1, N2 do
energy += xc[i] * xc[i]
end
end
local w = newW(2048)
put(w, 0, 1) -- audio packet
-- (one mode: 0 bits) long block, previous and next long
put(w, 1, 1)
put(w, 1, 1)
local silent = energy < 1e-18
if silent then
for _ = 1, ch do
put(w, 0, 1) -- no floor: the channel is zero
end
else
-- the floor from the loudest channel's band energies at each post
for j = 1, NPOSTS do
local x = POSTS[j]
-- the band around x: halfway to the neighbouring posts in x order
local idx = table.find(SORTED, j) :: number
local lo = if idx > 1 then (POSTS[SORTED[idx - 1]] + x) // 2 else 0
local hi = if idx < NPOSTS then (POSTS[SORTED[idx + 1]] + x) // 2 else N2 - 1
if hi < lo then
hi = lo
end
local e = 0
for c = 1, ch do
local xc = X[c]
local s = 0
for i = lo + 1, math.min(hi + 1, N2) do
s += xc[i] * xc[i]
end
s /= (hi - lo + 1)
if s > e then
e = s
end
end
local db = if e > 0 then 10 * math.log10(e) - snrDb + 8 * x / N2 else -200
Y[j] = yOf(db)
end
-- the decoder's step 2 flags: a point is drawn when its value or a later neighbour's value is nonzero
used[1], used[2] = true, true
for j = 3, NPOSTS do
local v = floorVal(Y, j)
vals[j] = v
used[j] = v ~= 0
if v ~= 0 then
used[LOW[j]], used[HIGH[j]] = true, true
end
end
renderFloor(Y, used, F)
-- residues: X / F rounded, then coupling, then interleaving
for c = 1, ch do
local xc, rc = X[c], R[c]
for i = 1, N2 do
local v = floor(xc[i] / F[i] + 0.5)
rc[i] = math.clamp(v, -4095, 4095)
end
end
if ch == 2 then
local l, r = R[1], R[2]
for i = 1, N2 do
local a, b = l[i], r[i]
local m, an
if abs(a) > abs(b) then
m = a
an = if a > 0 then a - b else b - a
else
m = b
an = if b > 0 then a - b else b - a
end
-- keep the angle inside the books' range
l[i], r[i] = m, math.clamp(an, -4095, 4095)
end
end
for c = 1, ch do
local rc = R[c]
for i = 1, N2 do
inter[(i - 1) * ch + c] = rc[i]
end
end
-- floors
for _ = 1, ch do
put(w, 1, 1)
put(w, Y[1], 7)
put(w, Y[2], 7)
for j = 3, NPOSTS do
putEntry(w, BOOK_FLOOR, vals[j])
end
end
-- residue classes
for p = 0, npart - 1 do
local m = 0
for i = 1, psize do
local a = abs(inter[p * psize + i])
if a > m then
m = a
end
end
local c = 1
while CLASS_MAX[c] < m do
c += 1
end
classes[p + 1] = c
end
classes[npart + 1] = 1
for pass = 1, 3 do
for p = 0, npart - 1, 2 do
if pass == 1 then
putEntry(w, BOOK_CLASS, (classes[p + 1] - 1) * NCLASS + (classes[p + 2] - 1)) -- first partition: the high digit
end
writePartition(w, inter, p * psize, psize, classes[p + 1], pass)
if p + 1 < npart then
writePartition(w, inter, (p + 1) * psize, psize, classes[p + 2], pass)
end
end
end
end
local pk = finish(w)
local last = lastWanted >= 0 and k >= lastWanted
local granule = if k == 0 then 0 else math.min(k * N2, if lastWanted >= 0 then total else math.huge)
stream:packet(pk, granule, if last then { eos = true } else nil)
if last then
break
end
k += 1
end
if src.err then
return nil, tostring(src.err)
end
return mux:finish(), nil
end
-- the codebooks (tests check the Huffman lengths are a valid prefix code)
Encode.BOOKS = BOOKS
return Encode
+42 -4
View File
@@ -5,8 +5,10 @@
-- 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).
-- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Encode (audio/vorbis/Encode, new code): a basic
-- Ogg Vorbis encoder from an Audio or a streamed Decoder (long blocks, floor 1, coupled residue 2, a fixed codebook
-- set, quality -1 .. 10). 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), short blocks in the encoder.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
@@ -15,6 +17,8 @@ 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")
local Encode = require("@formats/audio/vorbis/Encode")
local Pcm = require("@formats/codecs/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Vorbis = {
@@ -22,13 +26,18 @@ local 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 },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 },
}
export type OpenOptions = {
verify: boolean?, -- check the Ogg page CRCs (default true)
}
export type EncodeOptions = {
quality: number?, -- -1 .. 10 (default 3): the floor sits 2 * quality - 1 dB under the band energies (8 dB
-- less at the top of the spectrum), which sets the residue's quantization step
serial: number?, -- the Ogg stream serial number (default 0x464C5541)
}
-- ------------------------------------------------------------------------------------------------ constants
local TAG_KEYS = { tracknumber = "track", description = "comment" }
@@ -109,6 +118,35 @@ function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audioOrDecoder, opts?) -> an Ogg Vorbis file | nil, Err
function Vorbis.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local o: EncodeOptions = opts or {}
local q = o.quality or 3
if type(q) ~= "number" or q ~= q or q < -1 or q > 10 then
return nil, Err.new(Err.ARG, "quality must be -1 .. 10")
end
if src.channels > 255 then
return nil, Err.new(Err.ARG, "at most 255 channels")
end
if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "the sample rate must be a positive integer")
end
local serial = o.serial or 0x464C5541
if type(serial) ~= "number" or serial ~= math.floor(serial) or serial < 0 or serial >= 2 ^ 32 then
return nil, Err.new(Err.ARG, "serial must be a 32-bit unsigned integer")
end
local out, msg = Encode.encode(src :: any, { quality = q, vendor = "formats-luau Vorbis encoder", serial = serial })
if not out then
return nil, Err.new(Err.CORRUPT, tostring(msg))
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ open
local Stream = {}
Stream.__index = Stream
+110
View File
@@ -0,0 +1,110 @@
-- audio/vorbis encoder tests: every fixture-step encode (qualities -1 .. 10, mono / stereo / 5.1, 8 .. 96 kHz, odd
-- lengths, silence) passes ogginfo, decodes in oggdec (libvorbisfile) with the exact input length and an SNR over a
-- per-quality floor, and in ffmpeg; our own decoder gives the same; the codebooks are valid prefix codes; streaming
-- from a Decoder gives the same bytes; tags round-trip; option errors. Fixtures: tools/fixtures/vorbis_enc.py.
local T = require("@tests/T")
local Vorbis = require("@formats/audio/vorbis")
local VEnc = require("@formats/audio/vorbis/Encode")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Enc = require("@tests/gen/vorbis_enc")
local Sigs = require("@tests/gen/vorbis_enc_sigs")
local t = T.suite("vorbis_encode")
local function audio(name: string): Types.Audio
local s = Sigs[name]
local a = Types.Audio.new(s.rate, s.channels, s.frames)
buffer.writestring(a.samples, 0, s.data)
return a
end
local function snr(x: Types.Audio, y: Types.Audio): number
local sig, er = 0, 0
for i = 0, math.min(x.frames, y.frames) * x.channels - 1 do
local a = buffer.readf32(x.samples, i * 4)
local d = a - buffer.readf32(y.samples, i * 4)
sig += a * a
er += d * d
end
if er == 0 then
return 200
end
return if sig > 0 then 10 * math.log10(sig / er) else -200
end
local function floorFor(q: number): number
return 8 + 1.2 * math.max(q, 0)
end
t:check(Vorbis.caps.encode and Vorbis.encode ~= nil, "caps.encode")
-- the codebooks: Kraft sums of exactly 1 (complete prefix codes) and lengths 1 .. 24
for i, b in VEnc.BOOKS do
local k, okLen = 0, true
for _, l in b.lengths do
k += 2 ^ -l
okLen = okLen and l >= 1 and l <= 24
end
t:check(math.abs(k - 1) < 1e-9 and okLen, "codebook " .. (i - 1) .. ": complete prefix code")
end
local minSnr = math.huge
for _, e in Enc do
t:eq(e.ogginfo, "", e.name .. ": ogginfo reports no warnings / errors")
t:eq(e.oggdecFrames, e.frames, e.name .. ": oggdec frames = input frames")
t:eq(e.ffErrors, "", e.name .. ": ffmpeg decodes without errors")
local silent = string.find(e.name, "silence", 1, true) ~= nil
local f = if silent then -math.huge else floorFor(e.quality)
t:check(e.oggdecSnr >= f, string.format("%s: oggdec SNR %.1f dB (floor %.1f)", e.name, e.oggdecSnr, f))
if e.frames >= 2048 then
-- (ffmpeg does not trim the end of a stream that fits on one Ogg page: up to a block more)
t:check(e.ffFrames >= e.frames and e.ffFrames <= e.frames + 1024, string.format("%s: ffmpeg frames %d", e.name, e.ffFrames))
t:check(e.ffSnr >= f, string.format("%s: ffmpeg SNR %.1f dB", e.name, e.ffSnr))
end
if not silent then
minSnr = math.min(minSnr, e.oggdecSnr)
end
-- our decoder: the same length and quality (it is sample-exact with libvorbis)
local x = audio(e.sig)
local y, err = Vorbis.decode(Bytes.reader(buffer.fromstring(e.data)))
t:check(y, e.name .. ": our decoder: " .. tostring(err))
t:eq(y.frames, e.frames, e.name .. ": our decoder's frames")
local s = snr(x, y)
t:check(math.abs(s - e.oggdecSnr) < 0.5 or s >= 100, string.format("%s: our decoder %.1f dB, oggdec %.1f dB", e.name, s, e.oggdecSnr))
end
t:note("%d encodes pass ogginfo / oggdec / ffmpeg; lowest SNR %.1f dB", #Enc, minSnr)
-- streaming, tags
do
local a = audio("music_2_3000_44100")
local f1 = Vorbis.encode(a) :: buffer
local f2 = Vorbis.encode(Pcm.audioDecoder(a)) :: buffer
t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source")
a.tags = { title = "Tïtle", artist = "Artist", track = "9" }
local f3 = Vorbis.encode(a, { quality = 1, serial = 77 }) :: buffer
local d = Vorbis.open(Bytes.reader(f3)) :: any
t:eq(d.tags.title, "Tïtle", "title tag")
t:eq(d.tags.track, "9", "track tag")
t:check(string.find(d.vendor, "formats-luau", 1, true) ~= nil, "vendor")
local empty = Vorbis.encode(Types.Audio.new(44100, 1, 0)) :: buffer
local e0 = Vorbis.decode(Bytes.reader(empty))
t:check(e0 and e0.frames == 0, "empty input")
end
-- errors
do
local a = Types.Audio.new(44100, 2, 10)
local function code(v: any, o: any): string?
local _, e = Vorbis.encode(v, o)
return e and e.code
end
t:eq(code("x", nil), Err.ARG, "junk")
t:eq(code(a, { quality = 11 }), Err.ARG, "quality 11")
t:eq(code(a, { quality = -2 }), Err.ARG, "quality -2")
t:eq(code(a, { serial = -1 }), Err.ARG, "serial -1")
t:eq(code(Types.Audio.new(44100.5, 1, 1), nil), Err.ARG, "fractional rate")
end
-- (the decoder's fuzz pass is in tests/audio/vorbis.luau; the encoder takes no untrusted bytes)
t:done()
+14
View File
@@ -160,3 +160,17 @@ do
print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt))
end
end
-- vorbis encode (ws-audio): 10 s of 44.1 kHz stereo tones at quality 3
do
local Vb = require("@formats/audio/vorbis")
local n = 441000
local a = Types.Audio.new(44100, 2, n)
for i = 0, n - 1 do
buffer.writef32(a.samples, i * 8, math.sin(i * 0.031) * 0.4 + math.sin(i * 0.21) * 0.1)
buffer.writef32(a.samples, i * 8 + 4, math.sin(i * 0.017) * 0.3)
end
local dt = bench("vorbis encode q3 (10 s st)", 2, n * 8, function()
Vb.encode(a, { quality = 3 })
end)
print(string.format("%-8s %-30s %8.1fx real time", runtime, "", 10 / dt))
end
+74
View File
@@ -0,0 +1,74 @@
# Vorbis encoder fixtures (tools/fixtures.py): our encoder runs in the fixture step (tools/fixtures/_audio.py
# encode_luau_many) on test signals (qualities -1 .. 10, mono / stereo / 5.1, 8 .. 96 kHz, odd lengths, silence);
# oggdec (libvorbisfile) and ffmpeg decode every file, ogginfo checks the stream. Recorded per file: ogginfo's warnings
# and errors, oggdec's frame count, the SNR of oggdec's and ffmpeg's decodes against the input (no delay: the
# granules are exact).
# tests/gen/vorbis_enc.luau { name, sig, quality, rate, channels, frames, ogginfo, oggdecFrames, oggdecSnr,
# ffFrames, ffSnr, ffErrors, kbps, data }
# tests/gen/vorbis_enc_sigs.luau { [sig] = { rate, channels, frames, data (f32le) } }
import importlib.util, os, re
_spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py"))
A = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(A)
INPUTS = ["src/Formats/audio/vorbis", "src/Formats/codecs", "src/Formats/containers/Ogg"]
WAVE_FROM_VORBIS6 = [0, 2, 1, 4, 5, 3] # vorbis channel k is WAVE channel WAVE_FROM_VORBIS6[k]
def reorder(x):
out = [0.0] * len(x)
for i in range(0, len(x) - 5, 6):
for k in range(6):
out[i + k] = x[i + WAVE_FROM_VORBIS6[k]]
return out
def generate(ctx):
sigs = {}
def sig(kind, ch, frames, rate):
name = "%s_%d_%d_%d" % (kind, ch, frames, rate)
if name not in sigs:
sigs[name] = (A.from_f32le(A.f32le(A.signal(kind, rate, ch, frames, seed=frames % 1000 + ch))), rate, ch)
return name
cases = []
for q in (-1, 0, 3, 6, 10):
cases.append(("music-st-44k-q%d" % q, sig("music", 2, 44100, 44100), q))
cases.append(("sine-st-44k-q3", sig("sine", 2, 30000, 44100), 3))
cases.append(("sweep-mono-48k-q3", sig("sweep", 1, 40000, 48000), 3))
cases.append(("noise-mono-22k-q5", sig("noise", 1, 15000, 22050), 5))
cases.append(("music-mono-8k-q2", sig("music", 1, 9000, 8000), 2))
cases.append(("music-st-96k-q4", sig("music", 2, 30000, 96000), 4))
cases.append(("music-6ch-48k-q3", sig("music", 6, 20000, 48000), 3))
cases.append(("square-st-32k-q5", sig("square", 2, 20000, 32000), 5))
cases.append(("loud-st-44k-q8", sig("loud", 2, 20000, 44100), 8))
cases.append(("silence-st-44k", sig("silence", 2, 10000, 44100), 3))
for n in (1, 100, 1024, 1025, 3000):
cases.append(("len-%d" % n, sig("music", 2, n, 44100), 3))
ctx.emit("vorbis_enc_sigs", {n: {"rate": r, "channels": c, "frames": len(x) // c, "data": A.f32le(x)} for n, (x, r, c) in sigs.items()})
outs = A.encode_luau_many(ctx, "audio/vorbis", [(c[1], "{ quality = %d }" % c[2]) for c in cases], "vorbis_enc_sigs")
emitted = []
for (name, sigmod, q), data in zip(cases, outs):
samples, rate, ch = sigs[sigmod]
frames = len(samples) // ch
info = A.tool(ctx, "vorbis-tools", ["sh", "-c", "ogginfo {in} 2>&1; true"], data, "ogg").decode(errors="replace")
problems = "\n".join(l for l in info.split("\n") if re.search(r"(?i)warning|error", l))
raw = A.tool(ctx, "vorbis-tools", ["oggdec", "-Q", "-R", "-o", "{out}", "{in}"], data, "ogg", "raw")
od = [int.from_bytes(raw[i:i + 2], "little", signed=True) / 32768 for i in range(0, len(raw) - 1, 2)]
osnr, _ = A.snr(samples, od, ch) # (oggdec -R keeps the Vorbis channel order)
ffe = A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}", "-f", "null", "-"], data, "ogg").decode(errors="replace")
_, fch, ff = A.ffdecode(ctx, data, ext="ogg")
if ch == 6: # ffmpeg reorders to WAVE order (FL FR FC LFE RL RR); Vorbis order is FL FC FR RL RR LFE
ff = reorder(ff)
fsnr, _ = A.snr(samples, ff, ch) if fch == ch else (-99.0, 0)
e = {"name": name, "sig": sigmod, "quality": q, "rate": rate, "channels": ch, "frames": frames, "ogginfo": problems,
"oggdecFrames": len(od) // ch, "oggdecSnr": osnr, "ffFrames": len(ff) // max(1, fch), "ffSnr": fsnr,
"ffErrors": ffe, "kbps": len(data) * 8 / (frames / rate) / 1000, "data": data}
emitted.append(e)
print(" vorbis_enc: %-22s %7.1f kbps oggdec %d/%d frames %.1f dB ffmpeg %.1f dB%s" % (name, e["kbps"], e["oggdecFrames"], frames,
osnr, fsnr, (" OGGINFO " + problems[:80]) if problems else ""))
ctx.emit("vorbis_enc", emitted)