diff --git a/crates/ec-opus/src/analysis.rs b/crates/ec-opus/src/analysis.rs index 99f7b849..3ebe4bf7 100644 --- a/crates/ec-opus/src/analysis.rs +++ b/crates/ec-opus/src/analysis.rs @@ -28,7 +28,6 @@ //! `st->Fs >= 16000` guard arranges; below that `AnalysisInfo::valid` stays //! false and every consumer takes its no-analysis branch. -use crate::celt::Fft15; /// Number of past frames the band-energy history keeps (`NB_FRAMES`). const NB_FRAMES: usize = 8; @@ -59,6 +58,12 @@ const WEIGHTS_SCALE: f32 = 1.0 / 128.0; /// libopus's truncated `1.442695` (log2(e)), kept verbatim for bit-exact band energies. #[allow(clippy::approx_constant)] const LIBOPUS_LOG2_E: f32 = 1.442_695; +const SIG_SCALE: f32 = 32768.0; +const HALF_OVER_PI: f32 = (0.5f64 / core::f64::consts::PI) as f32; + +fn ln_f64(x: f32) -> f32 { + f64::from(x).ln() as f32 +} /// Tonality band edges in 480-point FFT bins (`tbands`). const TBANDS: [usize; NB_TBANDS + 1] = [ @@ -256,7 +261,6 @@ pub(crate) struct TonalityAnalysis { fs: u32, /// False for rates libopus never analyses (below 16 kHz). enabled: bool, - fft: Fft15, angle: Vec, d_angle: Vec, d2_angle: Vec, @@ -302,7 +306,6 @@ impl TonalityAnalysis { TonalityAnalysis { fs: sample_rate, enabled: matches!(sample_rate, 16000 | 24000 | 48000), - fft: Fft15::new(N), angle: vec![0.0; N2], d_angle: vec![0.0; N2], d2_angle: vec![0.0; N2], @@ -342,10 +345,7 @@ impl TonalityAnalysis { /// Clears every non-reusable field — libopus `tonality_analysis_reset()`. pub(crate) fn reset(&mut self) { - let fs = self.fs; - let fft = std::mem::replace(&mut self.fft, Fft15::new(15)); - *self = TonalityAnalysis::new(fs); - self.fft = fft; + *self = TonalityAnalysis::new(self.fs); } /// libopus `run_analysis()`: consumes one API frame of interleaved input @@ -410,6 +410,7 @@ impl TonalityAnalysis { for c in 1..channels { acc += pcm[base + c]; } + let acc = acc.clamp(-2.0, 2.0); *t = if channels == 2 { 0.5 * acc } else { acc }; } let mut st = self.downmix_state; @@ -480,7 +481,8 @@ impl TonalityAnalysis { self.write_pos -= DETECT_SIZE; } - let is_silence = self.inmem.iter().all(|&v| v == 0.0); + let max_abs = self.inmem.iter().fold(0.0f32, |m, &v| m.max(v.abs())); + let is_silence = max_abs * 32768.0 <= 1.0 / (1u32 << lsb_depth) as f32; let mut re = std::mem::take(&mut self.fft_re); let mut im = std::mem::take(&mut self.fft_im); @@ -509,16 +511,15 @@ impl TonalityAnalysis { self.fft_im = im; return; } - // libopus takes `opus_fft` (forward, scaled by 1/N); ours is the - // unscaled conjugate transform, so conjugate in and out and scale. - for v in im.iter_mut() { - *v = -*v; + let st = &crate::celt_flp::tables::FFT_STATES[0]; + let mut fout = [[0.0f32; 2]; N]; + for i in 0..N { + fout[st.bitrev[i] as usize] = [re[i] * st.scale, im[i] * st.scale]; } - self.fft.inverse(&mut re, &mut im); - let s = 1.0 / N as f32; + crate::celt_flp::fft::opus_fft_impl(st, &mut fout); for i in 0..N { - re[i] *= s; - im[i] *= -s; + re[i] = fout[i][0]; + im[i] = fout[i][1]; } if re[0].is_nan() { self.info[write].valid = false; @@ -537,11 +538,11 @@ impl TonalityAnalysis { let x2r = im[i] + im[N - i]; let x2i = re[N - i] - re[i]; - let angle = (0.5 / core::f32::consts::PI) * fast_atan2f(x1i, x1r); + let angle = HALF_OVER_PI * fast_atan2f(x1i * SIG_SCALE, x1r * SIG_SCALE); let d_angle = angle - self.angle[i]; let d2_angle = d_angle - self.d_angle[i]; - let angle2 = (0.5 / core::f32::consts::PI) * fast_atan2f(x2i, x2r); + let angle2 = HALF_OVER_PI * fast_atan2f(x2i * SIG_SCALE, x2r * SIG_SCALE); let d_angle2 = angle2 - angle; let d2_angle2 = d_angle2 - d_angle; @@ -594,7 +595,7 @@ impl TonalityAnalysis { for i in 1..4 { e += bin_e(&re, &im, i); } - band_log2[0] = 0.5 * LIBOPUS_LOG2_E * (e + 1e-10).ln(); + band_log2[0] = 0.5 * LIBOPUS_LOG2_E * ln_f64(e + 1e-10); } let mut band_tonality = [0.0f32; NB_TBANDS]; let mut slope = 0.0f32; @@ -618,8 +619,8 @@ impl TonalityAnalysis { self.e[self.e_count][b] = e; frame_noisiness += ne / (1e-15 + e); frame_loudness += (e + 1e-10).sqrt(); - log_e[b] = (e + 1e-10).ln(); - band_log2[b + 1] = 0.5 * LIBOPUS_LOG2_E * (e + 1e-10).ln(); + log_e[b] = ln_f64(e + 1e-10); + band_log2[b + 1] = 0.5 * LIBOPUS_LOG2_E * ln_f64(e + 1e-10); self.log_e[self.e_count][b] = log_e[b]; if self.count == 0 { self.high_e[b] = log_e[b]; @@ -647,7 +648,7 @@ impl TonalityAnalysis { l1 += self.e[i][b].sqrt(); l2 += self.e[i][b]; } - let mut stationarity = 0.99f32.min(l1 / (1e-15 + NB_FRAMES as f32 * l2).sqrt()); + let mut stationarity = 0.99f32.min(l1 / (1e-15 + f64::from(NB_FRAMES as f32 * l2)).sqrt() as f32); stationarity *= stationarity; stationarity *= stationarity; frame_stationarity += stationarity; @@ -680,7 +681,7 @@ impl TonalityAnalysis { for b in 0..NB_TBANDS + 1 { let boost = (leakage_to[b] - band_log2[b]).max(0.0) + (band_log2[b] - (leakage_from[b] + LEAKAGE_OFFSET)).max(0.0); - leak_boost[b] = (0.5 + 64.0 * boost).floor().min(255.0) as u8; + leak_boost[b] = (0.5 + f64::from(64.0 * boost)).floor().min(255.0) as u8; } let mut spec_variability = 0.0f32; @@ -756,7 +757,7 @@ impl TonalityAnalysis { if self.count <= 2 { bandwidth = 20; } - frame_loudness = 20.0 * frame_loudness.log10(); + frame_loudness = 20.0 * f64::from(frame_loudness).log10() as f32; self.e_tracker = (self.e_tracker - 0.003).max(frame_loudness); self.low_e_count *= 1.0 - alpha_e; if frame_loudness < self.e_tracker - 30.0 { diff --git a/crates/ec-opus/src/celt.rs b/crates/ec-opus/src/celt.rs index f2588989..b3040593 100644 --- a/crates/ec-opus/src/celt.rs +++ b/crates/ec-opus/src/celt.rs @@ -263,7 +263,6 @@ pub(crate) const PREEMPH: f32 = 0.850_006_1; pub(crate) const SIG_SCALE: f32 = 32768.0; pub(crate) const SPREAD_NONE: usize = 0; -pub(crate) const SPREAD_LIGHT: usize = 1; pub(crate) const SPREAD_NORMAL: usize = 2; pub(crate) const SPREAD_AGGRESSIVE: usize = 3; @@ -663,7 +662,9 @@ const fn compute_pvq_u() -> [u32; PVQ_U_LEN] { while a < 15 { let mut b = 1; while b < 177 { - uu[a][b] = uu[a - 1][b].wrapping_add(uu[a][b - 1]).wrapping_add(uu[a - 1][b - 1]); + uu[a][b] = uu[a - 1][b] + .wrapping_add(uu[a][b - 1]) + .wrapping_add(uu[a - 1][b - 1]); b += 1; } a += 1; @@ -842,20 +843,36 @@ enum AllocationMode<'a, 'b> { intensity: usize, dual_stereo: bool, prev_coded_bands: usize, + signal_bandwidth: usize, }, } impl AllocationMode<'_, '_> { - fn keep_band(&mut self, j: usize, band_bits: i32, band_width: i32, lm: usize) -> bool { + fn keep_band( + &mut self, + j: usize, + band_bits: i32, + band_width: i32, + lm: usize, + start: usize, + coded_bands: usize, + ) -> bool { match self { AllocationMode::Decode(dec) => dec.dec_bit_logp(1), AllocationMode::Encode { enc, prev_coded_bands, + signal_bandwidth, .. } => { - let hysteresis = if j < *prev_coded_bands { 7 } else { 9 }; - let stay = band_bits > ((hysteresis * band_width) << lm << BITRES) >> 4; + let depth_threshold = if coded_bands > 17 { + if j < *prev_coded_bands { 7 } else { 9 } + } else { + 0 + }; + let stay = coded_bands <= start + 2 + || (band_bits > ((depth_threshold * band_width) << lm << BITRES) >> 4 + && j <= *signal_bandwidth); enc.enc_bit_logp(stay, 1); stay } @@ -959,6 +976,7 @@ pub(crate) fn compute_allocation_encode( intensity: usize, dual_stereo: bool, prev_coded_bands: usize, + signal_bandwidth: usize, ) -> AllocationResult { compute_allocation_shared( AllocationMode::Encode { @@ -966,6 +984,7 @@ pub(crate) fn compute_allocation_encode( intensity, dual_stereo, prev_coded_bands, + signal_bandwidth, }, start, end, @@ -1140,7 +1159,7 @@ fn compute_allocation_shared( let band_width = (E_BANDS[coded_bands] - E_BANDS[j]) as i32; let mut band_bits = pulses[j] + percoeff * band_width + rem; if band_bits >= thresh[j].max(alloc_floor + (1 << BITRES)) { - if mode.keep_band(j, band_bits, band_width, lm) { + if mode.keep_band(j, band_bits, band_width, lm, start, coded_bands) { break; } psum += 1 << BITRES; @@ -1645,7 +1664,11 @@ impl CeltDecoder { // RFC 8251 Section 8: cap the log2 energy at 32 so the amplitude // stays finite (libopus `log2Amp`, `MIN32(QCONST32(32.f, 16), lg)`). let lg = (self.old_band_e[ch * NB_BANDS + i] + mean) as f64; - let lg = if self.legacy_rfc6716 { lg } else { lg.min(32.0) }; + let lg = if self.legacy_rfc6716 { + lg + } else { + lg.min(32.0) + }; lg.exp2() as f32 }; } @@ -1868,13 +1891,13 @@ impl CeltDecoder { budget -= i32::from(tf_select_rsv); let mut curr = 0i32; let mut changed = false; - for i in start..end { + for tf in self.tf_res.iter_mut().take(end).skip(start) { if tell + logp as i32 <= budget { curr ^= i32::from(dec.dec_bit_logp(logp)); tell = dec.tell() as i32; changed |= curr != 0; } - self.tf_res[i] = curr; + *tf = curr; logp = if transient { 4 } else { 5 }; } let t = usize::from(transient); @@ -1941,7 +1964,8 @@ impl CeltDecoder { let n2 = m * (E_BANDS[start + 2] - E_BANDS[start + 1]); let offset = m * E_BANDS[start]; if n2 > n1 && n2 <= 2 * n1 { - self.norm.copy_within(offset + 2 * n1 - n2..offset + n1, offset + n1); + self.norm + .copy_within(offset + 2 * n1 - n2..offset + n1, offset + n1); if c == 2 { let o2 = norm_len + offset; self.norm.copy_within(o2 + 2 * n1 - n2..o2 + n1, o2 + n1); @@ -2062,7 +2086,12 @@ impl CeltDecoder { } /// Decodes one band (Section 4.3.4), recursing for splits and for stereo. - fn quant_band(&mut self, dec: &mut RangeDecoder, a: BandArgs, remaining_bits: &mut i32) -> Result { + fn quant_band( + &mut self, + dec: &mut RangeDecoder, + a: BandArgs, + remaining_bits: &mut i32, + ) -> Result { let BandArgs { i, x, @@ -2463,7 +2492,13 @@ impl CeltDecoder { // Undo the reorganisations, and pass the band on for later folding. if stereo { if n != 2 { - stereo_merge(&mut self.x, x, y.ok_or_else(|| Error::corrupt(INV_SIDE))?, mid, n); + stereo_merge( + &mut self.x, + x, + y.ok_or_else(|| Error::corrupt(INV_SIDE))?, + mid, + n, + ); } if inv { let ys = y.ok_or_else(|| Error::corrupt(INV_SIDE))?; @@ -2540,8 +2575,8 @@ impl CeltDecoder { ) -> u32 { decode_pulses(dec, n, k, &mut self.iy); let mut ryy = 0.0f32; - for j in 0..n { - ryy += (self.iy[j] * self.iy[j]) as f32; + for &v in &self.iy[..n] { + ryy += (v * v) as f32; } let g = gain / ryy.sqrt(); for j in 0..n { @@ -2648,7 +2683,6 @@ impl CeltDecoder { } } - #[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)] fn comb_filter( &mut self, @@ -3084,11 +3118,7 @@ pub(crate) fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 { lo = mid; } } - let lo_cost = if lo == 0 { - -1 - } else { - row[lo as usize] as i32 - }; + let lo_cost = if lo == 0 { -1 } else { row[lo as usize] as i32 }; if bits - lo_cost <= row[hi as usize] as i32 - bits { lo } else { @@ -3404,8 +3434,12 @@ mod tests { // U(N,K) = U(N-1,K) + U(N,K-1) + U(N-1,K-1). for n in 3..8usize { for k in 2..8usize { - let (v1, v2, v3, v) = - (pvq_v(n - 1, k), pvq_v(n, k - 1), pvq_v(n - 1, k - 1), pvq_v(n, k)); + let (v1, v2, v3, v) = ( + pvq_v(n - 1, k), + pvq_v(n, k - 1), + pvq_v(n - 1, k - 1), + pvq_v(n, k), + ); assert_eq!(v, v1.wrapping_add(v2).wrapping_add(v3), "V({n},{k})"); } } diff --git a/crates/ec-opus/src/celt_enc.rs b/crates/ec-opus/src/celt_enc.rs deleted file mode 100644 index 0f0e05b3..00000000 --- a/crates/ec-opus/src/celt_enc.rs +++ /dev/null @@ -1,3120 +0,0 @@ -//! The CELT encoder — RFC 6716 Section 5.3, throughput-first. -//! -//! The *coding* path — every symbol written, every `tell()` the bit allocation -//! reads — mirrors the normative reference (RFC 6716 Appendix A) exactly, -//! because the decoder derives the allocation from the same arithmetic and one -//! bit of drift desynchronises the frame. The *analysis* path is where this -//! encoder buys its speed, with fast deterministic heuristics in place of the -//! reference's searches: -//! -//! - **No pitch prefilter.** The postfilter-off bit is coded every frame, -//! which removes the most expensive analysis in the reference encoder (an -//! autocorrelation search over 1024 lags). Same choice the reference makes -//! below complexity 5. -//! - **Time/frequency Viterbi ported and enabled.** `tf_analysis()` and the -//! libopus float-mode `transient_analysis()` (returning `tf_estimate`/ -//! `tf_chan`) are ported from the reference; `const TF_ANALYSIS: bool` -//! gates the Viterbi search. It is `true`: `dynalloc_analysis()` computes -//! per-band `importance[]` and feeds it to the search, matching the -//! reference's analysis path. -//! - **Fixed spreading.** `SPREAD_NORMAL` every frame, coded explicitly. -//! - **Coarse energy**: the reference's two-pass encode-both-and-compare is -//! ported (`TWO_PASS_COARSE_ENERGY`) but ships off — it measured mixed on -//! the library gate's err_ratio; the delayed-intra heuristic decides. -//! -//! What stays: transient detection, the closed-form allocation-trim and -//! dynalloc spike heuristics, the stereo-mode analysis, intensity thresholds -//! and constrained-VBR reservoir — all cheap O(frame) arithmetic that decides -//! *rates*, not searches. -//! -//! Steady state allocates nothing: every buffer is owned by the encoder and -//! sized at construction. - -use ec_core::{Error, Result}; - -use crate::analysis::AnalysisInfo; -use crate::celt::{ - self, BETA_COEF, BETA_INTRA, BITRES, CACHE_CAPS, E_BANDS, E_MEANS, E_PROB_MODEL, LOG_N, - MAX_FINE_BITS, NB_BANDS, OVERLAP, PRED_COEF, PREEMPH, QTHETA_OFFSET, QTHETA_OFFSET_TWOPHASE, - SHORT_MDCT, SIG_SCALE, SMALL_ENERGY_ICDF, SPREAD_AGGRESSIVE, SPREAD_ICDF, SPREAD_LIGHT, - SPREAD_NONE, SPREAD_NORMAL, TF_SELECT, TRIM_ICDF, bitexact_cos, bitexact_log2tan, bits2pulses, - cache_index, compute_allocation_encode, compute_qn, deinterleave_hadamard, exp_rotation, - frac_mul16, get_pulses, haar1, pulses2bits, -}; -use crate::range::RangeEncoder; - -/// `EC_OPUS_TRIM13` override of the continuous allocation trim. -fn trim13_env() -> Option { - static P: std::sync::OnceLock> = std::sync::OnceLock::new(); - *P.get_or_init(|| std::env::var("EC_OPUS_TRIM13").ok().map(|v| v != "0")) -} - -/// TF-boost sweep knobs (lane opustr2): `k * (tf_estimate - off) * target`, -/// optionally applied only on frames the transient analysis flagged (other -/// frames keep the shipped k=1). Read once from the environment; -/// `EC_OPUS_TF_K` / `EC_OPUS_TF_OFF` / `EC_OPUS_TF_GATE=transient` / -/// `EC_OPUS_TF_THRESH` (k applies only from that `tf_estimate` up). -fn tf_boost_params() -> (f32, f32, bool, f32) { - static P: std::sync::OnceLock<(f32, f32, bool, f32)> = std::sync::OnceLock::new(); - *P.get_or_init(|| { - let f = |name: &str, dflt: f32| { - std::env::var(name) - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(dflt) - }; - let gate = std::env::var("EC_OPUS_TF_GATE") - .map(|v| v == "transient") - .unwrap_or(false); - ( - f("EC_OPUS_TF_K", 1.0), - f("EC_OPUS_TF_OFF", 0.044), - gate, - f("EC_OPUS_TF_THRESH", 0.0), - ) - }) -} - -/// Which consumers of the [`crate::analysis`] tonality analysis are live. -/// -/// The analysis itself runs whenever `EC_OPUS_ANALYSIS` is not `0`; each -/// downstream term was measured on the 12-row library gate on its own, so -/// each keeps its own switch (`1`/`0`) around the shipped default: -/// `EC_OPUS_TRIM_TONAL` (`alloc_trim`'s `tonality_slope` term), -/// `EC_OPUS_TRIM13` (the continuous 1.3 trim the term belongs to), -/// `EC_OPUS_VBR_TONAL` (`compute_vbr`'s tonality boost) and -/// `EC_OPUS_VBR_ACT` (`compute_vbr`'s low-activity cut), -/// `EC_OPUS_LEAK` (`dynalloc_analysis`'s per-band leakage boost) and -/// `EC_OPUS_BW_DETECT` (the detected bandwidth lowering the coded one). -/// -/// MEASURED (lane opustonal, four detached 12-row library-gate runs against -/// the shipped rows `lanes/opus-opustr2-r1.sweep.txt`). The analysis itself is -/// byte-neutral -- no consumer reads it unless its own switch is on -- and -/// **every consumer arm is rejected by the KEEP rule**, so all three default -/// off. err_ratio, better rows first, blocking rows named: -/// -/// | arm | better | blocking | -/// |---|---|---| -/// | 1.3 trim + tonality term (`-r1`) | nik@64 .708→.647, reelo@64 1.510→1.071, reelo@96 .940→.898, reell@96 4.499→2.458, dl8a .552/.374→.512/.336 | nik@96 .985→1.006, her@64 1.103→1.109, her@96 1.051→1.085, reell@64 2.697→2.872 | -/// | vbr tonality + activity (`-r2`) | hein@64 .853→.327, hein@96 .528→.426, nik@64 →.672, dl8a@64 →.541 | nik@96 →1.061, reelo@96 →1.165, her@64 →1.104, her@96 →1.060, dl8a@96 →.414 | -/// | vbr activity alone (`-r3`) | hein@64 →.430, hein@96 →.408, nik@64 →.657, dl8a@64 →.511 | nik@96 →.990, her@64 →1.104, her@96 →1.071, dl8a@96 →.382 | -/// | `EC_OPUS_BW_DETECT` (`opusmode -r1`) | -- | -- (byte-identical: `analysis.bandwidth` is 20 on every valid frame of every gate source, so the clamp never fires) | -/// | `EC_OPUS_LEAK` (`opusmode -r2`) | -- | nik@64 .708→.709, nik@96 .985→.986, her@96 1.051→1.052 (the rest identical) | -/// | `EC_OPUS_BW_DETECT` + `EC_OPUS_VBR_ACT` + `EC_OPUS_TF_K=1.25` (`opusmode -r3`) | reell@96 4.499→2.516, reell@64 2.697→1.440, hein@64 .853→.470, hein@96 .528→.404, dl8a@96 .374→.315, dl8a@64 →.535, nik@64 →.651, **nik@96 .985→.957**, reelo@96 →.928, reelo@64 →1.509 | her@96 1.051→1.071, her@64 1.103→1.104 | -/// | all four + `EC_OPUS_ALIGN=1` (`-r4`) | reell@64 →1.865, reell@96 →3.986, reelo@64 →1.123, reelo@96 →.891, her@64 →.952 | nik@64 →1.014, nik@96 →1.842, her@96 →1.217, dl8a →1.162/.988, hein →.971/1.514 | -/// -/// `corr_ours` is never worse by more than .0005 on any unaligned arm (it is -/// *better* on every row of `-r2`/`-r3`), so corr is not what rejects them. -/// The `alloc_trim` term is small by construction -- `tonality_slope` averages -/// -.09 (speech) to -.17 (music), so the term is ±.08 of a trim step and -/// rounds away entirely on the shipped discrete ladder, which is why no -/// discrete-ladder arm was run. The activity cut is the nearest miss ever -/// measured on this gate for a speech source (hein halves) and is blocked by -/// her@96 +.020 and nik@96 +.005 -- the same two rows that have blocked the -/// The combined arm (`opusmode -r3`) is the first arm ever measured on this -/// gate that moves a blocking row the right way: nik@96 .985→.957. It is -/// **rejected by the per-row KEEP rule** (her@96 +.020, her@64 +.001) and -/// **passes the aggregate rule** (geometric-mean err_ratio 1.0218→0.8378, -/// -18.0%; worst row her@96 +1.9%, under the 5% bound; `corr_ours` within -/// .0001 on every row). Which rule ships is the user's call; the default is -/// off either way. Aligned, the analysis moves reell/reelo/her@64 a long way but leaves -/// the aligned blocking set (nik, her@96, dl8a, hein) exactly where the -/// analysis-free aligned arms left it, so the alignment default stays off. -pub(crate) fn analysis_params() -> (bool, bool, bool, bool, bool, bool) { - static P: std::sync::OnceLock<(bool, bool, bool, bool, bool, bool)> = - std::sync::OnceLock::new(); - *P.get_or_init(|| { - let b = |name: &str, dflt: bool| std::env::var(name).map(|v| v != "0").unwrap_or(dflt); - let trim = b("EC_OPUS_TRIM_TONAL", true); - let vbr_tonal = b("EC_OPUS_VBR_TONAL", false); - let vbr_act = b("EC_OPUS_VBR_ACT", false); - // The analysis costs ~25% of the encoder (5.1 384k: 126x -> 100x - // realtime), so it only runs when something reads it: any consumer - // switch, an explicit `EC_OPUS_ANALYSIS=1`, or - // `Encoder::set_analysis(true)` for the diagnostics. - let leak = b("EC_OPUS_LEAK", true); - let bw = b("EC_OPUS_BW_DETECT", false); - let any = trim || vbr_tonal || vbr_act || leak || bw; - ( - b("EC_OPUS_ANALYSIS", any), - trim, - vbr_tonal, - vbr_act, - leak, - bw, - ) - }) -} - -const CACHE_BITS: &[u8] = &crate::celt::CACHE_BITS; -const INV_TABLE: [u8; 128] = [ - 255, 255, 156, 110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25, 23, 22, 21, 20, 19, 18, 17, - 16, 16, 15, 15, 14, 13, 13, 12, 12, 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 9, 9, 8, 8, 8, - 8, 8, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, -]; - -// --------------------------------------------------------------------------- -// Forward MDCT -// --------------------------------------------------------------------------- - -/// One forward-MDCT plan, the exact adjoint of the decoder's `ImdctPlan`: -/// window-fold, pre-rotation, an `l/2`-point FFT and post-rotation, scaled by -/// `2/l` so that decode(encode(x)) reconstructs at unit gain. -/// libopus `opus_encoder.c`'s `delay_compensation = Fs/250`: how far behind -/// the API frame the CELT analysis window sits, in 48 kHz samples. -const CELT_DELAY_48K: usize = 192; - -#[derive(Clone, Debug)] -struct MdctPlan { - l: usize, - fft: celt::Fft15, - rot_re: Vec, - rot_im: Vec, - fre: Vec, - fim: Vec, - t: Vec, -} - -impl MdctPlan { - fn new(l: usize) -> MdctPlan { - let n = 2 * l; - let quarter = l / 2; - let mut rot_re = vec![0.0; quarter]; - let mut rot_im = vec![0.0; quarter]; - for i in 0..quarter { - let a = 2.0 * core::f64::consts::PI * (i as f64 + 0.125) / n as f64; - rot_re[i] = a.cos() as f32; - rot_im[i] = a.sin() as f32; - } - MdctPlan { - l, - fft: celt::Fft15::new(quarter), - rot_re, - rot_im, - fre: vec![0.0; quarter], - fim: vec![0.0; quarter], - t: vec![0.0; l], - } - } - - /// Transforms `l + OVERLAP` time samples starting at `input[off]` — the - /// support of the low-overlap window — into `l` MDCT coefficients written - /// at `out[out_off + k*stride]`. - fn forward( - &mut self, - input: &[f32], - off: usize, - window: &[f32], - out: &mut [f32], - out_off: usize, - stride: usize, - ) { - let l = self.l; - let quarter = l / 2; - let flat = quarter - OVERLAP / 2; - let mirror = quarter + OVERLAP / 2; - let t = &mut self.t; - // Window fold: the adjoint of the inverse's scatter, so every - // coefficient, sign and window position matches by construction. - for i in 0..flat { - t[quarter - 1 - i] = input[off + mirror - 1 - i]; - } - for i in flat..quarter { - let w = i - flat; - t[quarter - 1 - i] = - -window[w] * input[off + w] + window[OVERLAP - 1 - w] * input[off + mirror - 1 - i]; - } - for i in 0..flat { - t[quarter + i] = input[off + mirror + i]; - } - for i in flat..quarter { - let w = i - flat; - t[quarter + i] = window[w] * input[off + l + OVERLAP - 1 - w] - + window[OVERLAP - 1 - w] * input[off + mirror + i]; - } - // Shuffle into the complex FFT input. - for i in 0..quarter { - self.fre[i] = -t[2 * i]; - self.fim[i] = t[2 * (quarter - 1 - i) + 1]; - } - // Rotate by -theta (adjoint of the inverse's post-rotation). - for i in 0..quarter { - let (c, s) = (self.rot_re[i], self.rot_im[i]); - let (re, im) = (self.fre[i], self.fim[i]); - self.fre[i] = re * c + im * s; - self.fim[i] = im * c - re * s; - } - // Forward FFT = conjugate, +i-convention FFT, conjugate. - for v in self.fim.iter_mut() { - *v = -*v; - } - self.fft.inverse(&mut self.fre, &mut self.fim); - for v in self.fim.iter_mut() { - *v = -*v; - } - // Adjoint of the pre-rotation, with the 2/l forward scaling CELT puts - // on this side of the transform. - let scale = 2.0 / l as f32; - for i in 0..quarter { - let (c, s) = (self.rot_re[i], self.rot_im[i]); - let (re, im) = (self.fre[i], self.fim[i]); - out[out_off + (2 * i) * stride] = scale * (s * re - c * im); - out[out_off + (l - 1 - 2 * i) * stride] = scale * (-c * re - s * im); - } - } -} - -// --------------------------------------------------------------------------- -// Symbol-level helpers -// --------------------------------------------------------------------------- - -/// `ec_laplace_encode()`: the coarse-energy prediction error. May clamp -/// `value`, which is why it is passed back. -fn laplace_encode(enc: &mut RangeEncoder, value: &mut i32, mut fs: u32, decay: i32) -> i32 { - const MINP: u32 = 1; - const NMIN: u32 = 16; - let mut fl = 0u32; - let mut val = *value; - if val != 0 { - let s = if val < 0 { -1i32 } else { 0 }; - val = (val + s) ^ s; - fl = fs; - let fs0 = fs; - fs = ((32768 - MINP * (2 * NMIN) - fs0) * (16384 - decay as u32)) >> 15; - // Search the decaying part of the pdf. - let mut i = 1i32; - while fs > 0 && i < val { - fs *= 2; - fl += fs + 2 * MINP; - fs = (fs * decay as u32) >> 15; - i += 1; - } - if fs == 0 { - // Everything beyond has probability MINP. - let mut ndi_max = (32768 - fl + MINP - 1) as i32; - ndi_max = (ndi_max - s) >> 1; - let di = (val - i).min(ndi_max - 1); - fl += ((2 * di + 1 + s) as u32) * MINP; - fs = MINP.min(32768 - fl); - *value = (i + di + s) ^ s; - } else { - fs += MINP; - if s == 0 { - fl += fs; - } - } - debug_assert!(fl + fs <= 32768); - debug_assert!(fs > 0); - } - enc.encode_bin(fl, fl + fs, 15); - *value -} - -/// `encode_pulses()` for the general case: index the pulse vector in the -/// V(N,K) enumeration and code it as one uniform symbol (Section 5.3.4). -fn encode_pulses(enc: &mut RangeEncoder, iy: &[i32], n: usize, k: usize) { - debug_assert!(n >= 2 && k > 0); - let mut j = n - 1; - let mut i = u32::from(iy[j] < 0); - let mut kk = iy[j].unsigned_abs() as usize; - while j > 0 { - j -= 1; - // The row the reference stepping left in place at this dimension is - // `U(n - j, .)`; read it from the table instead. - i = i.wrapping_add(celt::pvq_u(n - j, kk)); - kk += iy[j].unsigned_abs() as usize; - if iy[j] < 0 { - i = i.wrapping_add(celt::pvq_u(n - j, kk + 1)); - } - } - let nc = celt::pvq_v(n, kk); - enc.enc_uint(i, nc.max(2)); -} - -/// `stereo_itheta()`: the angle between mid and side (or the two halves of a -/// split mono band), in Q14 (0..16384). -fn stereo_itheta(x: &[f32], y: &[f32], stereo: bool, n: usize) -> i32 { - let mut emid = 1e-15f32; - let mut eside = 1e-15f32; - if stereo { - for j in 0..n { - let m = x[j] + y[j]; - let s = x[j] - y[j]; - emid += m * m; - eside += s * s; - } - } else { - for j in 0..n { - emid += x[j] * x[j]; - eside += y[j] * y[j]; - } - } - let mid = emid.sqrt(); - let side = eside.sqrt(); - // 0.63662 is the reference's own 2/pi literal (vq.c, stereo_itheta); the - // exact constant would round a boundary theta differently. The angle is - // the reference float build's `fast_atan2f` (the rational approximation - // the tonality features share), which also keeps libm's `atan2` out of - // the per-band loop. - #[allow(clippy::approx_constant)] - const TWO_OVER_PI: f32 = 0.63662; - (TWO_OVER_PI * 16384.0 * crate::analysis::fast_atan2f(side, mid) + 0.5).floor() as i32 -} - -/// `l1_metric()` from the reference: L1 norm scaled by `(1 + LM*bias)`. -/// In float mode `MAC16_32_Q15(c, a*b) = c + a*b`, so this is `L1*(1 + LM*bias)`. -fn l1_metric(tmp: &[f32], n: usize, lm: usize, bias: f32) -> f32 { - let mut l1 = 0.0f32; - for v in &tmp[..n] { - l1 += v.abs(); - } - l1 * (1.0 + lm as f32 * bias) -} - -// --------------------------------------------------------------------------- -// The encoder -// --------------------------------------------------------------------------- - -/// Arguments threaded through the band-encode recursion; the encode-side -/// mirror of the decoder's `BandArgs`, minus everything only resynthesis -/// needs (folding sources, gains, collapse fill). -#[derive(Clone, Copy, Debug)] -struct EncBand { - i: usize, - x: usize, - y: Option, - n: usize, - b: i32, - spread: usize, - blocks: usize, - intensity: usize, - tf_change: i32, - level: i32, - lm: i32, -} - -/// Per-frame encoder diagnostics for the dropout investigation. Captured at -/// the end of `CeltEncoder::encode`; read via [`CeltEncoder::last_diag`]. -#[derive(Clone, Debug)] -pub struct CeltFrameDiag { - /// Transient flag as coded into the bitstream. - pub is_transient: bool, - /// `short_blocks` (0 = long, else `m` short blocks). - pub short_blocks: usize, - /// Coarse-energy intra-frame reset was used. - pub intra: bool, - /// The whole frame was coded as silence. - pub silence: bool, - /// Frame-size exponent (`120 << lm`). - pub lm: usize, - /// First/last coded band indices. - pub start: usize, - /// Highest band actually allocated pulses. - pub coded_bands: usize, - /// Stereo intensity band (bands >= this collapse to mono). - pub intensity: usize, - /// Dual-stereo (no mid/side folding) flag. - pub dual_stereo: bool, - /// Allocation trim index (0..10). - pub alloc_trim: i32, - /// Constrained-VBR reservoir level after this frame, in 1/8-bit units. - pub vbr_reservoir: i32, - /// Final compressed payload of this frame, in bytes. - pub nb_compressed: usize, - /// Per-band log2 energy minus `E_MEANS`, both channels (ch0 then ch1). - pub band_log_e: [f32; 2 * NB_BANDS], - /// Per-band allocated pulses (ch0/ch1 share for intensity bands). - pub pulses: [i32; NB_BANDS], - /// Per-band fine-energy precision bits. - pub fine_quant: [i32; NB_BANDS], - /// Whether the tonality analysis produced a usable window for this frame. - pub analysis_valid: bool, - /// `AnalysisInfo::music_prob` — 0 is speech, 1 is music. - pub music_prob: f32, - /// `AnalysisInfo::tonality`. - pub tonality: f32, - /// `AnalysisInfo::tonality_slope`, `alloc_trim`'s input. - pub tonality_slope: f32, - /// `AnalysisInfo::activity`, `compute_vbr`'s input. - pub activity: f32, - /// `AnalysisInfo::bandwidth`, the detected bandwidth band index. - pub analysis_bandwidth: i32, -} - -impl Default for CeltFrameDiag { - fn default() -> Self { - Self { - is_transient: false, - short_blocks: 0, - intra: false, - silence: false, - lm: 0, - start: 0, - coded_bands: 0, - intensity: 0, - dual_stereo: false, - alloc_trim: 0, - vbr_reservoir: 0, - nb_compressed: 0, - band_log_e: [0.0; 2 * NB_BANDS], - pulses: [0; NB_BANDS], - fine_quant: [0; NB_BANDS], - analysis_valid: false, - music_prob: 0.0, - tonality: 0.0, - tonality_slope: 0.0, - activity: 0.0, - analysis_bandwidth: 0, - } - } -} - -/// A CELT-layer encoder for one elementary Opus stream (mono or stereo). -/// CELT itself always runs at 48 kHz; slower input is zero-stuffed up to it. -#[derive(Clone, Debug)] -pub struct CeltEncoder { - channels: usize, - stream_channels: usize, - constrained_vbr: bool, - silk_offset: i32, - /// 48000 / input rate, 1 for native 48 kHz input. - upsample: usize, - window: Vec, - plans: Vec, - /// Preemphasised history, `channels * OVERLAP`. - in_mem: Vec, - /// libopus `opus_encoder.c`'s `delay_buffer`: the CELT layer is fed the - /// input delayed by `delay_compensation = Fs/250` (192 samples at 48 kHz), - /// so its analysis window sits 4 ms behind the API frame. Interleaved, - /// `CELT_DELAY_48K / upsample` samples per channel. - delay_buf: Vec, - /// Whether that delay is applied at all — see - /// [`crate::Encoder::set_libopus_input_alignment`] for why it ships off. - align_input: bool, - preemph_mem: [f32; 2], - /// Coarse-energy prediction state, `2 * NB_BANDS`. - old_band_e: Vec, - delayed_intra: f32, - consec_transient: u32, - // Spreading decision state (libopus celt_encoder.c:2534-2537). - spread_decision: usize, - tonal_average: i32, - hf_average: i32, - tapset_decision: i32, - last_coded_bands: usize, - force_intra: bool, - // Constrained-VBR reservoir. - vbr_reservoir: i32, - vbr_drift: i32, - vbr_offset: i32, - vbr_count: i32, - /// libopus `st->stereo_saving` — mid/side bit-saving estimate (Q8 in C, - /// plain f32 here), updated in `alloc_trim_analysis`. - stereo_saving: f32, - /// libopus `st->spec_avg` — temporal-VBR follower average, updated each frame. - spec_avg: f32, - // Per-frame scratch, allocated once. - in_buf: Vec, - freq: Vec, - x: Vec, - band_e: Vec, - band_log_e: Vec, - /// Long-window log energies used by dynalloc (`bandLogE2`). - band_log_e2: Vec, - /// Coarse-energy two-pass scratch: state before the first pass, and the - /// intra pass's results while the inter pass overwrites the live arrays. - old_e_save: Vec, - old_e_intra: Vec, - error_intra: Vec, - /// Bytes the intra pass wrote, kept while the inter pass is tried. - coarse_bytes: Vec, - /// Previous intensity decision (hysteresis state, libopus `st->intensity`). - intensity: usize, - error: Vec, - transient_tmp: Vec, - hadamard_tmp: Vec, - tf_res: [i32; NB_BANDS], - pulses: [i32; NB_BANDS], - fine_quant: [i32; NB_BANDS], - fine_priority: [i32; NB_BANDS], - offsets: [i32; NB_BANDS], - caps: [i32; NB_BANDS], - iy: Vec, - pvq_y: Vec, - pvq_sign: Vec, - /// Per-frame diagnostics captured at the end of the last `encode` call. - last_diag: CeltFrameDiag, - /// libopus `st->analysis`'s per-frame output, handed in by - /// [`crate::Encoder`] (which owns the estimator and runs it once per API - /// frame, libopus's order); the `valid == false` default when the - /// analysis is off. - info: AnalysisInfo, -} - -impl CeltEncoder { - /// An encoder for `channels` channels (1 or 2) fed at `48000/upsample` Hz. - pub fn new(channels: usize, upsample: usize) -> CeltEncoder { - assert!((1..=2).contains(&channels)); - assert!(upsample >= 1); - let max_n = SHORT_MDCT * 8; - CeltEncoder { - channels, - stream_channels: channels, - constrained_vbr: true, - silk_offset: 0, - upsample, - window: celt::overlap_window(), - plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(), - in_mem: vec![0.0; channels * OVERLAP], - delay_buf: vec![0.0; channels * CELT_DELAY_48K], - align_input: false, - preemph_mem: [0.0; 2], - old_band_e: vec![0.0; 2 * NB_BANDS], - delayed_intra: 1.0, - consec_transient: 0, - last_coded_bands: 0, - force_intra: true, - spread_decision: SPREAD_NORMAL, - tonal_average: 256, - hf_average: 0, - tapset_decision: 0, - vbr_reservoir: 0, - vbr_drift: 0, - vbr_offset: 0, - vbr_count: 0, - stereo_saving: 0.0, - spec_avg: 0.0, - in_buf: vec![0.0; channels * (max_n + OVERLAP)], - freq: vec![0.0; channels * max_n], - x: vec![0.0; channels * max_n], - band_e: vec![0.0; 2 * NB_BANDS], - band_log_e: vec![0.0; 2 * NB_BANDS], - band_log_e2: vec![0.0; 2 * NB_BANDS], - old_e_save: vec![0.0; 2 * NB_BANDS], - old_e_intra: vec![0.0; 2 * NB_BANDS], - error_intra: vec![0.0; 2 * NB_BANDS], - coarse_bytes: Vec::with_capacity(1275), - intensity: 0, - error: vec![0.0; 2 * NB_BANDS], - transient_tmp: vec![0.0; max_n + OVERLAP], - hadamard_tmp: vec![0.0; max_n], - tf_res: [0; NB_BANDS], - pulses: [0; NB_BANDS], - fine_quant: [0; NB_BANDS], - fine_priority: [0; NB_BANDS], - offsets: [0; NB_BANDS], - caps: [0; NB_BANDS], - iy: vec![0; max_n], - pvq_y: vec![0.0; max_n], - pvq_sign: vec![0; max_n], - last_diag: CeltFrameDiag::default(), - info: AnalysisInfo::default(), - } - } - - /// Channels this encoder codes. - pub fn channels(&self) -> usize { - self.channels - } - - pub(crate) fn set_stream_channels(&mut self, c: usize) { - self.stream_channels = c.clamp(1, self.channels); - } - - pub(crate) fn set_prediction(&mut self, level: u8) { - self.force_intra = level == 0; - } - - pub(crate) fn set_constrained_vbr(&mut self, on: bool) { - self.constrained_vbr = on; - } - - pub(crate) fn set_silk_offset(&mut self, offset: i32) { - self.silk_offset = offset; - } - - pub(crate) fn window(&self) -> &[f32] { - &self.window - } - - /// Diagnostics captured at the end of the most recent `encode` call. - pub fn last_diag(&self) -> &CeltFrameDiag { - &self.last_diag - } - - /// Feeds the layer the input delayed by `CELT_DELAY_48K`, as libopus - /// does; see [`crate::Encoder::set_libopus_input_alignment`]. - pub fn set_align_input(&mut self, on: bool) { - self.align_input = on; - } - - /// Drops all inter-frame state. - pub fn reset(&mut self) { - self.in_mem.fill(0.0); - self.delay_buf.fill(0.0); - self.preemph_mem = [0.0; 2]; - self.old_band_e.fill(0.0); - self.delayed_intra = 1.0; - self.consec_transient = 0; - self.last_coded_bands = 0; - self.force_intra = true; - self.spread_decision = SPREAD_NORMAL; - self.tonal_average = 256; - self.hf_average = 0; - self.tapset_decision = 0; - self.vbr_reservoir = 0; - self.vbr_drift = 0; - self.vbr_offset = 0; - self.vbr_count = 0; - self.stereo_saving = 0.0; - self.spec_avg = 0.0; - self.info = AnalysisInfo::default(); - } - - /// Encodes one frame of interleaved `f32` (`frame_size` samples per - /// channel at 48 kHz, one of 120/240/480/960 — of which - /// `frame_size/upsample` are read from `pcm`) into `enc`, which must have - /// been `reset` to the frame's byte budget. `start..end` bounds the coded - /// bands — `end` is how the caller limits the coded bandwidth, `start` - /// (0, or 17 under a hybrid packet's SILK layer) skips the low bands - /// exactly as the decoder's `start_band` does: no energy, no shapes, no - /// postfilter bit, allocation over the coded span only. With - /// `vbr_rate_bps` set, the frame may be shrunk below that budget - /// (constrained VBR); the return value is the final frame size in bytes. - // The encoder entry point takes the per-frame knobs the caller owns, one argument each. - #[allow(clippy::too_many_arguments)] - pub(crate) fn encode( - &mut self, - enc: &mut RangeEncoder, - pcm: &[f32], - frame_size: usize, - start: usize, - end: usize, - vbr_rate_bps: u32, - info: &AnalysisInfo, - ) -> Result { - let lm: usize = match frame_size { - 120 => 0, - 240 => 1, - 480 => 2, - 960 => 3, - _ => { - return Err(Error::unsupported( - format!("celt frame of {frame_size} samples"), - "CELT frames are 2.5, 5, 10 or 20 ms at 48 kHz", - )); - } - }; - let m = 1usize << lm; - let n = frame_size; - let cc = self.channels; - let c = self.stream_channels; - let in_n = n / self.upsample; - if pcm.len() < in_n * cc { - return Err(Error::corrupt(format!( - "celt encode: {} samples for a {cc}-channel {in_n}-sample frame", - pcm.len() - ))); - } - let tell0_frac = enc.tell_frac() as i32; - let end = end.clamp(start + 1, NB_BANDS); - - // libopus `opus_encode_native` runs the tonality analysis on the raw - // API frame before the mode decision, so the estimator lives in - // `Encoder` and its result is handed down here. - self.info = *info; - - let mut nb_compressed = enc.storage(); - let mut nb_available = nb_compressed as i32; - // The target rate in 1/8-bit units per frame, VBR only. - let (vbr_rate, mut effective_bytes) = if vbr_rate_bps > 0 { - let den = 48000i64 >> BITRES; - let vr = ((vbr_rate_bps as i64 * n as i64 + (den >> 1)) / den) as i32; - (vr, vr >> (3 + BITRES)) - } else { - (0, nb_compressed as i32) - }; - - if vbr_rate > 0 && self.constrained_vbr { - // Constrained VBR: cap this frame so the reservoir never dips - // below one frame of buffering. - let vbr_bound = vbr_rate; - let floor = if enc.tell() == 1 { 2i32 } else { 0 }; - let max_allowed = (floor - .max((vbr_rate + vbr_bound - self.vbr_reservoir) >> (BITRES + 3))) - .min(nb_available); - if max_allowed < nb_available { - nb_compressed = max_allowed as usize; - nb_available = max_allowed; - enc.shrink(nb_compressed); - } - } - let mut total_bits = (nb_compressed * 8) as i32; - - // --- Preemphasis ---------------------------------------------------- - let stride = n + OVERLAP; - let mut silence = true; - let mut delay = std::mem::take(&mut self.delay_buf); - let mut next_delay = [0.0f32; 2 * CELT_DELAY_48K]; - for ch in 0..cc { - let base = ch * stride; - self.in_buf[base..base + OVERLAP] - .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]); - let mut mem = self.preemph_mem[ch]; - let up = self.upsample; - // `src(j)`: input sample `j` of the delayed stream libopus's CELT - // layer sees -- the `d` samples held over from the previous call - // first, then this frame's. - let dd = CELT_DELAY_48K / up; - let d = if self.align_input { dd } else { 0 }; - let src = |j: usize| { - if j < d { - delay[j * cc + ch] - } else { - pcm[(j - d) * cc + ch] - } - }; - for i in 0..n { - // Zero-stuffing to 48 kHz: the images above the input's own - // Nyquist are never coded (the caller caps `end`) and the - // decoder's decimation drops them. - let mut x = if up == 1 { - src(i) * SIG_SCALE - } else if i.is_multiple_of(up) { - src(i / up) * SIG_SCALE * up as f32 - } else { - 0.0 - }; - if !x.is_finite() { - x = 0.0; - } - x = x.clamp(-65536.0, 65536.0); - let v = x + mem; - mem = -PREEMPH * x; - self.in_buf[base + OVERLAP + i] = v; - silence &= v == 0.0; - } - self.preemph_mem[ch] = mem; - for k in 0..dd { - let j = in_n + k; - next_delay[k * cc + ch] = if j < dd { - delay[j * cc + ch] - } else { - pcm[(j - dd) * cc + ch] - }; - } - self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP] - .copy_from_slice(&self.in_buf[base + n..base + n + OVERLAP]); - } - delay[..cc * (CELT_DELAY_48K / self.upsample)] - .copy_from_slice(&next_delay[..cc * (CELT_DELAY_48K / self.upsample)]); - self.delay_buf = delay; - - // --- Silence flag (first symbol of the frame) ----------------------- - // Only exists when CELT opens the stream (decoder: `tell == 1`); under - // a hybrid packet's SILK layer the frame is never flagged silent. - if enc.tell() == 1 { - enc.enc_bit_logp(silence, 15); - } else { - silence = false; - } - if silence { - if vbr_rate > 0 { - nb_compressed = nb_compressed.min(2); - total_bits = (nb_compressed * 8) as i32; - nb_available = 2; - enc.shrink(nb_compressed); - } - enc.pad_to_end(); - } - - // --- Postfilter: always off (throughput-first, = complexity < 5) ---- - // The flag exists only when band 0 is coded (decoder: `start == 0`). - if start == 0 && enc.tell() as i32 + 16 <= total_bits { - enc.enc_bit_logp(false, 1); - } - - // --- Transient flag ------------------------------------------------- - let mut is_transient = false; - let mut short_blocks = 0usize; - let mut tf_estimate = 0.0f32; - let mut tf_chan = 0usize; - if lm > 0 && enc.tell() as i32 + 3 <= total_bits { - let (ta, te, tc) = self.transient_analysis(n + OVERLAP, cc, stride); - is_transient = ta; - tf_estimate = te; - tf_chan = if cc == 2 && c == 1 { 0 } else { tc }; - if is_transient { - short_blocks = m; - } - enc.enc_bit_logp(is_transient, 3); - } - - // --- Forward MDCTs, energies, normalisation ------------------------- - // dynalloc looks at long-window energies (`bandLogE2`): on transient - // frames that is a second MDCT pass, offset by LM/2 for the block size. - if short_blocks != 0 { - self.compute_mdcts(0, lm, n, cc, c); - for ch in 0..c { - for i in start..end { - let mut sum = 1e-27f32; - for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { - let v = self.freq[ch * n + j]; - sum += v * v; - } - self.band_log_e2[i + ch * NB_BANDS] = - (sum.sqrt() as f64).log2() as f32 - E_MEANS[i] + 0.5 * lm as f32; - } - } - } - self.compute_mdcts(short_blocks, lm, n, cc, c); - for ch in 0..c { - self.x[ch * n..ch * n + m * E_BANDS[start]].fill(0.0); - for i in start..end { - let mut sum = 1e-27f32; - for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { - let v = self.freq[ch * n + j]; - sum += v * v; - } - self.band_e[i + ch * NB_BANDS] = sum.sqrt(); - self.band_log_e[i + ch * NB_BANDS] = - (self.band_e[i + ch * NB_BANDS] as f64).log2() as f32 - E_MEANS[i]; - if short_blocks == 0 { - self.band_log_e2[i + ch * NB_BANDS] = self.band_log_e[i + ch * NB_BANDS]; - } - } - for i in start..end { - let g = 1.0 / (1e-27 + self.band_e[i + ch * NB_BANDS]); - for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { - self.x[ch * n + j] = self.freq[ch * n + j] * g; - } - } - } - - if std::env::var_os("EC_OPUS_X_DEBUG").is_some() { - let f: Vec = self.in_buf[OVERLAP..OVERLAP + 16] - .iter() - .map(|v| format!("{v:.5}")) - .collect(); - let e: f64 = self.in_buf[..n + OVERLAP] - .iter() - .map(|v| *v as f64 * *v as f64) - .sum(); - let ovl: Vec = self.in_buf[..4].iter().map(|v| format!("{v:.5}")).collect(); - eprintln!("XPRE {} | E {e:.6e} ovl {}", f.join(" "), ovl.join(" ")); - let fr: Vec = self.freq[..16].iter().map(|v| format!("{v:.5}")).collect(); - let be: Vec = self.band_e[..8].iter().map(|v| format!("{v:.5}")).collect(); - let bl: Vec = self.band_log_e[..8] - .iter() - .map(|v| format!("{v:.5}")) - .collect(); - eprintln!( - "XMDCT sb {short_blocks} {} | bandE {} | bandLogE {}", - fr.join(" "), - be.join(" "), - bl.join(" ") - ); - let sx: f64 = self.x[..n].iter().map(|v| v.abs() as f64).sum(); - let x0: Vec = self.x[..8].iter().map(|v| format!("{v:.5}")).collect(); - eprintln!("XNORM sumX {sx:.5} X0..8 {}", x0.join(" ")); - } - - // --- Dynalloc analysis (offsets + spread_weight + importance) ----- - self.offsets = [0; NB_BANDS]; - let mut spread_weight = [0i32; NB_BANDS]; - let mut importance = [0i32; NB_BANDS]; - let max_depth = self.dynalloc_analysis( - start, - end, - c, - lm, - is_transient, - effective_bytes, - &mut spread_weight, - &mut importance, - ); - - // --- tf_res --------------------------------------------------------- - // `TF_ANALYSIS`: run the libopus Viterbi tf search when there are - // enough bits; otherwise fall back to the no-analysis default (raw - // `is_transient` per band codes "no tf change" under tf_select=0). - const TF_ANALYSIS: bool = true; - let tf_select = if TF_ANALYSIS && effective_bytes >= 15 * c as i32 { - let lambda = (80i32).max(20480 / effective_bytes + 2); - self.tf_analysis( - end, - is_transient, - lambda, - n, - lm, - tf_estimate, - tf_chan, - &importance, - ) - } else { - self.tf_res = [i32::from(is_transient); NB_BANDS]; - 0usize - }; - - // --- Coarse energy -------------------------------------------------- - // libopus runs the two-pass coarse-energy search at complexity >= 4. - // MEASURED OFF (lane opus64, 12-row library gate vs libopus): it moves - // err_ratio 6 rows better / 4 worse (nik@96 .982->.990, reelo@64 - // 1.510->1.581, her@64 1.102->1.135, her@96 1.052->1.059; nik@64 - // .708->.703, reelo@96 .940->.872, dl8a .551/.374->.503/.346, hein - // .855/.528->.771/.419), corr within +.0001 everywhere. The KEEP rule - // is "err_ratio not worse on every row", so the search ships off. - // `EC_OPUS_TWO_PASS=1` re-arms it for a sweep (lane opusx2 r2). - const TWO_PASS_COARSE_ENERGY: bool = false; - let mut two_pass = TWO_PASS_COARSE_ENERGY || std::env::var_os("EC_OPUS_TWO_PASS").is_some(); - let mut intra = self.force_intra - || (!two_pass - && self.delayed_intra > (2 * c * (end - start)) as f32 - && nb_available > ((end - start) * c) as i32); - let new_distortion = { - let mut dist = 0.0f32; - for ch in 0..c { - for i in start..end { - let d = self.band_log_e[i + ch * NB_BANDS] - self.old_band_e[i + ch * NB_BANDS]; - dist += d * d; - } - } - dist.min(200.0) - }; - let tell = enc.tell(); - if tell + 3 > total_bits as u32 { - intra = false; - two_pass = false; - } - let max_decay = 16.0f32.min(0.125 * nb_available as f32); - if two_pass || intra { - intra = self.quant_coarse_energy(enc, start, end, intra, c, lm, total_bits, max_decay); - } else { - self.quant_coarse_energy_impl(enc, start, end, intra, c, lm, total_bits, max_decay); - } - self.delayed_intra = if intra { - new_distortion - } else { - PRED_COEF[lm] * PRED_COEF[lm] * self.delayed_intra + new_distortion - }; - - // --- tf encode ------------------------------------------------------ - self.tf_encode(enc, start, end, is_transient, lm, tf_select, nb_compressed); - - // --- Spread decision (libopus celt_encoder.c:1933-1977) -------------- - // No LFE, no hybrid, no complexity field (treated as ≥ 3): the only - // guards that apply are shortBlocks and nbAvailableBytes < 10*C. - if enc.tell() as i32 + 4 <= total_bits { - if short_blocks != 0 || nb_available < 10 * c as i32 { - self.spread_decision = SPREAD_NORMAL; - } else { - self.spread_decision = self.spreading_decision(end, c, lm, &spread_weight); - } - enc.enc_icdf(self.spread_decision, &SPREAD_ICDF, 5); - } - - // --- Caps ------------------------------------------------------------ - for i in 0..NB_BANDS { - let bw = (E_BANDS[i + 1] - E_BANDS[i]) << lm; - self.caps[i] = - ((CACHE_CAPS[NB_BANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * bw as i32) - >> 2; - } - let mut dynalloc_logp = 6u32; - let total_bits_frac = total_bits << BITRES; - let mut total_boost = 0i32; - let mut tell_frac = enc.tell_frac() as i32; - for i in start..end { - let width = ((c * (E_BANDS[i + 1] - E_BANDS[i])) << lm) as i32; - let quanta = (width << BITRES).min((6 << BITRES).max(width)); - let mut loop_logp = dynalloc_logp; - let mut boost = 0i32; - let mut j = 0i32; - while tell_frac + ((loop_logp as i32) << BITRES) < total_bits_frac - total_boost - && boost < self.caps[i] - { - let flag = j < self.offsets[i]; - enc.enc_bit_logp(flag, loop_logp); - tell_frac = enc.tell_frac() as i32; - if !flag { - break; - } - boost += quanta; - total_boost += quanta; - loop_logp = 1; - j += 1; - } - if j > 0 { - dynalloc_logp = dynalloc_logp.saturating_sub(1).max(2); - } - self.offsets[i] = boost; - } - - // --- Intensity decision (libopus celt_encoder.c:2392-2407) ------- - // Moved before alloc_trim so alloc_trim_analysis can use - // self.intensity in the stereo_saving minXC loop. - let overhead = (40 * c as i32 + 20) * ((400 >> lm) - 50); - let mut equiv_rate = ((nb_compressed as i32 * 8 * 50) << (3 - lm)) - overhead; - if vbr_rate_bps > 0 { - equiv_rate = equiv_rate.min(vbr_rate_bps as i32 - overhead); - } - if c == 2 { - self.intensity_decision(nb_compressed, c, lm, vbr_rate_bps); - self.intensity = self.intensity.clamp(start, end); - } - - // --- Allocation trim ------------------------------------------------ - let mut alloc_trim = 5i32; - if tell_frac + (6 << BITRES) <= total_bits_frac - total_boost { - alloc_trim = self.alloc_trim_analysis(end, lm, c, n, tf_estimate); - enc.enc_icdf(alloc_trim as usize, &TRIM_ICDF, 7); - tell_frac = enc.tell_frac() as i32; - } - - // --- Temporal VBR (libopus celt_encoder.c:2187-2204) ------------- - // lfe=0 so always computed. In float mode SHR32/SHL32/QCONST32 are - // identity, so follow/frame_avg/temporal_vbr are raw floats. - let temporal_vbr = { - let mut follow = -10.0f32; - let mut frame_avg = 0.0f32; - let offset = if short_blocks != 0 { - 0.5 * lm as f32 - } else { - 0.0 - }; - for i in start..end { - follow = (follow - 1.0).max(self.band_log_e[i] - offset); - if c == 2 { - follow = follow.max(self.band_log_e[i + NB_BANDS] - offset); - } - frame_avg += follow; - } - frame_avg /= (end - start) as f32; - let tvbr = (frame_avg - self.spec_avg).clamp(-1.5, 3.0); - self.spec_avg += 0.02 * tvbr; - tvbr - }; - - // --- Constrained VBR ------------------------------------------------ - if vbr_rate > 0 { - let lm_diff = 3 - lm as i32; - let hybrid = start != 0; - let offset_term = if self.constrained_vbr { - self.vbr_offset >> lm_diff - } else { - 0 - }; - let base_target = if hybrid { - (vbr_rate - ((9 * c as i32 + 4) << BITRES)).max(0) + offset_term - } else { - vbr_rate + offset_term - ((40 * c as i32 + 20) << BITRES) - }; - let mut target = base_target; - if hybrid { - let shift = 3 - lm as i32; - if self.silk_offset < 100 { - target += (12 << BITRES) >> shift; - } - if self.silk_offset > 100 { - target -= (18 << BITRES) >> shift; - } - target += ((tf_estimate - 0.25) * (50 << BITRES) as f32) as i32; - if tf_estimate > 0.7 { - target = target.max(50 << BITRES); - } - } else { - let (_, _, vbr_tonal, vbr_act, _, _) = analysis_params(); - // compute_vbr (libopus celt_encoder.c:1605-1716), float-mode. - // Skipped: activity, tonality, surround_mask (analysis->valid= - // false, has_surround_mask=0, pitch_change=0, lfe=0). The qext - // 2-pass transient compute_vbr (C:2546-2554) is inside - // #ifdef ENABLE_QEXT — this encoder has no qext. - let coded_bands = if self.last_coded_bands != 0 { - self.last_coded_bands - } else { - NB_BANDS - }; - let mut coded_bins = E_BANDS[coded_bands] << lm; - if c == 2 { - coded_bins += E_BANDS[self.intensity.min(coded_bands)] << lm; - } - // Low-activity cut (C:1632-1633). REJECTED on the 12-row gate - // (lane opustonal r2/r3): halves hein's err_ratio but costs - // her@96 +.020 and nik@96 +.005 -- see `analysis_params`. - if vbr_act && self.info.valid && self.info.activity < 0.4 { - target -= ((coded_bins << BITRES) as f32 * (0.4 - self.info.activity)) as i32; - } - // Stereo savings (C:1636-1649) - if c == 2 { - let coded_stereo_bands = self.intensity.min(coded_bands); - let coded_stereo_dof = (E_BANDS[coded_stereo_bands] << lm) - coded_stereo_bands; - let max_frac = 0.8 * coded_stereo_dof as f32 / coded_bins as f32; - let ss = self.stereo_saving.min(1.0); - target -= (max_frac * target as f32) - .min((ss - 0.1) * coded_stereo_dof as f32 * 8.0) - as i32; - } - // dynalloc boost minus calibration average (C:1651) - target += total_boost - (19 << lm); - // TF boost (C:1653-1654): MULT16_32_Q15 is identity in float mode, - // SHL32(.., 1) is the x2 and tf_calibration is .04 at a fixed frame - // size. MEASURED TWICE (lane opus-vbr r2/r3 on the old 14-row gate, - // lane opustr r2 on the 12-row one): the x2 costs .0030 corr on - // hein@64 and .0014 on hein@96 and pushes 5 err_ratio rows the - // wrong way, so the x1 stand-in stays. The reelm rows that carried - // the first rejection are gone; hein reproduced it exactly. - // SWEPT WHOLE (lane opustr2, 12 detached gate runs, r1 = this - // default reproducing the base rows exactly; the gate is - // deterministic, so every delta below is real, not run noise). - // err_ratio deltas vs r1, worst rows only: - // k=2 off=.04 her@96 +.021 hein@96 +.067, hein corr - // -.0024 (r2) - // k=1.5 off=.04/.06/.08 reelo@96 +.09 her@96 +.019, hein corr - // -.0012 -- the offset is inert (r3,7,6) - // k=2 off=.04 transient reelo@96 +.095 dl8a@96 +.040 (r4) - // k=1.5 off=.04 transient hein@64 +.026 her@96 +.020 (r5) - // k=2 tfe>=.6 / >=.35 nik@96 +.042/+.060 hein@96 +.075 (r9,10) - // k=1.25 tfe>=.6 / >=.35 hein@64 +.090 / dl8a@96 +.065 (r11,12) - // k=1.25 off=.044 her@64 +.001 her@96 +.021 ONLY, corr - // worst -.0005 (hein@64), and reell@64 - // 2.697->1.440, reell@96 4.499->2.516, - // hein@64 .853->.302, nik@64 .708->.643, - // dl8a@96 .374->.315 (r8) - // r8 is the nearest miss ever measured on this term and still - // fails the keep rule on her@96, so the x1 stand-in stays. Every - // variant that moves reell also costs her@96 ~+.02, and the reell gain - // comes entirely from frames with tf_estimate >= 0.6 (r11 keeps the - // full reell win) -- so her@96's loss lives on the same frames and - // no content gate built from `tf_estimate` or the transient flag - // can separate them. Upgrade path: libopus gates this boost with - // its tonality analysis (`analysis->valid`, music_prob), which this - // encoder does not run at all. Sweeps: lanes/opus-opustr2-r*.sweep.txt. - // SWEPT (lane opustr2): k/offset/gate come from `tf_boost_params()`; - // the defaults (k=1, off=.044, gate=all) are the shipped point and - // reproduce the line above byte for byte. - { - let (k, off, gate_transient, thresh) = tf_boost_params(); - let fires = (!gate_transient || is_transient) && tf_estimate >= thresh; - let k_eff = if fires { k } else { 1.0 }; - target += (k_eff * (tf_estimate - off) * target as f32) as i32; - } - // Tonality boost (C:1658-1669), compensating for the average. - // REJECTED on the 12-row gate (lane opustonal r2): it is what - // pushes reelo@96 .940->1.165 -- see `analysis_params`. - // `pitch_change` is 0 here (no prefilter), so its term is absent. - if vbr_tonal && self.info.valid { - let tonal = (self.info.tonality - 0.15).max(0.0) - 0.12; - target += ((coded_bins << BITRES) as f32 * 1.2 * tonal) as i32; - } - // floor depth cap (C:1683-1695): SHR32/MULT16_32_Q15 are identity. - { - let bins = E_BANDS[NB_BANDS - 2] << lm; - let floor_depth = ((c * bins * 8) as f32 * max_depth) as i32; - let floor_depth = floor_depth.max(target >> 2); - target = target.min(floor_depth); - } - // Constrained VBR (C:1699-1702) - target = base_target + (0.67 * (target - base_target) as f32) as i32; - // Temporal VBR (C:1704-1711) - if tf_estimate < 0.2 { - let amount = 0.0000031 * (96000 - equiv_rate).clamp(0, 32000) as f32; - target += (temporal_vbr * amount * target as f32) as i32; - } - // Never more than double the base rate (C:1714) - target = target.min(2 * base_target); - } - target += tell_frac; - let mut min_allowed = - ((tell_frac + total_boost + (1 << (BITRES + 3)) - 1) >> (BITRES + 3)) + 2; - if hybrid { - min_allowed = min_allowed.max( - (tell0_frac + (37 << BITRES) + total_boost + (1 << (BITRES + 3)) - 1) - >> (BITRES + 3), - ); - } - let mut nb_avail = (target + (1 << (BITRES + 2))) >> (BITRES + 3); - nb_avail = nb_avail.max(min_allowed); - nb_avail = nb_avail.min(nb_compressed as i32); - let mut delta = target - vbr_rate; - target = nb_avail << (BITRES + 3); - if silence { - delta = 0; - if hybrid { - nb_avail = 2; - target = (2 * 8) << BITRES; - } - } - let alpha = if self.vbr_count < 970 { - self.vbr_count += 1; - 1.0 / (self.vbr_count + 20) as f32 - } else { - 0.001 - }; - if self.constrained_vbr { - self.vbr_reservoir += target - vbr_rate; - self.vbr_drift += (alpha - * ((delta * (1 << lm_diff)) as f32 - - self.vbr_offset as f32 - - self.vbr_drift as f32)) as i32; - self.vbr_offset = -self.vbr_drift; - if hybrid { - if self.vbr_reservoir < 0 { - let adjust = (-self.vbr_reservoir) / (8 << BITRES); - if !silence { - nb_avail += adjust; - } - self.vbr_reservoir = 0; - } - } else { - // Bound banked credit at eight frames' worth of rate. - self.vbr_reservoir = self.vbr_reservoir.max(-8 * vbr_rate); - if self.vbr_reservoir < 0 { - // Release banked credit slowly (8 bytes per frame) so it stays - // available for transient boosts; libopus CVBR re-adds all of - // it to the next frame, which would defeat banking entirely. - // MEASURED (lane opustr r3, `lanes/opus-opustr-r3.sweep.txt`): - // restoring the libopus uncapped one-frame release on its own - // is neutral-to-worse -- 3 rows better, 5 worse (dl8a@96 - // .374->.415, hein@96 .528->.555, her@96 1.051->1.064) and - // hein@64 corr -.0008. The drip stays. - let adjust = ((-self.vbr_reservoir) / (8 << BITRES)).min(8); - if !silence { - nb_avail += adjust; - self.vbr_reservoir += adjust << (BITRES + 3); - } else { - self.vbr_reservoir = 0; - } - } - } - } - let floor = if hybrid { 0 } else { 2 }; - let shrunk = (nb_compressed as i32).min(nb_avail).max(floor) as usize; - if shrunk < nb_compressed { - nb_compressed = shrunk; - enc.shrink(nb_compressed); - } - } - - // --- Stereo decisions ----------------------------------------------- - let mut intensity = 0usize; - let mut dual_stereo = false; - if c == 2 { - if lm != 0 { - dual_stereo = self.stereo_analysis(lm, n); - } - intensity = self.intensity.clamp(start, end); - } - let _ = &mut effective_bytes; - - // --- Bit allocation ------------------------------------------------- - let mut bits = (((nb_compressed * 8) as i32) << BITRES) - enc.tell_frac() as i32 - 1; - let anti_collapse_rsv = if is_transient && lm >= 2 && bits >= ((lm as i32 + 2) << BITRES) { - 1 << BITRES - } else { - 0 - }; - bits -= anti_collapse_rsv; - let alloc = compute_allocation_encode( - enc, - start, - end, - alloc_trim, - bits, - c, - lm, - &self.offsets, - &self.caps, - &mut self.pulses, - &mut self.fine_quant, - &mut self.fine_priority, - intensity, - dual_stereo, - self.last_coded_bands, - ); - let intensity = alloc.intensity; - let dual_stereo = alloc.dual_stereo; - let balance = alloc.balance; - let coded_bands = alloc.coded_bands; - // libopus: lastCodedBands follows codedBands by at most one band per frame. - self.last_coded_bands = if self.last_coded_bands != 0 { - coded_bands.clamp(self.last_coded_bands - 1, self.last_coded_bands + 1) - } else { - coded_bands - }; - - // --- Fine energy ---------------------------------------------------- - for i in start..end { - if self.fine_quant[i] <= 0 { - continue; - } - let frac = 1 << self.fine_quant[i]; - for ch in 0..c { - let e = &mut self.error[i + ch * NB_BANDS]; - let q2 = (((*e + 0.5) * frac as f32).floor() as i32).clamp(0, frac - 1); - enc.enc_bits(q2 as u32, self.fine_quant[i] as u32); - let offset = (q2 as f32 + 0.5) / frac as f32 - 0.5; - self.old_band_e[i + ch * NB_BANDS] += offset; - *e -= offset; - } - } - - // --- Shapes --------------------------------------------------------- - self.quant_all_bands( - enc, - start, - end, - short_blocks, - self.spread_decision, - dual_stereo, - intensity, - (nb_compressed as i32 * (8 << BITRES)) - anti_collapse_rsv, - balance, - lm, - coded_bands, - c, - n, - ); - - // --- Anti-collapse -------------------------------------------------- - if anti_collapse_rsv > 0 { - let on = self.consec_transient < 2; - enc.enc_bits(u32::from(on), 1); - } - - // --- Leftover fine bits --------------------------------------------- - let mut bits_left = nb_compressed as i32 * 8 - enc.tell() as i32; - for prio in 0..2 { - for i in start..end { - if bits_left < c as i32 { - break; - } - if self.fine_quant[i] >= MAX_FINE_BITS || self.fine_priority[i] != prio { - continue; - } - for ch in 0..c { - let q2 = i32::from(self.error[i + ch * NB_BANDS] >= 0.0); - enc.enc_bits(q2 as u32, 1); - let offset = (q2 as f32 - 0.5) / (1 << (self.fine_quant[i] + 1)) as f32; - self.old_band_e[i + ch * NB_BANDS] += offset; - bits_left -= 1; - } - } - } - - if silence { - for e in self.old_band_e.iter_mut() { - *e = -28.0; - } - } - if c == 1 { - for i in 0..NB_BANDS { - self.old_band_e[NB_BANDS + i] = self.old_band_e[i]; - } - } - // Uncoded bands hold no energy history (the decoder clears them the - // same way), so a later start/end change predicts from the same state. - for ch in 0..2 { - for i in (0..start).chain(end..NB_BANDS) { - self.old_band_e[ch * NB_BANDS + i] = 0.0; - } - } - if is_transient { - self.consec_transient += 1; - } else { - self.consec_transient = 0; - } - self.force_intra = false; - - enc.done(); - if enc.error() { - return Err(Error::corrupt("celt encode: busted the frame budget")); - } - // Capture per-frame diagnostics for the dropout investigation. - let mut band_log_e = [0.0f32; 2 * NB_BANDS]; - band_log_e[..2 * NB_BANDS].copy_from_slice(&self.band_log_e); - self.last_diag = CeltFrameDiag { - is_transient, - short_blocks, - intra, - silence, - lm, - start, - coded_bands, - intensity, - dual_stereo, - alloc_trim, - vbr_reservoir: self.vbr_reservoir, - nb_compressed, - band_log_e, - pulses: self.pulses, - fine_quant: self.fine_quant, - analysis_valid: self.info.valid, - music_prob: self.info.music_prob, - tonality: self.info.tonality, - tonality_slope: self.info.tonality_slope, - activity: self.info.activity, - analysis_bandwidth: self.info.bandwidth, - }; - Ok(nb_compressed) - } - // -- Analysis ------------------------------------------------------------ - - /// `transient_analysis()` — libopus float-mode algorithm. - /// Returns `(is_transient, tf_estimate, tf_chan)`. - fn transient_analysis(&mut self, len: usize, c: usize, stride: usize) -> (bool, f32, usize) { - let tmp = &mut self.transient_tmp[..len]; - let len2 = len / 2; - let mut mask_metric: i32 = 0; - let mut tf_chan: usize = 0; - - for ch in 0..c { - // Copy this channel's samples (C layout: in[i + c*len] = in_buf[ch*stride + i]) - tmp.copy_from_slice(&self.in_buf[ch * stride..ch * stride + len]); - - // High-pass filter: (1 - 2*z^-1 + z^-2) / (1 - z^-1 + .5*z^-2) - let mut mem0 = 0.0f32; - let mut mem1 = 0.0f32; - for v in tmp.iter_mut() { - let x = *v; - let y = mem0 + x; - mem0 = mem1 + y - 2.0 * x; - mem1 = x - 0.5 * y; - *v = y; - } - // First few samples are bad because we don't propagate the memory - for v in tmp.iter_mut().take(12) { - *v = 0.0; - } - - // Forward pass: post-echo threshold (forward_decay = 0.0625) - let mut mean = 0.0f32; - let mut fm0 = 0.0f32; - for i in 0..len2 { - let x2 = tmp[2 * i] * tmp[2 * i] + tmp[2 * i + 1] * tmp[2 * i + 1]; - mean += x2; - tmp[i] = fm0 + 0.0625 * (x2 - fm0); - fm0 = tmp[i]; - } - - // Backward pass: pre-echo threshold (backward_decay = 0.125) - let mut bm0 = 0.0f32; - let mut max_e = 0.0f32; - for i in (0..len2).rev() { - tmp[i] = bm0 + 0.125 * (tmp[i] - bm0); - bm0 = tmp[i]; - max_e = max_e.max(bm0); - } - - // Geometric mean of frame energy and half the max - mean = (mean * max_e * 0.5 * len2 as f32).sqrt(); - - // Inverse of the mean energy (float mode: SHL32/SHR32 are no-ops) - let norm = len2 as f32 / (1e-15 + mean); - - // Harmonic mean discarding unreliable boundaries (1/4th of samples) - let mut unmask: i32 = 0; - let mut i = 12; - while i < len2 - 5 { - let id = ((64.0 * norm * (tmp[i] + 1e-15)).floor() as i32).clamp(0, 127) as usize; - unmask += INV_TABLE[id] as i32; - i += 4; - } - // Normalize: 1/4th sampling, factor of 6 in inv_table - unmask = 64 * unmask * 4 / (6 * (len2 as i32 - 17)); - if unmask > mask_metric { - tf_chan = ch; - mask_metric = unmask; - } - } - - let is_transient = mask_metric > 200; - // tf_max and tf_estimate (float mode: all Q-shifts are no-ops) - let tf_max = ((27.0 * mask_metric as f32).sqrt() - 42.0).max(0.0); - let tf_estimate = (0.0069 * tf_max.min(163.0) - 0.139).max(0.0).sqrt(); - - (is_transient, tf_estimate, tf_chan) - } - - /// libopus `dynalloc_analysis`: per-band boost requests from a follower / - /// median masking model over the long-window energies. Writes - /// `self.offsets[i]` in boost units (the loop that codes them converts to - /// bits via the band's quanta). Also computes `importance[]` for - /// `tf_analysis()` (libopus celt_encoder.c:1176-1189). - // Mirrors libopus's dynalloc_analysis() signature; the inputs stay separate. - #[allow(clippy::too_many_arguments)] - fn dynalloc_analysis( - &mut self, - start: usize, - end: usize, - c: usize, - lm: usize, - is_transient: bool, - effective_bytes: i32, - spread_weight: &mut [i32; NB_BANDS], - importance: &mut [i32; NB_BANDS], - ) -> f32 { - const LSB_DEPTH: f32 = 24.0; - let mut noise_floor = [0.0f32; NB_BANDS]; - for i in 0..end { - noise_floor[i] = 0.0625 * LOG_N[i] as f32 + 0.5 + (9.0 - LSB_DEPTH) - E_MEANS[i] - + 0.0062 * ((i + 5) * (i + 5)) as f32; - } - // maxDepth = max(bandLogE - noise_floor) across channels (libopus 995-999). - let mut max_depth = -31.9f32; - for ch in 0..c { - // Parallel arrays are indexed by band or bin, as in libopus. - #[allow(clippy::needless_range_loop)] - for i in 0..end { - max_depth = max_depth.max(self.band_log_e[ch * NB_BANDS + i] - noise_floor[i]); - } - } - // Simple masking model for spread_weight (libopus celt_encoder.c:1000-1035). - let mut mask = [0.0f32; NB_BANDS]; - for i in 0..end { - mask[i] = self.band_log_e[i] - noise_floor[i]; - } - if c == 2 { - for i in 0..end { - mask[i] = mask[i].max(self.band_log_e[NB_BANDS + i] - noise_floor[i]); - } - } - let mut sig = [0.0f32; NB_BANDS]; - sig[..end].copy_from_slice(&mask[..end]); - for i in 1..end { - mask[i] = mask[i].max(mask[i - 1] - 2.0); - } - for i in (0..end - 1).rev() { - mask[i] = mask[i].max(mask[i + 1] - 3.0); - } - for i in 0..end { - // SMR: mask is never more than 12 below the peak and never below the - // noise floor. - let smr = sig[i] - 0.0_f32.max(max_depth - 12.0).max(mask[i]); - let shift = (5).min(0.max(-((smr + 0.5).floor() as i32))); - spread_weight[i] = 32 >> shift; - } - // Dynamic allocation can't make us bust the budget (libopus 1036-1037). - if !(effective_bytes > 50 && lm >= 1) { - // Parallel arrays are indexed by band or bin, as in libopus. - #[allow(clippy::needless_range_loop)] - for i in start..end { - importance[i] = 13; - } - return max_depth; - } - let median3 = |a: &[f32]| -> f32 { - let (x, y, z) = (a[0], a[1], a[2]); - x.max(y).min(z).max(x.min(y)) - }; - let median5 = |a: &[f32]| -> f32 { - let mut v = [a[0], a[1], a[2], a[3], a[4]]; - v.sort_by(|p, q| p.partial_cmp(q).unwrap()); - v[2] - }; - let mut follower = [0.0f32; 2 * NB_BANDS]; - let mut last = 0usize; - for ch in 0..c { - let e2 = &self.band_log_e2[ch * NB_BANDS..ch * NB_BANDS + NB_BANDS]; - let f = &mut follower[ch * NB_BANDS..ch * NB_BANDS + NB_BANDS]; - f[0] = e2[0]; - for i in 1..end { - // The last band at least .5 dB above its predecessor bounds - // the backward pass (band-limited signals). - if e2[i] > e2[i - 1] + 0.5 { - last = i; - } - f[i] = (f[i - 1] + 1.5).min(e2[i]); - } - for i in (0..last).rev() { - f[i] = f[i].min((f[i + 1] + 2.0).min(e2[i])); - } - let offset = 1.0f32; - for i in 2..end.saturating_sub(2) { - f[i] = f[i].max(median5(&e2[i - 2..i + 3]) - offset); - } - let tmp = median3(&e2[0..3]) - offset; - f[0] = f[0].max(tmp); - f[1] = f[1].max(tmp); - let tmp = median3(&e2[end - 3..end]) - offset; - f[end - 2] = f[end - 2].max(tmp); - f[end - 1] = f[end - 1].max(tmp); - for i in 0..end { - f[i] = f[i].max(noise_floor[i]); - } - } - if c == 2 { - for i in start..end { - // 24 dB cross-talk between channels. - follower[NB_BANDS + i] = follower[NB_BANDS + i].max(follower[i] - 4.0); - follower[i] = follower[i].max(follower[NB_BANDS + i] - 4.0); - follower[i] = 0.5 - * ((self.band_log_e[i] - follower[i]).max(0.0) - + (self.band_log_e[NB_BANDS + i] - follower[NB_BANDS + i]).max(0.0)); - } - } else { - // Parallel arrays are indexed by band or bin, as in libopus. - #[allow(clippy::needless_range_loop)] - for i in start..end { - follower[i] = (self.band_log_e[i] - follower[i]).max(0.0); - } - } - // Importance for tf_analysis (libopus celt_encoder.c:1176-1189): - // 13 * 2^min(follower, 4), rounded to nearest integer. - for i in start..end { - importance[i] = (13.0 * (2.0_f32).powf(follower[i].min(4.0)) + 0.5).floor() as i32; - } - // Our VBR is always constrained: halve dynalloc on steady frames. - if !is_transient { - for f in &mut follower[start..end] { - *f *= 0.5; - } - } - // Parallel arrays are indexed by band or bin, as in libopus. - #[allow(clippy::needless_range_loop)] - for i in start..end { - if i < 8 { - follower[i] *= 2.0; - } - if i >= 12 { - follower[i] *= 0.5; - } - } - // libopus `celt_encoder.c:1226-1230`: the analysis's per-band - // leakage boost, in 1/64 dB units, on top of the follower. - if analysis_params().4 && self.info.valid { - // Parallel arrays are indexed by band or bin, as in libopus. - #[allow(clippy::needless_range_loop)] - for i in start..crate::analysis::LEAK_BANDS.min(end) { - follower[i] += f32::from(self.info.leak_boost[i]) / 64.0; - } - } - let mut tot_boost = 0i32; - for i in start..end { - let f = follower[i].min(4.0); - let width = ((c * (E_BANDS[i + 1] - E_BANDS[i])) << lm) as i32; - let (boost, boost_bits) = if width < 6 { - let b = f as i32; - (b, (b * width) << BITRES) - } else if width > 48 { - let b = (f * 8.0) as i32; - (b, ((b * width) << BITRES) / 8) - } else { - let b = (f * width as f32 / 6.0) as i32; - (b, (b * 6) << BITRES) - }; - // Constrained VBR, steady frame: dynalloc may take 2/3 of the bits. - if !is_transient && ((tot_boost + boost_bits) >> BITRES >> 3) > 2 * effective_bytes / 3 - { - let cap = ((2 * effective_bytes / 3) << BITRES) << 3; - self.offsets[i] = cap - tot_boost; - break; - } - self.offsets[i] = boost; - tot_boost += boost_bits; - } - max_depth - } - - /// libopus `spreading_decision` (bands.c:479-570): classifies the current - /// frame's spectral shape as `SPREAD_NONE`/`SPREAD_LIGHT`/`SPREAD_NORMAL`/ - /// `SPREAD_AGGRESSIVE` by counting how concentrated the normalized band - /// coefficients are, weighted by the masking-based `spread_weight` from - /// `dynalloc_analysis`. Maintains `tonal_average` (recursive averaging) - /// and applies hysteresis against the previous decision. - /// - /// `update_hf` is always false here (no pitch prefilter), so the - /// `hf_average`/`tapset_decision` state is carried but never updated — - /// matching libopus with `pf_on = false`. - fn spreading_decision( - &mut self, - end: usize, - c: usize, - lm: usize, - spread_weight: &[i32; NB_BANDS], - ) -> usize { - let m = 1usize << lm; - let n0 = SHORT_MDCT << lm; // = M * shortMdctSize - // Last band too narrow: nothing to spread. - if m * (E_BANDS[end] - E_BANDS[end - 1]) <= 8 { - return SPREAD_NONE; - } - let mut sum = 0i32; - let mut nb_bands = 0i32; - for ch in 0..c { - for i in 0..end { - let n = m * (E_BANDS[i + 1] - E_BANDS[i]); - if n <= 8 { - continue; - } - let base = ch * n0 + m * E_BANDS[i]; - let x = &self.x[base..base + n]; - let mut tcount = [0i32; 3]; - // Parallel arrays are indexed by band or bin, as in libopus. - #[allow(clippy::needless_range_loop)] - for j in 0..n { - // Float-mode: x2N = x[j]^2 * N; thresholds are the literal - // QCONST16 values (0.25, 0.0625, 0.015625). - let x2n = x[j] * x[j] * n as f32; - if x2n < 0.25 { - tcount[0] += 1; - } - if x2n < 0.0625 { - tcount[1] += 1; - } - if x2n < 0.015625 { - tcount[2] += 1; - } - } - // hf_sum accumulation is only used when update_hf is true - // (prefilter on), which never happens here. The branch is - // kept for structural fidelity but the result is unused. - let _hf_sum_contrib = if i > NB_BANDS - 4 { - 32 * (tcount[1] + tcount[0]) / n as i32 - } else { - 0 - }; - let tmp = (2 * tcount[2] >= n as i32) as i32 - + (2 * tcount[1] >= n as i32) as i32 - + (2 * tcount[0] >= n as i32) as i32; - sum += tmp * spread_weight[i]; - nb_bands += spread_weight[i]; - } - } - if nb_bands == 0 { - return self.spread_decision; - } - let mut s = (sum << 8) / nb_bands; - // Recursive averaging. - s = (s + self.tonal_average) >> 1; - self.tonal_average = s; - // Hysteresis against the last decision. - let last = self.spread_decision as i32; - s = (3 * s + (((3 - last) << 7) + 64) + 2) >> 2; - if s < 80 { - SPREAD_AGGRESSIVE - } else if s < 256 { - SPREAD_NORMAL - } else if s < 384 { - SPREAD_LIGHT - } else { - SPREAD_NONE - } - } - - fn compute_mdcts(&mut self, short_blocks: usize, lm: usize, n: usize, cc: usize, c: usize) { - let stride = n + OVERLAP; - let (n2, blocks, plan_lm) = if short_blocks != 0 { - (SHORT_MDCT, short_blocks, 0) - } else { - (n, 1, lm) - }; - for ch in 0..cc { - for b in 0..blocks { - let plan = &mut self.plans[plan_lm]; - plan.forward( - &self.in_buf, - ch * stride + b * n2, - &self.window, - &mut self.freq, - ch * n + b, - blocks, - ); - } - } - if cc == 2 && c == 1 { - for i in 0..n { - self.freq[i] = 0.5 * self.freq[i] + 0.5 * self.freq[n + i]; - } - } - } - - /// `alloc_trim_analysis()`: stereo correlation plus spectral tilt. - /// - /// This is the pre-1.1 libopus discrete ladder, not the continuous 1.3 - /// form. MEASURED (lane opustr r1, `lanes/opus-opustr-r1.sweep.txt`): the - /// whole 1.3 float function -- `trim += max(-4, .75*log2(1.001-sum^2))`, - /// `trim -= clamp(-2, 2, (diff+1)/6)` with `diff /= C*(end-1)`, and the - /// transient term `trim -= 2*tf_estimate` -- moves the 12-row library gate - /// 5 rows better / 4 worse on err_ratio (reelo@64 1.510->1.049, reell@96 - /// 4.499->2.458, nik@64 .708->.648, dl8a .552/.374->.487/.336; against - /// reell@64 2.697->2.872, her@96 1.051->1.085, nik@96 .985->1.006, her@64 - /// 1.103->1.109) and costs corr on every row (nik@64 .9887->.9878, - /// dl8a@64 .9889->.9879). The KEEP rule rejects it; this is the third - /// rejection of the same port (see `lanes/opus-trim-r2.{A,B}.sweep.txt`). - /// Do not re-port it without a fix for the transient rows first. - /// - /// `EC_OPUS_TRIM13=1` selects the continuous 1.3 form instead, for the - /// re-sweep on the aligned (delayed) spectrum the discrete ladder was - /// never measured against. - fn alloc_trim_analysis( - &mut self, - end: usize, - lm: usize, - c: usize, - n0: usize, - tf_estimate: f32, - ) -> i32 { - // Continuous (libopus 1.3+) trim; `EC_OPUS_TRIM13=0` restores the old discrete ladder. - let cont = !matches!(trim13_env(), Some(false)); - let mut trim_f = 5.0f32; - let mut trim = 5i32; - if c == 2 { - let mut sum = 0.0f32; - for i in 0..8 { - let mut partial = 0.0f32; - for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) { - partial += self.x[j] * self.x[n0 + j]; - } - sum += partial; - } - sum *= 1.0 / 8.0; - if cont { - let sum_c = sum.abs().min(1.0); - trim_f += (0.75 * (1.001 - sum_c * sum_c).log2()).max(-4.0); - } - if sum > 0.995 { - trim -= 4; - } else if sum > 0.92 { - trim -= 3; - } else if sum > 0.85 { - trim -= 2; - } else if sum > 0.8 { - trim -= 1; - } - // Stereo_saving: inter-channel correlation savings (libopus - // celt_encoder.c:897-920). In float mode all Q macros are - // identity; sum and per-band partial are raw inner products. - let sum_c = sum.abs().min(1.0); - let mut min_xc = sum_c; - for i in 8..self.intensity { - let mut partial = 0.0f32; - for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) { - partial += self.x[j] * self.x[n0 + j]; - } - min_xc = min_xc.min(partial.abs()); - } - min_xc = min_xc.min(1.0); - let log_xc = (1.001 - sum_c * sum_c).log2(); - let log_xc2 = (0.5 * log_xc).max((1.001 - min_xc * min_xc).log2()); - self.stereo_saving = (self.stereo_saving + 0.25).min(-0.5 * log_xc2); - } - let mut diff = 0.0f32; - for ch in 0..c { - for i in 0..end - 1 { - diff += self.band_log_e[i + ch * NB_BANDS] - * (2 + 2 * i as i32 - NB_BANDS as i32) as f32; - } - } - // libopus's `analysis->valid` term (celt_encoder.c:935-939): a tonal - // spectrum wants a lower trim. It is only defined on the continuous - // 1.3 trim; on the discrete ladder it can only be applied rounded, - // where it is inert (|term| <= .08). REJECTED with the 1.3 trim it - // belongs to -- see `analysis_params`, lane opustonal r1. - let tonal_trim = if analysis_params().1 && self.info.valid { - (2.0 * (self.info.tonality_slope + 0.05)).clamp(-2.0, 2.0) - } else { - 0.0 - }; - if cont { - // libopus divides the same sum by `C*(end-1)`; the ladder above - // carries an extra factor of two in its thresholds. - let diff = diff / (c * (end - 1)) as f32; - trim_f -= ((diff + 1.0) / 6.0).clamp(-2.0, 2.0); - trim_f -= 2.0 * tf_estimate; - trim_f -= tonal_trim; - return (trim_f + 0.5).floor().clamp(0.0, 10.0) as i32; - } - trim -= tonal_trim.round_ties_even() as i32; - diff /= (2 * c * (end - 1)) as f32; - if diff > 2.0 { - trim -= 1; - } - if diff > 8.0 { - trim -= 1; - } - if diff < -4.0 { - trim += 1; - } - if diff < -10.0 { - trim += 1; - } - trim.clamp(0, 10) - } - - /// libopus `equiv_rate` + `hysteresis_decision()` for the intensity band: - /// the frame's bytes as a 20 ms-equivalent bitrate minus the per-frame - /// overhead, capped by the VBR target. Idempotent within a frame. - fn intensity_decision(&mut self, nb_compressed: usize, c: usize, lm: usize, vbr_rate_bps: u32) { - let overhead = (40 * c as i32 + 20) * ((400 >> lm) - 50); - let mut equiv_rate = ((nb_compressed as i32 * 8 * 50) << (3 - lm)) - overhead; - if vbr_rate_bps > 0 { - equiv_rate = equiv_rate.min(vbr_rate_bps as i32 - overhead); - } - self.intensity = hysteresis_decision( - equiv_rate as f32 / 1000.0, - &INTENSITY_THRESHOLDS, - &INTENSITY_HYSTERESIS, - self.intensity, - ); - } - - /// `stereo_analysis()`: L1 entropy model of L/R against M/S. - fn stereo_analysis(&self, lm: usize, n0: usize) -> bool { - let mut sum_lr = 1e-15f64; - let mut sum_ms = 1e-15f64; - for i in 0..13 { - for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) { - let l = self.x[j] as f64; - let r = self.x[n0 + j] as f64; - sum_lr += l.abs() + r.abs(); - sum_ms += (l + r).abs() + (l - r).abs(); - } - } - // The reference's own literal (bands.c, stereo_analysis), kept as such. - #[allow(clippy::approx_constant)] - const SQRT_HALF: f64 = 0.707107; - sum_ms *= SQRT_HALF; - let mut thetas = 13; - if lm <= 1 { - thetas -= 8; - } - ((E_BANDS[13] << (lm + 1)) + thetas) as f64 * sum_ms - > ((E_BANDS[13] << (lm + 1)) as f64) * sum_lr - } - - // -- Energy -------------------------------------------------------------- - - #[allow(clippy::too_many_arguments)] - /// libopus `quant_coarse_energy_impl()`: codes one pass of coarse energy - /// with the given intra setting and returns its *badness* — the total - /// clamping the bit budget forced on the quantised deltas, which the - /// two-pass search in [`CeltEncoder::quant_coarse_energy`] minimises. - fn quant_coarse_energy_impl( - &mut self, - enc: &mut RangeEncoder, - start: usize, - end: usize, - intra: bool, - c: usize, - lm: usize, - budget: i32, - max_decay: f32, - ) -> i32 { - let mut badness = 0i32; - let tell = enc.tell() as i32; - if tell + 3 <= budget { - enc.enc_bit_logp(intra, 3); - } - let model = &E_PROB_MODEL[lm][usize::from(intra)]; - let (coef, beta) = if intra { - (0.0, BETA_INTRA) - } else { - (PRED_COEF[lm], BETA_COEF[lm]) - }; - let mut prev = [0.0f32; 2]; - for i in start..end { - for (ch, prev) in prev.iter_mut().enumerate().take(c) { - let x = self.band_log_e[i + ch * NB_BANDS]; - let old_raw = self.old_band_e[i + ch * NB_BANDS]; - let old = old_raw.max(-9.0); - let f = x - coef * old - *prev; - let mut qi = (0.5 + f).floor() as i32; - let decay_bound = old_raw.max(-28.0) - max_decay; - // Prevent the energy from dropping faster than the decoder - // can follow. - if qi < 0 && x < decay_bound { - qi += (decay_bound - x) as i32; - if qi > 0 { - qi = 0; - } - } - let qi0 = qi; - let tell = enc.tell() as i32; - let bits_left = budget - tell - 3 * (c as i32) * (end - i) as i32; - if i != start && bits_left < 30 { - if bits_left < 24 { - qi = qi.min(1); - } - if bits_left < 16 { - qi = qi.max(-1); - } - } - if budget - tell >= 15 { - let pi = 2 * i.min(20); - laplace_encode( - enc, - &mut qi, - (model[pi] as u32) << 7, - (model[pi + 1] as i32) << 6, - ); - } else if budget - tell >= 2 { - qi = qi.clamp(-1, 1); - enc.enc_icdf( - ((2 * qi) ^ -i32::from(qi < 0)) as usize, - &SMALL_ENERGY_ICDF, - 2, - ); - } else if budget - tell >= 1 { - qi = qi.min(0); - enc.enc_bit_logp(qi != 0, 1); - } else { - qi = -1; - } - self.error[i + ch * NB_BANDS] = f - qi as f32; - badness += (qi0 - qi).abs(); - let q = qi as f32; - self.old_band_e[i + ch * NB_BANDS] = coef * old + *prev + q; - *prev += q - beta * q; - } - } - badness - } - - /// libopus `quant_coarse_energy()`: codes the coarse band energies twice — - /// once intra, once inter-predicted — and keeps the pass with the lower - /// badness, breaking ties on bits used. `intra_bias` is zero here because - /// this encoder has no packet-loss rate to trade against. - #[allow(clippy::too_many_arguments)] - fn quant_coarse_energy( - &mut self, - enc: &mut RangeEncoder, - start: usize, - end: usize, - intra: bool, - c: usize, - lm: usize, - budget: i32, - max_decay: f32, - ) -> bool { - let start_state = enc.snapshot(); - let start_offs = enc.front_offs(); - self.old_e_save.copy_from_slice(&self.old_band_e); - // Pass 1 is always the intra one, as in the reference. - let badness1 = - self.quant_coarse_energy_impl(enc, start, end, true, c, lm, budget, max_decay); - if intra { - return true; - } - let tell_intra = enc.tell_frac(); - let intra_state = enc.snapshot(); - let intra_offs = enc.front_offs(); - self.coarse_bytes.clear(); - self.coarse_bytes - .extend_from_slice(&enc.front()[start_offs..intra_offs]); - self.old_e_intra.copy_from_slice(&self.old_band_e); - self.error_intra.copy_from_slice(&self.error); - - // Pass 2: inter-predicted, from the state the first pass started in. - enc.restore(&start_state); - self.old_band_e.copy_from_slice(&self.old_e_save); - let badness2 = - self.quant_coarse_energy_impl(enc, start, end, false, c, lm, budget, max_decay); - if badness1 < badness2 || (badness1 == badness2 && enc.tell_frac() > tell_intra) { - enc.restore(&intra_state); - enc.front_write(start_offs, &self.coarse_bytes); - self.old_band_e.copy_from_slice(&self.old_e_intra); - self.error.copy_from_slice(&self.error_intra); - return true; - } - false - } - - #[allow(clippy::too_many_arguments)] - fn tf_encode( - &mut self, - enc: &mut RangeEncoder, - start: usize, - end: usize, - transient: bool, - lm: usize, - mut tf_select: usize, - len: usize, - ) { - let mut budget = (len * 8) as i32; - let mut tell = enc.tell() as i32; - let mut logp: u32 = if transient { 2 } else { 4 }; - let tf_select_rsv = lm > 0 && tell + (logp as i32) < budget; - budget -= i32::from(tf_select_rsv); - let mut curr = 0i32; - let mut changed = false; - for i in start..end { - if tell + (logp as i32) <= budget { - enc.enc_bit_logp((self.tf_res[i] ^ curr) != 0, logp); - tell = enc.tell() as i32; - curr = self.tf_res[i]; - changed |= curr != 0; - } else { - self.tf_res[i] = curr; - } - logp = if transient { 4 } else { 5 }; - } - let t = usize::from(transient); - let ch = usize::from(changed); - if tf_select_rsv && TF_SELECT[lm][4 * t + ch] != TF_SELECT[lm][4 * t + 2 + ch] { - enc.enc_bit_logp(tf_select != 0, 1); - } else { - tf_select = 0; - } - for i in start..end { - self.tf_res[i] = TF_SELECT[lm][4 * t + 2 * tf_select + self.tf_res[i] as usize]; - } - } - - /// `tf_analysis()` — libopus Viterbi time/frequency search. - /// Writes `self.tf_res[0..len]` and returns `tf_select`. - #[allow(clippy::too_many_arguments)] - fn tf_analysis( - &mut self, - len: usize, - is_transient: bool, - lambda: i32, - n: usize, - lm: usize, - tf_estimate: f32, - tf_chan: usize, - importance: &[i32; NB_BANDS], - ) -> usize { - // bias = 0.04 * max(-0.25, 0.5 - tf_estimate) - let bias = 0.04 * (0.5 - tf_estimate).max(-0.25); - let t = usize::from(is_transient); - - let mut metric = [0i32; NB_BANDS]; - let mut path0 = [0i32; NB_BANDS]; - let mut path1 = [0i32; NB_BANDS]; - let mut tf_res = [0i32; NB_BANDS]; - - // Max band width for tmp/tmp_1 scratch - let max_band_w = ((E_BANDS[len] - E_BANDS[len - 1]) << lm).max(1); - let (tmp_s, tmp_1_s) = self.hadamard_tmp.split_at_mut(max_band_w); - let x = &self.x; - - for i in 0..len { - let band_w = (E_BANDS[i + 1] - E_BANDS[i]) << lm; - let narrow = E_BANDS[i + 1] - E_BANDS[i] == 1; - let tmp = &mut tmp_s[..band_w]; - let tmp_1 = &mut tmp_1_s[..band_w]; - - // Copy band coefficients: X[tf_chan*N0 + (eBands[i]<> lm, 1 << lm); - let l1 = l1_metric(tmp_1, band_w, lm + 1, bias); - if l1 < best_l1 { - best_l1 = l1; - best_level = -1; - } - } - - for k in 0..(lm + usize::from(!(is_transient || narrow))) { - let b = if is_transient { lm - k - 1 } else { k + 1 }; - haar1(tmp, band_w >> k, 1 << k); - let l1 = l1_metric(tmp, band_w, b, bias); - if l1 < best_l1 { - best_l1 = l1; - best_level = (k as i32) + 1; - } - } - - metric[i] = if is_transient { - 2 * best_level - } else { - -2 * best_level - }; - if narrow && (metric[i] == 0 || metric[i] == -2 * lm as i32) { - metric[i] -= 1; - } - } - - // Search for optimal tf resolution (tf_select) - let mut tf_select = 0usize; - let mut selcost = [0i32; 2]; - for sel in 0..2 { - let mut cost0 = importance[0] * (metric[0] - 2 * TF_SELECT[lm][4 * t + 2 * sel]).abs(); - let mut cost1 = importance[0] - * (metric[0] - 2 * TF_SELECT[lm][4 * t + 2 * sel + 1]).abs() - + if is_transient { 0 } else { lambda }; - for i in 1..len { - let curr0 = cost0.min(cost1 + lambda); - let curr1 = (cost0 + lambda).min(cost1); - cost0 = - curr0 + importance[i] * (metric[i] - 2 * TF_SELECT[lm][4 * t + 2 * sel]).abs(); - cost1 = curr1 - + importance[i] * (metric[i] - 2 * TF_SELECT[lm][4 * t + 2 * sel + 1]).abs(); - } - selcost[sel] = cost0.min(cost1); - } - if selcost[1] < selcost[0] && is_transient { - tf_select = 1; - } - if std::env::var_os("EC_OPUS_TF_DEBUG").is_some() { - let fp: f32 = self.x[tf_chan * n..tf_chan * n + (E_BANDS[len] << lm)] - .iter() - .map(|v| v.abs()) - .sum(); - let ble: Vec = self.band_log_e[..8] - .iter() - .map(|v| format!("{v:.3}")) - .collect(); - eprint!("BLE {} | FP {fp:.6} ", ble.join(" ")); - eprintln!( - "tf: trans {is_transient} lm {lm} tfe {tf_estimate:.4} bias {bias:.5} \ - lambda {lambda} sel {tf_select} selcost {selcost:?} metric {:?} imp {:?}", - &metric[..len], - &importance[..len] - ); - } - - // Final Viterbi forward pass - let mut cost0 = - importance[0] * (metric[0] - 2 * TF_SELECT[lm][4 * t + 2 * tf_select]).abs(); - let mut cost1 = importance[0] - * (metric[0] - 2 * TF_SELECT[lm][4 * t + 2 * tf_select + 1]).abs() - + if is_transient { 0 } else { lambda }; - for i in 1..len { - // curr0: best path to state 0 - let from0 = cost0; - let from1 = cost1 + lambda; - let (curr0, p0) = if from0 < from1 { - (from0, 0) - } else { - (from1, 1) - }; - path0[i] = p0; - // curr1: best path to state 1 (uses OLD cost0) - let from0 = cost0 + lambda; - let from1 = cost1; - let (curr1, p1) = if from0 < from1 { - (from0, 0) - } else { - (from1, 1) - }; - path1[i] = p1; - - cost0 = curr0 - + importance[i] * (metric[i] - 2 * TF_SELECT[lm][4 * t + 2 * tf_select]).abs(); - cost1 = curr1 - + importance[i] * (metric[i] - 2 * TF_SELECT[lm][4 * t + 2 * tf_select + 1]).abs(); - } - - // Backward pass - tf_res[len - 1] = if cost0 < cost1 { 0 } else { 1 }; - for i in (0..len - 1).rev() { - tf_res[i] = if tf_res[i + 1] == 1 { - path1[i + 1] - } else { - path0[i + 1] - }; - } - - self.tf_res = tf_res; - tf_select - } - - // -- Band shapes --------------------------------------------------------- - - #[allow(clippy::too_many_arguments)] - fn quant_all_bands( - &mut self, - enc: &mut RangeEncoder, - start: usize, - end: usize, - short_blocks: usize, - spread: usize, - mut dual_stereo: bool, - intensity: usize, - total_bits: i32, - mut balance: i32, - lm: usize, - coded_bands: usize, - c: usize, - n: usize, - ) { - let m = 1usize << lm; - let blocks = if short_blocks != 0 { m } else { 1 }; - for i in start..end { - let n_band = m * E_BANDS[i + 1] - m * E_BANDS[i]; - let tell = enc.tell_frac() as i32; - if i != start { - balance -= tell; - } - let mut remaining_bits = total_bits - tell - 1; - let b = if i < coded_bands { - let curr_balance = balance / 3.min(coded_bands - i) as i32; - 0.max(16383.min((remaining_bits + 1).min(self.pulses[i] + curr_balance))) - } else { - 0 - }; - let tf_change = self.tf_res[i]; - if dual_stereo && i == intensity { - dual_stereo = false; - } - let x_off = m * E_BANDS[i]; - let base = EncBand { - i, - x: x_off, - y: None, - n: n_band, - b, - spread, - blocks, - intensity, - tf_change, - level: 0, - lm: lm as i32, - }; - if dual_stereo { - self.quant_band(enc, EncBand { b: b / 2, ..base }, &mut remaining_bits); - self.quant_band( - enc, - EncBand { - x: n + x_off, - b: b / 2, - ..base - }, - &mut remaining_bits, - ); - } else { - self.quant_band( - enc, - EncBand { - y: if c == 2 { Some(n + x_off) } else { None }, - ..base - }, - &mut remaining_bits, - ); - } - balance += self.pulses[i] + tell; - } - } - - /// Encodes one band (Section 5.3.4-5.3.5), recursing for splits and for - /// stereo. The mirror of the decoder's `quant_band`, with the resynthesis - /// paths removed — nothing the encoder writes depends on them. - fn quant_band(&mut self, enc: &mut RangeEncoder, a: EncBand, remaining_bits: &mut i32) { - let EncBand { - i, - x, - mut y, - mut n, - mut b, - spread, - mut blocks, - intensity, - mut tf_change, - level, - mut lm, - } = a; - let stereo = y.is_some(); - let mut split = stereo; - let long_blocks = blocks == 1; - let mut b0 = blocks; - - if n == 1 { - for offs in [Some(x), y].into_iter().flatten() { - if *remaining_bits >= 1 << BITRES { - let sign = self.x[offs] < 0.0; - enc.enc_bits(u32::from(sign), 1); - *remaining_bits -= 1 << BITRES; - } - } - return; - } - - let mut n_b = n / blocks; - if !stereo && level == 0 { - let recombine = if tf_change > 0 { tf_change as usize } else { 0 }; - for k in 0..recombine { - haar1(&mut self.x[x..], n >> k, 1 << k); - } - blocks >>= recombine; - n_b <<= recombine; - while (n_b & 1) == 0 && tf_change < 0 { - haar1(&mut self.x[x..], n_b, blocks); - blocks <<= 1; - n_b >>= 1; - tf_change += 1; - } - b0 = blocks; - if b0 > 1 { - deinterleave_hadamard( - &mut self.x[x..x + n], - &mut self.hadamard_tmp, - n_b >> recombine, - b0 << recombine, - long_blocks, - ); - } - } - - let cache_start = cache_index(i, lm); - let cache0 = CACHE_BITS[cache_start] as usize; - if !stereo && lm != -1 && b > CACHE_BITS[cache_start + cache0] as i32 + 12 && n > 2 { - n >>= 1; - y = Some(x + n); - split = true; - lm -= 1; - blocks = (blocks + 1) >> 1; - } - - if split { - let pulse_cap = LOG_N[i] + lm * (1 << BITRES); - let offset = (pulse_cap >> 1) - - if stereo && n == 2 { - QTHETA_OFFSET_TWOPHASE - } else { - QTHETA_OFFSET - }; - let mut qn = compute_qn(n as i32, b, offset, pulse_cap, stereo); - if stereo && i >= intensity { - qn = 1; - } - // The angle between the two halves, before any quantisation. - let mut itheta = { - let yy = y.unwrap(); - let (xs, ys) = (&self.x[x..x + n], &self.x[yy..yy + n]); - stereo_itheta(xs, ys, stereo, n) - }; - let tell = enc.tell_frac() as i32; - if qn != 1 { - itheta = (itheta * qn + 8192) >> 14; - // Entropy coding of the angle: step pdf for stereo, uniform - // for the time split, triangular otherwise. - if stereo && n > 2 { - let p0 = 3i32; - let x0 = qn / 2; - let ft = (p0 * (x0 + 1) + x0) as u32; - let xv = itheta; - let (fl, fh) = if xv <= x0 { - (p0 * xv, p0 * (xv + 1)) - } else { - ((xv - 1 - x0) + (x0 + 1) * p0, (xv - x0) + (x0 + 1) * p0) - }; - enc.encode(fl as u32, fh as u32, ft); - } else if b0 > 1 || stereo { - enc.enc_uint(itheta as u32, (qn + 1) as u32); - } else { - let ft = ((qn >> 1) + 1) * ((qn >> 1) + 1); - let (fl, fs) = if itheta <= qn >> 1 { - ((itheta * (itheta + 1)) >> 1, itheta + 1) - } else { - ( - ft - (((qn + 1 - itheta) * (qn + 2 - itheta)) >> 1), - qn + 1 - itheta, - ) - }; - enc.encode(fl as u32, (fl + fs) as u32, ft as u32); - } - itheta = itheta * 16384 / qn; - if stereo { - let yy = y.unwrap(); - if itheta == 0 { - self.intensity_stereo(i, x, yy, n); - } else { - // stereo_split - for j in 0..n { - let l = core::f32::consts::FRAC_1_SQRT_2 * self.x[x + j]; - let r = core::f32::consts::FRAC_1_SQRT_2 * self.x[yy + j]; - self.x[x + j] = l + r; - self.x[yy + j] = r - l; - } - } - } - } else if stereo { - let yy = y.unwrap(); - let inv = itheta > 8192; - if inv { - for j in 0..n { - self.x[yy + j] = -self.x[yy + j]; - } - } - self.intensity_stereo(i, x, yy, n); - if b > 2 << BITRES && *remaining_bits > 2 << BITRES { - enc.enc_bit_logp(inv, 2); - } - itheta = 0; - } - let qalloc = enc.tell_frac() as i32 - tell; - b -= qalloc; - - let mut delta; - let imid; - let iside; - if itheta == 0 { - imid = 32767; - iside = 0; - delta = -16384; - } else if itheta == 16384 { - imid = 0; - iside = 32767; - delta = 16384; - } else { - imid = bitexact_cos(itheta as i16) as i32; - iside = bitexact_cos((16384 - itheta) as i16) as i32; - delta = frac_mul16( - ((n as i32 - 1) << 7) as i16, - bitexact_log2tan(iside, imid) as i16, - ); - } - let _ = imid; - let _ = iside; - - if n == 2 && stereo { - let mut mbits = b; - let mut sbits = 0; - if itheta != 0 && itheta != 16384 { - sbits = 1 << BITRES; - } - mbits -= sbits; - let yy = y.unwrap(); - let swap = itheta > 8192; - *remaining_bits -= qalloc + sbits; - let (x2, y2) = if swap { (yy, x) } else { (x, yy) }; - if sbits != 0 { - let sign = self.x[x2] * self.x[y2 + 1] - self.x[x2 + 1] * self.x[y2] < 0.0; - enc.enc_bits(u32::from(sign), 1); - } - self.quant_band( - enc, - EncBand { - x: x2, - y: None, - n, - b: mbits, - blocks, - tf_change, - lm, - ..a - }, - remaining_bits, - ); - } else { - if b0 > 1 && !stereo && (itheta & 0x3fff) != 0 { - if itheta > 8192 { - delta -= delta >> (4 - lm); - } else { - delta = 0.min(delta + ((n as i32) << BITRES >> (5 - lm))); - } - } - let mut mbits = 0.max(b.min((b - delta) / 2)); - let mut sbits = b - mbits; - *remaining_bits -= qalloc; - let next_level = if stereo { level } else { level + 1 }; - let mid_args = EncBand { - x, - y: None, - n, - blocks, - tf_change, - level: next_level, - lm, - ..a - }; - let side_args = EncBand { - x: y.unwrap(), - y: None, - n, - blocks, - tf_change, - level: next_level, - lm, - ..a - }; - let mut rebalance = *remaining_bits; - if mbits >= sbits { - self.quant_band( - enc, - EncBand { - b: mbits, - ..mid_args - }, - remaining_bits, - ); - rebalance = mbits - (rebalance - *remaining_bits); - if rebalance > 3 << BITRES && itheta != 0 { - sbits += rebalance - (3 << BITRES); - } - self.quant_band( - enc, - EncBand { - b: sbits, - ..side_args - }, - remaining_bits, - ); - } else { - self.quant_band( - enc, - EncBand { - b: sbits, - ..side_args - }, - remaining_bits, - ); - rebalance = sbits - (rebalance - *remaining_bits); - if rebalance > 3 << BITRES && itheta != 16384 { - mbits += rebalance - (3 << BITRES); - } - self.quant_band( - enc, - EncBand { - b: mbits, - ..mid_args - }, - remaining_bits, - ); - } - } - } else { - // The basic no-split case: straight PVQ. - let mut q = bits2pulses(i, lm, b); - let mut curr_bits = pulses2bits(i, lm, q); - *remaining_bits -= curr_bits; - while *remaining_bits < 0 && q > 0 { - *remaining_bits += curr_bits; - q -= 1; - curr_bits = pulses2bits(i, lm, q); - *remaining_bits -= curr_bits; - } - if q != 0 { - let k = get_pulses(q) as usize; - self.alg_quant(enc, x, n, k, spread, blocks); - } - // q == 0: the decoder folds or fills with noise on its own; - // nothing is coded. - } - } - - /// `intensity_stereo()`: collapses the pair onto a single channel weighted - /// by the band energies; only the combined channel is coded. - fn intensity_stereo(&mut self, band: usize, x: usize, y: usize, n: usize) { - let left = self.band_e[band]; - let right = self.band_e[band + NB_BANDS]; - let norm = 1e-15 + (1e-15 + left * left + right * right).sqrt(); - let a1 = left / norm; - let a2 = right / norm; - for j in 0..n { - let l = self.x[x + j]; - let r = self.x[y + j]; - self.x[x + j] = a1 * l + a2 * r; - } - } - - /// `alg_quant()`: the PVQ search — greedy pyramid projection plus one - /// pulse at a time on the exact `Rxy^2/Ryy` criterion — then the - /// enumeration encode. - fn alg_quant( - &mut self, - enc: &mut RangeEncoder, - x: usize, - n: usize, - k: usize, - spread: usize, - blocks: usize, - ) { - debug_assert!(n > 1 && k > 0); - exp_rotation(&mut self.x[x..x + n], n, 1, blocks, k, spread); - let xs = &mut self.x[x..x + n]; - let iy = &mut self.iy[..n]; - let y = &mut self.pvq_y[..n]; - let signs = &mut self.pvq_sign[..n]; - for j in 0..n { - if xs[j] > 0.0 { - signs[j] = 1; - } else { - signs[j] = -1; - xs[j] = -xs[j]; - } - iy[j] = 0; - y[j] = 0.0; - } - let mut xy = 0.0f32; - let mut yy = 0.0f32; - let mut pulses_left = k as i32; - if k > n >> 1 { - let mut sum = 0.0f32; - for v in xs.iter() { - sum += *v; - } - if !(sum > 1e-15 && sum < 64.0) { - xs[0] = 1.0; - for v in xs.iter_mut().skip(1) { - *v = 0.0; - } - sum = 1.0; - } - let rcp = (k as f32 - 1.0) / sum; - for j in 0..n { - iy[j] = (rcp * xs[j]).floor() as i32; - y[j] = iy[j] as f32; - yy += y[j] * y[j]; - xy += xs[j] * y[j]; - y[j] *= 2.0; - pulses_left -= iy[j]; - } - } - debug_assert!(pulses_left >= 1); - if pulses_left > n as i32 + 3 { - let tmp = pulses_left as f32; - yy += tmp * tmp; - yy += tmp * y[0]; - iy[0] += pulses_left; - pulses_left = 0; - } - // The pulse-placement search is the encoder's hottest loop — O(K*N) - // per band, dominant at high rates — so it runs eight candidates a - // lane with `wide`. Lane-local bests are reduced after the sweep; - // only the tie-breaking order differs from the scalar loop, and any - // pulse choice is a valid codeword — the enumeration, not the - // search, is what conformance constrains. - for _ in 0..pulses_left { - yy += 1.0; - let mut best_id = 0usize; - let mut best_num = -1e15f32; - let mut best_den = 0.0f32; - let mut j0 = 0usize; - if n >= 16 { - use wide::f32x8; - let chunks = n / 8; - let xy_v = f32x8::splat(xy); - let yy_v = f32x8::splat(yy); - let mut bn = f32x8::splat(-1e15); - let mut bd = f32x8::splat(0.0); - let mut bc = f32x8::splat(0.0); - for c in 0..chunks { - let mut xa = [0f32; 8]; - let mut ya = [0f32; 8]; - xa.copy_from_slice(&xs[c * 8..c * 8 + 8]); - ya.copy_from_slice(&y[c * 8..c * 8 + 8]); - let rxy = xy_v + f32x8::from(xa); - let ryy = yy_v + f32x8::from(ya); - let rxy2 = rxy * rxy; - let mask = (bd * rxy2).simd_gt(ryy * bn); - // wide 1.5 deprecates `blend` in favour of a split that - // does not exist yet in this release; the mask here is a - // true lane mask, which is exactly blend's contract. - #[allow(deprecated)] - { - bn = mask.blend(rxy2, bn); - bd = mask.blend(ryy, bd); - bc = mask.blend(f32x8::splat(c as f32), bc); - } - } - let bn_a: [f32; 8] = bn.into(); - let bd_a: [f32; 8] = bd.into(); - let bc_a: [f32; 8] = bc.into(); - for l in 0..8 { - if best_den * bn_a[l] > bd_a[l] * best_num { - best_den = bd_a[l]; - best_num = bn_a[l]; - best_id = bc_a[l] as usize * 8 + l; - } - } - j0 = chunks * 8; - } - for j in j0..n { - let rxy = xy + xs[j]; - let ryy = yy + y[j]; - let rxy2 = rxy * rxy; - if best_den * rxy2 > ryy * best_num { - best_den = ryy; - best_num = rxy2; - best_id = j; - } - } - xy += xs[best_id]; - yy += y[best_id]; - y[best_id] += 2.0; - iy[best_id] += 1; - } - for j in 0..n { - if signs[j] < 0 { - iy[j] = -iy[j]; - } - } - encode_pulses(enc, &self.iy[..n], n, k); - } -} - -const INTENSITY_THRESHOLDS: [f32; 21] = [ - 1., 2., 3., 4., 5., 6., 7., 8., 16., 24., 36., 44., 50., 56., 62., 67., 72., 79., 88., 106., - 134., -]; -const INTENSITY_HYSTERESIS: [f32; 21] = [ - 1., 1., 1., 1., 1., 1., 1., 2., 2., 2., 2., 2., 2., 2., 3., 3., 4., 5., 6., 8., 8., -]; - -/// libopus `hysteresis_decision()`: the largest `i` with `val >= thresholds[i]`, -/// sticky around the previous decision by `hysteresis`. -fn hysteresis_decision(val: f32, thresholds: &[f32], hysteresis: &[f32], prev: usize) -> usize { - let n = thresholds.len(); - let mut i = 0; - while i < n { - if val < thresholds[i] { - break; - } - i += 1; - } - if i > prev && val < thresholds[prev] + hysteresis[prev] { - i = prev; - } - if i < prev && val > thresholds[prev - 1] - hysteresis[prev - 1] { - i = prev; - } - i -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::range::RangeDecoder; - - /// The forward MDCT against the transform's definition, at the 2/l scale - /// CELT puts on the analysis side. - #[test] - fn forward_mdct_matches_the_definition() { - for &l in &[120usize, 240, 480, 960] { - let w = celt::overlap_window(); - let flat = (l - OVERLAP) / 2; - // The full 2l low-overlap window. - let mut win = vec![0.0f32; 2 * l]; - for i in 0..l { - win[i] = if i < flat { - 0.0 - } else if i < flat + OVERLAP { - w[i - flat] - } else { - 1.0 - }; - win[2 * l - 1 - i] = win[i]; - } - // A signal over the window's support, zero-padded to 2l. - let support = l + OVERLAP; - let sig: Vec = (0..support) - .map(|i| ((i * 2654435761usize) % 2000) as f32 / 1000.0 - 1.0) - .collect(); - let mut x2l = vec![0.0f32; 2 * l]; - for j in 0..support { - x2l[flat + j] = win[flat + j] * sig[j]; - } - // Direct MDCT by definition. - let direct: Vec = (0..l) - .map(|k| { - let mut sum = 0.0f64; - for (nn, &v) in x2l.iter().enumerate() { - let a = core::f64::consts::PI / l as f64 - * (nn as f64 + 0.5 + l as f64 / 2.0) - * (k as f64 + 0.5); - sum += v as f64 * a.cos(); - } - sum * 2.0 / l as f64 - }) - .collect(); - let mut plan = MdctPlan::new(l); - let mut out = vec![0.0f32; l]; - plan.forward(&sig, 0, &w, &mut out, 0, 1); - let mut worst = 0.0f64; - for k in 0..l { - worst = worst.max((direct[k] - out[k] as f64).abs()); - } - assert!(worst < 1e-4, "l={l}: worst coefficient error {worst}"); - } - } - - /// encode_pulses must invert decode_pulses for every (n, k) shape the - /// allocation can produce. - #[test] - fn pulse_enumeration_round_trips() { - let mut state = 0x2545F491u32; - let mut rand = move || { - state ^= state << 13; - state ^= state >> 17; - state ^= state << 5; - state - }; - for &(n, k) in &[ - (2usize, 1usize), - (2, 8), - (3, 4), - (4, 6), - (5, 3), - (8, 10), - (16, 7), - (24, 4), - (48, 2), - (96, 1), - (176, 2), - (22, 8), - (32, 6), - (11, 12), - (64, 4), - ] { - for _ in 0..20 { - // A random pulse vector with |y| summing to k. - let mut iy = vec![0i32; n]; - for _ in 0..k { - let j = (rand() as usize) % n; - iy[j] += 1; - } - for v in iy.iter_mut() { - if *v != 0 && rand() & 1 == 1 { - *v = -*v; - } - } - let mut enc = RangeEncoder::new(); - enc.reset(600); - encode_pulses(&mut enc, &iy, n, k); - enc.done(); - assert!(!enc.error()); - let data = enc.data().to_vec(); - let mut dec = RangeDecoder::new(&data); - let mut got = vec![0i32; n]; - crate::celt::decode_pulses(&mut dec, n, k, &mut got); - assert_eq!(got, iy, "n={n} k={k}"); - } - } - } - - /// The Laplace encoder against the decoder, over the whole coarse-energy - /// model space. - #[test] - fn laplace_round_trips() { - #[allow(clippy::needless_range_loop)] - for lm in 0..4 { - for intra in 0..2 { - for band in 0..21usize { - let model = &E_PROB_MODEL[lm][intra]; - let pi = 2 * band.min(20); - let fs = (model[pi] as u32) << 7; - let decay = (model[pi + 1] as i32) << 6; - for val in -12i32..=12 { - let mut enc = RangeEncoder::new(); - enc.reset(64); - let mut v = val; - laplace_encode(&mut enc, &mut v, fs, decay); - enc.done(); - let data = enc.data().to_vec(); - let mut dec = RangeDecoder::new(&data); - let got = crate::celt::laplace_decode(&mut dec, fs, decay); - assert_eq!(got, v, "lm={lm} intra={intra} band={band} val={val}"); - } - } - } - } - } - - fn allocation_caps(lm: usize, c: usize) -> [i32; NB_BANDS] { - let mut caps = [0i32; NB_BANDS]; - for i in 0..NB_BANDS { - let bw = (E_BANDS[i + 1] - E_BANDS[i]) << lm; - caps[i] = - ((CACHE_CAPS[NB_BANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * bw as i32) - >> 2; - } - caps - } - - #[test] - fn allocation_encoder_and_decoder_match_on_grid() { - let frame_grid = [(0usize, 120usize), (1, 240), (2, 480), (3, 960)]; - let bitrate_grid = [16_000i32, 24_000, 48_000, 96_000, 192_000]; - let stereo_grid = [ - (0usize, false), - (8, false), - (12, true), - (18, false), - (NB_BANDS, true), - ]; - - for &(lm, frame_size) in &frame_grid { - assert_eq!(SHORT_MDCT << lm, frame_size); - for &bitrate in &bitrate_grid { - for &c in &[1usize, 2] { - let start = 0usize; - let end = NB_BANDS; - let caps = allocation_caps(lm, c); - let mut offsets = [0i32; NB_BANDS]; - for i in start..end { - if (i + lm + bitrate as usize / 8_000 + c).is_multiple_of(7) { - let width = ((c * (E_BANDS[i + 1] - E_BANDS[i])) << lm) as i32; - offsets[i] = (width << BITRES).min(caps[i] / 2).max(0); - } - } - let total = ((bitrate * frame_size as i32 / 48_000) << BITRES).max(2 << BITRES); - let trim = ((bitrate / 24_000) + lm as i32 + c as i32).rem_euclid(11); - let prev = end.saturating_sub((bitrate as usize / 24_000 + lm + c) % 6); - let stereo_cases: &[(usize, bool)] = - if c == 2 { &stereo_grid } else { &[(0, false)] }; - - for &(requested_intensity, requested_dual) in stereo_cases { - let mut ep = [0i32; NB_BANDS]; - let mut ef = [0i32; NB_BANDS]; - let mut eprio = [0i32; NB_BANDS]; - let mut enc = RangeEncoder::new(); - enc.reset(64); - let er = compute_allocation_encode( - &mut enc, - start, - end, - trim, - total, - c, - lm, - &offsets, - &caps, - &mut ep, - &mut ef, - &mut eprio, - requested_intensity, - requested_dual, - prev, - ); - let enc_tell = enc.tell_frac(); - enc.done(); - assert!(!enc.error()); - - let data = enc.data().to_vec(); - let mut dp = [0i32; NB_BANDS]; - let mut df = [0i32; NB_BANDS]; - let mut dprio = [0i32; NB_BANDS]; - let mut dec = RangeDecoder::new(&data); - let dr = celt::compute_allocation_decode( - &mut dec, start, end, trim, total, c, lm, &offsets, &caps, &mut dp, - &mut df, &mut dprio, - ); - - assert_eq!(dr, er, "lm={lm} bitrate={bitrate} c={c}"); - assert_eq!( - dec.tell_frac(), - enc_tell, - "tell lm={lm} bitrate={bitrate} c={c}" - ); - assert_eq!( - &dp[start..end], - &ep[start..end], - "pulses lm={lm} bitrate={bitrate} c={c}" - ); - assert_eq!( - &df[start..end], - &ef[start..end], - "fine lm={lm} bitrate={bitrate} c={c}" - ); - assert_eq!( - &dprio[start..end], - &eprio[start..end], - "priority lm={lm} bitrate={bitrate} c={c}" - ); - } - } - } - } - } -} diff --git a/crates/ec-opus/src/celt_flp/bands.rs b/crates/ec-opus/src/celt_flp/bands.rs new file mode 100644 index 00000000..a1b8ce2f --- /dev/null +++ b/crates/ec-opus/src/celt_flp/bands.rs @@ -0,0 +1,1234 @@ +use super::vq::{alg_quant, renormalise_vector, stereo_itheta}; +use super::{EPSILON, LOG_N, SHORT_MDCT, celt_rsqrt, celt_sqrt}; +use crate::celt::{ + BITRES, CACHE_BITS, E_BANDS, NB_BANDS, QTHETA_OFFSET, QTHETA_OFFSET_TWOPHASE, + SPREAD_AGGRESSIVE, SPREAD_NONE, bitexact_cos, bitexact_log2tan, bits2pulses, cache_index, + compute_qn, frac_mul16, get_pulses, pulses2bits, +}; +use crate::range::RangeEncoder; + +const BR: i32 = BITRES as i32; +const MAX_BAND: usize = 176; +const MAX_NORM: usize = 2 * 960; +const MAX_BYTES: usize = 1275; +const C70: f32 = 0.70710678; +const ORDERY: [usize; 30] = [ + 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, +]; +const BIT_INTERLEAVE: [u8; 16] = [0, 1, 1, 1, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3]; +const BIT_DEINTERLEAVE: [u8; 16] = [ + 0x00, 0x03, 0x0C, 0x0F, 0x30, 0x33, 0x3C, 0x3F, 0xC0, 0xC3, 0xCC, 0xCF, 0xF0, 0xF3, 0xFC, 0xFF, +]; + +#[derive(Clone, Copy)] +struct BandCtx<'a> { + resynth: bool, + i: usize, + intensity: usize, + spread: i32, + tf_change: i32, + remaining_bits: i32, + band_e: &'a [f32], + seed: u32, + theta_round: i32, + disable_inv: bool, + avoid_split_noise: bool, +} + +struct SplitCtx { + inv: bool, + imid: i32, + iside: i32, + delta: i32, + itheta: i32, + qalloc: i32, +} + +fn lcg_rand(seed: u32) -> u32 { + seed.wrapping_mul(1664525).wrapping_add(1013904223) +} + +fn inner(a: &[f32], b: &[f32]) -> f32 { + let mut s = 0.0f32; + for (p, q) in a.iter().zip(b) { + s += p * q; + } + s +} + +/// `hysteresis_decision`; the count `N` is `thresholds.len()`. +pub(crate) fn hysteresis_decision( + val: f32, + thresholds: &[f32], + hysteresis: &[f32], + prev: i32, +) -> i32 { + let mut i = thresholds + .iter() + .position(|&t| val < t) + .unwrap_or(thresholds.len()) as i32; + if i > prev && val < thresholds[prev as usize] + hysteresis[prev as usize] { + i = prev; + } + if i < prev && val > thresholds[(prev - 1) as usize] - hysteresis[(prev - 1) as usize] { + i = prev; + } + i +} + +/// `compute_band_energies`; `x` is C `X` (`c * (N << lm)` frequency bins as C lays them out), `band_e` is `c * 21`. +pub(crate) fn compute_band_energies( + x: &[f32], + band_e: &mut [f32], + end: usize, + c: usize, + lm: usize, +) { + let n = SHORT_MDCT << lm; + for ch in 0..c { + for i in 0..end { + let lo = ch * n + (E_BANDS[i] << lm); + let len = (E_BANDS[i + 1] - E_BANDS[i]) << lm; + let s = &x[lo..lo + len]; + let sum = 1e-27f32 + inner(s, s); + band_e[i + ch * NB_BANDS] = celt_sqrt(sum); + } + } +} + +/// `normalise_bands`; `m` is C `M` (`1 << lm`). +pub(crate) fn normalise_bands( + freq: &[f32], + x: &mut [f32], + band_e: &[f32], + end: usize, + c: usize, + m: usize, +) { + let n = m * SHORT_MDCT; + for ch in 0..c { + for i in 0..end { + let g = 1.0f32 / (1e-27f32 + band_e[i + ch * NB_BANDS]); + for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { + x[j + ch * n] = freq[j + ch * n] * g; + } + } + } +} + +/// `spreading_decision`; returns the decision. +pub(crate) fn spreading_decision( + x: &[f32], + average: &mut i32, + last_decision: i32, + hf_average: &mut i32, + tapset_decision: &mut i32, + update_hf: bool, + end: usize, + c: usize, + m: usize, + spread_weight: &[i32], +) -> i32 { + let n0 = m * SHORT_MDCT; + let mut sum: i32 = 0; + let mut nb_bands: i32 = 0; + let mut hf_sum: i32 = 0; + if m * (E_BANDS[end] - E_BANDS[end - 1]) <= 8 { + return SPREAD_NONE as i32; + } + for ch in 0..c { + for i in 0..end { + let mut tcount = [0i32; 3]; + let base = m * E_BANDS[i] + ch * n0; + let n = (m * (E_BANDS[i + 1] - E_BANDS[i])) as i32; + if n <= 8 { + continue; + } + for j in 0..n as usize { + let v = x[base + j]; + let x2n = (v * v) * n as f32; + if x2n < 0.25 { + tcount[0] += 1; + } + if x2n < 0.0625 { + tcount[1] += 1; + } + if x2n < 0.015625 { + tcount[2] += 1; + } + } + if i + 4 > NB_BANDS { + hf_sum += 32 * (tcount[1] + tcount[0]) / n; + } + let tmp = (2 * tcount[2] >= n) as i32 + + (2 * tcount[1] >= n) as i32 + + (2 * tcount[0] >= n) as i32; + sum += tmp * spread_weight[i]; + nb_bands += spread_weight[i]; + } + } + if update_hf { + if hf_sum != 0 { + hf_sum /= c as i32 * (4 - NB_BANDS as i32 + end as i32); + } + *hf_average = (*hf_average + hf_sum) >> 1; + hf_sum = *hf_average; + if *tapset_decision == 2 { + hf_sum += 4; + } else if *tapset_decision == 0 { + hf_sum -= 4; + } + *tapset_decision = if hf_sum > 22 { + 2 + } else if hf_sum > 18 { + 1 + } else { + 0 + }; + } + sum = (sum << 8) / nb_bands; + sum = (sum + *average) >> 1; + *average = sum; + sum = (3 * sum + (((3 - last_decision) << 7) + 64) + 2) >> 2; + if sum < 80 { + SPREAD_AGGRESSIVE as i32 + } else if sum < 256 { + 2 + } else if sum < 384 { + 1 + } else { + SPREAD_NONE as i32 + } +} + +fn deinterleave_hadamard(x: &mut [f32], n0: usize, stride: usize, hadamard: bool) { + let n = n0 * stride; + let mut tmp_buf = [0f32; MAX_BAND]; + let tmp = &mut tmp_buf[..n]; + if hadamard { + let ordery = &ORDERY[stride - 2..]; + for i in 0..stride { + for j in 0..n0 { + tmp[ordery[i] * n0 + j] = x[j * stride + i]; + } + } + } else { + for i in 0..stride { + for j in 0..n0 { + tmp[i * n0 + j] = x[j * stride + i]; + } + } + } + x[..n].copy_from_slice(tmp); +} + +fn interleave_hadamard(x: &mut [f32], n0: usize, stride: usize, hadamard: bool) { + let n = n0 * stride; + let mut tmp_buf = [0f32; MAX_BAND]; + let tmp = &mut tmp_buf[..n]; + if hadamard { + let ordery = &ORDERY[stride - 2..]; + for i in 0..stride { + for j in 0..n0 { + tmp[j * stride + i] = x[ordery[i] * n0 + j]; + } + } + } else { + for i in 0..stride { + for j in 0..n0 { + tmp[j * stride + i] = x[i * n0 + j]; + } + } + } + x[..n].copy_from_slice(tmp); +} + +fn haar1(x: &mut [f32], n0: usize, stride: usize) { + let n0 = n0 >> 1; + for i in 0..stride { + for j in 0..n0 { + let tmp1 = C70 * x[stride * 2 * j + i]; + let tmp2 = C70 * x[stride * (2 * j + 1) + i]; + x[stride * 2 * j + i] = tmp1 + tmp2; + x[stride * (2 * j + 1) + i] = tmp1 - tmp2; + } + } +} + +fn compute_channel_weights(ex: f32, ey: f32) -> [f32; 2] { + let min_e = if ex < ey { ex } else { ey }; + [ex + min_e / 3.0, ey + min_e / 3.0] +} + +fn intensity_stereo(x: &mut [f32], y: &[f32], band_e: &[f32], i: usize, n: usize) { + let left = band_e[i]; + let right = band_e[i + NB_BANDS]; + let norm = EPSILON + celt_sqrt(EPSILON + left * left + right * right); + let a1 = left / norm; + let a2 = right / norm; + for j in 0..n { + x[j] = a1 * x[j] + a2 * y[j]; + } +} + +fn stereo_split(x: &mut [f32], y: &mut [f32], n: usize) { + for j in 0..n { + let l = C70 * x[j]; + let r = C70 * y[j]; + x[j] = l + r; + y[j] = r - l; + } +} + +fn stereo_merge(x: &mut [f32], y: &mut [f32], mid: f32, n: usize) { + let mut xp = inner(&y[..n], &x[..n]); + let side = inner(&y[..n], &y[..n]); + xp *= mid; + let el = mid * mid + side - 2.0 * xp; + let er = mid * mid + side + 2.0 * xp; + if er < 6e-4f32 || el < 6e-4f32 { + y[..n].copy_from_slice(&x[..n]); + return; + } + let lgain = celt_rsqrt(el); + let rgain = celt_rsqrt(er); + for j in 0..n { + let l = mid * x[j]; + let r = y[j]; + x[j] = lgain * (l - r); + y[j] = rgain * (l + r); + } +} + +fn special_hybrid_folding( + norm: &mut [f32], + norm2: &mut [f32], + start: usize, + m: usize, + dual_stereo: bool, +) { + let n1 = m * (E_BANDS[start + 1] - E_BANDS[start]); + let n2 = m * (E_BANDS[start + 2] - E_BANDS[start + 1]); + norm.copy_within(2 * n1 - n2..n1, n1); + if dual_stereo { + norm2.copy_within(2 * n1 - n2..n1, n1); + } +} + +fn cache_top(band: usize, lm: i32) -> i32 { + let base = cache_index(band, lm); + CACHE_BITS[base + CACHE_BITS[base] as usize] as i32 +} + +fn theta_delta(n: i32, imid: i32, iside: i32) -> i32 { + frac_mul16(((n - 1) << 7) as i16, bitexact_log2tan(iside, imid) as i16) +} + +fn compute_theta( + ctx: &mut BandCtx, + enc: &mut RangeEncoder, + x: &mut [f32], + y: &mut [f32], + n: usize, + b: &mut i32, + bb: i32, + b0: i32, + lm: i32, + stereo: bool, + fill: &mut i32, +) -> SplitCtx { + let i = ctx.i; + let ni = n as i32; + let pulse_cap = LOG_N[i] + lm * (1 << BR); + let offset = (pulse_cap >> 1) + - if stereo && n == 2 { + QTHETA_OFFSET_TWOPHASE + } else { + QTHETA_OFFSET + }; + let mut qn = compute_qn(ni, *b, offset, pulse_cap, stereo); + if stereo && i >= ctx.intensity { + qn = 1; + } + let mut itheta = stereo_itheta(x, y, stereo, n) >> 16; + let tell = enc.tell_frac() as i32; + let mut inv = false; + if qn != 1 { + if !stereo || ctx.theta_round == 0 { + itheta = (itheta * qn + 8192) >> 14; + if !stereo && ctx.avoid_split_noise && itheta > 0 && itheta < qn { + let unquantized = itheta * 16384 / qn; + let imid = bitexact_cos(unquantized as i16) as i32; + let iside = bitexact_cos((16384 - unquantized) as i16) as i32; + let delta = theta_delta(ni, imid, iside); + if delta > *b { + itheta = qn; + } else if delta < -*b { + itheta = 0; + } + } + } else { + let bias = if itheta > 8192 { + 32767 / qn + } else { + -32767 / qn + }; + let down = (qn - 1).min(((itheta * qn + bias) >> 14).max(0)); + itheta = if ctx.theta_round < 0 { down } else { down + 1 }; + } + if stereo && n > 2 { + let p0 = 3; + let x0 = qn / 2; + let ft = p0 * (x0 + 1) + x0; + let (fl, fh) = if itheta <= x0 { + (p0 * itheta, p0 * (itheta + 1)) + } else { + ( + (itheta - 1 - x0) + (x0 + 1) * p0, + (itheta - x0) + (x0 + 1) * p0, + ) + }; + enc.encode(fl as u32, fh as u32, ft as u32); + } else if b0 > 1 || stereo { + enc.enc_uint(itheta as u32, (qn + 1) as u32); + } else { + let ft = ((qn >> 1) + 1) * ((qn >> 1) + 1); + let fs = if itheta <= (qn >> 1) { + itheta + 1 + } else { + qn + 1 - itheta + }; + let fl = if itheta <= (qn >> 1) { + (itheta * (itheta + 1)) >> 1 + } else { + ft - (((qn + 1 - itheta) * (qn + 2 - itheta)) >> 1) + }; + enc.encode(fl as u32, (fl + fs) as u32, ft as u32); + } + itheta = itheta * 16384 / qn; + if stereo { + if itheta == 0 { + intensity_stereo(x, y, ctx.band_e, i, n); + } else { + stereo_split(x, y, n); + } + } + } else if stereo { + inv = itheta > 8192 && !ctx.disable_inv; + if inv { + for v in y[..n].iter_mut() { + *v = -*v; + } + } + intensity_stereo(x, y, ctx.band_e, i, n); + if *b > 2 << BR && ctx.remaining_bits > 2 << BR { + enc.enc_bit_logp(inv, 2); + } else { + inv = false; + } + if ctx.disable_inv { + inv = false; + } + itheta = 0; + } + let qalloc = enc.tell_frac() as i32 - tell; + *b -= qalloc; + + let (imid, iside, delta) = if itheta == 0 { + *fill &= (1 << bb) - 1; + (32767, 0, -16384) + } else if itheta == 16384 { + *fill &= ((1 << bb) - 1) << bb; + (0, 32767, 16384) + } else { + let imid = bitexact_cos(itheta as i16) as i32; + let iside = bitexact_cos((16384 - itheta) as i16) as i32; + (imid, iside, theta_delta(ni, imid, iside)) + }; + SplitCtx { + inv, + imid, + iside, + delta, + itheta, + qalloc, + } +} + +fn n1_channel(ctx: &mut BandCtx, enc: &mut RangeEncoder, v: &mut f32) { + let mut sign = false; + if ctx.remaining_bits >= 1 << BR { + sign = *v < 0.0; + enc.enc_bits(sign as u32, 1); + ctx.remaining_bits -= 1 << BR; + } + if ctx.resynth { + *v = if sign { -1.0 } else { 1.0 }; + } +} + +fn quant_band_n1( + ctx: &mut BandCtx, + enc: &mut RangeEncoder, + x: &mut [f32], + y: Option<&mut [f32]>, + lowband_out: Option<&mut [f32]>, +) -> u32 { + n1_channel(ctx, enc, &mut x[0]); + if let Some(y) = y { + n1_channel(ctx, enc, &mut y[0]); + } + if let Some(out) = lowband_out { + out[0] = x[0]; + } + 1 +} + +fn quant_partition( + ctx: &mut BandCtx, + enc: &mut RangeEncoder, + x: &mut [f32], + n: usize, + b: i32, + bb: i32, + lowband: Option<&mut [f32]>, + lm: i32, + gain: f32, + fill: i32, +) -> u32 { + let i = ctx.i; + let b0 = bb; + let mut n = n; + let mut b = b; + let mut bb = bb; + let mut lm = lm; + let mut fill = fill; + if lm != -1 && b > cache_top(i, lm) + 12 && n > 2 { + n >>= 1; + lm -= 1; + if bb == 1 { + fill = (fill & 1) | (fill << 1); + } + bb = (bb + 1) >> 1; + let (xa, ya) = x[..2 * n].split_at_mut(n); + let sc = compute_theta(ctx, enc, xa, ya, n, &mut b, bb, b0, lm, false, &mut fill); + let mid = (1.0f32 / 32768.0) * sc.imid as f32; + let side = (1.0f32 / 32768.0) * sc.iside as f32; + let itheta = sc.itheta; + let mut delta = sc.delta; + if b0 > 1 && (itheta & 0x3fff) != 0 { + if itheta > 8192 { + delta -= delta >> (4 - lm); + } else { + delta = (delta + (((n as i32) << BR) >> (5 - lm))).min(0); + } + } + let mut mbits = 0.max(b.min((b - delta) / 2)); + let mut sbits = b - mbits; + ctx.remaining_bits -= sc.qalloc; + let rem_before = ctx.remaining_bits; + let (lb1, lb2) = match lowband { + Some(lb) => { + let (p, q) = lb.split_at_mut(n); + (Some(p), Some(q)) + } + None => (None, None), + }; + if mbits >= sbits { + let c1 = quant_partition(ctx, enc, xa, n, mbits, bb, lb1, lm, gain * mid, fill); + let rb = mbits - (rem_before - ctx.remaining_bits); + if rb > 3 << BR && itheta != 0 { + sbits += rb - (3 << BR); + } + c1 | (quant_partition(ctx, enc, ya, n, sbits, bb, lb2, lm, gain * side, fill >> bb) + << (b0 >> 1)) + } else { + let c1 = quant_partition(ctx, enc, ya, n, sbits, bb, lb2, lm, gain * side, fill >> bb) + << (b0 >> 1); + let rb = sbits - (rem_before - ctx.remaining_bits); + if rb > 3 << BR && itheta != 16384 { + mbits += rb - (3 << BR); + } + c1 | quant_partition(ctx, enc, xa, n, mbits, bb, lb1, lm, gain * mid, fill) + } + } else { + let mut q = bits2pulses(i, lm, b); + let mut curr_bits = pulses2bits(i, lm, q); + ctx.remaining_bits -= curr_bits; + while ctx.remaining_bits < 0 && q > 0 { + ctx.remaining_bits += curr_bits; + q -= 1; + curr_bits = pulses2bits(i, lm, q); + ctx.remaining_bits -= curr_bits; + } + if q != 0 { + let k = get_pulses(q); + alg_quant(x, n, k, ctx.spread, bb, enc, gain, ctx.resynth) + } else if ctx.resynth { + let cm_mask: u32 = (1u32 << bb) - 1; + fill &= cm_mask as i32; + if fill == 0 { + x[..n].fill(0.0); + 0 + } else { + let cm = match lowband { + None => { + for v in x[..n].iter_mut() { + ctx.seed = lcg_rand(ctx.seed); + *v = ((ctx.seed as i32) >> 20) as f32; + } + cm_mask + } + Some(lb) => { + for j in 0..n { + ctx.seed = lcg_rand(ctx.seed); + let tmp = 1.0f32 / 256.0; + let tmp = if ctx.seed & 0x8000 != 0 { tmp } else { -tmp }; + x[j] = lb[j] + tmp; + } + fill as u32 + } + }; + renormalise_vector(x, n, gain); + cm + } + } else { + 0 + } + } +} + +fn opt_scratch(on: bool, buf: &mut [f32]) -> Option<&mut [f32]> { + if on { Some(buf) } else { None } +} + +fn quant_band( + ctx: &mut BandCtx, + enc: &mut RangeEncoder, + x: &mut [f32], + n: usize, + b: i32, + bb: i32, + lowband: Option<&mut [f32]>, + lm: i32, + lowband_out: Option<&mut [f32]>, + gain: f32, + lowband_scratch: Option<&mut [f32]>, + fill: i32, +) -> u32 { + if n == 1 { + return quant_band_n1(ctx, enc, x, None, lowband_out); + } + let n0 = n; + let b0_long = bb; + let long_blocks = b0_long == 1; + let mut bb = bb; + let mut fill = fill; + let mut n_b = (n as i32) / bb; + let mut tf_change = ctx.tf_change; + let recombine = if tf_change > 0 { tf_change } else { 0 }; + let copy = recombine != 0 || ((n_b & 1) == 0 && tf_change < 0) || b0_long > 1; + let mut lowband = match (lowband, lowband_scratch) { + (Some(lb), Some(sc)) if copy => { + sc[..n].copy_from_slice(&lb[..n]); + Some(sc) + } + (lb, _) => lb, + }; + for k in 0..recombine as usize { + haar1(x, n0 >> k, 1 << k); + if let Some(lb) = lowband.as_deref_mut() { + haar1(lb, n0 >> k, 1 << k); + } + fill = BIT_INTERLEAVE[(fill & 0xF) as usize] as i32 + | ((BIT_INTERLEAVE[(fill >> 4) as usize] as i32) << 2); + } + bb >>= recombine; + n_b <<= recombine; + let mut time_divide = 0; + while (n_b & 1) == 0 && tf_change < 0 { + haar1(x, n_b as usize, bb as usize); + if let Some(lb) = lowband.as_deref_mut() { + haar1(lb, n_b as usize, bb as usize); + } + fill |= fill << bb; + bb <<= 1; + n_b >>= 1; + time_divide += 1; + tf_change += 1; + } + let b0 = bb; + let n_b0 = n_b; + if b0 > 1 { + deinterleave_hadamard( + x, + (n_b >> recombine) as usize, + (b0 << recombine) as usize, + long_blocks, + ); + if let Some(lb) = lowband.as_deref_mut() { + deinterleave_hadamard( + lb, + (n_b >> recombine) as usize, + (b0 << recombine) as usize, + long_blocks, + ); + } + } + let mut cm = quant_partition(ctx, enc, x, n, b, bb, lowband, lm, gain, fill); + if ctx.resynth { + if b0 > 1 { + interleave_hadamard( + x, + (n_b >> recombine) as usize, + (b0 << recombine) as usize, + long_blocks, + ); + } + n_b = n_b0; + bb = b0; + for _ in 0..time_divide { + bb >>= 1; + n_b <<= 1; + cm |= cm >> bb; + haar1(x, n_b as usize, bb as usize); + } + for k in 0..recombine as usize { + cm = BIT_DEINTERLEAVE[cm as usize] as u32; + haar1(x, n0 >> k, 1 << k); + } + bb <<= recombine; + if let Some(out) = lowband_out { + let nn = celt_sqrt(n0 as f32); + for j in 0..n0 { + out[j] = nn * x[j]; + } + } + cm &= (1u32 << bb) - 1; + } + cm +} + +fn quant_band_stereo( + ctx: &mut BandCtx, + enc: &mut RangeEncoder, + x: &mut [f32], + y: &mut [f32], + n: usize, + b: i32, + bb: i32, + lowband: Option<&mut [f32]>, + lm: i32, + lowband_out: Option<&mut [f32]>, + lowband_scratch: Option<&mut [f32]>, + fill: i32, +) -> u32 { + if n == 1 { + return quant_band_n1(ctx, enc, x, Some(y), lowband_out); + } + let i = ctx.i; + let nb = NB_BANDS; + let orig_fill = fill; + if ctx.band_e[i] < 1e-10 || ctx.band_e[nb + i] < 1e-10 { + if ctx.band_e[i] > ctx.band_e[nb + i] { + y[..n].copy_from_slice(&x[..n]); + } else { + x[..n].copy_from_slice(&y[..n]); + } + } + let mut fill = fill; + let mut bm = b; + let sc = compute_theta(ctx, enc, x, y, n, &mut bm, bb, bb, lm, true, &mut fill); + let mid = (1.0f32 / 32768.0) * sc.imid as f32; + let side = (1.0f32 / 32768.0) * sc.iside as f32; + let cm = if n == 2 { + let mut mbits = bm; + let mut sbits = 0; + if sc.itheta != 0 && sc.itheta != 16384 { + sbits = 1 << BR; + } + mbits -= sbits; + let c = sc.itheta > 8192; + ctx.remaining_bits -= sc.qalloc + sbits; + let (x2, y2): (&mut [f32], &mut [f32]) = if c { + (&mut *y, &mut *x) + } else { + (&mut *x, &mut *y) + }; + let mut sign = 0i32; + if sbits != 0 { + sign = (x2[0] * y2[1] - x2[1] * y2[0] < 0.0) as i32; + enc.enc_bits(sign as u32, 1); + } + let sign = 1 - 2 * sign; + let cm = quant_band( + ctx, + enc, + x2, + 2, + mbits, + bb, + lowband, + lm, + lowband_out, + 1.0, + lowband_scratch, + orig_fill, + ); + y2[0] = (-sign) as f32 * x2[1]; + y2[1] = sign as f32 * x2[0]; + cm + } else { + let mut mbits = 0.max(bm.min((bm - sc.delta) / 2)); + let mut sbits = bm - mbits; + ctx.remaining_bits -= sc.qalloc; + let rem_before = ctx.remaining_bits; + if mbits >= sbits { + let c1 = quant_band( + ctx, + enc, + x, + n, + mbits, + bb, + lowband, + lm, + lowband_out, + 1.0, + lowband_scratch, + fill, + ); + let rb = mbits - (rem_before - ctx.remaining_bits); + if rb > 3 << BR && sc.itheta != 0 { + sbits += rb - (3 << BR); + } + c1 | quant_band( + ctx, + enc, + y, + n, + sbits, + bb, + None, + lm, + None, + side, + None, + fill >> bb, + ) + } else { + let c1 = quant_band( + ctx, + enc, + y, + n, + sbits, + bb, + None, + lm, + None, + side, + None, + fill >> bb, + ); + let rb = sbits - (rem_before - ctx.remaining_bits); + if rb > 3 << BR && sc.itheta != 16384 { + mbits += rb - (3 << BR); + } + c1 | quant_band( + ctx, + enc, + x, + n, + mbits, + bb, + lowband, + lm, + lowband_out, + 1.0, + lowband_scratch, + fill, + ) + } + }; + if ctx.resynth { + if n == 2 { + x[0] *= mid; + x[1] *= mid; + y[0] *= side; + y[1] *= side; + let tmp = x[0]; + x[0] = tmp - y[0]; + y[0] += tmp; + let tmp = x[1]; + x[1] = tmp - y[1]; + y[1] += tmp; + } else { + stereo_merge(x, y, mid, n); + } + if sc.inv { + for v in y[..n].iter_mut() { + *v = -*v; + } + } + } + cm +} + +fn store(buf: &mut [f32], off: usize, v: Option<&[f32]>) { + if let Some(v) = v { + buf[off..off + v.len()].copy_from_slice(v); + } +} + +fn lowband_copy<'a>( + buf: &'a mut [f32; MAX_BAND], + norm: &[f32], + e: Option, + nu: usize, +) -> Option<&'a mut [f32]> { + let e = e?; + buf[..nu].copy_from_slice(&norm[e..e + nu]); + Some(&mut buf[..nu]) +} + +/// `quant_all_bands` with `encode = 1` (no QEXT); `y` is C `Y` (None for mono). +pub(crate) fn quant_all_bands( + start: usize, + end: usize, + x: &mut [f32], + y: Option<&mut [f32]>, + collapse_masks: &mut [u8], + band_e: &[f32], + pulses: &[i32], + short_blocks: bool, + spread: i32, + dual_stereo: bool, + intensity: usize, + tf_res: &[i32], + total_bits: i32, + balance: i32, + enc: &mut RangeEncoder, + lm: usize, + coded_bands: usize, + seed: &mut u32, + complexity: i32, + disable_inv: bool, +) { + let mut y = y; + let mut dual_stereo = dual_stereo; + let mut balance = balance; + let c = if y.is_some() { 2 } else { 1 }; + let theta_rdo = y.is_some() && !dual_stereo && complexity >= 8; + let resynth = theta_rdo; + let m = 1usize << lm; + let lm = lm as i32; + let b_full = if short_blocks { m as i32 } else { 1 }; + let eb = |k: usize| (m * E_BANDS[k]) as i32; + let norm_offset = eb(start); + let norm_len = (eb(NB_BANDS - 1) - norm_offset) as usize; + let mut norm_buf = [0f32; MAX_NORM]; + let mut norm2_buf = [0f32; MAX_NORM]; + let norm = &mut norm_buf[..norm_len]; + let norm2 = &mut norm2_buf[..norm_len]; + let scratch_len = if resynth { + m * (E_BANDS[NB_BANDS] - E_BANDS[NB_BANDS - 1]) + } else { + 0 + }; + let mut scratch_buf = [0f32; MAX_BAND]; + let scratch = &mut scratch_buf[..scratch_len]; + let mut lowband_offset = 0usize; + let mut update_lowband = true; + let mut ctx = BandCtx { + resynth, + i: start, + intensity, + spread, + tf_change: 0, + remaining_bits: 0, + band_e, + seed: *seed, + theta_round: 0, + disable_inv, + avoid_split_noise: b_full > 1, + }; + + for i in start..end { + ctx.i = i; + let last = i + 1 == end; + let lo = eb(i); + let n = eb(i + 1) - lo; + let nu = n as usize; + let lo_u = lo as usize; + let out_off = (lo - norm_offset) as usize; + let tell = enc.tell_frac() as i32; + if i != start { + balance -= tell; + } + let remaining_bits = total_bits - tell - 1; + ctx.remaining_bits = remaining_bits; + let b = if i < coded_bands { + let curr_balance = balance / ((coded_bands - i) as i32).min(3); + (remaining_bits + 1) + .min(pulses[i] + curr_balance) + .clamp(0, 16383) + } else { + 0 + }; + if resynth + && (lo - n >= norm_offset || i == start + 1) + && (update_lowband || lowband_offset == 0) + { + lowband_offset = i; + } + if i == start + 1 { + special_hybrid_folding(norm, norm2, start, m, dual_stereo); + } + let tf_change = tf_res[i]; + ctx.tf_change = tf_change; + + let mut effective_lowband: Option = None; + let (mut x_cm, mut y_cm): (u32, u32) = if lowband_offset != 0 + && (spread != SPREAD_AGGRESSIVE as i32 || b_full > 1 || tf_change < 0) + { + let eff = (eb(lowband_offset) - norm_offset - n).max(0); + effective_lowband = Some(eff as usize); + let mut fold_start = lowband_offset; + loop { + fold_start -= 1; + if eb(fold_start) <= eff + norm_offset { + break; + } + } + let mut fold_end = lowband_offset - 1; + loop { + fold_end += 1; + if !(fold_end < i && eb(fold_end) < eff + norm_offset + n) { + break; + } + } + let mut xc = 0u32; + let mut yc = 0u32; + let mut fi = fold_start; + loop { + xc |= collapse_masks[fi * c] as u32; + yc |= collapse_masks[fi * c + c - 1] as u32; + fi += 1; + if fi >= fold_end { + break; + } + } + (xc, yc) + } else { + let all = (1u32 << b_full) - 1; + (all, all) + }; + + if dual_stereo && i == intensity { + dual_stereo = false; + if resynth { + for j in 0..(eb(i) - norm_offset) as usize { + norm[j] = 0.5f32 * (norm[j] + norm2[j]); + } + } + } + + let xb = &mut x[lo_u..lo_u + nu]; + let yb = y.as_deref_mut().map(|yy| &mut yy[lo_u..lo_u + nu]); + match yb { + None => { + let mut lb_buf = [0f32; MAX_BAND]; + let mut lbo_buf = [0f32; MAX_BAND]; + let lb = lowband_copy(&mut lb_buf, norm, effective_lowband, nu); + let mut lbo = if last { None } else { Some(&mut lbo_buf[..nu]) }; + x_cm = quant_band( + &mut ctx, + enc, + xb, + nu, + b, + b_full, + lb, + lm, + lbo.as_deref_mut(), + 1.0, + opt_scratch(resynth, scratch), + (x_cm | y_cm) as i32, + ); + store(norm, out_off, lbo.as_deref()); + y_cm = x_cm; + } + Some(yb) => { + if dual_stereo { + let mut lb_buf = [0f32; MAX_BAND]; + let mut lbo_buf = [0f32; MAX_BAND]; + let mut lb2_buf = [0f32; MAX_BAND]; + let mut lbo2_buf = [0f32; MAX_BAND]; + let lb = lowband_copy(&mut lb_buf, norm, effective_lowband, nu); + let mut lbo = if last { None } else { Some(&mut lbo_buf[..nu]) }; + x_cm = quant_band( + &mut ctx, + enc, + xb, + nu, + b / 2, + b_full, + lb, + lm, + lbo.as_deref_mut(), + 1.0, + None, + x_cm as i32, + ); + store(norm, out_off, lbo.as_deref()); + let lb2 = lowband_copy(&mut lb2_buf, norm2, effective_lowband, nu); + let mut lbo2 = if last { + None + } else { + Some(&mut lbo2_buf[..nu]) + }; + y_cm = quant_band( + &mut ctx, + enc, + yb, + nu, + b / 2, + b_full, + lb2, + lm, + lbo2.as_deref_mut(), + 1.0, + None, + y_cm as i32, + ); + store(norm2, out_off, lbo2.as_deref()); + } else if theta_rdo && i < intensity { + let w = compute_channel_weights(band_e[i], band_e[i + NB_BANDS]); + let cm_in = x_cm | y_cm; + let ec_save = enc.snapshot(); + let offs = enc.front_offs(); + let ctx_save = ctx; + let mut x_save_buf = [0f32; MAX_BAND]; + let mut y_save_buf = [0f32; MAX_BAND]; + x_save_buf[..nu].copy_from_slice(xb); + y_save_buf[..nu].copy_from_slice(yb); + let x_save = &x_save_buf[..nu]; + let y_save = &y_save_buf[..nu]; + + ctx.theta_round = -1; + let mut lb_buf = [0f32; MAX_BAND]; + let mut lbo_buf = [0f32; MAX_BAND]; + let lb = lowband_copy(&mut lb_buf, norm, effective_lowband, nu); + let mut lbo = if last { None } else { Some(&mut lbo_buf[..nu]) }; + x_cm = quant_band_stereo( + &mut ctx, + enc, + xb, + yb, + nu, + b, + b_full, + lb, + lm, + lbo.as_deref_mut(), + opt_scratch(resynth, scratch), + cm_in as i32, + ); + store(norm, out_off, lbo.as_deref()); + let dist0 = w[0] * inner(x_save, xb) + w[1] * inner(y_save, yb); + + let cm2 = x_cm; + let ec_save2 = enc.snapshot(); + let ctx_save2 = ctx; + let mut x_save2_buf = [0f32; MAX_BAND]; + let mut y_save2_buf = [0f32; MAX_BAND]; + x_save2_buf[..nu].copy_from_slice(xb); + y_save2_buf[..nu].copy_from_slice(yb); + let x_save2 = &x_save2_buf[..nu]; + let y_save2 = &y_save2_buf[..nu]; + let mut norm_save2_buf = [0f32; MAX_BAND]; + if !last { + norm_save2_buf[..nu].copy_from_slice(&norm[out_off..out_off + nu]); + } + let bytes_len = enc.data().len() - offs; + let mut bytes_save_buf = [0u8; MAX_BYTES]; + bytes_save_buf[..bytes_len].copy_from_slice(&enc.data()[offs..]); + let bytes_save = &bytes_save_buf[..bytes_len]; + + enc.restore(&ec_save); + ctx = ctx_save; + xb.copy_from_slice(x_save); + yb.copy_from_slice(y_save); + if i == start + 1 { + special_hybrid_folding(norm, norm2, start, m, dual_stereo); + } + + ctx.theta_round = 1; + let mut lb_buf = [0f32; MAX_BAND]; + let mut lbo_buf = [0f32; MAX_BAND]; + let lb = lowband_copy(&mut lb_buf, norm, effective_lowband, nu); + let mut lbo = if last { None } else { Some(&mut lbo_buf[..nu]) }; + x_cm = quant_band_stereo( + &mut ctx, + enc, + xb, + yb, + nu, + b, + b_full, + lb, + lm, + lbo.as_deref_mut(), + opt_scratch(resynth, scratch), + cm_in as i32, + ); + store(norm, out_off, lbo.as_deref()); + let dist1 = w[0] * inner(x_save, xb) + w[1] * inner(y_save, yb); + + if dist0 >= dist1 { + x_cm = cm2; + enc.restore(&ec_save2); + ctx = ctx_save2; + xb.copy_from_slice(x_save2); + yb.copy_from_slice(y_save2); + if !last { + norm[out_off..out_off + nu].copy_from_slice(&norm_save2_buf[..nu]); + } + enc.front_write(offs, bytes_save); + } + y_cm = x_cm; + } else { + ctx.theta_round = 0; + let mut lb_buf = [0f32; MAX_BAND]; + let mut lbo_buf = [0f32; MAX_BAND]; + let lb = lowband_copy(&mut lb_buf, norm, effective_lowband, nu); + let mut lbo = if last { None } else { Some(&mut lbo_buf[..nu]) }; + x_cm = quant_band_stereo( + &mut ctx, + enc, + xb, + yb, + nu, + b, + b_full, + lb, + lm, + lbo.as_deref_mut(), + opt_scratch(resynth, scratch), + (x_cm | y_cm) as i32, + ); + store(norm, out_off, lbo.as_deref()); + y_cm = x_cm; + } + } + } + + collapse_masks[i * c] = x_cm as u8; + collapse_masks[i * c + c - 1] = y_cm as u8; + balance += pulses[i] + tell; + update_lowband = b > (n << BR); + ctx.avoid_split_noise = false; + } + *seed = ctx.seed; +} diff --git a/crates/ec-opus/src/celt_flp/enc.rs b/crates/ec-opus/src/celt_flp/enc.rs new file mode 100644 index 00000000..905b38aa --- /dev/null +++ b/crates/ec-opus/src/celt_flp/enc.rs @@ -0,0 +1,1389 @@ +use crate::analysis::{AnalysisInfo, LEAK_BANDS}; +use crate::celt::{ + CACHE_CAPS, SPREAD_AGGRESSIVE, SPREAD_ICDF, SPREAD_NONE, SPREAD_NORMAL, TRIM_ICDF, + compute_allocation_encode, ilog, +}; +use crate::range::RangeEncoder; + +use super::bands::{ + compute_band_energies, hysteresis_decision, normalise_bands, quant_all_bands, + spreading_decision, +}; +use super::enc_an::{ + alloc_trim_analysis, compute_vbr, dynalloc_analysis, patch_transient_decision, stereo_analysis, + tf_analysis, tf_encode, tone_detect, transient_analysis, +}; +use super::fft::clt_mdct_forward; +use super::pitch::{comb_filter, pitch_downsample, pitch_search, remove_doubling}; +use super::quant_bands::{amp2log2, quant_coarse_energy, quant_energy_finalise, quant_fine_energy}; +use super::tables::WINDOW120; +use super::{BITRES, E_BANDS}; +use super::{ + COMBFILTER_MAXPERIOD, COMBFILTER_MINPERIOD, EPSILON, MAX_LM, NB_BANDS, OVERLAP, PI, SHORT_MDCT, + celt_rcp, +}; + +const BR: i32 = BITRES as i32; +const NB: usize = NB_BANDS; +const PACKET_SIZE_CAP: i32 = 1275; +const TAPSET_ICDF: [u8; 3] = [2, 1, 0]; +const INTENSITY_THRESHOLDS: [f32; NB_BANDS] = [ + 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 16.0, 24.0, 36.0, 44.0, 50.0, 56.0, 62.0, 67.0, 72.0, + 79.0, 88.0, 106.0, 134.0, +]; +const INTENSITY_HYSTERESIS: [f32; NB_BANDS] = [ + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 4.0, 5.0, 6.0, + 8.0, 8.0, +]; +const CH_MAX: usize = 2; +const N_MAX: usize = 960; +const PRE_LEN: usize = CH_MAX * (N_MAX + COMBFILTER_MAXPERIOD); +const PITCH_BUF_LEN: usize = (N_MAX + COMBFILTER_MAXPERIOD) >> 1; +const INPUT_LEN: usize = CH_MAX * (N_MAX + OVERLAP); +const FREQ_LEN: usize = CH_MAX * N_MAX; +const BAND_LEN: usize = CH_MAX * NB; + +/// libopus `OPUS_BITRATE_MAX`. +pub(crate) const BITRATE_MAX: i32 = -1; + +/// libopus `OpusCustomEncoder` for the static 48 kHz / 960 mode (float, no QEXT). +#[derive(Clone, Debug)] +pub(crate) struct CeltEnc { + channels: usize, + stream_channels: usize, + upsample: usize, + start: usize, + end: usize, + bitrate: i32, + vbr: bool, + constrained_vbr: bool, + loss_rate: i32, + lsb_depth: i32, + lfe: bool, + disable_inv: bool, + disable_pf: bool, + force_intra: bool, + complexity: i32, + clip: bool, + rng: u32, + spread_decision: i32, + delayed_intra: f32, + tonal_average: i32, + last_coded_bands: usize, + hf_average: i32, + tapset_decision: i32, + prefilter_period: i32, + prefilter_gain: f32, + prefilter_tapset: i32, + consec_transient: i32, + analysis: AnalysisInfo, + silk_signal_type: i32, + silk_offset: i32, + preemph_mem_e: [f32; 2], + vbr_reservoir: i32, + vbr_drift: i32, + vbr_offset: i32, + vbr_count: i32, + overlap_max: f32, + stereo_saving: f32, + intensity: usize, + spec_avg: f32, + in_mem: Vec, + prefilter_mem: Vec, + old_band_e: Vec, + old_log_e: Vec, + old_log_e2: Vec, + energy_error: Vec, +} + +fn zero_analysis() -> AnalysisInfo { + AnalysisInfo { + valid: false, + tonality: 0.0, + tonality_slope: 0.0, + noisiness: 0.0, + activity: 0.0, + music_prob: 0.0, + music_prob_min: 0.0, + music_prob_max: 0.0, + activity_probability: 0.0, + max_pitch_ratio: 0.0, + bandwidth: 0, + leak_boost: [0; LEAK_BANDS], + } +} + +fn max32(a: f32, b: f32) -> f32 { + if a > b { a } else { b } +} + +fn min32(a: f32, b: f32) -> f32 { + if a < b { a } else { b } +} + +fn maxabs(x: &[f32]) -> f32 { + let mut maxval = 0.0f32; + let mut minval = 0.0f32; + for &v in x { + maxval = max32(maxval, v); + minval = min32(minval, v); + } + max32(maxval, -minval) +} + +fn bitrate_to_bits(bitrate: i32, fs: i32, frame_size: i32) -> i32 { + bitrate * 6 / (6 * fs / frame_size) +} + +fn init_caps(lm: usize, c: usize) -> [i32; NB_BANDS] { + let mut cap = [0i32; NB_BANDS]; + for i in 0..NB_BANDS { + let n = ((E_BANDS[i + 1] - E_BANDS[i]) << lm) as i32; + cap[i] = ((CACHE_CAPS[NB_BANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * n) >> 2; + } + cap +} + +/// `compute_mdcts`: `short_blocks == 0` means long blocks. +fn compute_mdcts( + short_blocks: usize, + input: &[f32], + out: &mut [f32], + c: usize, + cc: usize, + lm: usize, + upsample: usize, +) { + let (b, nn, shift) = if short_blocks != 0 { + (short_blocks, SHORT_MDCT, MAX_LM) + } else { + (1, SHORT_MDCT << lm, MAX_LM - lm) + }; + for ch in 0..cc { + for blk in 0..b { + let in_off = ch * (b * nn + OVERLAP) + blk * nn; + let out_off = blk + ch * nn * b; + clt_mdct_forward(&input[in_off..], &mut out[out_off..], OVERLAP, shift, b); + } + } + if cc == 2 && c == 1 { + for i in 0..b * nn { + out[i] = 0.5f32 * out[i] + 0.5f32 * out[b * nn + i]; + } + } + if upsample != 1 { + for ch in 0..c { + let bound = b * nn / upsample; + for i in 0..bound { + out[ch * b * nn + i] *= upsample as f32; + } + out[ch * b * nn + bound..ch * b * nn + b * nn].fill(0.0); + } + } +} + +/// `celt_preemphasis` for the static mode, where `coef[1] == 0` so only the +/// single-pole branch is live. +fn celt_preemphasis( + pcm: &[f32], + inp: &mut [f32], + n: usize, + cc: usize, + upsample: usize, + coef0: f32, + mem: &mut f32, + clip: bool, +) { + let nu = n / upsample; + if upsample != 1 { + inp[..n].fill(0.0); + } + for i in 0..nu { + inp[i * upsample] = 32768.0f32 * pcm[cc * i]; + } + if clip { + for i in 0..nu { + inp[i * upsample] = max32(-65536.0, min32(65536.0, inp[i * upsample])); + } + } + let mut m = *mem; + for i in 0..n { + let x = inp[i]; + inp[i] = x - m; + m = coef0 * x; + } + *mem = m; +} + +impl CeltEnc { + /// `celt_encoder_init(st, 48000 / upsample, channels)`. + pub(crate) fn new(channels: usize, upsample: usize) -> CeltEnc { + let mut st = CeltEnc { + channels, + stream_channels: channels, + upsample, + start: 0, + end: NB_BANDS, + bitrate: BITRATE_MAX, + vbr: false, + constrained_vbr: true, + loss_rate: 0, + lsb_depth: 24, + lfe: false, + disable_inv: false, + disable_pf: false, + force_intra: false, + complexity: 5, + clip: true, + rng: 0, + spread_decision: 0, + delayed_intra: 0.0, + tonal_average: 0, + last_coded_bands: 0, + hf_average: 0, + tapset_decision: 0, + prefilter_period: 0, + prefilter_gain: 0.0, + prefilter_tapset: 0, + consec_transient: 0, + analysis: zero_analysis(), + silk_signal_type: 0, + silk_offset: 0, + preemph_mem_e: [0.0; 2], + vbr_reservoir: 0, + vbr_drift: 0, + vbr_offset: 0, + vbr_count: 0, + overlap_max: 0.0, + stereo_saving: 0.0, + intensity: 0, + spec_avg: 0.0, + in_mem: vec![0.0; channels * OVERLAP], + prefilter_mem: vec![0.0; channels * COMBFILTER_MAXPERIOD], + old_band_e: vec![0.0; channels * NB_BANDS], + old_log_e: vec![0.0; channels * NB_BANDS], + old_log_e2: vec![0.0; channels * NB_BANDS], + energy_error: vec![0.0; channels * NB_BANDS], + }; + st.reset(); + st + } + + /// `OPUS_RESET_STATE`. + pub(crate) fn reset(&mut self) { + self.rng = 0; + self.spread_decision = SPREAD_NORMAL as i32; + self.delayed_intra = 1.0; + self.tonal_average = 256; + self.last_coded_bands = 0; + self.hf_average = 0; + self.tapset_decision = 0; + self.prefilter_period = 0; + self.prefilter_gain = 0.0; + self.prefilter_tapset = 0; + self.consec_transient = 0; + self.analysis = zero_analysis(); + self.silk_signal_type = 0; + self.silk_offset = 0; + self.preemph_mem_e = [0.0; 2]; + self.vbr_reservoir = 0; + self.vbr_drift = 0; + self.vbr_offset = 0; + self.vbr_count = 0; + self.overlap_max = 0.0; + self.stereo_saving = 0.0; + self.intensity = 0; + self.spec_avg = 0.0; + self.in_mem.fill(0.0); + self.prefilter_mem.fill(0.0); + self.old_band_e.fill(0.0); + self.energy_error.fill(0.0); + self.old_log_e.fill(-28.0); + self.old_log_e2.fill(-28.0); + } + + /// `run_prefilter`: returns `(pf_on, pitch, gain, qgain)`. `prefilter_mem` is + /// the caller-taken `st->prefilter_mem`. + #[allow(clippy::too_many_arguments)] + fn run_prefilter( + &mut self, + input: &mut [f32], + prefilter_mem: &mut [f32], + cc: usize, + n: usize, + prefilter_tapset: i32, + enabled: bool, + tf_estimate: f32, + nb_available_bytes: i32, + analysis: &AnalysisInfo, + tone_freq: f32, + toneishness: f32, + ) -> (bool, i32, f32, i32) { + let max_period = COMBFILTER_MAXPERIOD; + let min_period = COMBFILTER_MINPERIOD; + let overlap = OVERLAP; + let window: &[f32] = &WINDOW120; + let pre_stride = n + max_period; + let mut pre_buf = [0.0f32; PRE_LEN]; + let pre = &mut pre_buf[..cc * pre_stride]; + for ch in 0..cc { + pre[ch * pre_stride..ch * pre_stride + max_period] + .copy_from_slice(&prefilter_mem[ch * max_period..(ch + 1) * max_period]); + let base = ch * pre_stride + max_period; + pre[base..base + n].copy_from_slice( + &input[ch * (n + overlap) + overlap..ch * (n + overlap) + overlap + n], + ); + } + + let mut pitch_index: i32; + let mut gain1: f32; + let mut tone_freq = tone_freq; + if enabled && toneishness > 0.99f32 { + let mut multiple: i32 = 1; + if tone_freq >= 3.1416f32 { + tone_freq = 3.141593f32 - tone_freq; + } + while tone_freq >= multiple as f32 * 0.39f32 { + multiple += 1; + } + if tone_freq > 0.006148f32 { + let v = (0.5f64 + 2.0f64 * PI * multiple as f64 / tone_freq as f64).floor() as i32; + pitch_index = v.min(COMBFILTER_MAXPERIOD as i32 - 2); + } else { + pitch_index = COMBFILTER_MINPERIOD as i32; + } + gain1 = 0.75; + } else if enabled && self.complexity >= 5 { + let mut pitch_buf_arr = [0.0f32; PITCH_BUF_LEN]; + let pitch_buf = &mut pitch_buf_arr[..(max_period + n) >> 1]; + { + let chans: [&[f32]; CH_MAX] = [&pre[..pre_stride], &pre[pre_stride..]]; + pitch_downsample(&chans[..cc], pitch_buf, (max_period + n) >> 1, 2); + } + pitch_index = pitch_search( + &pitch_buf[max_period >> 1..], + pitch_buf, + n, + max_period - 3 * min_period, + ); + pitch_index = max_period as i32 - pitch_index; + gain1 = remove_doubling( + pitch_buf, + max_period as i32, + min_period as i32, + n as i32, + &mut pitch_index, + self.prefilter_period, + self.prefilter_gain, + ); + if pitch_index > max_period as i32 - 2 { + pitch_index = max_period as i32 - 2; + } + gain1 *= 0.7f32; + if self.loss_rate > 2 { + gain1 *= 0.5; + } + if self.loss_rate > 4 { + gain1 *= 0.5; + } + if self.loss_rate > 8 { + gain1 = 0.0; + } + } else { + gain1 = 0.0; + pitch_index = COMBFILTER_MINPERIOD as i32; + } + if analysis.valid { + gain1 *= analysis.max_pitch_ratio; + } + + let mut pf_threshold: f32 = 0.2; + if (pitch_index - self.prefilter_period).abs() * 10 > pitch_index { + pf_threshold += 0.2; + if tf_estimate > 0.98f32 { + gain1 = 0.0; + } + } + if nb_available_bytes < 25 { + pf_threshold += 0.1; + } + if nb_available_bytes < 35 { + pf_threshold += 0.1; + } + if self.prefilter_gain > 0.4f32 { + pf_threshold -= 0.1; + } + if self.prefilter_gain > 0.55f32 { + pf_threshold -= 0.1; + } + pf_threshold = max32(pf_threshold, 0.2); + + let mut pf_on: bool; + let mut qg: i32; + if gain1 < pf_threshold { + gain1 = 0.0; + pf_on = false; + qg = 0; + } else { + if (gain1 - self.prefilter_gain).abs() < 0.1f32 { + gain1 = self.prefilter_gain; + } + qg = ((0.5f32 + gain1 * 32.0 / 3.0) as f64).floor() as i32 - 1; + qg = qg.clamp(0, 7); + gain1 = 0.09375f32 * (qg + 1) as f32; + pf_on = true; + } + + let offset = SHORT_MDCT - overlap; + let mut before = [0.0f32; 2]; + let mut after = [0.0f32; 2]; + for ch in 0..cc { + self.prefilter_period = self.prefilter_period.max(COMBFILTER_MINPERIOD as i32); + let in_base = ch * (n + overlap); + let pre_base = ch * pre_stride; + input[in_base..in_base + overlap] + .copy_from_slice(&self.in_mem[ch * overlap..(ch + 1) * overlap]); + for i in 0..n { + before[ch] += input[in_base + overlap + i].abs(); + } + if offset != 0 { + comb_filter( + &mut input[in_base + overlap..], + pre, + pre_base + max_period, + self.prefilter_period, + self.prefilter_period, + offset, + -self.prefilter_gain, + -self.prefilter_gain, + self.prefilter_tapset, + self.prefilter_tapset, + &[], + 0, + ); + } + comb_filter( + &mut input[in_base + overlap + offset..], + pre, + pre_base + max_period + offset, + self.prefilter_period, + pitch_index, + n - offset, + -self.prefilter_gain, + -gain1, + self.prefilter_tapset, + prefilter_tapset, + window, + overlap, + ); + for i in 0..n { + after[ch] += input[in_base + overlap + i].abs(); + } + } + + let mut cancel_pitch = false; + if cc == 2 { + let thresh0 = (0.25f32 * gain1) * before[0] + 0.01f32 * before[1]; + let thresh1 = (0.25f32 * gain1) * before[1] + 0.01f32 * before[0]; + if after[0] - before[0] > thresh0 || after[1] - before[1] > thresh1 { + cancel_pitch = true; + } + if before[0] - after[0] < thresh0 && before[1] - after[1] < thresh1 { + cancel_pitch = true; + } + } else if after[0] > before[0] { + cancel_pitch = true; + } + if cancel_pitch { + for ch in 0..cc { + let in_base = ch * (n + overlap); + let pre_base = ch * pre_stride; + input[in_base + overlap..in_base + overlap + n] + .copy_from_slice(&pre[pre_base + max_period..pre_base + max_period + n]); + comb_filter( + &mut input[in_base + overlap + offset..], + pre, + pre_base + max_period + offset, + self.prefilter_period, + pitch_index, + overlap, + -self.prefilter_gain, + 0.0, + self.prefilter_tapset, + prefilter_tapset, + window, + overlap, + ); + } + gain1 = 0.0; + pf_on = false; + qg = 0; + } + + for ch in 0..cc { + let in_base = ch * (n + overlap); + let pre_base = ch * pre_stride; + let mem_base = ch * max_period; + self.in_mem[ch * overlap..(ch + 1) * overlap] + .copy_from_slice(&input[in_base + n..in_base + n + overlap]); + if n > max_period { + prefilter_mem[mem_base..mem_base + max_period] + .copy_from_slice(&pre[pre_base + n..pre_base + n + max_period]); + } else { + prefilter_mem.copy_within(mem_base + n..mem_base + max_period, mem_base); + prefilter_mem[mem_base + max_period - n..mem_base + max_period] + .copy_from_slice(&pre[pre_base + max_period..pre_base + max_period + n]); + } + } + + (pf_on, pitch_index, gain1, qg) + } + + /// `celt_encode_with_ec`: `pcm` holds `frame_size * channels` samples at the API rate. + /// With `own == true` C's `enc == NULL` path: `enc` is reset to + /// `nb_compressed_bytes` here. Returns the byte count (C's return value). + pub(crate) fn encode( + &mut self, + pcm: &[f32], + frame_size: usize, + nb_compressed_bytes: usize, + enc: &mut RangeEncoder, + own: bool, + ) -> i32 { + if nb_compressed_bytes < 2 { + return -1; + } + let cc = self.channels; + let c = self.stream_channels; + let up = self.upsample; + let start = self.start; + let end = self.end; + let hybrid = start != 0; + let analysis = self.analysis; + let fs = 48000i32; + let frame_size = frame_size * up; + let mut lm = 0usize; + while lm <= MAX_LM && (SHORT_MDCT << lm) != frame_size { + lm += 1; + } + if lm > MAX_LM { + return -1; + } + let lm_i = lm as i32; + let c_i = c as i32; + let m = 1usize << lm; + let n = m * SHORT_MDCT; + let eff_end = end.min(NB); + + let mut tell: i32; + let tell0_frac: i32; + let nb_filled: i32; + if own { + tell0_frac = 1; + tell = 1; + nb_filled = 0; + } else { + tell0_frac = enc.tell_frac() as i32; + tell = enc.tell() as i32; + nb_filled = (tell + 4) >> 3; + } + + let mut nb = (nb_compressed_bytes as i32).min(PACKET_SIZE_CAP); + let vbr_rate: i32; + let mut effective_bytes: i32; + if self.vbr && self.bitrate != BITRATE_MAX { + vbr_rate = bitrate_to_bits(self.bitrate, fs, frame_size as i32) << BR; + effective_bytes = vbr_rate >> (3 + BR); + } else { + vbr_rate = 0; + let mut tmp = self.bitrate.wrapping_mul(frame_size as i32); + if tell > 1 { + tmp = tmp.wrapping_add(tell.wrapping_mul(fs)); + } + if self.bitrate != BITRATE_MAX { + nb = 2.max(nb.min((tmp + 4 * fs) / (8 * fs))); + if !own { + enc.shrink(nb as usize); + } + } + effective_bytes = nb - nb_filled; + } + let mut nb_avail = nb - nb_filled; + let mut equiv_rate = ((nb * 8 * 50) << (3 - lm_i)) - (40 * c_i + 20) * ((400 >> lm_i) - 50); + if self.bitrate != BITRATE_MAX { + equiv_rate = equiv_rate.min(self.bitrate - (40 * c_i + 20) * ((400 >> lm_i) - 50)); + } + + if own { + enc.reset(nb as usize); + } + + if vbr_rate > 0 && self.constrained_vbr { + let vbr_bound = vbr_rate; + let floor = if tell == 1 { 2 } else { 0 }; + let max_allowed = floor + .max((vbr_rate + vbr_bound - self.vbr_reservoir) >> (BR + 3)) + .min(nb_avail); + if max_allowed < nb_avail { + nb = nb_filled + max_allowed; + nb_avail = max_allowed; + enc.shrink(nb as usize); + } + } + let mut total_bits = nb * 8; + + let mut input_buf = [0.0f32; INPUT_LEN]; + let input = &mut input_buf[..cc * (n + OVERLAP)]; + let pcm_split = cc * (n - OVERLAP) / up; + let mut sample_max = max32(self.overlap_max, maxabs(&pcm[..pcm_split])); + self.overlap_max = maxabs(&pcm[pcm_split..pcm_split + cc * OVERLAP / up]); + sample_max = max32(sample_max, self.overlap_max); + let mut silence = sample_max <= 1.0f32 / ((1i32 << self.lsb_depth) as f32); + + if tell == 1 { + enc.enc_bit_logp(silence, 15); + } else { + silence = false; + } + if silence { + if vbr_rate > 0 { + nb = nb.min(nb_filled + 2); + effective_bytes = nb; + total_bits = nb * 8; + nb_avail = 2; + enc.shrink(nb as usize); + } + let before = enc.tell() as i32; + tell = nb * 8; + enc.add_tell(tell - before); + } + + for ch in 0..cc { + let need_clip = self.clip && sample_max > 65536.0; + let in_base = ch * (n + OVERLAP); + celt_preemphasis( + &pcm[ch..], + &mut input[in_base + OVERLAP..], + n, + cc, + up, + 0.85000610f32, + &mut self.preemph_mem_e[ch], + need_clip, + ); + let src = (ch + 1) * COMBFILTER_MAXPERIOD - OVERLAP; + input[in_base..in_base + OVERLAP] + .copy_from_slice(&self.prefilter_mem[src..src + OVERLAP]); + } + + let mut toneishness: f32 = 0.0; + let tone_freq = tone_detect(input, cc, n + OVERLAP, &mut toneishness, fs); + let mut is_transient = false; + let mut short_blocks = 0usize; + let mut tf_estimate: f32 = 0.0; + let mut tf_chan: usize = 0; + let mut weak_transient = false; + let mut transient_got_disabled = false; + if self.complexity >= 1 && !self.lfe { + let allow_weak_transients = + hybrid && effective_bytes < 15 && self.silk_signal_type != 2; + is_transient = transient_analysis( + input, + n + OVERLAP, + cc, + &mut tf_estimate, + &mut tf_chan, + allow_weak_transients, + &mut weak_transient, + tone_freq, + toneishness, + ); + } + toneishness = min32(toneishness, 1.0 - tf_estimate); + + let mut pitch_index: i32; + let gain1: f32; + let prefilter_tapset: i32; + let pf_on: bool; + let mut pitch_change = false; + { + let enabled = ((self.lfe && nb_avail > 3) || nb_avail > 12 * c_i) + && !hybrid + && !silence + && tell + 16 <= total_bits + && !self.disable_pf; + prefilter_tapset = self.tapset_decision; + let mut prefilter_mem = std::mem::take(&mut self.prefilter_mem); + let (on, pi, g, qg) = self.run_prefilter( + input, + &mut prefilter_mem, + cc, + n, + prefilter_tapset, + enabled, + tf_estimate, + nb_avail, + &analysis, + tone_freq, + toneishness, + ); + self.prefilter_mem = prefilter_mem; + pf_on = on; + pitch_index = pi; + gain1 = g; + if (gain1 > 0.4f32 || self.prefilter_gain > 0.4f32) + && (!analysis.valid || (analysis.tonality as f64) > 0.3) + && ((pitch_index as f64) > 1.26 * (self.prefilter_period as f64) + || (pitch_index as f64) < 0.79 * (self.prefilter_period as f64)) + { + pitch_change = true; + } + if !pf_on { + if !hybrid && tell + 16 <= total_bits { + enc.enc_bit_logp(false, 1); + } + } else { + enc.enc_bit_logp(true, 1); + pitch_index += 1; + let octave = ilog(pitch_index as u32) - 5; + enc.enc_uint(octave as u32, 6); + enc.enc_bits((pitch_index - (16 << octave)) as u32, (4 + octave) as u32); + pitch_index -= 1; + enc.enc_bits(qg as u32, 3); + enc.enc_icdf(prefilter_tapset as usize, &TAPSET_ICDF, 2); + } + } + if lm > 0 && (enc.tell() as i32) + 3 <= total_bits { + if is_transient { + short_blocks = m; + } + } else { + is_transient = false; + transient_got_disabled = true; + } + + let mut freq_buf = [0.0f32; FREQ_LEN]; + let freq = &mut freq_buf[..cc * n]; + let mut band_e_buf = [0.0f32; BAND_LEN]; + let band_e = &mut band_e_buf[..cc * NB]; + let mut band_log_e_buf = [0.0f32; BAND_LEN]; + let band_log_e = &mut band_log_e_buf[..cc * NB]; + let mut band_log_e2_buf = [0.0f32; BAND_LEN]; + let band_log_e2 = &mut band_log_e2_buf[..c * NB]; + + let second_mdct = short_blocks != 0 && self.complexity >= 8; + if second_mdct { + compute_mdcts(0, input, freq, c, cc, lm, up); + compute_band_energies(freq, band_e, eff_end, c, lm); + amp2log2(eff_end, end, band_e, band_log_e2, c); + for ch in 0..c { + for i in 0..end { + band_log_e2[NB * ch + i] += 0.5f32 * lm as f32; + } + } + } + + compute_mdcts(short_blocks, input, freq, c, cc, lm, up); + if cc == 2 && c == 1 { + tf_chan = 0; + } + compute_band_energies(freq, band_e, eff_end, c, lm); + if self.lfe { + for i in 2..end { + band_e[i] = min32(band_e[i], 1e-4f32 * band_e[0]); + band_e[i] = max32(band_e[i], EPSILON); + } + } + amp2log2(eff_end, end, band_e, band_log_e, c); + + let surround_buf = [0.0f32; BAND_LEN]; + let surround_dynalloc = &surround_buf[..cc * NB]; + let mut temporal_vbr: f32 = 0.0; + if !self.lfe { + let mut follow: f32 = -10.0; + let mut frame_avg: f32 = 0.0; + let offset: f32 = if short_blocks != 0 { + 0.5f32 * lm as f32 + } else { + 0.0 + }; + for i in start..end { + follow = max32(follow - 1.0, band_log_e[i] - offset); + if c == 2 { + follow = max32(follow, band_log_e[i + NB] - offset); + } + frame_avg += follow; + } + frame_avg /= (end as i32 - start as i32) as f32; + temporal_vbr = frame_avg - self.spec_avg; + temporal_vbr = min32(3.0, max32(-1.5, temporal_vbr)); + self.spec_avg += 0.02f32 * temporal_vbr; + } + + if !second_mdct { + band_log_e2[..c * NB].copy_from_slice(&band_log_e[..c * NB]); + } + + if lm > 0 + && (enc.tell() as i32) + 3 <= total_bits + && !is_transient + && self.complexity >= 5 + && !self.lfe + && !hybrid + && patch_transient_decision(band_log_e, &self.old_band_e, start, end, c) + { + is_transient = true; + short_blocks = m; + compute_mdcts(short_blocks, input, freq, c, cc, lm, up); + compute_band_energies(freq, band_e, eff_end, c, lm); + amp2log2(eff_end, end, band_e, band_log_e, c); + for ch in 0..c { + for i in 0..end { + band_log_e2[NB * ch + i] += 0.5f32 * lm as f32; + } + } + tf_estimate = 0.2f32; + } + + if lm > 0 && (enc.tell() as i32) + 3 <= total_bits { + enc.enc_bit_logp(is_transient, 3); + } + + let mut x_buf = [0.0f32; FREQ_LEN]; + let x = &mut x_buf[..c * n]; + normalise_bands(freq, x, band_e, eff_end, c, m); + + let enable_tf_analysis = effective_bytes >= 15 * c_i + && !hybrid + && self.complexity >= 2 + && !self.lfe + && toneishness < 0.98f32; + + let mut offsets = [0i32; NB]; + let mut importance = [0i32; NB]; + let mut spread_weight = [0i32; NB]; + let mut tot_boost: i32 = 0; + let max_depth = dynalloc_analysis( + band_log_e, + band_log_e2, + &self.old_band_e, + start, + end, + c, + &mut offsets, + self.lsb_depth, + is_transient, + self.vbr, + self.constrained_vbr, + lm, + effective_bytes, + &mut tot_boost, + self.lfe, + surround_dynalloc, + &analysis, + &mut importance, + &mut spread_weight, + tone_freq, + toneishness, + ); + + let mut tf_res = [0i32; NB]; + + let tf_select: i32; + if enable_tf_analysis { + let lambda = 80.max(20480 / effective_bytes + 2); + tf_select = tf_analysis( + eff_end, + is_transient, + &mut tf_res, + lambda, + x, + n, + lm, + tf_estimate, + tf_chan, + &importance, + ); + for i in eff_end..end { + tf_res[i] = tf_res[eff_end - 1]; + } + } else if hybrid && weak_transient { + for i in 0..end { + tf_res[i] = 1; + } + tf_select = 0; + } else if hybrid && effective_bytes < 15 && self.silk_signal_type != 2 { + for i in 0..end { + tf_res[i] = 0; + } + tf_select = is_transient as i32; + } else { + for i in 0..end { + tf_res[i] = is_transient as i32; + } + tf_select = 0; + } + + let mut error_buf = [0.0f32; BAND_LEN]; + let error = &mut error_buf[..c * NB]; + for ch in 0..c { + for i in start..end { + let idx = i + ch * NB; + if (band_log_e[idx] - self.old_band_e[idx]).abs() < 2.0f32 { + band_log_e[idx] -= 0.25f32 * self.energy_error[idx]; + } + } + } + quant_coarse_energy( + start, + end, + eff_end, + band_log_e, + &mut self.old_band_e, + total_bits as u32, + error, + enc, + c, + lm, + nb_avail, + self.force_intra, + &mut self.delayed_intra, + self.complexity >= 4, + self.loss_rate, + self.lfe, + ); + + tf_encode(start, end, is_transient, &mut tf_res, lm, tf_select, enc); + + if (enc.tell() as i32) + 4 <= total_bits { + if self.lfe { + self.tapset_decision = 0; + self.spread_decision = SPREAD_NORMAL as i32; + } else if hybrid { + if self.complexity == 0 { + self.spread_decision = SPREAD_NONE as i32; + } else if is_transient { + self.spread_decision = SPREAD_NORMAL as i32; + } else { + self.spread_decision = SPREAD_AGGRESSIVE as i32; + } + } else if short_blocks != 0 || self.complexity < 3 || nb_avail < 10 * c_i { + if self.complexity == 0 { + self.spread_decision = SPREAD_NONE as i32; + } else { + self.spread_decision = SPREAD_NORMAL as i32; + } + } else { + self.spread_decision = spreading_decision( + x, + &mut self.tonal_average, + self.spread_decision, + &mut self.hf_average, + &mut self.tapset_decision, + pf_on && short_blocks == 0, + eff_end, + c, + m, + &spread_weight, + ); + } + enc.enc_icdf(self.spread_decision as usize, &SPREAD_ICDF, 5); + } else { + self.spread_decision = SPREAD_NORMAL as i32; + } + + if self.lfe { + offsets[0] = 8.min(effective_bytes / 3); + } + let cap = init_caps(lm, c); + + let mut dynalloc_logp: i32 = 6; + total_bits <<= BR; + let mut total_boost: i32 = 0; + tell = enc.tell_frac() as i32; + for i in start..end { + let width = (c_i * (E_BANDS[i + 1] - E_BANDS[i]) as i32) << lm_i; + let quanta = (width << BR).min((6 << BR).max(width)); + let mut dynalloc_loop_logp = dynalloc_logp; + let mut boost: i32 = 0; + let mut j: i32 = 0; + while tell + (dynalloc_loop_logp << BR) < total_bits - total_boost && boost < cap[i] { + let flag = j < offsets[i]; + enc.enc_bit_logp(flag, dynalloc_loop_logp as u32); + tell = enc.tell_frac() as i32; + if !flag { + break; + } + boost += quanta; + total_boost += quanta; + dynalloc_loop_logp = 1; + j += 1; + } + if j != 0 { + dynalloc_logp = 2.max(dynalloc_logp - 1); + } + offsets[i] = boost; + } + + let mut dual_stereo = false; + if c == 2 { + if lm != 0 { + dual_stereo = stereo_analysis(x, lm, n); + } + let v = hysteresis_decision( + (equiv_rate / 1000) as f32, + &INTENSITY_THRESHOLDS, + &INTENSITY_HYSTERESIS, + self.intensity as i32, + ); + let v = (start as i32).max(v); + let v = (end as i32).min(v); + self.intensity = v as usize; + } + + let mut alloc_trim: i32 = 5; + if tell + (6 << BR) <= total_bits - total_boost { + if start > 0 || self.lfe { + self.stereo_saving = 0.0; + alloc_trim = 5; + } else { + alloc_trim = alloc_trim_analysis( + x, + band_log_e, + end, + lm, + c, + n, + &analysis, + &mut self.stereo_saving, + tf_estimate, + self.intensity, + 0.0, + equiv_rate, + ); + } + enc.enc_icdf(alloc_trim as usize, &TRIM_ICDF, 7); + tell = enc.tell_frac() as i32; + } + + let mut min_allowed = ((tell + total_boost + (1 << (BR + 3)) - 1) >> (BR + 3)) + 2; + if hybrid { + min_allowed = min_allowed + .max((tell0_frac + (37 << BR) + total_boost + (1 << (BR + 3)) - 1) >> (BR + 3)); + } + + if vbr_rate > 0 { + let lm_diff = MAX_LM as i32 - lm_i; + nb = nb.min(PACKET_SIZE_CAP >> (3 - lm_i)); + let mut base_target = if !hybrid { + vbr_rate - ((40 * c_i + 20) << BR) + } else { + 0.max(vbr_rate - ((9 * c_i + 4) << BR)) + }; + if self.constrained_vbr { + base_target += self.vbr_offset >> lm_diff; + } + let target = if !hybrid { + compute_vbr( + &analysis, + base_target, + lm, + equiv_rate, + self.last_coded_bands, + c, + self.intensity, + self.constrained_vbr, + self.stereo_saving, + tot_boost, + tf_estimate, + pitch_change, + max_depth, + self.lfe, + false, + 0.0, + temporal_vbr, + ) + } else { + let mut t = base_target; + if self.silk_offset < 100 { + t += (12 << BR) >> (3 - lm_i); + } + if self.silk_offset > 100 { + t -= (18 << BR) >> (3 - lm_i); + } + t += ((tf_estimate - 0.25f32) * ((50 << BR) as f32)) as i32; + if tf_estimate > 0.7f32 { + t = t.max(50 << BR); + } + t + }; + let target = target + tell; + + nb_avail = (target + (1 << (BR + 2))) >> (BR + 3); + nb_avail = min_allowed.max(nb_avail); + nb_avail = nb.min(nb_avail); + + let mut delta = target - vbr_rate; + let mut target_bits = nb_avail << (BR + 3); + + if silence { + nb_avail = 2; + target_bits = (2 * 8) << BR; + delta = 0; + } + + let alpha: f32 = if self.vbr_count < 970 { + self.vbr_count += 1; + celt_rcp((self.vbr_count + 20) as f32) + } else { + 0.001f32 + }; + if self.constrained_vbr { + self.vbr_reservoir += target_bits - vbr_rate; + let d = delta * (1 << lm_diff) - self.vbr_offset - self.vbr_drift; + self.vbr_drift += (alpha * d as f32) as i32; + self.vbr_offset = -self.vbr_drift; + } + if self.constrained_vbr && self.vbr_reservoir < 0 { + let adjust = (-self.vbr_reservoir) / (8 << BR); + if !silence { + nb_avail += adjust; + } + self.vbr_reservoir = 0; + } + nb = nb.min(nb_avail); + enc.shrink(nb as usize); + } + + let mut bits = ((nb * 8) << BR) - (enc.tell_frac() as i32) - 1; + let anti_collapse_rsv = if is_transient && lm >= 2 && bits >= ((lm_i + 2) << BR) { + 1 << BR + } else { + 0 + }; + bits -= anti_collapse_rsv; + + let mut pulses = [0i32; NB]; + let mut fine_quant = [0i32; NB]; + let mut fine_priority = [0i32; NB]; + let mut signal_bandwidth = end - 1; + if analysis.valid { + let min_bandwidth = if equiv_rate < 32000 * c_i { + 13 + } else if equiv_rate < 48000 * c_i { + 16 + } else if equiv_rate < 60000 * c_i { + 18 + } else if equiv_rate < 80000 * c_i { + 19 + } else { + 20 + }; + signal_bandwidth = (analysis.bandwidth.max(min_bandwidth)) as usize; + } + if self.lfe { + signal_bandwidth = 1; + } + let alloc = compute_allocation_encode( + enc, + start, + end, + alloc_trim, + bits, + c, + lm, + &offsets, + &cap, + &mut pulses, + &mut fine_quant, + &mut fine_priority, + self.intensity, + dual_stereo, + self.last_coded_bands, + signal_bandwidth, + ); + self.intensity = alloc.intensity; + dual_stereo = alloc.dual_stereo; + let balance = alloc.balance; + let coded_bands = alloc.coded_bands; + + if self.last_coded_bands != 0 { + self.last_coded_bands = + (self.last_coded_bands + 1).min((self.last_coded_bands - 1).max(coded_bands)); + } else { + self.last_coded_bands = coded_bands; + } + + quant_fine_energy(start, end, &mut self.old_band_e, error, &fine_quant, enc, c); + self.energy_error.fill(0.0); + + let mut collapse_buf = [0u8; BAND_LEN]; + let collapse_masks = &mut collapse_buf[..c * NB]; + { + let (x0, x1) = x.split_at_mut(n); + let y = if c == 2 { Some(x1) } else { None }; + quant_all_bands( + start, + end, + x0, + y, + collapse_masks, + band_e, + &pulses, + short_blocks != 0, + self.spread_decision, + dual_stereo, + self.intensity, + &tf_res, + nb * (8 << BR) - anti_collapse_rsv, + balance, + enc, + lm, + coded_bands, + &mut self.rng, + self.complexity, + self.disable_inv, + ); + } + + if anti_collapse_rsv > 0 { + let anti_collapse_on = self.consec_transient < 2; + enc.enc_bits(anti_collapse_on as u32, 1); + } + quant_energy_finalise( + start, + end, + &mut self.old_band_e, + error, + &fine_quant, + &fine_priority, + nb * 8 - enc.tell() as i32, + enc, + c, + ); + for ch in 0..c { + for i in start..end { + let idx = i + ch * NB; + self.energy_error[idx] = max32(-0.5, min32(0.5, error[idx])); + } + } + if silence { + self.old_band_e[..c * NB].fill(-28.0); + } + + self.prefilter_period = pitch_index; + self.prefilter_gain = gain1; + self.prefilter_tapset = prefilter_tapset; + + if cc == 2 && c == 1 { + self.old_band_e.copy_within(0..NB, NB); + } + + if !is_transient { + self.old_log_e2.copy_from_slice(&self.old_log_e); + self.old_log_e.copy_from_slice(&self.old_band_e); + } else { + for i in 0..cc * NB { + self.old_log_e[i] = min32(self.old_log_e[i], self.old_band_e[i]); + } + } + for ch in 0..cc { + for i in 0..start { + self.old_band_e[ch * NB + i] = 0.0; + self.old_log_e[ch * NB + i] = -28.0; + self.old_log_e2[ch * NB + i] = -28.0; + } + for i in end..NB { + self.old_band_e[ch * NB + i] = 0.0; + self.old_log_e[ch * NB + i] = -28.0; + self.old_log_e2[ch * NB + i] = -28.0; + } + } + + if is_transient || transient_got_disabled { + self.consec_transient += 1; + } else { + self.consec_transient = 0; + } + self.rng = enc.range(); + + enc.done(); + if enc.error() { + return -3; + } + nb + } + + /// `CELT_SET_START_BAND`. + pub(crate) fn set_start_band(&mut self, v: usize) { + if v < NB_BANDS { + self.start = v; + } + } + /// `CELT_SET_END_BAND`. + pub(crate) fn set_end_band(&mut self, v: usize) { + if (1..=NB_BANDS).contains(&v) { + self.end = v; + } + } + /// `CELT_SET_CHANNELS`. + pub(crate) fn set_stream_channels(&mut self, v: usize) { + if (1..=2).contains(&v) { + self.stream_channels = v; + } + } + /// `OPUS_SET_VBR`. + pub(crate) fn set_vbr(&mut self, v: bool) { + self.vbr = v; + } + /// `OPUS_SET_VBR_CONSTRAINT`. + pub(crate) fn set_vbr_constraint(&mut self, v: bool) { + self.constrained_vbr = v; + } + /// `OPUS_SET_BITRATE` (`BITRATE_MAX` allowed). + pub(crate) fn set_bitrate(&mut self, v: i32) { + if v <= 500 && v != BITRATE_MAX { + return; + } + self.bitrate = v.min(750000 * self.channels as i32); + } + /// `CELT_SET_PREDICTION`. + pub(crate) fn set_prediction(&mut self, v: i32) { + if !(0..=2).contains(&v) { + return; + } + self.disable_pf = v <= 1; + self.force_intra = v == 0; + } + /// `OPUS_SET_COMPLEXITY`. + pub(crate) fn set_complexity(&mut self, v: i32) { + if (0..=10).contains(&v) { + self.complexity = v; + } + } + /// `OPUS_SET_PACKET_LOSS_PERC`. + pub(crate) fn set_loss_rate(&mut self, v: i32) { + if (0..=100).contains(&v) { + self.loss_rate = v; + } + } + /// `OPUS_SET_LSB_DEPTH`. + pub(crate) fn set_lsb_depth(&mut self, v: i32) { + if (8..=24).contains(&v) { + self.lsb_depth = v; + } + } + /// `CELT_SET_ANALYSIS`. + pub(crate) fn set_analysis(&mut self, v: &AnalysisInfo) { + self.analysis = *v; + } + /// `CELT_SET_SILK_INFO`. + pub(crate) fn set_silk_info(&mut self, signal_type: i32, offset: i32) { + self.silk_signal_type = signal_type; + self.silk_offset = offset; + } + /// `OPUS_GET_FINAL_RANGE`. + pub(crate) fn final_range(&self) -> u32 { + self.rng + } +} diff --git a/crates/ec-opus/src/celt_flp/enc_an.rs b/crates/ec-opus/src/celt_flp/enc_an.rs new file mode 100644 index 00000000..c8222937 --- /dev/null +++ b/crates/ec-opus/src/celt_flp/enc_an.rs @@ -0,0 +1,843 @@ +use super::{EPSILON, MAX_LM, OVERLAP, PI, celt_exp2, celt_log2}; +use crate::analysis::{AnalysisInfo, LEAK_BANDS}; +use crate::celt::{BITRES, E_BANDS, E_MEANS, LOG_N, NB_BANDS, TF_SELECT}; +use crate::range::RangeEncoder; + +const MAX_FRAME: usize = 960; +const ANALYSIS_MAX_LEN: usize = MAX_FRAME + OVERLAP; +const TF_TMP_MAX: usize = 100 << MAX_LM; + +fn min_f(a: f32, b: f32) -> f32 { + if a < b { a } else { b } +} + +fn max_f(a: f32, b: f32) -> f32 { + if a > b { a } else { b } +} + +fn inner_prod(x: &[f32], y: &[f32]) -> f32 { + let mut xy = 0f32; + for i in 0..x.len() { + xy += x[i] * y[i]; + } + xy +} + +fn haar1(x: &mut [f32], n0: usize, stride: usize) { + let n0 = n0 >> 1; + for i in 0..stride { + for j in 0..n0 { + let tmp1 = 0.70710678f32 * x[stride * 2 * j + i]; + let tmp2 = 0.70710678f32 * x[stride * (2 * j + 1) + i]; + x[stride * 2 * j + i] = tmp1 + tmp2; + x[stride * (2 * j + 1) + i] = tmp1 - tmp2; + } + } +} + +const INV_TABLE: [u8; 128] = [ + 255, 255, 156, 110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25, 23, 22, 21, 20, 19, 18, 17, + 16, 16, 15, 15, 14, 13, 13, 12, 12, 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 9, 9, 8, 8, 8, + 8, 8, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, +]; + +/// `transient_analysis`; `input` is C `in` (`c * len`), returns `is_transient`. +pub(crate) fn transient_analysis( + input: &[f32], + len: usize, + c: usize, + tf_estimate: &mut f32, + tf_chan: &mut usize, + allow_weak_transients: bool, + weak_transient: &mut bool, + tone_freq: f32, + toneishness: f32, +) -> bool { + let forward_decay: f32 = if allow_weak_transients { + 0.03125 + } else { + 0.0625 + }; + let len2 = len / 2; + let mut tmp_buf = [0f32; ANALYSIS_MAX_LEN]; + let tmp = &mut tmp_buf[..len]; + let mut mask_metric: i32 = 0; + *weak_transient = false; + for ch in 0..c { + let mut mem0: f32 = 0.0; + let mut mem1: f32 = 0.0; + for i in 0..len { + let x = input[i + ch * len]; + let y = mem0 + x; + let mem00 = mem0; + mem0 = mem0 - x + 0.5f32 * mem1; + mem1 = x - mem00; + tmp[i] = y; + } + for v in tmp.iter_mut().take(12) { + *v = 0.0; + } + let mut mean: f32 = 0.0; + mem0 = 0.0; + for i in 0..len2 { + let x2 = tmp[2 * i] * tmp[2 * i] + tmp[2 * i + 1] * tmp[2 * i + 1]; + mean += x2; + mem0 = x2 + (1.0f32 - forward_decay) * mem0; + tmp[i] = forward_decay * mem0; + } + mem0 = 0.0; + let mut max_e: f32 = 0.0; + for i in (0..len2).rev() { + mem0 = tmp[i] + 0.875f32 * mem0; + tmp[i] = 0.125f32 * mem0; + max_e = max_f(max_e, 0.125f32 * mem0); + } + let arg: f64 = ((mean * max_e) as f64 * 0.5) * len2 as f64; + mean = arg.sqrt() as f32; + let norm: f32 = len2 as f32 / (EPSILON + mean); + let mut unmask: i32 = 0; + let mut i = 12usize; + while i + 5 < len2 { + let v = ((64.0f32 * norm) * (tmp[i] + EPSILON)).floor(); + let id = max_f(0.0, min_f(127.0, v)) as usize; + unmask += INV_TABLE[id] as i32; + i += 4; + } + unmask = (64 * unmask * 4) + .checked_div(6 * (len2 as i32 - 17)) + .unwrap_or(0); + if unmask > mask_metric { + *tf_chan = ch; + mask_metric = unmask; + } + } + let mut is_transient = mask_metric > 200; + if toneishness > 0.98f32 && tone_freq < 0.026f32 { + is_transient = false; + mask_metric = 0; + } + if allow_weak_transients && is_transient && mask_metric < 600 { + is_transient = false; + *weak_transient = true; + } + let tf_max = max_f( + 0.0, + ((27i32.wrapping_mul(mask_metric)) as f64).sqrt() as f32 - 42.0, + ); + let p = 0.0069f64 as f32 * min_f(163.0, tf_max); + let d = p as f64 - 0.139; + let d = if 0.0 > d { 0.0 } else { d }; + *tf_estimate = d.sqrt() as f32; + is_transient +} + +/// `patch_transient_decision`. +pub(crate) fn patch_transient_decision( + new_e: &[f32], + old_e: &[f32], + start: usize, + end: usize, + c: usize, +) -> bool { + let nb = NB_BANDS; + let mut spread_old = [0f32; 26]; + if c == 1 { + spread_old[start] = old_e[start]; + for i in start + 1..end { + spread_old[i] = max_f(spread_old[i - 1] - 1.0, old_e[i]); + } + } else { + spread_old[start] = max_f(old_e[start], old_e[start + nb]); + for i in start + 1..end { + spread_old[i] = max_f(spread_old[i - 1] - 1.0, max_f(old_e[i], old_e[i + nb])); + } + } + let mut i = end as i32 - 2; + while i >= start as i32 { + let iu = i as usize; + spread_old[iu] = max_f(spread_old[iu], spread_old[iu + 1] - 1.0); + i -= 1; + } + let mut mean_diff: f32 = 0.0; + for ch in 0..c { + for i in start.max(2)..end.saturating_sub(1) { + let x1 = max_f(0.0, new_e[i + ch * nb]); + let x2 = max_f(0.0, spread_old[i]); + mean_diff += max_f(0.0, x1 - x2); + } + } + let den = c as i32 * (end as i32 - 1 - start.max(2) as i32); + mean_diff /= den as f32; + mean_diff > 1.0 +} + +fn l1_metric(tmp: &[f32], n: usize, lm: i32, bias: f32) -> f32 { + let mut l1 = 0f32; + for i in 0..n { + l1 += tmp[i].abs(); + } + l1 + (lm as f32 * bias) * l1 +} + +/// `tf_analysis`; returns `tf_select`. +pub(crate) fn tf_analysis( + len: usize, + is_transient: bool, + tf_res: &mut [i32], + lambda: i32, + x: &[f32], + n0: usize, + lm: usize, + tf_estimate: f32, + tf_chan: usize, + importance: &[i32], +) -> i32 { + let is_t = is_transient as usize; + let bias = 0.04f32 * max_f(-0.25f32, 0.5f32 - tf_estimate); + let tmp_len = (E_BANDS[len] - E_BANDS[len - 1]) << lm; + let mut metric_buf = [0i32; NB_BANDS]; + let mut tmp_buf = [0f32; TF_TMP_MAX]; + let mut tmp_1_buf = [0f32; TF_TMP_MAX]; + let mut path0_buf = [0i32; NB_BANDS]; + let mut path1_buf = [0i32; NB_BANDS]; + let metric = &mut metric_buf[..len]; + let tmp = &mut tmp_buf[..tmp_len]; + let tmp_1 = &mut tmp_1_buf[..tmp_len]; + let path0 = &mut path0_buf[..len]; + let path1 = &mut path1_buf[..len]; + for i in 0..len { + let width = E_BANDS[i + 1] - E_BANDS[i]; + let n = width << lm; + let narrow = width == 1; + let base = tf_chan * n0 + (E_BANDS[i] << lm); + tmp[..n].copy_from_slice(&x[base..base + n]); + let mut l1 = l1_metric(&tmp[..n], n, if is_transient { lm as i32 } else { 0 }, bias); + let mut best_l1 = l1; + let mut best_level: i32 = 0; + if is_transient && !narrow { + tmp_1[..n].copy_from_slice(&tmp[..n]); + haar1(&mut tmp_1[..n], n >> lm, 1 << lm); + l1 = l1_metric(&tmp_1[..n], n, lm as i32 + 1, bias); + if l1 < best_l1 { + best_l1 = l1; + best_level = -1; + } + } + let kmax = lm + !(is_transient || narrow) as usize; + for k in 0..kmax { + let b = if is_transient { lm - k - 1 } else { k + 1 }; + haar1(&mut tmp[..n], n >> k, 1 << k); + l1 = l1_metric(&tmp[..n], n, b as i32, bias); + if l1 < best_l1 { + best_l1 = l1; + best_level = k as i32 + 1; + } + } + metric[i] = if is_transient { + 2 * best_level + } else { + -2 * best_level + }; + if narrow && (metric[i] == 0 || metric[i] == -2 * lm as i32) { + metric[i] -= 1; + } + } + let tbl = |idx: usize| TF_SELECT[lm][idx]; + let mut selcost = [0i32; 2]; + for sel in 0..2 { + let s0 = 4 * is_t + 2 * sel; + let s1 = s0 + 1; + let mut cost0 = importance[0] * (metric[0] - 2 * tbl(s0)).abs(); + let mut cost1 = + importance[0] * (metric[0] - 2 * tbl(s1)).abs() + if is_transient { 0 } else { lambda }; + for i in 1..len { + let curr0 = min_i(cost0, cost1 + lambda); + let curr1 = min_i(cost0 + lambda, cost1); + cost0 = curr0 + importance[i] * (metric[i] - 2 * tbl(s0)).abs(); + cost1 = curr1 + importance[i] * (metric[i] - 2 * tbl(s1)).abs(); + } + selcost[sel] = min_i(cost0, cost1); + } + let mut tf_select = 0i32; + if selcost[1] < selcost[0] && is_transient { + tf_select = 1; + } + let s0 = 4 * is_t + 2 * tf_select as usize; + let s1 = s0 + 1; + let mut cost0 = importance[0] * (metric[0] - 2 * tbl(s0)).abs(); + let mut cost1 = + importance[0] * (metric[0] - 2 * tbl(s1)).abs() + if is_transient { 0 } else { lambda }; + for i in 1..len { + let from0 = cost0; + let from1 = cost1 + lambda; + let (curr0, p0) = if from0 < from1 { + (from0, 0) + } else { + (from1, 1) + }; + let from0 = cost0 + lambda; + let from1 = cost1; + let (curr1, p1) = if from0 < from1 { + (from0, 0) + } else { + (from1, 1) + }; + path0[i] = p0; + path1[i] = p1; + cost0 = curr0 + importance[i] * (metric[i] - 2 * tbl(s0)).abs(); + cost1 = curr1 + importance[i] * (metric[i] - 2 * tbl(s1)).abs(); + } + tf_res[len - 1] = if cost0 < cost1 { 0 } else { 1 }; + for i in (0..len - 1).rev() { + tf_res[i] = if tf_res[i + 1] == 1 { + path1[i + 1] + } else { + path0[i + 1] + }; + } + tf_select +} + +fn min_i(a: i32, b: i32) -> i32 { + if a < b { a } else { b } +} + +/// `tf_encode`. +pub(crate) fn tf_encode( + start: usize, + end: usize, + is_transient: bool, + tf_res: &mut [i32], + lm: usize, + tf_select: i32, + enc: &mut RangeEncoder, +) { + let is_t = is_transient as usize; + let mut budget = enc.storage() as u32 * 8; + let mut tell = enc.tell(); + let mut logp: u32 = if is_transient { 2 } else { 4 }; + let tf_select_rsv = (lm > 0 && tell + logp < budget) as u32; + budget = budget.wrapping_sub(tf_select_rsv); + let mut curr = 0i32; + let mut tf_changed = 0i32; + for i in start..end { + if tell + logp <= budget { + enc.enc_bit_logp((tf_res[i] ^ curr) != 0, logp); + tell = enc.tell(); + curr = tf_res[i]; + tf_changed |= curr; + } else { + tf_res[i] = curr; + } + logp = if is_transient { 4 } else { 5 }; + } + let mut tf_select = tf_select; + if tf_select_rsv != 0 + && TF_SELECT[lm][4 * is_t + tf_changed as usize] + != TF_SELECT[lm][4 * is_t + 2 + tf_changed as usize] + { + enc.enc_bit_logp(tf_select != 0, 1); + } else { + tf_select = 0; + } + for i in start..end { + tf_res[i] = TF_SELECT[lm][4 * is_t + 2 * tf_select as usize + tf_res[i] as usize]; + } +} + +/// `alloc_trim_analysis`. +pub(crate) fn alloc_trim_analysis( + x: &[f32], + band_log_e: &[f32], + end: usize, + lm: usize, + c: usize, + n0: usize, + analysis: &AnalysisInfo, + stereo_saving: &mut f32, + tf_estimate: f32, + intensity: usize, + surround_trim: f32, + equiv_rate: i32, +) -> i32 { + let mut trim: f32 = 5.0; + if equiv_rate < 64000 { + trim = 4.0; + } else if equiv_rate < 80000 { + let frac = (equiv_rate - 64000) >> 10; + trim = 4.0 + (1.0f32 / 16.0f32) * frac as f32; + } + if c == 2 { + let mut sum: f32 = 0.0; + for i in 0..8 { + let lo = E_BANDS[i] << lm; + let n = (E_BANDS[i + 1] - E_BANDS[i]) << lm; + let partial = inner_prod(&x[lo..lo + n], &x[n0 + lo..n0 + lo + n]); + sum += partial; + } + sum *= 0.125f32; + sum = min_f(1.0, sum.abs()); + let mut min_xc = sum; + for i in 8..intensity { + let lo = E_BANDS[i] << lm; + let n = (E_BANDS[i + 1] - E_BANDS[i]) << lm; + let partial = inner_prod(&x[lo..lo + n], &x[n0 + lo..n0 + lo + n]); + min_xc = min_f(min_xc, partial.abs()); + } + min_xc = min_f(1.0, min_xc.abs()); + let log_xc = celt_log2(1.001f32 - sum * sum); + let log_xc2 = max_f(0.5f32 * log_xc, celt_log2(1.001f32 - min_xc * min_xc)); + trim += max_f(-4.0, 0.75f32 * log_xc); + *stereo_saving = min_f(*stereo_saving + 0.25, -(0.5f32 * log_xc2)); + } + let mut diff: f32 = 0.0; + for ch in 0..c { + for i in 0..end - 1 { + diff += band_log_e[i + ch * NB_BANDS] * (2 + 2 * i as i32 - end as i32) as f32; + } + } + diff /= (c as i32 * (end as i32 - 1)) as f32; + let t = (diff + 1.0) / 6.0; + trim -= max_f(-2.0, min_f(2.0, t)); + trim -= surround_trim; + trim -= 2.0 * tf_estimate; + if analysis.valid { + trim -= max_f( + -2.0, + min_f(2.0, 2.0f32 * (analysis.tonality_slope + 0.05f32)), + ); + } + let trim_index = ((0.5f32 + trim) as f64).floor() as i32; + trim_index.clamp(0, 10) +} + +/// `stereo_analysis`; returns `dual_stereo`. +pub(crate) fn stereo_analysis(x: &[f32], lm: usize, n0: usize) -> bool { + let mut sum_lr = EPSILON; + let mut sum_ms = EPSILON; + for i in 0..13 { + for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) { + let l = x[j]; + let r = x[n0 + j]; + let m = l + r; + let s = l - r; + sum_lr += l.abs() + r.abs(); + sum_ms += m.abs() + s.abs(); + } + } + sum_ms *= 0.707107f32; + let mut thetas: i32 = 13; + if lm <= 1 { + thetas -= 8; + } + let lhs = ((E_BANDS[13] << (lm + 1)) as i32 + thetas) as f32 * sum_ms; + let rhs = (E_BANDS[13] << (lm + 1)) as f32 * sum_lr; + lhs > rhs +} + +fn median_of_5(x: &[f32]) -> f32 { + let t2 = x[2]; + let (mut t0, mut t1) = if x[0] > x[1] { + (x[1], x[0]) + } else { + (x[0], x[1]) + }; + let (mut t3, mut t4) = if x[3] > x[4] { + (x[4], x[3]) + } else { + (x[3], x[4]) + }; + if t0 > t3 { + std::mem::swap(&mut t0, &mut t3); + std::mem::swap(&mut t1, &mut t4); + } + if t2 > t1 { + if t1 < t3 { + min_f(t2, t3) + } else { + min_f(t4, t1) + } + } else if t2 < t3 { + min_f(t1, t3) + } else { + min_f(t2, t4) + } +} + +fn median_of_3(x: &[f32]) -> f32 { + let (t0, t1) = if x[0] > x[1] { + (x[1], x[0]) + } else { + (x[0], x[1]) + }; + let t2 = x[2]; + if t1 < t2 { + t1 + } else if t0 < t2 { + t2 + } else { + t0 + } +} + +/// `dynalloc_analysis` (no QEXT); returns `maxDepth`. +pub(crate) fn dynalloc_analysis( + band_log_e: &[f32], + band_log_e2: &[f32], + old_band_e: &[f32], + start: usize, + end: usize, + c: usize, + offsets: &mut [i32], + lsb_depth: i32, + is_transient: bool, + vbr: bool, + constrained_vbr: bool, + lm: usize, + effective_bytes: i32, + tot_boost: &mut i32, + lfe: bool, + surround_dynalloc: &[f32], + analysis: &AnalysisInfo, + importance: &mut [i32], + spread_weight: &mut [i32], + tone_freq: f32, + toneishness: f32, +) -> f32 { + let nb = NB_BANDS; + let mut tb: i32 = 0; + let mut max_depth: f32 = -31.9; + let mut follower = [0f32; 2 * NB_BANDS]; + let mut noise_floor = [0f32; NB_BANDS]; + let mut band_log_e3 = [0f32; NB_BANDS]; + for v in offsets.iter_mut().take(nb) { + *v = 0; + } + for i in 0..end { + noise_floor[i] = 0.0625f32 * LOG_N[i] as f32 + 0.5 + (9 - lsb_depth) as f32 - E_MEANS[i] + + 0.0062f32 * (i + 5) as f32 * (i + 5) as f32; + } + for ch in 0..c { + for i in 0..end { + max_depth = max_f(max_depth, band_log_e[ch * nb + i] - noise_floor[i]); + } + } + let mut mask = [0f32; NB_BANDS]; + let mut sig = [0f32; NB_BANDS]; + for i in 0..end { + mask[i] = band_log_e[i] - noise_floor[i]; + } + if c == 2 { + for i in 0..end { + mask[i] = max_f(mask[i], band_log_e[nb + i] - noise_floor[i]); + } + } + sig[..end].copy_from_slice(&mask[..end]); + for i in 1..end { + mask[i] = max_f(mask[i], mask[i - 1] - 2.0); + } + for i in (0..end.saturating_sub(1)).rev() { + mask[i] = max_f(mask[i], mask[i + 1] - 3.0); + } + for i in 0..end { + let smr = sig[i] - max_f(max_f(0.0, max_depth - 12.0), mask[i]); + let fl = ((0.5f32 + smr) as f64).floor() as i32; + let shift = 5.min(0.max(fl.wrapping_neg())); + spread_weight[i] = 32 >> shift; + } + if effective_bytes >= 30 + 5 * lm as i32 && !lfe { + let mut last = 0usize; + for ch in 0..c { + band_log_e3[..end].copy_from_slice(&band_log_e2[ch * nb..ch * nb + end]); + if lm == 0 { + for i in 0..end.min(8) { + band_log_e3[i] = max_f(band_log_e2[ch * nb + i], old_band_e[ch * nb + i]); + } + } + let fb = ch * nb; + follower[fb] = band_log_e3[0]; + for i in 1..end { + if band_log_e3[i] > band_log_e3[i - 1] + 0.5 { + last = i; + } + follower[fb + i] = min_f(follower[fb + i - 1] + 1.5, band_log_e3[i]); + } + for i in (0..last).rev() { + follower[fb + i] = min_f( + follower[fb + i], + min_f(follower[fb + i + 1] + 2.0, band_log_e3[i]), + ); + } + let offset = 1.0f32; + for i in 2..end.saturating_sub(2) { + follower[fb + i] = max_f( + follower[fb + i], + median_of_5(&band_log_e3[i - 2..]) - offset, + ); + } + let tmp = median_of_3(&band_log_e3[..]) - offset; + follower[fb] = max_f(follower[fb], tmp); + follower[fb + 1] = max_f(follower[fb + 1], tmp); + let tmp = median_of_3(&band_log_e3[end - 3..]) - offset; + follower[fb + end - 2] = max_f(follower[fb + end - 2], tmp); + follower[fb + end - 1] = max_f(follower[fb + end - 1], tmp); + for i in 0..end { + follower[fb + i] = max_f(follower[fb + i], noise_floor[i]); + } + } + if c == 2 { + for i in start..end { + follower[nb + i] = max_f(follower[nb + i], follower[i] - 4.0); + follower[i] = max_f(follower[i], follower[nb + i] - 4.0); + follower[i] = 0.5f32 + * (max_f(0.0, band_log_e[i] - follower[i]) + + max_f(0.0, band_log_e[nb + i] - follower[nb + i])); + } + } else { + for i in start..end { + follower[i] = max_f(0.0, band_log_e[i] - follower[i]); + } + } + for i in start..end { + follower[i] = max_f(follower[i], surround_dynalloc[i]); + } + for i in start..end { + importance[i] = + ((0.5f32 + 13.0f32 * celt_exp2(min_f(follower[i], 4.0))) as f64).floor() as i32; + } + if (!vbr || constrained_vbr) && !is_transient { + for i in start..end { + follower[i] *= 0.5f32; + } + } + for i in start..end { + if i < 8 { + follower[i] *= 2.0; + } + if i >= 12 { + follower[i] *= 0.5f32; + } + } + if toneishness > 0.98f32 { + let freq_bin = (0.5f64 + ((tone_freq * 120.0f32) as f64) / PI).floor() as i32; + for i in start..end { + let lo = E_BANDS[i] as i32; + let hi = E_BANDS[i + 1] as i32; + if freq_bin >= lo && freq_bin <= hi { + follower[i] += 2.0; + } + if freq_bin >= lo - 1 && freq_bin <= hi + 1 { + follower[i] += 1.0; + } + if freq_bin >= lo - 2 && freq_bin <= hi + 2 { + follower[i] += 1.0; + } + if freq_bin >= lo - 3 && freq_bin <= hi + 3 { + follower[i] += 0.5; + } + } + if freq_bin >= E_BANDS[end] as i32 { + follower[end - 1] += 2.0; + follower[end - 2] += 1.0; + } + } + if analysis.valid { + for i in start..end.min(LEAK_BANDS) { + follower[i] += (1.0f32 / 64.0f32) * analysis.leak_boost[i] as f32; + } + } + if effective_bytes > 320 { + follower[0] += min_f(1.5, 1e-3f32 * (effective_bytes - 320) as f32); + } + for i in start..end { + follower[i] = min_f(follower[i], 4.0); + let width = ((c as i32) * (E_BANDS[i + 1] - E_BANDS[i]) as i32) << lm; + let (boost, boost_bits) = if width < 6 { + let boost = follower[i] as i32; + (boost, (boost * width) << BITRES) + } else if width > 48 { + let boost = (follower[i] * 8.0) as i32; + (boost, ((boost * width) << BITRES) / 8) + } else { + let boost = (follower[i] * width as f32 / 6.0) as i32; + (boost, (boost * 6) << BITRES) + }; + if (!vbr || (constrained_vbr && !is_transient)) + && ((tb + boost_bits) >> BITRES >> 3) > 2 * effective_bytes / 3 + { + let cap = ((2 * effective_bytes / 3) << BITRES) << 3; + offsets[i] = cap - tb; + tb = cap; + break; + } else { + offsets[i] = boost; + tb += boost_bits; + } + } + } else { + for i in start..end { + importance[i] = 13; + } + } + *tot_boost = tb; + max_depth +} + +/// `tone_detect`; returns `tone_freq`. +pub(crate) fn tone_detect( + input: &[f32], + cc: usize, + n: usize, + toneishness: &mut f32, + fs: i32, +) -> f32 { + let mut delay: usize = 1; + let mut x_buf = [0f32; ANALYSIS_MAX_LEN]; + let x = &mut x_buf[..n]; + if cc == 2 { + for i in 0..n { + x[i] = input[i] + input[i + n]; + } + } else { + x.copy_from_slice(&input[..n]); + } + let mut lpc = [0f32; 2]; + let mut fail = tone_lpc(x, n, delay, &mut lpc); + while delay <= (fs / 3000) as usize && (fail || (lpc[0] > 1.0 && lpc[1] < 0.0)) { + delay *= 2; + fail = tone_lpc(x, n, delay, &mut lpc); + } + let check = (lpc[0] * lpc[0]) as f64 + 3.999999f64 * lpc[1] as f64; + if !fail && check < 0.0 { + *toneishness = -lpc[1]; + ((((0.5f32 * lpc[0]) as f64).acos()) / delay as f64) as f32 + } else { + *toneishness = 0.0; + -1.0 + } +} + +fn tone_lpc(x: &[f32], len: usize, delay: usize, lpc: &mut [f32; 2]) -> bool { + let mut r00 = 0f32; + let mut r01 = 0f32; + let mut r02 = 0f32; + for i in 0..len - 2 * delay { + r00 += x[i] * x[i]; + r01 += x[i] * x[i + delay]; + r02 += x[i] * x[i + 2 * delay]; + } + let mut edges = 0f32; + for i in 0..delay { + edges += x[len + i - 2 * delay] * x[len + i - 2 * delay] - x[i] * x[i]; + } + let r11 = r00 + edges; + edges = 0.0; + for i in 0..delay { + edges += x[len + i - delay] * x[len + i - delay] - x[i + delay] * x[i + delay]; + } + let r22 = r11 + edges; + edges = 0.0; + for i in 0..delay { + edges += x[len + i - 2 * delay] * x[len + i - delay] - x[i] * x[i + delay]; + } + let r12 = r01 + edges; + let (r00, r01, r11, r02, r12) = (r00 + r22, r01 + r12, 2.0 * r11, 2.0 * r02, r12 + r01); + let den = r00 * r11 - r01 * r01; + if den < 0.001f32 * (r00 * r11) { + return true; + } + let num1 = r02 * r11 - r01 * r12; + lpc[1] = if num1 >= den { + 1.0 + } else if num1 <= -den { + -1.0 + } else { + num1 / den + }; + let num0 = r00 * r12 - r02 * r01; + lpc[0] = if 0.5f32 * num0 >= den { + 1.999999 + } else if 0.5f32 * num0 <= -den { + -1.999999 + } else { + num0 / den + }; + false +} + +/// `compute_vbr` (no QEXT); returns the target in 1/8 bits. +pub(crate) fn compute_vbr( + analysis: &AnalysisInfo, + base_target: i32, + lm: usize, + bitrate: i32, + last_coded_bands: usize, + c: usize, + intensity: usize, + constrained_vbr: bool, + stereo_saving: f32, + tot_boost: i32, + tf_estimate: f32, + pitch_change: bool, + max_depth: f32, + lfe: bool, + has_surround_mask: bool, + surround_masking: f32, + temporal_vbr: f32, +) -> i32 { + let coded_bands = if last_coded_bands != 0 { + last_coded_bands + } else { + NB_BANDS + }; + let mut coded_bins = (E_BANDS[coded_bands] << lm) as i32; + if c == 2 { + coded_bins += (E_BANDS[intensity.min(coded_bands)] << lm) as i32; + } + let mut target = base_target; + if analysis.valid && (analysis.activity as f64) < 0.4 { + target -= ((coded_bins << BITRES) as f32 * (0.4f32 - analysis.activity)) as i32; + } + let mut stereo_saving = stereo_saving; + if c == 2 { + let coded_stereo_bands = intensity.min(coded_bands); + let coded_stereo_dof = ((E_BANDS[coded_stereo_bands] << lm) - coded_stereo_bands) as i32; + let max_frac = (0.8f32 * coded_stereo_dof as f32) / coded_bins as f32; + stereo_saving = min_f(stereo_saving, 1.0); + let saving = min_f( + max_frac * target as f32, + (stereo_saving - 0.1f32) * ((coded_stereo_dof << BITRES) as f32), + ); + target -= saving as i32; + } + target += tot_boost - (19 << lm); + let tf_calibration = 0.044f32; + target += ((tf_estimate - tf_calibration) * target as f32) as i32; + if analysis.valid && !lfe { + let tonal: f32 = max_f(0.0, analysis.tonality - 0.15) - 0.12; + let mut tonal_target = target + ((coded_bins << BITRES) as f32 * 1.2f32 * tonal) as i32; + if pitch_change { + tonal_target += ((coded_bins << BITRES) as f32 * 0.8f32) as i32; + } + target = tonal_target; + } + if has_surround_mask && !lfe { + let surround_target = target + (surround_masking * (coded_bins << BITRES) as f32) as i32; + target = (target / 4).max(surround_target); + } + let bins = (E_BANDS[NB_BANDS - 2] << lm) as i32; + let mut floor_depth = ((((c as i32) * bins) << BITRES) as f32 * max_depth) as i32; + floor_depth = floor_depth.max(target >> 2); + target = target.min(floor_depth); + if (!has_surround_mask || lfe) && constrained_vbr { + target = base_target + ((target - base_target) as f32 * 0.67f32) as i32; + } + if !has_surround_mask && tf_estimate < 0.2f32 { + let amount = 0.0000031f32 * (96000 - bitrate).clamp(0, 32000) as f32; + let tvbr_factor = temporal_vbr * amount; + target += (tvbr_factor * target as f32) as i32; + } + target.min(2 * base_target) +} diff --git a/crates/ec-opus/src/celt_flp/fft.rs b/crates/ec-opus/src/celt_flp/fft.rs new file mode 100644 index 00000000..5e0ef3d0 --- /dev/null +++ b/crates/ec-opus/src/celt_flp/fft.rs @@ -0,0 +1,268 @@ +use super::tables::{self, FftState}; + +type Cpx = [f32; 2]; + +const MAX_N2: usize = 960; +const MAX_N4: usize = 480; + +fn cmul(a: Cpx, b: Cpx) -> Cpx { + [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]] +} + +fn cadd(a: Cpx, b: Cpx) -> Cpx { + [a[0] + b[0], a[1] + b[1]] +} + +fn csub(a: Cpx, b: Cpx) -> Cpx { + [a[0] - b[0], a[1] - b[1]] +} + +fn kf_bfly2(fout: &mut [Cpx], n: usize) { + const TW: f32 = 0.7071067812; + for i in 0..n { + let b = 8 * i; + let t = fout[b + 4]; + fout[b + 4] = csub(fout[b], t); + fout[b] = cadd(fout[b], t); + + let f5 = fout[b + 5]; + let t = [(f5[0] + f5[1]) * TW, (f5[1] - f5[0]) * TW]; + fout[b + 5] = csub(fout[b + 1], t); + fout[b + 1] = cadd(fout[b + 1], t); + + let f6 = fout[b + 6]; + let t = [f6[1], -f6[0]]; + fout[b + 6] = csub(fout[b + 2], t); + fout[b + 2] = cadd(fout[b + 2], t); + + let f7 = fout[b + 7]; + let t = [(f7[1] - f7[0]) * TW, (-(f7[1] + f7[0])) * TW]; + fout[b + 7] = csub(fout[b + 3], t); + fout[b + 3] = cadd(fout[b + 3], t); + } +} + +fn kf_bfly4(fout: &mut [Cpx], fstride: usize, m: usize, n: usize, mm: usize) { + let tw = &tables::FFT_TWIDDLES; + if m == 1 { + for i in 0..n { + let b = 4 * i; + let s0 = csub(fout[b], fout[b + 2]); + fout[b] = cadd(fout[b], fout[b + 2]); + let s1 = cadd(fout[b + 1], fout[b + 3]); + fout[b + 2] = csub(fout[b], s1); + fout[b] = cadd(fout[b], s1); + let s1 = csub(fout[b + 1], fout[b + 3]); + fout[b + 1] = [s0[0] + s1[1], s0[1] - s1[0]]; + fout[b + 3] = [s0[0] - s1[1], s0[1] + s1[0]]; + } + return; + } + let m2 = 2 * m; + let m3 = 3 * m; + for i in 0..n { + for j in 0..m { + let f = i * mm + j; + let s0 = cmul(fout[f + m], tw[j * fstride]); + let s1 = cmul(fout[f + m2], tw[j * 2 * fstride]); + let s2 = cmul(fout[f + m3], tw[j * 3 * fstride]); + + let s5 = csub(fout[f], s1); + fout[f] = cadd(fout[f], s1); + let s3 = cadd(s0, s2); + let s4 = csub(s0, s2); + fout[f + m2] = csub(fout[f], s3); + fout[f] = cadd(fout[f], s3); + + fout[f + m] = [s5[0] + s4[1], s5[1] - s4[0]]; + fout[f + m3] = [s5[0] - s4[1], s5[1] + s4[0]]; + } + } +} + +fn kf_bfly3(fout: &mut [Cpx], fstride: usize, m: usize, n: usize, mm: usize) { + let tw = &tables::FFT_TWIDDLES; + let m2 = 2 * m; + let epi3 = tw[fstride * m]; + for i in 0..n { + for j in 0..m { + let f = i * mm + j; + let s1 = cmul(fout[f + m], tw[j * fstride]); + let s2 = cmul(fout[f + m2], tw[j * 2 * fstride]); + + let s3 = cadd(s1, s2); + let mut s0 = csub(s1, s2); + + fout[f + m] = [fout[f][0] - s3[0] * 0.5, fout[f][1] - s3[1] * 0.5]; + + s0 = [s0[0] * epi3[1], s0[1] * epi3[1]]; + + fout[f] = cadd(fout[f], s3); + + fout[f + m2] = [fout[f + m][0] + s0[1], fout[f + m][1] - s0[0]]; + fout[f + m] = [fout[f + m][0] - s0[1], fout[f + m][1] + s0[0]]; + } + } +} + +fn kf_bfly5(fout: &mut [Cpx], fstride: usize, m: usize, n: usize, mm: usize) { + let tw = &tables::FFT_TWIDDLES; + let ya = tw[fstride * m]; + let yb = tw[fstride * 2 * m]; + for i in 0..n { + let base = i * mm; + for u in 0..m { + let f0 = base + u; + let f1 = f0 + m; + let f2 = f0 + 2 * m; + let f3 = f0 + 3 * m; + let f4 = f0 + 4 * m; + + let s0 = fout[f0]; + let s1 = cmul(fout[f1], tw[u * fstride]); + let s2 = cmul(fout[f2], tw[2 * u * fstride]); + let s3 = cmul(fout[f3], tw[3 * u * fstride]); + let s4 = cmul(fout[f4], tw[4 * u * fstride]); + + let s7 = cadd(s1, s4); + let s10 = csub(s1, s4); + let s8 = cadd(s2, s3); + let s9 = csub(s2, s3); + + fout[f0] = [fout[f0][0] + (s7[0] + s8[0]), fout[f0][1] + (s7[1] + s8[1])]; + + let s5 = [ + s0[0] + (s7[0] * ya[0] + s8[0] * yb[0]), + s0[1] + (s7[1] * ya[0] + s8[1] * yb[0]), + ]; + + let s6 = [ + s10[1] * ya[1] + s9[1] * yb[1], + -(s10[0] * ya[1] + s9[0] * yb[1]), + ]; + + fout[f1] = csub(s5, s6); + fout[f4] = cadd(s5, s6); + + let s11 = [ + s0[0] + (s7[0] * yb[0] + s8[0] * ya[0]), + s0[1] + (s7[1] * yb[0] + s8[1] * ya[0]), + ]; + let s12 = [ + s9[1] * ya[1] - s10[1] * yb[1], + s10[0] * yb[1] - s9[0] * ya[1], + ]; + + fout[f2] = cadd(s11, s12); + fout[f3] = csub(s11, s12); + } + } +} + +/// `opus_fft_impl` (float, in place on `fout`). +pub(crate) fn opus_fft_impl(st: &FftState, fout: &mut [[f32; 2]]) { + let shift = if st.shift > 0 { st.shift as usize } else { 0 }; + let mut fstride = [0usize; 9]; + fstride[0] = 1; + let mut l = 0usize; + loop { + let p = st.factors[2 * l] as usize; + let m = st.factors[2 * l + 1]; + fstride[l + 1] = fstride[l] * p; + l += 1; + if m == 1 { + break; + } + } + let mut m = st.factors[2 * l - 1] as usize; + for i in (0..l).rev() { + let m2 = if i != 0 { + st.factors[2 * i - 1] as usize + } else { + 1 + }; + match st.factors[2 * i] { + 2 => kf_bfly2(fout, fstride[i]), + 4 => kf_bfly4(fout, fstride[i] << shift, m, fstride[i], m2), + 3 => kf_bfly3(fout, fstride[i] << shift, m, fstride[i], m2), + 5 => kf_bfly5(fout, fstride[i] << shift, m, fstride[i], m2), + _ => {} + } + m = m2; + } +} + +/// `clt_mdct_forward_c` for the static 1920-point lookup; `input` is C `in`, +/// output goes to `out[k * stride]`. +pub(crate) fn clt_mdct_forward( + input: &[f32], + out: &mut [f32], + overlap: usize, + shift: usize, + stride: usize, +) { + let st = &tables::FFT_STATES[shift]; + let window = &tables::WINDOW120; + let trig_tab = &tables::MDCT_TWIDDLES; + let scale = st.scale; + + let mut n = 1920usize; + let mut trig = 0usize; + for _ in 0..shift { + n >>= 1; + trig += n; + } + let n2 = n >> 1; + let n4 = n >> 2; + + let h = overlap >> 1; + let mut f_buf = [0f32; MAX_N2]; + let mut f2_buf = [[0f32; 2]; MAX_N4]; + let f = &mut f_buf[..n2]; + let f2 = &mut f2_buf[..n4]; + + let fold_end = (overlap + 3) >> 2; + let tail_start = n4 - fold_end; + for i in 0..n4 { + let x1 = h + 2 * i; + let x2 = n2 - 1 + h - 2 * i; + let yp = 2 * i; + if i < fold_end { + let w1 = h + 2 * i; + let w2 = h - 1 - 2 * i; + f[yp] = input[x1 + n2] * window[w2] + input[x2] * window[w1]; + f[yp + 1] = input[x1] * window[w1] - input[x2 - n2] * window[w2]; + } else if i < tail_start { + f[yp] = input[x2]; + f[yp + 1] = input[x1]; + } else { + let k = i - tail_start; + let w1 = 2 * k; + let w2 = overlap - 1 - 2 * k; + f[yp] = -(input[x1 - n2] * window[w1]) + input[x2] * window[w2]; + f[yp + 1] = input[x1] * window[w2] + input[x2 + n2] * window[w1]; + } + } + + for i in 0..n4 { + let t0 = trig_tab[trig + 2 * i]; + let t1 = trig_tab[trig + 2 * i + 1]; + let re = f[2 * i]; + let im = f[2 * i + 1]; + let yr = re * t1 - im * t0; + let yi = im * t1 + re * t0; + f2[st.bitrev[i] as usize] = [yr * scale, yi * scale]; + } + + opus_fft_impl(st, f2); + + for i in 0..n4 { + let t0 = trig_tab[trig + 2 * i]; + let t1 = trig_tab[trig + 2 * i + 1]; + let fp = f2[i]; + let yr = fp[1] * t0 - fp[0] * t1; + let yi = fp[0] * t0 + fp[1] * t1; + out[2 * i * stride] = yr; + out[(n2 - 1 - 2 * i) * stride] = yi; + } +} diff --git a/crates/ec-opus/src/celt_flp/mod.rs b/crates/ec-opus/src/celt_flp/mod.rs new file mode 100644 index 00000000..4ebbe4be --- /dev/null +++ b/crates/ec-opus/src/celt_flp/mod.rs @@ -0,0 +1,81 @@ +#![allow( + clippy::needless_range_loop, + clippy::too_many_arguments, + clippy::manual_memcpy, + clippy::explicit_counter_loop, + clippy::excessive_precision, + clippy::approx_constant +)] + +pub(crate) mod bands; +pub(crate) mod enc; +pub(crate) mod enc_an; +pub(crate) mod fft; +pub(crate) mod pitch; +pub(crate) mod quant_bands; +pub(crate) mod tables; +pub(crate) mod vq; + +pub(crate) use crate::celt::{BITRES, E_BANDS, LOG_N, NB_BANDS}; + +pub(crate) const OVERLAP: usize = 120; +pub(crate) const COMBFILTER_MAXPERIOD: usize = 1024; +pub(crate) const COMBFILTER_MINPERIOD: usize = 15; +pub(crate) const SHORT_MDCT: usize = 120; +pub(crate) const MAX_LM: usize = 3; +pub(crate) const PI: f64 = std::f64::consts::PI; +pub(crate) const EPSILON: f32 = 1e-15; + +pub(crate) fn celt_sqrt(x: f32) -> f32 { + (x as f64).sqrt() as f32 +} + +pub(crate) fn celt_rsqrt(x: f32) -> f32 { + 1.0 / celt_sqrt(x) +} + +pub(crate) fn celt_rcp(x: f32) -> f32 { + 1.0 / x +} + +pub(crate) fn celt_log2(x: f32) -> f32 { + (1.442695040888963387f64 * (x as f64).ln()) as f32 +} + +pub(crate) fn celt_exp2(x: f32) -> f32 { + (0.6931471805599453094f64 * x as f64).exp() as f32 +} + +pub(crate) fn celt_cos_norm(x: f32) -> f32 { + ((0.5f32 as f64 * PI) * x as f64).cos() as f32 +} + +pub(crate) fn celt_atan_norm(x: f32) -> f32 { + const ATAN2_2_OVER_PI: f32 = 0.636619772367581; + const A03: f32 = -3.3331659436225891113281250000e-01; + const A05: f32 = 1.99627041816711425781250000000e-01; + const A07: f32 = -1.3976582884788513183593750000e-01; + const A09: f32 = 9.79423448443412780761718750000e-02; + const A11: f32 = -5.7773590087890625000000000000e-02; + const A13: f32 = 2.30401363223791122436523437500e-02; + const A15: f32 = -4.3554059229791164398193359375e-03; + let x_sq = x * x; + ATAN2_2_OVER_PI + * (x + x + * x_sq + * (A03 + + x_sq + * (A05 + + x_sq * (A07 + x_sq * (A09 + x_sq * (A11 + x_sq * (A13 + x_sq * A15))))))) +} + +pub(crate) fn celt_atan2p_norm(y: f32, x: f32) -> f32 { + if x * x + y * y < 1e-18 { + return 0.0; + } + if y < x { + celt_atan_norm(y / x) + } else { + 1.0 - celt_atan_norm(x / y) + } +} diff --git a/crates/ec-opus/src/celt_flp/pitch.rs b/crates/ec-opus/src/celt_flp/pitch.rs new file mode 100644 index 00000000..dd5a8cd9 --- /dev/null +++ b/crates/ec-opus/src/celt_flp/pitch.rs @@ -0,0 +1,569 @@ +use super::{COMBFILTER_MINPERIOD, celt_sqrt}; + +const SECOND_CHECK: [i32; 16] = [0, 0, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 5, 2, 3, 2]; + +const MAX_PERIOD: usize = 1024; +const MAX_FRAME: usize = 960; +const MAX_DOWN: usize = (MAX_PERIOD + MAX_FRAME) >> 1; +const MAX_LAG: usize = MAX_PERIOD + MAX_FRAME; +const MAX_YY_LOOKUP: usize = (MAX_PERIOD >> 1) + 1; + +const COMB_GAINS: [[f32; 3]; 3] = [ + [0.3066406250, 0.2170410156, 0.1296386719], + [0.4638671875, 0.2680664062, 0.0], + [0.7998046875, 0.1000976562, 0.0], +]; + +fn max_f(a: f32, b: f32) -> f32 { + if a > b { a } else { b } +} + +fn half32(x: f32) -> f32 { + 0.5f32 * x +} + +fn half16(x: f32) -> f32 { + 0.5f32 * x +} + +fn xcorr_kernel(x: &[f32], y: &[f32], sum: &mut [f32; 4], len: usize) { + let len = len as isize; + let mut xi = 0usize; + let mut yi = 3usize; + let mut y0 = y[0]; + let mut y1 = y[1]; + let mut y2 = y[2]; + let mut y3 = 0.0f32; + let mut j: isize = 0; + while j < len - 3 { + let tmp = x[xi]; + xi += 1; + y3 = y[yi]; + yi += 1; + sum[0] += tmp * y0; + sum[1] += tmp * y1; + sum[2] += tmp * y2; + sum[3] += tmp * y3; + let tmp = x[xi]; + xi += 1; + y0 = y[yi]; + yi += 1; + sum[0] += tmp * y1; + sum[1] += tmp * y2; + sum[2] += tmp * y3; + sum[3] += tmp * y0; + let tmp = x[xi]; + xi += 1; + y1 = y[yi]; + yi += 1; + sum[0] += tmp * y2; + sum[1] += tmp * y3; + sum[2] += tmp * y0; + sum[3] += tmp * y1; + let tmp = x[xi]; + xi += 1; + y2 = y[yi]; + yi += 1; + sum[0] += tmp * y3; + sum[1] += tmp * y0; + sum[2] += tmp * y1; + sum[3] += tmp * y2; + j += 4; + } + let c = j < len; + j += 1; + if c { + let tmp = x[xi]; + xi += 1; + y3 = y[yi]; + yi += 1; + sum[0] += tmp * y0; + sum[1] += tmp * y1; + sum[2] += tmp * y2; + sum[3] += tmp * y3; + } + let c = j < len; + j += 1; + if c { + let tmp = x[xi]; + xi += 1; + y0 = y[yi]; + yi += 1; + sum[0] += tmp * y1; + sum[1] += tmp * y2; + sum[2] += tmp * y3; + sum[3] += tmp * y0; + } + if j < len { + let tmp = x[xi]; + y1 = y[yi]; + sum[0] += tmp * y2; + sum[1] += tmp * y3; + sum[2] += tmp * y0; + sum[3] += tmp * y1; + } +} + +fn celt_pitch_xcorr(x: &[f32], y: &[f32], xcorr: &mut [f32], len: usize, max_pitch: usize) { + let mut i = 0usize; + while i + 4 <= max_pitch { + let mut sum = [0f32; 4]; + xcorr_kernel(x, &y[i..], &mut sum, len); + xcorr[i..i + 4].copy_from_slice(&sum); + i += 4; + } + while i < max_pitch { + xcorr[i] = celt_inner_prod(x, &y[i..], len); + i += 1; + } +} + +fn dual_inner_prod(x: &[f32], y01: &[f32], y02: &[f32], n: usize) -> (f32, f32) { + let mut xy01 = 0f32; + let mut xy02 = 0f32; + for i in 0..n { + xy01 += x[i] * y01[i]; + xy02 += x[i] * y02[i]; + } + (xy01, xy02) +} + +fn celt_fir5(x: &mut [f32], num: &[f32], n: usize) { + let (num0, num1, num2, num3, num4) = (num[0], num[1], num[2], num[3], num[4]); + let (mut mem0, mut mem1, mut mem2, mut mem3, mut mem4) = (0f32, 0f32, 0f32, 0f32, 0f32); + for xi in x.iter_mut().take(n) { + let mut sum = *xi; + sum += num0 * mem0; + sum += num1 * mem1; + sum += num2 * mem2; + sum += num3 * mem3; + sum += num4 * mem4; + mem4 = mem3; + mem3 = mem2; + mem2 = mem1; + mem1 = mem0; + mem0 = *xi; + *xi = sum; + } +} + +fn celt_lpc(lpc: &mut [f32], ac: &[f32], p: usize) { + for v in lpc.iter_mut().take(p) { + *v = 0.0; + } + let mut error = ac[0]; + if ac[0] > 1e-10f32 { + for i in 0..p { + let mut rr = 0f32; + for j in 0..i { + rr += lpc[j] * ac[i - j]; + } + rr += ac[i + 1]; + let r = -(rr / error); + lpc[i] = r; + for j in 0..((i + 1) >> 1) { + let tmp1 = lpc[j]; + let tmp2 = lpc[i - 1 - j]; + lpc[j] = tmp1 + r * tmp2; + lpc[i - 1 - j] = tmp2 + r * tmp1; + } + error = error - r * r * error; + if error <= 0.001f32 * ac[0] { + break; + } + } + } +} + +fn celt_autocorr( + x: &[f32], + ac: &mut [f32], + window: Option<&[f32]>, + overlap: usize, + lag: usize, + n: usize, +) { + let mut xx_buf = [0f32; MAX_DOWN]; + let xx = &mut xx_buf[..n]; + xx.copy_from_slice(&x[..n]); + if let Some(w) = window { + for i in 0..overlap { + xx[i] = x[i] * w[i]; + xx[n - i - 1] = x[n - i - 1] * w[i]; + } + } + let fast_n = n - lag; + celt_pitch_xcorr(xx, xx, ac, fast_n, lag + 1); + for k in 0..=lag { + let mut d = 0f32; + for i in (k + fast_n)..n { + d += xx[i] * xx[i - k]; + } + ac[k] += d; + } +} + +/// `pitch_downsample`; `x[c]` is C `x[c]` (one slice per channel). +pub(crate) fn pitch_downsample(x: &[&[f32]], x_lp: &mut [f32], len: usize, factor: usize) { + let offset = factor / 2; + let mut ac = [0f32; 5]; + let mut tmp = 1.0f32; + let mut lpc = [0f32; 4]; + let mut lpc2 = [0f32; 5]; + let c1 = 0.8f32; + for i in 1..len { + x_lp[i] = 0.25f32 * x[0][factor * i - offset] + + 0.25f32 * x[0][factor * i + offset] + + 0.5f32 * x[0][factor * i]; + } + x_lp[0] = 0.25f32 * x[0][offset] + 0.5f32 * x[0][0]; + if x.len() == 2 { + for i in 1..len { + x_lp[i] += 0.25f32 * x[1][factor * i - offset] + + 0.25f32 * x[1][factor * i + offset] + + 0.5f32 * x[1][factor * i]; + } + x_lp[0] += 0.25f32 * x[1][offset] + 0.5f32 * x[1][0]; + } + celt_autocorr(&x_lp[..len], &mut ac, None, 0, 4, len); + ac[0] *= 1.0001f32; + for i in 1..=4 { + let t = 0.008f32 * (i as f32); + ac[i] -= ac[i] * t * t; + } + celt_lpc(&mut lpc, &ac, 4); + for i in 0..4 { + tmp *= 0.9f32; + lpc[i] *= tmp; + } + lpc2[0] = lpc[0] + 0.8f32; + lpc2[1] = lpc[1] + c1 * lpc[0]; + lpc2[2] = lpc[2] + c1 * lpc[1]; + lpc2[3] = lpc[3] + c1 * lpc[2]; + lpc2[4] = c1 * lpc[3]; + celt_fir5(x_lp, &lpc2, len); +} + +fn find_best_pitch( + xcorr: &[f32], + y: &[f32], + len: usize, + max_pitch: usize, + best_pitch: &mut [i32; 2], +) { + let mut syy = 1.0f32; + let mut best_num = [-1.0f32; 2]; + let mut best_den = [0.0f32; 2]; + best_pitch[0] = 0; + best_pitch[1] = 1; + for j in 0..len { + syy += y[j] * y[j]; + } + for i in 0..max_pitch { + if xcorr[i] > 0.0 { + let mut xcorr16 = xcorr[i]; + xcorr16 *= 1e-12f32; + let num = xcorr16 * xcorr16; + if num * best_den[1] > best_num[1] * syy { + if num * best_den[0] > best_num[0] * syy { + best_num[1] = best_num[0]; + best_den[1] = best_den[0]; + best_pitch[1] = best_pitch[0]; + best_num[0] = num; + best_den[0] = syy; + best_pitch[0] = i as i32; + } else { + best_num[1] = num; + best_den[1] = syy; + best_pitch[1] = i as i32; + } + } + } + syy += y[i + len] * y[i + len] - y[i] * y[i]; + syy = max_f(1.0, syy); + } +} + +/// `pitch_search`; returns C `*pitch`. +pub(crate) fn pitch_search(x_lp: &[f32], y: &[f32], len: usize, max_pitch: usize) -> i32 { + let lag = len + max_pitch; + let mut x_lp4_buf = [0f32; MAX_FRAME >> 2]; + let mut y_lp4_buf = [0f32; MAX_LAG >> 2]; + let mut xcorr_buf = [0f32; MAX_PERIOD >> 1]; + let x_lp4 = &mut x_lp4_buf[..len >> 2]; + let y_lp4 = &mut y_lp4_buf[..lag >> 2]; + let xcorr = &mut xcorr_buf[..max_pitch >> 1]; + for j in 0..len >> 2 { + x_lp4[j] = x_lp[2 * j]; + } + for j in 0..lag >> 2 { + y_lp4[j] = y[2 * j]; + } + celt_pitch_xcorr(x_lp4, y_lp4, xcorr, len >> 2, max_pitch >> 2); + let mut best_pitch = [0i32; 2]; + find_best_pitch(xcorr, y_lp4, len >> 2, max_pitch >> 2, &mut best_pitch); + for i in 0..max_pitch >> 1 { + xcorr[i] = 0.0; + let ii = i as i32; + if (ii - 2 * best_pitch[0]).abs() > 2 && (ii - 2 * best_pitch[1]).abs() > 2 { + continue; + } + let sum = celt_inner_prod(x_lp, &y[i..], len >> 1); + xcorr[i] = if -1.0f32 > sum { -1.0f32 } else { sum }; + } + find_best_pitch(xcorr, y, len >> 1, max_pitch >> 1, &mut best_pitch); + let bp = best_pitch[0]; + let offset = if bp > 0 && bp < (max_pitch as i32 >> 1) - 1 { + let b_idx = bp as usize; + let a = xcorr[b_idx - 1]; + let b = xcorr[b_idx]; + let c = xcorr[b_idx + 1]; + if (c - a) > 0.7f32 * (b - a) { + 1 + } else if (a - c) > 0.7f32 * (b - c) { + -1 + } else { + 0 + } + } else { + 0 + }; + 2 * bp - offset +} + +fn compute_pitch_gain(xy: f32, xx: f32, yy: f32) -> f32 { + xy / celt_sqrt(1.0 + xx * yy) +} + +/// `remove_doubling`; `x` is C `x` (before its internal `x += maxperiod`). +pub(crate) fn remove_doubling( + x: &[f32], + maxperiod: i32, + minperiod: i32, + n: i32, + t0: &mut i32, + prev_period: i32, + prev_gain: f32, +) -> f32 { + let minperiod0 = minperiod; + let maxperiod = maxperiod / 2; + let minperiod = minperiod / 2; + *t0 /= 2; + let prev_period = prev_period / 2; + let n = n / 2; + let nn = n as usize; + let base = maxperiod as isize; + let at = |d: isize| (base + d) as usize; + if *t0 >= maxperiod { + *t0 = maxperiod - 1; + } + let t0v = *t0; + let (xx, xy) = dual_inner_prod(&x[at(0)..], &x[at(0)..], &x[at(-(t0v as isize))..], nn); + let mut yy_lookup_buf = [0f32; MAX_YY_LOOKUP]; + let yy_lookup = &mut yy_lookup_buf[..(maxperiod + 1) as usize]; + yy_lookup[0] = xx; + let mut yy = xx; + for i in 1..=maxperiod as isize { + let a = x[at(-i)]; + let b = x[at(n as isize - i)]; + yy = yy + a * a - b * b; + yy_lookup[i as usize] = max_f(0.0, yy); + } + let mut t = t0v; + let mut best_xy = xy; + let mut best_yy = yy_lookup[t0v as usize]; + let mut g = compute_pitch_gain(xy, xx, best_yy); + let g0 = g; + for k in 2..=15 { + let t1 = (2 * t0v + k) / (2 * k); + if t1 < minperiod { + break; + } + let t1b = if k == 2 { + if t1 + t0v > maxperiod { t0v } else { t0v + t1 } + } else { + (2 * SECOND_CHECK[k as usize] * t0v + k) / (2 * k) + }; + let (xy_a, xy2) = dual_inner_prod( + &x[at(0)..], + &x[at(-(t1 as isize))..], + &x[at(-(t1b as isize))..], + nn, + ); + let xy_k = half32(xy_a + xy2); + let yy_k = half32(yy_lookup[t1 as usize] + yy_lookup[t1b as usize]); + let g1 = compute_pitch_gain(xy_k, xx, yy_k); + let cont = if (t1 - prev_period).abs() <= 1 { + prev_gain + } else if (t1 - prev_period).abs() <= 2 && 5 * k * k < t0v { + half16(prev_gain) + } else { + 0.0 + }; + let mut thresh = max_f(0.3f32, 0.7f32 * g0 - cont); + if t1 < 3 * minperiod { + thresh = max_f(0.4f32, 0.85f32 * g0 - cont); + } else if t1 < 2 * minperiod { + thresh = max_f(0.5f32, 0.9f32 * g0 - cont); + } + if g1 > thresh { + best_xy = xy_k; + best_yy = yy_k; + t = t1; + g = g1; + } + } + if t < minperiod * 2 { + let t1 = t * 5 / 8; + let t2 = t * 6 / 8; + let (xy_a, xy2) = dual_inner_prod( + &x[at(0)..], + &x[at(-(t1 as isize))..], + &x[at(-(t2 as isize))..], + nn, + ); + let g1 = compute_pitch_gain(xy_a, xx, yy_lookup[t1 as usize]); + let g2 = compute_pitch_gain(xy2, xx, yy_lookup[t2 as usize]); + if g1 >= g || g2 >= g { + g = 0.0; + } + } + best_xy = max_f(0.0, best_xy); + let mut pg = if best_yy <= best_xy { + 1.0f32 + } else { + best_xy / (best_yy + 1.0) + }; + let mut xcorr = [0f32; 3]; + for k in 0..3 { + let off = at(-(t as isize) - k as isize + 1); + xcorr[k] = celt_inner_prod(&x[at(0)..], &x[off..], nn); + } + let offset = if (xcorr[2] - xcorr[0]) > 0.7f32 * (xcorr[1] - xcorr[0]) { + 1 + } else if (xcorr[0] - xcorr[2]) > 0.7f32 * (xcorr[1] - xcorr[2]) { + -1 + } else { + 0 + }; + if pg > g { + pg = g; + } + *t0 = 2 * t + offset; + if *t0 < minperiod0 { + *t0 = minperiod0; + } + pg +} + +/// `comb_filter` (celt.c, float, no QEXT) with distinct buffers: C `y` is +/// `y[0..n]`, C `x[i]` is `x[x_off + i]` (read down to `x_off - T - 2`). +pub(crate) fn comb_filter( + y: &mut [f32], + x: &[f32], + x_off: usize, + t0: i32, + t1: i32, + n: usize, + g0: f32, + g1: f32, + tapset0: i32, + tapset1: i32, + window: &[f32], + overlap: usize, +) { + if g0 == 0.0 && g1 == 0.0 { + y[..n].copy_from_slice(&x[x_off..x_off + n]); + return; + } + let t0 = t0.max(COMBFILTER_MINPERIOD as i32) as isize; + let t1 = t1.max(COMBFILTER_MINPERIOD as i32) as isize; + let ts0 = tapset0 as usize; + let ts1 = tapset1 as usize; + let g00 = g0 * COMB_GAINS[ts0][0]; + let g01 = g0 * COMB_GAINS[ts0][1]; + let g02 = g0 * COMB_GAINS[ts0][2]; + let g10 = g1 * COMB_GAINS[ts1][0]; + let g11 = g1 * COMB_GAINS[ts1][1]; + let g12 = g1 * COMB_GAINS[ts1][2]; + let p = |d: isize| (x_off as isize + d) as usize; + let mut x1 = x[p(-t1 + 1)]; + let mut x2 = x[p(-t1)]; + let mut x3 = x[p(-t1 - 1)]; + let mut x4 = x[p(-t1 - 2)]; + let mut overlap = overlap; + if g0 == g1 && t0 == t1 && tapset0 == tapset1 { + overlap = 0; + } + for i in 0..overlap { + let ii = i as isize; + let x0 = x[p(ii - t1 + 2)]; + let f = window[i] * window[i]; + let a0 = (1.0f32 - f) * g00; + let a1 = (1.0f32 - f) * g01; + let a2 = (1.0f32 - f) * g02; + let b0 = f * g10; + let b1 = f * g11; + let b2 = f * g12; + y[i] = x[p(ii)] + + a0 * x[p(ii - t0)] + + a1 * (x[p(ii - t0 + 1)] + x[p(ii - t0 - 1)]) + + a2 * (x[p(ii - t0 + 2)] + x[p(ii - t0 - 2)]) + + b0 * x2 + + b1 * (x1 + x3) + + b2 * (x0 + x4); + x4 = x3; + x3 = x2; + x2 = x1; + x1 = x0; + } + if g1 == 0.0 { + y[overlap..n].copy_from_slice(&x[x_off + overlap..x_off + n]); + return; + } + comb_filter_const( + &mut y[overlap..], + x, + x_off + overlap, + t1, + n - overlap, + g10, + g11, + g12, + ); +} + +fn comb_filter_const( + y: &mut [f32], + x: &[f32], + x_off: usize, + t: isize, + n: usize, + g10: f32, + g11: f32, + g12: f32, +) { + let p = |d: isize| (x_off as isize + d) as usize; + let mut x4 = x[p(-t - 2)]; + let mut x3 = x[p(-t - 1)]; + let mut x2 = x[p(-t)]; + let mut x1 = x[p(-t + 1)]; + for i in 0..n { + let ii = i as isize; + let x0 = x[p(ii - t + 2)]; + y[i] = x[p(ii)] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4); + x4 = x3; + x3 = x2; + x2 = x1; + x1 = x0; + } +} + +/// `celt_inner_prod_c`. +pub(crate) fn celt_inner_prod(x: &[f32], y: &[f32], n: usize) -> f32 { + let mut xy = 0f32; + for i in 0..n { + xy += x[i] * y[i]; + } + xy +} diff --git a/crates/ec-opus/src/celt_flp/quant_bands.rs b/crates/ec-opus/src/celt_flp/quant_bands.rs new file mode 100644 index 00000000..9af6a3d6 --- /dev/null +++ b/crates/ec-opus/src/celt_flp/quant_bands.rs @@ -0,0 +1,358 @@ +use super::celt_log2; +use crate::celt::{ + BETA_COEF, BETA_INTRA, E_MEANS, E_PROB_MODEL, MAX_FINE_BITS, NB_BANDS, PRED_COEF, + SMALL_ENERGY_ICDF, +}; +use crate::range::RangeEncoder; + +const LAPLACE_MINP: u32 = 1; +const LAPLACE_NMIN: u32 = 16; +const MAX_FRAME_BYTES: usize = 1275; + +fn laplace_get_freq1(fs0: u32, decay: i32) -> u32 { + let ft = 32768 - LAPLACE_MINP * (2 * LAPLACE_NMIN) - fs0; + ft.wrapping_mul((16384 - decay) as u32) >> 15 +} + +fn laplace_encode(enc: &mut RangeEncoder, value: &mut i32, fs: u32, decay: i32) { + let mut fs = fs; + let mut fl: u32 = 0; + let mut val = *value; + if val != 0 { + let s: i32 = -((val < 0) as i32); + val = (val + s) ^ s; + fl = fs; + fs = laplace_get_freq1(fs, decay); + let mut i: i32 = 1; + while fs > 0 && i < val { + fs *= 2; + fl += fs + 2 * LAPLACE_MINP; + fs = (fs * decay as u32) >> 15; + i += 1; + } + if fs == 0 { + let ndi_max = + ((32768u32.wrapping_sub(fl).wrapping_add(LAPLACE_MINP - 1)) as i32 - s) >> 1; + let di = (val - i).min(ndi_max - 1); + fl = fl.wrapping_add((2 * di + 1 + s) as u32 * LAPLACE_MINP); + fs = LAPLACE_MINP.min(32768u32.wrapping_sub(fl)); + *value = (i + di + s) ^ s; + } else { + fs += LAPLACE_MINP; + if s == 0 { + fl += fs; + } + } + } + enc.encode_bin(fl, fl + fs, 15); +} + +fn loss_distortion( + e_bands: &[f32], + old_e_bands: &[f32], + start: usize, + end: usize, + c: usize, +) -> f32 { + let mut dist = 0f32; + for ch in 0..c { + for i in start..end { + let d = e_bands[i + ch * NB_BANDS] - old_e_bands[i + ch * NB_BANDS]; + dist += d * d; + } + } + if 200.0 < dist { 200.0 } else { dist } +} + +fn quant_coarse_energy_impl( + start: usize, + end: usize, + e_bands: &[f32], + old_e_bands: &mut [f32], + budget: i32, + mut tell: i32, + prob_model: &[u8; 42], + error: &mut [f32], + enc: &mut RangeEncoder, + c: usize, + lm: usize, + intra: bool, + max_decay: f32, + lfe: bool, +) -> i32 { + let mut badness = 0i32; + let mut prev = [0f32; 2]; + if tell + 3 <= budget { + enc.enc_bit_logp(intra, 3); + } + let (coef, beta) = if intra { + (0f32, BETA_INTRA) + } else { + (PRED_COEF[lm], BETA_COEF[lm]) + }; + for i in start..end { + for ch in 0..c { + let idx = i + ch * NB_BANDS; + let x = e_bands[idx]; + let old_e = if -9.0f32 > old_e_bands[idx] { + -9.0f32 + } else { + old_e_bands[idx] + }; + let f = x - coef * old_e - prev[ch]; + let mut qi = ((0.5f32 + f) as f64).floor() as i32; + let raw_old = if -28.0f32 > old_e_bands[idx] { + -28.0f32 + } else { + old_e_bands[idx] + }; + let decay_bound = raw_old - max_decay; + if qi < 0 && x < decay_bound { + qi += (decay_bound - x) as i32; + if qi > 0 { + qi = 0; + } + } + let qi0 = qi; + tell = enc.tell() as i32; + let bits_left = budget - tell - 3 * c as i32 * (end - i) as i32; + if i != start && bits_left < 30 { + if bits_left < 24 { + qi = qi.min(1); + } + if bits_left < 16 { + qi = qi.max(-1); + } + } + if lfe && i >= 2 { + qi = qi.min(0); + } + if budget - tell >= 15 { + let pi = 2 * i.min(20); + laplace_encode( + enc, + &mut qi, + (prob_model[pi] as u32) << 7, + (prob_model[pi + 1] as i32) << 6, + ); + } else if budget - tell >= 2 { + qi = qi.clamp(-1, 1); + let k = (2 * qi) ^ if qi < 0 { -1 } else { 0 }; + enc.enc_icdf(k as usize, &SMALL_ENERGY_ICDF, 2); + } else if budget - tell >= 1 { + qi = qi.min(0); + enc.enc_bit_logp(qi != 0, 1); + } else { + qi = -1; + } + error[idx] = f - qi as f32; + badness += (qi0 - qi).abs(); + let q = qi as f32; + old_e_bands[idx] = coef * old_e + prev[ch] + q; + prev[ch] = prev[ch] + q - beta * q; + } + } + if lfe { 0 } else { badness } +} + +/// `quant_coarse_energy`. +pub(crate) fn quant_coarse_energy( + start: usize, + end: usize, + eff_end: usize, + e_bands: &[f32], + old_e_bands: &mut [f32], + budget: u32, + error: &mut [f32], + enc: &mut RangeEncoder, + c: usize, + lm: usize, + nb_available_bytes: i32, + force_intra: bool, + delayed_intra: &mut f32, + two_pass: bool, + loss_rate: i32, + lfe: bool, +) { + let n = c * NB_BANDS; + let mut two_pass = two_pass; + let mut intra = force_intra + || (!two_pass + && *delayed_intra > (2 * c * (end - start)) as f32 + && nb_available_bytes > ((end - start) * c) as i32); + let intra_bias = + ((budget as f32 * *delayed_intra * loss_rate as f32) / (c * 512) as f32) as i32; + let new_distortion = loss_distortion(e_bands, old_e_bands, start, eff_end, c); + + let tell = enc.tell(); + if tell + 3 > budget { + two_pass = false; + intra = false; + } + + let mut max_decay = 16f32; + if end - start > 10 { + let v = 0.125f32 * nb_available_bytes as f32; + max_decay = if max_decay < v { max_decay } else { v }; + } + if lfe { + max_decay = 3.0; + } + + let start_state = enc.snapshot(); + let nstart = enc.front_offs(); + let mut old_intra = [0f32; 2 * NB_BANDS]; + let mut err_intra = [0f32; 2 * NB_BANDS]; + old_intra[..n].copy_from_slice(&old_e_bands[..n]); + + let mut badness1 = 0; + if two_pass || intra { + badness1 = quant_coarse_energy_impl( + start, + end, + e_bands, + &mut old_intra, + budget as i32, + tell as i32, + &E_PROB_MODEL[lm][1], + &mut err_intra, + enc, + c, + lm, + true, + max_decay, + lfe, + ); + } + + if !intra { + let tell_intra = enc.tell_frac() as i32; + let intra_state = enc.snapshot(); + let nintra = enc.front_offs(); + let intra_len = nintra - nstart; + let mut intra_bits = [0u8; MAX_FRAME_BYTES]; + intra_bits[..intra_len].copy_from_slice(&enc.front()[nstart..nintra]); + + enc.restore(&start_state); + let badness2 = quant_coarse_energy_impl( + start, + end, + e_bands, + old_e_bands, + budget as i32, + tell as i32, + &E_PROB_MODEL[lm][0], + error, + enc, + c, + lm, + false, + max_decay, + lfe, + ); + + if two_pass + && (badness1 < badness2 + || (badness1 == badness2 && enc.tell_frac() as i32 + intra_bias > tell_intra)) + { + enc.restore(&intra_state); + enc.front_write(nstart, &intra_bits[..intra_len]); + old_e_bands[..n].copy_from_slice(&old_intra[..n]); + error[..n].copy_from_slice(&err_intra[..n]); + intra = true; + } + } else { + old_e_bands[..n].copy_from_slice(&old_intra[..n]); + error[..n].copy_from_slice(&err_intra[..n]); + } + + if intra { + *delayed_intra = new_distortion; + } else { + *delayed_intra = PRED_COEF[lm] * PRED_COEF[lm] * *delayed_intra + new_distortion; + } +} + +/// `quant_fine_energy` as celt_encode_with_ec calls it without QEXT (`prev_quant` NULL). +pub(crate) fn quant_fine_energy( + start: usize, + end: usize, + old_e_bands: &mut [f32], + error: &mut [f32], + fine_quant: &[i32], + enc: &mut RangeEncoder, + c: usize, +) { + for i in start..end { + let fq = fine_quant[i]; + if fq <= 0 { + continue; + } + if enc.tell() as i32 + c as i32 * fq > enc.storage() as i32 * 8 { + continue; + } + let extra = 1i32 << fq; + for ch in 0..c { + let idx = i + ch * NB_BANDS; + let q2 = (((error[idx] + 0.5f32) * extra as f32) as f64).floor() as i32; + let q2 = q2.min(extra - 1).max(0); + enc.enc_bits(q2 as u32, fq as u32); + let offset = (q2 as f32 + 0.5) * (1 << (14 - fq)) as f32 * (1.0f32 / 16384.0) - 0.5; + old_e_bands[idx] += offset; + error[idx] -= offset; + } + } +} + +/// `quant_energy_finalise`. +pub(crate) fn quant_energy_finalise( + start: usize, + end: usize, + old_e_bands: &mut [f32], + error: &mut [f32], + fine_quant: &[i32], + fine_priority: &[i32], + bits_left: i32, + enc: &mut RangeEncoder, + c: usize, +) { + let mut bits_left = bits_left; + for prio in 0..2 { + for i in start..end { + if bits_left < c as i32 { + break; + } + if fine_quant[i] >= MAX_FINE_BITS || fine_priority[i] != prio { + continue; + } + for ch in 0..c { + let idx = i + ch * NB_BANDS; + let q2: u32 = if error[idx] < 0.0 { 0 } else { 1 }; + enc.enc_bits(q2, 1); + let offset = + (q2 as f32 - 0.5) * (1 << (14 - fine_quant[i] - 1)) as f32 * (1.0f32 / 16384.0); + old_e_bands[idx] += offset; + error[idx] -= offset; + bits_left -= 1; + } + } + } +} + +/// `amp2Log2`; `band_e`/`band_log_e` are `c * 21`. +pub(crate) fn amp2log2( + eff_end: usize, + end: usize, + band_e: &[f32], + band_log_e: &mut [f32], + c: usize, +) { + for ch in 0..c { + for i in 0..eff_end { + band_log_e[i + ch * NB_BANDS] = celt_log2(band_e[i + ch * NB_BANDS]) - E_MEANS[i]; + } + for i in eff_end..end { + band_log_e[ch * NB_BANDS + i] = -14.0; + } + } +} diff --git a/crates/ec-opus/src/celt_flp/tables.rs b/crates/ec-opus/src/celt_flp/tables.rs new file mode 100644 index 00000000..e1a9c67e --- /dev/null +++ b/crates/ec-opus/src/celt_flp/tables.rs @@ -0,0 +1,2501 @@ +/// One `kiss_fft_state` of the static 48 kHz mode (nfft 480, 240, 120, 60). +pub(crate) struct FftState { + pub(crate) scale: f32, + pub(crate) shift: i32, + pub(crate) factors: [i16; 16], + pub(crate) bitrev: &'static [i16], +} + +/// `window120`. +pub(crate) static WINDOW120: [f32; 120] = [ + 6.7286966e-05, + 0.00060551348, + 0.0016815970, + 0.0032947962, + 0.0054439943, + 0.0081276923, + 0.011344001, + 0.015090633, + 0.019364886, + 0.024163635, + 0.029483315, + 0.035319905, + 0.041668911, + 0.048525347, + 0.055883718, + 0.063737999, + 0.072081616, + 0.080907428, + 0.090207705, + 0.099974111, + 0.11019769, + 0.12086883, + 0.13197729, + 0.14351214, + 0.15546177, + 0.16781389, + 0.18055550, + 0.19367290, + 0.20715171, + 0.22097682, + 0.23513243, + 0.24960208, + 0.26436860, + 0.27941419, + 0.29472040, + 0.31026818, + 0.32603788, + 0.34200931, + 0.35816177, + 0.37447407, + 0.39092462, + 0.40749142, + 0.42415215, + 0.44088423, + 0.45766484, + 0.47447104, + 0.49127978, + 0.50806798, + 0.52481261, + 0.54149077, + 0.55807973, + 0.57455701, + 0.59090049, + 0.60708841, + 0.62309951, + 0.63891306, + 0.65450896, + 0.66986776, + 0.68497077, + 0.69980010, + 0.71433873, + 0.72857055, + 0.74248043, + 0.75605425, + 0.76927895, + 0.78214257, + 0.79463430, + 0.80674445, + 0.81846456, + 0.82978733, + 0.84070669, + 0.85121779, + 0.86131698, + 0.87100183, + 0.88027111, + 0.88912479, + 0.89756398, + 0.90559094, + 0.91320904, + 0.92042270, + 0.92723738, + 0.93365955, + 0.93969656, + 0.94535671, + 0.95064907, + 0.95558353, + 0.96017067, + 0.96442171, + 0.96834849, + 0.97196334, + 0.97527906, + 0.97830883, + 0.98106616, + 0.98356480, + 0.98581869, + 0.98784191, + 0.98964856, + 0.99125274, + 0.99266849, + 0.99390969, + 0.99499004, + 0.99592297, + 0.99672162, + 0.99739874, + 0.99796667, + 0.99843728, + 0.99882195, + 0.99913147, + 0.99937606, + 0.99956527, + 0.99970802, + 0.99981248, + 0.99988613, + 0.99993565, + 0.99996697, + 0.99998518, + 0.99999457, + 0.99999859, + 0.99999982, + 1.0000000, +]; +/// `fft_twiddles48000_960`. +pub(crate) static FFT_TWIDDLES: [[f32; 2]; 480] = [ + [1.0000000, -0.0000000], + [0.99991433, -0.013089596], + [0.99965732, -0.026176948], + [0.99922904, -0.039259816], + [0.99862953, -0.052335956], + [0.99785892, -0.065403129], + [0.99691733, -0.078459096], + [0.99580493, -0.091501619], + [0.99452190, -0.10452846], + [0.99306846, -0.11753740], + [0.99144486, -0.13052619], + [0.98965139, -0.14349262], + [0.98768834, -0.15643447], + [0.98555606, -0.16934950], + [0.98325491, -0.18223553], + [0.98078528, -0.19509032], + [0.97814760, -0.20791169], + [0.97534232, -0.22069744], + [0.97236992, -0.23344536], + [0.96923091, -0.24615329], + [0.96592583, -0.25881905], + [0.96245524, -0.27144045], + [0.95881973, -0.28401534], + [0.95501994, -0.29654157], + [0.95105652, -0.30901699], + [0.94693013, -0.32143947], + [0.94264149, -0.33380686], + [0.93819134, -0.34611706], + [0.93358043, -0.35836795], + [0.92880955, -0.37055744], + [0.92387953, -0.38268343], + [0.91879121, -0.39474386], + [0.91354546, -0.40673664], + [0.90814317, -0.41865974], + [0.90258528, -0.43051110], + [0.89687274, -0.44228869], + [0.89100652, -0.45399050], + [0.88498764, -0.46561452], + [0.87881711, -0.47715876], + [0.87249601, -0.48862124], + [0.86602540, -0.50000000], + [0.85940641, -0.51129309], + [0.85264016, -0.52249856], + [0.84572782, -0.53361452], + [0.83867057, -0.54463904], + [0.83146961, -0.55557023], + [0.82412619, -0.56640624], + [0.81664156, -0.57714519], + [0.80901699, -0.58778525], + [0.80125381, -0.59832460], + [0.79335334, -0.60876143], + [0.78531693, -0.61909395], + [0.77714596, -0.62932039], + [0.76884183, -0.63943900], + [0.76040597, -0.64944805], + [0.75183981, -0.65934582], + [0.74314483, -0.66913061], + [0.73432251, -0.67880075], + [0.72537437, -0.68835458], + [0.71630194, -0.69779046], + [0.70710678, -0.70710678], + [0.69779046, -0.71630194], + [0.68835458, -0.72537437], + [0.67880075, -0.73432251], + [0.66913061, -0.74314483], + [0.65934582, -0.75183981], + [0.64944805, -0.76040597], + [0.63943900, -0.76884183], + [0.62932039, -0.77714596], + [0.61909395, -0.78531693], + [0.60876143, -0.79335334], + [0.59832460, -0.80125381], + [0.58778525, -0.80901699], + [0.57714519, -0.81664156], + [0.56640624, -0.82412619], + [0.55557023, -0.83146961], + [0.54463904, -0.83867057], + [0.53361452, -0.84572782], + [0.52249856, -0.85264016], + [0.51129309, -0.85940641], + [0.50000000, -0.86602540], + [0.48862124, -0.87249601], + [0.47715876, -0.87881711], + [0.46561452, -0.88498764], + [0.45399050, -0.89100652], + [0.44228869, -0.89687274], + [0.43051110, -0.90258528], + [0.41865974, -0.90814317], + [0.40673664, -0.91354546], + [0.39474386, -0.91879121], + [0.38268343, -0.92387953], + [0.37055744, -0.92880955], + [0.35836795, -0.93358043], + [0.34611706, -0.93819134], + [0.33380686, -0.94264149], + [0.32143947, -0.94693013], + [0.30901699, -0.95105652], + [0.29654157, -0.95501994], + [0.28401534, -0.95881973], + [0.27144045, -0.96245524], + [0.25881905, -0.96592583], + [0.24615329, -0.96923091], + [0.23344536, -0.97236992], + [0.22069744, -0.97534232], + [0.20791169, -0.97814760], + [0.19509032, -0.98078528], + [0.18223553, -0.98325491], + [0.16934950, -0.98555606], + [0.15643447, -0.98768834], + [0.14349262, -0.98965139], + [0.13052619, -0.99144486], + [0.11753740, -0.99306846], + [0.10452846, -0.99452190], + [0.091501619, -0.99580493], + [0.078459096, -0.99691733], + [0.065403129, -0.99785892], + [0.052335956, -0.99862953], + [0.039259816, -0.99922904], + [0.026176948, -0.99965732], + [0.013089596, -0.99991433], + [6.1232340e-17, -1.0000000], + [-0.013089596, -0.99991433], + [-0.026176948, -0.99965732], + [-0.039259816, -0.99922904], + [-0.052335956, -0.99862953], + [-0.065403129, -0.99785892], + [-0.078459096, -0.99691733], + [-0.091501619, -0.99580493], + [-0.10452846, -0.99452190], + [-0.11753740, -0.99306846], + [-0.13052619, -0.99144486], + [-0.14349262, -0.98965139], + [-0.15643447, -0.98768834], + [-0.16934950, -0.98555606], + [-0.18223553, -0.98325491], + [-0.19509032, -0.98078528], + [-0.20791169, -0.97814760], + [-0.22069744, -0.97534232], + [-0.23344536, -0.97236992], + [-0.24615329, -0.96923091], + [-0.25881905, -0.96592583], + [-0.27144045, -0.96245524], + [-0.28401534, -0.95881973], + [-0.29654157, -0.95501994], + [-0.30901699, -0.95105652], + [-0.32143947, -0.94693013], + [-0.33380686, -0.94264149], + [-0.34611706, -0.93819134], + [-0.35836795, -0.93358043], + [-0.37055744, -0.92880955], + [-0.38268343, -0.92387953], + [-0.39474386, -0.91879121], + [-0.40673664, -0.91354546], + [-0.41865974, -0.90814317], + [-0.43051110, -0.90258528], + [-0.44228869, -0.89687274], + [-0.45399050, -0.89100652], + [-0.46561452, -0.88498764], + [-0.47715876, -0.87881711], + [-0.48862124, -0.87249601], + [-0.50000000, -0.86602540], + [-0.51129309, -0.85940641], + [-0.52249856, -0.85264016], + [-0.53361452, -0.84572782], + [-0.54463904, -0.83867057], + [-0.55557023, -0.83146961], + [-0.56640624, -0.82412619], + [-0.57714519, -0.81664156], + [-0.58778525, -0.80901699], + [-0.59832460, -0.80125381], + [-0.60876143, -0.79335334], + [-0.61909395, -0.78531693], + [-0.62932039, -0.77714596], + [-0.63943900, -0.76884183], + [-0.64944805, -0.76040597], + [-0.65934582, -0.75183981], + [-0.66913061, -0.74314483], + [-0.67880075, -0.73432251], + [-0.68835458, -0.72537437], + [-0.69779046, -0.71630194], + [-0.70710678, -0.70710678], + [-0.71630194, -0.69779046], + [-0.72537437, -0.68835458], + [-0.73432251, -0.67880075], + [-0.74314483, -0.66913061], + [-0.75183981, -0.65934582], + [-0.76040597, -0.64944805], + [-0.76884183, -0.63943900], + [-0.77714596, -0.62932039], + [-0.78531693, -0.61909395], + [-0.79335334, -0.60876143], + [-0.80125381, -0.59832460], + [-0.80901699, -0.58778525], + [-0.81664156, -0.57714519], + [-0.82412619, -0.56640624], + [-0.83146961, -0.55557023], + [-0.83867057, -0.54463904], + [-0.84572782, -0.53361452], + [-0.85264016, -0.52249856], + [-0.85940641, -0.51129309], + [-0.86602540, -0.50000000], + [-0.87249601, -0.48862124], + [-0.87881711, -0.47715876], + [-0.88498764, -0.46561452], + [-0.89100652, -0.45399050], + [-0.89687274, -0.44228869], + [-0.90258528, -0.43051110], + [-0.90814317, -0.41865974], + [-0.91354546, -0.40673664], + [-0.91879121, -0.39474386], + [-0.92387953, -0.38268343], + [-0.92880955, -0.37055744], + [-0.93358043, -0.35836795], + [-0.93819134, -0.34611706], + [-0.94264149, -0.33380686], + [-0.94693013, -0.32143947], + [-0.95105652, -0.30901699], + [-0.95501994, -0.29654157], + [-0.95881973, -0.28401534], + [-0.96245524, -0.27144045], + [-0.96592583, -0.25881905], + [-0.96923091, -0.24615329], + [-0.97236992, -0.23344536], + [-0.97534232, -0.22069744], + [-0.97814760, -0.20791169], + [-0.98078528, -0.19509032], + [-0.98325491, -0.18223553], + [-0.98555606, -0.16934950], + [-0.98768834, -0.15643447], + [-0.98965139, -0.14349262], + [-0.99144486, -0.13052619], + [-0.99306846, -0.11753740], + [-0.99452190, -0.10452846], + [-0.99580493, -0.091501619], + [-0.99691733, -0.078459096], + [-0.99785892, -0.065403129], + [-0.99862953, -0.052335956], + [-0.99922904, -0.039259816], + [-0.99965732, -0.026176948], + [-0.99991433, -0.013089596], + [-1.0000000, -1.2246468e-16], + [-0.99991433, 0.013089596], + [-0.99965732, 0.026176948], + [-0.99922904, 0.039259816], + [-0.99862953, 0.052335956], + [-0.99785892, 0.065403129], + [-0.99691733, 0.078459096], + [-0.99580493, 0.091501619], + [-0.99452190, 0.10452846], + [-0.99306846, 0.11753740], + [-0.99144486, 0.13052619], + [-0.98965139, 0.14349262], + [-0.98768834, 0.15643447], + [-0.98555606, 0.16934950], + [-0.98325491, 0.18223553], + [-0.98078528, 0.19509032], + [-0.97814760, 0.20791169], + [-0.97534232, 0.22069744], + [-0.97236992, 0.23344536], + [-0.96923091, 0.24615329], + [-0.96592583, 0.25881905], + [-0.96245524, 0.27144045], + [-0.95881973, 0.28401534], + [-0.95501994, 0.29654157], + [-0.95105652, 0.30901699], + [-0.94693013, 0.32143947], + [-0.94264149, 0.33380686], + [-0.93819134, 0.34611706], + [-0.93358043, 0.35836795], + [-0.92880955, 0.37055744], + [-0.92387953, 0.38268343], + [-0.91879121, 0.39474386], + [-0.91354546, 0.40673664], + [-0.90814317, 0.41865974], + [-0.90258528, 0.43051110], + [-0.89687274, 0.44228869], + [-0.89100652, 0.45399050], + [-0.88498764, 0.46561452], + [-0.87881711, 0.47715876], + [-0.87249601, 0.48862124], + [-0.86602540, 0.50000000], + [-0.85940641, 0.51129309], + [-0.85264016, 0.52249856], + [-0.84572782, 0.53361452], + [-0.83867057, 0.54463904], + [-0.83146961, 0.55557023], + [-0.82412619, 0.56640624], + [-0.81664156, 0.57714519], + [-0.80901699, 0.58778525], + [-0.80125381, 0.59832460], + [-0.79335334, 0.60876143], + [-0.78531693, 0.61909395], + [-0.77714596, 0.62932039], + [-0.76884183, 0.63943900], + [-0.76040597, 0.64944805], + [-0.75183981, 0.65934582], + [-0.74314483, 0.66913061], + [-0.73432251, 0.67880075], + [-0.72537437, 0.68835458], + [-0.71630194, 0.69779046], + [-0.70710678, 0.70710678], + [-0.69779046, 0.71630194], + [-0.68835458, 0.72537437], + [-0.67880075, 0.73432251], + [-0.66913061, 0.74314483], + [-0.65934582, 0.75183981], + [-0.64944805, 0.76040597], + [-0.63943900, 0.76884183], + [-0.62932039, 0.77714596], + [-0.61909395, 0.78531693], + [-0.60876143, 0.79335334], + [-0.59832460, 0.80125381], + [-0.58778525, 0.80901699], + [-0.57714519, 0.81664156], + [-0.56640624, 0.82412619], + [-0.55557023, 0.83146961], + [-0.54463904, 0.83867057], + [-0.53361452, 0.84572782], + [-0.52249856, 0.85264016], + [-0.51129309, 0.85940641], + [-0.50000000, 0.86602540], + [-0.48862124, 0.87249601], + [-0.47715876, 0.87881711], + [-0.46561452, 0.88498764], + [-0.45399050, 0.89100652], + [-0.44228869, 0.89687274], + [-0.43051110, 0.90258528], + [-0.41865974, 0.90814317], + [-0.40673664, 0.91354546], + [-0.39474386, 0.91879121], + [-0.38268343, 0.92387953], + [-0.37055744, 0.92880955], + [-0.35836795, 0.93358043], + [-0.34611706, 0.93819134], + [-0.33380686, 0.94264149], + [-0.32143947, 0.94693013], + [-0.30901699, 0.95105652], + [-0.29654157, 0.95501994], + [-0.28401534, 0.95881973], + [-0.27144045, 0.96245524], + [-0.25881905, 0.96592583], + [-0.24615329, 0.96923091], + [-0.23344536, 0.97236992], + [-0.22069744, 0.97534232], + [-0.20791169, 0.97814760], + [-0.19509032, 0.98078528], + [-0.18223553, 0.98325491], + [-0.16934950, 0.98555606], + [-0.15643447, 0.98768834], + [-0.14349262, 0.98965139], + [-0.13052619, 0.99144486], + [-0.11753740, 0.99306846], + [-0.10452846, 0.99452190], + [-0.091501619, 0.99580493], + [-0.078459096, 0.99691733], + [-0.065403129, 0.99785892], + [-0.052335956, 0.99862953], + [-0.039259816, 0.99922904], + [-0.026176948, 0.99965732], + [-0.013089596, 0.99991433], + [-1.8369702e-16, 1.0000000], + [0.013089596, 0.99991433], + [0.026176948, 0.99965732], + [0.039259816, 0.99922904], + [0.052335956, 0.99862953], + [0.065403129, 0.99785892], + [0.078459096, 0.99691733], + [0.091501619, 0.99580493], + [0.10452846, 0.99452190], + [0.11753740, 0.99306846], + [0.13052619, 0.99144486], + [0.14349262, 0.98965139], + [0.15643447, 0.98768834], + [0.16934950, 0.98555606], + [0.18223553, 0.98325491], + [0.19509032, 0.98078528], + [0.20791169, 0.97814760], + [0.22069744, 0.97534232], + [0.23344536, 0.97236992], + [0.24615329, 0.96923091], + [0.25881905, 0.96592583], + [0.27144045, 0.96245524], + [0.28401534, 0.95881973], + [0.29654157, 0.95501994], + [0.30901699, 0.95105652], + [0.32143947, 0.94693013], + [0.33380686, 0.94264149], + [0.34611706, 0.93819134], + [0.35836795, 0.93358043], + [0.37055744, 0.92880955], + [0.38268343, 0.92387953], + [0.39474386, 0.91879121], + [0.40673664, 0.91354546], + [0.41865974, 0.90814317], + [0.43051110, 0.90258528], + [0.44228869, 0.89687274], + [0.45399050, 0.89100652], + [0.46561452, 0.88498764], + [0.47715876, 0.87881711], + [0.48862124, 0.87249601], + [0.50000000, 0.86602540], + [0.51129309, 0.85940641], + [0.52249856, 0.85264016], + [0.53361452, 0.84572782], + [0.54463904, 0.83867057], + [0.55557023, 0.83146961], + [0.56640624, 0.82412619], + [0.57714519, 0.81664156], + [0.58778525, 0.80901699], + [0.59832460, 0.80125381], + [0.60876143, 0.79335334], + [0.61909395, 0.78531693], + [0.62932039, 0.77714596], + [0.63943900, 0.76884183], + [0.64944805, 0.76040597], + [0.65934582, 0.75183981], + [0.66913061, 0.74314483], + [0.67880075, 0.73432251], + [0.68835458, 0.72537437], + [0.69779046, 0.71630194], + [0.70710678, 0.70710678], + [0.71630194, 0.69779046], + [0.72537437, 0.68835458], + [0.73432251, 0.67880075], + [0.74314483, 0.66913061], + [0.75183981, 0.65934582], + [0.76040597, 0.64944805], + [0.76884183, 0.63943900], + [0.77714596, 0.62932039], + [0.78531693, 0.61909395], + [0.79335334, 0.60876143], + [0.80125381, 0.59832460], + [0.80901699, 0.58778525], + [0.81664156, 0.57714519], + [0.82412619, 0.56640624], + [0.83146961, 0.55557023], + [0.83867057, 0.54463904], + [0.84572782, 0.53361452], + [0.85264016, 0.52249856], + [0.85940641, 0.51129309], + [0.86602540, 0.50000000], + [0.87249601, 0.48862124], + [0.87881711, 0.47715876], + [0.88498764, 0.46561452], + [0.89100652, 0.45399050], + [0.89687274, 0.44228869], + [0.90258528, 0.43051110], + [0.90814317, 0.41865974], + [0.91354546, 0.40673664], + [0.91879121, 0.39474386], + [0.92387953, 0.38268343], + [0.92880955, 0.37055744], + [0.93358043, 0.35836795], + [0.93819134, 0.34611706], + [0.94264149, 0.33380686], + [0.94693013, 0.32143947], + [0.95105652, 0.30901699], + [0.95501994, 0.29654157], + [0.95881973, 0.28401534], + [0.96245524, 0.27144045], + [0.96592583, 0.25881905], + [0.96923091, 0.24615329], + [0.97236992, 0.23344536], + [0.97534232, 0.22069744], + [0.97814760, 0.20791169], + [0.98078528, 0.19509032], + [0.98325491, 0.18223553], + [0.98555606, 0.16934950], + [0.98768834, 0.15643447], + [0.98965139, 0.14349262], + [0.99144486, 0.13052619], + [0.99306846, 0.11753740], + [0.99452190, 0.10452846], + [0.99580493, 0.091501619], + [0.99691733, 0.078459096], + [0.99785892, 0.065403129], + [0.99862953, 0.052335956], + [0.99922904, 0.039259816], + [0.99965732, 0.026176948], + [0.99991433, 0.013089596], +]; +/// `fft_bitrev480`. +pub(crate) static FFT_BITREV480: [i16; 480] = [ + 0, 96, 192, 288, 384, 32, 128, 224, 320, 416, 64, 160, 256, 352, 448, 8, 104, 200, 296, 392, + 40, 136, 232, 328, 424, 72, 168, 264, 360, 456, 16, 112, 208, 304, 400, 48, 144, 240, 336, 432, + 80, 176, 272, 368, 464, 24, 120, 216, 312, 408, 56, 152, 248, 344, 440, 88, 184, 280, 376, 472, + 4, 100, 196, 292, 388, 36, 132, 228, 324, 420, 68, 164, 260, 356, 452, 12, 108, 204, 300, 396, + 44, 140, 236, 332, 428, 76, 172, 268, 364, 460, 20, 116, 212, 308, 404, 52, 148, 244, 340, 436, + 84, 180, 276, 372, 468, 28, 124, 220, 316, 412, 60, 156, 252, 348, 444, 92, 188, 284, 380, 476, + 1, 97, 193, 289, 385, 33, 129, 225, 321, 417, 65, 161, 257, 353, 449, 9, 105, 201, 297, 393, + 41, 137, 233, 329, 425, 73, 169, 265, 361, 457, 17, 113, 209, 305, 401, 49, 145, 241, 337, 433, + 81, 177, 273, 369, 465, 25, 121, 217, 313, 409, 57, 153, 249, 345, 441, 89, 185, 281, 377, 473, + 5, 101, 197, 293, 389, 37, 133, 229, 325, 421, 69, 165, 261, 357, 453, 13, 109, 205, 301, 397, + 45, 141, 237, 333, 429, 77, 173, 269, 365, 461, 21, 117, 213, 309, 405, 53, 149, 245, 341, 437, + 85, 181, 277, 373, 469, 29, 125, 221, 317, 413, 61, 157, 253, 349, 445, 93, 189, 285, 381, 477, + 2, 98, 194, 290, 386, 34, 130, 226, 322, 418, 66, 162, 258, 354, 450, 10, 106, 202, 298, 394, + 42, 138, 234, 330, 426, 74, 170, 266, 362, 458, 18, 114, 210, 306, 402, 50, 146, 242, 338, 434, + 82, 178, 274, 370, 466, 26, 122, 218, 314, 410, 58, 154, 250, 346, 442, 90, 186, 282, 378, 474, + 6, 102, 198, 294, 390, 38, 134, 230, 326, 422, 70, 166, 262, 358, 454, 14, 110, 206, 302, 398, + 46, 142, 238, 334, 430, 78, 174, 270, 366, 462, 22, 118, 214, 310, 406, 54, 150, 246, 342, 438, + 86, 182, 278, 374, 470, 30, 126, 222, 318, 414, 62, 158, 254, 350, 446, 94, 190, 286, 382, 478, + 3, 99, 195, 291, 387, 35, 131, 227, 323, 419, 67, 163, 259, 355, 451, 11, 107, 203, 299, 395, + 43, 139, 235, 331, 427, 75, 171, 267, 363, 459, 19, 115, 211, 307, 403, 51, 147, 243, 339, 435, + 83, 179, 275, 371, 467, 27, 123, 219, 315, 411, 59, 155, 251, 347, 443, 91, 187, 283, 379, 475, + 7, 103, 199, 295, 391, 39, 135, 231, 327, 423, 71, 167, 263, 359, 455, 15, 111, 207, 303, 399, + 47, 143, 239, 335, 431, 79, 175, 271, 367, 463, 23, 119, 215, 311, 407, 55, 151, 247, 343, 439, + 87, 183, 279, 375, 471, 31, 127, 223, 319, 415, 63, 159, 255, 351, 447, 95, 191, 287, 383, 479, +]; +/// `fft_bitrev240`. +pub(crate) static FFT_BITREV240: [i16; 240] = [ + 0, 48, 96, 144, 192, 16, 64, 112, 160, 208, 32, 80, 128, 176, 224, 4, 52, 100, 148, 196, 20, + 68, 116, 164, 212, 36, 84, 132, 180, 228, 8, 56, 104, 152, 200, 24, 72, 120, 168, 216, 40, 88, + 136, 184, 232, 12, 60, 108, 156, 204, 28, 76, 124, 172, 220, 44, 92, 140, 188, 236, 1, 49, 97, + 145, 193, 17, 65, 113, 161, 209, 33, 81, 129, 177, 225, 5, 53, 101, 149, 197, 21, 69, 117, 165, + 213, 37, 85, 133, 181, 229, 9, 57, 105, 153, 201, 25, 73, 121, 169, 217, 41, 89, 137, 185, 233, + 13, 61, 109, 157, 205, 29, 77, 125, 173, 221, 45, 93, 141, 189, 237, 2, 50, 98, 146, 194, 18, + 66, 114, 162, 210, 34, 82, 130, 178, 226, 6, 54, 102, 150, 198, 22, 70, 118, 166, 214, 38, 86, + 134, 182, 230, 10, 58, 106, 154, 202, 26, 74, 122, 170, 218, 42, 90, 138, 186, 234, 14, 62, + 110, 158, 206, 30, 78, 126, 174, 222, 46, 94, 142, 190, 238, 3, 51, 99, 147, 195, 19, 67, 115, + 163, 211, 35, 83, 131, 179, 227, 7, 55, 103, 151, 199, 23, 71, 119, 167, 215, 39, 87, 135, 183, + 231, 11, 59, 107, 155, 203, 27, 75, 123, 171, 219, 43, 91, 139, 187, 235, 15, 63, 111, 159, + 207, 31, 79, 127, 175, 223, 47, 95, 143, 191, 239, +]; +/// `fft_bitrev120`. +pub(crate) static FFT_BITREV120: [i16; 120] = [ + 0, 24, 48, 72, 96, 8, 32, 56, 80, 104, 16, 40, 64, 88, 112, 4, 28, 52, 76, 100, 12, 36, 60, 84, + 108, 20, 44, 68, 92, 116, 1, 25, 49, 73, 97, 9, 33, 57, 81, 105, 17, 41, 65, 89, 113, 5, 29, + 53, 77, 101, 13, 37, 61, 85, 109, 21, 45, 69, 93, 117, 2, 26, 50, 74, 98, 10, 34, 58, 82, 106, + 18, 42, 66, 90, 114, 6, 30, 54, 78, 102, 14, 38, 62, 86, 110, 22, 46, 70, 94, 118, 3, 27, 51, + 75, 99, 11, 35, 59, 83, 107, 19, 43, 67, 91, 115, 7, 31, 55, 79, 103, 15, 39, 63, 87, 111, 23, + 47, 71, 95, 119, +]; +/// `fft_bitrev60`. +pub(crate) static FFT_BITREV60: [i16; 60] = [ + 0, 12, 24, 36, 48, 4, 16, 28, 40, 52, 8, 20, 32, 44, 56, 1, 13, 25, 37, 49, 5, 17, 29, 41, 53, + 9, 21, 33, 45, 57, 2, 14, 26, 38, 50, 6, 18, 30, 42, 54, 10, 22, 34, 46, 58, 3, 15, 27, 39, 51, + 7, 19, 31, 43, 55, 11, 23, 35, 47, 59, +]; +/// `fft_state48000_960_0..3`, indexed by mdct shift. +pub(crate) static FFT_STATES: [FftState; 4] = [ + FftState { + scale: 0.0020833334, + shift: -1, + factors: [5, 96, 3, 32, 4, 8, 2, 4, 4, 1, 0, 0, 0, 0, 0, 0], + bitrev: &FFT_BITREV480, + }, + FftState { + scale: 0.0041666669, + shift: 1, + factors: [5, 48, 3, 16, 4, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0], + bitrev: &FFT_BITREV240, + }, + FftState { + scale: 0.0083333338, + shift: 2, + factors: [5, 24, 3, 8, 2, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0], + bitrev: &FFT_BITREV120, + }, + FftState { + scale: 0.016666668, + shift: 3, + factors: [5, 12, 3, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + bitrev: &FFT_BITREV60, + }, +]; +/// `mdct_twiddles960`. +pub(crate) static MDCT_TWIDDLES: [f32; 1800] = [ + -0.00040906153, + 0.99999992, + -0.0036815456, + 0.99999322, + -0.0069539902, + 0.99997582, + -0.010226360, + 0.99994771, + -0.013498621, + 0.99990889, + -0.016770737, + 0.99985936, + -0.020042673, + 0.99979913, + -0.023314395, + 0.99972818, + -0.026585867, + 0.99964653, + -0.029857055, + 0.99955418, + -0.033127923, + 0.99945112, + -0.036398436, + 0.99933736, + -0.039668559, + 0.99921289, + -0.042938257, + 0.99907773, + -0.046207495, + 0.99893186, + -0.049476239, + 0.99877530, + -0.052744453, + 0.99860804, + -0.056012102, + 0.99843009, + -0.059279151, + 0.99824144, + -0.062545565, + 0.99804211, + -0.065811309, + 0.99783209, + -0.069076349, + 0.99761138, + -0.072340649, + 0.99737998, + -0.075604174, + 0.99713791, + -0.078866890, + 0.99688516, + -0.082128761, + 0.99662173, + -0.085389752, + 0.99634763, + -0.088649829, + 0.99606285, + -0.091908956, + 0.99576741, + -0.095167100, + 0.99546131, + -0.098424224, + 0.99514455, + -0.10168029, + 0.99481713, + -0.10493528, + 0.99447905, + -0.10818913, + 0.99413033, + -0.11144183, + 0.99377096, + -0.11469334, + 0.99340095, + -0.11794361, + 0.99302029, + -0.12119263, + 0.99262901, + -0.12444034, + 0.99222709, + -0.12768673, + 0.99181455, + -0.13093174, + 0.99139139, + -0.13417536, + 0.99095760, + -0.13741753, + 0.99051321, + -0.14065824, + 0.99005821, + -0.14389744, + 0.98959261, + -0.14713510, + 0.98911641, + -0.15037118, + 0.98862961, + -0.15360565, + 0.98813223, + -0.15683848, + 0.98762427, + -0.16006962, + 0.98710573, + -0.16329906, + 0.98657662, + -0.16652674, + 0.98603694, + -0.16975264, + 0.98548670, + -0.17297673, + 0.98492591, + -0.17619896, + 0.98435457, + -0.17941930, + 0.98377269, + -0.18263772, + 0.98318028, + -0.18585419, + 0.98257734, + -0.18906866, + 0.98196387, + -0.19228112, + 0.98133989, + -0.19549151, + 0.98070539, + -0.19869981, + 0.98006040, + -0.20190598, + 0.97940491, + -0.20510998, + 0.97873893, + -0.20831180, + 0.97806247, + -0.21151138, + 0.97737554, + -0.21470869, + 0.97667813, + -0.21790371, + 0.97597027, + -0.22109639, + 0.97525196, + -0.22428671, + 0.97452320, + -0.22747462, + 0.97378401, + -0.23066010, + 0.97303439, + -0.23384310, + 0.97227435, + -0.23702361, + 0.97150389, + -0.24020157, + 0.97072303, + -0.24337696, + 0.96993178, + -0.24654975, + 0.96913014, + -0.24971989, + 0.96831812, + -0.25288736, + 0.96749573, + -0.25605213, + 0.96666298, + -0.25921415, + 0.96581987, + -0.26237339, + 0.96496643, + -0.26552983, + 0.96410265, + -0.26868342, + 0.96322854, + -0.27183413, + 0.96234412, + -0.27498193, + 0.96144939, + -0.27812679, + 0.96054437, + -0.28126867, + 0.95962906, + -0.28440754, + 0.95870347, + -0.28754336, + 0.95776762, + -0.29067610, + 0.95682151, + -0.29380573, + 0.95586515, + -0.29693221, + 0.95489856, + -0.30005551, + 0.95392174, + -0.30317560, + 0.95293471, + -0.30629245, + 0.95193746, + -0.30940601, + 0.95093003, + -0.31251626, + 0.94991241, + -0.31562316, + 0.94888462, + -0.31872668, + 0.94784667, + -0.32182679, + 0.94679856, + -0.32492345, + 0.94574032, + -0.32801664, + 0.94467195, + -0.33110631, + 0.94359346, + -0.33419243, + 0.94250486, + -0.33727497, + 0.94140618, + -0.34035391, + 0.94029741, + -0.34342920, + 0.93917857, + -0.34650081, + 0.93804967, + -0.34956871, + 0.93691073, + -0.35263286, + 0.93576176, + -0.35569324, + 0.93460276, + -0.35874981, + 0.93343375, + -0.36180254, + 0.93225475, + -0.36485139, + 0.93106577, + -0.36789634, + 0.92986681, + -0.37093735, + 0.92865789, + -0.37397438, + 0.92743903, + -0.37700741, + 0.92621024, + -0.38003640, + 0.92497153, + -0.38306132, + 0.92372291, + -0.38608214, + 0.92246440, + -0.38909883, + 0.92119602, + -0.39211135, + 0.91991776, + -0.39511967, + 0.91862966, + -0.39812375, + 0.91733172, + -0.40112358, + 0.91602395, + -0.40411910, + 0.91470637, + -0.40711031, + 0.91337900, + -0.41009715, + 0.91204185, + -0.41307959, + 0.91069493, + -0.41605762, + 0.90933825, + -0.41903119, + 0.90797184, + -0.42200027, + 0.90659570, + -0.42496483, + 0.90520986, + -0.42792484, + 0.90381432, + -0.43088027, + 0.90240910, + -0.43383109, + 0.90099422, + -0.43677726, + 0.89956969, + -0.43971875, + 0.89813553, + -0.44265553, + 0.89669174, + -0.44558757, + 0.89523836, + -0.44851484, + 0.89377538, + -0.45143731, + 0.89230284, + -0.45435494, + 0.89082074, + -0.45726770, + 0.88932910, + -0.46017557, + 0.88782793, + -0.46307851, + 0.88631726, + -0.46597650, + 0.88479710, + -0.46886949, + 0.88326746, + -0.47175746, + 0.88172836, + -0.47464038, + 0.88017982, + -0.47751821, + 0.87862185, + -0.48039093, + 0.87705448, + -0.48325851, + 0.87547771, + -0.48612091, + 0.87389156, + -0.48897811, + 0.87229606, + -0.49183006, + 0.87069121, + -0.49467676, + 0.86907704, + -0.49751815, + 0.86745357, + -0.50035422, + 0.86582080, + -0.50318492, + 0.86417876, + -0.50601024, + 0.86252747, + -0.50883014, + 0.86086694, + -0.51164459, + 0.85919719, + -0.51445356, + 0.85751824, + -0.51725703, + 0.85583010, + -0.52005495, + 0.85413281, + -0.52284730, + 0.85242636, + -0.52563406, + 0.85071078, + -0.52841518, + 0.84898610, + -0.53119065, + 0.84725232, + -0.53396043, + 0.84550947, + -0.53672449, + 0.84375756, + -0.53948280, + 0.84199662, + -0.54223533, + 0.84022666, + -0.54498206, + 0.83844771, + -0.54772295, + 0.83665977, + -0.55045797, + 0.83486287, + -0.55318710, + 0.83305704, + -0.55591031, + 0.83124228, + -0.55862756, + 0.82941862, + -0.56133883, + 0.82758608, + -0.56404409, + 0.82574467, + -0.56674331, + 0.82389442, + -0.56943646, + 0.82203535, + -0.57212351, + 0.82016748, + -0.57480443, + 0.81829082, + -0.57747920, + 0.81640540, + -0.58014778, + 0.81451123, + -0.58281015, + 0.81260835, + -0.58546628, + 0.81069676, + -0.58811614, + 0.80877649, + -0.59075970, + 0.80684755, + -0.59339694, + 0.80490998, + -0.59602782, + 0.80296379, + -0.59865231, + 0.80100899, + -0.60127040, + 0.79904562, + -0.60388204, + 0.79707370, + -0.60648722, + 0.79509323, + -0.60908591, + 0.79310425, + -0.61167807, + 0.79110678, + -0.61426368, + 0.78910084, + -0.61684271, + 0.78708644, + -0.61941514, + 0.78506362, + -0.62198093, + 0.78303239, + -0.62454007, + 0.78099277, + -0.62709251, + 0.77894479, + -0.62963824, + 0.77688847, + -0.63217722, + 0.77482382, + -0.63470944, + 0.77275088, + -0.63723486, + 0.77066967, + -0.63975345, + 0.76858020, + -0.64226519, + 0.76648250, + -0.64477006, + 0.76437659, + -0.64726802, + 0.76226250, + -0.64975905, + 0.76014024, + -0.65224312, + 0.75800984, + -0.65472020, + 0.75587132, + -0.65719027, + 0.75372471, + -0.65965331, + 0.75157003, + -0.66210928, + 0.74940730, + -0.66455816, + 0.74723654, + -0.66699992, + 0.74505779, + -0.66943454, + 0.74287105, + -0.67186199, + 0.74067635, + -0.67428225, + 0.73847373, + -0.67669528, + 0.73626320, + -0.67910107, + 0.73404478, + -0.68149959, + 0.73181850, + -0.68389080, + 0.72958438, + -0.68627470, + 0.72734245, + -0.68865124, + 0.72509273, + -0.69102041, + 0.72283525, + -0.69338218, + 0.72057002, + -0.69573652, + 0.71829708, + -0.69808341, + 0.71601644, + -0.70042283, + 0.71372814, + -0.70275474, + 0.71143220, + -0.70507913, + 0.70912863, + -0.70739597, + 0.70681747, + -0.70970524, + 0.70449874, + -0.71200690, + 0.70217247, + -0.71430093, + 0.69983868, + -0.71658732, + 0.69749739, + -0.71886604, + 0.69514863, + -0.72113705, + 0.69279243, + -0.72340034, + 0.69042881, + -0.72565589, + 0.68805780, + -0.72790366, + 0.68567941, + -0.73014364, + 0.68329369, + -0.73237580, + 0.68090064, + -0.73460012, + 0.67850031, + -0.73681657, + 0.67609270, + -0.73902513, + 0.67367786, + -0.74122577, + 0.67125580, + -0.74341848, + 0.66882656, + -0.74560322, + 0.66639015, + -0.74777998, + 0.66394661, + -0.74994874, + 0.66149595, + -0.75210946, + 0.65903821, + -0.75426212, + 0.65657341, + -0.75640671, + 0.65410159, + -0.75854320, + 0.65162275, + -0.76067157, + 0.64913694, + -0.76279178, + 0.64664418, + -0.76490383, + 0.64414449, + -0.76700769, + 0.64163790, + -0.76910334, + 0.63912444, + -0.77119075, + 0.63660414, + -0.77326989, + 0.63407702, + -0.77534076, + 0.63154311, + -0.77740333, + 0.62900244, + -0.77945757, + 0.62645503, + -0.78150346, + 0.62390091, + -0.78354098, + 0.62134011, + -0.78557011, + 0.61877265, + -0.78759083, + 0.61619857, + -0.78960312, + 0.61361789, + -0.79160694, + 0.61103064, + -0.79360229, + 0.60843685, + -0.79558915, + 0.60583654, + -0.79756748, + 0.60322974, + -0.79953727, + 0.60061648, + -0.80149850, + 0.59799679, + -0.80345114, + 0.59537069, + -0.80539518, + 0.59273822, + -0.80733060, + 0.59009940, + -0.80925737, + 0.58745427, + -0.81117547, + 0.58480284, + -0.81308489, + 0.58214514, + -0.81498559, + 0.57948122, + -0.81687757, + 0.57681109, + -0.81876081, + 0.57413478, + -0.82063527, + 0.57145232, + -0.82250095, + 0.56876374, + -0.82435781, + 0.56606907, + -0.82620585, + 0.56336834, + -0.82804505, + 0.56066158, + -0.82987537, + 0.55794881, + -0.83169681, + 0.55523006, + -0.83350933, + 0.55250537, + -0.83531294, + 0.54977477, + -0.83710760, + 0.54703827, + -0.83889329, + 0.54429592, + -0.84067000, + 0.54154774, + -0.84243770, + 0.53879376, + -0.84419639, + 0.53603401, + -0.84594603, + 0.53326852, + -0.84768662, + 0.53049731, + -0.84941812, + 0.52772043, + -0.85114053, + 0.52493790, + -0.85285383, + 0.52214974, + -0.85455799, + 0.51935599, + -0.85625300, + 0.51655668, + -0.85793884, + 0.51375184, + -0.85961549, + 0.51094149, + -0.86128294, + 0.50812568, + -0.86294116, + 0.50530442, + -0.86459014, + 0.50247775, + -0.86622986, + 0.49964570, + -0.86786031, + 0.49680830, + -0.86948146, + 0.49396558, + -0.87109330, + 0.49111757, + -0.87269581, + 0.48826430, + -0.87428898, + 0.48540580, + -0.87587278, + 0.48254210, + -0.87744720, + 0.47967323, + -0.87901223, + 0.47679923, + -0.88056784, + 0.47392012, + -0.88211402, + 0.47103594, + -0.88365076, + 0.46814671, + -0.88517803, + 0.46525247, + -0.88669582, + 0.46235324, + -0.88820412, + 0.45944907, + -0.88970290, + 0.45653997, + -0.89119216, + 0.45362599, + -0.89267187, + 0.45070714, + -0.89414203, + 0.44778347, + -0.89560260, + 0.44485501, + -0.89705359, + 0.44192178, + -0.89849497, + 0.43898381, + -0.89992673, + 0.43604115, + -0.90134885, + 0.43309382, + -0.90276131, + 0.43014185, + -0.90416411, + 0.42718527, + -0.90555723, + 0.42422412, + -0.90694065, + 0.42125842, + -0.90831436, + 0.41828822, + -0.90967833, + 0.41531353, + -0.91103257, + 0.41233440, + -0.91237705, + 0.40935085, + -0.91371176, + 0.40636291, + -0.91503669, + 0.40337063, + -0.91635181, + 0.40037402, + -0.91765712, + 0.39737313, + -0.91895261, + 0.39436798, + -0.92023825, + 0.39135861, + -0.92151404, + 0.38834505, + -0.92277996, + 0.38532733, + -0.92403600, + 0.38230548, + -0.92528214, + 0.37927953, + -0.92651837, + 0.37624953, + -0.92774468, + 0.37321550, + -0.92896106, + 0.37017747, + -0.93016748, + 0.36713547, + -0.93136395, + 0.36408955, + -0.93255044, + 0.36103972, + -0.93372694, + 0.35798603, + -0.93489345, + 0.35492850, + -0.93604994, + 0.35186718, + -0.93719641, + 0.34880208, + -0.93833284, + 0.34573325, + -0.93945922, + 0.34266072, + -0.94057555, + 0.33958451, + -0.94168180, + 0.33650468, + -0.94277796, + 0.33342123, + -0.94386403, + 0.33033422, + -0.94493999, + 0.32724367, + -0.94600583, + 0.32414961, + -0.94706154, + 0.32105209, + -0.94810711, + 0.31795112, + -0.94914252, + 0.31484675, + -0.95016777, + 0.31173901, + -0.95118284, + 0.30862793, + -0.95218773, + 0.30551354, + -0.95318242, + 0.30239588, + -0.95416690, + 0.29927499, + -0.95514117, + 0.29615089, + -0.95610520, + 0.29302362, + -0.95705900, + 0.28989321, + -0.95800255, + 0.28675969, + -0.95893583, + 0.28362310, + -0.95985885, + 0.28048348, + -0.96077159, + 0.27734085, + -0.96167404, + 0.27419526, + -0.96256619, + 0.27104672, + -0.96344803, + 0.26789529, + -0.96431956, + 0.26474098, + -0.96518076, + 0.26158384, + -0.96603162, + 0.25842390, + -0.96687213, + 0.25526119, + -0.96770230, + 0.25209575, + -0.96852209, + 0.24892761, + -0.96933152, + 0.24575680, + -0.97013057, + 0.24258336, + -0.97091922, + 0.23940732, + -0.97169748, + 0.23622872, + -0.97246533, + 0.23304759, + -0.97322277, + 0.22986396, + -0.97396979, + 0.22667787, + -0.97470637, + 0.22348935, + -0.97543252, + 0.22029844, + -0.97614822, + 0.21710517, + -0.97685347, + 0.21390958, + -0.97754825, + 0.21071169, + -0.97823257, + 0.20751155, + -0.97890641, + 0.20430919, + -0.97956977, + 0.20110463, + -0.98022263, + 0.19789793, + -0.98086500, + 0.19468910, + -0.98149687, + 0.19147819, + -0.98211822, + 0.18826523, + -0.98272906, + 0.18505026, + -0.98332937, + 0.18183330, + -0.98391915, + 0.17861439, + -0.98449840, + 0.17539357, + -0.98506710, + 0.17217088, + -0.98562525, + 0.16894634, + -0.98617285, + 0.16571999, + -0.98670988, + 0.16249186, + -0.98723635, + 0.15926200, + -0.98775225, + 0.15603043, + -0.98825757, + 0.15279719, + -0.98875230, + 0.14956231, + -0.98923645, + 0.14632583, + -0.98971000, + 0.14308778, + -0.99017295, + 0.13984820, + -0.99062530, + 0.13660713, + -0.99106704, + 0.13336459, + -0.99149817, + 0.13012062, + -0.99191868, + 0.12687526, + -0.99232857, + 0.12362854, + -0.99272783, + 0.12038049, + -0.99311645, + 0.11713116, + -0.99349445, + 0.11388057, + -0.99386180, + 0.11062877, + -0.99421851, + 0.10737578, + -0.99456457, + 0.10412163, + -0.99489998, + 0.10086638, + -0.99522474, + 0.097610040, + -0.99553884, + 0.094352658, + -0.99584227, + 0.091094266, + -0.99613505, + 0.087834897, + -0.99641715, + 0.084574589, + -0.99668858, + 0.081313374, + -0.99694934, + 0.078051289, + -0.99719943, + 0.074788367, + -0.99743883, + 0.071524645, + -0.99766756, + 0.068260157, + -0.99788559, + 0.064994938, + -0.99809295, + 0.061729023, + -0.99828961, + 0.058462447, + -0.99847558, + 0.055195244, + -0.99865086, + 0.051927451, + -0.99881544, + 0.048659101, + -0.99896933, + 0.045390231, + -0.99911252, + 0.042120874, + -0.99924501, + 0.038851066, + -0.99936680, + 0.035580842, + -0.99947789, + 0.032310238, + -0.99957827, + 0.029039287, + -0.99966795, + 0.025768025, + -0.99974692, + 0.022496487, + -0.99981519, + 0.019224708, + -0.99987275, + 0.015952723, + -0.99991960, + 0.012680568, + -0.99995574, + 0.0094082767, + -0.99998118, + 0.0061358846, + -0.99999590, + 0.0028634269, + -0.00081812300, + 0.99999967, + -0.0073630412, + 0.99997289, + -0.013907644, + 0.99990328, + -0.020451651, + 0.99979084, + -0.026994782, + 0.99963557, + -0.033536757, + 0.99943748, + -0.040077295, + 0.99919658, + -0.046616116, + 0.99891288, + -0.053152941, + 0.99858638, + -0.059687488, + 0.99821711, + -0.066219479, + 0.99780508, + -0.072748633, + 0.99735031, + -0.079274670, + 0.99685281, + -0.085797312, + 0.99631261, + -0.092316279, + 0.99572973, + -0.098831291, + 0.99510420, + -0.10534207, + 0.99443605, + -0.11184834, + 0.99372529, + -0.11834981, + 0.99297196, + -0.12484622, + 0.99217610, + -0.13133727, + 0.99133774, + -0.13782270, + 0.99045692, + -0.14430223, + 0.98953366, + -0.15077558, + 0.98856802, + -0.15724246, + 0.98756003, + -0.16370261, + 0.98650973, + -0.17015575, + 0.98541718, + -0.17660160, + 0.98428242, + -0.18303989, + 0.98310549, + -0.18947033, + 0.98188645, + -0.19589266, + 0.98062534, + -0.20230660, + 0.97932224, + -0.20871187, + 0.97797718, + -0.21510820, + 0.97659022, + -0.22149531, + 0.97516144, + -0.22787294, + 0.97369088, + -0.23424080, + 0.97217861, + -0.24059864, + 0.97062469, + -0.24694616, + 0.96902920, + -0.25328311, + 0.96739220, + -0.25960920, + 0.96571376, + -0.26592418, + 0.96399395, + -0.27222777, + 0.96223284, + -0.27851969, + 0.96043052, + -0.28479968, + 0.95858705, + -0.29106748, + 0.95670253, + -0.29732280, + 0.95477702, + -0.30356539, + 0.95281061, + -0.30979497, + 0.95080338, + -0.31601129, + 0.94875543, + -0.32221406, + 0.94666684, + -0.32840304, + 0.94453769, + -0.33457794, + 0.94236808, + -0.34073852, + 0.94015810, + -0.34688450, + 0.93790786, + -0.35301562, + 0.93561743, + -0.35913161, + 0.93328693, + -0.36523223, + 0.93091644, + -0.37131719, + 0.92850608, + -0.37738626, + 0.92605595, + -0.38343915, + 0.92356614, + -0.38947562, + 0.92103677, + -0.39549541, + 0.91846795, + -0.40149825, + 0.91585979, + -0.40748390, + 0.91321239, + -0.41345209, + 0.91052587, + -0.41940257, + 0.90780035, + -0.42533508, + 0.90503595, + -0.43124938, + 0.90223277, + -0.43714520, + 0.89939095, + -0.44302229, + 0.89651059, + -0.44888041, + 0.89359184, + -0.45471930, + 0.89063481, + -0.46053871, + 0.88763962, + -0.46633839, + 0.88460641, + -0.47211810, + 0.88153531, + -0.47787758, + 0.87842644, + -0.48361659, + 0.87527995, + -0.48933489, + 0.87209596, + -0.49503222, + 0.86887462, + -0.50070835, + 0.86561605, + -0.50636303, + 0.86232041, + -0.51199602, + 0.85898782, + -0.51760707, + 0.85561844, + -0.52319595, + 0.85221241, + -0.52876243, + 0.84876987, + -0.53430625, + 0.84529098, + -0.53982718, + 0.84177587, + -0.54532499, + 0.83822471, + -0.55079944, + 0.83463763, + -0.55625029, + 0.83101481, + -0.56167732, + 0.82735639, + -0.56708028, + 0.82366252, + -0.57245896, + 0.81993338, + -0.57781311, + 0.81616911, + -0.58314251, + 0.81236987, + -0.58844693, + 0.80853584, + -0.59372614, + 0.80466718, + -0.59897992, + 0.80076404, + -0.60420805, + 0.79682660, + -0.60941029, + 0.79285503, + -0.61458642, + 0.78884950, + -0.61973623, + 0.78481017, + -0.62485949, + 0.78073723, + -0.62995598, + 0.77663084, + -0.63502549, + 0.77249118, + -0.64006780, + 0.76831844, + -0.64508268, + 0.76411277, + -0.65006994, + 0.75987438, + -0.65502934, + 0.75560344, + -0.65996069, + 0.75130013, + -0.66486377, + 0.74696464, + -0.66973837, + 0.74259715, + -0.67458427, + 0.73819784, + -0.67940128, + 0.73376692, + -0.68418919, + 0.72930457, + -0.68894779, + 0.72481097, + -0.69367688, + 0.72028632, + -0.69837625, + 0.71573083, + -0.70304571, + 0.71114467, + -0.70768504, + 0.70652804, + -0.71229407, + 0.70188116, + -0.71687258, + 0.69720420, + -0.72142039, + 0.69249738, + -0.72593729, + 0.68776090, + -0.73042309, + 0.68299495, + -0.73487761, + 0.67819975, + -0.73930064, + 0.67337550, + -0.74369201, + 0.66852240, + -0.74805152, + 0.66364066, + -0.75237898, + 0.65873050, + -0.75667422, + 0.65379211, + -0.76093704, + 0.64882573, + -0.76516727, + 0.64383154, + -0.76936471, + 0.63880978, + -0.77352921, + 0.63376065, + -0.77766056, + 0.62868438, + -0.78175861, + 0.62358117, + -0.78582316, + 0.61845126, + -0.78985406, + 0.61329485, + -0.79385112, + 0.60811216, + -0.79781417, + 0.60290343, + -0.80174305, + 0.59766888, + -0.80563758, + 0.59240872, + -0.80949760, + 0.58712318, + -0.81332295, + 0.58181249, + -0.81711346, + 0.57647688, + -0.82086896, + 0.57111658, + -0.82458930, + 0.56573181, + -0.82827432, + 0.56032281, + -0.83192386, + 0.55488980, + -0.83553776, + 0.54943303, + -0.83911587, + 0.54395272, + -0.84265803, + 0.53844911, + -0.84616410, + 0.53292243, + -0.84963392, + 0.52737292, + -0.85306735, + 0.52180083, + -0.85646423, + 0.51620638, + -0.85982442, + 0.51058981, + -0.86314779, + 0.50495138, + -0.86643418, + 0.49929132, + -0.86968345, + 0.49360987, + -0.87289547, + 0.48790727, + -0.87607009, + 0.48218377, + -0.87920719, + 0.47643962, + -0.88230663, + 0.47067506, + -0.88536827, + 0.46489034, + -0.88839199, + 0.45908570, + -0.89137765, + 0.45326139, + -0.89432512, + 0.44741768, + -0.89723429, + 0.44155479, + -0.90010502, + 0.43567299, + -0.90293719, + 0.42977253, + -0.90573069, + 0.42385365, + -0.90848539, + 0.41791662, + -0.91120117, + 0.41196169, + -0.91387791, + 0.40598911, + -0.91651551, + 0.39999914, + -0.91911385, + 0.39399204, + -0.92167282, + 0.38796806, + -0.92419231, + 0.38192746, + -0.92667220, + 0.37587050, + -0.92911240, + 0.36979743, + -0.93151280, + 0.36370853, + -0.93387330, + 0.35760405, + -0.93619380, + 0.35148424, + -0.93847419, + 0.34534939, + -0.94071438, + 0.33919973, + -0.94291427, + 0.33303555, + -0.94507377, + 0.32685710, + -0.94719279, + 0.32066465, + -0.94927123, + 0.31445847, + -0.95130901, + 0.30823881, + -0.95330604, + 0.30200595, + -0.95526223, + 0.29576015, + -0.95717750, + 0.28950169, + -0.95905177, + 0.28323082, + -0.96088496, + 0.27694782, + -0.96267699, + 0.27065295, + -0.96442777, + 0.26434649, + -0.96613725, + 0.25802871, + -0.96780534, + 0.25169988, + -0.96943197, + 0.24536026, + -0.97101707, + 0.23901013, + -0.97256058, + 0.23264977, + -0.97406243, + 0.22627944, + -0.97552255, + 0.21989941, + -0.97694089, + 0.21350997, + -0.97831737, + 0.20711138, + -0.97965195, + 0.20070391, + -0.98094456, + 0.19428785, + -0.98219515, + 0.18786347, + -0.98340367, + 0.18143104, + -0.98457006, + 0.17499084, + -0.98569428, + 0.16854314, + -0.98677627, + 0.16208822, + -0.98781599, + 0.15562636, + -0.98881340, + 0.14915783, + -0.98976845, + 0.14268292, + -0.99068110, + 0.13620189, + -0.99155132, + 0.12971502, + -0.99237906, + 0.12322260, + -0.99316428, + 0.11672491, + -0.99390697, + 0.11022221, + -0.99460708, + 0.10371479, + -0.99526458, + 0.097202924, + -0.99587945, + 0.090686897, + -0.99645166, + 0.084166986, + -0.99698119, + 0.077643468, + -0.99746801, + 0.071116625, + -0.99791210, + 0.064586736, + -0.99831344, + 0.058054080, + -0.99867202, + 0.051518937, + -0.99898782, + 0.044981587, + -0.99926082, + 0.038442310, + -0.99949102, + 0.031901387, + -0.99967841, + 0.025359097, + -0.99982297, + 0.018815721, + -0.99992470, + 0.012271538, + -0.99998360, + 0.0057268303, + -0.0016362454, + 0.99999866, + -0.014725683, + 0.99989157, + -0.027812598, + 0.99961315, + -0.040894747, + 0.99916346, + -0.053969889, + 0.99854256, + -0.067035784, + 0.99775057, + -0.080090192, + 0.99678762, + -0.093130877, + 0.99565388, + -0.10615561, + 0.99434953, + -0.11916214, + 0.99287481, + -0.13214826, + 0.99122996, + -0.14511174, + 0.98941527, + -0.15805036, + 0.98743105, + -0.17096189, + 0.98527764, + -0.18384413, + 0.98295541, + -0.19669487, + 0.98046475, + -0.20951190, + 0.97780610, + -0.22229304, + 0.97497990, + -0.23503609, + 0.97198664, + -0.24773886, + 0.96882685, + -0.26039919, + 0.96550104, + -0.27301490, + 0.96200980, + -0.28558383, + 0.95835373, + -0.29810383, + 0.95453345, + -0.31057274, + 0.95054962, + -0.32298845, + 0.94640291, + -0.33534881, + 0.94209404, + -0.34765171, + 0.93762375, + -0.35989504, + 0.93299280, + -0.37207670, + 0.92820199, + -0.38419461, + 0.92325213, + -0.39624670, + 0.91814408, + -0.40823088, + 0.91287871, + -0.42014512, + 0.90745693, + -0.43198737, + 0.90187965, + -0.44375560, + 0.89614785, + -0.45544780, + 0.89026249, + -0.46706195, + 0.88422459, + -0.47859608, + 0.87803519, + -0.49004821, + 0.87169533, + -0.50141636, + 0.86520612, + -0.51269860, + 0.85856866, + -0.52389299, + 0.85178409, + -0.53499762, + 0.84485357, + -0.54601058, + 0.83777828, + -0.55692998, + 0.83055945, + -0.56775395, + 0.82319831, + -0.57848064, + 0.81569611, + -0.58910822, + 0.80805415, + -0.59963485, + 0.80027373, + -0.61005873, + 0.79235620, + -0.62037809, + 0.78430289, + -0.63059115, + 0.77611520, + -0.64069616, + 0.76779452, + -0.65069139, + 0.75934229, + -0.66057513, + 0.75075995, + -0.67034568, + 0.74204897, + -0.68000137, + 0.73321084, + -0.68954054, + 0.72424708, + -0.69896157, + 0.71515923, + -0.70826283, + 0.70594883, + -0.71744274, + 0.69661748, + -0.72649972, + 0.68716676, + -0.73543221, + 0.67759830, + -0.74423869, + 0.66791374, + -0.75291765, + 0.65811474, + -0.76146760, + 0.64820297, + -0.76988708, + 0.63818013, + -0.77817464, + 0.62804795, + -0.78632887, + 0.61780815, + -0.79434836, + 0.60746249, + -0.80223175, + 0.59701275, + -0.80997767, + 0.58646072, + -0.81758481, + 0.57580819, + -0.82505187, + 0.56505701, + -0.83237755, + 0.55420900, + -0.83956061, + 0.54326604, + -0.84659981, + 0.53222998, + -0.85349396, + 0.52110274, + -0.86024186, + 0.50988620, + -0.86684237, + 0.49858230, + -0.87329434, + 0.48719297, + -0.87959669, + 0.47572016, + -0.88574831, + 0.46416584, + -0.89174817, + 0.45253199, + -0.89759523, + 0.44082059, + -0.90328850, + 0.42903367, + -0.90882699, + 0.41717323, + -0.91420976, + 0.40524131, + -0.91943588, + 0.39323996, + -0.92450446, + 0.38117123, + -0.92941463, + 0.36903718, + -0.93416555, + 0.35683990, + -0.93875641, + 0.34458148, + -0.94318642, + 0.33226402, + -0.94745482, + 0.31988962, + -0.95156087, + 0.30746042, + -0.95550388, + 0.29497853, + -0.95928317, + 0.28244610, + -0.96289809, + 0.26986527, + -0.96634802, + 0.25723821, + -0.96963238, + 0.24456706, + -0.97275059, + 0.23185402, + -0.97570213, + 0.21910124, + -0.97848649, + 0.20631092, + -0.98110318, + 0.19348526, + -0.98355177, + 0.18062644, + -0.98583184, + 0.16773667, + -0.98794298, + 0.15481816, + -0.98988485, + 0.14187312, + -0.99165711, + 0.12890377, + -0.99325945, + 0.11591234, + -0.99469160, + 0.10290104, + -0.99595331, + 0.089872115, + -0.99704438, + 0.076827789, + -0.99796460, + 0.063770300, + -0.99871383, + 0.050701883, + -0.99929194, + 0.037624779, + -0.99969882, + 0.024541229, + -0.99993441, + 0.011453473, + -0.0032724865, + 0.99999465, + -0.029448173, + 0.99956631, + -0.055603678, + 0.99845292, + -0.081721074, + 0.99665524, + -0.10778246, + 0.99417450, + -0.13376998, + 0.99101241, + -0.15966582, + 0.98717112, + -0.18545224, + 0.98265328, + -0.21111155, + 0.97746197, + -0.23662618, + 0.97160077, + -0.26197864, + 0.96507367, + -0.28715155, + 0.95788516, + -0.31212766, + 0.95004017, + -0.33688985, + 0.94154407, + -0.36142116, + 0.93240267, + -0.38570477, + 0.92262226, + -0.40972403, + 0.91220953, + -0.43346249, + 0.90117161, + -0.45690388, + 0.88951608, + -0.48003212, + 0.87725091, + -0.50283138, + 0.86438452, + -0.52528602, + 0.85092573, + -0.54738066, + 0.83688375, + -0.56910015, + 0.82226822, + -0.59042960, + 0.80708914, + -0.61135441, + 0.79135693, + -0.63186022, + 0.77508236, + -0.65193299, + 0.75827658, + -0.67155895, + 0.74095113, + -0.69072467, + 0.72311786, + -0.70941699, + 0.70478900, + -0.72762312, + 0.68597711, + -0.74533057, + 0.66669509, + -0.76252720, + 0.64695615, + -0.77920124, + 0.62677382, + -0.79534126, + 0.60616193, + -0.81093618, + 0.58513461, + -0.82597533, + 0.56370626, + -0.84044840, + 0.54189158, + -0.85434547, + 0.51970551, + -0.86765701, + 0.49716327, + -0.88037390, + 0.47428029, + -0.89248743, + 0.45107226, + -0.90398929, + 0.42755509, + -0.91487161, + 0.40374490, + -0.92512691, + 0.37965800, + -0.93474818, + 0.35531090, + -0.94372882, + 0.33072029, + -0.95206268, + 0.30590302, + -0.95974404, + 0.28087610, + -0.96676764, + 0.25565668, + -0.97312866, + 0.23026205, + -0.97882275, + 0.20470960, + -0.98384601, + 0.17901686, + -0.98819498, + 0.15320143, + -0.99186670, + 0.12728100, + -0.99485864, + 0.10127334, + -0.99716875, + 0.075196277, + -0.99879546, + 0.049067674, + -0.99973764, + 0.022905443, +]; diff --git a/crates/ec-opus/src/celt_flp/vq.rs b/crates/ec-opus/src/celt_flp/vq.rs new file mode 100644 index 00000000..3cfc2cae --- /dev/null +++ b/crates/ec-opus/src/celt_flp/vq.rs @@ -0,0 +1,250 @@ +use super::{EPSILON, celt_atan2p_norm, celt_cos_norm, celt_rcp, celt_rsqrt, celt_sqrt}; +use crate::celt::{pvq_u, pvq_v}; +use crate::range::RangeEncoder; + +const SPREAD_FACTOR: [i32; 3] = [15, 10, 5]; +const MAX_N: usize = 176; + +fn inner_prod(x: &[f32], y: &[f32], n: usize) -> f32 { + let mut xy: f32 = 0.0; + for i in 0..n { + xy += x[i] * y[i]; + } + xy +} + +fn exp_rotation1(x: &mut [f32], len: usize, stride: usize, c: f32, s: f32) { + let ms = -s; + for i in 0..len.saturating_sub(stride) { + let x1 = x[i]; + let x2 = x[i + stride]; + x[i + stride] = c * x2 + s * x1; + x[i] = c * x1 + ms * x2; + } + for i in (0..len.saturating_sub(2 * stride)).rev() { + let x1 = x[i]; + let x2 = x[i + stride]; + x[i + stride] = c * x2 + s * x1; + x[i] = c * x1 + ms * x2; + } +} + +/// `exp_rotation`. +pub(crate) fn exp_rotation( + x: &mut [f32], + len: usize, + dir: i32, + stride: usize, + k: i32, + spread: i32, +) { + if 2 * k >= len as i32 || spread == 0 { + return; + } + let factor = SPREAD_FACTOR[(spread - 1) as usize]; + let gain = len as f32 / (len as i32 + factor * k) as f32; + let theta = 0.5f32 * (gain * gain); + let c = celt_cos_norm(theta); + let s = celt_cos_norm(1.0 - theta); + let mut stride2 = 0usize; + if len >= 8 * stride { + stride2 = 1; + while (stride2 * stride2 + stride2) * stride + (stride >> 2) < len { + stride2 += 1; + } + } + let len = len / stride; + for i in 0..stride { + let seg = &mut x[i * len..]; + if dir < 0 { + if stride2 != 0 { + exp_rotation1(seg, len, stride2, s, c); + } + exp_rotation1(seg, len, 1, c, s); + } else { + exp_rotation1(seg, len, 1, c, -s); + if stride2 != 0 { + exp_rotation1(seg, len, stride2, s, -c); + } + } + } +} + +fn normalise_residual(iy: &[i32], x: &mut [f32], n: usize, ryy: f32, gain: f32) { + let g = celt_rsqrt(ryy) * gain; + for i in 0..n { + x[i] = iy[i] as f32 * g; + } +} + +fn extract_collapse_mask(iy: &[i32], n: usize, b: usize) -> u32 { + if b <= 1 { + return 1; + } + let n0 = n / b; + let mut mask = 0u32; + for i in 0..b { + let mut tmp = 0u32; + for j in 0..n0 { + tmp |= iy[i * n0 + j] as u32; + } + mask |= ((tmp != 0) as u32) << i; + } + mask +} + +fn op_pvq_search(x: &mut [f32], iy: &mut [i32], k: i32, n: usize) -> f32 { + let mut y_buf = [0f32; MAX_N]; + let mut signx_buf = [0i32; MAX_N]; + let y = &mut y_buf[..n]; + let signx = &mut signx_buf[..n]; + for j in 0..n { + signx[j] = (x[j] < 0.0) as i32; + x[j] = x[j].abs(); + iy[j] = 0; + y[j] = 0.0; + } + + let mut xy: f32 = 0.0; + let mut yy: f32 = 0.0; + let mut pulses_left = k; + + if k > (n >> 1) as i32 { + let mut sum: f32 = 0.0; + for j in 0..n { + sum += x[j]; + } + if !(sum > EPSILON && sum < 64.0) { + x[0] = 1.0; + for j in 1..n { + x[j] = 0.0; + } + sum = 1.0; + } + let rcp = (k as f32 + 0.8f32) * celt_rcp(sum); + for j in 0..n { + iy[j] = ((rcp * x[j]) as f64).floor() as i32; + y[j] = iy[j] as f32; + yy += y[j] * y[j]; + xy += x[j] * y[j]; + y[j] *= 2.0; + pulses_left -= iy[j]; + } + } + + if pulses_left > n as i32 + 3 { + let tmp = pulses_left as f32; + yy += tmp * tmp; + yy += tmp * y[0]; + iy[0] += pulses_left; + pulses_left = 0; + } + + for _ in 0..pulses_left { + let mut best_id = 0usize; + yy += 1.0; + let mut rxy = xy + x[0]; + let mut ryy = yy + y[0]; + rxy = rxy * rxy; + let mut best_den = ryy; + let mut best_num = rxy; + for j in 1..n { + rxy = xy + x[j]; + ryy = yy + y[j]; + rxy = rxy * rxy; + if best_den * rxy > ryy * best_num { + best_den = ryy; + best_num = rxy; + best_id = j; + } + } + xy += x[best_id]; + yy += y[best_id]; + y[best_id] += 2.0; + iy[best_id] += 1; + } + + for j in 0..n { + if signx[j] != 0 { + iy[j] = -iy[j]; + } + } + yy +} + +fn icwrs(n: usize, y: &[i32]) -> u32 { + let mut j = n - 1; + let mut i = (y[j] < 0) as u32; + let mut k = y[j].unsigned_abs() as usize; + loop { + j -= 1; + i = i.wrapping_add(pvq_u(n - j, k)); + k += y[j].unsigned_abs() as usize; + if y[j] < 0 { + i = i.wrapping_add(pvq_u(n - j, k + 1)); + } + if j == 0 { + break; + } + } + i +} + +fn encode_pulses(y: &[i32], n: usize, k: i32, enc: &mut RangeEncoder) { + enc.enc_uint(icwrs(n, y), pvq_v(n, k as usize)); +} + +/// `alg_quant` (encoder, no QEXT); returns the collapse mask. +pub(crate) fn alg_quant( + x: &mut [f32], + n: usize, + k: i32, + spread: i32, + b: i32, + enc: &mut RangeEncoder, + gain: f32, + resynth: bool, +) -> u32 { + let b = b as usize; + let mut iy_buf = [0i32; MAX_N + 3]; + let iy = &mut iy_buf[..n + 3]; + exp_rotation(x, n, 1, b, k, spread); + let yy = op_pvq_search(x, iy, k, n); + let collapse_mask = extract_collapse_mask(iy, n, b); + encode_pulses(iy, n, k, enc); + if resynth { + normalise_residual(iy, x, n, yy, gain); + exp_rotation(x, n, -1, b, k, spread); + } + collapse_mask +} + +/// `stereo_itheta`. +pub(crate) fn stereo_itheta(x: &[f32], y: &[f32], stereo: bool, n: usize) -> i32 { + let mut emid: f32 = 0.0; + let mut eside: f32 = 0.0; + if stereo { + for i in 0..n { + let m = x[i] + y[i]; + let s = x[i] - y[i]; + emid += m * m; + eside += s * s; + } + } else { + emid += inner_prod(x, x, n); + eside += inner_prod(y, y, n); + } + let mid = celt_sqrt(emid); + let side = celt_sqrt(eside); + let v = 0.5f32 + (65536.0f32 * 16384.0f32) * celt_atan2p_norm(side, mid); + (v as f64).floor() as i32 +} + +/// `renormalise_vector`. +pub(crate) fn renormalise_vector(x: &mut [f32], n: usize, gain: f32) { + let e = EPSILON + inner_prod(x, x, n); + let g = celt_rsqrt(e) * gain; + for i in 0..n { + x[i] *= g; + } +} diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index e3bc4e5c..68712986 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -27,7 +27,8 @@ use ec_core::{Error, Result}; use crate::analysis::{AnalysisInfo, TonalityAnalysis}; -use crate::celt_enc::CeltEncoder; +use crate::celt_flp::enc::{BITRATE_MAX, CeltEnc}; +use crate::celt_flp::tables::WINDOW120; use crate::packet::{Bandwidth, Mode}; use crate::range::RangeEncoder; use crate::silk_flp::opus::{ @@ -100,6 +101,7 @@ struct Decision { to_celt: bool, prefill: Prefill, to_mono: bool, + toc_only: Option, } #[derive(Clone, Copy, Debug, Default)] @@ -227,11 +229,26 @@ const DTX_START_Q1: i32 = 10 * 2 * 20; const DTX_END_Q1: i32 = (10 + 20) * 2 * 20; const DTX_ACTIVITY_THRESHOLD: f32 = 0.1; const DTX_PSEUDO_SNR_THRESHOLD: f32 = 316.23; -const DTX_SILENCE: f32 = 1.0 / 16_777_216.0; /// The TOC-only packet libopus sends in DTX: code 0 is the TOC alone; code 3 /// keeps its frame-count byte with no frames. Self-delimited framing adds a /// zero frame length after it. +fn gen_toc(mode: Mode, frame_rate: usize, bw: Bandwidth, channels: usize) -> u8 { + let mut period = 0; + let mut rate = frame_rate; + while rate < 400 { + rate <<= 1; + period += 1; + } + let bw = bw_index(bw) as u8; + let toc = match mode { + Mode::Silk => (bw << 5) | ((period - 2) << 3), + Mode::Celt => 0x80 | (bw.saturating_sub(1) << 5) | (period << 3), + Mode::Hybrid => 0x60 | ((bw - 3) << 4) | ((period - 2) << 3), + }; + toc | (u8::from(channels == 2) << 2) +} + fn dtx_packet(toc: u8, count: u8, self_delimited: bool) -> ([u8; 3], usize) { let mut bytes = [0u8; 3]; let len = if toc & 3 == 3 { @@ -249,14 +266,12 @@ fn encoder_buffer(sample_rate: u32) -> usize { sample_rate as usize / 100 } -fn total_buffer(sample_rate: u32) -> usize { - sample_rate as usize / 250 -} - /// One elementary Opus encoder: mono or stereo. #[derive(Clone, Debug)] pub struct Encoder { - celt: CeltEncoder, + celt: CeltEnc, + bitrate_bps: i32, + lsb_depth: i32, range: RangeEncoder, sample_rate: u32, /// 48000 / `sample_rate`: the zero-stuffing factor into CELT. @@ -295,10 +310,7 @@ pub struct Encoder { analysis: TonalityAnalysis, /// The current frame's analysis output, handed to `celt.encode`. info: AnalysisInfo, - /// Whether the analysis runs at all — see `celt_enc::analysis_params`. analysis_on: bool, - /// Whether the detected bandwidth may lower the coded one (`EC_OPUS_BW_DETECT`). - bw_detect: bool, inband_fec: bool, packet_loss_perc: u8, lbrr_coded: bool, @@ -414,7 +426,9 @@ impl Encoder { )); } let mut enc = Encoder { - celt: CeltEncoder::new(channels, upsample), + celt: CeltEnc::new(channels, upsample), + bitrate_bps: 0, + lsb_depth: 24, range: RangeEncoder::new(), sample_rate, upsample, @@ -436,8 +450,7 @@ impl Encoder { redundant: RangeEncoder::new(), analysis: TonalityAnalysis::new(sample_rate), info: AnalysisInfo::default(), - analysis_on: crate::celt_enc::analysis_params().0, - bw_detect: crate::celt_enc::analysis_params().5, + analysis_on: true, inband_fec: false, packet_loss_perc: 0, lbrr_coded: false, @@ -460,15 +473,13 @@ impl Encoder { nonfinal: false, prev_hb_gain: 1.0, }; - enc.celt.set_align_input(false); + enc.celt.set_complexity(DEFAULT_COMPLEXITY); Ok(enc) } - /// Turns the tonality analysis on or off for this encoder. It is off - /// unless one of its consumers is switched on (see - /// `celt_enc::analysis_params`), because it costs ~25% of the encoder; - /// turn it on to read `music_prob`/`tonality` back through - /// [`Encoder::last_celt_diag`]. + /// Turns libopus's tonality analysis on (the default) or off. Off saves + /// about a quarter of the encoder's time but drops what it feeds: speech/music + /// detection, bandwidth detection, and CELT's tonality-driven allocation. pub fn set_analysis(&mut self, on: bool) { self.analysis_on = on; } @@ -561,7 +572,6 @@ impl Encoder { /// becomes 312, not 120, and the Ogg pre-skip must follow it. pub fn set_libopus_input_alignment(&mut self, on: bool) { self.align_input = on; - self.celt.set_align_input(false); self.filter = InputFilter::new(); } @@ -585,6 +595,7 @@ impl Encoder { /// OPUS_SET_PACKET_LOSS_PERC: expected packet loss, 0..=100 (clamped). pub fn set_packet_loss_perc(&mut self, perc: u8) { self.packet_loss_perc = perc.min(100); + self.celt.set_loss_rate(i32::from(self.packet_loss_perc)); } /// OPUS_SET_DTX: send TOC-only packets during silence/inactivity (after 200 ms), refreshing every 400 ms. @@ -595,7 +606,11 @@ impl Encoder { /// libopus's peak signal energy tracker, run on every frame after the analysis. fn track_peak(&mut self, pcm: &[f32], frame_size: usize) { let n = frame_size * self.channels; - if pcm.iter().take(n).all(|x| x.abs() <= DTX_SILENCE) { + if pcm + .iter() + .take(n) + .all(|x| x.abs() <= self.silence_threshold()) + { return; } if !self.info.valid || self.info.activity_probability > DTX_ACTIVITY_THRESHOLD { @@ -608,7 +623,11 @@ impl Encoder { /// -1 (`VAD_NO_DECISION`) without it. fn silk_activity(&self, pcm: &[f32], frame_size: usize) -> i32 { let n = frame_size * self.channels; - if pcm.iter().take(n).all(|x| x.abs() <= DTX_SILENCE) { + if pcm + .iter() + .take(n) + .all(|x| x.abs() <= self.silence_threshold()) + { return 0; } if !self.info.valid { @@ -629,7 +648,7 @@ impl Encoder { } let n = frame_size * self.channels; let energy = pcm.iter().take(n).map(|x| x * x).sum::() / n as f32; - let is_silence = pcm.iter().all(|x| x.abs() <= DTX_SILENCE); + let is_silence = pcm.iter().all(|x| x.abs() <= self.silence_threshold()); let (valid, prob) = (self.info.valid, self.info.activity_probability); let active = if is_silence { false @@ -672,16 +691,6 @@ impl Encoder { self.final_range } - /// Per-frame CELT diagnostics from the most recent [`encode_float`] call. - /// Intended for the reelm@64k dropout investigation; the fields are only - /// meaningful when the last frame was coded as pure CELT (the path every - /// fullband Audio frame at 64 kbps stereo takes). - /// - /// [`encode_float`]: Encoder::encode_float - pub fn last_celt_diag(&self) -> &crate::celt_enc::CeltFrameDiag { - self.celt.last_diag() - } - /// Drops all inter-frame state; the next packet starts like the first. pub fn reset(&mut self) { self.celt.reset(); @@ -799,12 +808,17 @@ impl Encoder { ) -> Result<(u8, &[u8])> { let cursor = self.analysis.cursor(); self.info = if self.analysis_on { - self.analysis.run(pcm, frame_size, self.channels, 24) + self.analysis + .run(pcm, frame_size, self.channels, self.lsb_depth) } else { AnalysisInfo::default() }; self.track_peak(pcm, frame_size); let d = self.decide(pcm, frame_size, cap + 1); + if let Some(max_data) = d.toc_only { + let (toc, n) = self.toc_only_packet(d, frame_size, cap + 1, max_data)?; + return Ok((toc, &self.silk_buf[..n])); + } if d.prefill == Prefill::Reset { self.silk_layer().reset(); } @@ -818,6 +832,57 @@ impl Encoder { Ok((toc, self.payload_bytes(payload))) } + fn toc_only_packet( + &mut self, + d: Decision, + frame_size: usize, + out_bytes: usize, + max_data: usize, + ) -> Result<(u8, usize)> { + let mut frame_rate = 48000 / (frame_size * self.upsample); + let mut mode = d.mode; + let mut bw = d.bandwidth; + let mut code = 0u8; + let mut count = 1; + if frame_rate > 100 { + mode = Mode::Celt; + } + if frame_rate == 25 && mode != Mode::Silk { + frame_rate = 50; + code = 1; + count = 2; + } + if frame_rate <= 16 { + if out_bytes == 1 || (mode == Mode::Silk && frame_rate != 10) { + mode = Mode::Silk; + code = u8::from(frame_rate <= 12); + count = if code == 1 { 2 } else { 1 }; + frame_rate = if frame_rate == 12 { 25 } else { 16 }; + } else { + count = 50 / frame_rate; + frame_rate = 50; + code = 3; + } + } + bw = match mode { + Mode::Silk if bw > Bandwidth::Wide => Bandwidth::Wide, + Mode::Celt if bw == Bandwidth::Medium => Bandwidth::Narrow, + Mode::Hybrid if bw <= Bandwidth::SuperWide => Bandwidth::SuperWide, + _ => bw, + }; + let toc = gen_toc(mode, frame_rate, bw, d.stream_channels); + let frames = vec![Vec::new(); count]; + if !self.vbr && max_data > 1 + usize::from(code >= 2) { + let (_, n) = self.pack_frames(&frames, max_data, true)?; + return Ok((toc | 3, n)); + } + if code == 3 { + self.silk_buf[0] = count as u8; + return Ok((toc | 3, 1)); + } + Ok((toc | code, 0)) + } + fn encode_frame_decided( &mut self, pcm: &[f32], @@ -853,6 +918,7 @@ impl Encoder { self.hp_buf = buf; self.pcm_buf = delayed; self.prev_mode = Some(if d.to_celt { Mode::Celt } else { d.mode }); + self.prev_channels = d.stream_channels; r } @@ -885,16 +951,14 @@ impl Encoder { }; self.filter .hp_cutoff(&pcm[..n], out, smth1, self.channels, fs); - } else if self.align_input { - self.filter.dc_reject(&pcm[..n], out, self.channels, fs); } else { - out.copy_from_slice(&pcm[..n]); + self.filter.dc_reject(&pcm[..n], out, self.channels, fs); } } fn delay_input(&self, frame: &[f32], frame_size: usize, out: &mut Vec) { let ch = self.channels; - let start = (encoder_buffer(self.sample_rate) - total_buffer(self.sample_rate)) * ch; + let start = (encoder_buffer(self.sample_rate) - self.total_buffer()) * ch; out.clear(); out.extend_from_slice(&self.delay_buffer[start..]); out.extend_from_slice(&frame[..frame_size * ch]); @@ -903,7 +967,7 @@ impl Encoder { fn update_delay(&mut self, delayed: &[f32], frame_size: usize) { let ch = self.channels; let eb = encoder_buffer(self.sample_rate) * ch; - let tb = total_buffer(self.sample_rate) * ch; + let tb = self.total_buffer() * ch; let fb = frame_size * ch; if eb > fb + tb { let keep = eb - fb - tb; @@ -923,14 +987,7 @@ impl Encoder { { let g1 = self.hybrid_stereo_width_q14 as f32 / 16384.0; let g2 = self.stereo_width_q14 as f32 / 16384.0; - stereo_fade( - delayed, - g1, - g2, - self.celt.window(), - frame_size, - self.sample_rate, - ); + stereo_fade(delayed, g1, g2, &WINDOW120, frame_size, self.sample_rate); self.hybrid_stereo_width_q14 = self.stereo_width_q14; } } @@ -942,7 +999,7 @@ impl Encoder { delayed, prev, hb_gain, - self.celt.window(), + &WINDOW120, frame_size, self.channels, self.sample_rate, @@ -983,12 +1040,12 @@ impl Encoder { fn fade_prefill_history(&mut self) { let (fs, ch) = (self.sample_rate, self.channels); let n = fs as usize / 400; - let off = (encoder_buffer(fs) - total_buffer(fs) - n) * ch; + let off = (encoder_buffer(fs) - self.total_buffer() - n) * ch; gain_fade( &mut self.delay_buffer[off..], 0.0, 1.0, - self.celt.window(), + &WINDOW120, n, ch, fs, @@ -1006,71 +1063,95 @@ impl Encoder { self.history = history; } - fn celt_dummy( - &mut self, - pcm: &[f32], - frame_48k: usize, - start: usize, - end: usize, - vbr_rate: u32, - pred: u8, - ) { - self.celt.set_prediction(pred); - self.redundant.reset(2); - let _ = self.celt.encode( - &mut self.redundant, - pcm, - frame_48k, - start, - end, - vbr_rate, - &self.info, - ); + fn celt_setup(&mut self, mode: Mode, end: usize, stream_channels: usize) { + self.celt.set_lsb_depth(self.lsb_depth); + self.celt.set_end_band(end); + self.celt.set_stream_channels(stream_channels); + self.celt.set_bitrate(BITRATE_MAX); + if mode != Mode::Silk { + self.celt.set_prediction(2); + } } - fn celt_prefill(&mut self, start: usize, end: usize, vbr_rate: u32) { - let (fs, ch) = (self.sample_rate, self.channels); - let n = fs as usize / 400 * ch; - let off = (encoder_buffer(fs) - total_buffer(fs)) * ch - n; - let mut tmp = [0.0f32; 2 * 120]; - tmp[..n].copy_from_slice(&self.history[off..off + n]); + fn celt_own(&mut self, pcm: &[f32], frame_size: usize, bytes: usize) -> u32 { + let mut enc = std::mem::take(&mut self.redundant); + self.celt.encode(pcm, frame_size, bytes, &mut enc, true); + self.redundant = enc; + self.celt.final_range() + } + + fn celt_to_silk_redundancy(&mut self, delayed: &[f32], bytes: usize, out: &mut [u8]) -> u32 { + let n2 = self.sample_rate as usize / 200; + self.celt.set_start_band(0); + self.celt.set_vbr(false); + self.celt.set_bitrate(BITRATE_MAX); + let rng = self.celt_own(&delayed[..self.channels * n2], n2, bytes); + out[..bytes].copy_from_slice(&self.redundant.data()[..bytes]); self.celt.reset(); - self.celt_dummy(&tmp[..n], 120, start, end, vbr_rate, 2); - self.celt.set_prediction(0); + rng } - fn celt_redundancy( + fn celt_main( &mut self, - pcm: &[f32], - frame_48k: usize, - end: usize, - bytes: usize, - pred: u8, - out: &mut [u8], - ) -> Result { - self.celt.set_prediction(pred); - self.redundant.reset(bytes); - self.celt - .encode(&mut self.redundant, pcm, frame_48k, 0, end, 0, &self.info)?; - out[..bytes].copy_from_slice(&self.redundant.data()[..bytes]); - Ok(self.redundant.range()) + mode: Mode, + delayed: &[f32], + frame_size: usize, + nb_compr: usize, + celt_rate: i32, + ) -> usize { + self.celt.set_vbr(self.vbr); + if self.vbr { + if mode == Mode::Hybrid { + self.celt.set_bitrate(celt_rate.max(501)); + self.celt.set_vbr_constraint(false); + } else { + self.celt.set_vbr_constraint(true); + self.celt.set_bitrate(self.bitrate_bps); + } + } + if self.prev_mode.is_some_and(|p| p != mode) { + let (fs, ch) = (self.sample_rate as usize, self.channels); + let n = fs / 400; + let off = (encoder_buffer(fs as u32) - self.total_buffer()) * ch - n * ch; + let mut tmp = [0.0f32; 2 * 120]; + tmp[..n * ch].copy_from_slice(&self.history[off..off + n * ch]); + self.celt.reset(); + self.celt_own(&tmp[..n * ch], n, 2); + self.celt.set_prediction(0); + } + let mut ret = nb_compr; + if self.range.tell() as usize <= 8 * nb_compr { + let mut range = std::mem::take(&mut self.range); + let r = self + .celt + .encode(delayed, frame_size, nb_compr, &mut range, false); + self.range = range; + ret = r.max(0) as usize; + } + self.final_range = self.celt.final_range(); + ret } fn silk_to_celt_redundancy( &mut self, delayed: &[f32], frame_size: usize, - end: usize, bytes: usize, out: &mut [u8], - ) -> Result { + ) -> u32 { let ch = self.channels; let n2 = self.sample_rate as usize / 200; let n4 = self.sample_rate as usize / 400; self.celt.reset(); + self.celt.set_start_band(0); + self.celt.set_prediction(0); + self.celt.set_vbr(false); + self.celt.set_bitrate(BITRATE_MAX); let tail = &delayed[ch * (frame_size - n2 - n4)..ch * frame_size]; - self.celt_dummy(&tail[..ch * n4], 120, 0, end, 0, 0); - self.celt_redundancy(&tail[ch * n4..], 240, end, bytes, 0, out) + self.celt_own(&tail[..ch * n4], n4, 2); + let rng = self.celt_own(&tail[ch * n4..], n2, bytes); + out[..bytes].copy_from_slice(&self.redundant.data()[..bytes]); + rng } fn code_redundancy_flags(&mut self, d: &mut Decision, max_data: usize, hybrid: bool) { @@ -1110,7 +1191,6 @@ impl Encoder { cap: usize, d: Decision, ) -> Result<(u8, Payload)> { - self.celt.set_stream_channels(d.stream_channels); match d.mode { Mode::Silk => self.encode_silk(raw, pcm, delayed, frame_size, cap, d), Mode::Hybrid => { @@ -1131,9 +1211,9 @@ impl Encoder { let (toc, frame_48k, end) = self.toc(frame_size, d.bandwidth, d.stream_channels)?; self.fade_celt_input(delayed, frame_size, 1.0); self.stereo_fade_step(delayed, frame_size, d); - let input = if self.align_input { &*delayed } else { pcm }; - let switch = self.prev_mode.is_some_and(|p| p != Mode::Celt); - let n = self.encode_frame(input, frame_48k, end, cap, switch)?; + let input = &*delayed; + let _ = frame_48k; + let n = self.encode_frame(input, frame_size, end, cap, d.stream_channels)?; Ok((toc, Payload::Range(n))) } } @@ -1171,20 +1251,16 @@ impl Encoder { self.code_redundancy_flags(&mut d, max_data_bytes, false); let khz = silk.internal_khz; let end = if khz == 8 { 13 } else { 17 }; + self.celt_setup(Mode::Silk, end, d.stream_channels); + if d.redundancy { + self.celt.set_analysis(&self.info); + } let mut red = [0u8; MAX_REDUNDANCY_BYTES]; let mut red_rng = 0; if d.redundancy && d.celt_to_silk { - let n2 = self.sample_rate as usize / 200; - red_rng = self.celt_redundancy( - &delayed[..self.channels * n2], - 240, - end, - d.redundancy_bytes, - 2, - &mut red, - )?; - self.celt.reset(); + red_rng = self.celt_to_silk_redundancy(delayed, d.redundancy_bytes, &mut red); } + self.celt.set_start_band(17); let mut len = (self.range.tell() as usize).div_ceil(8); self.range.done(); let bust = self.range.tell() as usize > (max_data_bytes - 1) * 8; @@ -1197,13 +1273,8 @@ impl Encoder { } } if d.redundancy && !d.celt_to_silk { - red_rng = self.silk_to_celt_redundancy( - delayed, - frame_size, - end, - d.redundancy_bytes, - &mut red, - )?; + red_rng = + self.silk_to_celt_redundancy(delayed, frame_size, d.redundancy_bytes, &mut red); } let red_len = if d.redundancy { d.redundancy_bytes } else { 0 }; self.final_range = if bust { @@ -1324,7 +1395,7 @@ impl Encoder { result?; let dtx = frames.iter().filter(|f| f.is_empty()).count(); let pad = !self_delimited && !self.vbr && dtx != count; - let (code, size) = self.pack_frames(&frames, max_data, pad, self_delimited)?; + let (code, size) = self.pack_frames(&frames, max_data, pad)?; Ok(((toc & !3) | code, Payload::Silk(size))) } @@ -1333,14 +1404,13 @@ impl Encoder { frames: &[Vec], max_data: usize, pad: bool, - self_delimited: bool, ) -> Result<(u8, usize)> { let count = frames.len(); let len0 = frames[0].len(); let limit = max_data - 1; let lens_differ = frames.iter().any(|f| f.len() != len0); let too_big = || Error::corrupt("opus encode: multi-frame packet exceeds its budget"); - if count == 2 && !self_delimited { + if count == 2 { let size = if lens_differ { len0 + frames[1].len() + 1 + usize::from(len0 >= 252) } else { @@ -1362,7 +1432,7 @@ impl Encoder { return Ok((if lens_differ { 2 } else { 1 }, pos)); } } - let vbr = self_delimited || lens_differ; + let vbr = lens_differ; let size = if vbr { 1 + frames[..count - 1] .iter() @@ -1396,12 +1466,61 @@ impl Encoder { pos += f.len(); } if pad_amount != 0 { - buf[pos..limit].fill(1); + buf[pos..limit].fill(0); pos = limit; } Ok((3, pos)) } + fn frame_len_at(payload: &[u8], pos: usize) -> (usize, usize) { + let b0 = usize::from(payload[pos]); + if b0 < 252 { + (b0, 1) + } else { + (b0 + 4 * usize::from(payload[pos + 1]), 2) + } + } + + fn self_delimited_split(toc: u8, payload: &[u8]) -> (usize, usize) { + match toc & 3 { + 0 => (0, payload.len()), + 1 => (0, payload.len() / 2), + 2 => { + let (len0, used) = Self::frame_len_at(payload, 0); + (used, payload.len() - used - len0) + } + _ => { + let count = usize::from(payload[0] & 0x3F); + let vbr = payload[0] & 0x80 != 0; + let mut pos = 1; + let mut pad = 0; + if payload[0] & 0x40 != 0 { + loop { + let p = usize::from(payload[pos]); + pos += 1; + if p == 255 { + pad += 254; + } else { + pad += p; + break; + } + } + } + if vbr { + let mut sum = 0; + for _ in 1..count { + let (len, used) = Self::frame_len_at(payload, pos); + sum += len; + pos += used; + } + (pos, payload.len() - pos - pad - sum) + } else { + (pos, (payload.len() - pos - pad) / count) + } + } + } + } + /// The TOC byte, the frame size in 48 kHz samples and the CELT end band /// for a frame of `frame_size` input samples per channel. fn toc( @@ -1494,7 +1613,7 @@ impl Encoder { let is_silence = pcm .iter() .take(frame_size * self.channels) - .all(|x| x.abs() <= DTX_SILENCE); + .all(|x| x.abs() <= self.silence_threshold()); let stereo_width = if self.channels == 2 && !self.force_mono { update_stereo_width(&mut self.width_mem, pcm, frame_size, self.sample_rate) } else { @@ -1511,8 +1630,10 @@ impl Encoder { }; self.voice_ratio = (0.5 + 100.0 * (1.0 - prob)).floor() as i32; } - let detected = - (self.bw_detect && self.info.valid).then(|| detected_bandwidth(self.info.bandwidth)); + let detected = self + .info + .valid + .then(|| detected_bandwidth(self.info.bandwidth)); let mut bitrate = (self.bitrate as i32).min(bits_to_bitrate(max_data_bytes as i32 * 8, fs, fsz)); @@ -1522,6 +1643,25 @@ impl Encoder { bitrate = bits_to_bitrate(cbr_bytes * 8, fs, fsz); max_data = cbr_bytes.max(1); } + self.bitrate_bps = bitrate; + if max_data < 3 + || bitrate < 3 * frame_rate * 8 + || (frame_rate < 50 && (max_data * frame_rate < 300 || bitrate < 2400)) + { + return Decision { + mode: self.prev_mode.unwrap_or(Mode::Hybrid), + bandwidth: self.coded_bandwidth, + stream_channels: self.stream_channels, + equiv_rate: 0, + redundancy: false, + redundancy_bytes: 0, + celt_to_silk: false, + to_celt: false, + prefill: Prefill::Off, + to_mono: false, + toc_only: Some(max_data as usize), + }; + } let max_rate = bits_to_bitrate(max_data * 8, fs, fsz); let ve = self.voice_est(); let mut equiv = compute_equiv_rate(bitrate, channels, frame_rate, self.vbr, None, loss); @@ -1735,6 +1875,7 @@ impl Encoder { to_celt, prefill, to_mono, + toc_only: None, } } @@ -1781,7 +1922,22 @@ impl Encoder { /// [`Encoder::encode_float`] from 16-bit samples. pub fn encode(&mut self, pcm: &[i16], frame_size: usize, out: &mut [u8]) -> Result { let float: Vec = pcm.iter().map(|&v| v as f32 * (1.0 / 32768.0)).collect(); - self.encode_float(&float, frame_size, out) + self.lsb_depth = 16; + let r = self.encode_float(&float, frame_size, out); + self.lsb_depth = 24; + r + } + + fn total_buffer(&self) -> usize { + if self.align_input { + self.sample_rate as usize / 250 + } else { + 0 + } + } + + fn silence_threshold(&self) -> f32 { + 1.0 / (1u32 << self.lsb_depth) as f32 } /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716 @@ -1797,24 +1953,7 @@ impl Encoder { Err(e) => Err(e), Ok((toc, payload)) => { let count = payload.first().copied().unwrap_or(0); - let (head, last) = if toc & 3 == 3 { - let count = usize::from(payload[0] & 0x3F); - let mut pos = 1; - let mut sum = 0; - for _ in 1..count { - let b0 = usize::from(payload[pos]); - let (len, used) = if b0 < 252 { - (b0, 1) - } else { - (b0 + 4 * usize::from(payload[pos + 1]), 2) - }; - sum += len; - pos += used; - } - (pos, payload.len() - pos - sum) - } else { - (0, payload.len()) - }; + let (head, last) = Self::self_delimited_split(toc, payload); let mut len = [0u8; 2]; let mut len_bytes = 0; let r = Self::write_frame_len(&mut len, &mut len_bytes, last); @@ -1874,7 +2013,7 @@ impl Encoder { } let max_data_bytes = self.frame_max_data(frame_48k, cap); let budget = max_data_bytes - 1; - self.range.reset(cap); + self.range.reset(budget); let f = self.silk_frame( d, max_data_bytes, @@ -1896,104 +2035,55 @@ impl Encoder { self.switch_ready(&mut d, max_data_bytes, frame_size); } let celt_rate = silk.total_bit_rate - silk.bit_rate; - let hb_gain = 1.0 - 0.5 * (-(celt_rate as f32) / 1024.0).exp2(); + let hb_gain = 1.0 - crate::celt_flp::celt_exp2(-(celt_rate as f32) * (1.0 / 1024.0)); self.fade_celt_input(delayed, frame_size, hb_gain); self.stereo_fade_step(delayed, frame_size, d); - let tell_bytes = (self.range.tell() as usize).div_ceil(8); self.code_redundancy_flags(&mut d, max_data_bytes, true); let end = bandwidth.celt_end_band(); let red_len = if d.redundancy { d.redundancy_bytes } else { 0 }; + let nb_compr = budget - red_len; + self.range.shrink(nb_compr); + self.celt_setup(Mode::Hybrid, end, d.stream_channels); + self.celt.set_analysis(&self.info); + self.celt.set_silk_info(silk.signal_type, silk.offset); let mut red = [0u8; MAX_REDUNDANCY_BYTES]; let mut red_rng = 0; if d.redundancy && d.celt_to_silk { - let n2 = self.sample_rate as usize / 200; - red_rng = self.celt_redundancy( - &delayed[..self.channels * n2], - 240, - end, - red_len, - 2, - &mut red, - )?; - self.celt.reset(); + red_rng = self.celt_to_silk_redundancy(delayed, red_len, &mut red); } - let nb_base = if self.vbr { - cap - } else { - budget.max(tell_bytes + HYBRID_CELT_MIN_BYTES).min(cap) - }; - self.range.shrink(nb_base - red_len); - self.celt.set_constrained_vbr(!self.vbr); - self.celt.set_silk_offset(silk.offset); - let vbr_rate = if self.vbr { - (self.bitrate as i32 - silk.bit_rate).max(501) as u32 - } else { - 0 - }; - let switch = self.prev_mode.is_some_and(|p| p != d.mode); - if switch { - self.celt_prefill(17, end, vbr_rate); - } - let n = self.celt.encode( - &mut self.range, - delayed, - frame_48k, - 17, - end, - vbr_rate, - &self.info, - )?; + self.celt.set_start_band(17); + let celt_rate = self.bitrate_bps - silk.bit_rate; + let n = self.celt_main(Mode::Hybrid, delayed, frame_size, nb_compr, celt_rate); if d.redundancy && !d.celt_to_silk { - red_rng = self.silk_to_celt_redundancy(delayed, frame_size, end, red_len, &mut red)?; + self.range.shrink(n); + red_rng = self.silk_to_celt_redundancy(delayed, frame_size, red_len, &mut red); } - self.final_range = self.range.range() ^ red_rng; + let final_range = self.final_range ^ red_rng; + self.final_range = final_range; self.silk_buf[..n].copy_from_slice(&self.range.data()[..n]); self.silk_buf[n..n + red_len].copy_from_slice(&red[..red_len]); Ok(Payload::Silk(n + red_len)) } - /// Encodes the CELT frame into the internal range coder and returns its - /// byte length. `frame_size` is in 48 kHz samples, `end` is the last coded - /// band, and `cap` bounds the frame (the caller's buffer minus headers). - /// `switch` is set when the previous frame was another mode: the CELT - /// state is reset and primed first, as libopus does. fn encode_frame( &mut self, - pcm: &[f32], + delayed: &[f32], frame_size: usize, end: usize, cap: usize, - switch: bool, + stream_channels: usize, ) -> Result { - let cap = cap.min(MAX_FRAME_BYTES); - if cap < 2 { + let max_data_bytes = self.frame_max_data(frame_size * self.upsample, cap); + if max_data_bytes < 3 { return Err(Error::corrupt( "opus encode: output buffer smaller than the minimum packet", )); } - // One byte per packet goes to the TOC; the CELT layer sees the rest. - let toc_bps = 8 * 48000 / frame_size as u32; - let (budget, vbr_rate) = if self.vbr { - (cap, self.bitrate.saturating_sub(toc_bps).max(500)) - } else { - let b = ((self.bitrate as u64 * frame_size as u64 + 4 * 48000) / (8 * 48000)) as usize; - (b.saturating_sub(1).clamp(2, cap), 0) - }; - self.range.reset(budget); - self.celt.set_constrained_vbr(true); - if switch { - self.celt_prefill(0, end, vbr_rate); - } - let n = self.celt.encode( - &mut self.range, - pcm, - frame_size, - 0, - end, - vbr_rate, - &self.info, - )?; - self.final_range = self.range.range(); + self.range.reset(max_data_bytes - 1); + self.celt_setup(Mode::Celt, end, stream_channels); + self.celt.set_analysis(&self.info); + self.celt.set_start_band(0); + let n = self.celt_main(Mode::Celt, delayed, frame_size, max_data_bytes - 1, 0); Ok(n) } } @@ -2014,8 +2104,6 @@ mod tests { e.set_bitrate(64_000); e.info.valid = true; e.info.bandwidth = 15; - assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full); - e.bw_detect = true; assert_eq!(decided_bandwidth(&mut e), Bandwidth::SuperWide); e.info.bandwidth = 20; assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full); @@ -2074,7 +2162,11 @@ mod tests { let mut last = 0u8; for per_channel in 500..=45_000u32 { e.set_bitrate(per_channel * channels as u32); - let class = match e.decide(&pcm, 960, 1276).mode { + let d = e.decide(&pcm, 960, 1276); + if d.toc_only.is_some() { + continue; + } + let class = match d.mode { Mode::Silk => 0, Mode::Hybrid => 1, Mode::Celt => 2, diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index 7410165b..2289aaf4 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -66,7 +66,7 @@ pub(crate) mod analysis; pub mod celt; -pub mod celt_enc; +pub(crate) mod celt_flp; pub mod encoder; pub mod multistream; pub mod multistream_enc; @@ -79,7 +79,6 @@ pub(crate) mod silk_flp; mod stack_budget; pub use celt::CeltDecoder; -pub use celt_enc::CeltFrameDiag; pub use encoder::{Application, Encoder}; pub use multistream::MultistreamDecoder; pub use multistream_enc::MultistreamEncoder; diff --git a/crates/ec-opus/src/range.rs b/crates/ec-opus/src/range.rs index 8f8491a4..00ba99bc 100644 --- a/crates/ec-opus/src/range.rs +++ b/crates/ec-opus/src/range.rs @@ -611,6 +611,11 @@ impl RangeEncoder { self.nbits_total.saturating_mul(8).saturating_sub(lg) } + /// `enc->nbits_total += bits` (the CELT silence path). + pub fn add_tell(&mut self, bits: i32) { + self.nbits_total = (self.nbits_total as i32 + bits) as u32; + } + /// Declares the rest of the frame used, so [`RangeEncoder::tell`] reports /// the whole frame — the encoder side of the decoder's `skip_to_end`, /// which is what a silent CELT frame does with its remaining bits. diff --git a/crates/ec-opus/src/silk.rs b/crates/ec-opus/src/silk.rs index 27c51c8f..839fe47c 100644 --- a/crates/ec-opus/src/silk.rs +++ b/crates/ec-opus/src/silk.rs @@ -1057,7 +1057,7 @@ pub(crate) fn nlsf2a(nlsf: &[i16], order: usize) -> [i16; MAX_LPC_ORDER] { if maxabs_q12 > 32767 { let maxabs_q12 = maxabs_q12.min(163838); let sc_q16 = - 65471 - ((maxabs_q12 - 32767) << 14) / ((maxabs_q12 * (idx as i32 + 1)) >> 2); + 65470 - ((maxabs_q12 - 32767) << 14) / ((maxabs_q12 * (idx as i32 + 1)) >> 2); bwexpander_32(&mut a32_qa1[..order], sc_q16); } else { break; diff --git a/crates/ec-opus/src/silk_flp/encode.rs b/crates/ec-opus/src/silk_flp/encode.rs index df126c7b..0b7665da 100644 --- a/crates/ec-opus/src/silk_flp/encode.rs +++ b/crates/ec-opus/src/silk_flp/encode.rs @@ -22,6 +22,7 @@ const VARIABLE_HP_MIN_CUTOFF_HZ_Q16: i32 = fix_const(60.0, 16); const VARIABLE_HP_MAX_DELTA_FREQ_Q7: i32 = fix_const(0.4, 7); const VARIABLE_HP_SMTH_COEF1_Q16: i32 = fix_const(0.1, 16); const VAD_NO_ACTIVITY: i32 = 0; +const MAX_FRAME_BYTES: usize = 1275; pub(crate) const TRANSITION_FRAMES: i32 = 5120 / MAX_FRAME_LENGTH_MS as i32; const TRANSITION_NB: usize = 3; @@ -311,8 +312,10 @@ pub(crate) fn encode_frame( find_pred_coefs(st, &mut ctrl, &res_pitch, cond_coding); process_gains(st, &mut ctrl, cond_coding); - let x: Vec = st.x_buf[x_frame..x_frame + frame_length].to_vec(); - lbrr_encode(st, &mut ctrl, &x, cond_coding); + let mut x_copy = [0f32; MAX_FRAME_LENGTH]; + x_copy[..frame_length].copy_from_slice(&st.x_buf[x_frame..x_frame + frame_length]); + let x = &x_copy[..frame_length]; + lbrr_encode(st, &mut ctrl, x, cond_coding); let mut gain_mult_q8 = 256i32; let mut found_lower = false; @@ -337,7 +340,8 @@ pub(crate) fn encode_frame( let prev_lag_copy = st.ec_prev_lag_index; let prev_sig_copy = st.ec_prev_signal_type; let mut snap2 = snap_start; - let mut ec_buf_copy: Vec = Vec::new(); + let mut ec_buf_copy = [0u8; MAX_FRAME_BYTES]; + let mut ec_buf_len = 0usize; let mut iter = 0; loop { @@ -355,7 +359,7 @@ pub(crate) fn encode_frame( st.ec_prev_signal_type = prev_sig_copy; } - run_nsq(st, &ctrl, &x); + run_nsq(st, &ctrl, x); if iter == MAX_ITER && !found_lower { snap2 = enc.snapshot(); @@ -386,7 +390,7 @@ pub(crate) fn encode_frame( if iter == MAX_ITER { if found_lower && (gains_id_cur == gains_id_lower || n_bits > max_bits) { enc.restore(&snap2); - enc.front_write(0, &ec_buf_copy); + enc.front_write(0, &ec_buf_copy[..ec_buf_len]); st.s_nsq = nsq_copy1.clone(); st.s_shape.last_gain_index = last_gain_index_copy2; } @@ -412,7 +416,8 @@ pub(crate) fn encode_frame( if gains_id_cur != gains_id_lower { gains_id_lower = gains_id_cur; snap2 = enc.snapshot(); - ec_buf_copy = enc.front().to_vec(); + ec_buf_len = enc.front().len(); + ec_buf_copy[..ec_buf_len].copy_from_slice(enc.front()); nsq_copy1 = st.s_nsq.clone(); last_gain_index_copy2 = st.s_shape.last_gain_index; } diff --git a/crates/ec-opus/src/silk_flp/opus.rs b/crates/ec-opus/src/silk_flp/opus.rs index b106ec33..d6a0fabb 100644 --- a/crates/ec-opus/src/silk_flp/opus.rs +++ b/crates/ec-opus/src/silk_flp/opus.rs @@ -237,6 +237,7 @@ impl SilkLayer { total_bit_rate: total_bitrate, bit_rate, offset: self.ctl.offset, + signal_type: self.ctl.signal_type, stereo_width_q14: self.ctl.stereo_width_q14, opus_can_switch: self.ctl.opus_can_switch, } @@ -276,6 +277,7 @@ pub(crate) struct SilkResult { pub(crate) total_bit_rate: i32, pub(crate) bit_rate: i32, pub(crate) offset: i32, + pub(crate) signal_type: i32, pub(crate) stereo_width_q14: i32, pub(crate) opus_can_switch: bool, } diff --git a/crates/ec-opus/src/stack_budget.rs b/crates/ec-opus/src/stack_budget.rs index e4ed3676..a0c275e3 100755 --- a/crates/ec-opus/src/stack_budget.rs +++ b/crates/ec-opus/src/stack_budget.rs @@ -68,9 +68,9 @@ //! that holds one is a `Box`, which //! [`the_crate_private_silk_encoders_stay_behind_a_box`] pins by source. //! -//! **Where the number sits.** At 8 KiB with the worst budgeted return at 4,016 -//! bytes ([`Encoder`]), the worst a caller owes is `2 x 4232 = 8,464` bytes -- -//! **0.39%** of a 2 MiB thread -- and the budget sits 2.04x above the +//! **Where the number sits.** At 8 KiB with the worst budgeted return at 2,936 +//! bytes ([`Encoder`]), the worst a caller owes is `2 x 2936 = 5,872` bytes -- +//! **0.28%** of a 2 MiB thread -- and the budget sits 2.79x above the //! incumbent. The pre-fix `Encoder` (87,024 B) is **10.62x over** and the //! pre-fix `Decoder` (7,576 B) sat at 92.5% of it, so the historical defect //! and the near-miss both red by a factor rather than by a hair. @@ -121,7 +121,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ // -- encoder.rs ------------------------------------------------------- ( "Encoder", - Some(4232), + Some(2936), true, "Encoder::new -> Result. Was 87024, 10.62x the budget: six \ inline SILK encoder slots (79176 together) and an inline 3831-byte \ @@ -142,24 +142,6 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ "celt::CeltDecoder::new(channels, downsample) -> Self; also moved by \ value into Decoder::celt", ), - // -- celt_enc.rs ------------------------------------------------------ - ( - "CeltEncoder", - Some(1600), - false, - "celt_enc::CeltEncoder::new -> Self. `pub`, and stored inline in \ - Encoder::celt, but 1600 is 20% of budget and it is the second \ - largest field of a type that is itself budgeted; the crate-private \ - 19744-byte SILK stereo layer is the one this module had to pin", - ), - ( - "CeltFrameDiag", - Some(424), - true, - "celt_enc::last_diag(&self) -> &CeltFrameDiag hands back a \ - reference; the row is here because Encoder::last_celt_diag and \ - Decoder::last_celt_diag name it in their signatures", - ), // -- multistream.rs / multistream_enc.rs ------------------------------ ( "MultistreamDecoder", @@ -234,10 +216,10 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ // -- analysis.rs (crate-private) -------------------------------------- ( "TonalityAnalysis", - Some(2168), + Some(2096), false, "analysis::TonalityAnalysis::new(sample_rate) -> Self, stored \ - INLINE in Encoder::analysis. 2168 is inside the budget and the field \ + INLINE in Encoder::analysis. 2096 is inside the budget and the field \ is reached only through an Encoder that is itself budgeted, so it is \ measured here rather than pinned behind a Box", ), @@ -269,14 +251,6 @@ fn measured_by_name() -> Vec<(&'static str, usize)> { "CeltDecoder", std::mem::size_of::(), ), - ( - "CeltEncoder", - std::mem::size_of::(), - ), - ( - "CeltFrameDiag", - std::mem::size_of::(), - ), ( "MultistreamDecoder", std::mem::size_of::(), @@ -406,7 +380,18 @@ mod tests { const FILES: &[(&str, &str)] = &[ ("analysis.rs", include_str!("analysis.rs")), ("celt.rs", include_str!("celt.rs")), - ("celt_enc.rs", include_str!("celt_enc.rs")), + ("celt_flp/bands.rs", include_str!("celt_flp/bands.rs")), + ("celt_flp/enc.rs", include_str!("celt_flp/enc.rs")), + ("celt_flp/enc_an.rs", include_str!("celt_flp/enc_an.rs")), + ("celt_flp/fft.rs", include_str!("celt_flp/fft.rs")), + ("celt_flp/mod.rs", include_str!("celt_flp/mod.rs")), + ("celt_flp/pitch.rs", include_str!("celt_flp/pitch.rs")), + ( + "celt_flp/quant_bands.rs", + include_str!("celt_flp/quant_bands.rs"), + ), + ("celt_flp/tables.rs", include_str!("celt_flp/tables.rs")), + ("celt_flp/vq.rs", include_str!("celt_flp/vq.rs")), ("encoder.rs", include_str!("encoder.rs")), ("lib.rs", include_str!("lib.rs")), ("multistream.rs", include_str!("multistream.rs")), diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 587ffc79..de6e2be7 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -3027,276 +3027,6 @@ fn per_second_corr(source: &[f32], decoded: &[f32], channels: usize) -> (f64, u3 (min_c, drops) } -// --------------------------------------------------------------------------- -// Per-second diagnostic: reelm@64k encoder decisions vs libopus correlation -// --------------------------------------------------------------------------- -// -// Dumps per-second correlation (ours vs ref) with per-frame CeltFrameDiag to -// lanes/opus-64-r1.seconds.txt. Run with: -// cargo test -p ec-opus --release --test conformance reelm64_persecond_diag -- --ignored --nocapture - -#[test] -#[ignore = "probe: per-second correlation dump for the 64k lane; unblocks when ~/Music/reelm.wav is back in the corpus (hard-asserts src.exists)"] -fn reelm64_persecond_diag() { - let _timing = timing_shared(); - const SECS: f64 = 120.0; - const FRAME: usize = 960; // 20 ms - const CHANNELS: usize = 2; - const MAX_LAG: usize = 2000; - const KBPS: u32 = 64; - - let src = shellexpand("~/Music/reelm.wav"); - assert!(src.exists(), "reelm.wav not found at {}", src.display()); - let source_pcm = ffmpeg_decode_pcm(&src, SECS); - let source_frames = source_pcm.len() / CHANNELS; - let seconds = source_frames as f64 / 48000.0; - - // Reference: ffmpeg libopus - let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes"); - fs::create_dir_all(&lanes_dir).unwrap(); - let scratch = lanes_dir.join("opus-64-r1.scratch.ogg"); - ffmpeg_encode_libopus(&src, KBPS, &scratch, SECS); - let ref_packets = ogg_packets(&fs::read(&scratch).unwrap()); - let ref_payload: Vec = ref_packets - .iter() - .skip(2) // skip opus_head + opus_comment - .filter(|p| !p.is_empty()) - .map(|p| p.len()) - .collect(); - let (ref_dec, ref_ch) = decode_ogg(&scratch); - assert_eq!(ref_ch, CHANNELS); - let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CHANNELS, MAX_LAG); - let _ = fs::remove_file(&scratch); - - // Ours: ec-opus encoder, collecting per-frame diag - let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder"); - enc.set_bitrate(KBPS * 1000); - enc.set_vbr_constrained(true); - let mut dec = Decoder::new(48000, CHANNELS).unwrap(); - let mut out = vec![0u8; 1500]; - let mut buf = vec![0.0f32; 5760 * CHANNELS]; - let mut padded = Vec::new(); - let mut ours_dec = Vec::new(); - let mut diags: Vec = Vec::new(); - let mut ours_bytes: Vec = Vec::new(); - - for block in source_pcm.chunks(FRAME * CHANNELS) { - let block = if block.len() < FRAME * CHANNELS { - padded.clear(); - padded.extend_from_slice(block); - padded.resize(FRAME * CHANNELS, 0.0); - &padded[..] - } else { - block - }; - let len = enc.encode_float(block, FRAME, &mut out).expect("encode"); - let d = enc.last_celt_diag().clone(); - ours_bytes.push(len); - diags.push(d); - let n = dec.decode_float(&out[..len], &mut buf).expect("decode"); - ours_dec.extend_from_slice(&buf[..n * CHANNELS]); - } - let (_, ours_aligned) = align_to_source(&source_pcm, &ours_dec, CHANNELS, MAX_LAG); - - // Per-second correlation for both - let n_frames = (source_frames) - .min(ours_aligned.len() / CHANNELS) - .min(ref_aligned.len() / CHANNELS); - let sec_samples = 48000usize; - let frames_per_sec = sec_samples / FRAME; // 50 - - let mut sec_rows: Vec<(usize, f64, f64, f64)> = Vec::new(); // (sec, corr_ours, corr_ref, gap) - let mut start = 0usize; - let mut sec_idx = 0usize; - while start + sec_samples <= n_frames { - let mut acc_o = 0.0f64; - let mut acc_r = 0.0f64; - for ch in 0..CHANNELS { - let (mut sxy_o, mut sxx_o, mut syy_o) = (0.0f64, 0.0f64, 0.0f64); - let (mut sxy_r, mut sxx_r, mut syy_r) = (0.0f64, 0.0f64, 0.0f64); - for i in 0..sec_samples { - let s = source_pcm[(start + i) * CHANNELS + ch] as f64; - let o = ours_aligned[(start + i) * CHANNELS + ch] as f64; - let r = ref_aligned[(start + i) * CHANNELS + ch] as f64; - sxy_o += s * o; - sxx_o += s * s; - syy_o += o * o; - sxy_r += s * r; - sxx_r += s * s; - syy_r += r * r; - } - if sxx_o > 0.0 && syy_o > 0.0 { - acc_o += sxy_o / (sxx_o * syy_o).sqrt(); - } - if sxx_r > 0.0 && syy_r > 0.0 { - acc_r += sxy_r / (sxx_r * syy_r).sqrt(); - } - } - let co = acc_o / CHANNELS as f64; - let cr = acc_r / CHANNELS as f64; - sec_rows.push((sec_idx, co, cr, cr - co)); - start += sec_samples; - sec_idx += 1; - } - - // Sort by gap descending - let mut sorted = sec_rows.clone(); - sorted.sort_by(|a, b| b.3.partial_cmp(&a.3).unwrap()); - - let mut out_str = String::new(); - out_str.push_str("# reelm@64k per-second diagnostic (r1, current code)\n"); - out_str.push_str("# 120s cap, 20ms frames, VBR constrained, 48kHz stereo\n"); - out_str.push_str(&format!( - "# total frames: ours={} ref={}\n", - diags.len(), - ref_payload.len() - )); - let total_corr_o: f64 = sec_rows.iter().map(|r| r.1).sum::() / sec_rows.len() as f64; - let total_corr_r: f64 = sec_rows.iter().map(|r| r.2).sum::() / sec_rows.len() as f64; - out_str.push_str(&format!( - "# avg corr: ours={:.4} ref={:.4} gap={:+.4}\n\n", - total_corr_o, - total_corr_r, - total_corr_r - total_corr_o - )); - - // Per-second summary table - out_str.push_str("# sec\tcorr_ours\tcorr_ref\tgap\tavg_trim\tdual_n\tint_typ\tavg_B_ours\tavg_B_ref\ttf_chng_n\ttrans_n\n"); - for &(s, co, cr, g) in &sec_rows { - let f0 = s * frames_per_sec; - let f1 = ((s + 1) * frames_per_sec).min(diags.len()); - let sec_diags = &diags[f0..f1.min(diags.len())]; - let avg_trim: f64 = if !sec_diags.is_empty() { - sec_diags.iter().map(|d| d.alloc_trim as f64).sum::() / sec_diags.len() as f64 - } else { - -1.0 - }; - let dual_n = sec_diags.iter().filter(|d| d.dual_stereo).count(); - let int_typ = if !sec_diags.is_empty() { - sec_diags.iter().map(|d| d.intensity).max().unwrap_or(0) - } else { - 0 - }; - let avg_b_o: f64 = if !sec_diags.is_empty() { - sec_diags - .iter() - .map(|d| d.nb_compressed as f64) - .sum::() - / sec_diags.len() as f64 - } else { - 0.0 - }; - let ref_f0 = f0.min(ref_payload.len()); - let ref_f1 = f1.min(ref_payload.len()); - let avg_b_r: f64 = if ref_f1 > ref_f0 { - ref_payload[ref_f0..ref_f1] - .iter() - .map(|&b| b as f64) - .sum::() - / (ref_f1 - ref_f0) as f64 - } else { - 0.0 - }; - // tf_changed: count bands where tf_res != 0 (we don't have tf_res in diag, - // but is_transient tells us if short blocks were used) - let trans_n = sec_diags.iter().filter(|d| d.is_transient).count(); - out_str.push_str(&format!( - "{}\t{:.4}\t{:.4}\t{:+.4}\t{:.1}\t{}\t{}\t{:.0}\t{:.0}\t-\t{}\n", - s, co, cr, g, avg_trim, dual_n, int_typ, avg_b_o, avg_b_r, trans_n - )); - } - - // Top 10 worst seconds with per-frame diag - out_str.push_str("\n# --- 10 worst seconds by gap (per-frame diag) ---\n"); - out_str.push_str("# frame\tt_ms\tB_ours\tB_ref\ttrans\tshort\tintra\tsil\tlm\tstart\tbands\tint\tdual\ttrim\treservoir\tpulses[0..5]\tfine[0..5]\n"); - for &(s, _co, _cr, g) in sorted.iter().take(10) { - let f0 = s * frames_per_sec; - let f1 = ((s + 1) * frames_per_sec).min(diags.len()); - out_str.push_str(&format!("# second {} gap={:+.4}\n", s, g)); - // Index loop kept: the index also drives other lookups or parallel arrays. - #[allow(clippy::needless_range_loop)] - for fi in f0..f1.min(diags.len()) { - let d = &diags[fi]; - let b_ref = ref_payload.get(fi).copied().unwrap_or(0); - let p5: Vec = (0..5).map(|i| format!("{}", d.pulses[i])).collect(); - let f5: Vec = (0..5).map(|i| format!("{}", d.fine_quant[i])).collect(); - out_str.push_str(&format!( - "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", - fi, - fi * 20, - d.nb_compressed, - b_ref, - d.is_transient as u8, - d.short_blocks, - d.intra as u8, - d.silence as u8, - d.lm, - d.start, - d.coded_bands, - d.intensity, - d.dual_stereo as u8, - d.alloc_trim, - d.vbr_reservoir, - p5.join(","), - f5.join(",") - )); - } - out_str.push('\n'); - } - - // Global stats - out_str.push_str("# --- global stats ---\n"); - let trim_hist: Vec<(i32, usize)> = { - let mut h = std::collections::HashMap::new(); - for d in &diags { - *h.entry(d.alloc_trim).or_insert(0) += 1; - } - let mut v: Vec<_> = h.into_iter().collect(); - v.sort(); - v - }; - out_str.push_str(&format!("# alloc_trim histogram: {:?}\n", trim_hist)); - let dual_count = diags.iter().filter(|d| d.dual_stereo).count(); - out_str.push_str(&format!( - "# dual_stereo frames: {}/{}\n", - dual_count, - diags.len() - )); - let trans_count = diags.iter().filter(|d| d.is_transient).count(); - out_str.push_str(&format!( - "# transient frames: {}/{}\n", - trans_count, - diags.len() - )); - let intensity_hist: Vec<(usize, usize)> = { - let mut h = std::collections::HashMap::new(); - for d in &diags { - *h.entry(d.intensity).or_insert(0) += 1; - } - let mut v: Vec<_> = h.into_iter().collect(); - v.sort(); - v - }; - out_str.push_str(&format!("# intensity histogram: {:?}\n", intensity_hist)); - let avg_b_ours: f64 = - diags.iter().map(|d| d.nb_compressed as f64).sum::() / diags.len() as f64; - let avg_b_ref: f64 = - ref_payload.iter().map(|&b| b as f64).sum::() / ref_payload.len() as f64; - out_str.push_str(&format!( - "# avg bytes/frame: ours={:.1} ref={:.1}\n", - avg_b_ours, avg_b_ref - )); - let ours_kbps = ours_bytes.iter().map(|&b| b as f64).sum::() * 8.0 / seconds / 1000.0; - let ref_kbps = ref_payload.iter().map(|&b| b as f64).sum::() * 8.0 / seconds / 1000.0; - out_str.push_str(&format!( - "# realised kbps: ours={:.1} ref={:.1}\n", - ours_kbps, ref_kbps - )); - - let out_path = lanes_dir.join("opus-64-r1.seconds.txt"); - fs::write(&out_path, out_str).unwrap(); - println!("wrote {}", out_path.display()); -} #[test] #[ignore = "library gate: hand-run 14-row sweep, 120s per source, needs ffmpeg libopus and the local ~/Music corpus (~12 min); the reelm@64k dropout that first failed it is fixed per lanes/opus-drop-r2.report.md, so only the corpus dependency keeps it out of the default suite"] fn encoder_library_gate_vs_libopus() { @@ -4672,458 +4402,12 @@ fn opus_compare_err_pinned_against_c() { ); } -// --------------------------------------------------------------------------- -// Spectral-divergence diagnostic: WHERE the 96 kbps err_ratio outlier loses -// its error. Per opus_compare band: mean ln-energy error ours-vs-source and -// ref-vs-source, plus the band's share of the frame error; per source: the -// top-5 worst seconds with what the encoder did there (CeltFrameDiag). -// Run: SWEEP_ONLY=reell,dl8a cargo test -p ec-opus --release \ -// spectral_divergence_vs_libopus -- --ignored --nocapture -// Writes lanes/opus-reell-r1.bands.txt. -// --------------------------------------------------------------------------- - /// libopus CELT band edges (copy of `celt.rs::E_BANDS`, which is pub(crate)): /// band `i` ends at `CELT_EBANDS[i] * 240` Hz at 48 kHz. const CELT_EBANDS: [usize; NBANDS + 1] = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100, ]; -#[test] -#[ignore = "probe: per-window CELT band divergence sweep over the local corpus; a multi-minute ffmpeg report run, not a suite gate"] -fn spectral_divergence_vs_libopus() { - let _timing = timing_shared(); - const SECS: f64 = 120.0; - const FRAME: usize = 960; - const CHANNELS: usize = 2; - const MAX_LAG: usize = 2000; - let kbps_env: u32 = std::env::var("SWEEP_KBPS") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(96); - #[allow(non_snake_case)] - let KBPS: u32 = kbps_env; - - let all: &[(&str, &str)] = &[ - ("reell", "~/Music/reell.mp4"), - ("reelo", "~/Music/reelo.mp3"), - ("nik", "~/Music/reeln.mp4"), - ("dl8a", "~/Downloads/8a3b6d1d19.mp3"), - ("her", "~/Music/reeli.mp3"), - ("reelm", "~/Music/reelm.wav"), - ("hein", "~/Downloads/reelm.mp3"), - ]; - let only: Vec = std::env::var("SWEEP_ONLY") - .unwrap_or_else(|_| "reell,dl8a".to_owned()) - .split(',') - .filter(|s| !s.is_empty()) - .map(|s| s.trim().to_owned()) - .collect(); - let sources: Vec<(String, PathBuf)> = all - .iter() - .filter(|(tag, _)| only.iter().any(|o| o == tag)) - .map(|(tag, p)| (tag.to_string(), shellexpand(p))) - .collect(); - assert!(!sources.is_empty(), "SWEEP_ONLY matched no sources"); - - let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes"); - fs::create_dir_all(&lanes_dir).unwrap(); - let stem = std::env::var("SWEEP_TAG").unwrap_or_else(|_| "opus-reell-r2".to_owned()); - let out_path = lanes_dir.join(format!("{stem}.bands.txt")); - let frames_path = lanes_dir.join(format!("{stem}.frames.txt")); - let scratch = lanes_dir.join("opus-reell-r1.scratch.ogg"); - let mut frames_all = String::new(); - let mut report = String::new(); - - for (tag, src) in &sources { - if !src.exists() { - eprintln!("SKIP {tag}: missing {}", src.display()); - continue; - } - let source_pcm = ffmpeg_decode_pcm(src, SECS); - let source_frames = source_pcm.len() / CHANNELS; - let seconds = source_frames as f64 / 48000.0; - let source_i16 = to_i16(&source_pcm); - - // Reference: ffmpeg libopus at 96k, VBR, decoded by our decoder. - ffmpeg_encode_libopus(src, KBPS, &scratch, SECS); - let ref_bytes = fs::metadata(&scratch) - .map(|m| m.len() as usize) - .unwrap_or(0); - let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0; - let ref_pkts: Vec> = ogg_packets(&fs::read(&scratch).unwrap()) - .into_iter() - .skip(2) - .collect(); - let (ref_dec, ref_ch) = decode_ogg(&scratch); - assert_eq!(ref_ch, CHANNELS, "{tag}: ref not stereo"); - let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CHANNELS, MAX_LAG); - - // Ours at the reference's realised rate, per-frame diag captured. - let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder"); - enc.set_bitrate((ref_kbps * 1000.0).round() as u32); - enc.set_vbr_constrained(true); - let mut dec = Decoder::new(48000, CHANNELS).unwrap(); - let mut packet = vec![0u8; 1500]; - let mut dbuf = vec![0.0f32; 5760 * CHANNELS]; - let mut ours_dec = Vec::new(); - let mut first_pkts: Vec> = Vec::new(); - let mut diags = Vec::new(); - let mut ours_bytes = 0usize; - for block in source_pcm.chunks(FRAME * CHANNELS) { - let mut padded = block.to_vec(); - padded.resize(FRAME * CHANNELS, 0.0); - let len = enc - .encode_float(&padded, FRAME, &mut packet) - .expect("encode"); - if first_pkts.len() < 10 { - first_pkts.push(packet[..len].to_vec()); - } - ours_bytes += len; - let n = dec.decode_float(&packet[..len], &mut dbuf).expect("decode"); - ours_dec.extend_from_slice(&dbuf[..n * CHANNELS]); - diags.push(enc.last_celt_diag().clone()); - } - let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0; - // Transient-frame counts as the decoder sees them: libopus vs ours. - let count_transients = |pkts: &[Vec]| -> (usize, usize) { - let mut d = Decoder::new(48000, CHANNELS).unwrap(); - let mut buf = vec![0.0f32; 5760 * CHANNELS]; - let mut t = 0usize; - for p in pkts { - if d.decode_float(p, &mut buf).is_ok() && d.last_celt_diag().transient { - t += 1; - } - } - (t, pkts.len()) - }; - let (ref_tr, ref_n) = count_transients(&ref_pkts); - let ours_tr = diags.iter().filter(|d| d.is_transient).count(); - eprintln!( - "{tag}@{KBPS}k transient frames: ours {ours_tr}/{} ref {ref_tr}/{ref_n}", - diags.len() - ); - let ours_trim: Vec = ours_dec - .into_iter() - .take(source_frames * CHANNELS) - .collect(); - let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG); - let ours_i16 = to_i16(&ours_aligned); - let ref_i16 = to_i16(&ref_aligned); - - let cmp_frames = (source_i16.len() / CHANNELS) - .min(ours_i16.len() / CHANNELS) - .min(ref_i16.len() / CHANNELS); - let trim = |v: &[i16]| -> Vec { v[..cmp_frames * CHANNELS].to_vec() }; - let s_i = trim(&source_i16); - let o_i = trim(&ours_i16); - let r_i = trim(&ref_i16); - - // Metric totals, per-band shares, per-frame errors. - let (err_o, eb2_o, ef2_o) = opus_compare_err_parts(&s_i, &o_i, CHANNELS); - let (err_r, eb2_r, ef2_r) = opus_compare_err_parts(&s_i, &r_i, CHANNELS); - let corr_o = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS); - let corr_r = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS); - - // Raw per-band energies (no masking): spectral shape in the ln domain. - let nframes = (cmp_frames - WIN_SIZE + WIN_STEP) / WIN_STEP; - let as_f64 = |v: &[i16]| -> Vec { v.iter().map(|&x| x as f64).collect() }; - let mut bands_s = Vec::new(); - let mut bands_o = Vec::new(); - let mut bands_r = Vec::new(); - let mut scratch_ps = Vec::new(); - band_energy( - &as_f64(&s_i), - CHANNELS, - nframes, - &mut Some(&mut bands_s), - &mut scratch_ps, - ); - band_energy( - &as_f64(&o_i), - CHANNELS, - nframes, - &mut Some(&mut bands_o), - &mut scratch_ps, - ); - band_energy( - &as_f64(&r_i), - CHANNELS, - nframes, - &mut Some(&mut bands_r), - &mut scratch_ps, - ); - - report.push_str(&format!( - "\n# source {tag} @{KBPS}k: ours {ours_kbps:.1} kbps, ref {ref_kbps:.1} kbps; \ - corr o={corr_o:.4} r={corr_r:.4}; err o={err_o:.3} r={err_r:.3} ratio={:.2}\n", - err_o / err_r - )); - // opus_compare's err is (mean ef²)^(1/16), so one window can carry a - // whole file. Recompute both sides with the worst k windows dropped - // (same denominator) to separate a broadband gap from an outlier one. - let drop_err = |v: &[f64], k: usize| -> f64 { - let mut w = v.to_vec(); - w.sort_by(|a, b| b.partial_cmp(a).unwrap()); - (w[k..].iter().sum::() / v.len() as f64).powf(1.0 / 16.0) - }; - for k in [0usize, 1, 8, ef2_o.len() / 100] { - let (eo, er) = (drop_err(&ef2_o, k), drop_err(&ef2_r, k)); - report.push_str(&format!( - "# drop-{k} worst windows ({} total): err o={eo:.3} r={er:.3} ratio={:.3}\n", - ef2_o.len(), - eo / er - )); - } - report.push_str( - "# dln = mean ln(E_test/E_src) per channel (neg = energy missing); \ - err = mean |dln|; eb2 = band's mean share of the pre-squared frame error\n", - ); - report.push_str( - "# lo_hz\thi_hz\tdlnL_o\tdlnR_o\tdlnL_r\tdlnR_r\terrL_o\terrR_o\terrL_r\terrR_r\teb2_o\teb2_r\n", - ); - for bi in 0..NBANDS { - let (mut dol, mut dor, mut drl, mut drr) = (0.0f64, 0.0, 0.0, 0.0); - let (mut aol, mut aor, mut arl, mut arr) = (0.0f64, 0.0, 0.0, 0.0); - for xi in 0..nframes { - let e = |b: &Vec, ci: usize| b[(xi * NBANDS + bi) * CHANNELS + ci].ln(); - let (sl, sr) = (e(&bands_s, 0), e(&bands_s, 1)); - let (o_l, o_r) = (e(&bands_o, 0) - sl, e(&bands_o, 1) - sr); - let (r_l, r_r) = (e(&bands_r, 0) - sl, e(&bands_r, 1) - sr); - dol += o_l; - dor += o_r; - drl += r_l; - drr += r_r; - aol += o_l.abs(); - aor += o_r.abs(); - arl += r_l.abs(); - arr += r_r.abs(); - } - let n = nframes as f64; - report.push_str(&format!( - "{}\t{}\t{:+.3}\t{:+.3}\t{:+.3}\t{:+.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3e}\t{:.3e}\n", - BANDS[bi] * 100, - BANDS[bi + 1] * 100, - dol / n, - dor / n, - drl / n, - drr / n, - aol / n, - aor / n, - arl / n, - arr / n, - eb2_o[bi], - eb2_r[bi], - )); - } - - // Top-5 worst seconds by ours per-frame error, with encoder behavior. - let mframes_per_sec = 48000 / WIN_STEP; // 400 metric frames per second - let eframes_per_sec = 48000 / FRAME; // 50 encoder frames per second - let nsecs = cmp_frames / 48000; - let mut sec_score: Vec<(usize, f64)> = (0..nsecs) - .map(|s| { - let (mut sum, mut cnt) = (0.0f64, 0usize); - for xi in s * mframes_per_sec..(s + 1) * mframes_per_sec { - if xi < ef2_o.len() { - sum += ef2_o[xi]; - cnt += 1; - } - } - (s, sum / cnt.max(1) as f64) - }) - .collect(); - sec_score.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); - report.push_str("# top-5 seconds by ours frame error (mean ef²) with encoder diag:\n"); - report.push_str( - "# sec\tscore\ttrans\tcbb_min_hz\tcbb_mean_hz\tint_mean_hz\tdual\tintra\tbits/fr\n", - ); - for &(s, score) in &sec_score[..nsecs.min(5)] { - let f0 = s * eframes_per_sec; - let f1 = ((s + 1) * eframes_per_sec).min(diags.len()); - let fr = &diags[f0.min(f1)..f1]; - let dn = fr.len(); - if dn == 0 { - continue; - } - let transient = fr.iter().filter(|d| d.is_transient).count(); - let dual = fr.iter().filter(|d| d.dual_stereo).count(); - let intra = fr.iter().filter(|d| d.intra).count(); - let cbb_min = fr.iter().map(|d| d.coded_bands).min().unwrap_or(0); - let cbb_mean = fr.iter().map(|d| d.coded_bands).sum::() as f64 / dn as f64; - let int_mean = fr.iter().map(|d| d.intensity).sum::() as f64 / dn as f64; - let bits = fr.iter().map(|d| d.nb_compressed).sum::() as f64 * 8.0 / dn as f64; - report.push_str(&format!( - "{}\t{:.3e}\t{}/{}\t{}\t{}\t{}\t{}/{}\t{}/{}\t{:.0}\n", - s, - score, - transient, - dn, - CELT_EBANDS[cbb_min] * 240, - CELT_EBANDS[cbb_mean as usize] * 240, - CELT_EBANDS[int_mean as usize] * 240, - dual, - dn, - intra, - dn, - bits, - )); - } - - // Whole-file encoder summary for ours. - let dn = diags.len(); - if dn > 0 { - let transient = diags.iter().filter(|d| d.is_transient).count(); - let dual = diags.iter().filter(|d| d.dual_stereo).count(); - let intra = diags.iter().filter(|d| d.intra).count(); - let cbb_min = diags.iter().map(|d| d.coded_bands).min().unwrap_or(0); - let cbb_mean = diags.iter().map(|d| d.coded_bands).sum::() as f64 / dn as f64; - let int_mean = diags.iter().map(|d| d.intensity).sum::() as f64 / dn as f64; - let bits = - diags.iter().map(|d| d.nb_compressed).sum::() as f64 * 8.0 / dn as f64; - report.push_str(&format!( - "# whole file: transient {}/{} dual {}/{} intra {}/{}; coded_bands min {} mean {} Hz; \ - intensity mean {} Hz; bits/frame {:.0}\n", - transient, - dn, - dual, - dn, - intra, - dn, - CELT_EBANDS[cbb_min] * 240, - CELT_EBANDS[cbb_mean as usize] * 240, - CELT_EBANDS[int_mean as usize] * 240, - bits, - )); - } - - // Top-8 worst single metric windows (ours vs ref), with the encoder - // frame each window lands in. - let mut byf: Vec<(usize, f64)> = ef2_o.iter().cloned().enumerate().collect(); - byf.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); - report - .push_str("# top-8 metric windows by ours ef²: offset_ms ours ref | enc frame diag\n"); - for &(xi, v) in &byf[..byf.len().min(8)] { - let rv = if xi < ef2_r.len() { - ef2_r[xi] - } else { - f64::NAN - }; - let ms = xi * WIN_STEP * 1000 / 48000; - let eidx = xi * WIN_STEP / FRAME; - let d = diags.get(eidx); - let ds = d.map(|d| { - format!( - "{}:trans{},intra{},sil{},cbb{}Hz,int{}Hz,bt{}", - eidx, - d.is_transient as u8, - d.intra as u8, - d.silence as u8, - CELT_EBANDS[d.coded_bands] * 240, - CELT_EBANDS[d.intensity] * 240, - d.nb_compressed - ) - }); - report.push_str(&format!( - "+{}ms\t{:.3e}\t{:.3e}\t{}\n", - ms, - v, - rv, - ds.as_deref().unwrap_or("-") - )); - } - - // Startup behavior: first 10 encoder frames. - report - .push_str("# first encoder frames: idx trans intra silence cbb_hz int_hz dual bytes\n"); - for (i, d) in diags.iter().take(10).enumerate() { - report.push_str(&format!( - "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", - i, - d.is_transient as u8, - d.intra as u8, - d.silence as u8, - CELT_EBANDS[d.coded_bands] * 240, - CELT_EBANDS[d.intensity] * 240, - d.dual_stereo as u8, - d.nb_compressed - )); - } - - // Per-window per-band ln-energies for the metric windows 12..=20 - // (+120..+200 ms): the leak's shape, band by band. - report.push_str("# windows 12..=20: win +ms band lo-hi | lnE src/ours/ref, ch L then R\n"); - // WIN_CENTRE= recentres the dump on another window. - let wc: usize = std::env::var("WIN_CENTRE") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(16); - for xi in wc.saturating_sub(4)..=wc + 4 { - if xi >= nframes { - break; - } - for bi in 0..NBANDS { - let e = |b: &Vec, ci: usize| b[(xi * NBANDS + bi) * CHANNELS + ci].ln(); - let (sl, sr) = (e(&bands_s, 0), e(&bands_s, 1)); - let (ol, or_) = (e(&bands_o, 0), e(&bands_o, 1)); - let (rl, rr) = (e(&bands_r, 0), e(&bands_r, 1)); - report.push_str(&format!( - "w{xi} +{}ms b{bi} {}-{}Hz\t{:+8.2} {:+8.2} {:+8.2} | {:+8.2} {:+8.2} {:+8.2}\n", - xi * WIN_STEP * 1000 / 48000, - CELT_EBANDS[bi] * 240, - CELT_EBANDS[bi + 1] * 240, - sl, - ol, - rl, - sr, - or_, - rr, - )); - } - } - - // Decode the first 10 packets of each stream with our decoder: does - // the silence flag survive, and what energies does it leave behind? - frames_all.push_str(&format!( - "# {tag}: first 10 packets through our decoder; energies are log2 old_band_e\n" - )); - for (label, pkts) in [("ours", &first_pkts), ("ref", &ref_pkts)] { - let mut d = Decoder::new(48000, CHANNELS).unwrap(); - let mut ob = vec![0.0f32; 5760 * CHANNELS]; - for (i, p) in pkts.iter().take(10).enumerate() { - let _ = d.decode_float(p, &mut ob).expect("decode"); - let g = d.last_celt_diag(); - frames_all.push_str(&format!( - "{label} {i} bytes={} toc={:#04x} sil{} intra{} trans{} bits{}\n", - p.len(), - p.first().copied().unwrap_or(0), - g.silence as u8, - g.intra as u8, - g.transient as u8, - g.total_bits, - )); - for (ch, name) in [(0usize, 'L'), (1usize, 'R')] { - let band = &g.old_band_e - [ch * ec_opus::celt::NB_BANDS..(ch + 1) * ec_opus::celt::NB_BANDS]; - let e: Vec = band.iter().map(|v| format!("{v:+6.1}")).collect(); - frames_all.push_str(&format!(" {name} {}\n", e.join(" "))); - } - } - } - println!( - "{tag}@{KBPS}k: err o={err_o:.3} r={err_r:.3} ratio={:.2}", - err_o / err_r - ); - } - let _ = fs::remove_file(&scratch); - let header = format!( - "# spectral divergence vs libopus @ {KBPS}k, {SECS:.0}s cap, sources {}\n", - only.join(",") - ); - fs::write(&out_path, header + &report).unwrap(); - fs::write(&frames_path, &frames_all).unwrap(); - println!("wrote {}", out_path.display()); -} - /// Startup leak repro (lane-opus-reell): the first frames of the reell source /// (digital silence then an attack) through the library gate's encoder /// settings and our decoder. Prints per-frame CELT facts; fails if the decode @@ -5150,15 +4434,14 @@ fn celt_silence_then_attack_decodes_bounded() { let pcm_i16 = to_i16(slice); let mut buf = [0u8; 1500]; let n = enc.encode(&pcm_i16, fs, &mut buf).unwrap(); - let ed = enc.last_celt_diag().clone(); let mut out = vec![0f32; fs * ch]; let got = dec.decode_float(&buf[..n], &mut out).unwrap(); let d = dec.last_celt_diag().clone(); let peak = out[..got * ch].iter().fold(0f32, |a, &x| a.max(x.abs())); let emax = d.old_band_e.iter().cloned().fold(f32::MIN, f32::max); println!( - "frame {frame}: in_peak {in_peak:.5} bytes {n} enc(sil {} intra {} trans {}) dec(sil {} intra {} trans {} bits {}) bandE max {emax:.2} peak {peak:.5}", - ed.silence, ed.intra, ed.is_transient, d.silence, d.intra, d.transient, d.total_bits + "frame {frame}: in_peak {in_peak:.5} bytes {n} dec(sil {} intra {} trans {} bits {}) bandE max {emax:.2} peak {peak:.5}", + d.silence, d.intra, d.transient, d.total_bits ); if peak > 4.0 * in_peak.max(1e-4) { bad.push(frame); @@ -5167,118 +4450,6 @@ fn celt_silence_then_attack_decodes_bounded() { assert!(bad.is_empty(), "decode peak >4x input in frames {bad:?}"); } -/// Sample-level view of the reell startup: per-120-sample energy of source, -/// ours (gate path) and libopus reference around the first attack. -#[test] -#[ignore = "probe: HOP_SRC/HOP_MS-driven hop-energy dump around the reell startup attack; returns silently when HOP_SRC is absent, so it can never be a suite gate"] -fn reell_startup_hop_energies() { - let _timing = timing_shared(); - const CH: usize = 2; - // HOP_SRC / HOP_MS pick another source and window centre (diagnostic). - let src_s = std::env::var("HOP_SRC").unwrap_or_else(|_| "~/Music/reell.mp4".into()); - let centre_ms: f64 = std::env::var("HOP_MS") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(42.5); - let src = shellexpand(&src_s); - if !src.exists() { - return; - } - let secs = (centre_ms / 1000.0 + 1.0).max(2.0); - let pcm = ffmpeg_decode_pcm(&src, secs); - let scratch = std::env::temp_dir().join("ec-opus-reell-startup.opus"); - let kbps: u32 = std::env::var("HOP_KBPS") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(96); - ffmpeg_encode_libopus(&src, kbps, &scratch, secs); - let (ref_dec, _) = decode_ogg(&scratch); - let (lag_r, ref_al) = align_to_source(&pcm, &ref_dec, CH, 2000); - let mut enc = Encoder::new(48000, CH, Application::Audio).unwrap(); - enc.set_bitrate(kbps * 1000); - enc.set_vbr_constrained(true); - let mut frames_diag = Vec::new(); - let mut dec = Decoder::new(48000, CH).unwrap(); - let mut out = vec![0u8; 1500]; - let mut buf = vec![0f32; 5760 * CH]; - let mut ours_dec = Vec::new(); - for block in pcm.as_chunks::<{ 960 * CH }>().0 { - let n = enc.encode_float(block, 960, &mut out).unwrap(); - let m = dec.decode_float(&out[..n], &mut buf).unwrap(); - ours_dec.extend_from_slice(&buf[..m * CH]); - let e = enc.last_celt_diag().clone(); - let d = dec.last_celt_diag().clone(); - frames_diag.push(( - n, - e.is_transient, - e.intra, - d.tf_res.clone(), - d.anti_collapse, - )); - } - let (lag_o, ours_al) = align_to_source(&pcm, &ours_dec, CH, 2000); - let first = |v: &[f32]| v.iter().position(|x| x.abs() > 1e-4).map(|i| i / CH); - println!( - "lag ref {lag_r} ours {lag_o}; first>1e-4: src {:?} ours {:?} ref {:?}", - first(&pcm), - first(&ours_al), - first(&ref_al) - ); - let e = |v: &[f32], h: usize| -> f64 { - let a = (h * 120 * CH).min(v.len()); - let b = ((h + 1) * 120 * CH).min(v.len()); - v[a..b].iter().map(|&x| (x as f64) * (x as f64)).sum() - }; - let hc = (centre_ms / 2.5) as usize; - for f in (hc / 8).saturating_sub(1)..=(hc / 8 + 1) { - if let Some((n, t, i, tf, ac)) = frames_diag.get(f) { - println!( - "frame {f} ({:.1} ms): bytes {n} trans {t} intra {i} ac {ac} tf {tf:?}", - f as f64 * 20.0 - ); - } - } - println!("hop(ms)\tsrc\tours\tref"); - for h in hc.saturating_sub(8)..hc + 8 { - println!( - "{:.1}\t{:.3e}\t{:.3e}\t{:.3e}", - h as f64 * 2.5, - e(&pcm, h), - e(&ours_al, h), - e(&ref_al, h) - ); - } -} - -/// Where a lone click lands after a CELT-only fullband roundtrip, relative to -/// the encoder look-ahead (diagnostic for the hybrid alignment tolerance). -#[test] -#[ignore = "probe: self-contained, but prints where a synthetic click lands after a CELT-only roundtrip and asserts nothing; unblocks when that offset is turned into a tolerance assert"] -fn celt_click_peak_offset() { - let _timing = timing_shared(); - let mut click = vec![0f32; 48000]; - let at = 960 * 10 + 300; - click[at] = 0.9; - for bps in [32_000u32, 64_000, 128_000] { - let mut enc = Encoder::new(48000, 1, Application::Audio).unwrap(); - enc.set_mode(Some(ec_opus::Mode::Celt)); - enc.set_bitrate(bps); - let (dec, _) = roundtrip_own(&mut enc, &click, 1, 960); - let p = dec - .iter() - .enumerate() - .max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()) - .unwrap() - .0; - let d = enc.last_celt_diag().clone(); - println!( - "celt click {bps}: peak +{} (lm {})", - p as i64 - at as i64, - d.lm - ); - } -} - /// Per-frame allocation diagnostics for SHORT-block (transient) frames at a /// fixed bitrate: decodes both our stream and libopus's with our decoder, then /// prints per-band mean pulses, fine_quant, alloc_trim, coded_bands, intensity, @@ -5568,258 +4739,6 @@ fn short_block_bits_vs_libopus() { // the same analysis for any row of the library gate, not just her@96. // --------------------------------------------------------------------------- -#[test] -#[ignore = "probe: EC_ERRMAP_SRC-driven per-window error map; returns silently when the named source is missing, so it can never be a suite gate"] -fn err_map_vs_libopus() { - let _timing = timing_shared(); - const SECS: f64 = 120.0; - const FRAME: usize = 960; - const CH: usize = 2; - const HOP: usize = 120; // WIN_STEP: one opus_compare hop = 2.5 ms - const HOPS_PER_WIN: usize = 48_000 / HOP; // 1 s window = 400 hops - let kbps_env: u32 = std::env::var("EC_ERRMAP_KBPS") - .or_else(|_| std::env::var("HER_KBPS")) - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(96); - let tag = std::env::var("EC_ERRMAP_TAG").unwrap_or_else(|_| "opus-her-r1".to_string()); - - let src = shellexpand( - &std::env::var("EC_ERRMAP_SRC").unwrap_or_else(|_| "~/Music/reeli.mp3".to_string()), - ); - if !src.exists() { - eprintln!("SKIP: missing {}", src.display()); - return; - } - let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes"); - fs::create_dir_all(&lanes_dir).unwrap(); - let scratch = lanes_dir.join(format!("{tag}.scratch.ogg")); - let out_path = lanes_dir.join(format!("{tag}.map.txt")); - - let source_pcm = ffmpeg_decode_pcm(&src, SECS); - let source_frames = source_pcm.len() / CH; - let seconds = source_frames as f64 / 48000.0; - let source_i16 = to_i16(&source_pcm); - - // Reference: ffmpeg libopus, VBR — the gate's path. - ffmpeg_encode_libopus(&src, kbps_env, &scratch, SECS); - let ref_bytes = fs::metadata(&scratch) - .map(|m| m.len() as usize) - .unwrap_or(0); - let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0; - let (ref_dec, ref_ch) = decode_ogg(&scratch); - assert_eq!(ref_ch, CH, "ref not stereo"); - let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CH, 2000); - - // Ref per-packet decoder diag, tagged with its first source sample. - struct FD { - sample: usize, - enc: Option, - dec: ec_opus::celt::CeltDecDiag, - } - let ref_pkts: Vec> = ogg_packets(&fs::read(&scratch).unwrap()) - .into_iter() - .skip(2) - .collect(); - let mut ref_fd: Vec = Vec::new(); - { - let mut d = Decoder::new(48000, CH).unwrap(); - let mut buf = vec![0f32; 5760 * CH]; - let mut at = 0usize; - for p in &ref_pkts { - if p.is_empty() { - continue; - } - let toc = ec_opus::Toc::new(p[0]); - let got = d.decode_float(p, &mut buf).unwrap_or(0); - if toc.mode() != Mode::Silk { - ref_fd.push(FD { - sample: at, - enc: None, - dec: d.last_celt_diag().clone(), - }); - } - at += got; - } - } - - // Ours at the reference's realised rate (gate path), with per-frame diags. - let mut enc = Encoder::new(48000, CH, Application::Audio).expect("encoder"); - enc.set_bitrate((ref_kbps * 1000.0).round() as u32); - enc.set_vbr_constrained(true); - let mut dec = Decoder::new(48000, CH).unwrap(); - let mut pkt = vec![0u8; 1500]; - let mut dbuf = vec![0f32; 5760 * CH]; - let mut ours_dec = Vec::new(); - let mut ours_bytes = 0usize; - let mut ours_fd: Vec = Vec::new(); - for (fi, block) in source_pcm.chunks(FRAME * CH).enumerate() { - let mut padded = block.to_vec(); - padded.resize(FRAME * CH, 0.0); - let n = enc.encode_float(&padded, FRAME, &mut pkt).unwrap(); - ours_bytes += n; - let m = dec.decode_float(&pkt[..n], &mut dbuf).unwrap(); - ours_dec.extend_from_slice(&dbuf[..m * CH]); - ours_fd.push(FD { - sample: fi * FRAME, - enc: Some(enc.last_celt_diag().clone()), - dec: dec.last_celt_diag().clone(), - }); - } - let (_, ours_aligned) = align_to_source(&source_pcm, &ours_dec, CH, 2000); - let ours_i16 = to_i16(&ours_aligned); - let ref_i16 = to_i16(&ref_aligned); - let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0; - - // Per-hop ef² for both encoders (gate numerics). - let cmp_frames = (source_i16.len() / CH) - .min(ours_i16.len() / CH) - .min(ref_i16.len() / CH); - let trim = |v: &[i16]| -> Vec { v[..cmp_frames * CH].to_vec() }; - let (err_o, _, hop_o) = opus_compare_err_parts(&trim(&source_i16), &trim(&ours_i16), CH); - let (err_r, _, hop_r) = opus_compare_err_parts(&trim(&source_i16), &trim(&ref_i16), CH); - - // 1 s windows. - let nwin = hop_o.len() / HOPS_PER_WIN; - let sum = |h: &[f64], w: usize| { - h[w * HOPS_PER_WIN..(w + 1) * HOPS_PER_WIN] - .iter() - .sum::() - }; - let tot_o: f64 = hop_o.iter().sum(); - let tot_r: f64 = hop_r.iter().sum(); - let mut wins: Vec<(usize, f64, f64, f64)> = (0..nwin) - .map(|w| (w, sum(&hop_o, w), sum(&hop_r, w), 0.0)) - .collect(); - for w in wins.iter_mut() { - w.3 = w.1 / w.2.max(f64::MIN_POSITIVE); - } - let max_share = wins.iter().map(|w| w.1).fold(0.0f64, f64::max); - - let mut out = String::new(); - out.push_str(&format!( - "# {tag}@{kbps_env}k error map: ref {ref_kbps:.1} ours {ours_kbps:.1} kbps, \ - err o={err_o:.3} r={err_r:.3} ratio {:.3}, {nwin} s windows\n", - err_o / err_r - )); - out.push_str("# window time = first hop of the 1 s bucket; ratio = ours/ref window ef² sum\n"); - out.push_str("# ratio table de-noised: windows with ours share < 1e-6·max excluded\n"); - - let fmt_fd = |f: &FD| -> String { - let e = f.enc.as_ref(); - format!( - "trans{} intra{} trim{} int{} cb{} dual{} | tf_sum {:+3} tf8 {:?} sp{} ac{} bits{}", - f.dec.transient as u8, - f.dec.intra as u8, - f.dec.alloc_trim, - f.dec.intensity, - f.dec.coded_bands, - f.dec.dual_stereo as u8, - f.dec.tf_res.iter().sum::(), - f.dec.tf_res.iter().take(8).collect::>(), - f.dec.spread, - f.dec.anti_collapse as u8, - f.dec.total_bits, - ) + &e - .map(|e| format!(" | ENC sb{} vbr{}", e.short_blocks, e.vbr_reservoir)) - .unwrap_or_default() - }; - let ref_at = |s: usize| -> Option<&FD> { - let i = ref_fd.partition_point(|f| f.sample <= s); - i.checked_sub(1).map(|i| &ref_fd[i]) - }; - - for (label, order) in [ - ("TOP-10 WINDOWS BY ours/ref RATIO", { - let mut v: Vec = (0..nwin) - .filter(|&w| wins[w].1 >= 1e-6 * max_share) - .collect(); - v.sort_by(|&a, &b| wins[b].3.total_cmp(&wins[a].3)); - v - }), - ("TOP-10 WINDOWS BY ours ERROR SHARE", { - let mut v: Vec = (0..nwin).collect(); - v.sort_by(|&a, &b| wins[b].1.total_cmp(&wins[a].1)); - v - }), - ] { - out.push_str(&format!("\n== {label} ==\n")); - for w in order.into_iter().take(10) { - let (wo, wr, ratio) = (wins[w].1, wins[w].2, wins[w].3); - out.push_str(&format!( - "t={:5.0}s: ours {:.3e} ({:4.1}% of ours) ref {:.3e} ({:4.1}% of ref) ratio {:.1}\n", - w as f64, - wo, - 100.0 * wo / tot_o, - wr, - 100.0 * wr / tot_r, - ratio, - )); - // Worst hop in the window: flags from both encoders. - let (hw, he) = (w * HOPS_PER_WIN, (w + 1) * HOPS_PER_WIN); - let hb = hop_o[hw..he] - .iter() - .enumerate() - .max_by(|a, b| a.1.total_cmp(b.1)) - .map(|(i, v)| (hw + i, *v)) - .unwrap(); - let mid = hb.0 * HOP + 240; // centre sample of the hop - let fi = mid / FRAME; - out.push_str(&format!( - " worst hop {:.1} ms (frame {fi}) ours_ef2 {:.3e}\n", - hb.0 as f64 * 2.5, - hb.1 - )); - if let Some(f) = ours_fd.get(fi) { - out.push_str(&format!(" OUR {}/{}: {}\n", fi, f.sample, fmt_fd(f))); - } - if let Some(f) = ref_at(mid) { - out.push_str(&format!(" REF @{}: {}\n", f.sample, fmt_fd(f))); - } - if let (Some(o), Some(r)) = (ours_fd.get(fi), ref_at(mid)) { - let d0: Vec = (0..ec_opus::celt::NB_BANDS) - .map(|b| format!("{:+5.1}", o.dec.old_band_e[b] - r.dec.old_band_e[b])) - .collect(); - let d1: Vec = (0..ec_opus::celt::NB_BANDS) - .map(|b| { - format!( - "{:+5.1}", - o.dec.old_band_e[ec_opus::celt::NB_BANDS + b] - - r.dec.old_band_e[ec_opus::celt::NB_BANDS + b] - ) - }) - .collect(); - out.push_str(&format!( - " Δlog2E L {}\n R {}\n", - d0.join(" "), - d1.join(" ") - )); - } - } - } - - // The single worst ours window, frame by frame: where do decisions diverge. - let worst = (0..nwin) - .max_by(|&a, &b| wins[a].1.total_cmp(&wins[b].1)) - .unwrap(); - out.push_str(&format!( - "\n== WORST WINDOW t={}..{}s, ALL FRAMES (OUR | REF) ==\n", - worst, - worst + 1 - )); - for fi in worst * 50..(worst + 1) * 50 { - let our = ours_fd.get(fi).map(fmt_fd).unwrap_or_else(|| "-".into()); - let rf = ref_at(fi * FRAME + 480) - .map(fmt_fd) - .unwrap_or_else(|| "-".into()); - out.push_str(&format!("f{fi}: OUR {our}\n REF {rf}\n")); - } - - fs::write(&out_path, &out).unwrap(); - let _ = fs::remove_file(&scratch); - println!("wrote {}", out_path.display()); -} - /// Per-frame ours-vs-libopus coded decisions over a window of frames, decoded /// with our own decoder on both sides. FRAME_SRC / FRAME_KBPS / FRAME_FROM / /// FRAME_TO pick the source, rate and frame range (diagnostic). @@ -5987,136 +4906,6 @@ fn frame_decisions_vs_libopus() { const NB_BANDS_DIAG: usize = ec_opus::celt::NB_BANDS; -/// The ported tonality analysis (`crates/ec-opus/src/analysis.rs`) must -/// actually tell speech from music, since `music_prob` is what libopus's mode -/// and bandwidth decisions read. Drives the real entry surface -/// (`Encoder::encode_float`) over 30 s of each gate source and reads the -/// per-frame value back through [`CeltFrameDiag`]. Speech (hein) must land -/// clearly below the two music sources (reell, reelo). -#[test] -#[ignore = "needs the local library sources; run with --ignored"] -fn analysis_music_prob_separates_speech_from_music() { - let _timing = timing_shared(); - const SECS: f64 = 30.0; - const FRAME: usize = 960; - const CHANNELS: usize = 2; - let sources: &[(&str, &str, bool)] = &[ - ("hein", "~/Downloads/reelm.mp3", false), - ("reell", "~/Music/reell.mp4", true), - ("reelo", "~/Music/reelo.mp3", true), - ]; - // Oracle: libopus v1.6 built from source with one fprintf of `analysis_info` - // after `run_analysis()` in `opus_encode_native`, fed the same 30 s of - // ffmpeg-decoded f32 at the same settings, 1498-1499 valid windows each. - // Means of (music_prob, tonality, tonality_slope, activity). - let oracle = |tag: &str| -> Option<[f64; 4]> { - match tag { - "hein" => Some([0.160, 0.155, -0.0876, 0.567]), - "reell" => Some([0.991, 0.362, -0.1680, 0.701]), - "reelo" => Some([0.977, 0.313, -0.1333, 0.735]), - _ => None, - } - }; - let mut means: Vec<(String, bool, f64)> = Vec::new(); - for (tag, path, is_music) in sources { - let src = shellexpand(path); - if !src.exists() { - eprintln!("SKIP {tag}: missing {}", src.display()); - continue; - } - let pcm = ffmpeg_decode_pcm(&src, SECS); - let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder"); - enc.set_bitrate(96_000); - enc.set_vbr_constrained(true); - // The analysis is off unless a consumer needs it (it costs ~25% of the - // encoder); the diagnostics are exactly the "explicitly asked for it" - // case. - enc.set_analysis(true); - let mut out = vec![0u8; 4000]; - let mut sum = [0.0f64; 4]; - let mut n = 0usize; - let mut valid = 0usize; - // Histogram of the detected bandwidth index, which drives - // `opus_encoder.c`'s `detected_bandwidth` clamp. - let mut bw_hist = [0u32; 21]; - for chunk in pcm.as_chunks::<{ FRAME * CHANNELS }>().0 { - enc.encode_float(chunk, FRAME, &mut out).expect("encode"); - let d = enc.last_celt_diag(); - n += 1; - if d.analysis_valid { - valid += 1; - sum[0] += f64::from(d.music_prob); - sum[1] += f64::from(d.tonality); - sum[2] += f64::from(d.tonality_slope); - sum[3] += f64::from(d.activity); - bw_hist[(d.analysis_bandwidth.clamp(0, 20)) as usize] += 1; - } - } - assert!( - valid * 10 > n * 9, - "{tag}: analysis valid on only {valid}/{n} frames" - ); - let bw: Vec = bw_hist - .iter() - .enumerate() - .filter(|&(_, &c)| c > 0) - .map(|(i, c)| format!("{i}:{c}")) - .collect(); - println!("analysis {tag}: bandwidth histogram {}", bw.join(" ")); - let m = sum.map(|v| v / valid as f64); - println!( - "analysis {tag}: music {:.3} tonality {:.3} slope {:.4} activity {:.3} over {valid}/{n} frames (music={is_music})", - m[0], m[1], m[2], m[3] - ); - if let Some(o) = oracle(tag) { - for (i, name) in ["music_prob", "tonality", "tonality_slope", "activity"] - .iter() - .enumerate() - { - assert!( - (m[i] - o[i]).abs() < 0.02, - "{tag} {name}: ours {:.4} vs libopus {:.4}", - m[i], - o[i] - ); - } - } - means.push(((*tag).to_string(), *is_music, m[0])); - } - if means.len() < 2 { - eprintln!("SKIP: fewer than two sources present"); - return; - } - let speech: Vec<_> = means.iter().filter(|m| !m.1).collect(); - let music: Vec<_> = means.iter().filter(|m| m.1).collect(); - for s in &speech { - assert!( - s.2 < 0.5, - "{}: speech music_prob {:.3} should be < 0.5", - s.0, - s.2 - ); - for m in &music { - assert!( - m.2 - s.2 > 0.2, - "{} ({:.3}) does not separate from {} ({:.3}) by 0.2", - m.0, - m.2, - s.0, - s.2 - ); - } - } - for m in &music { - assert!( - m.2 > 0.5, - "{}: music music_prob {:.3} should be > 0.5", - m.0, - m.2 - ); - } -} - // --------------------------------------------------------------------------- // Rate against the target: the CBR default must land within 5% of the bitrate // asked for, on stereo music and speech.