diff --git a/crates/ec-opus/src/analysis.rs b/crates/ec-opus/src/analysis.rs new file mode 100644 index 00000000..fb05aa0c --- /dev/null +++ b/crates/ec-opus/src/analysis.rs @@ -0,0 +1,1645 @@ +//! libopus's tonality analysis (`src/analysis.c`, `src/mlp.c`, `src/mlp_data.c` +//! at v1.6, the release ffmpeg's reference build links) ported to float Rust. +//! +//! The encoder feeds every API frame here *undelayed* — the same input +//! `opus_encode()` hands `run_analysis()`, before the CELT layer's +//! `delay_compensation` — and the analysis maintains its own 30 ms window at +//! 24 kHz (720 samples, [`ANALYSIS_BUF_SIZE`]). Each window yields one +//! [`AnalysisInfo`]: a tonality estimate and its spectral slope, a noisiness +//! and an activity measure, the detected bandwidth, and the music/activity +//! probabilities of a 25-input dense → 24-unit GRU → 2-output MLP whose +//! `i8` weights are copied verbatim from `mlp_data.c` (they are generated from +//! a Keras model upstream and have no closed form). +//! +//! **What is verbatim.** `tonality_analysis()`, `tonality_get_info()`, +//! `run_analysis()`, the 480-point analysis window and DCT tables, the band +//! edges, `silk_resampler_down2_hp()`, `fast_atan2f()`, the `tansig`/`sigmoid` +//! rational approximations, and all seven weight tables. The float build's Q +//! macros (`SHR32`, `MULT16_32_Q15`, `QCONST16`, `SHR64`) are identities and +//! are dropped. +//! +//! **What is omitted.** The fixed-point arms; `MLP_TRAINING`; the +//! `application`/`arch` fields (we have one code path); and libopus's +//! `CELT_SIG_SCALE` (32768) input scaling together with the matching +//! `SCALE_ENER` division by 32768² — they cancel exactly, so this port works +//! in the ±1 sample units our encoder already uses, and every energy-domain +//! constant (`noise_floor`, the `hp_ener` term) is in those same units. +//! `run_analysis()` only runs at 16, 24 and 48 kHz, exactly as libopus's +//! `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; +/// Number of tonality bands (`NB_TBANDS`). +const NB_TBANDS: usize = 18; +/// Analysis buffer: 30 ms at 24 kHz (`ANALYSIS_BUF_SIZE`). +const ANALYSIS_BUF_SIZE: usize = 720; +/// Ring size of the per-window info history (`DETECT_SIZE`). +const DETECT_SIZE: usize = 100; +/// libopus stops counting frames here (`ANALYSIS_COUNT_MAX`). +const ANALYSIS_COUNT_MAX: i32 = 10000; +/// Bands skipped at the top of the tonality sum (`NB_TONAL_SKIP_BANDS`). +const NB_TONAL_SKIP_BANDS: usize = 9; +/// Penalty for switching speech/music during active audio (`TRANSITION_PENALTY`). +const TRANSITION_PENALTY: f32 = 10.0; +/// Bands of the leakage boost vector (`LEAK_BANDS`, celt.h). +pub(crate) const LEAK_BANDS: usize = 19; +/// Analysis MDCT/FFT length (`N` in `tonality_analysis`). +const N: usize = 480; +/// Half of [`N`] (`N2`). +const N2: usize = 240; +const LEAKAGE_OFFSET: f32 = 2.5; +const LEAKAGE_SLOPE: f32 = 2.0; +/// Neurons of the widest MLP layer (`MAX_NEURONS`). +const MAX_NEURONS: usize = 32; +/// `1/128`, the `i8` weight scale (`WEIGHTS_SCALE`). +const WEIGHTS_SCALE: f32 = 1.0 / 128.0; + +/// Tonality band edges in 480-point FFT bins (`tbands`). +const TBANDS: [usize; NB_TBANDS + 1] = [ + 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 136, 160, 192, 240, +]; + +/// One analysis window's result — libopus's `AnalysisInfo`. +/// +/// Every field is meaningless unless [`AnalysisInfo::valid`] is set; the +/// [`Default`] value is libopus's "analysis did not run" state. +// `noisiness`, `max_pitch_ratio` and `leak_boost` are computed by the port but +// have no consumer in this encoder yet: their libopus readers are +// `dynalloc_analysis`'s leakage boost and `run_prefilter`'s gain scaling, +// neither of which is wired. They stay so the port is whole. +#[allow(dead_code)] +#[derive(Clone, Copy, Debug)] +pub(crate) struct AnalysisInfo { + /// Whether the rest of this struct may be read at all. + pub valid: bool, + /// Tonality of the frame, roughly 0 (noise) to 1 (pure tones). + pub tonality: f32, + /// Spectral slope of the per-band tonality, `alloc_trim`'s input. + pub tonality_slope: f32, + /// Mean per-band noisiness. + pub noisiness: f32, + /// Perceptual activity measure, `compute_vbr`'s input. + pub activity: f32, + /// Music probability, look-ahead-smoothed by `tonality_get_info`. + pub music_prob: f32, + /// Lower switching threshold for speech → music. + pub music_prob_min: f32, + /// Upper switching threshold for music → speech. + pub music_prob_max: f32, + /// Raw MLP activity (voice-activity) probability of this window. + pub activity_probability: f32, + /// Energy ratio below/above the maximum pitch bin. + pub max_pitch_ratio: f32, + /// Detected bandwidth as a tonality-band index (0..=20). + pub bandwidth: i32, + /// Per-band spectral-leakage boost, in 1/64 log2 units. + pub leak_boost: [u8; LEAK_BANDS], +} + +impl Default for AnalysisInfo { + fn default() -> Self { + 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], + } + } +} + +/// libopus `fast_atan2f()` — the rational approximation `analysis.c` uses for +/// the per-bin phase, kept because the tonality features are calibrated on it. +fn fast_atan2f(y: f32, x: f32) -> f32 { + const CA: f32 = 0.431_579_74; + const CB: f32 = 0.678_484_04; + const CC: f32 = 0.085_955_42; + const CE: f32 = core::f32::consts::FRAC_PI_2; + let x2 = x * x; + let y2 = y * y; + if x2 + y2 < 1e-18 { + return 0.0; + } + if x2 < y2 { + let den = (y2 + CB * x2) * (y2 + CC * x2); + -x * y * (y2 + CA * x2) / den + if y < 0.0 { -CE } else { CE } + } else { + let den = (x2 + CB * y2) * (x2 + CC * y2); + x * y * (x2 + CA * y2) / den + if y < 0.0 { -CE } else { CE } + - if x * y < 0.0 { -CE } else { CE } + } +} + +/// libopus `tansig_approx()`. +fn tansig_approx(x: f32) -> f32 { + const N0: f32 = 952.528_02; + const N1: f32 = 96.392_357; + const N2C: f32 = 0.608_630_42; + const D0: f32 = 952.723_99; + const D1: f32 = 413.368_01; + const D2: f32 = 11.886_009; + let x2 = x * x; + let num = (N2C * x2 + N1) * x2 + N0; + let den = (D2 * x2 + D1) * x2 + D0; + (num * x / den).clamp(-1.0, 1.0) +} + +/// libopus `sigmoid_approx()`. +fn sigmoid_approx(x: f32) -> f32 { + 0.5 + 0.5 * tansig_approx(0.5 * x) +} + +/// libopus `gemm_accum()`: `out[i] += weights[j*col_stride + i] * x[j]`. +fn gemm_accum(out: &mut [f32], weights: &[i8], rows: usize, cols: usize, col_stride: usize, x: &[f32]) { + for (i, o) in out.iter_mut().take(rows).enumerate() { + for (j, &xj) in x.iter().take(cols).enumerate() { + *o += f32::from(weights[j * col_stride + i]) * xj; + } + } +} + +/// libopus `analysis_compute_dense()`. +fn compute_dense(bias: &[i8], weights: &[i8], nb_inputs: usize, nb_neurons: usize, sigmoid: bool, output: &mut [f32], input: &[f32]) { + for (i, o) in output.iter_mut().take(nb_neurons).enumerate() { + *o = f32::from(bias[i]); + } + gemm_accum(output, weights, nb_neurons, nb_inputs, nb_neurons, input); + for o in output.iter_mut().take(nb_neurons) { + *o *= WEIGHTS_SCALE; + *o = if sigmoid { sigmoid_approx(*o) } else { tansig_approx(*o) }; + } +} + +/// libopus `analysis_compute_gru()`. +fn compute_gru(bias: &[i8], weights: &[i8], recur: &[i8], nb_inputs: usize, nb_neurons: usize, state: &mut [f32], input: &[f32]) { + let n = nb_neurons; + let stride = 3 * n; + let mut z = [0.0f32; MAX_NEURONS]; + let mut r = [0.0f32; MAX_NEURONS]; + let mut h = [0.0f32; MAX_NEURONS]; + let mut tmp = [0.0f32; MAX_NEURONS]; + for i in 0..n { + z[i] = f32::from(bias[i]); + } + gemm_accum(&mut z, weights, n, nb_inputs, stride, input); + gemm_accum(&mut z, recur, n, n, stride, state); + for zi in z.iter_mut().take(n) { + *zi = sigmoid_approx(WEIGHTS_SCALE * *zi); + } + for i in 0..n { + r[i] = f32::from(bias[n + i]); + } + gemm_accum(&mut r, &weights[n..], n, nb_inputs, stride, input); + gemm_accum(&mut r, &recur[n..], n, n, stride, state); + for ri in r.iter_mut().take(n) { + *ri = sigmoid_approx(WEIGHTS_SCALE * *ri); + } + for i in 0..n { + h[i] = f32::from(bias[2 * n + i]); + tmp[i] = state[i] * r[i]; + } + gemm_accum(&mut h, &weights[2 * n..], n, nb_inputs, stride, input); + gemm_accum(&mut h, &recur[2 * n..], n, n, stride, &tmp); + for i in 0..n { + state[i] = z[i] * state[i] + (1.0 - z[i]) * tansig_approx(WEIGHTS_SCALE * h[i]); + } +} + +/// libopus `silk_resampler_down2_hp()` in float: halves the rate and returns +/// the energy of the discarded high band. +fn resampler_down2_hp(s: &mut [f32; 3], out: &mut [f32], input: &[f32]) -> f32 { + let len2 = input.len() / 2; + let mut hp_ener = 0.0f32; + for k in 0..len2 { + let in32 = input[2 * k]; + let y = in32 - s[0]; + let x = 0.607_437_1 * y; + let mut out32 = s[0] + x; + s[0] = in32 + x; + let mut out32_hp = out32; + + let in32 = input[2 * k + 1]; + let y = in32 - s[1]; + let x = 0.150_63 * y; + out32 = out32 + s[1] + x; + s[1] = in32 + x; + + let y = -in32 - s[2]; + let x = 0.150_63 * y; + out32_hp = out32_hp + s[2] + x; + s[2] = -in32 + x; + + hp_ener += out32_hp * out32_hp; + out[k] = 0.5 * out32; + } + hp_ener +} + +/// The rolling state of the tonality analysis — libopus's +/// `TonalityAnalysisState`, minus the fixed-point and `arch` fields. +#[derive(Clone, Debug)] +pub(crate) struct TonalityAnalysis { + /// Native input rate in Hz; 16000, 24000 or 48000 when enabled. + fs: u32, + /// False for rates libopus never analyses (below 16 kHz). + enabled: bool, + fft: Fft15, + angle: Vec, + d_angle: Vec, + d2_angle: Vec, + inmem: Vec, + mem_fill: usize, + prev_band_tonality: [f32; NB_TBANDS], + prev_tonality: f32, + prev_bandwidth: i32, + e: [[f32; NB_TBANDS]; NB_FRAMES], + log_e: [[f32; NB_TBANDS]; NB_FRAMES], + low_e: [f32; NB_TBANDS], + high_e: [f32; NB_TBANDS], + mean_e: [f32; NB_TBANDS + 1], + mem: [f32; 32], + cmean: [f32; 8], + std: [f32; 9], + e_tracker: f32, + low_e_count: f32, + e_count: usize, + count: i32, + analysis_offset: i32, + write_pos: usize, + read_pos: usize, + read_subframe: i32, + hp_ener_accum: f32, + initialized: bool, + rnn_state: [f32; MAX_NEURONS], + downmix_state: [f32; 3], + info: Vec, +} + +impl TonalityAnalysis { + /// A state for `sample_rate` Hz input. Rates below 16 kHz are accepted but + /// disabled, mirroring libopus's `st->Fs >= 16000` guard on `run_analysis`. + pub(crate) fn new(sample_rate: u32) -> 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], + inmem: vec![0.0; ANALYSIS_BUF_SIZE], + mem_fill: 0, + prev_band_tonality: [0.0; NB_TBANDS], + prev_tonality: 0.0, + prev_bandwidth: 0, + e: [[0.0; NB_TBANDS]; NB_FRAMES], + log_e: [[0.0; NB_TBANDS]; NB_FRAMES], + low_e: [0.0; NB_TBANDS], + high_e: [0.0; NB_TBANDS], + mean_e: [0.0; NB_TBANDS + 1], + mem: [0.0; 32], + cmean: [0.0; 8], + std: [0.0; 9], + e_tracker: 0.0, + low_e_count: 0.0, + e_count: 0, + count: 0, + analysis_offset: 0, + write_pos: 0, + read_pos: 0, + read_subframe: 0, + hp_ener_accum: 0.0, + initialized: false, + rnn_state: [0.0; MAX_NEURONS], + downmix_state: [0.0; 3], + info: vec![AnalysisInfo::default(); DETECT_SIZE], + } + } + + /// 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; + } + + /// libopus `run_analysis()`: consumes one API frame of interleaved input + /// (`frame_size` samples per channel at the native rate) and returns the + /// [`AnalysisInfo`] that applies to it. + pub(crate) fn run(&mut self, pcm: &[f32], frame_size: usize, channels: usize, lsb_depth: i32) -> AnalysisInfo { + let mut info = AnalysisInfo::default(); + if !self.enabled || frame_size == 0 { + return info; + } + let fs = self.fs as i32; + let mut analysis_frame_size = frame_size as i32; + analysis_frame_size -= analysis_frame_size & 1; + // Avoid overflow/wrap-around of the analysis buffer. + analysis_frame_size = analysis_frame_size.min((DETECT_SIZE as i32 - 5) * fs / 50); + let mut pcm_len = analysis_frame_size - self.analysis_offset; + let mut offset = self.analysis_offset; + while pcm_len > 0 { + self.tonality_analysis(pcm, (fs / 50).min(pcm_len), offset, channels, lsb_depth); + offset += fs / 50; + pcm_len -= fs / 50; + } + self.analysis_offset = analysis_frame_size - frame_size as i32; + self.get_info(&mut info, frame_size as i32); + info + } + + /// libopus `downmix_and_resample()` for the float API: mono-downmixes + /// `subframe` native samples starting at `offset` into 24 kHz `y`, + /// returning the high-band energy the 48 kHz decimator throws away. + fn downmix_and_resample(&mut self, pcm: &[f32], y: &mut [f32], subframe: usize, offset: usize, channels: usize) -> f32 { + if subframe == 0 { + return 0.0; + } + let (subframe, offset) = match self.fs { + 48000 => (subframe * 2, offset * 2), + 16000 => (subframe * 2 / 3, offset * 2 / 3), + _ => (subframe, offset), + }; + let mut tmp = vec![0.0f32; subframe]; + for (j, t) in tmp.iter_mut().enumerate() { + let base = (j + offset) * channels; + let mut acc = pcm[base]; + for c in 1..channels { + acc += pcm[base + c]; + } + *t = if channels == 2 { 0.5 * acc } else { acc }; + } + match self.fs { + 48000 => { + let mut st = self.downmix_state; + let e = resampler_down2_hp(&mut st, y, &tmp); + self.downmix_state = st; + e + } + 16000 => { + let mut tmp3x = vec![0.0f32; 3 * subframe]; + for j in 0..subframe { + tmp3x[3 * j] = tmp[j]; + tmp3x[3 * j + 1] = tmp[j]; + tmp3x[3 * j + 2] = tmp[j]; + } + let mut st = self.downmix_state; + resampler_down2_hp(&mut st, y, &tmp3x); + self.downmix_state = st; + 0.0 + } + _ => { + y[..subframe].copy_from_slice(&tmp); + 0.0 + } + } + } + + /// libopus `tonality_analysis()`: appends one 20 ms chunk of input and, + /// once 30 ms have accumulated, emits one window's [`AnalysisInfo`]. + #[allow(clippy::needless_range_loop)] + fn tonality_analysis(&mut self, pcm: &[f32], len: i32, offset: i32, channels: usize, lsb_depth: i32) { + if !self.initialized { + self.mem_fill = 240; + self.initialized = true; + } + let alpha = 1.0 / (10.min(1 + self.count)) as f32; + let alpha_e = 1.0 / (25.min(1 + self.count)) as f32; + // Noise floor related decay for bandwidth detection: -2.2 dB/second. + let mut alpha_e2 = 1.0 / (100.min(1 + self.count)) as f32; + if self.count <= 1 { + alpha_e2 = 1.0; + } + // len and offset are converted to the 24 kHz analysis domain. + let (len, offset) = match self.fs { + 48000 => (len / 2, offset / 2), + 16000 => (3 * len / 2, 3 * offset / 2), + _ => (len, offset), + }; + let (len, offset) = (len as usize, offset as usize); + + let take = len.min(ANALYSIS_BUF_SIZE - self.mem_fill); + let mut chunk = vec![0.0f32; take]; + let ener = self.downmix_and_resample(pcm, &mut chunk, take, offset, channels); + self.inmem[self.mem_fill..self.mem_fill + take].copy_from_slice(&chunk); + self.hp_ener_accum += ener; + if self.mem_fill + len < ANALYSIS_BUF_SIZE { + self.mem_fill += len; + return; + } + let hp_ener = self.hp_ener_accum; + let write = self.write_pos; + self.write_pos += 1; + if self.write_pos >= DETECT_SIZE { + self.write_pos -= DETECT_SIZE; + } + + let is_silence = self.inmem.iter().all(|&v| v == 0.0); + + let mut re = vec![0.0f32; N]; + let mut im = vec![0.0f32; N]; + for i in 0..N2 { + let w = ANALYSIS_WINDOW[i]; + re[i] = w * self.inmem[i]; + im[i] = w * self.inmem[N2 + i]; + re[N - i - 1] = w * self.inmem[N - i - 1]; + im[N - i - 1] = w * self.inmem[N + N2 - i - 1]; + } + self.inmem.copy_within(ANALYSIS_BUF_SIZE - 240.., 0); + let remaining = len - (ANALYSIS_BUF_SIZE - self.mem_fill); + let mut chunk = vec![0.0f32; remaining]; + let ener = self.downmix_and_resample(pcm, &mut chunk, remaining, offset + ANALYSIS_BUF_SIZE - self.mem_fill, channels); + self.inmem[240..240 + remaining].copy_from_slice(&chunk); + self.hp_ener_accum = ener; + self.mem_fill = 240 + remaining; + if is_silence { + // On silence, copy the previous analysis. + let prev = (write + DETECT_SIZE - 1) % DETECT_SIZE; + self.info[write] = self.info[prev]; + 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; + } + self.fft.inverse(&mut re, &mut im); + let s = 1.0 / N as f32; + for i in 0..N { + re[i] *= s; + im[i] *= -s; + } + if re[0].is_nan() { + self.info[write].valid = false; + return; + } + + let mut tonality = [0.0f32; N2]; + let mut tonality2 = [0.0f32; N2]; + let mut noisiness = [0.0f32; N2]; + let pi4 = (core::f64::consts::PI.powi(4)) as f32; + for i in 1..N2 { + let x1r = re[i] + re[N - i]; + let x1i = im[i] - im[N - i]; + 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 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 d_angle2 = angle2 - angle; + let d2_angle2 = d_angle2 - d_angle; + + let mut mod1 = d2_angle - d2_angle.round_ties_even(); + noisiness[i] = mod1.abs(); + mod1 *= mod1; + mod1 *= mod1; + + let mut mod2 = d2_angle2 - d2_angle2.round_ties_even(); + noisiness[i] += mod2.abs(); + mod2 *= mod2; + mod2 *= mod2; + + let avg_mod = 0.25 * (self.d2_angle[i] + mod1 + 2.0 * mod2); + // This introduces an extra delay of 2 frames in the detection. + tonality[i] = 1.0 / (1.0 + 40.0 * 16.0 * pi4 * avg_mod) - 0.015; + // No delay on this detection, but it's less reliable. + tonality2[i] = 1.0 / (1.0 + 40.0 * 16.0 * pi4 * mod2) - 0.015; + + self.angle[i] = angle2; + self.d_angle[i] = d_angle2; + self.d2_angle[i] = mod2; + } + for i in 2..N2 - 1 { + let tt = tonality2[i].min(tonality2[i - 1].max(tonality2[i + 1])); + tonality[i] = 0.9 * tonality[i].max(tt - 0.1); + } + let mut frame_tonality = 0.0f32; + let mut max_frame_tonality = 0.0f32; + let activity; + let mut frame_noisiness = 0.0f32; + let mut frame_stationarity = 0.0f32; + if self.count == 0 { + for b in 0..NB_TBANDS { + self.low_e[b] = 1e10; + self.high_e[b] = -1e10; + } + } + let mut relative_e = 0.0f32; + let mut frame_loudness = 0.0f32; + let mut band_log2 = [0.0f32; NB_TBANDS + 1]; + let mut log_e = [0.0f32; NB_TBANDS]; + let bin_e = |re: &[f32], im: &[f32], i: usize| { + re[i] * re[i] + re[N - i] * re[N - i] + im[i] * im[i] + im[N - i] * im[N - i] + }; + // The energy of the very first band is special because of DC. + { + let x1r = 2.0 * re[0]; + let x2r = 2.0 * im[0]; + let mut e = x1r * x1r + x2r * x2r; + for i in 1..4 { + e += bin_e(&re, &im, i); + } + band_log2[0] = 0.5 * 1.442_695 * (e + 1e-10).ln(); + } + let mut band_tonality = [0.0f32; NB_TBANDS]; + let mut slope = 0.0f32; + for b in 0..NB_TBANDS { + let (mut e, mut te, mut ne) = (0.0f32, 0.0f32, 0.0f32); + for i in TBANDS[b]..TBANDS[b + 1] { + let be = bin_e(&re, &im, i); + e += be; + te += be * tonality[i].max(0.0); + ne += be * 2.0 * (0.5 - noisiness[i]); + } + // Check for extreme band energies that could cause NaNs later. + if !(e < 1e9) || e.is_nan() { + self.info[write].valid = false; + return; + } + 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 * 1.442_695 * (e + 1e-10).ln(); + self.log_e[self.e_count][b] = log_e[b]; + if self.count == 0 { + self.high_e[b] = log_e[b]; + self.low_e[b] = log_e[b]; + } + if self.high_e[b] > self.low_e[b] + 7.5 { + if self.high_e[b] - log_e[b] > log_e[b] - self.low_e[b] { + self.high_e[b] -= 0.01; + } else { + self.low_e[b] += 0.01; + } + } + if log_e[b] > self.high_e[b] { + self.high_e[b] = log_e[b]; + self.low_e[b] = (self.high_e[b] - 15.0).max(self.low_e[b]); + } else if log_e[b] < self.low_e[b] { + self.low_e[b] = log_e[b]; + self.high_e[b] = (self.low_e[b] + 15.0).min(self.high_e[b]); + } + relative_e += (log_e[b] - self.low_e[b]) / (1e-5 + (self.high_e[b] - self.low_e[b])); + + let mut l1 = 0.0f32; + let mut l2 = 0.0f32; + for i in 0..NB_FRAMES { + 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()); + stationarity *= stationarity; + stationarity *= stationarity; + frame_stationarity += stationarity; + band_tonality[b] = (te / (1e-15 + e)).max(stationarity * self.prev_band_tonality[b]); + frame_tonality += band_tonality[b]; + if b >= NB_TBANDS - NB_TONAL_SKIP_BANDS { + frame_tonality -= band_tonality[b - NB_TBANDS + NB_TONAL_SKIP_BANDS]; + } + max_frame_tonality = + max_frame_tonality.max((1.0 + 0.03 * (b as f32 - NB_TBANDS as f32)) * frame_tonality); + slope += band_tonality[b] * (b as f32 - 8.0); + self.prev_band_tonality[b] = band_tonality[b]; + } + + let mut leakage_from = [0.0f32; NB_TBANDS + 1]; + let mut leakage_to = [0.0f32; NB_TBANDS + 1]; + leakage_from[0] = band_log2[0]; + leakage_to[0] = band_log2[0] - LEAKAGE_OFFSET; + for b in 1..NB_TBANDS + 1 { + let leak_slope = LEAKAGE_SLOPE * (TBANDS[b] - TBANDS[b - 1]) as f32 / 4.0; + leakage_from[b] = (leakage_from[b - 1] + leak_slope).min(band_log2[b]); + leakage_to[b] = (leakage_to[b - 1] - leak_slope).max(band_log2[b] - LEAKAGE_OFFSET); + } + for b in (0..NB_TBANDS - 1).rev() { + let leak_slope = LEAKAGE_SLOPE * (TBANDS[b + 1] - TBANDS[b]) as f32 / 4.0; + leakage_from[b] = (leakage_from[b + 1] + leak_slope).min(leakage_from[b]); + leakage_to[b] = (leakage_to[b + 1] - leak_slope).max(leakage_to[b]); + } + let mut leak_boost = [0u8; LEAK_BANDS]; + 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; + } + + let mut spec_variability = 0.0f32; + for i in 0..NB_FRAMES { + let mut mindist = 1e15f32; + for j in 0..NB_FRAMES { + let mut dist = 0.0f32; + for k in 0..NB_TBANDS { + let tmp = self.log_e[i][k] - self.log_e[j][k]; + dist += tmp * tmp; + } + if j != i { + mindist = mindist.min(dist); + } + } + spec_variability += mindist; + } + spec_variability = (spec_variability / NB_FRAMES as f32 / NB_TBANDS as f32).sqrt(); + let mut bandwidth_mask = 0.0f32; + let mut bandwidth = 0i32; + let mut max_e = 0.0f32; + let mut noise_floor = 5.7e-4 / (1 << 0.max(lsb_depth - 8)) as f32; + noise_floor *= noise_floor; + let mut below_max_pitch = 0.0f32; + let mut above_max_pitch = 0.0f32; + let mut is_masked = [false; NB_TBANDS + 1]; + for b in 0..NB_TBANDS { + let band_start = TBANDS[b]; + let band_end = TBANDS[b + 1]; + let mut e = 0.0f32; + for i in band_start..band_end { + e += bin_e(&re, &im, i); + } + max_e = max_e.max(e); + if band_start < 64 { + below_max_pitch += e; + } else { + above_max_pitch += e; + } + self.mean_e[b] = ((1.0 - alpha_e2) * self.mean_e[b]).max(e); + let em = e.max(self.mean_e[b]); + let width = (band_end - band_start) as f32; + if e * 1e9 > max_e && (em > 3.0 * noise_floor * width || e > noise_floor * width) { + bandwidth = b as i32 + 1; + } + is_masked[b] = e < if self.prev_bandwidth >= b as i32 + 1 { 0.01 } else { 0.05 } * bandwidth_mask; + bandwidth_mask = (0.05 * bandwidth_mask).max(e); + } + // The last two bands have no spectrum, only the energy above 12 kHz. + if self.fs == 48000 { + let b = NB_TBANDS; + let e = hp_ener * (1.0 / (60.0 * 60.0)); + let noise_ratio = if self.prev_bandwidth == 20 { 10.0 } else { 30.0 }; + above_max_pitch += e; + self.mean_e[b] = ((1.0 - alpha_e2) * self.mean_e[b]).max(e); + let em = e.max(self.mean_e[b]); + if em > 3.0 * noise_ratio * noise_floor * 160.0 || e > noise_ratio * noise_floor * 160.0 { + bandwidth = 20; + } + is_masked[b] = e < if self.prev_bandwidth == 20 { 0.01 } else { 0.05 } * bandwidth_mask; + } + let max_pitch_ratio = if above_max_pitch > below_max_pitch { + below_max_pitch / above_max_pitch + } else { + 1.0 + }; + // Resampling aliasing can leave energy in the first band being cut. + if bandwidth == 20 && is_masked[NB_TBANDS] { + bandwidth -= 2; + } else if bandwidth > 0 && bandwidth <= NB_TBANDS as i32 && is_masked[bandwidth as usize - 1] { + bandwidth -= 1; + } + if self.count <= 2 { + bandwidth = 20; + } + frame_loudness = 20.0 * frame_loudness.log10(); + 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 { + self.low_e_count += alpha_e; + } + + let mut bfcc = [0.0f32; 8]; + let mut mid_e = [0.0f32; 8]; + for i in 0..8 { + let mut sum = 0.0f32; + for b in 0..16 { + sum += DCT_TABLE[i * 16 + b] * log_e[b]; + } + bfcc[i] = sum; + } + for i in 0..8 { + let mut sum = 0.0f32; + for b in 0..16 { + sum += DCT_TABLE[i * 16 + b] * 0.5 * (self.high_e[b] + self.low_e[b]); + } + mid_e[i] = sum; + } + + frame_stationarity /= NB_TBANDS as f32; + relative_e /= NB_TBANDS as f32; + if self.count < 10 { + relative_e = 0.5; + } + frame_noisiness /= NB_TBANDS as f32; + activity = frame_noisiness + (1.0 - frame_noisiness) * relative_e; + let mut frame_tonality = max_frame_tonality / (NB_TBANDS - NB_TONAL_SKIP_BANDS) as f32; + frame_tonality = frame_tonality.max(self.prev_tonality * 0.8); + self.prev_tonality = frame_tonality; + slope /= 8.0 * 8.0; + let tonality_slope = slope; + + self.e_count = (self.e_count + 1) % NB_FRAMES; + self.count = (self.count + 1).min(ANALYSIS_COUNT_MAX); + + let mut features = [0.0f32; 25]; + for i in 0..4 { + features[i] = -0.122_99 * (bfcc[i] + self.mem[i + 24]) + + 0.491_95 * (self.mem[i] + self.mem[i + 16]) + + 0.696_93 * self.mem[i + 8] + - 1.434_9 * self.cmean[i]; + } + for i in 0..4 { + self.cmean[i] = (1.0 - alpha) * self.cmean[i] + alpha * bfcc[i]; + } + for i in 0..4 { + features[4 + i] = + 0.632_46 * (bfcc[i] - self.mem[i + 24]) + 0.316_23 * (self.mem[i] - self.mem[i + 16]); + } + for i in 0..3 { + features[8 + i] = 0.534_52 * (bfcc[i] + self.mem[i + 24]) + - 0.267_26 * (self.mem[i] + self.mem[i + 16]) + - 0.534_52 * self.mem[i + 8]; + } + if self.count > 5 { + for i in 0..9 { + self.std[i] = (1.0 - alpha) * self.std[i] + alpha * features[i] * features[i]; + } + } + for i in 0..4 { + features[i] = bfcc[i] - mid_e[i]; + } + for i in 0..8 { + self.mem[i + 24] = self.mem[i + 16]; + self.mem[i + 16] = self.mem[i + 8]; + self.mem[i + 8] = self.mem[i]; + self.mem[i] = bfcc[i]; + } + for i in 0..9 { + features[11 + i] = self.std[i].sqrt() - STD_FEATURE_BIAS[i]; + } + features[18] = spec_variability - 0.78; + features[20] = frame_tonality - 0.154_723; + features[21] = activity - 0.724_643; + features[22] = frame_stationarity - 0.743_717; + features[23] = tonality_slope + 0.069_216; + features[24] = self.low_e_count - 0.067_930; + + let mut layer_out = [0.0f32; MAX_NEURONS]; + let mut frame_probs = [0.0f32; 2]; + compute_dense(&LAYER0_BIAS, &LAYER0_WEIGHTS, 25, 32, false, &mut layer_out, &features); + let mut state = self.rnn_state; + compute_gru(&LAYER1_BIAS, &LAYER1_WEIGHTS, &LAYER1_RECUR_WEIGHTS, 32, 24, &mut state, &layer_out); + self.rnn_state = state; + compute_dense(&LAYER2_BIAS, &LAYER2_WEIGHTS, 24, 2, true, &mut frame_probs, &self.rnn_state); + + self.prev_bandwidth = bandwidth; + self.info[write] = AnalysisInfo { + valid: true, + tonality: frame_tonality, + tonality_slope, + noisiness: frame_noisiness, + activity, + music_prob: frame_probs[0], + music_prob_min: 0.0, + music_prob_max: 0.0, + activity_probability: frame_probs[1], + max_pitch_ratio, + bandwidth, + leak_boost, + }; + } + + /// libopus `tonality_get_info()`: picks the window that covers the frame + /// about to be coded and smooths `music_prob` over the look-ahead. + fn get_info(&mut self, info_out: &mut AnalysisInfo, len: i32) { + let mut pos = self.read_pos; + let mut curr_lookahead = self.write_pos as i32 - self.read_pos as i32; + if curr_lookahead < 0 { + curr_lookahead += DETECT_SIZE as i32; + } + self.read_subframe += len / (self.fs as i32 / 400); + while self.read_subframe >= 8 { + self.read_subframe -= 8; + self.read_pos += 1; + } + if self.read_pos >= DETECT_SIZE { + self.read_pos -= DETECT_SIZE; + } + // On long frames, look at the second analysis window rather than the first. + if len > self.fs as i32 / 50 && pos != self.write_pos { + pos += 1; + if pos == DETECT_SIZE { + pos = 0; + } + } + if pos == self.write_pos { + pos = (pos + DETECT_SIZE - 1) % DETECT_SIZE; + } + let pos0 = pos; + *info_out = self.info[pos]; + if !info_out.valid { + return; + } + let mut tonality_max = info_out.tonality; + let mut tonality_avg = info_out.tonality; + let mut tonality_count = 1; + // Look at the neighbouring frames and pick the largest bandwidth found. + let mut bandwidth_span = 6; + for _ in 0..3 { + pos += 1; + if pos == DETECT_SIZE { + pos = 0; + } + if pos == self.write_pos { + break; + } + tonality_max = tonality_max.max(self.info[pos].tonality); + tonality_avg += self.info[pos].tonality; + tonality_count += 1; + info_out.bandwidth = info_out.bandwidth.max(self.info[pos].bandwidth); + bandwidth_span -= 1; + } + pos = pos0; + for _ in 0..bandwidth_span { + pos = (pos + DETECT_SIZE - 1) % DETECT_SIZE; + if pos == self.write_pos { + break; + } + info_out.bandwidth = info_out.bandwidth.max(self.info[pos].bandwidth); + } + info_out.tonality = (tonality_avg / tonality_count as f32).max(tonality_max - 0.2); + + let mut mpos = pos0; + let mut vpos = pos0; + // With enough look-ahead, compensate for the ~5-frame delay in the + // music prob and the ~1 frame delay in the VAD prob. + if curr_lookahead > 15 { + mpos = (mpos + 5) % DETECT_SIZE; + vpos = (vpos + 1) % DETECT_SIZE; + } + // The "badness function" minimisation of libopus's comment block: what + // is computed is the threshold at which switching now is optimal. + let mut prob_min = 1.0f32; + let mut prob_max = 0.0f32; + let vad_prob = self.info[vpos].activity_probability; + let mut prob_count = 0.1f32.max(vad_prob); + let mut prob_avg = 0.1f32.max(vad_prob) * self.info[mpos].music_prob; + loop { + mpos = (mpos + 1) % DETECT_SIZE; + if mpos == self.write_pos { + break; + } + vpos = (vpos + 1) % DETECT_SIZE; + if vpos == self.write_pos { + break; + } + let pos_vad = self.info[vpos].activity_probability; + prob_min = ((prob_avg - TRANSITION_PENALTY * (vad_prob - pos_vad)) / prob_count).min(prob_min); + prob_max = ((prob_avg + TRANSITION_PENALTY * (vad_prob - pos_vad)) / prob_count).max(prob_max); + prob_count += 0.1f32.max(pos_vad); + prob_avg += 0.1f32.max(pos_vad) * self.info[mpos].music_prob; + } + info_out.music_prob = prob_avg / prob_count; + prob_min = (prob_avg / prob_count).min(prob_min); + prob_max = (prob_avg / prob_count).max(prob_max); + prob_min = prob_min.max(0.0); + prob_max = prob_max.min(1.0); + + // Without enough look-ahead, do our best to make a decent decision. + if curr_lookahead < 10 { + let mut pmin = prob_min; + let mut pmax = prob_max; + pos = pos0; + for _ in 0..(self.count - 1).min(15) { + pos = (pos + DETECT_SIZE - 1) % DETECT_SIZE; + pmin = pmin.min(self.info[pos].music_prob); + pmax = pmax.max(self.info[pos].music_prob); + } + // Bias against switching on active audio. + pmin = 0.0f32.max(pmin - 0.1 * vad_prob); + pmax = 1.0f32.min(pmax + 0.1 * vad_prob); + prob_min += (1.0 - 0.1 * curr_lookahead as f32) * (pmin - prob_min); + prob_max += (1.0 - 0.1 * curr_lookahead as f32) * (pmax - prob_max); + } + info_out.music_prob_min = prob_min; + info_out.music_prob_max = prob_max; + } +} + +// --------------------------------------------------------------------------- +// Tables copied verbatim from libopus v1.6: `src/analysis.c` (`dct_table`, +// `analysis_window`, `std_feature_bias`) and `src/mlp_data.c` (the Keras- +// generated `i8` weights of the 25x32 dense layer, the 24-unit GRU and the +// 2-output sigmoid layer). They have no closed form; do not "simplify" them. +// --------------------------------------------------------------------------- + +static DCT_TABLE: [f32; 128] = [ + 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, + 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, + 0.351851, 0.338330, 0.311806, 0.273300, 0.224292, 0.166664, 0.102631, 0.034654, + -0.034654, -0.102631, -0.166664, -0.224292, -0.273300, -0.311806, -0.338330, -0.351851, + 0.346760, 0.293969, 0.196424, 0.068975, -0.068975, -0.196424, -0.293969, -0.346760, + -0.346760, -0.293969, -0.196424, -0.068975, 0.068975, 0.196424, 0.293969, 0.346760, + 0.338330, 0.224292, 0.034654, -0.166664, -0.311806, -0.351851, -0.273300, -0.102631, + 0.102631, 0.273300, 0.351851, 0.311806, 0.166664, -0.034654, -0.224292, -0.338330, + 0.326641, 0.135299, -0.135299, -0.326641, -0.326641, -0.135299, 0.135299, 0.326641, + 0.326641, 0.135299, -0.135299, -0.326641, -0.326641, -0.135299, 0.135299, 0.326641, + 0.311806, 0.034654, -0.273300, -0.338330, -0.102631, 0.224292, 0.351851, 0.166664, + -0.166664, -0.351851, -0.224292, 0.102631, 0.338330, 0.273300, -0.034654, -0.311806, + 0.293969, -0.068975, -0.346760, -0.196424, 0.196424, 0.346760, 0.068975, -0.293969, + -0.293969, 0.068975, 0.346760, 0.196424, -0.196424, -0.346760, -0.068975, 0.293969, + 0.273300, -0.166664, -0.338330, 0.034654, 0.351851, 0.102631, -0.311806, -0.224292, + 0.224292, 0.311806, -0.102631, -0.351851, -0.034654, 0.338330, 0.166664, -0.273300, +]; + +static ANALYSIS_WINDOW: [f32; 240] = [ + 0.000043, 0.000171, 0.000385, 0.000685, 0.001071, 0.001541, 0.002098, 0.002739, + 0.003466, 0.004278, 0.005174, 0.006156, 0.007222, 0.008373, 0.009607, 0.010926, + 0.012329, 0.013815, 0.015385, 0.017037, 0.018772, 0.020590, 0.022490, 0.024472, + 0.026535, 0.028679, 0.030904, 0.033210, 0.035595, 0.038060, 0.040604, 0.043227, + 0.045928, 0.048707, 0.051564, 0.054497, 0.057506, 0.060591, 0.063752, 0.066987, + 0.070297, 0.073680, 0.077136, 0.080665, 0.084265, 0.087937, 0.091679, 0.095492, + 0.099373, 0.103323, 0.107342, 0.111427, 0.115579, 0.119797, 0.124080, 0.128428, + 0.132839, 0.137313, 0.141849, 0.146447, 0.151105, 0.155823, 0.160600, 0.165435, + 0.170327, 0.175276, 0.180280, 0.185340, 0.190453, 0.195619, 0.200838, 0.206107, + 0.211427, 0.216797, 0.222215, 0.227680, 0.233193, 0.238751, 0.244353, 0.250000, + 0.255689, 0.261421, 0.267193, 0.273005, 0.278856, 0.284744, 0.290670, 0.296632, + 0.302628, 0.308658, 0.314721, 0.320816, 0.326941, 0.333097, 0.339280, 0.345492, + 0.351729, 0.357992, 0.364280, 0.370590, 0.376923, 0.383277, 0.389651, 0.396044, + 0.402455, 0.408882, 0.415325, 0.421783, 0.428254, 0.434737, 0.441231, 0.447736, + 0.454249, 0.460770, 0.467298, 0.473832, 0.480370, 0.486912, 0.493455, 0.500000, + 0.506545, 0.513088, 0.519630, 0.526168, 0.532702, 0.539230, 0.545751, 0.552264, + 0.558769, 0.565263, 0.571746, 0.578217, 0.584675, 0.591118, 0.597545, 0.603956, + 0.610349, 0.616723, 0.623077, 0.629410, 0.635720, 0.642008, 0.648271, 0.654508, + 0.660720, 0.666903, 0.673059, 0.679184, 0.685279, 0.691342, 0.697372, 0.703368, + 0.709330, 0.715256, 0.721144, 0.726995, 0.732807, 0.738579, 0.744311, 0.750000, + 0.755647, 0.761249, 0.766807, 0.772320, 0.777785, 0.783203, 0.788573, 0.793893, + 0.799162, 0.804381, 0.809547, 0.814660, 0.819720, 0.824724, 0.829673, 0.834565, + 0.839400, 0.844177, 0.848895, 0.853553, 0.858151, 0.862687, 0.867161, 0.871572, + 0.875920, 0.880203, 0.884421, 0.888573, 0.892658, 0.896677, 0.900627, 0.904508, + 0.908321, 0.912063, 0.915735, 0.919335, 0.922864, 0.926320, 0.929703, 0.933013, + 0.936248, 0.939409, 0.942494, 0.945503, 0.948436, 0.951293, 0.954072, 0.956773, + 0.959396, 0.961940, 0.964405, 0.966790, 0.969096, 0.971321, 0.973465, 0.975528, + 0.977510, 0.979410, 0.981228, 0.982963, 0.984615, 0.986185, 0.987671, 0.989074, + 0.990393, 0.991627, 0.992778, 0.993844, 0.994826, 0.995722, 0.996534, 0.997261, + 0.997902, 0.998459, 0.998929, 0.999315, 0.999615, 0.999829, 0.999957, 1.000000, +]; + +static STD_FEATURE_BIAS: [f32; 9] = [ + 5.684947, 3.475288, 1.770634, 1.599784, 3.773215, + 2.163313, 1.260756, 1.116868, 1.918795, +]; + +static LAYER0_WEIGHTS: [i8; 800] = [ + -30, -9, 2, -12, 5, -1, 8, 9, + 9, 8, -13, 18, -17, -34, -5, 17, + -11, 0, -4, 10, 2, 10, 15, -8, + 2, -1, 0, 5, 13, -3, -16, 1, + -5, 3, 7, -28, -13, 6, 36, -3, + 19, -60, -17, -28, 7, -11, -30, -7, + 2, -42, -21, -3, 6, -22, 33, -9, + 7, -30, 21, -14, 24, -11, -20, -18, + -5, -12, 12, -49, -50, -49, 16, 9, + -37, -1, 9, 34, -13, -31, -31, 12, + 16, 44, -42, 2, -9, 8, -18, -6, + 9, 36, 19, 11, 13, 12, -21, 3, + -28, -12, 3, 33, 25, -14, 11, 1, + -94, -39, 18, -12, -11, -15, -7, 49, + 52, 10, -43, 9, 57, 8, 21, -6, + 14, -15, 44, -8, 7, -30, -13, -2, + -9, 25, -2, -127, 18, -11, -52, 26, + -27, 27, 10, -10, 7, 43, 6, -24, + 41, 10, -18, -27, 10, 17, 9, 10, + -17, -10, 20, -6, 22, 55, 35, -80, + 36, 25, -24, -36, 15, 9, -19, 88, + 19, 64, -51, -35, 17, 0, -7, 41, + -16, 27, 4, 15, -1, 18, -16, 47, + -39, -54, -8, 13, -25, -20, 102, -18, + -5, 44, 11, -28, 71, 2, -51, -5, + 5, 2, -83, -9, -29, 8, 21, -53, + 58, -37, -7, 13, 38, 9, 34, -1, + -41, 21, 4, -24, -36, -33, -21, 32, + 75, -2, 1, -68, -1, 47, -29, 32, + 20, 12, -65, -87, 5, 16, -12, 24, + 40, 15, 7, 19, -26, -17, 17, 6, + -2, -37, -30, -9, 32, -127, -39, 0, + -31, -27, 4, -22, 23, -6, -77, 35, + -61, 32, -37, -24, 13, -11, -1, -40, + -3, 17, -7, 13, 11, 59, -19, 10, + 6, -18, 0, 13, 3, -6, -23, 19, + 11, -17, 13, -1, -80, 40, -53, 69, + -29, -54, 0, -4, 33, -25, -2, 38, + 35, 36, -15, 46, 2, -13, -16, -8, + -8, 12, -24, -9, -55, -5, -9, 32, + 11, 7, 12, -18, -10, -86, -38, 54, + 37, -25, 18, -43, 7, -27, -27, -54, + 13, 9, 22, 70, 6, 35, -7, 23, + -15, -44, -6, 7, -66, -85, 32, 40, + -19, -9, -7, 12, -15, 7, 2, 6, + -35, 11, 28, 0, 26, 14, 1, 1, + 4, 12, 18, 35, 22, -18, -3, 14, + -1, 7, 14, -8, -14, -3, 4, -3, + -19, -7, -1, -25, -27, 25, -26, -2, + 33, -22, -27, -25, 4, -9, 7, 21, + 26, -30, 10, -9, -20, 11, 27, 10, + 5, -18, 14, -4, 2, -17, -5, -7, + -9, -13, 15, 29, 1, -10, -16, -10, + 35, 36, -7, -22, -44, 17, 30, 22, + 21, -1, 22, -11, 32, -8, -7, 5, + -10, 5, 30, -20, 29, -20, -34, 12, + -4, -6, 6, -13, 10, -5, -68, -1, + 24, 9, 19, -24, -64, 31, 19, 27, + -26, 75, -45, 41, 39, -42, 8, 6, + 23, -30, 16, -25, 30, 34, 8, -38, + -3, 18, 16, -31, 22, -4, -9, 1, + 20, 9, 38, -32, 0, -45, 0, -6, + -13, 11, -25, -32, -22, 31, -24, -11, + -11, -4, -4, 20, -34, 22, 20, 9, + -25, 27, -5, 28, -29, 29, 6, 21, + -6, -18, 54, 4, -46, 23, 21, -14, + -31, 36, -41, -24, 4, 22, 10, 11, + 7, 36, -32, -13, -52, -17, 24, 28, + -37, -36, -1, 24, 9, -38, 35, 48, + 18, 2, -1, 45, 10, 39, 24, -38, + 13, 8, -16, 8, 25, 11, 7, -29, + -11, 7, 20, -30, -38, -45, 14, -18, + -28, -9, 65, 61, 22, -53, -38, -16, + 36, 46, 20, -39, 32, -61, -6, -6, + -36, -33, -18, -28, 56, 101, 45, 11, + -28, -23, -29, -61, 20, -47, 2, 48, + 27, -17, 1, 40, 1, 3, -51, 15, + 35, 28, 22, 35, 53, -61, -29, 12, + -6, -21, 10, 3, -20, 2, -25, 1, + -6, 31, 11, -3, 1, -10, -52, 6, + 126, -105, 122, 127, -128, 127, 127, -128, + 127, 108, 12, 127, 48, -128, -36, -128, + 127, 127, -128, -128, 127, 89, -128, 127, + -128, -128, -128, 127, 127, -128, -128, -93, + -82, 20, 125, 65, -82, 127, 38, -74, + 81, 88, -88, 79, 51, -47, -111, -26, + 14, 83, -88, -112, 24, 35, -101, 98, + -99, -48, -45, 46, 83, -60, -79, 45, + -20, -41, 9, 4, 52, 54, 93, -10, + 4, 13, 3, 123, 6, 94, -111, -69, + -14, -31, 10, 12, 53, -79, -11, -21, + -2, -44, -72, 92, 65, -57, 56, -38, + 127, -56, -128, 127, 127, -128, 86, 117, + -75, -128, 127, -19, -99, -112, 127, -128, + 127, -48, 114, 118, -128, -128, 117, -17, + -6, 121, -128, 127, -128, 82, 54, -106, + 127, 127, -33, 100, -39, -23, 18, -78, + -34, -29, -1, -30, 127, -26, 127, -128, + 126, -128, 27, -23, -79, -120, -127, 127, + 72, 66, 29, 7, -66, -56, -117, -128, +]; + +static LAYER0_BIAS: [i8; 32] = [ + 51, -16, 1, 13, -5, -6, -16, -7, + 11, -6, 106, 26, 28, -14, 21, -29, + 7, 18, -18, -17, 21, -17, -9, 20, + -25, -3, -34, 48, 11, -13, -31, -20, +]; + +static LAYER1_WEIGHTS: [i8; 2304] = [ + 22, -1, -7, 7, 29, -27, -31, -17, + -13, 33, 44, -8, 11, 33, 24, 78, + 15, 19, 30, -2, -24, 5, 49, 5, + 36, 29, -14, -11, -48, -33, 21, -42, + -38, -12, 55, -37, 54, -8, 1, 36, + 17, 0, 51, 31, 59, 7, -12, 53, + 4, 32, -14, 48, 5, -10, -16, -8, + 1, -16, -56, -24, -6, 18, -2, 23, + 6, 46, -6, -10, 20, 35, -44, -15, + -49, 36, 16, 5, -7, -79, -67, 12, + 70, -3, -79, -54, -85, -24, 47, -22, + 33, 21, 69, -1, 11, 22, 14, -16, + -16, -22, -28, -11, 11, -41, 31, -26, + -33, -19, -4, 27, 32, -50, 5, -10, + -38, -22, -8, 35, -31, 1, -41, -15, + -11, 44, 28, -17, -41, -23, 17, 2, + -23, -26, -13, -13, -17, 6, 14, -31, + -25, 9, -19, 39, -8, 4, 31, -1, + -45, -11, -28, -92, -46, -15, 21, 118, + -22, 45, -51, 11, -20, -20, -15, 13, + -21, -97, -29, -32, -23, -42, 94, 1, + 23, -8, 63, -3, -46, 19, -26, 32, + -40, -74, -26, 26, -4, -13, 30, -20, + -30, -25, -14, -31, -45, -43, 4, -60, + -48, -12, -34, 2, 2, 3, 13, 15, + 11, 16, 5, 46, -9, -55, -16, -57, + 29, 14, 38, -50, -2, -44, -11, -8, + 52, -27, -38, -7, 20, 47, 17, -59, + 0, 47, 46, -63, 35, -17, 19, 33, + 68, -19, 2, 15, -16, 28, -16, -103, + 26, -35, 47, -39, -60, 30, 31, -23, + -52, -13, 116, 47, -25, 30, 40, 30, + -22, 2, 12, -27, -18, 31, -10, 27, + -8, -66, 12, 14, 4, -26, -28, -13, + 3, 13, -26, -51, 37, 5, 2, -21, + 47, 3, 13, 25, -41, -27, -8, -4, + 5, -76, -33, 28, 10, 9, -46, -74, + 19, 28, 25, 31, 54, -55, 68, 38, + -24, -32, 2, 4, 68, 11, -1, 99, + 5, 16, -2, -74, 40, 26, -26, 33, + 31, -1, -68, 14, -6, 25, 9, 29, + 60, 61, 7, -7, 0, -24, 7, 77, + 4, -1, 16, -7, 13, -15, -19, 28, + -31, -24, -16, 37, 24, 13, 30, 10, + -30, 11, 11, -10, 22, 60, 28, 45, + -3, -40, -62, -5, -102, 9, -32, -27, + -54, 21, 15, -5, 37, -43, -11, 37, + -19, 47, -64, -128, -27, -114, 21, -66, + 59, 46, -3, -12, -87, -9, 4, 19, + -113, -36, 78, 57, -26, -38, -77, -10, + 6, 6, -75, 25, -97, -11, 33, -46, + 1, 13, -21, -33, -20, 16, -6, -3, + -11, -4, -27, 38, 8, -41, -2, -33, + 18, 19, -26, 1, -29, -22, -4, -14, + -55, -11, -80, -3, 11, 34, 90, 51, + 11, 17, 43, 36, 127, -32, 29, 103, + 9, 27, 13, 64, 56, 70, -14, 3, + -12, 10, 37, 3, 12, -22, -10, 46, + 28, 10, 20, 26, -24, 18, 9, 7, + 14, 34, -5, -7, 31, -14, -56, 11, + -18, -8, -17, -7, -10, -40, 10, -33, + -32, -43, 5, 9, 11, -4, 10, 50, + -12, -5, 46, 9, 7, 1, 11, 15, + 91, -17, 7, -50, 23, 6, -30, -99, + 0, -17, 14, 8, -10, -25, -30, -69, + -62, 31, 127, 114, -23, 101, -5, -54, + -6, -22, 7, -56, 39, 18, -29, 0, + 46, 8, -79, 4, -21, 18, -32, 62, + -12, -8, -12, -58, 31, -32, 17, 6, + -24, 25, 24, 9, -4, -19, 45, 6, + 17, -14, 5, -27, 16, -4, -41, 25, + -36, 5, 15, 12, 50, 27, 25, 23, + -44, -69, -9, -19, -48, -8, 4, 12, + -6, 13, -19, -30, -36, 26, 37, -1, + -3, -30, -42, -14, -10, -20, 26, -54, + -27, -44, 4, 73, -26, 90, 32, -69, + -29, -16, 3, 103, 15, -17, 37, 24, + -23, -31, 33, -37, -64, 25, 13, -81, + -28, -32, 27, 5, -35, -23, 15, -22, + 19, -7, 9, 30, 19, -23, 27, -13, + 43, 29, -29, -6, 9, -40, -33, -33, + -32, 9, 11, -48, -8, -23, -52, 46, + 17, -22, -42, 35, -15, -41, 16, 34, + 31, -42, -19, -11, 55, 7, -39, 89, + -11, -33, 20, -14, 22, 32, 3, -17, + -6, 14, 34, 1, 55, -21, -90, -8, + 18, 27, 13, -29, 21, 15, -33, -51, + -9, -11, 4, -16, -18, 23, -4, -4, + 48, 1, 7, 29, -14, -12, -16, 17, + 35, 8, 0, -7, -2, 9, 8, 17, + -6, 53, -32, -21, -50, 5, 99, -60, + -5, -53, 10, -31, 12, -5, 7, 80, + 36, 18, -31, 9, 98, 36, -63, -35, + 4, -13, -28, -24, 28, -13, 18, 16, + -1, -18, -34, 10, 20, 7, 4, 29, + 11, 25, -7, 36, 14, 45, 24, 1, + -16, 30, 6, 35, -6, -11, -24, 13, + -1, 27, 39, 20, 48, -11, -4, -13, + 28, 11, -31, -18, 31, -29, 22, -2, + -20, -16, 5, 30, -12, -28, -3, 93, + -16, 23, 18, -29, 6, -54, -37, 28, + -3, -3, -47, -3, -36, -55, -3, 41, + -10, 47, -2, 23, 42, -7, -71, -27, + 83, -64, 7, -24, 8, 26, -17, 15, + 12, 31, -30, -38, -13, -33, -56, 4, + -17, 20, 18, 1, -30, -5, -6, -31, + -14, -37, 0, 22, 10, -30, 37, -17, + 18, 6, 5, 23, -36, -32, 14, 18, + -13, -61, -52, -69, 44, -30, 16, 18, + -4, -25, 14, 81, 26, -8, -23, -59, + 52, -104, 17, 119, -32, 26, 17, 1, + 23, 45, 29, -64, -57, -14, 73, 21, + -13, -13, 9, -68, -7, -52, 3, 24, + -39, 44, -15, 27, 14, 19, -9, -28, + -11, 5, 3, -34, -2, 2, 22, -6, + -23, 4, 3, 13, -22, -13, -10, -18, + 29, 6, 44, -13, -24, -8, 2, 30, + 14, 43, 6, 17, -73, -6, -7, 20, + -80, -7, -7, -28, 15, -69, -38, -5, + -100, -35, 15, -79, 23, 29, -18, -27, + 21, -66, -37, 8, -22, -39, 48, 4, + -13, 1, -9, 11, -29, 22, 6, -49, + 32, -14, 47, -18, -4, 44, -52, -74, + 43, 30, 23, -14, 5, 0, -27, 4, + -7, 10, -4, 10, 1, -16, 11, -18, + -2, -5, 2, -11, 0, -20, -4, 38, + 74, 59, 39, 64, -10, 26, -3, -40, + -68, 3, -30, -51, 8, -19, -27, -46, + 51, 52, 54, 36, 90, 92, 14, 13, + -5, 0, 16, -62, 16, 11, -47, -37, + -6, -5, 21, 54, -57, 32, 42, -6, + 62, -9, 16, 21, 24, 9, -10, -4, + 33, 50, 13, -15, 1, -35, -48, 18, + -11, -17, -67, -13, 21, 38, -44, 36, + -16, 29, 17, 5, -10, 18, 17, -32, + 2, 8, 22, -56, -15, -32, 40, 43, + 19, 46, -7, -100, -96, 19, 53, 24, + 21, -26, -48, -101, -82, 61, 38, -85, + -28, -34, -1, 63, -5, -5, 39, 39, + -38, 32, -12, -28, 20, 40, -8, 2, + 31, 12, -35, -13, 20, -25, 30, 8, + 3, -13, -9, -20, 2, -13, 24, 37, + -10, 33, 6, 20, -16, -24, -6, -6, + -19, -5, 22, 21, 10, 11, -4, -39, + -1, 6, 49, 41, -15, -57, 21, -62, + 77, -69, -13, 0, -74, 1, -7, -38, + -8, 6, 63, 28, 4, 26, -52, 82, + 63, 13, 45, -33, 44, -52, -65, -21, + -46, -49, 64, -17, 32, 24, 68, -39, + -16, -5, -26, 28, 5, -61, -28, 2, + 24, 11, -12, -33, 9, -37, -3, -28, + 22, -37, -12, 19, 0, -18, -2, 14, + 1, 4, 8, -9, -2, 43, -17, -2, + -66, -31, 56, -40, -87, -36, -2, -4, + -42, -45, -1, 31, -43, -15, 27, 63, + -11, 32, -10, -33, 27, -19, 4, 15, + -26, -34, 29, -4, -39, -65, 14, -20, + -21, -17, -36, 13, 59, 47, -38, -33, + 13, -37, -8, -37, -7, -6, -76, -31, + -12, -46, 7, 24, -21, -30, -14, 9, + 15, -12, -13, 47, -27, -25, -1, -39, + 0, 20, -9, 6, 7, 4, 3, 7, + 39, 50, 22, -7, 14, -20, 1, 70, + -28, 29, -41, 10, -16, -5, -28, -2, + -37, 32, -18, 17, 62, -11, -20, -50, + 36, 21, -62, -12, -56, 52, 50, 17, + 3, 48, 44, -41, -25, 3, 16, -3, + 0, 33, -6, 15, 27, 34, -25, 22, + 9, 17, -11, 36, 16, -2, 12, 21, + -52, 45, -2, -10, 46, 21, -18, 67, + -28, -13, 30, 37, 42, 16, -9, 11, + 75, 7, -64, -40, -10, 29, 57, -23, + 5, 53, -77, 3, -17, -5, 47, -55, + -35, -36, -13, 52, -53, -71, 52, -111, + -23, -26, -28, 29, -43, 55, -19, 43, + -19, 54, -12, -33, -44, -39, -19, -10, + -31, -10, 21, 38, -57, -20, 2, -25, + 8, -6, 50, 12, 15, 25, -25, 15, + -30, -6, 9, 25, 37, 19, -4, 31, + -22, 2, 4, 2, 36, 7, 3, -34, + -80, 36, -10, -2, -5, 31, -36, 49, + -70, 20, -36, 21, 24, 25, -46, -51, + 36, -58, -48, -40, -10, 55, 71, 47, + 10, -1, 1, 2, -46, -68, 16, 13, + 0, -74, -29, 73, -52, -18, -11, 7, + -44, -82, -32, -70, -28, -1, -39, -68, + -6, -41, 12, -22, -16, 40, -11, -25, + 51, -9, 21, 4, 4, -34, 7, -78, + 16, 6, -38, -30, -2, -44, 32, 0, + 22, 64, 5, -72, -2, -14, -10, -16, + -8, -25, 12, 102, -58, 37, -10, -23, + 15, 49, 7, -7, 2, -20, -32, 45, + -6, 48, 28, 30, 33, -1, 22, -6, + 30, 65, -17, 29, 74, 37, -26, -10, + 15, -24, 19, -66, 22, -10, -31, -1, + -18, -9, 11, 37, -4, 45, 5, 41, + 17, 1, 1, 24, -58, 41, 5, -51, + 14, 8, 43, 16, -10, -1, 45, 32, + -64, 3, -33, -25, -3, -27, -68, 12, + 23, -11, -13, -37, -40, 4, -21, -12, + 32, -23, -19, 76, 41, -23, -24, -44, + -65, -1, -15, 1, 71, 63, 5, 20, + -3, 21, -23, 31, -32, 18, -2, 27, + 31, 46, -5, -39, -5, -35, 18, -18, + -40, -10, 3, 12, 2, -2, -22, 40, + 5, -6, 60, 36, 3, 29, -27, 10, + 25, -54, 5, 26, 39, 35, -24, -37, + 30, -91, 28, -4, -21, -27, -39, -6, + 5, 12, -128, 38, -16, 29, -95, -29, + 82, -2, 35, 2, 12, 8, -22, 10, + 80, -47, 2, -25, -73, -79, 16, -30, + -32, -66, 48, 21, -45, -11, -47, 14, + -27, -17, -7, 15, -44, -14, -44, -26, + -32, 26, -23, 17, -7, -28, 26, -6, + 28, 6, -26, 2, 13, -14, -23, -14, + 19, 46, 16, 2, -33, -21, 28, -17, + -42, 44, -37, 1, -39, 28, 84, -46, + 15, 10, 13, -44, 72, -26, 26, 32, + -28, -12, -83, 2, 10, -30, -44, -10, + -28, 53, 45, 65, 0, -25, 57, 36, + -33, 6, 29, 44, -53, 11, 19, -2, + -27, 35, 32, 49, 4, 23, 38, 36, + 24, 10, 51, -39, 4, -7, 26, 37, + -35, 11, -47, -18, 28, 16, -35, 42, + 17, -21, -41, 28, 14, -12, 11, -45, + 7, -43, -15, 18, -5, 38, -40, -50, + -30, -21, 9, -98, 13, 12, 23, 75, + -56, -7, -3, -4, -1, -34, 12, -49, + 11, 26, -18, -28, -17, 33, 13, -14, + 40, 24, -72, -37, 10, 17, -6, 22, + 16, 16, -6, -12, -30, -14, 10, 40, + -23, 12, 15, -3, -15, 13, -56, -4, + -30, 1, -3, -17, 27, 50, -5, 64, + -36, -19, 7, 29, 22, 25, 9, -16, + -58, -69, -40, -61, -71, -14, 42, 93, + 26, 11, -6, -58, -11, 70, -52, 19, + 9, -30, -33, 11, -37, -47, -21, -22, + -40, 10, 47, 4, -23, 17, 48, 41, + -48, 14, 10, 15, 34, -23, -2, -47, + 23, -32, -13, -10, -26, -26, -4, 16, + 38, -14, 0, -12, -7, -7, 20, 44, + -1, -32, -27, -16, 4, -6, -18, 14, + 5, 4, -29, 28, 7, -7, 15, -11, + -20, -45, -36, 16, 84, 34, -59, -30, + 22, 126, 8, 68, 79, -17, 21, -68, + 37, 5, 15, 63, 49, 127, -90, 85, + 43, 7, 16, 9, 6, -45, -57, -43, + 57, 11, -23, -11, -29, 60, -26, 0, + 7, 42, -24, 10, 23, -25, 8, -7, + -40, 19, -17, 35, 4, 27, -39, -91, + 27, -36, 34, 2, 16, -24, 25, 7, + -21, 5, 17, 10, -22, -30, 9, -17, + -61, -26, 33, 21, 58, -51, -14, 69, + -38, 20, 7, 80, -4, -65, -6, -27, + 53, -12, 47, -1, -15, 1, 60, 102, + -79, -4, 12, 9, 22, 37, -8, -4, + 37, 2, -3, -15, -16, -11, -5, 19, + -6, -43, 20, -25, -18, 10, -27, 0, + -28, -27, -11, 10, -18, -2, -4, -16, + 26, 14, -6, 7, -6, 1, 53, -2, + -29, 23, 9, -30, -6, -4, -6, 56, + 70, 0, -33, -20, -17, -9, -24, 46, + -5, -105, 47, -46, -51, 20, 20, -53, + -81, -1, -7, 75, -5, -21, -65, 12, + -52, 22, -50, -12, 49, 54, 76, -81, + 10, 45, -41, -59, 18, -19, 25, 14, + -31, -53, -5, 12, 31, 84, -23, 2, + 7, 2, 10, -32, 39, -2, -12, 1, + -9, 0, -10, -11, 9, 15, -8, -2, + 2, -1, 10, 14, -5, -40, 19, -7, + -7, 26, -4, 2, 1, -27, 35, 32, + 21, -31, 26, 43, -9, 4, -32, 40, + -62, -52, 36, 22, 38, 22, 36, -96, + 6, -10, -23, -49, 15, -33, -18, -3, + 0, 41, 21, -19, 21, 23, -39, -23, + -6, 6, 47, 56, 4, 74, 0, -98, + 29, -47, -14, -36, 21, -22, 22, 16, + 13, 12, 16, -5, 13, 17, -13, -15, + 1, -34, -26, 26, 12, 32, 27, 13, + -67, 27, 2, 8, 10, 18, 16, 20, + -17, -17, 57, -64, 5, 14, 19, 31, + -18, -44, -46, -16, 4, -25, 17, -126, + -24, 39, 4, 8, 55, -25, -34, 39, + -16, 3, 9, 71, 72, -31, -55, 6, + 10, -25, 32, -85, -21, 18, -8, 15, + 12, -27, -7, 1, -21, -2, -5, 48, + -16, 18, 1, -22, -26, 16, 14, -31, + 27, -6, -15, -21, 4, -14, 18, -36, +]; + +static LAYER1_RECUR_WEIGHTS: [i8; 1728] = [ + 20, 67, -99, 12, 41, -25, 49, -44, + 35, 81, 110, 47, 34, -66, -14, 14, + -60, 34, 29, -73, 10, 41, 35, 89, + 7, -35, 22, 7, 27, -20, -6, 56, + 26, 66, 6, 33, -55, 53, 1, -21, + 14, 17, 68, 55, 59, 0, 18, -9, + 5, -41, 6, -5, -114, -12, 29, 42, + -23, 10, 81, -27, 20, -53, -30, -62, + 40, 95, 25, -4, 3, 18, -8, -15, + -29, -82, 2, -57, -3, -61, -29, -29, + 49, 2, -55, 5, -69, -99, -49, -51, + 6, -25, 12, 89, 44, -33, 5, 41, + 1, 23, -37, -37, -28, -48, 3, 4, + -41, -30, -57, -35, -39, -1, -13, -56, + -5, 50, 49, 41, -4, -4, 33, -22, + -1, 33, 34, 18, 40, -42, 12, 1, + -6, -2, 18, 17, 39, 44, 11, 65, + -60, -45, 10, 91, 21, 9, -62, -11, + 8, 69, 37, 24, -30, 21, 26, -27, + 1, -28, 24, 66, -8, 6, -71, 34, + 24, 44, 58, -78, -19, 57, 17, -60, + 1, 12, -3, -1, -40, 22, 11, -5, + 25, 12, 1, 72, 79, 7, -50, 23, + 18, 13, 21, -11, -20, 5, 77, -94, + 24, 15, 57, -51, 3, 36, 53, -1, + 4, 14, 30, -31, 22, 40, 32, -11, + -34, -36, -59, 58, 25, 21, -54, -23, + 40, 46, 18, 0, 12, 54, -96, -99, + -59, 5, 119, -38, 50, 55, 12, -16, + 67, 0, 34, 35, 39, 35, -1, 69, + 24, 27, -30, -35, -4, -70, 2, -44, + -7, -6, 19, -9, 60, 44, -21, -10, + 37, 43, -16, -3, 30, -15, -65, 31, + -55, 18, -98, 76, 64, 25, 24, -18, + -7, -68, -10, 38, 27, -60, 36, 33, + 16, 30, 34, -39, -37, 31, 12, 53, + -54, 14, -26, -49, -128, -13, -5, -22, + -11, -85, 55, -8, -51, -11, -33, -10, + -31, -76, -41, 23, 44, -40, -54, -127, + -101, 19, -23, -15, 15, 27, 58, -60, + 8, 14, -33, 1, 48, -9, -11, -123, + 3, 53, 23, 4, -28, 22, 2, -29, + -67, 36, 12, 7, 55, -21, 88, 20, + -1, -21, -17, 3, 41, 32, -10, -14, + -5, -57, 67, 57, 21, 23, -2, -27, + -73, -24, 120, 21, 18, -35, 42, -7, + 3, -45, -25, 76, -34, 50, 11, -54, + -91, 3, -113, -20, -5, 47, 15, -47, + 17, 27, -3, -26, -7, 10, 7, 74, + -40, 64, -7, -5, -24, -49, -24, -3, + -10, 27, -17, -8, -3, 14, -27, 33, + 13, 39, 28, -7, -38, 29, 16, 44, + 19, 55, -3, 9, -13, -57, 43, 43, + 31, 0, -93, -17, 19, -56, 4, -12, + -25, 37, -85, -13, -118, 33, -17, 56, + 71, -80, -4, 6, -11, -18, 47, -52, + 25, 9, 48, -107, 1, 21, 20, -3, + 10, -16, -4, 24, 17, 31, -61, -18, + -50, 24, -10, 12, 71, 26, 11, -3, + 4, 1, 0, -7, -40, 18, 38, -34, + 38, 17, 8, -34, 2, 21, 123, -32, + -26, 43, 14, -34, -1, -9, 37, -16, + 6, -17, -62, 68, 22, 17, 11, -75, + 33, -80, 62, -9, -75, 76, 36, -41, + -8, -40, -11, -71, 40, -39, 62, -49, + -81, 16, -9, -52, 52, 61, 17, -103, + -27, -10, -8, -54, -57, 21, 23, -16, + -52, 36, 18, 10, -5, 8, 15, -29, + 5, -19, -37, 8, -53, 6, 19, -37, + 38, -17, 48, 10, 0, 81, 46, 70, + -29, 101, 11, 44, -44, -3, 24, 11, + 3, 14, -9, 11, 14, -45, 13, 46, + -3, -57, 68, 44, 63, 98, 25, -28, + -23, 15, 32, -10, 53, -6, -2, -9, + -6, 16, -107, -11, -11, -28, 59, 57, + -22, 38, 42, 83, 27, 5, 29, -30, + 12, -21, -13, 31, 38, -21, 58, -10, + -10, -15, -2, -5, 11, 12, -73, -28, + -38, 22, 2, -25, 73, -52, -12, -55, + 32, -63, 21, 51, 33, 52, -26, 55, + -26, -26, 57, -32, -4, -52, -61, 21, + -33, -91, -51, 69, -90, -53, -38, -44, + 12, -76, -20, 77, -45, -7, 86, 43, + -109, -33, -105, -40, -121, -10, 0, -72, + 45, -51, -75, -49, -38, -1, -62, 18, + -1, 30, -44, -14, -10, -67, 40, -10, + -34, 46, -64, -32, 29, -13, 33, 3, + -32, -5, 28, -27, -25, 93, 24, 68, + -40, 57, 23, -3, -21, -58, 17, -39, + -17, -22, -89, 11, 18, -46, 27, 24, + 46, 127, 61, 87, 31, 127, -36, 47, + -23, 47, 127, -24, 110, 122, 30, 100, + 0, 96, -12, 6, 50, 44, -13, 73, + 4, 55, -11, -15, 49, 42, -6, 20, + -35, 58, 18, 38, 42, 72, 19, -21, + 11, 9, -37, 7, 29, 31, 16, -17, + 13, -50, 19, 5, -23, 51, -16, -5, + 4, -24, 76, 10, -53, -28, -7, -65, + 74, 40, -16, -29, 32, -16, -49, -35, + -3, 59, -96, -50, -43, -43, -61, -15, + -8, -36, -34, -33, -14, 11, -3, -39, + 4, -114, -123, -11, -49, -21, 14, -56, + 1, 43, -63, 26, 40, 18, -10, -26, + -14, -15, -35, -35, -11, 32, -44, -67, + 2, 22, 7, 3, -9, -30, -51, -28, + 28, 6, -22, 16, 34, -25, -52, -54, + -8, -6, 5, 8, 20, -16, -17, -44, + 27, 3, 31, -5, -48, -1, -3, 116, + 11, 71, -31, -47, 109, 50, -22, -12, + -57, 32, 66, 8, -25, -93, -54, -10, + 19, -76, -34, 97, 48, -36, -18, -30, + -39, -26, -12, 28, 14, 12, -12, -31, + 38, 2, 10, 4, -40, 20, 16, -61, + 2, 64, 39, 5, 15, 33, 40, -61, + -49, 93, -10, 33, 28, -11, -27, -18, + 39, -62, -6, -6, 62, 11, -8, 38, + -67, 12, 27, 39, -27, 123, -18, -6, + -65, 83, -64, 20, 19, -11, 33, 24, + 17, 56, 78, 7, -15, 54, -101, -9, + 115, -96, 50, 51, 35, 34, 27, 37, + -40, -11, 8, -36, 42, -45, 2, -23, + 0, 67, -8, -9, -13, 50, -14, -27, + 4, 0, -8, -14, 30, -9, 29, 15, + 9, -38, 37, -8, 50, -46, 54, 41, + -11, -8, -11, -26, 39, 45, 14, -26, + -17, -27, 69, 38, 39, 98, 66, 0, + 42, 123, -101, -19, -83, 117, -32, 56, + 10, 12, -88, 79, -53, 56, 63, 95, + -62, 9, 36, -13, -79, -16, 37, -46, + 35, -34, 14, 17, -54, 5, 21, -7, + 7, 63, 56, 15, 27, -76, -25, 4, + -26, -63, 28, -67, -52, 43, -47, -70, + 40, -12, 40, -66, -37, 0, 35, 37, + -53, 4, -17, -51, 11, 21, 14, -34, + -4, 24, -42, 29, 22, 7, 28, 12, + 37, 39, -39, -19, 65, -60, -50, -2, + 1, 82, 39, 19, -23, -43, -22, -67, + -35, -34, 32, 102, 81, 127, 36, 67, + -45, 1, -67, -52, -4, 35, 20, 28, + 71, 86, -35, -9, -83, -34, 12, 9, + -23, 2, 14, 28, -23, 7, -25, 45, + 7, 17, -37, 0, -19, 31, 26, 40, + -27, -16, 17, 5, -21, 23, 24, 96, + -55, 52, -19, -14, -6, 1, 50, -34, + 86, -53, 38, 2, -52, -36, -13, 60, + -85, -120, 32, 7, -12, 22, 70, -7, + -94, 38, -76, -31, -20, 15, -28, 7, + 6, 40, 53, 88, 3, 38, 18, -8, + -22, -23, 51, 37, -9, 13, -32, 25, + -21, 27, 31, 20, 18, -9, -13, 1, + 21, -24, -13, 39, 15, -11, -29, -36, + 18, 15, 8, 27, 21, -94, -1, -22, + 49, 66, -1, 6, -3, -40, -18, 6, + 28, 12, 33, -59, 62, 60, -48, 90, + -1, 108, 9, 18, -2, 27, 77, -65, + 82, -48, -38, -19, -11, 127, 50, 66, + 18, -13, -22, 60, -38, 40, -14, -26, + -13, 38, 67, 57, 30, 33, 26, 36, + 38, -17, 27, -28, 20, 12, -64, 18, + 5, -33, -27, 13, -26, 32, 35, -5, + -48, -14, 92, 43, -47, -14, 40, 11, + 51, 66, 22, -63, -16, -61, 4, -28, + 27, 20, -33, -30, -21, -29, -53, 31, + -40, 24, 43, -4, -19, 21, 67, 20, + 100, -16, -93, 78, -6, -18, -52, -37, + -9, 66, -31, -8, 26, 18, 4, 24, + -22, 17, -2, -13, 27, 0, 8, -18, + -25, 5, -21, -24, -7, 18, -93, 21, + 7, 2, -75, 69, 50, -5, -15, -17, + 60, -42, 55, 1, -4, 3, 10, 46, + 16, -13, 45, -7, -10, -44, -108, 49, + 2, -15, -64, -12, -72, 32, -38, -45, + 10, -54, 13, -13, -27, -36, -64, 58, + -62, -101, 88, -86, -71, -39, -9, -128, + 32, 15, -4, 54, -16, -39, -26, -36, + 46, 48, -64, -10, 19, 30, -13, 34, + -8, 50, 60, -22, -6, -11, -30, 5, + 50, 32, 56, 0, 25, 6, 68, 11, + -29, 45, -9, -12, 4, 1, 18, -49, + 0, -38, -19, 90, 29, 35, 51, 8, + -48, 96, -1, -12, -9, -32, -63, -65, + -7, 38, 89, 28, -85, -28, -23, -25, + -128, 56, 79, -36, 99, -6, -37, 7, + -13, -69, -46, -29, 25, 64, -21, 17, + 1, 42, -66, 1, 80, 26, -32, 21, + 15, 15, 6, 6, -10, 15, 127, 5, + 38, 27, 87, -57, -25, 11, 72, -21, + -5, 11, -13, -66, 78, 36, -3, 41, + -21, 8, -33, 23, 73, 28, 57, -25, + -5, 4, -22, -47, 15, 4, -57, -72, + 33, 1, 18, 2, 53, -71, -99, -21, + -3, -111, 108, 71, -14, 82, 25, 61, + -48, 5, 9, -51, -20, -25, -3, 14, + -33, 14, -3, -34, 22, 12, -19, -38, + -16, 2, 21, 16, 26, -31, 75, 44, + -31, 16, 26, 66, 17, -9, -22, -22, + 22, -44, 22, 27, 2, 58, -14, 10, + -73, -42, 55, -25, -61, 72, -1, 30, + -58, -25, 63, 26, -48, -40, 26, -30, + 60, 8, -17, -1, -18, -20, 43, -20, + -4, -28, 127, -106, 29, 70, 64, -27, + 39, -33, -5, -88, -40, -52, 26, 44, + -17, 23, 2, -49, 22, -9, -8, 86, + 49, -43, -60, 1, 10, 45, 36, -53, + -4, 33, 38, 48, -72, 1, 19, 21, + -65, 4, -5, -62, 27, -25, 17, -6, + 6, -45, -39, -46, 4, 26, 127, -9, + 18, -33, -18, -3, 33, 2, -5, 15, + -26, -22, -117, -63, -17, -59, 61, -74, + 7, -47, -58, -128, -67, 15, -16, -128, + 12, 2, 20, 9, -48, -40, 43, 3, + -40, -16, -38, -6, -22, -28, -16, -59, + -22, 6, -5, 11, -12, -66, -40, 27, + -62, -44, -19, 38, -3, 39, -8, 40, + -24, 13, 21, 50, -60, -22, 53, -29, + -6, 1, 22, -59, 0, 17, -39, 115, +]; + +static LAYER1_BIAS: [i8; 72] = [ + -42, 20, 16, 0, 105, 60, 1, -97, + 24, 60, 18, 13, 62, 25, 127, 34, + 79, 55, 118, 127, 95, 31, -4, 87, + 21, 12, 2, -14, 18, 23, 8, 17, + -1, -8, 5, 4, 24, 37, 21, 13, + 36, 13, 17, 18, 37, 30, 33, 1, + 8, -16, -11, -5, -31, -3, -5, 0, + 6, 3, 58, -7, -1, -16, 5, -13, + 16, 10, -2, -14, 11, -4, 3, -11, +]; + +static LAYER2_WEIGHTS: [i8; 48] = [ + -113, -88, 31, -128, -126, -61, 85, -35, + 118, -128, -61, 127, -128, -17, -128, 127, + 104, -9, -128, 33, 45, 127, 5, 83, + 84, -128, -85, -128, -45, 48, -53, -128, + 46, 127, -17, 125, 117, -41, -117, -91, + -127, -68, -1, -89, -80, 32, 106, 7, +]; + +static LAYER2_BIAS: [i8; 2] = [ + 14, 117, +]; diff --git a/crates/ec-opus/src/celt_enc.rs b/crates/ec-opus/src/celt_enc.rs index 23919409..c045b930 100644 --- a/crates/ec-opus/src/celt_enc.rs +++ b/crates/ec-opus/src/celt_enc.rs @@ -32,6 +32,7 @@ use ec_core::{Error, Result}; +use crate::analysis::{AnalysisInfo, TonalityAnalysis}; 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, @@ -59,6 +60,30 @@ fn tf_boost_params() -> (f32, f32, bool, f32) { }) } +/// 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). +fn analysis_params() -> (bool, bool, bool, bool) { + static P: std::sync::OnceLock<(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) + }; + ( + b("EC_OPUS_ANALYSIS", true), + b("EC_OPUS_TRIM_TONAL", false), + b("EC_OPUS_VBR_TONAL", false), + b("EC_OPUS_VBR_ACT", false), + ) + }) +} + 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, @@ -351,6 +376,18 @@ pub struct CeltFrameDiag { 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 { @@ -371,6 +408,12 @@ impl Default for CeltFrameDiag { 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, } } } @@ -448,6 +491,13 @@ pub struct CeltEncoder { urow: Vec, /// Per-frame diagnostics captured at the end of the last `encode` call. last_diag: CeltFrameDiag, + /// libopus `st->analysis`: the tonality/music-probability estimator, run + /// on the *undelayed* API input at the top of every `encode` call exactly + /// where `opus_encode()` runs `run_analysis()`. + analysis: TonalityAnalysis, + /// The window that covers the frame being coded, or the default + /// (`valid == false`) state when the analysis is off. + info: AnalysisInfo, } impl CeltEncoder { @@ -505,6 +555,8 @@ impl CeltEncoder { pvq_sign: vec![0; max_n], urow: vec![0; 1280], last_diag: CeltFrameDiag::default(), + analysis: TonalityAnalysis::new((48000 / upsample) as u32), + info: AnalysisInfo::default(), } } @@ -547,6 +599,8 @@ impl CeltEncoder { self.vbr_count = 0; self.stereo_saving = 0.0; self.spec_avg = 0.0; + self.analysis.reset(); + self.info = AnalysisInfo::default(); } /// Encodes one frame of interleaved `f32` (`frame_size` samples per @@ -592,6 +646,16 @@ impl CeltEncoder { } let end = end.clamp(start + 1, NB_BANDS); + // libopus `opus_encode_native` runs the tonality analysis on the raw + // API frame before anything else; the CELT layer's own delay does not + // apply to it, so this reads `pcm` and not the delayed buffer. 24 is + // libopus's `lsb_depth` default for the float API. + self.info = if analysis_params().0 { + self.analysis.run(pcm, in_n, c, 24) + } else { + AnalysisInfo::default() + }; + 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. @@ -942,6 +1006,7 @@ impl CeltEncoder { let base_target = vbr_rate + (self.vbr_offset >> lm_diff) - ((40 * c as i32 + 20) << BITRES); let mut target = base_target; + 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 @@ -956,6 +1021,10 @@ impl CeltEncoder { if c == 2 { coded_bins += E_BANDS[self.intensity.min(coded_bands)] << lm; } + // Low-activity cut (C:1632-1633). + 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); @@ -1010,6 +1079,12 @@ impl CeltEncoder { 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. + // `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; @@ -1228,6 +1303,12 @@ impl CeltEncoder { 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) } @@ -1651,14 +1732,24 @@ impl CeltEncoder { * (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. + 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; diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index 441706c9..29d09f29 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -61,6 +61,7 @@ #![forbid(unsafe_code)] #![warn(missing_docs)] +pub(crate) mod analysis; pub mod celt; pub mod celt_enc; pub mod encoder; diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index a95d04ad..fed2c898 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -5716,3 +5716,73 @@ 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() { + 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), + ]; + 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); + let mut out = vec![0u8; 4000]; + let mut sum = 0.0f64; + let mut n = 0usize; + let mut valid = 0usize; + for chunk in pcm.chunks_exact(FRAME * CHANNELS) { + enc.encode_float(chunk, FRAME, &mut out).expect("encode"); + let d = enc.last_celt_diag(); + n += 1; + if d.analysis_valid { + valid += 1; + sum += f64::from(d.music_prob); + } + } + assert!(valid * 10 > n * 9, "{tag}: analysis valid on only {valid}/{n} frames"); + let mean = sum / valid as f64; + println!("music_prob {tag}: mean {mean:.3} over {valid}/{n} frames (music={is_music})"); + means.push(((*tag).to_string(), *is_music, mean)); + } + 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); + } +}