--!strict --!native --!optimize 2 -- audio/opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms frames (LM 3), full band, constant -- bit rate, long MDCTs only (no transient detection), no pitch pre-filter, normal spreading, default allocation trim, -- mono, or stereo as mid / side per band (the angle, intensity when it has no bits; dual L / R stereo on request). The bitstream side is a port of the libopus 1.6 encoder paths -- (celt_encoder.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c; BSD: licenses/libopus-BSD.txt) that -- mirror audio/opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/Mdct. -- Never throws. local RE = require("@formats/audio/opus/RangeEncoder") local T = require("@formats/audio/opus/CeltTables") local Mdct = require("@formats/codecs/Mdct") local CeltEncoder = {} local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift local min, max, sqrt, floor, cos, log, atan2 = math.min, math.max, math.sqrt, math.floor, math.cos, math.log, math.atan2 local encBitLogp, encIcdf, encBits, encUint, encEncode, encEncodeBin = RE.bitLogp, RE.icdf, RE.bits, RE.uint, RE.encode, RE.encodeBin local tell, tellFrac = RE.tell, RE.tellFrac local NB_EBANDS = 21 local OVERLAP = 120 local SHORT_MDCT = 120 local BITRES = 3 local MAX_FINE_BITS = 8 local FINE_OFFSET = 21 local QTHETA_OFFSET = 4 local PREEMPH = 0.85000610 local LM = 3 -- 20 ms frames local M = 8 local N = 960 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, } 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 = { 0, -2, 0, -3, 3, 0, 1, -1 } -- LM 3 local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } local SPREAD_ICDF = { 25, 23, 2, 0 } local SMALL_ENERGY_ICDF = { 2, 1, 0 } local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } local SPREAD_NORMAL = 2 local SPREAD_FACTOR = { 15, 10, 5 } -- the MDCT window (the decoder's) and plan 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 local PLAN = Mdct.new(2 * N) :: Mdct.Plan -- forward scale matching the decoder's backward MDCT (calibrated against audio/opus/Mdct: tests/audio/opus_encode) local MDCT_SCALE = 2 / N -- PVQ codebook sizes U(n, k), flat: U[n * UK + k + 1] 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 local function pvqU(n: number, k: number): number return U[n * UK + k + 1] end 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 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 fracMul16(a: number, b: number): number return (16384 + a * b) // 32768 end local function bitexactCos(x: number): number local x2 = (4096 + x * x) // 8192 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 = RE.ilog(icos) local ls = RE.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 -- ec_laplace_encode: returns the value actually coded (clamped in the flat tail) local function laplaceEncode(enc: RE.Enc, value: number, fs: number, decay: number): number local fl = 0 local val = value if val ~= 0 then local s = if val < 0 then -1 else 0 val = if val < 0 then -val else val fl = fs fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 -- ec_laplace_get_freq1 local i = 1 while fs > 0 and i < val do fs *= 2 fl += fs + 2 fs = (fs * decay) // 32768 i += 1 end if fs == 0 then local ndiMax = 32768 - fl + 1 - 1 ndiMax = rshift(ndiMax - s, 1) local di = imin(val - i, ndiMax - 1) fl += (2 * di + 1 + s) fs = imin(1, 32768 - fl) value = if s ~= 0 then -(i + di) else i + di else fs += 1 if s == 0 then fl += fs end end end encEncodeBin(enc, fl, fl + fs, 15) return value end export type State = { channels: number, oldBandE: { number }, -- the decoder's view (2 * 21) preMem: { number }, inMem: { { number } }, -- the last OVERLAP pre-emphasised samples per channel frames: number, X: { { number } }, -- per channel 960 normalised coefficients bandLogE: { number }, bandE: { number }, -- linear band amplitudes (intensity stereo weights) error: { number }, work: { number }, tmp: { number }, iy: { number }, remaining: number, spread: number, dual: boolean, -- stereo: L / R coded independently (default false: mid / side) } -- new(channels) -> State function CeltEncoder.new(channels: number): State local inMem = {} local X = {} for c = 1, channels do inMem[c] = table.create(OVERLAP, 0) X[c] = table.create(N, 0) end return { channels = channels, oldBandE = table.create(2 * NB_EBANDS, 0), preMem = table.create(channels, 0), inMem = inMem, frames = 0, X = X, bandLogE = table.create(2 * NB_EBANDS, 0), bandE = table.create(2 * NB_EBANDS, 0), error = table.create(2 * NB_EBANDS, 0), work = table.create(2 * N, 0), tmp = table.create(2 * N, 0), iy = table.create(256, 0), remaining = 0, spread = SPREAD_NORMAL, dual = false, } end local function quantCoarseEnergy(st: State, intra: boolean, enc: RE.Enc, C: number, budget: number, nbBytes: number) local oldE, bandLogE, err = st.oldBandE, st.bandLogE, st.error local probBase = LM * 84 + (if intra then 42 else 0) local coef, beta if intra then coef, beta = 0, BETA_INTRA else coef, beta = PRED_COEF[LM + 1], BETA_COEF[LM + 1] end local maxDecay = min(16, nbBytes / 8) local prev0, prev1 = 0, 0 for i = 0, NB_EBANDS - 1 do for c = 0, C - 1 do local k = c * NB_EBANDS + i + 1 local x = bandLogE[k] local e = max(-9, oldE[k]) local prev = if c == 0 then prev0 else prev1 local f = x - coef * e - prev local qi = floor(0.5 + f) local decayBound = max(-28, oldE[k]) - maxDecay if qi < 0 and x < decayBound then qi += tdiv(decayBound - x, 1) if qi > 0 then qi = 0 end end local t = tell(enc) local bitsLeft = budget - t - 3 * C * (NB_EBANDS - i) if i ~= 0 and bitsLeft < 30 then if bitsLeft < 24 then qi = imin(1, qi) end if bitsLeft < 16 then qi = imax(-1, qi) end end if budget - t >= 15 then local pi = 2 * imin(i, 20) qi = laplaceEncode(enc, qi, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) elseif budget - t >= 2 then qi = imax(-1, imin(qi, 1)) encIcdf(enc, if qi < 0 then 1 else 2 * qi, SMALL_ENERGY_ICDF, 2) elseif budget - t >= 1 then qi = imin(0, qi) encBitLogp(enc, qi ~= 0, 1) else qi = -1 end err[k] = f - qi oldE[k] = coef * e + prev + qi prev = prev + qi - beta * qi if c == 0 then prev0 = prev else prev1 = prev end end end end local function quantFineEnergy(st: State, fineQuant: { number }, enc: RE.Enc, C: number) local oldE, err = st.oldBandE, st.error for i = 0, NB_EBANDS - 1 do local extra = fineQuant[i + 1] if extra <= 0 then continue end if tell(enc) + C * extra > enc.storage * 8 then continue end local frac = 2 ^ extra for c = 0, C - 1 do local k = c * NB_EBANDS + i + 1 local q2 = floor((err[k] + 0.5) * frac) q2 = math.clamp(q2, 0, frac - 1) encBits(enc, q2, extra) local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 oldE[k] += offset err[k] -= offset end end end local function quantEnergyFinalise(st: State, fineQuant: { number }, finePriority: { number }, bitsLeft: number, enc: RE.Enc, C: number) local oldE, err = st.oldBandE, st.error for prio = 0, 1 do local i = 0 while i < NB_EBANDS 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 k = c * NB_EBANDS + i + 1 local q2 = if err[k] < 0 then 0 else 1 encBits(enc, q2, 1) local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) oldE[k] += offset err[k] -= offset bitsLeft -= 1 end i += 1 end end end -- ------------------------------------------------------------------------------------------------ allocation 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 (encoder side): keeps every band it can, no intensity stereo, dual stereo for C == 2 local function computeAllocation(offsets: { number }, cap: { number }, allocTrim: number, total: number, pulses: { number }, ebits: { number }, finePriority: { number }, C: number, enc: RE.Enc, wantDual: boolean) local start, endb = 0, NB_EBANDS 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 = {}, {}, {}, {} 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 Nw = EB[j + 2] - EB[j + 1] local bitsj = (C * Nw * 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 Nw = EB[j + 2] - EB[j + 1] local bits1j = (C * Nw * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4 local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * Nw * 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 -- keep every band that can be coded: signal "no more skipping" encBitLogp(enc, true, 1) break 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 = codedBands -- no intensity stereo encUint(enc, intensity - start, codedBands + 1 - start) end if intensity <= start then total += dualStereoRsv dualStereoRsv = 0 end if dualStereoRsv > 0 then dualStereo = wantDual encBitLogp(enc, dualStereo, 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 Nw = N0 * 2 ^ LM local bit = bits[j + 1] + balance local excess if Nw > 1 then excess = imax(bit - cap[j + 1], 0) bits[j + 1] = bit - excess local den = C * Nw + (if C == 2 and Nw > 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 Nw == 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 -- icwrs: the index of the pulse vector iy[1..n] local function icwrs(n: number, iy: { number }): number local j = n -- 1-based position of _y[n - 1] local i = if iy[j] < 0 then 1 else 0 local k = math.abs(iy[j]) repeat j -= 1 local nn = n - (j - 1) -- _n - j with 0-based j i += pvqU(nn, k) k += math.abs(iy[j]) if iy[j] < 0 then i += pvqU(nn, k + 1) end until j <= 1 return i end local function expRotation1(X: { number }, xo: number, len: number, stride: number, c: number, s: number) local ms = -s local p = xo + 1 for _ = 0, len - stride - 1 do local x1 = X[p] local x2 = X[p + stride] X[p + stride] = c * x2 + s * x1 X[p] = c * x1 + ms * x2 p += 1 end p = xo + len - 2 * stride for _ = len - 2 * stride - 1, 0, -1 do local x1 = X[p] local x2 = X[p + stride] X[p + stride] = c * x2 + s * x1 X[p] = c * x1 + ms * x2 p -= 1 end end -- exp_rotation(X, len, dir = 1, stride, K, spread): the encoder's spreading rotation local function expRotation(X: { number }, xo: number, len: 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 = xo + i * len expRotation1(X, x, len, 1, c, -s) if stride2 ~= 0 then expRotation1(X, x, len, stride2, s, -c) end end end -- op_pvq_search: the K-pulse vector closest to X[xo + 1 .. xo + n] into iy[1..n] local function pvqSearch(X: { number }, xo: number, n: number, K: number, iy: { number }, y: { number }, absx: { number }) local sign = y -- reuse: y holds 2 * |pulses| during the search, signs kept in absx's sign local xy, yy = 0, 0 local pulsesLeft = K for j = 1, n do local v = X[xo + j] absx[j] = if v < 0 then -v else v sign[j] = 0 iy[j] = 0 end if K > rshift(n, 1) then local sum = 0 for j = 1, n do sum += absx[j] end if not (sum > 1e-15 and sum < 64) then absx[1] = 1 for j = 2, n do absx[j] = 0 end sum = 1 end local rcp = (K + 0.8) / sum for j = 1, n do local p = floor(rcp * absx[j]) iy[j] = p yy += p * p xy += absx[j] * p sign[j] = 2 * p pulsesLeft -= p end end if pulsesLeft > n + 3 then yy += pulsesLeft * pulsesLeft + pulsesLeft * sign[1] iy[1] += pulsesLeft pulsesLeft = 0 end for _ = 1, pulsesLeft do yy += 1 local best = 1 local rxy = xy + absx[1] local bestNum = rxy * rxy local bestDen = yy + sign[1] for j = 2, n do rxy = xy + absx[j] local num = rxy * rxy local den = yy + sign[j] if bestDen * num > den * bestNum then bestDen, bestNum, best = den, num, j end end xy += absx[best] yy += sign[best] sign[best] += 2 iy[best] += 1 end for j = 1, n do if X[xo + j] < 0 then iy[j] = -iy[j] end end end local SCRATCH_Y = table.create(256, 0) local SCRATCH_A = table.create(256, 0) local ROT = table.create(256, 0) local function algQuant(st: State, X: { number }, xo: number, n: number, K: number, enc: RE.Enc) -- rotate a copy (the original band stays for nothing else, but keep it intact) for j = 1, n do ROT[j] = X[xo + j] end expRotation(ROT, 0, n, 1, K, st.spread) local iy = st.iy pvqSearch(ROT, 0, n, K, iy, SCRATCH_Y, SCRATCH_A) encUint(enc, icwrs(n, iy), pvqU(n, K) + pvqU(n, K + 1)) end -- ------------------------------------------------------------------------------------------------ bands local function computeQn(n: number, b: number, offset: number, pulseCap: number): number local N2 = 2 * n - 1 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 -- quant_partition (encoder, B = 1, mono): returns nothing (no resynthesis) local function quantPartition(st: State, bandI: number, X: { number }, xo: number, n: number, b: number, lm: number, enc: RE.Enc) local split = false if lm ~= -1 and n > 2 then local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 end if split then n = rshift(n, 1) local yo = xo + n lm -= 1 -- compute_theta (mono split, B0 = 1: triangular pdf) local pulseCap = LOGN[bandI + 1] + lm * 8 local offset = (pulseCap // 2) - QTHETA_OFFSET local qn = computeQn(n, b, offset, pulseCap) local t0 = tellFrac(enc) local itheta = 0 if qn ~= 1 then local emid, eside = 1e-15, 1e-15 for j = 1, n do emid += X[xo + j] * X[xo + j] eside += X[yo + j] * X[yo + j] end local it = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) itheta = (it * qn + 8192) // 16384 local h = rshift(qn, 1) local ft = (h + 1) * (h + 1) local fs = if itheta <= h then itheta + 1 else qn + 1 - itheta local fl = if itheta <= h then rshift(itheta * (itheta + 1), 1) else ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) encEncode(enc, fl, fl + fs, ft) itheta = (itheta * 16384) // qn end local qalloc = tellFrac(enc) - t0 b -= qalloc local delta if itheta == 0 then delta = -16384 elseif itheta == 16384 then delta = 16384 else local imid = bitexactCos(itheta) local iside = bitexactCos(16384 - itheta) delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) end local mbits = imax(0, imin(b, tdiv(b - delta, 2))) local sbits = b - mbits st.remaining -= qalloc local rebalance = st.remaining if mbits >= sbits then quantPartition(st, bandI, X, xo, n, mbits, lm, enc) rebalance = mbits - (rebalance - st.remaining) if rebalance > 24 and itheta ~= 0 then sbits += rebalance - 24 end quantPartition(st, bandI, X, yo, n, sbits, lm, enc) else quantPartition(st, bandI, X, yo, n, sbits, lm, enc) rebalance = sbits - (rebalance - st.remaining) if rebalance > 24 and itheta ~= 16384 then mbits += rebalance - 24 end quantPartition(st, bandI, X, xo, n, mbits, lm, enc) end else local q = bits2pulses(bandI, lm, b) local currBits = pulses2bits(bandI, lm, q) st.remaining -= currBits while st.remaining < 0 and q > 0 do st.remaining += currBits q -= 1 currBits = pulses2bits(bandI, lm, q) st.remaining -= currBits end if q ~= 0 then algQuant(st, X, xo, n, getPulses(q), enc) end end end -- quant_band_stereo (encoder, N > 2, B = 1): the mid / side angle (step pdf), then mid and side as mono bands; -- qn == 1 falls back to intensity stereo (with the inversion bit when there is room) local function quantBandStereo(st: State, i: number, n: number, xo: number, b: number, enc: RE.Enc) local L, R = st.X[1], st.X[2] local pulseCap = LOGN[i + 1] + LM * 8 local offset = (pulseCap // 2) - QTHETA_OFFSET local qn = computeQn(n, b, offset, pulseCap) -- stereo_itheta: the angle between mid and side energies local emid, eside = 1e-15, 1e-15 for j = 1, n do local m = 0.5 * L[xo + j] + 0.5 * R[xo + j] local sd = 0.5 * L[xo + j] - 0.5 * R[xo + j] emid += m * m eside += sd * sd end local itheta = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) local t0 = tellFrac(enc) local function intensityStereo() local left, right = st.bandE[i + 1], st.bandE[NB_EBANDS + i + 1] local norm = 1e-15 + sqrt(1e-15 + left * left + right * right) local a1, a2 = left / norm, right / norm for j = 1, n do L[xo + j] = a1 * L[xo + j] + a2 * R[xo + j] end end if qn ~= 1 then itheta = (itheta * qn + 8192) // 16384 local p0 = 3 local x0 = qn // 2 local ft = p0 * (x0 + 1) + x0 if itheta <= x0 then encEncode(enc, p0 * itheta, p0 * (itheta + 1), ft) else encEncode(enc, (itheta - 1 - x0) + (x0 + 1) * p0, (itheta - x0) + (x0 + 1) * p0, ft) end itheta = (itheta * 16384) // qn if itheta == 0 then intensityStereo() else -- stereo_split: mid / side for j = 1, n do local l = 0.70710678 * L[xo + j] local r = 0.70710678 * R[xo + j] L[xo + j] = l + r R[xo + j] = r - l end end else local inv = itheta > 8192 if inv then for j = 1, n do R[xo + j] = -R[xo + j] end end intensityStereo() if b > 16 and st.remaining > 16 then encBitLogp(enc, inv, 2) end itheta = 0 end local qalloc = tellFrac(enc) - t0 b -= qalloc local delta if itheta == 0 then delta = -16384 elseif itheta == 16384 then delta = 16384 else local imid = bitexactCos(itheta) local iside = bitexactCos(16384 - itheta) delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) end local mbits = imax(0, imin(b, tdiv(b - delta, 2))) local sbits = b - mbits st.remaining -= qalloc local rebalance = st.remaining if mbits >= sbits then quantPartition(st, i, L, xo, n, mbits, LM, enc) rebalance = mbits - (rebalance - st.remaining) if rebalance > 24 and itheta ~= 0 then sbits += rebalance - 24 end quantPartition(st, i, R, xo, n, sbits, LM, enc) else quantPartition(st, i, R, xo, n, sbits, LM, enc) rebalance = sbits - (rebalance - st.remaining) if rebalance > 24 and itheta ~= 16384 then mbits += rebalance - 24 end quantPartition(st, i, L, xo, n, mbits, LM, enc) end end -- quant_all_bands (encoder): mono, dual stereo or mid / side stereo local function quantAllBands(st: State, C: number, pulses: { number }, dualStereo: boolean, totalBits: number, balance: number, enc: RE.Enc, codedBands: number, intensity: number) for i = 0, NB_EBANDS - 1 do local xo = M * EB[i + 1] local nb = M * EB[i + 2] - M * EB[i + 1] local t = tellFrac(enc) if i ~= 0 then balance -= t end local remainingBits = totalBits - t - 1 st.remaining = 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 dualStereo and i == intensity then dualStereo = false end if C == 2 and dualStereo then quantPartition(st, i, st.X[1], xo, nb, b // 2, LM, enc) quantPartition(st, i, st.X[2], xo, nb, b // 2, LM, enc) elseif C == 2 then quantBandStereo(st, i, nb, xo, b, enc) else quantPartition(st, i, st.X[1], xo, nb, b, LM, enc) end balance += pulses[i + 1] + t end end -- ------------------------------------------------------------------------------------------------ frame -- encodeFrame(st, pcm, base, stride, nbBytes) -> buffer: one CELT frame of nbBytes from 960 samples per channel -- (pcm[base + k * stride + c], floats -1 .. 1, interleaved) function CeltEncoder.encodeFrame(st: State, pcm: { number }, base: number, stride: number, nbBytes: number): buffer local C = st.channels local work, tmp = st.work, st.tmp local silent = true -- pre-emphasis, the windowed 1920-sample MDCT input, band energies, normalisation for c = 1, C do local inMem = st.inMem[c] local m = st.preMem[c] -- tmp[1..1080] = the last 120 pre-emphasised samples + this frame's 960 for k = 1, OVERLAP do tmp[k] = inMem[k] end for k = 0, N - 1 do local x = pcm[base + k * stride + c - 1] * 32768 if x ~= 0 then silent = false end tmp[OVERLAP + k + 1] = x - m m = PREEMPH * x end st.preMem[c] = m for k = 1, OVERLAP do inMem[k] = tmp[N + k] end local q = 420 -- (2N - (N + OVERLAP)) / 2 zeros at each end for k = 1, q do work[k] = 0 work[2 * N - k + 1] = 0 end for k = 1, OVERLAP do work[q + k] = tmp[k] * WINDOW[k] work[q + N + k] = tmp[N + k] * WINDOW[OVERLAP - k + 1] end for k = OVERLAP + 1, N do work[q + k] = tmp[k] end local X = st.X[c] Mdct.forward(PLAN, work, 1, X, 1, 1, MDCT_SCALE) for i = 0, NB_EBANDS - 1 do local a, z = M * EB[i + 1] + 1, M * EB[i + 2] local s = 1e-27 for k = a, z do s += X[k] * X[k] end local E = sqrt(s) st.bandE[(c - 1) * NB_EBANDS + i + 1] = E st.bandLogE[(c - 1) * NB_EBANDS + i + 1] = log(E) / log(2) - E_MEANS[i + 1] local g = 1 / (1e-27 + E) for k = a, z do X[k] *= g end end end local enc = RE.new(nbBytes) local totalBits = nbBytes * 8 local oldE = st.oldBandE -- silence if silent then encBitLogp(enc, true, 15) enc.nbits_total += totalBits - tell(enc) RE.done(enc) for i = 1, 2 * NB_EBANDS do oldE[i] = -28 end st.frames += 1 return enc.buf end encBitLogp(enc, false, 15) if tell(enc) + 16 <= totalBits then encBitLogp(enc, false, 1) -- no post-filter end if tell(enc) + 3 <= totalBits then encBitLogp(enc, false, 3) -- not transient end local intra = st.frames == 0 if tell(enc) + 3 <= totalBits then encBitLogp(enc, intra, 3) else intra = false end if C == 1 then for i = 1, NB_EBANDS do oldE[i] = max(oldE[i], oldE[NB_EBANDS + i]) end end quantCoarseEnergy(st, intra, enc, C, totalBits, nbBytes) -- tf_encode: no changes do local budget = totalBits local tt = tell(enc) local logp = 4 if tt + logp + 1 <= budget then budget -= 1 end for _ = 0, NB_EBANDS - 1 do if tt + logp <= budget then encBitLogp(enc, false, logp) tt = tell(enc) end logp = 5 end -- tf_select is only coded when it changes something: not for LM 3 without changes local _ = TF_SELECT end if tell(enc) + 4 <= totalBits then encIcdf(enc, st.spread, SPREAD_ICDF, 5) end local 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 = table.create(NB_EBANDS, 0) local total8 = totalBits * 8 local t = tellFrac(enc) for i = 0, NB_EBANDS - 1 do if t + 6 * 8 < total8 and 0 < cap[i + 1] then encBitLogp(enc, false, 6) -- no dynamic allocation boost t = tellFrac(enc) end end if t + 48 <= total8 then encIcdf(enc, 5, TRIM_ICDF, 7) end local bits = nbBytes * 64 - tellFrac(enc) - 1 local pulses, fineQuant, finePriority = table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0) local codedBands, balance, intensity, dualStereo = computeAllocation(offsets, cap, 5, bits, pulses, fineQuant, finePriority, C, enc, st.dual) quantFineEnergy(st, fineQuant, enc, C) quantAllBands(st, C, pulses, dualStereo, nbBytes * 64, balance, enc, codedBands, intensity) quantEnergyFinalise(st, fineQuant, finePriority, totalBits - tell(enc), enc, C) RE.done(enc) if C == 1 then for i = 1, NB_EBANDS do oldE[NB_EBANDS + i] = oldE[i] end end st.frames += 1 st.lastError = enc.error return enc.buf end CeltEncoder.FRAME = N CeltEncoder.DELAY = OVERLAP -- the decoder's output lags the input by the MDCT overlap return CeltEncoder