Files
rosetta/src/Formats/audio/opus/Celt.luau
T
4DBug 7169f2cc2c ws-cleanup: codecs/Resample, codecs/RangeCoder; Opus / MP3 / MP2 encoders resample through it
- codecs/Resample (new): Kaiser-windowed sinc resampler, polyphase (exact phases when to / gcd <= 4096, else 4096
  interpolated phases), quality low / medium / high (8 / 16 / 32 zero crossings), streaming (new / process / flush),
  whole buffer (Resample.buffer) and a codecs/Pcm source wrapper (Resample.source). tests/codecs/resample: SNR
  87 dB (44.1 -> 48 kHz, medium) .. 108 dB (high), alias rejection, streamed = whole, identity.
- audio/opus/Encode: input through codecs/Pcm (Pcm.source + collect) and codecs/Resample instead of its private
  resampler and Decoder loop; tags through codecs/VorbisComment.
- audio/mp3 encode: rates the layer cannot hold are resampled to the next rate up (opts.sampleRate picks one,
  opts.resampleQuality); was Err.ARG "no resampling".
- codecs/RangeCoder/{Decoder,Encoder}: the RFC 6716 range coder moved out of audio/opus (same code, no speed change).
- audio/opus/Mdct stays private: routing CELT through codecs/Mdct measured 2-3x slower CELT decoding and different
  output bits (documented in its header).
- (this commit also carries the Opus side of the tags / channel order consistency: codecs/VorbisComment for OpusTags,
  meta.source.comments, mapping family 1 decoded to WAVE channel order with Pcm.reorder / Pcm.WAVE_FROM_VORBIS.)
2026-10-31 10:50:56 -05:00

1865 lines
52 KiB
Luau

