Files
rosetta/src/Rosetta/codecs/audio/Aac/Decode.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

970 lines
24 KiB
Luau

--!strict
--!native
--!optimize 2
-- codecs/audio/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4).
-- Written from the standard; no third-party code. PNS uses FFmpeg's LCG so the noise matches it.
local Mdct = require("@rosetta/codecs/audio/Mdct")
local Tables = require("@rosetta/codecs/audio/Aac/Tables")
local Sbr = require("@rosetta/codecs/audio/Aac/Sbr")
local readu32, byteswap, lshift, rshift, band = buffer.readu32, bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band
local floor, sqrt, abs = math.floor, math.sqrt, math.abs
local Decode = {}
local ONLY_LONG, LONG_START, EIGHT_SHORT, LONG_STOP = 0, 1, 2, 3
local ZERO_HCB, ESC_HCB, NOISE_HCB, INTENSITY_HCB2, INTENSITY_HCB = 0, 11, 13, 14, 15
-- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields)
local B: buffer = buffer.create(16)
local BP = 0
local BL = 0
local OVER = false
local function getBits(n: number): number
local p = BP
BP = p + n
if p > BL then
OVER = true
return 0
end
return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n)
end
local function peekBits(n: number): number
local p = BP
if p > BL then
return 0
end
return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n)
end
local function getLong(n: number): number
if n > 24 then
local hi = getBits(n - 16)
return hi * 65536 + getBits(16)
end
return getBits(n)
end
local PEEK = 10
type Book = { tab: { number }, map: { [number]: number }, maxLen: number }
local function book(codes: { number }, bits: { number }): Book
local tab = table.create(2 ^ PEEK, 0)
local map = {}
local maxLen = 0
for s = 1, #codes do
local c, l = codes[s], bits[s]
maxLen = math.max(maxLen, l)
if l <= PEEK then
local shift = 2 ^ (PEEK - l)
for k = 0, shift - 1 do
tab[c * shift + k + 1] = (s - 1) * 32 + l
end
else
map[l * 2 ^ 20 + c] = s - 1
end
end
return { tab = tab, map = map, maxLen = maxLen }
end
local SF_BOOK = book(Tables.SF_CODES, Tables.SF_BITS)
local SPEC_BOOK: { Book } = {}
for i = 1, 11 do
SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i])
end
local function huff(bk: Book): number
local e = bk.tab[peekBits(PEEK) + 1]
if e > 0 then
BP += band(e, 31)
return rshift(e, 5)
end
local code = getBits(PEEK)
local map = bk.map
for l = PEEK + 1, bk.maxLen do
code = code * 2 + getBits(1)
local s = map[l * 1048576 + code]
if s then
return s
end
end
return -1
end
local DIM = { 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2 }
local UNSIGNED = { false, false, true, true, false, false, true, true, true, true, true }
local MOD = { 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17 }
local OFF = { 1, 1, 0, 0, 4, 4, 0, 0, 0, 0, 0 }
-- UNPACK[cb][4 sym + k]: a codeword's dim values (k = 1 .. dim), first value most significant
local UNPACK: { { number } } = {}
for cb = 1, 11 do
local dim, mod, off = DIM[cb], MOD[cb], OFF[cb]
local t = table.create(mod ^ dim * 4, 0)
for sym = 0, mod ^ dim - 1 do
local v = sym
for k = dim, 1, -1 do
t[sym * 4 + k] = v % mod - off
v = v // mod
end
end
UNPACK[cb] = t
end
-- |q|^(4/3)
local POW43 = table.create(8192, 0)
for i = 0, 8191 do
POW43[i + 1] = i ^ (4 / 3)
end
local SINE_LONG = Mdct.window("sine", 2048) :: { number }
local KBD_LONG = Mdct.window("kbd", 2048, 4) :: { number }
local SINE_SHORT = Mdct.window("sine", 256) :: { number }
local KBD_SHORT = Mdct.window("kbd", 256, 6) :: { number }
local PLAN_LONG = Mdct.new(2048) :: Mdct.Plan
local PLAN_SHORT = Mdct.new(256) :: Mdct.Plan
export type Channel = {
spec: { number },
overlap: { number },
prevShape: number,
windowSequence: number,
windowShape: number,
maxSfb: number,
numGroups: number,
groupLen: { number },
bandType: { number },
sf: { number },
tnsFilters: { { { number } } },
}
export type State = {
sfIndex: number,
channels: number,
frameLength: number,
ch: { Channel },
pcm: { number },
random: number,
time: { number },
frame: { number },
short: { number },
onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?,
extensions: number,
sbr: boolean,
map: { number }?,
-- SBR output (codecs/audio/Aac/Sbr): sbrRate = the output rate when on, psOut = a mono stream output as stereo
sbrOn: boolean,
sbrRate: number,
psOut: boolean,
sbrElems: { any },
elemKind: { number },
elemFirst: { number },
core: { { number } },
}
local function newChannel(): Channel
return {
spec = table.create(1024, 0),
overlap = table.create(1024, 0),
prevShape = 0,
windowSequence = 0,
windowShape = 0,
maxSfb = 0,
numGroups = 1,
groupLen = { 1, 0, 0, 0, 0, 0, 0, 0 },
bandType = table.create(8 * 64, 0),
sf = table.create(8 * 64, 0),
tnsFilters = {},
}
end
Decode.newChannel = newChannel
local function icsInfo(st: State, c: Channel): string?
if getBits(1) ~= 0 then
return "reserved ics bit set"
end
c.windowSequence = getBits(2)
c.windowShape = getBits(1)
if c.windowSequence == EIGHT_SHORT then
c.maxSfb = getBits(4)
local grouping = getBits(7)
local ng = 1
local gl = c.groupLen
gl[1] = 1
for w = 1, 7 do
if band(grouping, 2 ^ (6 - (w - 1))) ~= 0 then
gl[ng] += 1
else
ng += 1
gl[ng] = 1
end
end
c.numGroups = ng
if c.maxSfb > Tables.NUM_SWB_SHORT[st.sfIndex + 1] then
return "max_sfb over the short band count"
end
else
c.maxSfb = getBits(6)
c.numGroups = 1
c.groupLen[1] = 1
if getBits(1) ~= 0 then
return "prediction (AAC Main / LTP) is not supported"
end
if c.maxSfb > Tables.NUM_SWB_LONG[st.sfIndex + 1] then
return "max_sfb over the long band count"
end
end
return nil
end
local function sectionData(c: Channel): string?
local long = c.windowSequence ~= EIGHT_SHORT
local bits = if long then 5 else 3
local esc = 2 ^ bits - 1
local maxSfb = c.maxSfb
local bt = c.bandType
for g = 0, c.numGroups - 1 do
local k = 0
while k < maxSfb do
local cb = getBits(4)
if cb == 12 then
return "reserved codebook 12"
end
local len = 0
while true do
local inc = getBits(bits)
len += inc
if inc ~= esc then
break
end
if OVER then
return "section data runs past the end"
end
end
if k + len > maxSfb then
return "section runs past max_sfb"
end
for s = k, k + len - 1 do
bt[g * maxSfb + s + 1] = cb
end
k += len
if OVER then
return "section data runs past the end"
end
end
end
return nil
end
local function scaleFactors(c: Channel, globalGain: number): string?
local sfv = globalGain
local noise = globalGain - 90
local is = 0
local firstNoise = true
local maxSfb = c.maxSfb
local bt, sf = c.bandType, c.sf
for g = 0, c.numGroups - 1 do
for s = 0, maxSfb - 1 do
local i = g * maxSfb + s + 1
local cb = bt[i]
if cb == ZERO_HCB then
sf[i] = 0
elseif cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
local d = huff(SF_BOOK)
if d < 0 then
return "bad scalefactor code"
end
is += d - 60
sf[i] = math.clamp(is, -155, 100)
elseif cb == NOISE_HCB then
if firstNoise then
noise += getBits(9) - 256
firstNoise = false
else
local d = huff(SF_BOOK)
if d < 0 then
return "bad scalefactor code"
end
noise += d - 60
end
sf[i] = math.clamp(noise, -100, 155)
else
local d = huff(SF_BOOK)
if d < 0 then
return "bad scalefactor code"
end
sfv += d - 60
if sfv < 0 or sfv > 255 then
return "scalefactor out of range"
end
sf[i] = sfv
end
end
end
return nil
end
local function tnsData(st: State, c: Channel): string?
local short = c.windowSequence == EIGHT_SHORT
local nw = if short then 8 else 1
local filters = {}
for w = 1, nw do
local list = {}
local nFilt = getBits(if short then 1 else 2)
if nFilt > 0 then
local coefRes = getBits(1)
for _ = 1, nFilt do
local length = getBits(if short then 4 else 6)
local order = getBits(if short then 3 else 5)
local f = { length, order, 0 }
if order > (if short then 7 else 12) then
return "TNS order too high"
end
if order > 0 then
f[3] = getBits(1)
local compress = getBits(1)
local resBits = coefRes + 3
local nb = resBits - compress
local iq = ((2 ^ (resBits - 1)) - 0.5) / (math.pi / 2)
local iqm = ((2 ^ (resBits - 1)) + 0.5) / (math.pi / 2)
local tmp = table.create(order, 0)
for k = 1, order do
local v = getBits(nb)
if v >= 2 ^ (nb - 1) then
v -= 2 ^ nb
end
tmp[k] = math.sin(v / (if v >= 0 then iq else iqm))
end
-- parcor -> LPC
local a = table.create(order + 1, 0)
local b = table.create(order + 1, 0)
a[1] = 1
for m = 1, order do
for i = 1, m - 1 do
b[i + 1] = a[i + 1] + tmp[m] * a[m - i + 1]
end
for i = 1, m - 1 do
a[i + 1] = b[i + 1]
end
a[m + 1] = tmp[m]
end
for k = 1, order do
f[3 + k] = a[k + 1]
end
end
table.insert(list, f)
end
end
filters[w] = list
end
c.tnsFilters = filters
local _ = st
return nil
end
local function applyTns(st: State, c: Channel)
local short = c.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
local numSwb = if short then Tables.NUM_SWB_SHORT[st.sfIndex + 1] else Tables.NUM_SWB_LONG[st.sfIndex + 1]
local maxBands = if short then Tables.TNS_MAX_BANDS_SHORT[st.sfIndex + 1] else Tables.TNS_MAX_BANDS_LONG[st.sfIndex + 1]
local mmm = math.min(maxBands, c.maxSfb)
if mmm == 0 then
return
end
local spec = c.spec
for w, list in c.tnsFilters do
local bottom = numSwb
for _, f in list do
local top = bottom
bottom = math.max(0, top - f[1])
local order = f[2]
if order > 0 then
local start = swb[math.min(bottom, mmm) + 1]
local stop = swb[math.min(top, mmm) + 1]
local size = stop - start
if size > 0 then
local inc = 1
local p = (w - 1) * 128 + start + 1
if f[3] == 1 then
inc = -1
p = (w - 1) * 128 + stop
end
for m = 0, size - 1 do
local y = spec[p]
local lim = if m < order then m else order
for i = 1, lim do
y -= spec[p - i * inc] * f[3 + i]
end
spec[p] = y
p += inc
end
end
end
end
end
end
local function spectralData(st: State, c: Channel, pulses: { number }?): string?
local short = c.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
local spec = c.spec
for i = 1, 1024 do
spec[i] = 0
end
local maxSfb = c.maxSfb
local bt, sf = c.bandType, c.sf
local win = 0
for g = 0, c.numGroups - 1 do
local glen = c.groupLen[g + 1]
for s = 0, maxSfb - 1 do
local idx = g * maxSfb + s + 1
local cb = bt[idx]
local lo, hi = swb[s + 1], swb[s + 2]
local width = hi - lo
if cb == ZERO_HCB or cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
-- zeros (intensity bands are filled from the other channel later)
continue
elseif cb == NOISE_HCB then
local scale = 2 ^ (0.25 * sf[idx])
for w = 0, glen - 1 do
local base = (win + w) * 128 + lo
local energy = 0
local r = st.random
for k = 1, width do
r = (r * 1664525 + 1013904223) % 4294967296
local v = if r >= 2147483648 then r - 4294967296 else r
spec[base + k] = v
energy += v * v
end
st.random = r
local m = if energy > 0 then scale / sqrt(energy) else 0
for k = 1, width do
spec[base + k] *= m
end
end
continue
end
local bk = SPEC_BOOK[cb]
local dim, uns, unpack = DIM[cb], UNSIGNED[cb], UNPACK[cb]
local gain = 2 ^ (0.25 * (sf[idx] - 100))
for w = 0, glen - 1 do
local base = (win + w) * 128 + lo
local k = 0
while k < width do
local sym = huff(bk)
if sym < 0 then
return "bad spectral code"
end
-- unpack the symbol into dim values (first value most significant)
local u = sym * 4
local vals1, vals2, vals3, vals4 = unpack[u + 1], unpack[u + 2], unpack[u + 3], unpack[u + 4]
if uns then
if vals1 ~= 0 and getBits(1) == 1 then
vals1 = -vals1
end
if vals2 ~= 0 and getBits(1) == 1 then
vals2 = -vals2
end
if dim == 4 then
if vals3 ~= 0 and getBits(1) == 1 then
vals3 = -vals3
end
if vals4 ~= 0 and getBits(1) == 1 then
vals4 = -vals4
end
end
if cb == ESC_HCB then
for e = 1, 2 do
local v = if e == 1 then vals1 else vals2
if v == 16 or v == -16 then
local n = 0
while getBits(1) == 1 do
n += 1
if n > 8 or OVER then
return "bad escape"
end
end
local esc = 2 ^ (n + 4) + getBits(n + 4)
if v < 0 then
esc = -esc
end
if e == 1 then
vals1 = esc
else
vals2 = esc
end
end
end
end
end
local p = base + k + 1
spec[p] = vals1
spec[p + 1] = vals2
if dim == 4 then
spec[p + 2] = vals3
spec[p + 3] = vals4
end
k += dim
end
if OVER then
return "spectral data runs past the end"
end
end
-- dequantise (pulses are added to the quantised values first: long windows only, applied below)
if not pulses then
for w = 0, glen - 1 do
local base = (win + w) * 128 + lo
for k = 1, width do
local q = spec[base + k]
if q ~= 0 then
local aq = if q < 0 then -q else q
local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain
spec[base + k] = if q < 0 then -v else v
end
end
end
end
end
win += glen
end
if pulses then
for i = 1, #pulses, 2 do
local pos = pulses[i] + 1
if pos <= 1024 then
local q = spec[pos]
spec[pos] = if q > 0 then q + pulses[i + 1] else q - pulses[i + 1]
end
end
for s = 0, maxSfb - 1 do
local idx = s + 1
local cb = bt[idx]
if cb ~= ZERO_HCB and cb < NOISE_HCB then
local gain = 2 ^ (0.25 * (sf[idx] - 100))
for k = swb[s + 1] + 1, swb[s + 2] do
local q = spec[k]
if q ~= 0 then
local aq = if q < 0 then -q else q
local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain
spec[k] = if q < 0 then -v else v
end
end
end
end
end
return nil
end
-- individual_channel_stream
local function ics(st: State, c: Channel, commonWindow: boolean): string?
local globalGain = getBits(8)
if not commonWindow then
local e = icsInfo(st, c)
if e then
return e
end
end
local e = sectionData(c)
if e then
return e
end
e = scaleFactors(c, globalGain)
if e then
return e
end
local pulses: { number }? = nil
if getBits(1) == 1 then
if c.windowSequence == EIGHT_SHORT then
return "pulse data in a short window"
end
local n = getBits(2) + 1
local startSfb = getBits(6)
if startSfb >= Tables.NUM_SWB_LONG[st.sfIndex + 1] then
return "bad pulse start band"
end
local pos = Tables.SWB_LONG[st.sfIndex + 1][startSfb + 1]
local list = {}
for _ = 1, n do
pos += getBits(5)
table.insert(list, pos)
table.insert(list, getBits(4))
end
pulses = list
end
c.tnsFilters = {}
if getBits(1) == 1 then
e = tnsData(st, c)
if e then
return e
end
end
if getBits(1) == 1 then
return "gain control (AAC SSR) is not supported"
end
if OVER then
return "channel stream runs past the end"
end
return spectralData(st, c, pulses)
end
local function msStereo(st: State, l: Channel, r: Channel, mask: { number })
local short = l.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
local maxSfb = l.maxSfb
local a, b = l.spec, r.spec
local win = 0
for g = 0, l.numGroups - 1 do
local glen = l.groupLen[g + 1]
for s = 0, maxSfb - 1 do
local idx = g * maxSfb + s + 1
if mask[idx] == 1 and l.bandType[idx] < NOISE_HCB and r.bandType[idx] < NOISE_HCB then
for w = 0, glen - 1 do
local base = (win + w) * 128
for k = base + swb[s + 1] + 1, base + swb[s + 2] do
local m, sd = a[k], b[k]
a[k], b[k] = m + sd, m - sd
end
end
end
end
win += glen
end
end
local function intensity(st: State, l: Channel, r: Channel, mask: { number }, msPresent: number)
local short = r.windowSequence == EIGHT_SHORT
local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1]
local maxSfb = r.maxSfb
local a, b = l.spec, r.spec
local win = 0
for g = 0, r.numGroups - 1 do
local glen = r.groupLen[g + 1]
for s = 0, maxSfb - 1 do
local idx = g * maxSfb + s + 1
local cb = r.bandType[idx]
if cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then
local sign = if cb == INTENSITY_HCB then 1 else -1
if msPresent ~= 0 and mask[idx] == 1 then
sign = -sign
end
local scale = sign * 0.5 ^ (0.25 * r.sf[idx])
for w = 0, glen - 1 do
local base = (win + w) * 128
for k = base + swb[s + 1] + 1, base + swb[s + 2] do
b[k] = a[k] * scale
end
end
end
end
win += glen
end
end
local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number)
local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape
local spec, overlap = c.spec, c.overlap
local frame = st.frame
local scale = 1 / 32768
if seq == EIGHT_SHORT then
for i = 1, 2048 do
frame[i] = 0
end
local tmp = st.short
local rise0 = if prev == 1 then KBD_SHORT else SINE_SHORT
local wcur = if shape == 1 then KBD_SHORT else SINE_SHORT
for w = 0, 7 do
Mdct.inverse(PLAN_SHORT, spec, w * 128 + 1, 1, tmp, 1, 2 / 256)
local rise = if w == 0 then rise0 else wcur
local base = 448 + w * 128
for n = 1, 128 do
frame[base + n] += tmp[n] * rise[n]
frame[base + 128 + n] += tmp[128 + n] * wcur[128 + n]
end
end
else
local t = st.time
Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048)
if seq ~= LONG_STOP and seq ~= LONG_START then
-- ONLY_LONG: window, overlap-add and output in one pass
local rise = if prev == 1 then KBD_LONG else SINE_LONG
local fall = if shape == 1 then KBD_LONG else SINE_LONG
local p = offset
for n = 1, 1024 do
out[p] = (t[n] * rise[n] + overlap[n]) * scale
overlap[n] = t[1024 + n] * fall[1024 + n]
p += stride
end
c.prevShape = shape
return
end
if seq == LONG_STOP then
local rise = if prev == 1 then KBD_SHORT else SINE_SHORT
for n = 1, 448 do
frame[n] = 0
end
for n = 1, 128 do
frame[448 + n] = t[448 + n] * rise[n]
end
for n = 577, 1024 do
frame[n] = t[n]
end
else
local rise = if prev == 1 then KBD_LONG else SINE_LONG
for n = 1, 1024 do
frame[n] = t[n] * rise[n]
end
end
if seq == LONG_START then
local fall = if shape == 1 then KBD_SHORT else SINE_SHORT
for n = 1025, 1472 do
frame[n] = t[n]
end
for n = 1, 128 do
frame[1472 + n] = t[1472 + n] * fall[128 + n]
end
for n = 1601, 2048 do
frame[n] = 0
end
else
local fall = if shape == 1 then KBD_LONG else SINE_LONG
for n = 1025, 2048 do
frame[n] = t[n] * fall[n]
end
end
end
local p = offset
for n = 1, 1024 do
out[p] = (frame[n] + overlap[n]) * scale
overlap[n] = frame[1024 + n]
p += stride
end
c.prevShape = shape
end
local function sbrElement(st: State, i: number, nch: number): any
local e = st.sbrElems[i]
if not e or e.nch ~= nch then
e = Sbr.element(nch, st.sbrRate, st.psOut and nch == 1)
st.sbrElems[i] = e
end
return e
end
local OFFS = { 0, 0 }
local CORE2 = { {}, {} }
-- every element through SBR at the doubled rate (2048 samples per channel); the PS output of a mono element is stereo
local function sbrOutput(st: State, order: { Channel }, nElem: number): number
local n = #order
local ps = st.psOut and n == 1
local stride = if ps then 2 else n
local map = st.map
local core = st.core
for i, c in order do
local t = core[i]
if not t then
t = table.create(1024, 0)
core[i] = t
end
filterbank(st, c, t, 1, 1)
end
for ei = 1, nElem do
local first = st.elemFirst[ei]
local nch = if st.elemKind[ei] == 1 then 2 else 1
local e = sbrElement(st, ei, nch)
for j = 1, nch do
local idx = first + j - 1
OFFS[j] = if map and map[idx] then map[idx] else idx
CORE2[j] = core[idx]
end
if ps then
OFFS[2] = 2
end
Sbr.process(e, CORE2, st.pcm, stride, OFFS)
end
return stride
end
function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?)
if buffer.len(B) < len + 16 then
B = buffer.create(len + 256)
end
buffer.copy(B, 0, buf, off, len)
buffer.fill(B, len, 0, 16)
BP, BL, OVER = 0, len * 8, false
local chans = st.ch
local nextCh = 1
local order: { Channel } = {}
local lastElement = -1
local nElem = 0
local elemKind, elemFirst = st.elemKind, st.elemFirst
while true do
if BP + 3 > BL then
break -- tolerate a missing END
end
local id = getBits(3)
if id == 7 then
break
end
if id == 0 or id == 3 then -- SCE / LFE
getBits(4)
local c = chans[nextCh]
if not c then
c = newChannel()
chans[nextCh] = c
end
local e = ics(st, c, false)
if e then
return nil, e
end
applyTns(st, c)
table.insert(order, c)
nElem += 1
elemKind[nElem], elemFirst[nElem] = id, #order
nextCh += 1
lastElement = id
elseif id == 1 then -- CPE
getBits(4)
local l, r = chans[nextCh], chans[nextCh + 1]
if not l then
l = newChannel()
chans[nextCh] = l
end
if not r then
r = newChannel()
chans[nextCh + 1] = r
end
local common = getBits(1) == 1
local msPresent = 0
local mask = table.create(8 * 64, 0)
if common then
local e = icsInfo(st, l)
if e then
return nil, e
end
r.windowSequence, r.windowShape, r.maxSfb, r.numGroups = l.windowSequence, l.windowShape, l.maxSfb, l.numGroups
for i = 1, 8 do
r.groupLen[i] = l.groupLen[i]
end
msPresent = getBits(2)
if msPresent == 1 then
for i = 1, l.numGroups * l.maxSfb do
mask[i] = getBits(1)
end
elseif msPresent == 2 then
for i = 1, l.numGroups * l.maxSfb do
mask[i] = 1
end
elseif msPresent == 3 then
return nil, "reserved ms_mask_present"
end
end
local e = ics(st, l, common)
if e then
return nil, e
end
e = ics(st, r, common)
if e then
return nil, e
end
if common and msPresent ~= 0 then
msStereo(st, l, r, mask)
end
if common then
intensity(st, l, r, mask, msPresent)
end
applyTns(st, l)
applyTns(st, r)
table.insert(order, l)
table.insert(order, r)
nElem += 1
elemKind[nElem], elemFirst[nElem] = id, #order - 1
nextCh += 2
lastElement = id
elseif id == 2 then
return nil, "coupling channel elements are not supported"
elseif id == 4 then -- DSE
getBits(4)
local align = getBits(1)
local count = getBits(8)
if count == 255 then
count += getBits(8)
end
if align == 1 then
BP = (BP + 7) // 8 * 8
end
BP += count * 8
elseif id == 5 then -- PCE: skipped here (parsed from the configuration)
return nil, "program config element inside the stream is not supported"
elseif id == 6 then -- FIL
local count = getBits(4)
if count == 15 then
count += getBits(8) - 1
end
if count > 0 then
local start = BP
local kind = getBits(4)
if kind == 13 or kind == 14 then -- EXT_SBR_DATA / EXT_SBR_DATA_CRC
st.sbr = true
if st.sbrOn and nElem > 0 and lastElement ~= 3 then
Sbr.extension(sbrElement(st, nElem, if lastElement == 1 then 2 else 1), B, start + 4, count * 8 - 4, kind == 14)
end
end
st.extensions += 1
local hook = st.onExtension
if hook then
hook(kind, lastElement, B, start, count * 8)
end
BP = start + count * 8
end
end
if OVER or BP > BL then
return nil, "frame runs past the end"
end
if nextCh > 9 then
return nil, "more than 8 channels"
end
end
local n = #order
if n == 0 then
return 0, nil
end
if st.sbrOn then
return sbrOutput(st, order, nElem), nil
end
local pcm = st.pcm
local map = st.map
for i, c in order do
local o = if map and map[i] then map[i] else i
filterbank(st, c, pcm, n, o)
end
return n, nil
end
function Decode.state(sfIndex: number): State
return {
sfIndex = sfIndex,
channels = 0,
frameLength = 1024,
ch = {},
pcm = table.create(2048 * 8, 0),
random = 0x1f2e3d4c,
time = table.create(2048, 0),
frame = table.create(2048, 0),
short = table.create(256, 0),
onExtension = nil,
extensions = 0,
sbr = false,
map = nil,
sbrOn = false,
sbrRate = 0,
psOut = false,
sbrElems = {},
elemKind = {},
elemFirst = {},
core = {},
}
end
local _ = abs
local _2 = floor
return Decode