--!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/audio/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/audio/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