--!strict
--!native
--!optimize 2
-- audio/opus/Celt: CELT decoder (RFC 6716 section 4.3), a port of the libopus float decoder: celt/celt_decoder.c, bands.c, vq.c,
-- cwrs.c, rate.c, quant_bands.c, laplace.c, celt.c (comb filter). Only the standard 48 kHz / 960-sample mode is
-- needed by Opus. Packet loss concealment is the noise-based variant only (no pitch PLC).
--
-- Arrays are Luau tables of numbers. All normalised-band data (X, Y, the folding memory `norm` and the scratch
-- copies) lives in one table W, and the "pointers" of the C code are 0-based offsets into it.
local RD = require("@formats/codecs/RangeCoder/Decoder")
local Mdct = require("@formats/audio/opus/Mdct")
local T = require("@formats/audio/opus/CeltTables")
local Celt = {}
local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift
local min, max, sqrt, floor, exp, cos = math.min, math.max, math.sqrt, math.floor, math.exp, math.cos
local decBitLogp, decIcdf, decBits, decUint = RD.bitLogp, RD.icdf, RD.bits, RD.uint
local decDecode, decDecodeBin, decUpdate = RD.decode, RD.decodeBin, RD.update
local tell, tellFrac = RD.tell, RD.tellFrac
local NB_EBANDS = 21
local EFF_EBANDS = 21
local OVERLAP = 120
local SHORT_MDCT = 120
local MAX_LM = 3
local DECODE_BUFFER_SIZE = 2048
local BITRES = 3
local MAX_FINE_BITS = 8
local FINE_OFFSET = 21
local QTHETA_OFFSET = 4
local QTHETA_OFFSET_TWOPHASE = 16
local SPREAD_AGGRESSIVE = 3
local PREEMPH = 0.85000610
local COMBFILTER_MINPERIOD = 15
local FRAME_NONE, FRAME_NORMAL, FRAME_PLC_NOISE = 0, 1, 2
-- eBands (1-based: EB[i + 1] is eBands[i])
local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 }
local ALLOC = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0,
110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0,
118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0,
126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0,
134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1,
144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1,
152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1,
162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1,
172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20,
200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104,
}
local NB_ALLOC_VECTORS = 11
local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 }
local LOGN = T.logN400
local CACHE_INDEX = T.cache_index50
local CACHE_BITS = T.cache_bits50
local CACHE_CAPS = T.cache_caps50
local E_PROB = T.e_prob_model
local E_MEANS = {
6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500,
4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500,
3.750000, 3.750000, 3.750000, 3.750000, 3.750000,
}
local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 }
local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 }
local BETA_INTRA = 4915 / 32768
local TF_SELECT = { -- [LM][4 * isTransient + 2 * tf_select + flag]
{ 0, -1, 0, -1, 0, -1, 0, -1 },
{ 0, -1, 0, -2, 1, 0, 1, -1 },
{ 0, -2, 0, -3, 2, 0, 1, -1 },
{ 0, -2, 0, -3, 3, 0, 1, -1 },
}
local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 }
local SPREAD_ICDF = { 25, 23, 2, 0 }
local TAPSET_ICDF = { 2, 1, 0 }
local SMALL_ENERGY_ICDF = { 2, 1, 0 }
local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 }
local ORDERY = { 1, 0, 3, 0, 2, 1, 7, 0, 4, 3, 6, 1, 5, 2, 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5 }
local BIT_INTERLEAVE = { 0, 1, 1, 1, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3 }
local BIT_DEINTERLEAVE = { 0x00, 0x03, 0x0C, 0x0F, 0x30, 0x33, 0x3C, 0x3F, 0xC0, 0xC3, 0xCC, 0xCF, 0xF0, 0xF3, 0xFC, 0xFF }
local COMB_GAINS = {
{ 0.3066406250, 0.2170410156, 0.1296386719 },
{ 0.4638671875, 0.2680664062, 0.0 },
{ 0.7998046875, 0.1000976562, 0.0 },
}
local WINDOW = table.create(OVERLAP, 0)
for i = 0, OVERLAP - 1 do
local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP)
WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s)
end
Celt.window = WINDOW
-- PVQ codebook sizes U(n, k) (cwrs.c), flat: U[n * UK + k + 1], n, k in 0 .. 176
local UK = 177
local U = table.create(UK * UK, 0)
U[1] = 1
for n = 1, UK - 1 do
for k = 1, UK - 1 do
U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k]
end
end
-- shared workspace (decoding is not re-entrant)
local NORM_BASE = 1920
local W = table.create(4096, 0)
local TMP = table.create(256, 0)
local IY = table.create(256, 0)
local FREQ = table.create(960, 0)
local FREQ2 = table.create(960, 0)
local COLLAPSE = table.create(42, 0)
local TF_RES = table.create(21, 0)
local CAP = table.create(21, 0)
local OFFSETS = table.create(21, 0)
local FINE_QUANT = table.create(21, 0)
local PULSES = table.create(21, 0)
local FINE_PRIORITY = table.create(21, 0)
local BITS1 = table.create(21, 0)
local BITS2 = table.create(21, 0)
local THRESH = table.create(21, 0)
local TRIM_OFFSET = table.create(21, 0)
local function imin(a: number, b: number): number
return if a < b then a else b
end
local function imax(a: number, b: number): number
return if a > b then a else b
end
-- C integer division (truncates toward zero)
local function tdiv(a: number, b: number): number
local q = a / b
return if q >= 0 then floor(q) else -floor(-q)
end
local function exp2(x: number): number
return exp(0.6931471805599453094 * x)
end
local function lcg(seed: number): number
return (1664525 * seed + 1013904223) % 4294967296
end
local function signed32(x: number): number
return if x >= 2147483648 then x - 4294967296 else x
end
local function fracMul16(a: number, b: number): number
return (16384 + a * b) // 32768
end
local function bitexactCos(x: number): number
local tmp = (4096 + x * x) // 8192
local x2 = tmp
x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2)))))
return 1 + x2
end
local function bitexactLog2tan(isin: number, icos: number): number
local lc = RD.ilog(icos)
local ls = RD.ilog(isin)
icos = icos * 2 ^ (15 - lc)
isin = isin * 2 ^ (15 - ls)
return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932)
end
-- ---------------------------------------------------------------------------------------------------------------
-- energy (quant_bands.c, laplace.c)
local function laplaceDecode(dec: RD.Dec, fs: number, decay: number): number
local val = 0
local fm = decDecodeBin(dec, 15)
local fl = 0
if fm >= fs then
val += 1
fl = fs
fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 + 1
while fs > 1 and fm >= fl + 2 * fs do
fs *= 2
fl += fs
fs = ((fs - 2) * decay) // 32768
fs += 1
val += 1
end
if fs <= 1 then
local di = rshift(fm - fl, 1)
val += di
fl += 2 * di
end
if fm < fl + fs then
val = -val
else
fl += fs
end
end
decUpdate(dec, fl, imin(fl + fs, 32768), 32768)
return val
end
local function unquantCoarseEnergy(st: any, start: number, endb: number, intra: boolean, dec: RD.Dec, C: number, LM: number)
local oldE = st.oldBandE
local probBase = LM * 84 + (if intra then 42 else 0) -- e_prob_model[LM][intra], 0-based
local coef, beta
if intra then
coef = 0
beta = BETA_INTRA
else
beta = BETA_COEF[LM + 1]
coef = PRED_COEF[LM + 1]
end
local prev0, prev1 = 0, 0
local budget = dec.storage * 8
for i = start, endb - 1 do
for c = 0, C - 1 do
local t = tell(dec)
local qi
if budget - t >= 15 then
local pi = 2 * imin(i, 20)
qi = laplaceDecode(dec, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64)
elseif budget - t >= 2 then
qi = decIcdf(dec, SMALL_ENERGY_ICDF, 1, 2)
qi = if band(qi, 1) ~= 0 then -rshift(qi, 1) - 1 else rshift(qi, 1)
elseif budget - t >= 1 then
qi = if decBitLogp(dec, 1) then -1 else 0
else
qi = -1
end
local q = qi
local k = i + c * NB_EBANDS + 1
local e = max(-9, oldE[k])
local prev = if c == 0 then prev0 else prev1
oldE[k] = coef * e + prev + q
prev = prev + q - beta * q
if c == 0 then
prev0 = prev
else
prev1 = prev
end
end
end
end
local function unquantFineEnergy(st: any, start: number, endb: number, fineQuant: { number }, dec: RD.Dec, C: number)
local oldE = st.oldBandE
for i = start, endb - 1 do
local extra = fineQuant[i + 1]
if extra <= 0 then
continue
end
if tell(dec) + C * extra > dec.storage * 8 then
continue
end
for c = 0, C - 1 do
local q2 = decBits(dec, extra)
local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5
oldE[i + c * NB_EBANDS + 1] += offset
end
end
end
local function unquantEnergyFinalise(st: any, start: number, endb: number, fineQuant: { number }, finePriority: { number }, bitsLeft: number, dec: RD.Dec, C: number)
local oldE = st.oldBandE
for prio = 0, 1 do
local i = start
while i < endb and bitsLeft >= C do
if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then
i += 1
continue
end
for c = 0, C - 1 do
local q2 = decBits(dec, 1)
local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384)
oldE[i + c * NB_EBANDS + 1] += offset
bitsLeft -= 1
end
i += 1
end
end
end
-- ---------------------------------------------------------------------------------------------------------------
-- bit allocation (rate.c)
local function bits2pulses(bandI: number, LM: number, bits: number): number
local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1]
local lo, hi = 0, CACHE_BITS[base + 1]
bits -= 1
for _ = 1, 6 do
local mid = rshift(lo + hi + 1, 1)
if CACHE_BITS[base + mid + 1] >= bits then
hi = mid
else
lo = mid
end
end
local loBits = if lo == 0 then -1 else CACHE_BITS[base + lo + 1]
if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then
return lo
end
return hi
end
local function pulses2bits(bandI: number, LM: number, pulses: number): number
if pulses == 0 then
return 0
end
local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1]
return CACHE_BITS[base + pulses + 1] + 1
end
local function getPulses(i: number): number
if i < 8 then
return i
end
return lshift(8 + band(i, 7), rshift(i, 3) - 1)
end
-- clt_compute_allocation + interp_bits2pulses (decoder side). Returns codedBands, balance, intensity, dualStereo.
local function computeAllocation(start: number, endb: number, offsets: { number }, cap: { number }, allocTrim: number,
total: number, pulses: { number }, ebits: { number }, finePriority: { number }, C: number, LM: number, ec: RD.Dec)
total = imax(total, 0)
local len = NB_EBANDS
local skipStart = start
local skipRsv = if total >= 8 then 8 else 0
total -= skipRsv
local intensityRsv, dualStereoRsv = 0, 0
if C == 2 then
intensityRsv = LOG2_FRAC_TABLE[endb - start + 1]
if intensityRsv > total then
intensityRsv = 0
else
total -= intensityRsv
dualStereoRsv = if total >= 8 then 8 else 0
total -= dualStereoRsv
end
end
local bits1, bits2, thresh, trimOffset = BITS1, BITS2, THRESH, TRIM_OFFSET
for j = start, endb - 1 do
local w = EB[j + 2] - EB[j + 1]
thresh[j + 1] = imax(C * 8, (3 * w * 2 ^ LM * 8) // 16)
trimOffset[j + 1] = (C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) // 64
if w * 2 ^ LM == 1 then
trimOffset[j + 1] -= C * 8
end
end
local lo, hi = 1, NB_ALLOC_VECTORS - 1
repeat
local done = false
local psum = 0
local mid = rshift(lo + hi, 1)
for j = endb - 1, start, -1 do
local N = EB[j + 2] - EB[j + 1]
local bitsj = (C * N * ALLOC[mid * len + j + 1] * 2 ^ LM) // 4
if bitsj > 0 then
bitsj = imax(0, bitsj + trimOffset[j + 1])
end
bitsj += offsets[j + 1]
if bitsj >= thresh[j + 1] or done then
done = true
psum += imin(bitsj, cap[j + 1])
elseif bitsj >= C * 8 then
psum += C * 8
end
end
if psum > total then
hi = mid - 1
else
lo = mid + 1
end
until lo > hi
hi = lo
lo -= 1
for j = start, endb - 1 do
local N = EB[j + 2] - EB[j + 1]
local bits1j = (C * N * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4
local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * N * ALLOC[hi * len + j + 1] * 2 ^ LM) // 4
if bits1j > 0 then
bits1j = imax(0, bits1j + trimOffset[j + 1])
end
if bits2j > 0 then
bits2j = imax(0, bits2j + trimOffset[j + 1])
end
if lo > 0 then
bits1j += offsets[j + 1]
end
bits2j += offsets[j + 1]
if offsets[j + 1] > 0 then
skipStart = j
end
bits2j = imax(0, bits2j - bits1j)
bits1[j + 1] = bits1j
bits2[j + 1] = bits2j
end
-- interp_bits2pulses
local bits = pulses
local allocFloor = C * 8
local stereo = if C > 1 then 1 else 0
local logM = LM * 8
lo, hi = 0, 64
for _ = 1, 6 do
local mid = rshift(lo + hi, 1)
local psum = 0
local done = false
for j = endb - 1, start, -1 do
local tmp = bits1[j + 1] + (mid * bits2[j + 1]) // 64
if tmp >= thresh[j + 1] or done then
done = true
psum += imin(tmp, cap[j + 1])
elseif tmp >= allocFloor then
psum += allocFloor
end
end
if psum > total then
hi = mid
else
lo = mid
end
end
local psum = 0
local done = false
for j = endb - 1, start, -1 do
local tmp = bits1[j + 1] + (lo * bits2[j + 1]) // 64
if tmp < thresh[j + 1] and not done then
if tmp >= allocFloor then
tmp = allocFloor
else
tmp = 0
end
else
done = true
end
tmp = imin(tmp, cap[j + 1])
bits[j + 1] = tmp
psum += tmp
end
local codedBands = endb
while true do
local j = codedBands - 1
if j <= skipStart then
total += skipRsv
break
end
local left = total - psum
local percoeff = left // (EB[codedBands + 1] - EB[start + 1])
left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff
local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0)
local bandWidth = EB[codedBands + 1] - EB[j + 1]
local bandBits = bits[j + 1] + percoeff * bandWidth + rem
if bandBits >= imax(thresh[j + 1], allocFloor + 8) then
if decBitLogp(ec, 1) then
break
end
psum += 8
bandBits -= 8
end
psum -= bits[j + 1] + intensityRsv
if intensityRsv > 0 then
intensityRsv = LOG2_FRAC_TABLE[j - start + 1]
end
psum += intensityRsv
if bandBits >= allocFloor then
psum += allocFloor
bits[j + 1] = allocFloor
else
bits[j + 1] = 0
end
codedBands -= 1
end
local intensity, dualStereo = 0, false
if intensityRsv > 0 then
intensity = start + decUint(ec, codedBands + 1 - start)
end
if intensity <= start then
total += dualStereoRsv
dualStereoRsv = 0
end
if dualStereoRsv > 0 then
dualStereo = decBitLogp(ec, 1)
end
local left = total - psum
local percoeff = left // (EB[codedBands + 1] - EB[start + 1])
left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff
for j = start, codedBands - 1 do
bits[j + 1] += percoeff * (EB[j + 2] - EB[j + 1])
end
for j = start, codedBands - 1 do
local tmp = imin(left, EB[j + 2] - EB[j + 1])
bits[j + 1] += tmp
left -= tmp
end
local balance = 0
local j = start
while j < codedBands do
local N0 = EB[j + 2] - EB[j + 1]
local N = N0 * 2 ^ LM
local bit = bits[j + 1] + balance
local excess
if N > 1 then
excess = imax(bit - cap[j + 1], 0)
bits[j + 1] = bit - excess
local den = C * N + (if C == 2 and N > 2 and not dualStereo and j < intensity then 1 else 0)
local NClogN = den * (LOGN[j + 1] + logM)
local offset = (NClogN // 2) - den * FINE_OFFSET
if N == 2 then
offset += (den * 8) // 4
end
if bits[j + 1] + offset < den * 2 * 8 then
offset += NClogN // 4
elseif bits[j + 1] + offset < den * 3 * 8 then
offset += NClogN // 8
end
local eb = imax(0, bits[j + 1] + offset + den * 4)
eb = (eb // den) // 8
if C * eb > (bits[j + 1] // 8) then
eb = (bits[j + 1] // 2 ^ stereo) // 8
end
eb = imin(eb, MAX_FINE_BITS)
finePriority[j + 1] = if eb * (den * 8) >= bits[j + 1] + offset then 1 else 0
bits[j + 1] -= C * eb * 8
ebits[j + 1] = eb
else
excess = imax(0, bit - C * 8)
bits[j + 1] = bit - excess
ebits[j + 1] = 0
finePriority[j + 1] = 1
end
if excess > 0 then
local extraFine = imin(excess // 2 ^ (stereo + BITRES), MAX_FINE_BITS - ebits[j + 1])
ebits[j + 1] += extraFine
local extraBits = extraFine * C * 8
finePriority[j + 1] = if extraBits >= excess - balance then 1 else 0
excess -= extraBits
end
balance = excess
j += 1
end
while j < endb do
ebits[j + 1] = (bits[j + 1] // 2 ^ stereo) // 8
bits[j + 1] = 0
finePriority[j + 1] = if ebits[j + 1] < 1 then 1 else 0
j += 1
end
return codedBands, balance, intensity, dualStereo
end
-- ---------------------------------------------------------------------------------------------------------------
-- PVQ (cwrs.c, vq.c)
local function cwrsi(n: number, k: number, i: number, iy: { number }): number
local yy = 0
local idx = 1
local p, k0, val
while n > 2 do
if k >= n then
local rowBase = n * UK + 1
p = U[rowBase + k + 1]
local neg = i >= p
if neg then
i -= p
end
k0 = k
local q = U[rowBase + n]
if q > i then
k = n
repeat
k -= 1
p = U[k * UK + n + 1]
until p <= i
else
p = U[rowBase + k]
while p > i do
k -= 1
p = U[rowBase + k]
end
end
i -= p
val = if neg then k - k0 else k0 - k
iy[idx] = val
idx += 1
yy += val * val
else
p = U[k * UK + n + 1]
local q = U[(k + 1) * UK + n + 1]
if p <= i and i < q then
i -= p
iy[idx] = 0
idx += 1
else
local neg = i >= q
if neg then
i -= q
end
k0 = k
repeat
k -= 1
p = U[k * UK + n + 1]
until p <= i
i -= p
val = if neg then k - k0 else k0 - k
iy[idx] = val
idx += 1
yy += val * val
end
end
n -= 1
end
-- n == 2
p = 2 * k + 1
local neg = i >= p
if neg then
i -= p
end
k0 = k
k = rshift(i + 1, 1)
if k ~= 0 then
i -= 2 * k - 1
end
val = if neg then k - k0 else k0 - k
iy[idx] = val
yy += val * val
-- n == 1
val = if i ~= 0 then -k else k
iy[idx + 1] = val
yy += val * val
return yy
end
local function expRotation1(X: number, len: number, stride: number, c: number, s: number)
local ms = -s
local p = X + 1
for _ = 0, len - stride - 1 do
local x1 = W[p]
local x2 = W[p + stride]
W[p + stride] = c * x2 + s * x1
W[p] = c * x1 + ms * x2
p += 1
end
p = X + len - 2 * stride
for _ = len - 2 * stride - 1, 0, -1 do
local x1 = W[p]
local x2 = W[p + stride]
W[p + stride] = c * x2 + s * x1
W[p] = c * x1 + ms * x2
p -= 1
end
end
local SPREAD_FACTOR = { 15, 10, 5 }
local function expRotation(X: number, len: number, dir: number, stride: number, K: number, spread: number)
if 2 * K >= len or spread == 0 then
return
end
local factor = SPREAD_FACTOR[spread]
local gain = len / (len + factor * K)
local theta = 0.5 * (gain * gain)
local c = cos(0.5 * math.pi * theta)
local s = cos(0.5 * math.pi * (1 - theta))
local stride2 = 0
if len >= 8 * stride then
stride2 = 1
while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do
stride2 += 1
end
end
len = len // stride
for i = 0, stride - 1 do
local x = X + i * len
if dir < 0 then
if stride2 ~= 0 then
expRotation1(x, len, stride2, s, c)
end
expRotation1(x, len, 1, c, s)
else
expRotation1(x, len, 1, c, -s)
if stride2 ~= 0 then
expRotation1(x, len, stride2, s, -c)
end
end
end
end
local function renormaliseVector(X: number, N: number, gain: number)
local E = 1e-15
for i = X + 1, X + N do
local v = W[i]
E += v * v
end
local g = gain / sqrt(E)
for i = X + 1, X + N do
W[i] *= g
end
end
local function algUnquant(X: number, N: number, K: number, spread: number, B: number, dec: RD.Dec, gain: number): number
local iy = IY
local ft = U[N * UK + K + 1] + U[N * UK + K + 2]
local Ryy = cwrsi(N, K, decUint(dec, ft), iy)
local g = gain / sqrt(Ryy)
for i = 1, N do
W[X + i] = iy[i] * g
end
expRotation(X, N, -1, B, K, spread)
if B <= 1 then
return 1
end
local N0 = N // B
local mask = 0
for i = 0, B - 1 do
for j = 1, N0 do
if iy[i * N0 + j] ~= 0 then
mask = bor(mask, lshift(1, i))
break
end
end
end
return mask
end
-- ---------------------------------------------------------------------------------------------------------------
-- bands (bands.c)
type Ctx = {
i: number,
intensity: number,
spread: number,
tf_change: number,
ec: RD.Dec,
remaining_bits: number,
seed: number,
disable_inv: boolean,
avoid_split_noise: boolean,
}
local ctx: Ctx = {
i = 0,
intensity = 0,
spread = 0,
tf_change = 0,
ec = (nil :: any),
remaining_bits = 0,
seed = 0,
disable_inv = false,
avoid_split_noise = false,
}
local function haar1(X: number, N0: number, stride: number)
N0 = rshift(N0, 1)
local s = 0.70710678
for i = 0, stride - 1 do
for j = 0, N0 - 1 do
local a = X + stride * 2 * j + i + 1
local b = a + stride
local t1 = s * W[a]
local t2 = s * W[b]
W[a] = t1 + t2
W[b] = t1 - t2
end
end
end
local function deinterleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean)
local N = N0 * stride
local tmp = TMP
if hadamard then
local ob = stride - 2
for i = 0, stride - 1 do
local o = ORDERY[ob + i + 1] * N0
for j = 0, N0 - 1 do
tmp[o + j + 1] = W[X + j * stride + i + 1]
end
end
else
for i = 0, stride - 1 do
for j = 0, N0 - 1 do
tmp[i * N0 + j + 1] = W[X + j * stride + i + 1]
end
end
end
for k = 1, N do
W[X + k] = tmp[k]
end
end
local function interleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean)
local N = N0 * stride
local tmp = TMP
if hadamard then
local ob = stride - 2
for i = 0, stride - 1 do
local o = ORDERY[ob + i + 1] * N0
for j = 0, N0 - 1 do
tmp[j * stride + i + 1] = W[X + o + j + 1]
end
end
else
for i = 0, stride - 1 do
for j = 0, N0 - 1 do
tmp[j * stride + i + 1] = W[X + i * N0 + j + 1]
end
end
end
for k = 1, N do
W[X + k] = tmp[k]
end
end
local function computeQn(N: number, b: number, offset: number, pulseCap: number, stereo: boolean): number
local N2 = 2 * N - 1
if stereo and N == 2 then
N2 -= 1
end
local qb = tdiv(b + N2 * offset, N2)
qb = imin(b - pulseCap - 32, qb)
qb = imin(64, qb)
if qb < 4 then
return 1
end
local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3))
return lshift(rshift(qn + 1, 1), 1)
end
-- returns b, fill, inv, imid, iside, delta, itheta, qalloc
local function computeTheta(N: number, b: number, B: number, B0: number, LM: number, stereo: boolean, fill: number)
local i = ctx.i
local ec = ctx.ec
local pulseCap = LOGN[i + 1] + LM * 8
local offset = (pulseCap // 2) - (if stereo and N == 2 then QTHETA_OFFSET_TWOPHASE else QTHETA_OFFSET)
local qn = computeQn(N, b, offset, pulseCap, stereo)
if stereo and i >= ctx.intensity then
qn = 1
end
local t0 = tellFrac(ec)
local itheta = 0
local inv = false
if qn ~= 1 then
if stereo and N > 2 then
local p0 = 3
local x0 = qn // 2
local ft = p0 * (x0 + 1) + x0
local fs = decDecode(ec, ft)
local x
if fs < (x0 + 1) * p0 then
x = fs // p0
else
x = x0 + 1 + (fs - (x0 + 1) * p0)
end
if x <= x0 then
decUpdate(ec, p0 * x, p0 * (x + 1), ft)
else
decUpdate(ec, (x - 1 - x0) + (x0 + 1) * p0, (x - x0) + (x0 + 1) * p0, ft)
end
itheta = x
elseif B0 > 1 or stereo then
itheta = decUint(ec, qn + 1)
else
local h = rshift(qn, 1)
local ft = (h + 1) * (h + 1)
local fm = decDecode(ec, ft)
local fs, fl
if fm < rshift(h * (h + 1), 1) then
itheta = rshift(floor(sqrt(8 * fm + 1)) - 1, 1)
fs = itheta + 1
fl = rshift(itheta * (itheta + 1), 1)
else
itheta = rshift(2 * (qn + 1) - floor(sqrt(8 * (ft - fm - 1) + 1)), 1)
fs = qn + 1 - itheta
fl = ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1)
end
decUpdate(ec, fl, fl + fs, ft)
end
itheta = (itheta * 16384) // qn
elseif stereo then
if b > 16 and ctx.remaining_bits > 16 then
inv = decBitLogp(ec, 2)
end
if ctx.disable_inv then
inv = false
end
itheta = 0
end
local qalloc = tellFrac(ec) - t0
b -= qalloc
local imid, iside, delta
if itheta == 0 then
imid = 32767
iside = 0
fill = band(fill, lshift(1, B) - 1)
delta = -16384
elseif itheta == 16384 then
imid = 0
iside = 32767
fill = band(fill, lshift(lshift(1, B) - 1, B))
delta = 16384
else
imid = bitexactCos(itheta)
iside = bitexactCos(16384 - itheta)
delta = fracMul16((N - 1) * 128, bitexactLog2tan(iside, imid))
end
return b, fill, inv, imid, iside, delta, itheta, qalloc
end
local function quantBandN1(X: number, Y: number, lowbandOut: number): number
local x = X
local ec = ctx.ec
for _ = 0, (if Y >= 0 then 1 else 0) do
local sign = 0
if ctx.remaining_bits >= 8 then
sign = decBits(ec, 1)
ctx.remaining_bits -= 8
end
W[x + 1] = if sign ~= 0 then -1 else 1
x = Y
end
if lowbandOut >= 0 then
W[lowbandOut + 1] = W[X + 1]
end
return 1
end
local function quantPartition(X: number, N: number, b: number, B: number, lowband: number, LM: number, gain: number, fill: number): number
local i = ctx.i
local B0 = B
local cm = 0
local split = false
if LM ~= -1 and N > 2 then
local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + i + 1]
split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12
end
if split then
N = rshift(N, 1)
local Y = X + N
LM -= 1
if B == 1 then
fill = bor(band(fill, 1), lshift(fill, 1))
end
B = rshift(B + 1, 1)
local _inv, imid, iside, delta, itheta, qalloc
b, fill, _inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B0, LM, false, fill)
local mid = imid / 32768
local side = iside / 32768
if B0 > 1 and band(itheta, 0x3fff) ~= 0 then
if itheta > 8192 then
delta -= delta // 2 ^ (4 - LM)
else
delta = imin(0, delta + (N * 8) // 2 ^ (5 - LM))
end
end
local mbits = imax(0, imin(b, tdiv(b - delta, 2)))
local sbits = b - mbits
ctx.remaining_bits -= qalloc
local nextLowband2 = if lowband >= 0 then lowband + N else -1
local rebalance = ctx.remaining_bits
if mbits >= sbits then
cm = quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill)
rebalance = mbits - (rebalance - ctx.remaining_bits)
if rebalance > 24 and itheta ~= 0 then
sbits += rebalance - 24
end
cm = bor(cm, lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1)))
else
cm = lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1))
rebalance = sbits - (rebalance - ctx.remaining_bits)
if rebalance > 24 and itheta ~= 16384 then
mbits += rebalance - 24
end
cm = bor(cm, quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill))
end
else
local q = bits2pulses(i, LM, b)
local currBits = pulses2bits(i, LM, q)
ctx.remaining_bits -= currBits
while ctx.remaining_bits < 0 and q > 0 do
ctx.remaining_bits += currBits
q -= 1
currBits = pulses2bits(i, LM, q)
ctx.remaining_bits -= currBits
end
if q ~= 0 then
cm = algUnquant(X, N, getPulses(q), ctx.spread, B, ctx.ec, gain)
else
local cmMask = lshift(1, B) - 1
fill = band(fill, cmMask)
if fill == 0 then
for j = X + 1, X + N do
W[j] = 0
end
else
local seed = ctx.seed
if lowband < 0 then
for j = X + 1, X + N do
seed = lcg(seed)
W[j] = signed32(seed) // 1048576
end
cm = cmMask
else
for j = 0, N - 1 do
seed = lcg(seed)
local tmp = if band(seed, 0x8000) ~= 0 then 1 / 256 else -1 / 256
W[X + j + 1] = W[lowband + j + 1] + tmp
end
cm = fill
end
ctx.seed = seed
renormaliseVector(X, N, gain)
end
end
end
return cm
end
local function quantBand(X: number, N: number, b: number, B: number, lowband: number, LM: number, lowbandOut: number,
gain: number, lowbandScratch: number, fill: number): number
local N0 = N
local NB = N
local B0 = B
local timeDivide = 0
local recombine = 0
local longBlocks = B0 == 1
local tfChange = ctx.tf_change
NB = NB // B
if N == 1 then
return quantBandN1(X, -1, lowbandOut)
end
if tfChange > 0 then
recombine = tfChange
end
if lowbandScratch >= 0 and lowband >= 0 and (recombine ~= 0 or (band(NB, 1) == 0 and tfChange < 0) or B0 > 1) then
for j = 1, N do
W[lowbandScratch + j] = W[lowband + j]
end
lowband = lowbandScratch
end
for k = 0, recombine - 1 do
if lowband >= 0 then
haar1(lowband, rshift(N, k), lshift(1, k))
end
fill = bor(BIT_INTERLEAVE[band(fill, 0xF) + 1], lshift(BIT_INTERLEAVE[rshift(fill, 4) + 1], 2))
end
B = rshift(B, recombine)
NB = lshift(NB, recombine)
while band(NB, 1) == 0 and tfChange < 0 do
if lowband >= 0 then
haar1(lowband, NB, B)
end
fill = bor(fill, lshift(fill, B))
B = lshift(B, 1)
NB = rshift(NB, 1)
timeDivide += 1
tfChange += 1
end
B0 = B
local NB0 = NB
if B0 > 1 and lowband >= 0 then
deinterleaveHadamard(lowband, rshift(NB, recombine), lshift(B0, recombine), longBlocks)
end
local cm = quantPartition(X, N, b, B, lowband, LM, gain, fill)
if B0 > 1 then
interleaveHadamard(X, rshift(NB, recombine), lshift(B0, recombine), longBlocks)
end
NB = NB0
B = B0
for _ = 0, timeDivide - 1 do
B = rshift(B, 1)
NB = lshift(NB, 1)
cm = bor(cm, rshift(cm, B))
haar1(X, NB, B)
end
for k = 0, recombine - 1 do
cm = BIT_DEINTERLEAVE[cm + 1]
haar1(X, rshift(N0, k), lshift(1, k))
end
B = lshift(B, recombine)
if lowbandOut >= 0 then
local n = sqrt(N0)
for j = 1, N0 do
W[lowbandOut + j] = n * W[X + j]
end
end
return band(cm, lshift(1, B) - 1)
end
local function stereoMerge(X: number, Y: number, mid: number, N: number)
local xp, side = 0, 0
for j = 1, N do
local y = W[Y + j]
xp += y * W[X + j]
side += y * y
end
xp = mid * xp
local mm = mid * mid
local El = mm + side - 2 * xp
local Er = mm + side + 2 * xp
if Er < 6e-4 or El < 6e-4 then
for j = 1, N do
W[Y + j] = W[X + j]
end
return
end
local lgain = 1 / sqrt(El)
local rgain = 1 / sqrt(Er)
for j = 1, N do
local l = mid * W[X + j]
local r = W[Y + j]
W[X + j] = lgain * (l - r)
W[Y + j] = rgain * (l + r)
end
end
local function quantBandStereo(X: number, Y: number, N: number, b: number, B: number, lowband: number, LM: number,
lowbandOut: number, lowbandScratch: number, fill: number): number
if N == 1 then
return quantBandN1(X, Y, lowbandOut)
end
local origFill = fill
local inv, imid, iside, delta, itheta, qalloc
b, fill, inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B, LM, true, fill)
local mid = imid / 32768
local side = iside / 32768
local cm
if N == 2 then
local mbits = b
local sbits = 0
if itheta ~= 0 and itheta ~= 16384 then
sbits = 8
end
mbits -= sbits
local c = itheta > 8192
ctx.remaining_bits -= qalloc + sbits
local x2, y2 = X, Y
if c then
x2, y2 = Y, X
end
local sign = 0
if sbits ~= 0 then
sign = decBits(ctx.ec, 1)
end
sign = 1 - 2 * sign
cm = quantBand(x2, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, origFill)
W[y2 + 1] = -sign * W[x2 + 2]
W[y2 + 2] = sign * W[x2 + 1]
local x0, x1 = mid * W[X + 1], mid * W[X + 2]
local y0, y1 = side * W[Y + 1], side * W[Y + 2]
W[X + 1] = x0 - y0
W[Y + 1] = x0 + y0
W[X + 2] = x1 - y1
W[Y + 2] = x1 + y1
else
local mbits = imax(0, imin(b, tdiv(b - delta, 2)))
local sbits = b - mbits
ctx.remaining_bits -= qalloc
local rebalance = ctx.remaining_bits
if mbits >= sbits then
cm = quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill)
rebalance = mbits - (rebalance - ctx.remaining_bits)
if rebalance > 24 and itheta ~= 0 then
sbits += rebalance - 24
end
cm = bor(cm, quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B)))
else
cm = quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B))
rebalance = sbits - (rebalance - ctx.remaining_bits)
if rebalance > 24 and itheta ~= 16384 then
mbits += rebalance - 24
end
cm = bor(cm, quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill))
end
end
if N ~= 2 then
stereoMerge(X, Y, mid, N)
end
if inv then
for j = Y + 1, Y + N do
W[j] = -W[j]
end
end
return cm
end
local function quantAllBands(start: number, endb: number, hasY: boolean, N: number, collapse: { number },
pulses: { number }, shortBlocks: boolean, spread: number, dualStereo: boolean, intensity: number,
tfRes: { number }, totalBits: number, balance: number, ec: RD.Dec, LM: number, codedBands: number,
seed: number, disableInv: boolean): number
local M = lshift(1, LM)
local B = if shortBlocks then M else 1
local normOffset = M * EB[start + 1]
local C = if hasY then 2 else 1
local norm = NORM_BASE
local norm2 = NORM_BASE + M * EB[NB_EBANDS] - normOffset
local lowbandScratch = M * EB[EFF_EBANDS]
local lowbandOffset = 0
local updateLowband = true
ctx.ec = ec
ctx.intensity = intensity
ctx.seed = seed
ctx.spread = spread
ctx.disable_inv = disableInv
ctx.avoid_split_noise = B > 1
for i = start, endb - 1 do
ctx.i = i
local last = i == endb - 1
local X = M * EB[i + 1]
local Y = if hasY then N + M * EB[i + 1] else -1
local Nb = M * EB[i + 2] - M * EB[i + 1]
local t = tellFrac(ec)
if i ~= start then
balance -= t
end
local remainingBits = totalBits - t - 1
ctx.remaining_bits = remainingBits
local b
if i <= codedBands - 1 then
local currBalance = tdiv(balance, imin(3, codedBands - i))
b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance)))
else
b = 0
end
if (M * EB[i + 1] - Nb >= M * EB[start + 1] or i == start + 1) and (updateLowband or lowbandOffset == 0) then
lowbandOffset = i
end
if i == start + 1 then
local n1 = M * (EB[start + 2] - EB[start + 1])
local n2 = M * (EB[start + 3] - EB[start + 2])
for k = 0, n2 - n1 - 1 do
W[norm + n1 + k + 1] = W[norm + 2 * n1 - n2 + k + 1]
end
if dualStereo then
for k = 0, n2 - n1 - 1 do
W[norm2 + n1 + k + 1] = W[norm2 + 2 * n1 - n2 + k + 1]
end
end
end
local tfChange = tfRes[i + 1]
ctx.tf_change = tfChange
if last then
lowbandScratch = -1
end
local effectiveLowband = -1
local xcm, ycm
if lowbandOffset ~= 0 and (spread ~= SPREAD_AGGRESSIVE or B > 1 or tfChange < 0) then
effectiveLowband = imax(0, M * EB[lowbandOffset + 1] - normOffset - Nb)
local foldStart = lowbandOffset
repeat
foldStart -= 1
until M * EB[foldStart + 1] <= effectiveLowband + normOffset
local foldEnd = lowbandOffset - 1
repeat
foldEnd += 1
until not (foldEnd < i and M * EB[foldEnd + 1] < effectiveLowband + normOffset + Nb)
xcm, ycm = 0, 0
local fi = foldStart
repeat
xcm = bor(xcm, collapse[fi * C + 1])
ycm = bor(ycm, collapse[fi * C + C])
fi += 1
until fi >= foldEnd
else
xcm = lshift(1, B) - 1
ycm = xcm
end
if dualStereo and i == intensity then
dualStereo = false
for j = 1, M * EB[i + 1] - normOffset do
W[norm + j] = 0.5 * (W[norm + j] + W[norm2 + j])
end
end
if dualStereo then
xcm = quantBand(X, Nb, b // 2, B, if effectiveLowband ~= -1 then norm + effectiveLowband else -1, LM,
if last then -1 else norm + M * EB[i + 1] - normOffset, 1, lowbandScratch, xcm)
ycm = quantBand(Y, Nb, b // 2, B, if effectiveLowband ~= -1 then norm2 + effectiveLowband else -1, LM,
if last then -1 else norm2 + M * EB[i + 1] - normOffset, 1, lowbandScratch, ycm)
else
local lb = if effectiveLowband ~= -1 then norm + effectiveLowband else -1
local lo = if last then -1 else norm + M * EB[i + 1] - normOffset
if hasY then
xcm = quantBandStereo(X, Y, Nb, b, B, lb, LM, lo, lowbandScratch, bor(xcm, ycm))
else
xcm = quantBand(X, Nb, b, B, lb, LM, lo, 1, lowbandScratch, bor(xcm, ycm))
end
ycm = xcm
end
collapse[i * C + 1] = band(xcm, 255)
collapse[i * C + C] = band(ycm, 255)
balance += pulses[i + 1] + t
updateLowband = b > Nb * 8
ctx.avoid_split_noise = false
end
return ctx.seed
end
local function antiCollapse(st: any, C: number, size: number, LM: number, start: number, endb: number,
collapse: { number }, pulses: { number }, seed: number)
local logE, prev1logE, prev2logE = st.oldBandE, st.oldLogE, st.oldLogE2
for i = start, endb - 1 do
local N0 = EB[i + 2] - EB[i + 1]
local depth = rshift((1 + pulses[i + 1]) // N0, LM)
local thresh = 0.5 * exp2(-0.125 * depth)
local sqrt1 = 1 / sqrt(N0 * 2 ^ LM)
for c = 0, C - 1 do
local k0 = c * NB_EBANDS + i + 1
local prev1 = prev1logE[k0]
local prev2 = prev2logE[k0]
if C == 1 then
prev1 = max(prev1, prev1logE[NB_EBANDS + i + 1])
prev2 = max(prev2, prev2logE[NB_EBANDS + i + 1])
end
local Ediff = max(0, logE[k0] - min(prev1, prev2))
local r = 2 * exp2(-Ediff)
if LM == 3 then
r *= 1.41421356
end
r = min(thresh, r) * sqrt1
local X = c * size + EB[i + 1] * 2 ^ LM
local renorm = false
local cmask = collapse[i * C + c + 1]
for k = 0, 2 ^ LM - 1 do
if band(cmask, lshift(1, k)) == 0 then
for j = 0, N0 - 1 do
seed = lcg(seed)
W[X + j * 2 ^ LM + k + 1] = if band(seed, 0x8000) ~= 0 then r else -r
end
renorm = true
end
end
if renorm then
renormaliseVector(X, N0 * 2 ^ LM, 1)
end
end
end
end
-- ---------------------------------------------------------------------------------------------------------------
-- synthesis
local function denormaliseBands(X: number, freq: { number }, logE: { number }, eoff: number, start: number, endb: number, M: number, silence: boolean)
local N = M * SHORT_MDCT
local bound = M * EB[endb + 1]
if silence then
bound = 0
start = 0
endb = 0
end
local f = 1
local x = X + M * EB[start + 1]
if start ~= 0 then
for _ = 1, M * EB[start + 1] do
freq[f] = 0
f += 1
end
end
for i = start, endb - 1 do
local bandEnd = M * EB[i + 2]
local lg = logE[eoff + i + 1] + E_MEANS[i + 1]
local g = exp2(min(32, lg))
for _ = M * EB[i + 1], bandEnd - 1 do
freq[f] = W[x + 1] * g
f += 1
x += 1
end
end
for k = bound + 1, N do
freq[k] = 0
end
end
local function celtSynthesis(st: any, C: number, CC: number, start: number, effEnd: number, isTransient: boolean, LM: number, silence: boolean, N: number)
local M = lshift(1, LM)
local B, NB, shift
if isTransient then
B = M
NB = SHORT_MDCT
shift = MAX_LM
else
B = 1
NB = SHORT_MDCT * M
shift = MAX_LM - LM
end
local outBase = DECODE_BUFFER_SIZE - N + 1
local oldE = st.oldBandE
local freq = FREQ
if CC == 2 and C == 1 then
denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence)
for c = 1, 2 do
local mem = st.mem[c]
for b = 0, B - 1 do
Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B)
end
end
elseif CC == 1 and C == 2 then
denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence)
denormaliseBands(N, FREQ2, oldE, NB_EBANDS, start, effEnd, M, silence)
local f2 = FREQ2
for k = 1, N do
freq[k] = 0.5 * freq[k] + 0.5 * f2[k]
end
local mem = st.mem[1]
for b = 0, B - 1 do
Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B)
end
else
for c = 0, CC - 1 do
denormaliseBands(c * N, freq, oldE, c * NB_EBANDS, start, effEnd, M, silence)
local mem = st.mem[c + 1]
for b = 0, B - 1 do
Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B)
end
end
end
end
-- comb_filter, in place on mem (1-based base index of sample 0)
local function combFilter(mem: { number }, base: number, T0: number, T1: number, N: number, g0: number, g1: number,
tapset0: number, tapset1: number, overlap: number)
if g0 == 0 and g1 == 0 then
return
end
T0 = imax(T0, COMBFILTER_MINPERIOD)
T1 = imax(T1, COMBFILTER_MINPERIOD)
local ga, gb = COMB_GAINS[tapset0 + 1], COMB_GAINS[tapset1 + 1]
local g00, g01, g02 = g0 * ga[1], g0 * ga[2], g0 * ga[3]
local g10, g11, g12 = g1 * gb[1], g1 * gb[2], g1 * gb[3]
local x1 = mem[base - T1 + 1]
local x2 = mem[base - T1]
local x3 = mem[base - T1 - 1]
local x4 = mem[base - T1 - 2]
if g0 == g1 and T0 == T1 and tapset0 == tapset1 then
overlap = 0
end
local i = 0
while i < overlap do
local p = base + i
local x0 = mem[p - T1 + 2]
local w = WINDOW[i + 1]
local f = w * w
local of = 1 - f
mem[p] = mem[p] + (of * g00) * mem[p - T0] + (of * g01) * (mem[p - T0 + 1] + mem[p - T0 - 1])
+ (of * g02) * (mem[p - T0 + 2] + mem[p - T0 - 2]) + (f * g10) * x2 + (f * g11) * (x1 + x3)
+ (f * g12) * (x0 + x4)
x4 = x3
x3 = x2
x2 = x1
x1 = x0
i += 1
end
if g1 == 0 then
return
end
-- constant part (comb_filter_const)
local p = base + i
x4 = mem[p - T1 - 2]
x3 = mem[p - T1 - 1]
x2 = mem[p - T1]
x1 = mem[p - T1 + 1]
for q = p, base + N - 1 do
local x0 = mem[q - T1 + 2]
mem[q] = mem[q] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4)
x4 = x3
x3 = x2
x2 = x1
x1 = x0
end
end
local function deemphasis(st: any, CC: number, N: number, pcm: { number }, pbase: number, accum: boolean)
local coef0 = PREEMPH
local xbase = DECODE_BUFFER_SIZE - N
for c = 0, CC - 1 do
local x = st.mem[c + 1]
local m = st.preemph[c + 1]
local y = pbase + c
if accum then
for j = 1, N do
local tmp = x[xbase + j] + 1e-30 + m
m = coef0 * tmp
pcm[y] += tmp * (1 / 32768)
y += CC
end
else
for j = 1, N do
local tmp = x[xbase + j] + 1e-30 + m
m = coef0 * tmp
pcm[y] = tmp * (1 / 32768)
y += CC
end
end
st.preemph[c + 1] = m
end
end
-- ---------------------------------------------------------------------------------------------------------------
-- decoder state
local function resetState(st: any)
st.rng = 0
st.error = 0
st.loss_duration = 0
st.plc_duration = 0
st.last_frame_type = FRAME_NONE
st.skip_plc = true
st.postfilter_period = 0
st.postfilter_period_old = 0
st.postfilter_gain = 0
st.postfilter_gain_old = 0
st.postfilter_tapset = 0
st.postfilter_tapset_old = 0
st.preemph[1] = 0
st.preemph[2] = 0
for c = 1, st.channels do
local m = st.mem[c]
for k = 1, DECODE_BUFFER_SIZE + OVERLAP do
m[k] = 0
end
end
for k = 1, 2 * NB_EBANDS do
st.oldBandE[k] = 0
st.oldLogE[k] = -28
st.oldLogE2[k] = -28
st.backgroundLogE[k] = 0
end
end
-- celt_decoder_init(48000, channels)
function Celt.new(channels: number): any
local st = {
channels = channels,
stream_channels = channels,
start = 0,
["end"] = EFF_EBANDS,
disable_inv = channels == 1,
mem = {},
preemph = { 0, 0 },
oldBandE = table.create(2 * NB_EBANDS, 0),
oldLogE = table.create(2 * NB_EBANDS, -28),
oldLogE2 = table.create(2 * NB_EBANDS, -28),
backgroundLogE = table.create(2 * NB_EBANDS, 0),
}
for c = 1, channels do
st.mem[c] = table.create(DECODE_BUFFER_SIZE + OVERLAP, 0)
end
resetState(st)
return st
end
Celt.reset = resetState
-- noise-based concealment (celt_decode_lost, FRAME_PLC_NOISE)
local function decodeLost(st: any, N: number, LM: number)
local C = st.channels
local start = st.start
local endb = st["end"]
local effEnd = imax(start, imin(endb, EFF_EBANDS))
for c = 1, C do
table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1)
end
local decay = 2 ^ LM * 0.0625
if st.last_frame_type ~= FRAME_PLC_NOISE then
decay += max(1, imin(160, st.loss_duration) * 0.0625)
end
local oldE, bg = st.oldBandE, st.backgroundLogE
for c = 0, C - 1 do
for i = start, endb - 1 do
local k = c * NB_EBANDS + i + 1
oldE[k] = max(bg[k], oldE[k] - decay)
end
end
local seed = st.rng
for c = 0, C - 1 do
for i = start, effEnd - 1 do
local boffs = N * c + EB[i + 1] * 2 ^ LM
local blen = (EB[i + 2] - EB[i + 1]) * 2 ^ LM
for j = 1, blen do
seed = lcg(seed)
W[boffs + j] = signed32(seed) // 1048576
end
renormaliseVector(boffs, blen, 1)
end
end
st.rng = seed
celtSynthesis(st, C, C, start, effEnd, false, LM, false, N)
local base = DECODE_BUFFER_SIZE - N + 1
for c = 1, C do
st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD)
st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD)
combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old,
st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP)
if LM ~= 0 then
combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, st.postfilter_period, N - SHORT_MDCT,
st.postfilter_gain, st.postfilter_gain, st.postfilter_tapset, st.postfilter_tapset, OVERLAP)
end
end
st.postfilter_period_old = st.postfilter_period
st.postfilter_gain_old = st.postfilter_gain
st.postfilter_tapset_old = st.postfilter_tapset
st.skip_plc = true
st.loss_duration = imin(10000, st.loss_duration + 2 ^ LM)
st.plc_duration = imin(10000, st.plc_duration + 2 ^ LM)
st.last_frame_type = FRAME_PLC_NOISE
end
-- celt_decode_with_ec. pcm[pbase + j * channels + c]; frameSize at 48 kHz. dec may be nil (a new range decoder over
-- buf[off, off + len)). buf == nil or len <= 1 conceals. Returns the samples per channel, or < 0 on error.
function Celt.decode(st: any, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number,
dec: RD.Dec?, accum: boolean): number
local CC = st.channels
local C = st.stream_channels
local start = st.start
local endb = st["end"]
local LM = 0
while LM <= MAX_LM and lshift(SHORT_MDCT, LM) ~= frameSize do
LM += 1
end
if LM > MAX_LM then
return -1
end
local M = lshift(1, LM)
if len < 0 or len > 1275 then
return -1
end
local N = M * SHORT_MDCT
local effEnd = imin(endb, EFF_EBANDS)
if buf == nil or len <= 1 then
decodeLost(st, N, LM)
deemphasis(st, CC, N, pcm, pbase, accum)
return frameSize
end
if st.loss_duration == 0 then
st.skip_plc = false
end
if dec == nil then
dec = RD.new(buf :: buffer, off, len)
end
local ec = dec :: RD.Dec
local oldBandE, oldLogE, oldLogE2, bgLogE = st.oldBandE, st.oldLogE, st.oldLogE2, st.backgroundLogE
if C == 1 then
for i = 1, NB_EBANDS do
oldBandE[i] = max(oldBandE[i], oldBandE[NB_EBANDS + i])
end
end
local totalBits = len * 8
local t = tell(ec)
local silence
if t >= totalBits then
silence = true
elseif t == 1 then
silence = decBitLogp(ec, 15)
else
silence = false
end
if silence then
t = len * 8
ec.nbits_total += t - tell(ec)
end
local postfilterGain, postfilterPitch, postfilterTapset = 0, 0, 0
if start == 0 and t + 16 <= totalBits then
if decBitLogp(ec, 1) then
local octave = decUint(ec, 6)
postfilterPitch = lshift(16, octave) + decBits(ec, 4 + octave) - 1
local qg = decBits(ec, 3)
if tell(ec) + 2 <= totalBits then
postfilterTapset = decIcdf(ec, TAPSET_ICDF, 1, 2)
end
postfilterGain = 0.09375 * (qg + 1)
end
t = tell(ec)
end
local isTransient = false
if LM > 0 and t + 3 <= totalBits then
isTransient = decBitLogp(ec, 3)
t = tell(ec)
end
local shortBlocks = isTransient
local intraEner = if t + 3 <= totalBits then decBitLogp(ec, 3) else false
if not intraEner and st.loss_duration ~= 0 then
local missing = imin(10, rshift(st.loss_duration, LM))
local safety = if LM == 0 then 1.5 elseif LM == 1 then 0.5 else 0
for c = 0, 1 do
for i = start, endb - 1 do
local k = c * NB_EBANDS + i + 1
if oldBandE[k] < max(oldLogE[k], oldLogE2[k]) then
local E0, E1, E2 = oldBandE[k], oldLogE[k], oldLogE2[k]
local slope = max(E1 - E0, 0.5 * (E2 - E0))
slope = min(slope, 2)
E0 -= max(0, (1 + missing) * slope)
oldBandE[k] = max(-20, E0)
else
oldBandE[k] = min(min(oldBandE[k], oldLogE[k]), oldLogE2[k])
end
oldBandE[k] -= safety
end
end
end
unquantCoarseEnergy(st, start, endb, intraEner, ec, C, LM)
-- tf_decode
local tfRes = TF_RES
do
local budget = ec.storage * 8
local tt = tell(ec)
local logp = if isTransient then 2 else 4
local tfSelectRsv = LM > 0 and tt + logp + 1 <= budget
if tfSelectRsv then
budget -= 1
end
local tfChanged, curr = 0, 0
for i = start, endb - 1 do
if tt + logp <= budget then
if decBitLogp(ec, logp) then
curr = bit32.bxor(curr, 1)
end
tt = tell(ec)
tfChanged = bor(tfChanged, curr)
end
tfRes[i + 1] = curr
logp = if isTransient then 4 else 5
end
local tfSelect = 0
local row = TF_SELECT[LM + 1]
local ti = if isTransient then 4 else 0
if tfSelectRsv and row[ti + tfChanged + 1] ~= row[ti + 2 + tfChanged + 1] then
tfSelect = if decBitLogp(ec, 1) then 1 else 0
end
for i = start, endb - 1 do
tfRes[i + 1] = row[ti + 2 * tfSelect + tfRes[i + 1] + 1]
end
end
t = tell(ec)
local spread = 2
if t + 4 <= totalBits then
spread = decIcdf(ec, SPREAD_ICDF, 1, 5)
end
local cap = CAP
for i = 0, NB_EBANDS - 1 do
local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM
cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2)
end
local offsets = OFFSETS
local dynallocLogp = 6
totalBits *= 8
t = tellFrac(ec)
for i = start, endb - 1 do
local width = C * (EB[i + 2] - EB[i + 1]) * 2 ^ LM
local quanta = imin(width * 8, imax(48, width))
local loopLogp = dynallocLogp
local boost = 0
while t + loopLogp * 8 < totalBits and boost < cap[i + 1] do
local flag = decBitLogp(ec, loopLogp)
t = tellFrac(ec)
if not flag then
break
end
boost += quanta
totalBits -= quanta
loopLogp = 1
end
offsets[i + 1] = boost
if boost > 0 then
dynallocLogp = imax(2, dynallocLogp - 1)
end
end
local allocTrim = if t + 48 <= totalBits then decIcdf(ec, TRIM_ICDF, 1, 7) else 5
local bits = len * 64 - tellFrac(ec) - 1
local antiCollapseRsv = if isTransient and LM >= 2 and bits >= (LM + 2) * 8 then 8 else 0
bits -= antiCollapseRsv
local pulses, fineQuant, finePriority = PULSES, FINE_QUANT, FINE_PRIORITY
local codedBands, balance, intensity, dualStereo = computeAllocation(start, endb, offsets, cap, allocTrim, bits,
pulses, fineQuant, finePriority, C, LM, ec)
unquantFineEnergy(st, start, endb, fineQuant, ec, C)
-- shift the decoder memory by one frame
for c = 1, CC do
table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1)
end
local collapse = COLLAPSE
st.rng = quantAllBands(start, endb, C == 2, N, collapse, pulses, shortBlocks, spread, dualStereo, intensity, tfRes,
len * 64 - antiCollapseRsv, balance, ec, LM, codedBands, st.rng, st.disable_inv)
local antiCollapseOn = false
if antiCollapseRsv > 0 then
antiCollapseOn = decBits(ec, 1) ~= 0
end
unquantEnergyFinalise(st, start, endb, fineQuant, finePriority, len * 8 - tell(ec), ec, C)
if antiCollapseOn then
antiCollapse(st, C, N, LM, start, endb, collapse, pulses, st.rng)
end
if silence then
for i = 1, C * NB_EBANDS do
oldBandE[i] = -28
end
end
celtSynthesis(st, C, CC, start, effEnd, isTransient, LM, silence, N)
local base = DECODE_BUFFER_SIZE - N + 1
for c = 1, CC do
st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD)
st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD)
combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old,
st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP)
if LM ~= 0 then
combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, postfilterPitch, N - SHORT_MDCT,
st.postfilter_gain, postfilterGain, st.postfilter_tapset, postfilterTapset, OVERLAP)
end
end
st.postfilter_period_old = st.postfilter_period
st.postfilter_gain_old = st.postfilter_gain
st.postfilter_tapset_old = st.postfilter_tapset
st.postfilter_period = postfilterPitch
st.postfilter_gain = postfilterGain
st.postfilter_tapset = postfilterTapset
if LM ~= 0 then
st.postfilter_period_old = st.postfilter_period
st.postfilter_gain_old = st.postfilter_gain
st.postfilter_tapset_old = st.postfilter_tapset
end
if C == 1 then
for i = 1, NB_EBANDS do
oldBandE[NB_EBANDS + i] = oldBandE[i]
end
end
if not isTransient then
for i = 1, 2 * NB_EBANDS do
oldLogE2[i] = oldLogE[i]
oldLogE[i] = oldBandE[i]
end
else
for i = 1, 2 * NB_EBANDS do
oldLogE[i] = min(oldLogE[i], oldBandE[i])
end
end
local maxBgIncrease = imin(160, st.loss_duration + M) * 0.001
for i = 1, 2 * NB_EBANDS do
bgLogE[i] = min(bgLogE[i] + maxBgIncrease, oldBandE[i])
end
for c = 0, 1 do
for i = 0, start - 1 do
local k = c * NB_EBANDS + i + 1
oldBandE[k] = 0
oldLogE[k] = -28
oldLogE2[k] = -28
end
for i = endb, NB_EBANDS - 1 do
local k = c * NB_EBANDS + i + 1
oldBandE[k] = 0
oldLogE[k] = -28
oldLogE2[k] = -28
end
end
st.rng = ec.rng
deemphasis(st, CC, N, pcm, pbase, accum)
st.loss_duration = 0
st.plc_duration = 0
st.last_frame_type = FRAME_NORMAL
if tell(ec) > 8 * len then
return -3
end
if ec.error ~= 0 then
st.error = 1
end
return frameSize
end
return Celt