--!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 Pcm = require("@formats/codecs/Pcm") local VorbisComment = require("@formats/codecs/VorbisComment") 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 fields = VorbisComment.fields(tags) put(w, #fields, 32) for _, s in fields do 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 -- the input is in WAVE channel order; input channel c goes to Vorbis channel order[c] local order = Pcm.WAVE_FROM_VORBIS[ch] or {} if #order ~= ch then order = table.create(ch, 0) for c = 1, ch do order[c] = c end 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[order[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