Files
rosetta/src/Rosetta/codecs/audio/Aac/Sbr.luau
T
4DBug 686a1fbf86 codecs/audio/Aac: HE-AAC (SBR) and HE-AACv2 (baseline PS) decoding
New shared modules under codecs/audio/Aac: Sbr (bitstream, band tables,
delta decoding), SbrBits, SbrQmf (32-band analysis / 64-band synthesis QMF
through DCT-IV), SbrHf (HF generation and adjustment), Ps (baseline PS),
SbrTables (ISO tables, from syom 0.8.1, MIT). Explicit signalling enables
SBR at construction; implicit SBR / PS is found by Decoder:probe /
Aac.probeFrames. audio/aac and audio/m4a report the output rate and take
opts.sbr = false for the core only; m4a scales iTunSMPB by the media tick.

Outside the folder: containers/AudioWrap writes an AAC-LC ADTS header for
HE-AAC AudioSpecificConfigs (the decoder finds SBR in the stream); the api's
default openAudio hook forwards opts.sbr.
2026-11-02 00:21:13 -06:00

1070 lines
26 KiB
Luau

--!strict
--!native
--!optimize 2
-- codecs/audio/Aac/Sbr: Spectral Band Replication bitstream and control (ISO/IEC 14496-3 4.6.18, syntax 4.4.2.8).
-- Ported from syom 0.8.1 src/engine/sbr_*.rs (MIT, licenses/syom-LICENSE.txt). Supports: sbr_header, sbr_data for
-- SCE / CPE (coupled and independent), envelope / noise delta decoding and dequantisation, frequency band tables,
-- patches and limiter bands; ps_data is handed to codecs/audio/Aac/Ps. Not supported: down-sampled SBR, 960 frames.
local SbrTables = require("@rosetta/codecs/audio/Aac/SbrTables")
local SbrBits = require("@rosetta/codecs/audio/Aac/SbrBits")
local SbrQmf = require("@rosetta/codecs/audio/Aac/SbrQmf")
local SbrHf = require("@rosetta/codecs/audio/Aac/SbrHf")
local Ps = require("@rosetta/codecs/audio/Aac/Ps")
local floor, log = math.floor, math.log
local bits, huff, codebook = SbrBits.bits, SbrBits.huff, SbrBits.codebook
local Sbr = {}
local T_ENV15 = codebook(SbrTables.T_ENV15)
local F_ENV15 = codebook(SbrTables.F_ENV15)
local T_BAL15 = codebook(SbrTables.T_BAL15)
local F_BAL15 = codebook(SbrTables.F_BAL15)
local T_ENV30 = codebook(SbrTables.T_ENV30)
local F_ENV30 = codebook(SbrTables.F_ENV30)
local T_BAL30 = codebook(SbrTables.T_BAL30)
local F_BAL30 = codebook(SbrTables.F_BAL30)
local T_NOISE30 = codebook(SbrTables.T_NOISE30)
local T_NOISEBAL30 = codebook(SbrTables.T_NOISEBAL30)
-- ------------------------------------------------------------------------------------------------ band tables
local function nint(x: number): number
return floor(x + 0.5)
end
-- 4.6.18.3.2 Table 4.82 startMin offsets by the SBR rate
local OFFSETS = {
{ -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7 },
{ -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13 },
{ -5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16 },
{ -6, -4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16 },
{ -4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20 },
{ -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20, 24 },
}
local function sortInts(t: { number }, n: number)
for i = 2, n do
local v = t[i]
local j = i - 1
while j >= 1 and t[j] > v do
t[j + 1] = t[j]
j -= 1
end
t[j + 1] = v
end
end
-- vDk(i) = NINT(lo * r^((i + 1) / n)) - NINT(lo * r^(i / n)), sorted
local function warpSteps(lo: number, hi: number, n: number): { number }
local r = hi / lo
local d = table.create(n, 0)
for i = 0, n - 1 do
d[i + 1] = nint(lo * r ^ ((i + 1) / n)) - nint(lo * r ^ (i / n))
end
sortInts(d, n)
return d
end
-- 4.6.18.3.2: fMaster from k0, k2, bs_freq_scale, bs_alter_scale (nil when invalid)
local function masterTable(k0: number, k2: number, freqScale: number, alterScale: boolean): { number }?
if k2 <= k0 then
return nil
end
local f = { k0 }
if freqScale == 0 then
local dk = if alterScale then 2 else 1
local nb = if alterScale then 2 * nint((k2 - k0) / 4) else 2 * ((k2 - k0) // 2)
if nb <= 0 then
return nil
end
local d = table.create(nb, dk)
local diff = k2 - (k0 + nb * dk)
local k = if diff < 0 then 1 else nb
local incr = if diff < 0 then 1 else -1
local guard = 0
while diff ~= 0 do
if k < 1 or k > nb or guard > 64 then
return nil
end
d[k] -= incr
k += incr
diff += incr
guard += 1
end
for i = 1, nb do
if d[i] <= 0 then
return nil
end
f[i + 1] = f[i] + d[i]
end
return f
end
local bandsPerOct = ({ 12, 10, 8 })[freqScale] or 8
local warp = if alterScale then 1.3 else 1
local twoRegions = k2 / k0 > 2.2449
local k1 = if twoRegions then 2 * k0 else k2
local nb0 = 2 * nint(bandsPerOct * log(k1 / k0) / (2 * log(2)))
if nb0 <= 0 or nb0 > 64 then
return nil
end
local d0 = warpSteps(k0, k1, nb0)
local maxD0 = 0
for i = 1, nb0 do
if d0[i] <= 0 then
return nil
end
maxD0 = math.max(maxD0, d0[i])
f[i + 1] = f[i] + d0[i]
end
if not twoRegions then
return f
end
local nb1 = 2 * nint(bandsPerOct * log(k2 / k1) / (2 * log(2) * warp))
if nb1 <= 0 or nb1 > 64 then
return nil
end
local d1 = warpSteps(k1, k2, nb1)
if d1[1] < maxD0 then
local change = math.min(maxD0 - d1[1], (d1[nb1] - d1[1]) // 2)
d1[1] += change
d1[nb1] -= change
sortInts(d1, nb1)
end
local base = #f
for i = 1, nb1 do
if d1[i] <= 0 then
return nil
end
f[base + i] = f[base + i - 1] + d1[i]
end
return f
end
-- 4.6.18.6.3 patch construction: patchNum / patchStart per patch (nil when invalid)
local function patches(e: any, k0: number): boolean
local master, kx, m = e.fMaster, e.kx, e.M
local nMaster = #master - 1
local msb, usb = k0, kx
local goal = nint(2.048e6 / e.fs)
local k = nMaster
if goal < kx + m then
k = 0
local i = 0
while master[i + 1] < goal do
i += 1
k = i
end
end
local num, start = {}, {}
local sb = 0
local guard = 0
repeat
guard += 1
if guard > 64 then
return false
end
local j = k + 1
local odd = 0
repeat
j -= 1
if j < 0 then
return false
end
sb = master[j + 1]
odd = (sb - 2 + k0) % 2
until sb <= k0 - 1 + msb - odd
local n = math.max(sb - usb, 0)
if n > 0 then
local s = k0 - odd - n
if s < 0 or #num >= 5 or s + n > 32 then
return false
end
table.insert(num, n)
table.insert(start, s)
usb, msb = sb, sb
else
msb = kx
end
if master[k + 1] - sb < 3 then
k = nMaster
end
until sb == kx + m
if #num > 1 and num[#num] < 3 then
table.remove(num)
table.remove(start)
end
if #num == 0 then
return false
end
e.patchNum, e.patchStart = num, start
return true
end
local LIM_BANDS = { 1.2, 2, 3 }
local function limiterTable(e: any, limBands: number)
local low = e.fLow
local n = #low
if limBands == 0 then
e.fLim = { low[1], low[n] }
return
end
local per = LIM_BANDS[limBands]
local borders = { e.kx }
for i, p in e.patchNum do
borders[i + 1] = borders[i] + p
end
local function isBorder(v: number): boolean
for _, b in borders do
if b == v then
return true
end
end
return false
end
local t = table.clone(low)
for i = 2, #borders - 1 do
table.insert(t, borders[i])
end
sortInts(t, #t)
local k = 2
while k <= #t do
local a, b = t[k - 1], t[k]
if a < 1 then
k += 1
elseif log(b / a) / log(2) * per < 0.49 then
if b == a or not isBorder(b) then
table.remove(t, k)
elseif not isBorder(a) then
table.remove(t, k - 1)
else
k += 1
end
else
k += 1
end
end
e.fLim = t
end
local function rateRow(fs: number): { number }
if fs < 22050 then
return OFFSETS[1]
elseif fs < 24000 then
return OFFSETS[2]
elseif fs < 32000 then
return OFFSETS[3]
elseif fs < 44100 then
return OFFSETS[4]
elseif fs <= 64000 then
return OFFSETS[5]
end
return OFFSETS[6]
end
-- band index of QMF subband k in table f (0-based), or -1
local function bandOf(f: { number }, k: number): number
for i = 1, #f - 1 do
if f[i] <= k and k < f[i + 1] then
return i - 1
end
end
return -1
end
-- 4.6.18.3.2 - 4.6.18.3.6: every table derived from the header; false when the header is unusable
local function deriveTables(e: any, h: any): boolean
local fs = e.fs
local cMin = if fs < 32000 then 3000 elseif fs < 64000 then 4000 else 5000
local sMin = if fs < 32000 then 6000 elseif fs < 64000 then 8000 else 10000
local startMin = nint(cMin * 128 / fs)
local stopMin = nint(sMin * 128 / fs)
local k0 = startMin + rateRow(fs)[h.startFreq + 1]
local k2: number
if h.stopFreq == 14 then
k2 = math.min(2 * k0, 64)
elseif h.stopFreq == 15 then
k2 = math.min(3 * k0, 64)
else
local d = table.create(13, 0)
local r = 64 / stopMin
for p = 0, 12 do
d[p + 1] = nint(stopMin * r ^ ((p + 1) / 13)) - nint(stopMin * r ^ (p / 13))
end
sortInts(d, 13)
k2 = stopMin
for p = 1, h.stopFreq do
k2 += d[p]
end
k2 = math.min(k2, 64)
end
if k0 < 1 or k0 >= 32 or k2 <= k0 or k2 - k0 > 48 then
return false
end
local master = masterTable(k0, k2, h.freqScale, h.alterScale)
if not master then
return false
end
local nMaster = #master - 1
if h.xover >= nMaster then
return false
end
local high = {}
for i = h.xover, nMaster do
table.insert(high, master[i + 1])
end
local nHigh = #high - 1
local kx = high[1]
local m = high[nHigh + 1] - kx
if kx > 32 or kx + m > 64 or m <= 0 or nHigh > 48 then
return false
end
local nLow = nHigh // 2 + nHigh % 2
local low = { high[1] }
local parity = nHigh % 2
for k = 1, nLow do
low[k + 1] = high[2 * k - parity + 1]
end
local nQ = 1
if h.noiseBands > 0 then
nQ = math.max(1, nint(h.noiseBands * log(low[nLow + 1] / kx) / log(2)))
end
if nQ > 5 then
return false
end
local noise = { low[1] }
local ip = 0
for k = 1, nQ do
ip += (nLow - ip) // (nQ + 1 - k)
local v = low[ip + 1]
if not v then
return false
end
noise[k + 1] = v
end
e.fMaster, e.fHigh, e.fLow, e.fNoise = master, high, low, noise
e.kx, e.M, e.nHigh, e.nLow, e.nQ = kx, m, nHigh, nLow, nQ
if not patches(e, k0) then
return false
end
limiterTable(e, h.limiterBands)
-- per QMF subband k = kx + m: envelope / noise / limiter band (0-based)
local mapH, mapL, mapQ = table.create(m, 0), table.create(m, 0), table.create(m, 0)
for i = 0, m - 1 do
mapH[i + 1] = bandOf(high, kx + i)
mapL[i + 1] = bandOf(low, kx + i)
mapQ[i + 1] = bandOf(noise, kx + i)
if mapH[i + 1] < 0 or mapL[i + 1] < 0 or mapQ[i + 1] < 0 then
return false
end
end
e.mapH, e.mapL, e.mapQ = mapH, mapL, mapQ
-- the noise band of each patched target subband, for the chirp factor
return true
end
-- ------------------------------------------------------------------------------------------------ sbr_data
local function grid(c: any): boolean
local class = bits(2)
local nEnv = 1
local fr = c.freqRes
local rel0, rel1 = c.rel0, c.rel1
local nRel0, nRel1 = 0, 0
local vb0, vb1, ptr = 0, 0, 0
c.ampOverride = false
if class == 0 then
nEnv = 2 ^ bits(2)
if nEnv > 4 then
return false
end
local r = bits(1)
for i = 1, nEnv do
fr[i] = r
end
if nEnv == 1 then
c.ampOverride = true
end
nRel0 = nEnv - 1
elseif class == 1 then
vb1 = bits(2)
nRel1 = bits(2)
nEnv = nRel1 + 1
for i = 1, nRel1 do
rel1[i] = 2 * bits(2) + 2
end
ptr = bits(if nEnv + 1 <= 2 then 1 elseif nEnv + 1 <= 4 then 2 else 3)
for i = nEnv, 1, -1 do
fr[i] = bits(1)
end
elseif class == 2 then
vb0 = bits(2)
nRel0 = bits(2)
nEnv = nRel0 + 1
for i = 1, nRel0 do
rel0[i] = 2 * bits(2) + 2
end
ptr = bits(if nEnv + 1 <= 2 then 1 elseif nEnv + 1 <= 4 then 2 else 3)
for i = 1, nEnv do
fr[i] = bits(1)
end
else
vb0 = bits(2)
vb1 = bits(2)
nRel0 = bits(2)
nRel1 = bits(2)
nEnv = nRel0 + nRel1 + 1
if nEnv > 5 then
return false
end
for i = 1, nRel0 do
rel0[i] = 2 * bits(2) + 2
end
for i = 1, nRel1 do
rel1[i] = 2 * bits(2) + 2
end
ptr = bits(if nEnv + 1 <= 2 then 1 elseif nEnv + 1 <= 4 then 2 elseif nEnv + 1 <= 8 then 3 else 3)
for i = 1, nEnv do
fr[i] = bits(1)
end
end
c.class, c.nEnv, c.nNoise, c.pointer = class, nEnv, if nEnv > 1 then 2 else 1, ptr
-- 4.6.18.3.3 time borders (in time slots)
local tE, tQ = c.tE, c.tQ
local lead = if class >= 2 then vb0 else 0
local trail = if class == 1 or class == 3 then vb1 + 16 else 16
tE[1] = lead
tE[nEnv + 1] = trail
if class == 0 then
local step = (2 * 16 + nEnv) // (2 * nEnv)
for l = 1, nEnv - 1 do
tE[l + 1] = lead + l * step
end
else
local b = lead
for l = 1, nRel0 do
b += rel0[l]
tE[l + 1] = b
end
b = trail
for l = 1, nRel1 do
b -= rel1[l]
tE[nEnv + 1 - l] = b
end
end
for l = 1, nEnv do
if tE[l + 1] <= tE[l] then
return false
end
end
if nEnv == 1 then
tQ[1], tQ[2] = tE[1], tE[2]
else
local mid
if class == 0 then
mid = nEnv // 2
elseif class == 2 then
mid = if ptr == 0 then 1 elseif ptr == 1 then nEnv - 1 else ptr - 1
else
mid = if ptr <= 1 then nEnv - 1 else nEnv + 1 - ptr
end
if mid <= 0 or mid >= nEnv then
return false
end
tQ[1], tQ[2], tQ[3] = tE[1], tE[mid + 1], tE[nEnv + 1]
end
local lA = -1
if class == 1 or class == 3 then
if ptr > 0 then
lA = nEnv + 1 - ptr
end
elseif class == 2 then
if ptr > 1 then
lA = ptr - 1
end
end
c.lA = lA
return true
end
local function dtdf(c: any)
for i = 1, c.nEnv do
c.dfEnv[i] = bits(1)
end
for i = 1, c.nNoise do
c.dfNoise[i] = bits(1)
end
end
local function invf(c: any, nQ: number)
for i = 1, nQ do
c.invf[i] = bits(2)
end
end
-- sbr_envelope: raw deltas into c.envRaw[(l - 1) * 64 + i]
local function envelope(e: any, c: any, bal: boolean): boolean
local amp = e.ampRes == 1 and not c.ampOverride
c.amp = amp
local tb, fb
if bal then
tb, fb = if amp then T_BAL30 else T_BAL15, if amp then F_BAL30 else F_BAL15
else
tb, fb = if amp then T_ENV30 else T_ENV15, if amp then F_ENV30 else F_ENV15
end
local startBits = if bal then (if amp then 5 else 6) else (if amp then 6 else 7)
local raw = c.envRaw
for l = 1, c.nEnv do
local n = if c.freqRes[l] == 1 then e.nHigh else e.nLow
local base = (l - 1) * 64
if c.dfEnv[l] == 0 then
raw[base + 1] = bits(startBits)
for i = 2, n do
local v = huff(fb)
if not v then
return false
end
raw[base + i] = v
end
else
for i = 1, n do
local v = huff(tb)
if not v then
return false
end
raw[base + i] = v
end
end
end
return true
end
local function noise(e: any, c: any, bal: boolean): boolean
local tb = if bal then T_NOISEBAL30 else T_NOISE30
local fb = if bal then F_BAL30 else F_ENV30
local raw = c.noiseRaw
for l = 1, c.nNoise do
local base = (l - 1) * 8
if c.dfNoise[l] == 0 then
raw[base + 1] = bits(5)
for i = 2, e.nQ do
local v = huff(fb)
if not v then
return false
end
raw[base + i] = v
end
else
for i = 1, e.nQ do
local v = huff(tb)
if not v then
return false
end
raw[base + i] = v
end
end
end
return true
end
local function harmonics(e: any, c: any)
local h = c.harm
if bits(1) == 1 then
c.hasHarm = true
for i = 1, e.nHigh do
h[i] = bits(1)
end
else
c.hasHarm = false
end
end
-- sbr_extension: ps_data (bs_extension_id 2) is recorded for the PS tool
local function extended(e: any)
e.psPos, e.psBits = -1, 0
if bits(1) == 0 then
return
end
local cnt = bits(4)
if cnt == 15 then
cnt += bits(8)
end
local left = cnt * 8
while left > 7 do
local id = bits(2)
left -= 2
if id == 2 and e.psPos < 0 then
e.psPos, e.psBits = SbrBits.pos(), left
end
SbrBits.skip(left)
left = 0
end
SbrBits.skip(left)
end
local function newChannel(): any
return {
freqRes = table.create(6, 0),
rel0 = table.create(4, 0),
rel1 = table.create(4, 0),
tE = table.create(6, 0),
tQ = table.create(3, 0),
dfEnv = table.create(5, 0),
dfNoise = table.create(2, 0),
invf = table.create(5, 0),
envRaw = table.create(5 * 64, 0),
noiseRaw = table.create(16, 0),
harm = table.create(64, 0),
hasHarm = false,
class = 0,
nEnv = 0,
nNoise = 0,
pointer = 0,
lA = -1,
amp = false,
ampOverride = false,
-- decoded (persist across frames for the time-direction deltas)
env = table.create(5 * 64, 0),
envLast = table.create(64, 0),
envLastRes = -1,
noiseQ = table.create(16, 0),
noiseLast = table.create(8, 0),
noiseLastValid = false,
eOrig = table.create(5 * 64, 0),
qOrig = table.create(16, 0),
}
end
Sbr.newChannel = newChannel
local HEADER_KEYS = { "startFreq", "stopFreq", "xover", "freqScale", "alterScale", "noiseBands", "limiterBands" }
-- sbr_extension_data (4.4.2.8 Table 4.62) at bit position pos (after the extension_type nibble); true when parsed
function Sbr.parse(e: any, buf: buffer, pos: number, count: number, crc: boolean): boolean
SbrBits.start(buf, pos, count)
if crc then
bits(10)
end
local h = e.hdrNext
if bits(1) == 1 then
e.ampRes = bits(1)
h.startFreq = bits(4)
h.stopFreq = bits(4)
h.xover = bits(3)
bits(2)
local x1, x2 = bits(1), bits(1)
if x1 == 1 then
h.freqScale = bits(2)
h.alterScale = bits(1) == 1
h.noiseBands = bits(2)
else
h.freqScale, h.alterScale, h.noiseBands = 2, true, 2
end
if x2 == 1 then
h.limiterBands = bits(2)
h.limiterGains = bits(2)
h.interpolFreq = bits(1) == 1
h.smoothingMode = bits(1) == 1
else
h.limiterBands, h.limiterGains, h.interpolFreq, h.smoothingMode = 2, 2, true, true
end
if SbrBits.over() then
return false
end
local hc = e.hdr
local changed = not e.tablesOk
for _, k in HEADER_KEYS do
if hc[k] ~= h[k] then
changed = true
hc[k] = h[k]
end
end
hc.limiterGains, hc.interpolFreq, hc.smoothingMode = h.limiterGains, h.interpolFreq, h.smoothingMode
if changed then
e.tablesOk = deriveTables(e, hc)
e.reset = true
end
end
if not e.tablesOk then
return false
end
local nQ = e.nQ
if e.nch == 1 then
local c = e.ch[1]
if bits(1) == 1 then
bits(4)
end
if not grid(c) then
return false
end
dtdf(c)
invf(c, nQ)
if not envelope(e, c, false) or not noise(e, c, false) then
return false
end
harmonics(e, c)
e.coupling = false
else
local a, b = e.ch[1], e.ch[2]
if bits(1) == 1 then
bits(8)
end
local coupling = bits(1) == 1
e.coupling = coupling
if coupling then
if not grid(a) then
return false
end
for _, k in { "class", "nEnv", "nNoise", "pointer", "lA", "ampOverride" } do
b[k] = a[k]
end
for i = 1, 6 do
b.freqRes[i], b.tE[i] = a.freqRes[i], a.tE[i]
end
for i = 1, 3 do
b.tQ[i] = a.tQ[i]
end
dtdf(a)
dtdf(b)
invf(a, nQ)
for i = 1, nQ do
b.invf[i] = a.invf[i]
end
if not envelope(e, a, false) or not noise(e, a, false) then
return false
end
if not envelope(e, b, true) or not noise(e, b, true) then
return false
end
else
if not grid(a) or not grid(b) then
return false
end
dtdf(a)
dtdf(b)
invf(a, nQ)
invf(b, nQ)
if not envelope(e, a, false) or not envelope(e, b, false) then
return false
end
if not noise(e, a, false) or not noise(e, b, false) then
return false
end
end
harmonics(e, a)
harmonics(e, b)
end
extended(e)
return not SbrBits.over()
end
-- ------------------------------------------------------------------------------------------------ decoding
-- 4.6.18.3.5 delta decoding of one channel's envelopes and noise floors
local function decodeChannel(e: any, c: any, bal: boolean)
local delta = if bal then 2 else 1
local raw, env, last = c.envRaw, c.env, c.envLast
local fHigh, fLow = e.fHigh, e.fLow
local lastRes = c.envLastRes
for l = 1, c.nEnv do
local res = c.freqRes[l]
local n = if res == 1 then e.nHigh else e.nLow
local base = (l - 1) * 64
if c.dfEnv[l] == 0 then
local acc = 0
for i = 1, n do
acc += raw[base + i] * delta
env[base + i] = acc
end
else
local prevBase, prev = (l - 2) * 64, env
local prevRes = if l > 1 then c.freqRes[l - 1] else lastRes
if l == 1 then
prevBase, prev = 0, last
end
for i = 1, n do
local g = 0
if prevRes == res then
g = prev[prevBase + i] or 0
elseif prevRes >= 0 then
local idx
if res == 1 then
-- high band -> the low band containing it
local target = fHigh[i]
idx = 1
while fLow[idx + 1] and fLow[idx + 1] <= target do
idx += 1
end
if idx > e.nLow then
idx = e.nLow
end
else
local target = fLow[i]
idx = 1
for j = 1, e.nHigh + 1 do
if fHigh[j] == target then
idx = j
break
end
end
end
g = prev[prevBase + idx] or 0
end
env[base + i] = g + raw[base + i] * delta
end
end
end
local lb = (c.nEnv - 1) * 64
for i = 1, 64 do
last[i] = env[lb + i]
end
c.envLastRes = c.freqRes[c.nEnv]
local nq = e.nQ
local nr, q, ql = c.noiseRaw, c.noiseQ, c.noiseLast
for l = 1, c.nNoise do
local base = (l - 1) * 8
if c.dfNoise[l] == 0 then
local acc = 0
for i = 1, nq do
acc += nr[base + i] * delta
q[base + i] = acc
end
else
for i = 1, nq do
local g = if l > 1 then q[base - 8 + i] elseif c.noiseLastValid then ql[i] else 0
q[base + i] = g + nr[base + i] * delta
end
end
end
local qb = (c.nNoise - 1) * 8
for i = 1, 8 do
ql[i] = q[qb + i]
end
c.noiseLastValid = true
end
-- 4.6.18.3.5 dequantisation (E_orig, Q_orig), single or coupled
local function dequant(e: any)
local a, b = e.ch[1], e.ch[2]
if e.coupling and b then
local div = if a.amp then 1 else 2
local pan = if a.amp then 12 else 24
for l = 1, a.nEnv do
local n = if a.freqRes[l] == 1 then e.nHigh else e.nLow
local base = (l - 1) * 64
for i = 1, n do
local avg2 = 64 * 2 ^ (a.env[base + i] / div + 1)
local ratio = 2 ^ ((pan - b.env[base + i]) / div)
a.eOrig[base + i] = avg2 / (1 + ratio)
b.eOrig[base + i] = avg2 / (1 + 1 / ratio)
end
end
for l = 1, a.nNoise do
local base = (l - 1) * 8
for i = 1, e.nQ do
local avg2 = 2 ^ (6 - a.noiseQ[base + i] + 1)
local ratio = 2 ^ (12 - b.noiseQ[base + i])
a.qOrig[base + i] = avg2 / (1 + ratio)
b.qOrig[base + i] = avg2 / (1 + 1 / ratio)
end
end
return
end
for _, c in e.ch do
local div = if c.amp then 1 else 2
for l = 1, c.nEnv do
local n = if c.freqRes[l] == 1 then e.nHigh else e.nLow
local base = (l - 1) * 64
for i = 1, n do
c.eOrig[base + i] = 64 * 2 ^ (c.env[base + i] / div)
end
end
for l = 1, c.nNoise do
local base = (l - 1) * 8
for i = 1, e.nQ do
c.qOrig[base + i] = 2 ^ (6 - c.noiseQ[base + i])
end
end
end
end
-- after a successful parse: deltas, dequantisation
function Sbr.decode(e: any)
if e.reset then
for _, c in e.ch do
c.envLastRes = -1
c.noiseLastValid = false
end
end
for i, c in e.ch do
decodeChannel(e, c, e.coupling and i == 2)
end
dequant(e)
end
-- an SBR element: nch 1 (SCE / LFE) or 2 (CPE), fs = the SBR (output) rate; ps: a mono element output as stereo
function Sbr.element(nch: number, fs: number, ps: boolean?): any
local ch = {}
for i = 1, nch do
local c = newChannel()
c.q = SbrQmf.state()
c.h = SbrHf.state()
ch[i] = c
end
return {
nch = nch,
fs = fs,
ch = ch,
hdr = {},
hdrNext = {},
ampRes = 0,
tablesOk = false,
reset = true,
coupling = false,
present = false,
psPos = -1,
psBits = 0,
psOut = nch == 1 and ps == true,
ps = if nch == 1 and ps then Ps.state() else nil,
psq = if nch == 1 and ps then SbrQmf.state() else nil,
psHad = false,
kx = 32,
M = 0,
nHigh = 0,
nLow = 0,
nQ = 0,
}
end
-- a seek: filterbank, HF and delta-coding state restart; the header and its tables are kept
function Sbr.restart(e: any)
for _, c in e.ch do
SbrQmf.reset(c.q)
c.h = SbrHf.state()
c.envLastRes = -1
c.noiseLastValid = false
end
if e.ps then
local old = e.ps
local ps = Ps.state()
for _, k in { "haveConfig", "enableIid", "iidMode", "enableIcc", "iccMode", "enableExt" } do
ps[k] = old[k]
end
e.ps = ps
SbrQmf.reset(e.psq)
end
e.reset = true
e.present = false
end
-- an EXT_SBR_DATA(_CRC) payload for this element (bit position after the extension_type nibble)
function Sbr.extension(e: any, buf: buffer, pos: number, count: number, crc: boolean)
e.present = Sbr.parse(e, buf, pos, count, crc)
e.psHad = false
if e.present and e.ps and e.psPos >= 0 then
local stop = math.min(e.psPos + e.psBits, pos + count)
e.psHad = Ps.parse(e.ps, buf, e.psPos, stop - e.psPos)
end
end
local SR = table.create(64, 0)
local SI = table.create(64, 0)
local XR = table.create(38 * 64, 0)
local XI = table.create(38 * 64, 0)
local LR = table.create(32 * 64, 0)
local LI = table.create(32 * 64, 0)
local RR = table.create(32 * 64, 0)
local RI = table.create(32 * 64, 0)
-- 4.6.18.5 the QMF matrix of slot l (0 .. 31): X_low below kx, Y from kx to kx + M (the previous frame's Y up to lTemp)
local function slot(e: any, c: any, ok: boolean, lTemp: number, l: number, xr: { number }, xi: { number }, xo: number)
local q, h = c.q, c.h
local XLr, XLi = q.XLr, q.XLi
local kx, m = 32, 0
local yr, yi, col = h.Yr, h.Yi, l + 2
if l < lTemp then
kx, m, yr, yi, col = h.kxPrev, h.mPrev, h.Pr, h.Pi, l + 34
elseif ok then
kx, m = e.kx, e.M
end
local lo = (l + 2) * 32
for k = 1, kx do
xr[xo + k], xi[xo + k] = XLr[lo + k], XLi[lo + k]
end
local yo = col * 64
for k = kx + 1, kx + m do
xr[xo + k], xi[xo + k] = yr[yo + k], yi[yo + k]
end
for k = kx + m + 1, 64 do
xr[xo + k], xi[xo + k] = 0, 0
end
end
-- one frame of an element: core[ci] = 1024 core samples -> 2048 samples per output channel at out[offs[i] + j * stride]
function Sbr.process(e: any, core: { { number } }, out: { number }, stride: number, offs: { number })
local ok = e.present
if ok then
Sbr.decode(e)
end
for ci = 1, e.nch do
local c = e.ch[ci]
local q, h = c.q, c.h
SbrQmf.analysis(q, core[ci], 1, 1)
if ok then
SbrHf.generate(e, c, h, q.XLr, q.XLi)
SbrHf.adjust(e, c, e.hdr, h)
end
local lTemp = math.max(2 * h.tEPrev - 32, 0)
local o = offs[ci]
if e.psOut and e.ps then
for l = 0, 31 do
slot(e, c, ok, lTemp, l, XR, XI, l * 64)
end
local XLr, XLi = q.XLr, q.XLi
for l = 32, 37 do
local lo, xo = (l + 2) * 32, l * 64
for k = 1, 3 do
XR[xo + k], XI[xo + k] = XLr[lo + k], XLi[lo + k]
end
end
local ps = e.ps
if ps.haveConfig then
Ps.process(ps, ok and e.psHad, XR, XI, LR, LI, RR, RI)
local o2 = offs[2]
for l = 0, 31 do
SbrQmf.synthesis(q, l, LR, LI, l * 64, out, o + l * 64 * stride, stride)
SbrQmf.synthesis(e.psq, l, RR, RI, l * 64, out, o2 + l * 64 * stride, stride)
end
SbrQmf.endFrame(e.psq)
else
local o2 = offs[2]
for l = 0, 31 do
SbrQmf.synthesis(q, l, XR, XI, l * 64, out, o + l * 64 * stride, stride)
local p, p2 = o + l * 64 * stride, o2 + l * 64 * stride
for _ = 1, 64 do
out[p2] = out[p]
p += stride
p2 += stride
end
end
end
else
for l = 0, 31 do
slot(e, c, ok, lTemp, l, SR, SI, 0)
SbrQmf.synthesis(q, l, SR, SI, 0, out, o + l * 64 * stride, stride)
end
end
SbrQmf.endFrame(q)
h.Yr, h.Pr = h.Pr, h.Yr
h.Yi, h.Pi = h.Pi, h.Yi
if ok then
h.tEPrev, h.kxPrev, h.mPrev = c.tE[c.nEnv + 1], e.kx, e.M
else
h.tEPrev, h.kxPrev, h.mPrev = 16, 32, 0
end
end
if ok then
e.reset = false
end
e.present = false
end
return Sbr