--!strict --!native --!optimize 2 -- audio/opus/Silk: SILK decoder: a bit-exact port of the libopus fixed-point SILK decoder (silk/dec_API.c and what it calls: -- decode_frame, decode_indices, decode_pulses, shell_coder, code_signs, decode_parameters, gain_quant, NLSF_*, -- LPC_fit, LPC_inv_pred_gain, decode_core, stereo_*, CNG, PLC, resampler_private_up2_HQ / IIR_FIR). BSD, see -- licenses/. -- -- local st = Silk.new(apiChannels) -- local ret, n = Silk.decode(st, ctrl, lostFlag, firstFrame, ec, out, outBase) -- ctrl = { nChannelsAPI, nChannelsInternal, API_sampleRate, internalSampleRate, payloadSize_ms } -- decodes one 10 / 20 ms SILK frame and writes n samples per channel (at API_sampleRate) to the Luau array -- `out`, interleaved by nChannelsAPI: out[outBase + i * nChannelsAPI + c], scaled int16 / 32768. -- -- Fixed-point emulation: all values are Luau numbers holding C int32 / int16 values. Products of two int32 values -- (64-bit in C) are split so that every intermediate stays below 2^53 and therefore exact. local RD = require("@formats/audio/opus/RangeDecoder") local T = require("@formats/audio/opus/SilkTables") local icdf = RD.icdf local bitLogp = RD.bitLogp local countlz = bit32.countlz local floor = math.floor local Silk = {} local P2 = table.create(64, 0) -- P2[s] = 2^s (1-based by s: P2[s] for s >= 1, P2_0 = 1) for s = 1, 63 do P2[s] = 2 ^ s end local function p2(s: number): number if s == 0 then return 1 end return P2[s] end -- C helpers ----------------------------------------------------------------------------------------------------- local function s16(x: number): number x = x % 65536 if x >= 32768 then return x - 65536 end return x end local function i32(x: number): number x = x % 4294967296 if x >= 2147483648 then return x - 4294967296 end return x end local function sat16(x: number): number if x > 32767 then return 32767 elseif x < -32768 then return -32768 end return x end local function addSat32(a: number, b: number): number local s = a + b if s > 2147483647 then return 2147483647 elseif s < -2147483648 then return -2147483648 end return s end local function subSat32(a: number, b: number): number local s = a - b if s > 2147483647 then return 2147483647 elseif s < -2147483648 then return -2147483648 end return s end -- silk_CLZ32 of a non-negative int32 local function clz32(x: number): number return countlz(x) end -- silk_SMULWW (64-bit form): (a * b) >> 16, exact local function mulww(a: number, b: number): number return a * (b // 65536) + (a * (b % 65536)) // 65536 end -- floor(a * b / 2^s) for int32 a, b and s >= 16, exact local function mulshr(a: number, b: number, s: number): number local t = a * (b // 65536) + (a * (b % 65536)) // 65536 if s == 16 then return t end return t // P2[s - 16] end local function smmul(a: number, b: number): number return mulshr(a, b, 32) end -- silk_RSHIFT_ROUND (shift >= 1) local function rround(a: number, s: number): number return (a + p2(s - 1)) // P2[s] end local function lshiftSat32(a: number, sh: number): number if sh == 0 then return a end local m = P2[sh] local lo, hi = -2147483648 // m, 2147483647 // m if a < lo then a = lo elseif a > hi then a = hi end return a * m end -- C integer division (truncation toward zero) local function tdiv(a: number, b: number): number local q = a / b if q >= 0 then return floor(q) end return -floor(-q) end -- low 32 bits of a * b, as int32 local function imul32(a: number, b: number): number a = a % 4294967296 local ah, al = a // 65536, a % 65536 return i32(((ah * b) % 65536) * 65536 + al * b) end local function silkRand(seed: number): number return i32(907633515 + imul32(seed, 196314165)) end local function rshift(a: number, s: number): number if s == 0 then return a end return a // P2[s] end local function silkINVERSE32_varQ(b32: number, Qres: number): number local b_headrm = clz32(math.abs(b32)) - 1 local b32_nrm = b32 * p2(b_headrm) local b32_inv = tdiv(536870911, b32_nrm // 65536) local result = b32_inv * 65536 local err_Q32 = i32((536870912 - (b32_nrm * b32_inv) // 65536) * 8) result = i32(result + mulww(err_Q32, b32_inv)) local lshift = 61 - b_headrm - Qres if lshift <= 0 then return lshiftSat32(result, -lshift) elseif lshift < 32 then return result // P2[lshift] end return 0 end local function silkDIV32_varQ(a32: number, b32: number, Qres: number): number local a_headrm = clz32(math.abs(a32)) - 1 local a32_nrm = a32 * p2(a_headrm) local b_headrm = clz32(math.abs(b32)) - 1 local b32_nrm = b32 * p2(b_headrm) local b32_inv = tdiv(536870911, b32_nrm // 65536) local result = (a32_nrm * s16(b32_inv)) // 65536 a32_nrm = i32(a32_nrm - i32(smmul(b32_nrm, result) * 8)) result = result + (a32_nrm * s16(b32_inv)) // 65536 local lshift = 29 + a_headrm - b_headrm - Qres if lshift < 0 then return lshiftSat32(result, -lshift) elseif lshift < 32 then return rshift(result, lshift) end return 0 end local function silkLog2lin(inLog_Q7: number): number if inLog_Q7 < 0 then return 0 elseif inLog_Q7 >= 3967 then return 2147483647 end local out = p2(inLog_Q7 // 128) local frac_Q7 = inLog_Q7 % 128 local t = frac_Q7 + (frac_Q7 * (128 - frac_Q7) * -174) // 65536 if inLog_Q7 < 2048 then out = out + (out * t) // 128 else out = out + (out // 128) * t end return out end local function silkSQRT_APPROX(x: number): number if x <= 0 then return 0 end local lz = clz32(x) local rot = 24 - lz local r if rot == 0 then r = x elseif rot < 0 then r = bit32.lrotate(x, -rot) else r = bit32.rrotate(x, rot) end local frac_Q7 = bit32.band(r, 0x7f) local y = if bit32.band(lz, 1) ~= 0 then 32768 else 46214 y = y // p2(lz // 2) y = y + (y * (213 * frac_Q7)) // 65536 return y end -- silk_sum_sqr_shift: energy, shift local function sumSqrShift(x: { number }, xo: number, len: number): (number, number) local shft = 31 - clz32(len) local nrg = len local i = 0 while i < len - 1 do local a, b = x[xo + i], x[xo + i + 1] nrg = i32(nrg + rshift(a * a + b * b, shft)) i += 2 end if i < len then local a = x[xo + i] nrg = i32(nrg + rshift(a * a, shft)) end shft = math.max(0, shft + 3 - clz32(nrg)) nrg = 0 i = 0 while i < len - 1 do local a, b = x[xo + i], x[xo + i + 1] nrg = i32(nrg + rshift(a * a + b * b, shft)) i += 2 end if i < len then local a = x[xo + i] nrg = i32(nrg + rshift(a * a, shft)) end return nrg, shft end -- LPC helpers --------------------------------------------------------------------------------------------------- -- silk_bwexpander (int16 coefficients), ar 1-based local function bwexpander(ar: { number }, d: number, chirp_Q16: number) local chirp_minus_one_Q16 = chirp_Q16 - 65536 for i = 1, d - 1 do ar[i] = s16((chirp_Q16 * ar[i] + 32768) // 65536) chirp_Q16 += (chirp_Q16 * chirp_minus_one_Q16 + 32768) // 65536 end ar[d] = s16((chirp_Q16 * ar[d] + 32768) // 65536) end local function bwexpander32(ar: { number }, d: number, chirp_Q16: number) local chirp_minus_one_Q16 = chirp_Q16 - 65536 for i = 1, d - 1 do ar[i] = i32(mulww(chirp_Q16, ar[i])) chirp_Q16 += (chirp_Q16 * chirp_minus_one_Q16 + 32768) // 65536 end ar[d] = i32(mulww(chirp_Q16, ar[d])) end -- silk_LPC_fit: a_QIN (int32, QIN) -> a_QOUT (int16, QOUT) local function lpcFit(a_QOUT: { number }, a_QIN: { number }, QOUT: number, QIN: number, d: number) local sh = QIN - QOUT local idx = 0 local i = 0 while i < 10 do local maxabs = 0 for k = 1, d do local absval = math.abs(a_QIN[k]) if absval > maxabs then maxabs = absval idx = k - 1 end end maxabs = rround(maxabs, sh) if maxabs > 32767 then maxabs = math.min(maxabs, 163838) local chirp_Q16 = 65470 - tdiv((maxabs - 32767) * 16384, (maxabs * (idx + 1)) // 4) bwexpander32(a_QIN, d, chirp_Q16) else break end i += 1 end if i == 10 then for k = 1, d do a_QOUT[k] = sat16(rround(a_QIN[k], sh)) a_QIN[k] = a_QOUT[k] * P2[sh] end else for k = 1, d do a_QOUT[k] = s16(rround(a_QIN[k], sh)) end end end local A_LIMIT = 16773022 local INV_GAIN_MIN = 107374 local Atmp_QA = table.create(16, 0) -- RSHIFT_ROUND64(SMULL(a, b), Q) local function mulRound(a: number, b: number, Q: number): number if Q == 1 then local p = a * b return p // 2 + p % 2 end if Q - 1 >= 16 then return (mulshr(a, b, Q - 1) + 1) // 2 end return ((a * b) // P2[Q - 1] + 1) // 2 end local function lpcInversePredGainQA(A_QA: { number }, order: number): number local invGain_Q30 = 1073741824 local k = order - 1 while k > 0 do local ak = A_QA[k + 1] if ak > A_LIMIT or ak < -A_LIMIT then return 0 end local rc_Q31 = -(ak * 128) local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 if invGain_Q30 < INV_GAIN_MIN then return 0 end local mult2Q = 32 - clz32(math.abs(rc_mult1_Q30)) local rc_mult2 = silkINVERSE32_varQ(rc_mult1_Q30, mult2Q + 30) for n = 0, (k + 1) // 2 - 1 do local tmp1 = A_QA[n + 1] local tmp2 = A_QA[k - n] local t64 = mulRound(subSat32(tmp1, mulRound(tmp2, rc_Q31, 31)), rc_mult2, mult2Q) if t64 > 2147483647 or t64 < -2147483648 then return 0 end A_QA[n + 1] = t64 t64 = mulRound(subSat32(tmp2, mulRound(tmp1, rc_Q31, 31)), rc_mult2, mult2Q) if t64 > 2147483647 or t64 < -2147483648 then return 0 end A_QA[k - n] = t64 end k -= 1 end local a0 = A_QA[1] if a0 > A_LIMIT or a0 < -A_LIMIT then return 0 end local rc_Q31 = -(a0 * 128) local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 if invGain_Q30 < INV_GAIN_MIN then return 0 end return invGain_Q30 end local function lpcInversePredGain(A_Q12: { number }, order: number): number local DC_resp = 0 for k = 1, order do DC_resp += A_Q12[k] Atmp_QA[k] = A_Q12[k] * 4096 end if DC_resp >= 4096 then return 0 end return lpcInversePredGainQA(Atmp_QA, order) end local ordering16 = { 0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1 } local ordering10 = { 0, 9, 6, 3, 4, 5, 8, 1, 2, 7 } local cos_LSF_QA = table.create(16, 0) local polyP = table.create(9, 0) local polyQ = table.create(9, 0) local a32_QA1 = table.create(16, 0) local LSFCos = T.LSFCosTab_FIX_Q12 -- out[0..dd] (1-based storage), from interleaved cLSF starting at C index c0 local function findPoly(out: { number }, cLSF: { number }, c0: number, dd: number) out[1] = 65536 out[2] = -cLSF[c0 + 1] for k = 1, dd - 1 do local ftmp = cLSF[c0 + 2 * k + 1] out[k + 2] = out[k] * 2 - (ftmp * out[k + 1] + 32768) // 65536 for n = k, 2, -1 do out[n + 1] += out[n - 1] - (ftmp * out[n] + 32768) // 65536 end out[2] -= ftmp end end -- silk_NLSF2A: a_Q12 (1-based, d entries) from NLSF (1-based) local function nlsf2a(a_Q12: { number }, NLSF: { number }, d: number) local ordering = if d == 16 then ordering16 else ordering10 for k = 1, d do local nl = NLSF[k] local f_int = nl // 256 local f_frac = nl - f_int * 256 local cos_val = LSFCos[f_int + 1] local delta = LSFCos[f_int + 2] - cos_val cos_LSF_QA[ordering[k] + 1] = (cos_val * 256 + delta * f_frac + 8) // 16 end local dd = d // 2 findPoly(polyP, cos_LSF_QA, 0, dd) findPoly(polyQ, cos_LSF_QA, 1, dd) for k = 0, dd - 1 do local Ptmp = polyP[k + 2] + polyP[k + 1] local Qtmp = polyQ[k + 2] - polyQ[k + 1] a32_QA1[k + 1] = -Qtmp - Ptmp a32_QA1[d - k] = Qtmp - Ptmp end lpcFit(a_Q12, a32_QA1, 12, 17, d) local i = 0 while lpcInversePredGain(a_Q12, d) == 0 and i < 16 do bwexpander32(a32_QA1, d, 65536 - P2[i + 1]) for k = 1, d do a_Q12[k] = s16((a32_QA1[k] + 16) // 32) end i += 1 end end -- silk_LPC_analysis_filter: out[oo + ix] for ix in [0, len), from inp[io + ix]; B 1-based Q12 local function lpcAnalysisFilter(out: { number }, oo: number, inp: { number }, io: number, B: { number }, len: number, d: number) for ix = d, len - 1 do local base = io + ix - 1 local acc = 0 for j = 0, d - 1 do acc += inp[base - j] * B[j + 1] end local out32_Q12 = i32(inp[base + 1] * 4096 - acc) out[oo + ix] = sat16((out32_Q12 + 2048) // 4096) end for j = 0, d - 1 do out[oo + j] = 0 end end -- NLSF ---------------------------------------------------------------------------------------------------------- local CB_NB_MB = { nVectors = 32, order = 10, quantStepSize_Q16 = 11796, CB1_NLSF_Q8 = T.NLSF_CB1_NB_MB_Q8, CB1_Wght_Q9 = T.NLSF_CB1_Wght_Q9, CB1_iCDF = T.NLSF_CB1_iCDF_NB_MB, pred_Q8 = T.NLSF_PRED_NB_MB_Q8, ec_sel = T.NLSF_CB2_SELECT_NB_MB, ec_iCDF = T.NLSF_CB2_iCDF_NB_MB, deltaMin_Q15 = T.NLSF_DELTA_MIN_NB_MB_Q15, } local CB_WB = { nVectors = 32, order = 16, quantStepSize_Q16 = 9830, CB1_NLSF_Q8 = T.NLSF_CB1_WB_Q8, CB1_Wght_Q9 = T.NLSF_CB1_WB_Wght_Q9, CB1_iCDF = T.NLSF_CB1_iCDF_WB, pred_Q8 = T.NLSF_PRED_WB_Q8, ec_sel = T.NLSF_CB2_SELECT_WB, ec_iCDF = T.NLSF_CB2_iCDF_WB, deltaMin_Q15 = T.NLSF_DELTA_MIN_WB_Q15, } local ec_ix = table.create(16, 0) local pred_Q8 = table.create(16, 0) local res_Q10 = table.create(16, 0) local function nlsfUnpack(CB: any, CB1_index: number) local order = CB.order local sel = CB.ec_sel local pq = CB.pred_Q8 local p = CB1_index * order // 2 for i = 0, order - 1, 2 do p += 1 local entry = sel[p] ec_ix[i + 1] = (bit32.band(entry // 2, 7)) * 9 pred_Q8[i + 1] = pq[i + bit32.band(entry, 1) * (order - 1) + 1] ec_ix[i + 2] = (bit32.band(entry // 32, 7)) * 9 pred_Q8[i + 2] = pq[i + bit32.band(entry // 16, 1) * (order - 1) + 2] end end local function nlsfStabilize(NLSF: { number }, NDeltaMin: { number }, L: number) local loops = 0 while loops < 20 do local min_diff = NLSF[1] - NDeltaMin[1] local I = 0 for i = 1, L - 1 do local diff = NLSF[i + 1] - (NLSF[i] + NDeltaMin[i + 1]) if diff < min_diff then min_diff = diff I = i end end local diff = 32768 - (NLSF[L] + NDeltaMin[L + 1]) if diff < min_diff then min_diff = diff I = L end if min_diff >= 0 then return end if I == 0 then NLSF[1] = NDeltaMin[1] elseif I == L then NLSF[L] = 32768 - NDeltaMin[L + 1] else local min_center = 0 for k = 0, I - 1 do min_center += NDeltaMin[k + 1] end min_center += NDeltaMin[I + 1] // 2 local max_center = 32768 for k = L, I + 1, -1 do max_center -= NDeltaMin[k + 1] end max_center -= NDeltaMin[I + 1] // 2 local c = (NLSF[I] + NLSF[I + 1] + 1) // 2 -- silk_LIMIT_32(c, min_center, max_center) if min_center > max_center then if c > min_center then c = min_center elseif c < max_center then c = max_center end else if c > max_center then c = max_center elseif c < min_center then c = min_center end end c = s16(c) NLSF[I] = s16(c - NDeltaMin[I + 1] // 2) NLSF[I + 1] = s16(NLSF[I] + NDeltaMin[I + 1]) end loops += 1 end -- fall back: insertion sort, then clamp for i = 2, L do local value = NLSF[i] local j = i - 1 while j >= 1 and value < NLSF[j] do NLSF[j + 1] = NLSF[j] j -= 1 end NLSF[j + 1] = value end NLSF[1] = math.max(NLSF[1], NDeltaMin[1]) for i = 2, L do NLSF[i] = math.max(NLSF[i], sat16(NLSF[i - 1] + NDeltaMin[i])) end NLSF[L] = math.min(NLSF[L], 32768 - NDeltaMin[L + 1]) for i = L - 1, 1, -1 do NLSF[i] = math.min(NLSF[i], NLSF[i + 1] - NDeltaMin[i + 1]) end end -- silk_NLSF_decode: pNLSF_Q15 (1-based) from indices (1-based: [1] = CB1 index) local function nlsfDecode(pNLSF_Q15: { number }, NLSFIndices: { number }, CB: any) nlsfUnpack(CB, NLSFIndices[1]) local order = CB.order local step = CB.quantStepSize_Q16 local out_Q10 = 0 for i = order - 1, 0, -1 do local pred = (out_Q10 * pred_Q8[i + 1]) // 256 out_Q10 = NLSFIndices[i + 2] * 1024 if out_Q10 > 0 then out_Q10 -= 102 elseif out_Q10 < 0 then out_Q10 += 102 end out_Q10 = pred + (out_Q10 * step) // 65536 res_Q10[i + 1] = out_Q10 end local base = NLSFIndices[1] * order local cb, w = CB.CB1_NLSF_Q8, CB.CB1_Wght_Q9 for i = 1, order do local v = tdiv(res_Q10[i] * 16384, w[base + i]) + cb[base + i] * 128 if v < 0 then v = 0 elseif v > 32767 then v = 32767 end pNLSF_Q15[i] = v end nlsfStabilize(pNLSF_Q15, CB.deltaMin_Q15, order) end -- Resampler (decoder side: 8 / 12 / 16 kHz up to the API rate) ---------------------------------------------------- local RES_COPY, RES_UP2, RES_IIR_FIR = 0, 1, 2 local up2_hq_0 = { 1746, 14986, 39083 - 65536 } local up2_hq_1 = { 6854, 25769, 55542 - 65536 } local FIR12 = T.resampler_frac_FIR_12 local delay_matrix_dec = { { 4, 0, 2, 0, 0, 0 }, { 0, 9, 4, 7, 4, 4 }, { 0, 3, 12, 7, 7, 7 }, } local function rateID(R: number): number local a = R // 4096 - (if R > 16000 then 1 else 0) if R > 24000 then a = a // 2 end return math.min(5, a - 1) end local function newResampler(): any return { sIIR = table.create(6, 0), sFIR = table.create(8, 0), delayBuf = table.create(96, 0), buf = table.create(2 * 160 + 8, 0), resampler_function = RES_COPY, batchSize = 0, invRatio_Q16 = 0, inputDelay = 0, Fs_in_kHz = 0, Fs_out_kHz = 0, } end local function copyResampler(dst: any, src: any) for i = 1, 6 do dst.sIIR[i] = src.sIIR[i] end for i = 1, 8 do dst.sFIR[i] = src.sFIR[i] end for i = 1, 96 do dst.delayBuf[i] = src.delayBuf[i] end dst.resampler_function = src.resampler_function dst.batchSize = src.batchSize dst.invRatio_Q16 = src.invRatio_Q16 dst.inputDelay = src.inputDelay dst.Fs_in_kHz = src.Fs_in_kHz dst.Fs_out_kHz = src.Fs_out_kHz end local function resamplerInit(S: any, Fs_Hz_in: number, Fs_Hz_out: number): number table.clear(S.sIIR) table.clear(S.sFIR) table.clear(S.delayBuf) for i = 1, 6 do S.sIIR[i] = 0 end for i = 1, 8 do S.sFIR[i] = 0 end for i = 1, 96 do S.delayBuf[i] = 0 end if (Fs_Hz_in ~= 8000 and Fs_Hz_in ~= 12000 and Fs_Hz_in ~= 16000) or Fs_Hz_out < Fs_Hz_in then return -1 -- the decoder only upsamples (or copies) end S.inputDelay = delay_matrix_dec[rateID(Fs_Hz_in) + 1][rateID(Fs_Hz_out) + 1] or 0 S.Fs_in_kHz = Fs_Hz_in // 1000 S.Fs_out_kHz = Fs_Hz_out // 1000 S.batchSize = S.Fs_in_kHz * 10 local up2x = 0 if Fs_Hz_out > Fs_Hz_in then if Fs_Hz_out == Fs_Hz_in * 2 then S.resampler_function = RES_UP2 else S.resampler_function = RES_IIR_FIR up2x = 1 end else S.resampler_function = RES_COPY end local inv = (Fs_Hz_in * p2(14 + up2x)) // Fs_Hz_out * 4 while mulww(inv, Fs_Hz_out) < Fs_Hz_in * p2(up2x) do inv += 1 end S.invRatio_Q16 = inv return 0 end -- silk_resampler_private_up2_HQ: out[oo + 2k], out[oo + 2k + 1] from inp[io + k] local function up2HQ(S: { number }, out: { number }, oo: number, inp: { number }, io: number, len: number) local s0, s1, s2, s3, s4, s5 = S[1], S[2], S[3], S[4], S[5], S[6] local c00, c01, c02 = up2_hq_0[1], up2_hq_0[2], up2_hq_0[3] local c10, c11, c12 = up2_hq_1[1], up2_hq_1[2], up2_hq_1[3] for k = 0, len - 1 do local in32 = inp[io + k] * 1024 local Y = in32 - s0 local X = (Y * c00) // 65536 local out32_1 = s0 + X s0 = in32 + X Y = out32_1 - s1 X = (Y * c01) // 65536 local out32_2 = s1 + X s1 = out32_1 + X Y = out32_2 - s2 X = Y + (Y * c02) // 65536 out32_1 = s2 + X s2 = out32_2 + X out[oo + 2 * k] = sat16((out32_1 + 512) // 1024) Y = in32 - s3 X = (Y * c10) // 65536 out32_1 = s3 + X s3 = in32 + X Y = out32_1 - s4 X = (Y * c11) // 65536 out32_2 = s4 + X s4 = out32_1 + X Y = out32_2 - s5 X = Y + (Y * c12) // 65536 out32_1 = s5 + X s5 = out32_2 + X out[oo + 2 * k + 1] = sat16((out32_1 + 512) // 1024) end S[1], S[2], S[3], S[4], S[5], S[6] = s0, s1, s2, s3, s4, s5 end -- returns the next output index local function iirFirInterpol(out: { number }, oo: number, buf: { number }, max_index_Q16: number, incr: number): number local index_Q16 = 0 while index_Q16 < max_index_Q16 do local ti = ((index_Q16 % 65536) * 12) // 65536 local b = index_Q16 // 65536 + 1 -- buf is 1-based local f0 = ti * 4 local f1 = (11 - ti) * 4 local res_Q15 = buf[b] * FIR12[f0 + 1] + buf[b + 1] * FIR12[f0 + 2] + buf[b + 2] * FIR12[f0 + 3] + buf[b + 3] * FIR12[f0 + 4] + buf[b + 4] * FIR12[f1 + 4] + buf[b + 5] * FIR12[f1 + 3] + buf[b + 6] * FIR12[f1 + 2] + buf[b + 7] * FIR12[f1 + 1] out[oo] = sat16((res_Q15 + 16384) // 32768) oo += 1 index_Q16 += incr end return oo end local function iirFir(S: any, out: { number }, oo: number, inp: { number }, io: number, inLen: number) local buf = S.buf local sFIR = S.sFIR for i = 1, 8 do buf[i] = sFIR[i] end local incr = S.invRatio_Q16 local nSamplesIn while true do nSamplesIn = math.min(inLen, S.batchSize) up2HQ(S.sIIR, buf, 9, inp, io, nSamplesIn) oo = iirFirInterpol(out, oo, buf, nSamplesIn * 131072, incr) io += nSamplesIn inLen -= nSamplesIn if inLen > 0 then local o = nSamplesIn * 2 for i = 1, 8 do buf[i] = buf[o + i] end else break end end local o = nSamplesIn * 2 for i = 1, 8 do sFIR[i] = buf[o + i] end end local function resampleBlock(S: any, out: { number }, oo: number, inp: { number }, io: number, len: number) local f = S.resampler_function if f == RES_IIR_FIR then iirFir(S, out, oo, inp, io, len) elseif f == RES_UP2 then up2HQ(S.sIIR, out, oo, inp, io, len) else for i = 0, len - 1 do out[oo + i] = inp[io + i] end end end -- silk_resampler: out[1..] from inp[io .. io + inLen - 1] local function resampler(S: any, out: { number }, inp: { number }, io: number, inLen: number) local fin = S.Fs_in_kHz local delay = S.inputDelay local nSamples = fin - delay local db = S.delayBuf for i = 0, nSamples - 1 do db[delay + i + 1] = inp[io + i] end resampleBlock(S, out, 1, db, 1, fin) resampleBlock(S, out, 1 + S.Fs_out_kHz, inp, io + nSamples, inLen - fin) for i = 0, delay - 1 do db[i + 1] = inp[io + inLen - delay + i] end end -- Decoder state ------------------------------------------------------------------------------------------------- local function newChannel(): any return { prev_gain_Q16 = 65536, exc_Q14 = table.create(320, 0), sLPC_Q14_buf = table.create(16, 0), outBuf = table.create(480, 0), lagPrev = 0, LastGainIndex = 0, fs_kHz = 0, fs_API_hz = 0, nb_subfr = 0, frame_length = 0, subfr_length = 0, ltp_mem_length = 0, LPC_order = 0, prevNLSF_Q15 = table.create(16, 0), first_frame_after_reset = 1, pitch_lag_low_bits_iCDF = T.uniform4_iCDF, pitch_contour_iCDF = T.pitch_contour_iCDF, nFramesDecoded = 0, nFramesPerPacket = 0, ec_prevSignalType = 0, ec_prevLagIndex = 0, VAD_flags = { 0, 0, 0 }, LBRR_flag = 0, LBRR_flags = { 0, 0, 0 }, resampler_state = newResampler(), psNLSF_CB = CB_NB_MB, indices = { signalType = 0, quantOffsetType = 0, GainsIndices = { 0, 0, 0, 0 }, NLSFIndices = table.create(17, 0), NLSFInterpCoef_Q2 = 0, lagIndex = 0, contourIndex = 0, PERIndex = 0, LTPIndex = { 0, 0, 0, 0 }, LTP_scaleIndex = 0, Seed = 0, }, sCNG = { CNG_exc_buf_Q14 = table.create(320, 0), CNG_smth_NLSF_Q15 = table.create(16, 0), CNG_synth_state = table.create(16, 0), CNG_smth_Gain_Q16 = 0, rand_seed = 3176576, fs_kHz = 0, }, lossCnt = 0, prevSignalType = 0, sPLC = { pitchL_Q8 = 0, LTPCoef_Q14 = table.create(5, 0), prevLPC_Q12 = table.create(16, 0), last_frame_lost = 0, rand_seed = 0, randScale_Q14 = 0, conc_energy = 0, conc_energy_shift = 0, prevLTP_scale_Q14 = 0, prevGain_Q16 = { 65536, 65536 }, fs_kHz = 0, nb_subfr = 2, subfr_length = 20, }, -- per-frame decoder control (silk_decoder_control) and scratch ctrl = { pitchL = { 0, 0, 0, 0 }, Gains_Q16 = { 0, 0, 0, 0 }, PredCoef_Q12 = { table.create(16, 0), table.create(16, 0) }, LTPCoef_Q14 = table.create(20, 0), LTP_scale_Q14 = 0, }, pulses = table.create(336, 0), out = table.create(322, 0), -- samplesOut1_tmp: [1], [2] = the 2 buffered samples, frame from [3] } end local function decoderSetFs(ch: any, fs_kHz: number, fs_API_Hz: number): number local ret = 0 ch.subfr_length = 5 * fs_kHz local frame_length = ch.nb_subfr * ch.subfr_length if ch.fs_kHz ~= fs_kHz or ch.fs_API_hz ~= fs_API_Hz then ret += resamplerInit(ch.resampler_state, fs_kHz * 1000, fs_API_Hz) ch.fs_API_hz = fs_API_Hz end if ch.fs_kHz ~= fs_kHz or frame_length ~= ch.frame_length then if fs_kHz == 8 then ch.pitch_contour_iCDF = if ch.nb_subfr == 4 then T.pitch_contour_NB_iCDF else T.pitch_contour_10_ms_NB_iCDF else ch.pitch_contour_iCDF = if ch.nb_subfr == 4 then T.pitch_contour_iCDF else T.pitch_contour_10_ms_iCDF end if ch.fs_kHz ~= fs_kHz then ch.ltp_mem_length = 20 * fs_kHz if fs_kHz == 8 or fs_kHz == 12 then ch.LPC_order = 10 ch.psNLSF_CB = CB_NB_MB else ch.LPC_order = 16 ch.psNLSF_CB = CB_WB end if fs_kHz == 16 then ch.pitch_lag_low_bits_iCDF = T.uniform8_iCDF elseif fs_kHz == 12 then ch.pitch_lag_low_bits_iCDF = T.uniform6_iCDF else ch.pitch_lag_low_bits_iCDF = T.uniform4_iCDF end ch.first_frame_after_reset = 1 ch.lagPrev = 100 ch.LastGainIndex = 10 ch.prevSignalType = 0 local ob, sl = ch.outBuf, ch.sLPC_Q14_buf for i = 1, 480 do ob[i] = 0 end for i = 1, 16 do sl[i] = 0 end end ch.fs_kHz = fs_kHz ch.frame_length = frame_length end return ret end -- Bitstream: indices and pulses --------------------------------------------------------------------------------- local LTP_gain_iCDF = { T.LTP_gain_iCDF_0, T.LTP_gain_iCDF_1, T.LTP_gain_iCDF_2 } local LTP_vq_Q7 = { T.LTP_gain_vq_0, T.LTP_gain_vq_1, T.LTP_gain_vq_2 } local LBRR_flags_iCDF = { T.LBRR_flags_2_iCDF, T.LBRR_flags_3_iCDF } local function decodeIndices(ch: any, d: any, FrameIndex: number, decode_LBRR: boolean, condCoding: number) local ind = ch.indices local Ix if decode_LBRR or ch.VAD_flags[FrameIndex + 1] ~= 0 then Ix = icdf(d, T.type_offset_VAD_iCDF, 1, 8) + 2 else Ix = icdf(d, T.type_offset_no_VAD_iCDF, 1, 8) end local signalType = Ix // 2 ind.signalType = signalType ind.quantOffsetType = Ix % 2 local gi = ind.GainsIndices if condCoding == 2 then gi[1] = icdf(d, T.delta_gain_iCDF, 1, 8) else gi[1] = icdf(d, T.gain_iCDF, signalType * 8 + 1, 8) * 8 gi[1] += icdf(d, T.uniform8_iCDF, 1, 8) end for i = 2, ch.nb_subfr do gi[i] = icdf(d, T.delta_gain_iCDF, 1, 8) end local CB = ch.psNLSF_CB local ni = ind.NLSFIndices ni[1] = icdf(d, CB.CB1_iCDF, (signalType // 2) * CB.nVectors + 1, 8) nlsfUnpack(CB, ni[1]) for i = 1, CB.order do Ix = icdf(d, CB.ec_iCDF, ec_ix[i] + 1, 8) if Ix == 0 then Ix -= icdf(d, T.NLSF_EXT_iCDF, 1, 8) elseif Ix == 8 then Ix += icdf(d, T.NLSF_EXT_iCDF, 1, 8) end ni[i + 1] = Ix - 4 end if ch.nb_subfr == 4 then ind.NLSFInterpCoef_Q2 = icdf(d, T.NLSF_interpolation_factor_iCDF, 1, 8) else ind.NLSFInterpCoef_Q2 = 4 end if signalType == 2 then local absolute = true if condCoding == 2 and ch.ec_prevSignalType == 2 then local delta = icdf(d, T.pitch_delta_iCDF, 1, 8) if delta > 0 then ind.lagIndex = s16(ch.ec_prevLagIndex + delta - 9) absolute = false end end if absolute then ind.lagIndex = icdf(d, T.pitch_lag_iCDF, 1, 8) * (ch.fs_kHz // 2) ind.lagIndex += icdf(d, ch.pitch_lag_low_bits_iCDF, 1, 8) end ch.ec_prevLagIndex = ind.lagIndex ind.contourIndex = icdf(d, ch.pitch_contour_iCDF, 1, 8) ind.PERIndex = icdf(d, T.LTP_per_index_iCDF, 1, 8) local tab = LTP_gain_iCDF[ind.PERIndex + 1] for k = 1, ch.nb_subfr do ind.LTPIndex[k] = icdf(d, tab, 1, 8) end if condCoding == 0 then ind.LTP_scaleIndex = icdf(d, T.LTPscale_iCDF, 1, 8) else ind.LTP_scaleIndex = 0 end end ch.ec_prevSignalType = signalType ind.Seed = icdf(d, T.uniform4_iCDF, 1, 8) end local shell0, shell1, shell2, shell3 = T.shell_code_table0, T.shell_code_table1, T.shell_code_table2, T.shell_code_table3 local shellOff = T.shell_code_table_offsets local function split(d: any, p: number, tab: { number }): (number, number) if p > 0 then local a = icdf(d, tab, shellOff[p + 1] + 1, 8) return a, p - a end return 0, 0 end local function shellDecoder(out: { number }, o: number, d: any, pulses4: number) local p3a, p3b = split(d, pulses4, shell3) local p2a, p2b = split(d, p3a, shell2) local p1a, p1b = split(d, p2a, shell1) out[o], out[o + 1] = split(d, p1a, shell0) out[o + 2], out[o + 3] = split(d, p1b, shell0) p1a, p1b = split(d, p2b, shell1) out[o + 4], out[o + 5] = split(d, p1a, shell0) out[o + 6], out[o + 7] = split(d, p1b, shell0) p2a, p2b = split(d, p3b, shell2) p1a, p1b = split(d, p2a, shell1) out[o + 8], out[o + 9] = split(d, p1a, shell0) out[o + 10], out[o + 11] = split(d, p1b, shell0) p1a, p1b = split(d, p2b, shell1) out[o + 12], out[o + 13] = split(d, p1a, shell0) out[o + 14], out[o + 15] = split(d, p1b, shell0) end local sum_pulses = table.create(20, 0) local nLshifts = table.create(20, 0) local signIcdf = { 0, 0 } -- pulses[1 .. frame_length (rounded up to 16)] local function decodePulses(d: any, pulses: { number }, signalType: number, quantOffsetType: number, frame_length: number) local RateLevelIndex = icdf(d, T.rate_levels_iCDF, (signalType // 2) * 9 + 1, 8) local iter = frame_length // 16 if iter * 16 < frame_length then iter += 1 end local ppb = T.pulses_per_block_iCDF for i = 1, iter do nLshifts[i] = 0 local s = icdf(d, ppb, RateLevelIndex * 18 + 1, 8) while s == 17 do nLshifts[i] += 1 s = icdf(d, ppb, 9 * 18 + 1 + (if nLshifts[i] == 10 then 1 else 0), 8) if nLshifts[i] > 30 then break -- corrupt stream guard end end sum_pulses[i] = s end for i = 1, iter do local o = (i - 1) * 16 + 1 if sum_pulses[i] > 0 then shellDecoder(pulses, o, d, sum_pulses[i]) else for k = 0, 15 do pulses[o + k] = 0 end end end local lsb = T.lsb_iCDF for i = 1, iter do local nLS = nLshifts[i] if nLS > 0 then local o = (i - 1) * 16 + 1 for k = 0, 15 do local abs_q = pulses[o + k] for _ = 1, nLS do abs_q = abs_q * 2 + icdf(d, lsb, 1, 8) end pulses[o + k] = abs_q end sum_pulses[i] += nLS * 32 end end -- silk_decode_signs local signTab = T.sign_iCDF local base = 7 * (quantOffsetType + signalType * 2) local blocks = (frame_length + 8) // 16 for i = 1, blocks do local p = sum_pulses[i] if p > 0 then signIcdf[1] = signTab[base + math.min(p % 32, 6) + 1] local o = (i - 1) * 16 + 1 for j = 0, 15 do local q = pulses[o + j] if q > 0 then pulses[o + j] = q * (icdf(d, signIcdf, 1, 8) * 2 - 1) end end end end end -- Parameters ---------------------------------------------------------------------------------------------------- local pNLSF_Q15 = table.create(16, 0) local pNLSF0_Q15 = table.create(16, 0) local function gainsDequant(gain_Q16: { number }, ind: { number }, ch: any, conditional: boolean, nb_subfr: number) local prev = ch.LastGainIndex for k = 1, nb_subfr do if k == 1 and not conditional then prev = math.max(ind[k], prev - 16) else local ind_tmp = ind[k] - 4 local thr = 8 + prev if ind_tmp > thr then prev += ind_tmp * 2 - thr else prev += ind_tmp end end if prev < 0 then prev = 0 elseif prev > 63 then prev = 63 end gain_Q16[k] = silkLog2lin(math.min((1907825 * prev) // 65536 + 2090, 3967)) end ch.LastGainIndex = prev end local CB_lags = { [8] = { [4] = { T.CB_lags_stage2, 11 }, [2] = { T.CB_lags_stage2_10_ms, 3 } }, [0] = { [4] = { T.CB_lags_stage3, 34 }, [2] = { T.CB_lags_stage3_10_ms, 12 } }, } local function decodeParameters(ch: any, ctrl: any, condCoding: number) local ind = ch.indices gainsDequant(ctrl.Gains_Q16, ind.GainsIndices, ch, condCoding == 2, ch.nb_subfr) local order = ch.LPC_order nlsfDecode(pNLSF_Q15, ind.NLSFIndices, ch.psNLSF_CB) nlsf2a(ctrl.PredCoef_Q12[2], pNLSF_Q15, order) if ch.first_frame_after_reset == 1 then ind.NLSFInterpCoef_Q2 = 4 end local prevNLSF = ch.prevNLSF_Q15 if ind.NLSFInterpCoef_Q2 < 4 then local c = ind.NLSFInterpCoef_Q2 for i = 1, order do pNLSF0_Q15[i] = prevNLSF[i] + (c * (pNLSF_Q15[i] - prevNLSF[i])) // 4 end nlsf2a(ctrl.PredCoef_Q12[1], pNLSF0_Q15, order) else local a, b = ctrl.PredCoef_Q12[1], ctrl.PredCoef_Q12[2] for i = 1, order do a[i] = b[i] end end for i = 1, order do prevNLSF[i] = pNLSF_Q15[i] end if ch.lossCnt ~= 0 then bwexpander(ctrl.PredCoef_Q12[1], order, 63570) bwexpander(ctrl.PredCoef_Q12[2], order, 63570) end if ind.signalType == 2 then -- silk_decode_pitch local fs = ch.fs_kHz local cbinfo = CB_lags[if fs == 8 then 8 else 0][ch.nb_subfr] local cb, cbk_size = cbinfo[1], cbinfo[2] local min_lag, max_lag = 2 * fs, 18 * fs local lag = min_lag + ind.lagIndex for k = 0, ch.nb_subfr - 1 do local v = lag + cb[k * cbk_size + ind.contourIndex + 1] if v < min_lag then v = min_lag elseif v > max_lag then v = max_lag end ctrl.pitchL[k + 1] = v end local vq = LTP_vq_Q7[ind.PERIndex + 1] for k = 0, ch.nb_subfr - 1 do local Ix = ind.LTPIndex[k + 1] for i = 1, 5 do ctrl.LTPCoef_Q14[k * 5 + i] = vq[Ix * 5 + i] * 128 end end ctrl.LTP_scale_Q14 = T.LTPScales_table_Q14[ind.LTP_scaleIndex + 1] else for k = 1, ch.nb_subfr do ctrl.pitchL[k] = 0 end for k = 1, 5 * ch.nb_subfr do ctrl.LTPCoef_Q14[k] = 0 end ind.PERIndex = 0 ctrl.LTP_scale_Q14 = 0 end end -- Core synthesis ------------------------------------------------------------------------------------------------ local sLTP = table.create(320, 0) local sLTP_Q15 = table.create(640, 0) local res_Q14 = table.create(80, 0) local sLPC_Q14 = table.create(96, 0) local A_Q12_tmp = table.create(16, 0) local QuantOffsets = { { 100, 240 }, { 32, 100 } } -- silk_decode_core: xq[xo .. xo + frame_length - 1] local function decodeCore(ch: any, ctrl: any, xq: { number }, xo: number, pulses: { number }) local ind = ch.indices local exc = ch.exc_Q14 local offset_Q10 = QuantOffsets[ind.signalType // 2 + 1][ind.quantOffsetType + 1] local NLSF_interpolation_flag = ind.NLSFInterpCoef_Q2 < 4 local frame_length = ch.frame_length local subfr_length = ch.subfr_length local ltp_mem_length = ch.ltp_mem_length local order = ch.LPC_order local outBuf = ch.outBuf local rand_seed = ind.Seed for i = 1, frame_length do rand_seed = silkRand(rand_seed) local p = pulses[i] local e = p * 16384 if e > 0 then e -= 1280 elseif e < 0 then e += 1280 end e += offset_Q10 * 16 if rand_seed < 0 then e = -e end exc[i] = e rand_seed = i32(rand_seed + p) end local sl = ch.sLPC_Q14_buf for i = 1, 16 do sLPC_Q14[i] = sl[i] end local pexc = 0 -- C offset into exc local pxq = xo local sLTP_buf_idx = ltp_mem_length -- C index into sLTP_Q15 local lag = 0 for k = 0, ch.nb_subfr - 1 do local A_Q12 = ctrl.PredCoef_Q12[k // 2 + 1] for i = 1, order do A_Q12_tmp[i] = A_Q12[i] end local Bo = k * 5 -- C offset into LTPCoef_Q14 local B = ctrl.LTPCoef_Q14 local signalType = ind.signalType local gain = ctrl.Gains_Q16[k + 1] local Gain_Q10 = gain // 64 local inv_gain_Q31 = silkINVERSE32_varQ(gain, 47) local gain_adj_Q16 if gain ~= ch.prev_gain_Q16 then gain_adj_Q16 = silkDIV32_varQ(ch.prev_gain_Q16, gain, 16) for i = 1, 16 do sLPC_Q14[i] = i32(mulww(gain_adj_Q16, sLPC_Q14[i])) end else gain_adj_Q16 = 65536 end ch.prev_gain_Q16 = gain if ch.lossCnt ~= 0 and ch.prevSignalType == 2 and ind.signalType ~= 2 and k < 2 then for i = 1, 5 do B[Bo + i] = 0 end B[Bo + 3] = 4096 signalType = 2 ctrl.pitchL[k + 1] = ch.lagPrev end if signalType == 2 then lag = ctrl.pitchL[k + 1] if k == 0 or (k == 2 and NLSF_interpolation_flag) then local start_idx = ltp_mem_length - lag - order - 2 if start_idx < 1 then start_idx = 1 -- corrupt stream guard (C asserts start_idx > 0) end if k == 2 then for i = 0, 2 * subfr_length - 1 do outBuf[ltp_mem_length + i + 1] = xq[xo + i] end end lpcAnalysisFilter(sLTP, start_idx + 1, outBuf, start_idx + k * subfr_length + 1, A_Q12, ltp_mem_length - start_idx, order) if k == 0 then inv_gain_Q31 = ((inv_gain_Q31 * ctrl.LTP_scale_Q14) // 65536) * 4 end for i = 0, lag + 1 do sLTP_Q15[sLTP_buf_idx - i] = (inv_gain_Q31 * sLTP[ltp_mem_length - i]) // 65536 end else if gain_adj_Q16 ~= 65536 then for i = 0, lag + 1 do local j = sLTP_buf_idx - i sLTP_Q15[j] = i32(mulww(gain_adj_Q16, sLTP_Q15[j])) end end end end local presArr, presOff if signalType == 2 then local b0, b1, b2, b3, b4 = B[Bo + 1], B[Bo + 2], B[Bo + 3], B[Bo + 4], B[Bo + 5] local pl = sLTP_buf_idx - lag + 2 + 1 -- 1-based index of pred_lag_ptr[0] for i = 1, subfr_length do local pred = 2 pred += (sLTP_Q15[pl] * b0) // 65536 pred += (sLTP_Q15[pl - 1] * b1) // 65536 pred += (sLTP_Q15[pl - 2] * b2) // 65536 pred += (sLTP_Q15[pl - 3] * b3) // 65536 pred += (sLTP_Q15[pl - 4] * b4) // 65536 pl += 1 local r = exc[pexc + i] + pred * 2 res_Q14[i] = r sLTP_buf_idx += 1 sLTP_Q15[sLTP_buf_idx] = r * 2 end presArr, presOff = res_Q14, 0 else presArr, presOff = exc, pexc end local a0, a1, a2, a3, a4, a5, a6, a7, a8, a9 = A_Q12_tmp[1], A_Q12_tmp[2], A_Q12_tmp[3], A_Q12_tmp[4], A_Q12_tmp[5], A_Q12_tmp[6], A_Q12_tmp[7], A_Q12_tmp[8], A_Q12_tmp[9], A_Q12_tmp[10] local wide = order == 16 local a10, a11, a12, a13, a14, a15 = A_Q12_tmp[11], A_Q12_tmp[12], A_Q12_tmp[13], A_Q12_tmp[14], A_Q12_tmp[15], A_Q12_tmp[16] for i = 1, subfr_length do local j = 16 + i -- 1-based index of sLPC_Q14[MAX_LPC_ORDER + i - 1 (C)] + 1 local pred = order // 2 pred += (sLPC_Q14[j - 1] * a0) // 65536 pred += (sLPC_Q14[j - 2] * a1) // 65536 pred += (sLPC_Q14[j - 3] * a2) // 65536 pred += (sLPC_Q14[j - 4] * a3) // 65536 pred += (sLPC_Q14[j - 5] * a4) // 65536 pred += (sLPC_Q14[j - 6] * a5) // 65536 pred += (sLPC_Q14[j - 7] * a6) // 65536 pred += (sLPC_Q14[j - 8] * a7) // 65536 pred += (sLPC_Q14[j - 9] * a8) // 65536 pred += (sLPC_Q14[j - 10] * a9) // 65536 if wide then pred += (sLPC_Q14[j - 11] * a10) // 65536 pred += (sLPC_Q14[j - 12] * a11) // 65536 pred += (sLPC_Q14[j - 13] * a12) // 65536 pred += (sLPC_Q14[j - 14] * a13) // 65536 pred += (sLPC_Q14[j - 15] * a14) // 65536 pred += (sLPC_Q14[j - 16] * a15) // 65536 end pred = i32(pred) local v = addSat32(presArr[presOff + i], lshiftSat32(pred, 4)) sLPC_Q14[j] = v xq[pxq + i - 1] = sat16((mulww(v, Gain_Q10) + 128) // 256) end for i = 1, 16 do sLPC_Q14[i] = sLPC_Q14[subfr_length + i] end pexc += subfr_length pxq += subfr_length end for i = 1, 16 do sl[i] = sLPC_Q14[i] end end -- PLC / CNG ----------------------------------------------------------------------------------------------------- local HARM_ATT_Q15 = { 32440, 31130 } local PLC_RAND_ATTENUATE_V_Q15 = { 31130, 26214 } local PLC_RAND_ATTENUATE_UV_Q15 = { 32440, 29491 } local function plcReset(ch: any) local plc = ch.sPLC plc.pitchL_Q8 = ch.frame_length * 128 plc.prevGain_Q16[1] = 65536 plc.prevGain_Q16[2] = 65536 plc.subfr_length = 20 plc.nb_subfr = 2 end local function cngReset(ch: any) local step = tdiv(32767, ch.LPC_order + 1) local acc = 0 local cng = ch.sCNG for i = 1, ch.LPC_order do acc += step cng.CNG_smth_NLSF_Q15[i] = acc end cng.CNG_smth_Gain_Q16 = 0 cng.rand_seed = 3176576 end local function plcUpdate(ch: any, ctrl: any) local plc = ch.sPLC local nb = ch.nb_subfr ch.prevSignalType = ch.indices.signalType local LTP_Gain_Q14 = 0 local coef = plc.LTPCoef_Q14 if ch.indices.signalType == 2 then local j = 0 while j * ch.subfr_length < ctrl.pitchL[nb] do if j == nb then break end local t = 0 local o = (nb - 1 - j) * 5 for i = 1, 5 do t += ctrl.LTPCoef_Q14[o + i] end if t > LTP_Gain_Q14 then LTP_Gain_Q14 = t for i = 1, 5 do coef[i] = ctrl.LTPCoef_Q14[o + i] end plc.pitchL_Q8 = ctrl.pitchL[nb - j] * 256 end j += 1 end for i = 1, 5 do coef[i] = 0 end coef[3] = LTP_Gain_Q14 if LTP_Gain_Q14 < 11469 then local scale_Q10 = tdiv(11469 * 1024, math.max(LTP_Gain_Q14, 1)) for i = 1, 5 do coef[i] = (s16(coef[i]) * s16(scale_Q10)) // 1024 end elseif LTP_Gain_Q14 > 15565 then local scale_Q14 = tdiv(15565 * 16384, math.max(LTP_Gain_Q14, 1)) for i = 1, 5 do coef[i] = (s16(coef[i]) * s16(scale_Q14)) // 16384 end end else plc.pitchL_Q8 = ch.fs_kHz * 18 * 256 for i = 1, 5 do coef[i] = 0 end end local p = ctrl.PredCoef_Q12[2] for i = 1, ch.LPC_order do plc.prevLPC_Q12[i] = p[i] end plc.prevLTP_scale_Q14 = ctrl.LTP_scale_Q14 plc.prevGain_Q16[1] = ctrl.Gains_Q16[nb - 1] plc.prevGain_Q16[2] = ctrl.Gains_Q16[nb] plc.subfr_length = ch.subfr_length plc.nb_subfr = nb end local excBuf = table.create(160, 0) local plcLTP = table.create(320, 0) local plcLTP_Q14 = table.create(640, 0) local A_plc = table.create(16, 0) local function plcConceal(ch: any, ctrl: any, frame: { number }, fo: number) local plc = ch.sPLC local ltp_mem_length = ch.ltp_mem_length local order = ch.LPC_order local prevGain_Q10_0 = plc.prevGain_Q16[1] // 64 local prevGain_Q10_1 = plc.prevGain_Q16[2] // 64 if ch.first_frame_after_reset ~= 0 then for i = 1, 16 do plc.prevLPC_Q12[i] = 0 end end -- silk_PLC_energy local sl, nb = ch.subfr_length, ch.nb_subfr local exc = ch.exc_Q14 for k = 0, 1 do local g = if k == 0 then prevGain_Q10_0 else prevGain_Q10_1 for i = 0, sl - 1 do excBuf[k * sl + i + 1] = sat16(i32(mulww(exc[i + (k + nb - 2) * sl + 1], g)) // 256) end end local energy1, shift1 = sumSqrShift(excBuf, 1, sl) local energy2, shift2 = sumSqrShift(excBuf, sl + 1, sl) local rand_off -- C offset into exc_Q14 if rshift(energy1, shift2) < rshift(energy2, shift1) then rand_off = math.max(0, (plc.nb_subfr - 1) * plc.subfr_length - 128) else rand_off = math.max(0, plc.nb_subfr * plc.subfr_length - 128) end local B = plc.LTPCoef_Q14 local rand_scale_Q14 = plc.randScale_Q14 local att = math.min(1, ch.lossCnt) + 1 local harm_Gain_Q15 = HARM_ATT_Q15[att] local rand_Gain_Q15 = if ch.prevSignalType == 2 then PLC_RAND_ATTENUATE_V_Q15[att] else PLC_RAND_ATTENUATE_UV_Q15[att] bwexpander(plc.prevLPC_Q12, order, 64881) for i = 1, order do A_plc[i] = plc.prevLPC_Q12[i] end if ch.lossCnt == 0 then rand_scale_Q14 = 16384 if ch.prevSignalType == 2 then for i = 1, 5 do rand_scale_Q14 -= B[i] end rand_scale_Q14 = math.max(3277, s16(rand_scale_Q14)) rand_scale_Q14 = s16((rand_scale_Q14 * s16(plc.prevLTP_scale_Q14)) // 16384) else local invGain_Q30 = lpcInversePredGain(plc.prevLPC_Q12, order) local down = math.min(1073741824 // 8, invGain_Q30) down = math.max(1073741824 // 256, down) down = down * 8 rand_Gain_Q15 = ((down * s16(rand_Gain_Q15)) // 65536) // 16384 end end local rand_seed = plc.rand_seed local lag = (plc.pitchL_Q8 + 128) // 256 local sLTP_buf_idx = ltp_mem_length local idx = ltp_mem_length - lag - order - 2 if idx < 1 then idx = 1 end lpcAnalysisFilter(plcLTP, idx + 1, ch.outBuf, idx + 1, A_plc, ltp_mem_length - idx, order) local inv_gain_Q30 = silkINVERSE32_varQ(plc.prevGain_Q16[2], 46) inv_gain_Q30 = math.min(inv_gain_Q30, 1073741823) for i = idx + order, ltp_mem_length - 1 do plcLTP_Q14[i + 1] = (inv_gain_Q30 * plcLTP[i + 1]) // 65536 end for _ = 0, ch.nb_subfr - 1 do local pl = sLTP_buf_idx - lag + 2 + 1 local b0, b1, b2, b3, b4 = B[1], B[2], B[3], B[4], B[5] for _ = 1, sl do local pred = 2 pred += (plcLTP_Q14[pl] * b0) // 65536 pred += (plcLTP_Q14[pl - 1] * b1) // 65536 pred += (plcLTP_Q14[pl - 2] * b2) // 65536 pred += (plcLTP_Q14[pl - 3] * b3) // 65536 pred += (plcLTP_Q14[pl - 4] * b4) // 65536 pl += 1 rand_seed = silkRand(rand_seed) local ri = (rand_seed // 33554432) % 128 sLTP_buf_idx += 1 plcLTP_Q14[sLTP_buf_idx] = i32((pred + (exc[rand_off + ri + 1] * s16(rand_scale_Q14)) // 65536) * 4) end for j = 1, 5 do B[j] = (harm_Gain_Q15 * s16(B[j])) // 32768 end rand_scale_Q14 = (s16(rand_scale_Q14) * s16(rand_Gain_Q15)) // 32768 plc.pitchL_Q8 = plc.pitchL_Q8 + (plc.pitchL_Q8 * 655) // 65536 plc.pitchL_Q8 = math.min(plc.pitchL_Q8, 18 * ch.fs_kHz * 256) lag = (plc.pitchL_Q8 + 128) // 256 end -- LPC synthesis in place over plcLTP_Q14, starting at C offset ltp_mem_length - 16 local base = ltp_mem_length - 16 -- C offset of sLPC_Q14_ptr local slb = ch.sLPC_Q14_buf for i = 1, 16 do plcLTP_Q14[base + i] = slb[i] end for i = 0, ch.frame_length - 1 do local j = base + 16 + i + 1 -- 1-based index of sLPC_Q14_ptr[16 + i] local pred = order // 2 for t = 1, order do pred += (plcLTP_Q14[j - t] * A_plc[t]) // 65536 end pred = i32(pred) local v = addSat32(plcLTP_Q14[j], lshiftSat32(pred, 4)) plcLTP_Q14[j] = v frame[fo + i] = sat16((mulww(v, prevGain_Q10_1) + 128) // 256) end for i = 1, 16 do slb[i] = plcLTP_Q14[base + ch.frame_length + i] end plc.rand_seed = rand_seed plc.randScale_Q14 = s16(rand_scale_Q14) for i = 1, 4 do ctrl.pitchL[i] = lag end end local function plcGlueFrames(ch: any, frame: { number }, fo: number, length: number) local plc = ch.sPLC if ch.lossCnt ~= 0 then plc.conc_energy, plc.conc_energy_shift = sumSqrShift(frame, fo, length) plc.last_frame_lost = 1 else if plc.last_frame_lost ~= 0 then local energy, energy_shift = sumSqrShift(frame, fo, length) if energy_shift > plc.conc_energy_shift then plc.conc_energy = rshift(plc.conc_energy, energy_shift - plc.conc_energy_shift) elseif energy_shift < plc.conc_energy_shift then energy = rshift(energy, plc.conc_energy_shift - energy_shift) end if energy > plc.conc_energy then local LZ = clz32(plc.conc_energy) - 1 plc.conc_energy = i32(plc.conc_energy * p2(LZ)) energy = rshift(energy, math.max(24 - LZ, 0)) local frac_Q24 = tdiv(plc.conc_energy, math.max(energy, 1)) local gain_Q16 = silkSQRT_APPROX(frac_Q24) * 16 local slope_Q16 = tdiv(65536 - gain_Q16, length) * 4 for i = 0, length - 1 do frame[fo + i] = (gain_Q16 * frame[fo + i]) // 65536 gain_Q16 += slope_Q16 if gain_Q16 > 65536 then break end end end end plc.last_frame_lost = 0 end end local A_cng = table.create(16, 0) local CNG_sig = table.create(336, 0) local function cng(ch: any, ctrl: any, frame: { number }, fo: number, length: number) local c = ch.sCNG if ch.fs_kHz ~= c.fs_kHz then cngReset(ch) c.fs_kHz = ch.fs_kHz end local order = ch.LPC_order if ch.lossCnt == 0 and ch.prevSignalType == 0 then local sm = c.CNG_smth_NLSF_Q15 for i = 1, order do sm[i] += ((ch.prevNLSF_Q15[i] - sm[i]) * 16348) // 65536 end local max_Gain_Q16, subfr = 0, 0 for i = 0, ch.nb_subfr - 1 do if ctrl.Gains_Q16[i + 1] > max_Gain_Q16 then max_Gain_Q16 = ctrl.Gains_Q16[i + 1] subfr = i end end local eb = c.CNG_exc_buf_Q14 local sl = ch.subfr_length for i = (ch.nb_subfr - 1) * sl, 1, -1 do eb[sl + i] = eb[i] end for i = 1, sl do eb[i] = ch.exc_Q14[subfr * sl + i] end for i = 1, ch.nb_subfr do local g = ctrl.Gains_Q16[i] c.CNG_smth_Gain_Q16 += ((g - c.CNG_smth_Gain_Q16) * 4634) // 65536 if mulww(c.CNG_smth_Gain_Q16, 46396) > g then c.CNG_smth_Gain_Q16 = g end end end if ch.lossCnt ~= 0 then local gain_Q16 = i32(mulww(ch.sPLC.randScale_Q14, ch.sPLC.prevGain_Q16[2])) if gain_Q16 >= 2097152 or c.CNG_smth_Gain_Q16 > 8388608 then gain_Q16 = (gain_Q16 // 65536) * (gain_Q16 // 65536) gain_Q16 = i32((c.CNG_smth_Gain_Q16 // 65536) * (c.CNG_smth_Gain_Q16 // 65536) - gain_Q16 * 32) gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 65536) else gain_Q16 = i32(mulww(gain_Q16, gain_Q16)) gain_Q16 = i32(i32(mulww(c.CNG_smth_Gain_Q16, c.CNG_smth_Gain_Q16)) - gain_Q16 * 32) gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 256) end local gain_Q10 = gain_Q16 // 64 -- silk_CNG_exc local exc_mask = 255 while exc_mask > length do exc_mask //= 2 end local seed = c.rand_seed for i = 1, length do seed = silkRand(seed) local idx = bit32.band((seed // 16777216) % 256, exc_mask) CNG_sig[16 + i] = c.CNG_exc_buf_Q14[idx + 1] end c.rand_seed = seed nlsf2a(A_cng, c.CNG_smth_NLSF_Q15, order) for i = 1, 16 do CNG_sig[i] = c.CNG_synth_state[i] end for i = 0, length - 1 do local j = 16 + i + 1 local pred = order // 2 for t = 1, order do pred += (CNG_sig[j - t] * A_cng[t]) // 65536 end pred = i32(pred) local v = addSat32(CNG_sig[j], lshiftSat32(pred, 4)) CNG_sig[j] = v frame[fo + i] = sat16(frame[fo + i] + sat16((mulww(v, gain_Q10) + 128) // 256)) end for i = 1, 16 do c.CNG_synth_state[i] = CNG_sig[length + i] end else for i = 1, order do c.CNG_synth_state[i] = 0 end end end -- Frame decode -------------------------------------------------------------------------------------------------- -- silk_decode_frame: writes frame_length samples to out[fo ..] local function decodeFrame(ch: any, d: any, out: { number }, fo: number, lostFlag: number, condCoding: number): number local L = ch.frame_length local ctrl = ch.ctrl ctrl.LTP_scale_Q14 = 0 if lostFlag == 0 or (lostFlag == 2 and ch.LBRR_flags[ch.nFramesDecoded + 1] == 1) then local pulses = ch.pulses decodeIndices(ch, d, ch.nFramesDecoded, lostFlag ~= 0, condCoding) decodePulses(d, pulses, ch.indices.signalType, ch.indices.quantOffsetType, L) decodeParameters(ch, ctrl, condCoding) decodeCore(ch, ctrl, out, fo, pulses) local mv_len = ch.ltp_mem_length - L local ob = ch.outBuf for i = 1, mv_len do ob[i] = ob[L + i] end for i = 0, L - 1 do ob[mv_len + i + 1] = out[fo + i] end -- silk_PLC (update) if ch.fs_kHz ~= ch.sPLC.fs_kHz then plcReset(ch) ch.sPLC.fs_kHz = ch.fs_kHz end plcUpdate(ch, ctrl) ch.lossCnt = 0 ch.prevSignalType = ch.indices.signalType ch.first_frame_after_reset = 0 else if ch.fs_kHz ~= ch.sPLC.fs_kHz then plcReset(ch) ch.sPLC.fs_kHz = ch.fs_kHz end plcConceal(ch, ctrl, out, fo) ch.lossCnt += 1 local mv_len = ch.ltp_mem_length - L local ob = ch.outBuf for i = 1, mv_len do ob[i] = ob[L + i] end for i = 0, L - 1 do ob[mv_len + i + 1] = out[fo + i] end end cng(ch, ctrl, out, fo, L) plcGlueFrames(ch, out, fo, L) ch.lagPrev = ctrl.pitchL[ch.nb_subfr] return L end -- Stereo -------------------------------------------------------------------------------------------------------- local function stereoDecodePred(d: any, pred_Q13: { number }) local n = icdf(d, T.stereo_pred_joint_iCDF, 1, 8) local ix02 = n // 5 local ix12 = n - 5 * ix02 local ix00 = icdf(d, T.uniform3_iCDF, 1, 8) local ix01 = icdf(d, T.uniform5_iCDF, 1, 8) local ix10 = icdf(d, T.uniform3_iCDF, 1, 8) local ix11 = icdf(d, T.uniform5_iCDF, 1, 8) local q = T.stereo_pred_quant_Q13 for c = 1, 2 do local a = if c == 1 then ix00 + 3 * ix02 else ix10 + 3 * ix12 local b = if c == 1 then ix01 else ix11 local low_Q13 = q[a + 1] local step_Q13 = ((q[a + 2] - low_Q13) * 6554) // 65536 pred_Q13[c] = low_Q13 + s16(step_Q13) * (2 * b + 1) end pred_Q13[1] -= pred_Q13[2] end -- x1, x2: samplesOut1_tmp arrays (C index j at [j + 1]) local function stereoMSToLR(state: any, x1: { number }, x2: { number }, pred_Q13: { number }, fs_kHz: number, frame_length: number) x1[1], x1[2] = state.sMid[1], state.sMid[2] x2[1], x2[2] = state.sSide[1], state.sSide[2] state.sMid[1], state.sMid[2] = x1[frame_length + 1], x1[frame_length + 2] state.sSide[1], state.sSide[2] = x2[frame_length + 1], x2[frame_length + 2] local pred0 = state.pred_prev_Q13[1] local pred1 = state.pred_prev_Q13[2] local interp = 8 * fs_kHz local denom_Q16 = tdiv(65536, interp) local delta0 = (s16(pred_Q13[1] - pred0) * s16(denom_Q16) + 32768) // 65536 local delta1 = (s16(pred_Q13[2] - pred1) * s16(denom_Q16) + 32768) // 65536 for n = 0, frame_length - 1 do if n < interp then pred0 += delta0 pred1 += delta1 elseif n == interp then pred0 = pred_Q13[1] pred1 = pred_Q13[2] end local sum = (x1[n + 1] + x1[n + 3] + x1[n + 2] * 2) * 512 sum = x2[n + 2] * 256 + (sum * s16(pred0)) // 65536 sum = sum + ((x1[n + 2] * 2048) * s16(pred1)) // 65536 x2[n + 2] = sat16((sum + 128) // 256) end if frame_length <= interp then -- the second loop never ran; the C code still ends with pred = pred_Q13 end state.pred_prev_Q13[1] = pred_Q13[1] state.pred_prev_Q13[2] = pred_Q13[2] for n = 0, frame_length - 1 do local a, b = x1[n + 2], x2[n + 2] x1[n + 2] = sat16(a + b) x2[n + 2] = sat16(a - b) end end -- API ----------------------------------------------------------------------------------------------------------- export type State = any function Silk.new(apiChannels: number): State return { ch = { newChannel(), newChannel() }, sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } }, nChannelsAPI = 0, nChannelsInternal = 0, prev_decode_only_middle = 0, MS_pred_Q13 = { 0, 0 }, resampOut = table.create(960, 0), apiChannels = apiChannels, } end -- silk_ResetDecoder (keeps nChannelsAPI / nChannelsInternal, like libopus) function Silk.reset(st: State) st.ch[1] = newChannel() st.ch[2] = newChannel() for _, ch in st.ch do cngReset(ch) plcReset(ch) end st.sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } } st.prev_decode_only_middle = 0 end local function initChannel(st: State, n: number) local ch = newChannel() cngReset(ch) plcReset(ch) st.ch[n] = ch end function Silk.decode(st: State, ctrl: any, lostFlag: number, firstFrame: boolean, d: any, out: { number }, outBase: number): (number, number) local ret = 0 local nInt = ctrl.nChannelsInternal local nAPI = ctrl.nChannelsAPI local chs = st.ch local decode_only_middle = 0 local MS_pred_Q13 = st.MS_pred_Q13 MS_pred_Q13[1], MS_pred_Q13[2] = 0, 0 if nInt ~= 1 and nInt ~= 2 then return -200, 0 end if firstFrame then for n = 1, nInt do chs[n].nFramesDecoded = 0 end end if nInt > st.nChannelsInternal then initChannel(st, 2) end local ch1 = chs[1] local stereo_to_mono = nInt == 1 and st.nChannelsInternal == 2 and ctrl.internalSampleRate == 1000 * ch1.fs_kHz if ch1.nFramesDecoded == 0 then for n = 1, nInt do local ch = chs[n] local ms = ctrl.payloadSize_ms if ms == 0 or ms == 10 then ch.nFramesPerPacket = 1 ch.nb_subfr = 2 elseif ms == 20 then ch.nFramesPerPacket = 1 ch.nb_subfr = 4 elseif ms == 40 then ch.nFramesPerPacket = 2 ch.nb_subfr = 4 elseif ms == 60 then ch.nFramesPerPacket = 3 ch.nb_subfr = 4 else return -203, 0 end local fs_kHz_dec = ctrl.internalSampleRate // 1024 + 1 if fs_kHz_dec ~= 8 and fs_kHz_dec ~= 12 and fs_kHz_dec ~= 16 then return -200, 0 end ret += decoderSetFs(ch, fs_kHz_dec, ctrl.API_sampleRate) end end if nAPI == 2 and nInt == 2 and (st.nChannelsAPI == 1 or st.nChannelsInternal == 1) then local s = st.sStereo s.pred_prev_Q13[1], s.pred_prev_Q13[2] = 0, 0 s.sSide[1], s.sSide[2] = 0, 0 copyResampler(chs[2].resampler_state, ch1.resampler_state) end st.nChannelsAPI = nAPI st.nChannelsInternal = nInt if ctrl.API_sampleRate > 48000 or ctrl.API_sampleRate < 8000 then return -200, 0 end if lostFlag ~= 1 and ch1.nFramesDecoded == 0 then for n = 1, nInt do local ch = chs[n] for i = 1, ch.nFramesPerPacket do ch.VAD_flags[i] = if bitLogp(d, 1) then 1 else 0 end ch.LBRR_flag = if bitLogp(d, 1) then 1 else 0 end for n = 1, nInt do local ch = chs[n] ch.LBRR_flags[1], ch.LBRR_flags[2], ch.LBRR_flags[3] = 0, 0, 0 if ch.LBRR_flag ~= 0 then if ch.nFramesPerPacket == 1 then ch.LBRR_flags[1] = 1 else local sym = icdf(d, LBRR_flags_iCDF[ch.nFramesPerPacket - 1], 1, 8) + 1 for i = 0, ch.nFramesPerPacket - 1 do ch.LBRR_flags[i + 1] = bit32.band(bit32.rshift(sym, i), 1) end end end end if lostFlag == 0 then -- skip all LBRR data for i = 0, ch1.nFramesPerPacket - 1 do for n = 1, nInt do local ch = chs[n] if ch.LBRR_flags[i + 1] ~= 0 then if nInt == 2 and n == 1 then stereoDecodePred(d, MS_pred_Q13) if chs[2].LBRR_flags[i + 1] == 0 then decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) end end local condCoding = if i > 0 and ch.LBRR_flags[i] ~= 0 then 2 else 0 decodeIndices(ch, d, i, true, condCoding) decodePulses(d, ch.pulses, ch.indices.signalType, ch.indices.quantOffsetType, ch.frame_length) end end end end end if nInt == 2 then local fd = ch1.nFramesDecoded if lostFlag == 0 or (lostFlag == 2 and ch1.LBRR_flags[fd + 1] == 1) then stereoDecodePred(d, MS_pred_Q13) if (lostFlag == 0 and chs[2].VAD_flags[fd + 1] == 0) or (lostFlag == 2 and chs[2].LBRR_flags[fd + 1] == 0) then decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) else decode_only_middle = 0 end else MS_pred_Q13[1] = st.sStereo.pred_prev_Q13[1] MS_pred_Q13[2] = st.sStereo.pred_prev_Q13[2] end end if nInt == 2 and decode_only_middle == 0 and st.prev_decode_only_middle == 1 then local c2 = chs[2] for i = 1, 480 do c2.outBuf[i] = 0 end for i = 1, 16 do c2.sLPC_Q14_buf[i] = 0 end c2.lagPrev = 100 c2.LastGainIndex = 10 c2.prevSignalType = 0 c2.first_frame_after_reset = 1 end local has_side if lostFlag == 0 then has_side = decode_only_middle == 0 else has_side = st.prev_decode_only_middle == 0 or (nInt == 2 and lostFlag == 2 and chs[2].LBRR_flags[chs[2].nFramesDecoded + 1] == 1) end local nSamplesOutDec = ch1.frame_length for n = 1, nInt do local ch = chs[n] if n == 1 or has_side then local FrameIndex = ch1.nFramesDecoded - (n - 1) local condCoding if FrameIndex <= 0 then condCoding = 0 elseif lostFlag == 2 then condCoding = if ch.LBRR_flags[FrameIndex] ~= 0 then 2 else 0 elseif n > 1 and st.prev_decode_only_middle ~= 0 then condCoding = 1 else condCoding = 2 end nSamplesOutDec = decodeFrame(ch, d, ch.out, 3, lostFlag, condCoding) else local o = ch.out for i = 3, nSamplesOutDec + 2 do o[i] = 0 end end ch.nFramesDecoded += 1 end local o1 = ch1.out if nAPI == 2 and nInt == 2 then stereoMSToLR(st.sStereo, o1, chs[2].out, MS_pred_Q13, ch1.fs_kHz, nSamplesOutDec) else local sMid = st.sStereo.sMid o1[1], o1[2], sMid[1], sMid[2] = sMid[1], sMid[2], o1[nSamplesOutDec + 1], o1[nSamplesOutDec + 2] end local nSamplesOut = (nSamplesOutDec * ctrl.API_sampleRate) // (ch1.fs_kHz * 1000) local ro = st.resampOut local scale = 1 / 32768 for n = 1, math.min(nAPI, nInt) do resampler(chs[n].resampler_state, ro, chs[n].out, 2, nSamplesOutDec) if nAPI == 2 then local b = outBase + n - 1 for i = 0, nSamplesOut - 1 do out[b + 2 * i] = ro[i + 1] * scale end else for i = 0, nSamplesOut - 1 do out[outBase + i] = ro[i + 1] * scale end end end if nAPI == 2 and nInt == 1 then if stereo_to_mono then resampler(chs[2].resampler_state, ro, o1, 2, nSamplesOutDec) for i = 0, nSamplesOut - 1 do out[outBase + 1 + 2 * i] = ro[i + 1] * scale end else for i = 0, nSamplesOut - 1 do out[outBase + 1 + 2 * i] = out[outBase + 2 * i] end end end if lostFlag == 1 then for i = 1, st.nChannelsInternal do chs[i].LastGainIndex = 10 end else st.prev_decode_only_middle = decode_only_middle end return ret, nSamplesOut end -- the pitch lag of the last frame at 48 kHz (decControl->prevPitchLag), 0 when unvoiced function Silk.prevPitchLag(st: State): number local ch = st.ch[1] if ch.prevSignalType == 2 then local mult = { 6, 4, 3 } return ch.lagPrev * mult[(ch.fs_kHz - 8) // 4 + 1] end return 0 end return Silk