forge
Explore
Log in

Don't you dare go Hollow

Port libopus's tonality analysis (MDCT features + MLP music_prob), consumers behind switches

Browse files at this commit

2d08e3d8eed7e398bc2ed689e52114a60693bf16Ahmet Kaan GümüşParent: c299799
  • feat
    • port libopus's tonality analysis (MDCT features + MLP music_prob), consumers behind switches
Show full message
feat(opus): port libopus's tonality analysis (MDCT features + MLP music_prob), consumers behind switches

The analysis runs on the undelayed API frame exactly where opus_encode does;
alloc_trim's tonality_slope term and compute_vbr's tonality/activity terms are
wired but default off pending their gate rows. music_prob separates the gate's
speech source (hein 0.161) from its music sources (reell 0.991, reelo 0.976).
crates/ec-opus/src/analysis.rsadded+1645 -0
@@ -0,0 +1,1645 @@
1+//! libopus's tonality analysis (`src/analysis.c`, `src/mlp.c`, `src/mlp_data.c`
2+//! at v1.6, the release ffmpeg's reference build links) ported to float Rust.
3+//!
4+//! The encoder feeds every API frame here *undelayed* — the same input
5+//! `opus_encode()` hands `run_analysis()`, before the CELT layer's
6+//! `delay_compensation` — and the analysis maintains its own 30 ms window at
7+//! 24 kHz (720 samples, [`ANALYSIS_BUF_SIZE`]). Each window yields one
8+//! [`AnalysisInfo`]: a tonality estimate and its spectral slope, a noisiness
9+//! and an activity measure, the detected bandwidth, and the music/activity
10+//! probabilities of a 25-input dense → 24-unit GRU → 2-output MLP whose
11+//! `i8` weights are copied verbatim from `mlp_data.c` (they are generated from
12+//! a Keras model upstream and have no closed form).
13+//!
14+//! **What is verbatim.** `tonality_analysis()`, `tonality_get_info()`,
15+//! `run_analysis()`, the 480-point analysis window and DCT tables, the band
16+//! edges, `silk_resampler_down2_hp()`, `fast_atan2f()`, the `tansig`/`sigmoid`
17+//! rational approximations, and all seven weight tables. The float build's Q
18+//! macros (`SHR32`, `MULT16_32_Q15`, `QCONST16`, `SHR64`) are identities and
19+//! are dropped.
20+//!
21+//! **What is omitted.** The fixed-point arms; `MLP_TRAINING`; the
22+//! `application`/`arch` fields (we have one code path); and libopus's
23+//! `CELT_SIG_SCALE` (32768) input scaling together with the matching
24+//! `SCALE_ENER` division by 32768² — they cancel exactly, so this port works
25+//! in the ±1 sample units our encoder already uses, and every energy-domain
26+//! constant (`noise_floor`, the `hp_ener` term) is in those same units.
27+//! `run_analysis()` only runs at 16, 24 and 48 kHz, exactly as libopus's
28+//! `st->Fs >= 16000` guard arranges; below that `AnalysisInfo::valid` stays
29+//! false and every consumer takes its no-analysis branch.
30+
31+use crate::celt::Fft15;
32+
33+/// Number of past frames the band-energy history keeps (`NB_FRAMES`).
34+const NB_FRAMES: usize = 8;
35+/// Number of tonality bands (`NB_TBANDS`).
36+const NB_TBANDS: usize = 18;
37+/// Analysis buffer: 30 ms at 24 kHz (`ANALYSIS_BUF_SIZE`).
38+const ANALYSIS_BUF_SIZE: usize = 720;
39+/// Ring size of the per-window info history (`DETECT_SIZE`).
40+const DETECT_SIZE: usize = 100;
41+/// libopus stops counting frames here (`ANALYSIS_COUNT_MAX`).
42+const ANALYSIS_COUNT_MAX: i32 = 10000;
43+/// Bands skipped at the top of the tonality sum (`NB_TONAL_SKIP_BANDS`).
44+const NB_TONAL_SKIP_BANDS: usize = 9;
45+/// Penalty for switching speech/music during active audio (`TRANSITION_PENALTY`).
46+const TRANSITION_PENALTY: f32 = 10.0;
47+/// Bands of the leakage boost vector (`LEAK_BANDS`, celt.h).
48+pub(crate) const LEAK_BANDS: usize = 19;
49+/// Analysis MDCT/FFT length (`N` in `tonality_analysis`).
50+const N: usize = 480;
51+/// Half of [`N`] (`N2`).
52+const N2: usize = 240;
53+const LEAKAGE_OFFSET: f32 = 2.5;
54+const LEAKAGE_SLOPE: f32 = 2.0;
55+/// Neurons of the widest MLP layer (`MAX_NEURONS`).
56+const MAX_NEURONS: usize = 32;
57+/// `1/128`, the `i8` weight scale (`WEIGHTS_SCALE`).
58+const WEIGHTS_SCALE: f32 = 1.0 / 128.0;
59+
60+/// Tonality band edges in 480-point FFT bins (`tbands`).
61+const TBANDS: [usize; NB_TBANDS + 1] = [
62+ 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 136, 160, 192, 240,
63+];
64+
65+/// One analysis window's result — libopus's `AnalysisInfo`.
66+///
67+/// Every field is meaningless unless [`AnalysisInfo::valid`] is set; the
68+/// [`Default`] value is libopus's "analysis did not run" state.
69+// `noisiness`, `max_pitch_ratio` and `leak_boost` are computed by the port but
70+// have no consumer in this encoder yet: their libopus readers are
71+// `dynalloc_analysis`'s leakage boost and `run_prefilter`'s gain scaling,
72+// neither of which is wired. They stay so the port is whole.
73+#[allow(dead_code)]
74+#[derive(Clone, Copy, Debug)]
75+pub(crate) struct AnalysisInfo {
76+ /// Whether the rest of this struct may be read at all.
77+ pub valid: bool,
78+ /// Tonality of the frame, roughly 0 (noise) to 1 (pure tones).
79+ pub tonality: f32,
80+ /// Spectral slope of the per-band tonality, `alloc_trim`'s input.
81+ pub tonality_slope: f32,
82+ /// Mean per-band noisiness.
83+ pub noisiness: f32,
84+ /// Perceptual activity measure, `compute_vbr`'s input.
85+ pub activity: f32,
86+ /// Music probability, look-ahead-smoothed by `tonality_get_info`.
87+ pub music_prob: f32,
88+ /// Lower switching threshold for speech → music.
89+ pub music_prob_min: f32,
90+ /// Upper switching threshold for music → speech.
91+ pub music_prob_max: f32,
92+ /// Raw MLP activity (voice-activity) probability of this window.
93+ pub activity_probability: f32,
94+ /// Energy ratio below/above the maximum pitch bin.
95+ pub max_pitch_ratio: f32,
96+ /// Detected bandwidth as a tonality-band index (0..=20).
97+ pub bandwidth: i32,
98+ /// Per-band spectral-leakage boost, in 1/64 log2 units.
99+ pub leak_boost: [u8; LEAK_BANDS],
100+}
101+
102+impl Default for AnalysisInfo {
103+ fn default() -> Self {
104+ AnalysisInfo {
105+ valid: false,
106+ tonality: 0.0,
107+ tonality_slope: 0.0,
108+ noisiness: 0.0,
109+ activity: 0.0,
110+ music_prob: 0.0,
111+ music_prob_min: 0.0,
112+ music_prob_max: 0.0,
113+ activity_probability: 0.0,
114+ max_pitch_ratio: 0.0,
115+ bandwidth: 0,
116+ leak_boost: [0; LEAK_BANDS],
117+ }
118+ }
119+}
120+
121+/// libopus `fast_atan2f()` — the rational approximation `analysis.c` uses for
122+/// the per-bin phase, kept because the tonality features are calibrated on it.
123+fn fast_atan2f(y: f32, x: f32) -> f32 {
124+ const CA: f32 = 0.431_579_74;
125+ const CB: f32 = 0.678_484_04;
126+ const CC: f32 = 0.085_955_42;
127+ const CE: f32 = core::f32::consts::FRAC_PI_2;
128+ let x2 = x * x;
129+ let y2 = y * y;
130+ if x2 + y2 < 1e-18 {
131+ return 0.0;
132+ }
133+ if x2 < y2 {
134+ let den = (y2 + CB * x2) * (y2 + CC * x2);
135+ -x * y * (y2 + CA * x2) / den + if y < 0.0 { -CE } else { CE }
136+ } else {
137+ let den = (x2 + CB * y2) * (x2 + CC * y2);
138+ x * y * (x2 + CA * y2) / den + if y < 0.0 { -CE } else { CE }
139+ - if x * y < 0.0 { -CE } else { CE }
140+ }
141+}
142+
143+/// libopus `tansig_approx()`.
144+fn tansig_approx(x: f32) -> f32 {
145+ const N0: f32 = 952.528_02;
146+ const N1: f32 = 96.392_357;
147+ const N2C: f32 = 0.608_630_42;
148+ const D0: f32 = 952.723_99;
149+ const D1: f32 = 413.368_01;
150+ const D2: f32 = 11.886_009;
151+ let x2 = x * x;
152+ let num = (N2C * x2 + N1) * x2 + N0;
153+ let den = (D2 * x2 + D1) * x2 + D0;
154+ (num * x / den).clamp(-1.0, 1.0)
155+}
156+
157+/// libopus `sigmoid_approx()`.
158+fn sigmoid_approx(x: f32) -> f32 {
159+ 0.5 + 0.5 * tansig_approx(0.5 * x)
160+}
161+
162+/// libopus `gemm_accum()`: `out[i] += weights[j*col_stride + i] * x[j]`.
163+fn gemm_accum(out: &mut [f32], weights: &[i8], rows: usize, cols: usize, col_stride: usize, x: &[f32]) {
164+ for (i, o) in out.iter_mut().take(rows).enumerate() {
165+ for (j, &xj) in x.iter().take(cols).enumerate() {
166+ *o += f32::from(weights[j * col_stride + i]) * xj;
167+ }
168+ }
169+}
170+
171+/// libopus `analysis_compute_dense()`.
172+fn compute_dense(bias: &[i8], weights: &[i8], nb_inputs: usize, nb_neurons: usize, sigmoid: bool, output: &mut [f32], input: &[f32]) {
173+ for (i, o) in output.iter_mut().take(nb_neurons).enumerate() {
174+ *o = f32::from(bias[i]);
175+ }
176+ gemm_accum(output, weights, nb_neurons, nb_inputs, nb_neurons, input);
177+ for o in output.iter_mut().take(nb_neurons) {
178+ *o *= WEIGHTS_SCALE;
179+ *o = if sigmoid { sigmoid_approx(*o) } else { tansig_approx(*o) };
180+ }
181+}
182+
183+/// libopus `analysis_compute_gru()`.
184+fn compute_gru(bias: &[i8], weights: &[i8], recur: &[i8], nb_inputs: usize, nb_neurons: usize, state: &mut [f32], input: &[f32]) {
185+ let n = nb_neurons;
186+ let stride = 3 * n;
187+ let mut z = [0.0f32; MAX_NEURONS];
188+ let mut r = [0.0f32; MAX_NEURONS];
189+ let mut h = [0.0f32; MAX_NEURONS];
190+ let mut tmp = [0.0f32; MAX_NEURONS];
191+ for i in 0..n {
192+ z[i] = f32::from(bias[i]);
193+ }
194+ gemm_accum(&mut z, weights, n, nb_inputs, stride, input);
195+ gemm_accum(&mut z, recur, n, n, stride, state);
196+ for zi in z.iter_mut().take(n) {
197+ *zi = sigmoid_approx(WEIGHTS_SCALE * *zi);
198+ }
199+ for i in 0..n {
200+ r[i] = f32::from(bias[n + i]);
201+ }
202+ gemm_accum(&mut r, &weights[n..], n, nb_inputs, stride, input);
203+ gemm_accum(&mut r, &recur[n..], n, n, stride, state);
204+ for ri in r.iter_mut().take(n) {
205+ *ri = sigmoid_approx(WEIGHTS_SCALE * *ri);
206+ }
207+ for i in 0..n {
208+ h[i] = f32::from(bias[2 * n + i]);
209+ tmp[i] = state[i] * r[i];
210+ }
211+ gemm_accum(&mut h, &weights[2 * n..], n, nb_inputs, stride, input);
212+ gemm_accum(&mut h, &recur[2 * n..], n, n, stride, &tmp);
213+ for i in 0..n {
214+ state[i] = z[i] * state[i] + (1.0 - z[i]) * tansig_approx(WEIGHTS_SCALE * h[i]);
215+ }
216+}
217+
218+/// libopus `silk_resampler_down2_hp()` in float: halves the rate and returns
219+/// the energy of the discarded high band.
220+fn resampler_down2_hp(s: &mut [f32; 3], out: &mut [f32], input: &[f32]) -> f32 {
221+ let len2 = input.len() / 2;
222+ let mut hp_ener = 0.0f32;
223+ for k in 0..len2 {
224+ let in32 = input[2 * k];
225+ let y = in32 - s[0];
226+ let x = 0.607_437_1 * y;
227+ let mut out32 = s[0] + x;
228+ s[0] = in32 + x;
229+ let mut out32_hp = out32;
230+
231+ let in32 = input[2 * k + 1];
232+ let y = in32 - s[1];
233+ let x = 0.150_63 * y;
234+ out32 = out32 + s[1] + x;
235+ s[1] = in32 + x;
236+
237+ let y = -in32 - s[2];
238+ let x = 0.150_63 * y;
239+ out32_hp = out32_hp + s[2] + x;
240+ s[2] = -in32 + x;
241+
242+ hp_ener += out32_hp * out32_hp;
243+ out[k] = 0.5 * out32;
244+ }
245+ hp_ener
246+}
247+
248+/// The rolling state of the tonality analysis — libopus's
249+/// `TonalityAnalysisState`, minus the fixed-point and `arch` fields.
250+#[derive(Clone, Debug)]
251+pub(crate) struct TonalityAnalysis {
252+ /// Native input rate in Hz; 16000, 24000 or 48000 when enabled.
253+ fs: u32,
254+ /// False for rates libopus never analyses (below 16 kHz).
255+ enabled: bool,
256+ fft: Fft15,
257+ angle: Vec<f32>,
258+ d_angle: Vec<f32>,
259+ d2_angle: Vec<f32>,
260+ inmem: Vec<f32>,
261+ mem_fill: usize,
262+ prev_band_tonality: [f32; NB_TBANDS],
263+ prev_tonality: f32,
264+ prev_bandwidth: i32,
265+ e: [[f32; NB_TBANDS]; NB_FRAMES],
266+ log_e: [[f32; NB_TBANDS]; NB_FRAMES],
267+ low_e: [f32; NB_TBANDS],
268+ high_e: [f32; NB_TBANDS],
269+ mean_e: [f32; NB_TBANDS + 1],
270+ mem: [f32; 32],
271+ cmean: [f32; 8],
272+ std: [f32; 9],
273+ e_tracker: f32,
274+ low_e_count: f32,
275+ e_count: usize,
276+ count: i32,
277+ analysis_offset: i32,
278+ write_pos: usize,
279+ read_pos: usize,
280+ read_subframe: i32,
281+ hp_ener_accum: f32,
282+ initialized: bool,
283+ rnn_state: [f32; MAX_NEURONS],
284+ downmix_state: [f32; 3],
285+ info: Vec<AnalysisInfo>,
286+}
287+
288+impl TonalityAnalysis {
289+ /// A state for `sample_rate` Hz input. Rates below 16 kHz are accepted but
290+ /// disabled, mirroring libopus's `st->Fs >= 16000` guard on `run_analysis`.
291+ pub(crate) fn new(sample_rate: u32) -> TonalityAnalysis {
292+ TonalityAnalysis {
293+ fs: sample_rate,
294+ enabled: matches!(sample_rate, 16000 | 24000 | 48000),
295+ fft: Fft15::new(N),
296+ angle: vec![0.0; N2],
297+ d_angle: vec![0.0; N2],
298+ d2_angle: vec![0.0; N2],
299+ inmem: vec![0.0; ANALYSIS_BUF_SIZE],
300+ mem_fill: 0,
301+ prev_band_tonality: [0.0; NB_TBANDS],
302+ prev_tonality: 0.0,
303+ prev_bandwidth: 0,
304+ e: [[0.0; NB_TBANDS]; NB_FRAMES],
305+ log_e: [[0.0; NB_TBANDS]; NB_FRAMES],
306+ low_e: [0.0; NB_TBANDS],
307+ high_e: [0.0; NB_TBANDS],
308+ mean_e: [0.0; NB_TBANDS + 1],
309+ mem: [0.0; 32],
310+ cmean: [0.0; 8],
311+ std: [0.0; 9],
312+ e_tracker: 0.0,
313+ low_e_count: 0.0,
314+ e_count: 0,
315+ count: 0,
316+ analysis_offset: 0,
317+ write_pos: 0,
318+ read_pos: 0,
319+ read_subframe: 0,
320+ hp_ener_accum: 0.0,
321+ initialized: false,
322+ rnn_state: [0.0; MAX_NEURONS],
323+ downmix_state: [0.0; 3],
324+ info: vec![AnalysisInfo::default(); DETECT_SIZE],
325+ }
326+ }
327+
328+ /// Clears every non-reusable field — libopus `tonality_analysis_reset()`.
329+ pub(crate) fn reset(&mut self) {
330+ let fs = self.fs;
331+ let fft = std::mem::replace(&mut self.fft, Fft15::new(15));
332+ *self = TonalityAnalysis::new(fs);
333+ self.fft = fft;
334+ }
335+
336+ /// libopus `run_analysis()`: consumes one API frame of interleaved input
337+ /// (`frame_size` samples per channel at the native rate) and returns the
338+ /// [`AnalysisInfo`] that applies to it.
339+ pub(crate) fn run(&mut self, pcm: &[f32], frame_size: usize, channels: usize, lsb_depth: i32) -> AnalysisInfo {
340+ let mut info = AnalysisInfo::default();
341+ if !self.enabled || frame_size == 0 {
342+ return info;
343+ }
344+ let fs = self.fs as i32;
345+ let mut analysis_frame_size = frame_size as i32;
346+ analysis_frame_size -= analysis_frame_size & 1;
347+ // Avoid overflow/wrap-around of the analysis buffer.
348+ analysis_frame_size = analysis_frame_size.min((DETECT_SIZE as i32 - 5) * fs / 50);
349+ let mut pcm_len = analysis_frame_size - self.analysis_offset;
350+ let mut offset = self.analysis_offset;
351+ while pcm_len > 0 {
352+ self.tonality_analysis(pcm, (fs / 50).min(pcm_len), offset, channels, lsb_depth);
353+ offset += fs / 50;
354+ pcm_len -= fs / 50;
355+ }
356+ self.analysis_offset = analysis_frame_size - frame_size as i32;
357+ self.get_info(&mut info, frame_size as i32);
358+ info
359+ }
360+
361+ /// libopus `downmix_and_resample()` for the float API: mono-downmixes
362+ /// `subframe` native samples starting at `offset` into 24 kHz `y`,
363+ /// returning the high-band energy the 48 kHz decimator throws away.
364+ fn downmix_and_resample(&mut self, pcm: &[f32], y: &mut [f32], subframe: usize, offset: usize, channels: usize) -> f32 {
365+ if subframe == 0 {
366+ return 0.0;
367+ }
368+ let (subframe, offset) = match self.fs {
369+ 48000 => (subframe * 2, offset * 2),
370+ 16000 => (subframe * 2 / 3, offset * 2 / 3),
371+ _ => (subframe, offset),
372+ };
373+ let mut tmp = vec![0.0f32; subframe];
374+ for (j, t) in tmp.iter_mut().enumerate() {
375+ let base = (j + offset) * channels;
376+ let mut acc = pcm[base];
377+ for c in 1..channels {
378+ acc += pcm[base + c];
379+ }
380+ *t = if channels == 2 { 0.5 * acc } else { acc };
381+ }
382+ match self.fs {
383+ 48000 => {
384+ let mut st = self.downmix_state;
385+ let e = resampler_down2_hp(&mut st, y, &tmp);
386+ self.downmix_state = st;
387+ e
388+ }
389+ 16000 => {
390+ let mut tmp3x = vec![0.0f32; 3 * subframe];
391+ for j in 0..subframe {
392+ tmp3x[3 * j] = tmp[j];
393+ tmp3x[3 * j + 1] = tmp[j];
394+ tmp3x[3 * j + 2] = tmp[j];
395+ }
396+ let mut st = self.downmix_state;
397+ resampler_down2_hp(&mut st, y, &tmp3x);
398+ self.downmix_state = st;
399+ 0.0
400+ }
401+ _ => {
402+ y[..subframe].copy_from_slice(&tmp);
403+ 0.0
404+ }
405+ }
406+ }
407+
408+ /// libopus `tonality_analysis()`: appends one 20 ms chunk of input and,
409+ /// once 30 ms have accumulated, emits one window's [`AnalysisInfo`].
410+ #[allow(clippy::needless_range_loop)]
411+ fn tonality_analysis(&mut self, pcm: &[f32], len: i32, offset: i32, channels: usize, lsb_depth: i32) {
412+ if !self.initialized {
413+ self.mem_fill = 240;
414+ self.initialized = true;
415+ }
416+ let alpha = 1.0 / (10.min(1 + self.count)) as f32;
417+ let alpha_e = 1.0 / (25.min(1 + self.count)) as f32;
418+ // Noise floor related decay for bandwidth detection: -2.2 dB/second.
419+ let mut alpha_e2 = 1.0 / (100.min(1 + self.count)) as f32;
420+ if self.count <= 1 {
421+ alpha_e2 = 1.0;
422+ }
423+ // len and offset are converted to the 24 kHz analysis domain.
424+ let (len, offset) = match self.fs {
425+ 48000 => (len / 2, offset / 2),
426+ 16000 => (3 * len / 2, 3 * offset / 2),
427+ _ => (len, offset),
428+ };
429+ let (len, offset) = (len as usize, offset as usize);
430+
431+ let take = len.min(ANALYSIS_BUF_SIZE - self.mem_fill);
432+ let mut chunk = vec![0.0f32; take];
433+ let ener = self.downmix_and_resample(pcm, &mut chunk, take, offset, channels);
434+ self.inmem[self.mem_fill..self.mem_fill + take].copy_from_slice(&chunk);
435+ self.hp_ener_accum += ener;
436+ if self.mem_fill + len < ANALYSIS_BUF_SIZE {
437+ self.mem_fill += len;
438+ return;
439+ }
440+ let hp_ener = self.hp_ener_accum;
441+ let write = self.write_pos;
442+ self.write_pos += 1;
443+ if self.write_pos >= DETECT_SIZE {
444+ self.write_pos -= DETECT_SIZE;
445+ }
446+
447+ let is_silence = self.inmem.iter().all(|&v| v == 0.0);
448+
449+ let mut re = vec![0.0f32; N];
450+ let mut im = vec![0.0f32; N];
451+ for i in 0..N2 {
452+ let w = ANALYSIS_WINDOW[i];
453+ re[i] = w * self.inmem[i];
454+ im[i] = w * self.inmem[N2 + i];
455+ re[N - i - 1] = w * self.inmem[N - i - 1];
456+ im[N - i - 1] = w * self.inmem[N + N2 - i - 1];
457+ }
458+ self.inmem.copy_within(ANALYSIS_BUF_SIZE - 240.., 0);
459+ let remaining = len - (ANALYSIS_BUF_SIZE - self.mem_fill);
460+ let mut chunk = vec![0.0f32; remaining];
461+ let ener = self.downmix_and_resample(pcm, &mut chunk, remaining, offset + ANALYSIS_BUF_SIZE - self.mem_fill, channels);
462+ self.inmem[240..240 + remaining].copy_from_slice(&chunk);
463+ self.hp_ener_accum = ener;
464+ self.mem_fill = 240 + remaining;
465+ if is_silence {
466+ // On silence, copy the previous analysis.
467+ let prev = (write + DETECT_SIZE - 1) % DETECT_SIZE;
468+ self.info[write] = self.info[prev];
469+ return;
470+ }
471+ // libopus takes `opus_fft` (forward, scaled by 1/N); ours is the
472+ // unscaled conjugate transform, so conjugate in and out and scale.
473+ for v in im.iter_mut() {
474+ *v = -*v;
475+ }
476+ self.fft.inverse(&mut re, &mut im);
477+ let s = 1.0 / N as f32;
478+ for i in 0..N {
479+ re[i] *= s;
480+ im[i] *= -s;
481+ }
482+ if re[0].is_nan() {
483+ self.info[write].valid = false;
484+ return;
485+ }
486+
487+ let mut tonality = [0.0f32; N2];
488+ let mut tonality2 = [0.0f32; N2];
489+ let mut noisiness = [0.0f32; N2];
490+ let pi4 = (core::f64::consts::PI.powi(4)) as f32;
491+ for i in 1..N2 {
492+ let x1r = re[i] + re[N - i];
493+ let x1i = im[i] - im[N - i];
494+ let x2r = im[i] + im[N - i];
495+ let x2i = re[N - i] - re[i];
496+
497+ let angle = (0.5 / core::f32::consts::PI) * fast_atan2f(x1i, x1r);
498+ let d_angle = angle - self.angle[i];
499+ let d2_angle = d_angle - self.d_angle[i];
500+
501+ let angle2 = (0.5 / core::f32::consts::PI) * fast_atan2f(x2i, x2r);
502+ let d_angle2 = angle2 - angle;
503+ let d2_angle2 = d_angle2 - d_angle;
504+
505+ let mut mod1 = d2_angle - d2_angle.round_ties_even();
506+ noisiness[i] = mod1.abs();
507+ mod1 *= mod1;
508+ mod1 *= mod1;
509+
510+ let mut mod2 = d2_angle2 - d2_angle2.round_ties_even();
511+ noisiness[i] += mod2.abs();
512+ mod2 *= mod2;
513+ mod2 *= mod2;
514+
515+ let avg_mod = 0.25 * (self.d2_angle[i] + mod1 + 2.0 * mod2);
516+ // This introduces an extra delay of 2 frames in the detection.
517+ tonality[i] = 1.0 / (1.0 + 40.0 * 16.0 * pi4 * avg_mod) - 0.015;
518+ // No delay on this detection, but it's less reliable.
519+ tonality2[i] = 1.0 / (1.0 + 40.0 * 16.0 * pi4 * mod2) - 0.015;
520+
521+ self.angle[i] = angle2;
522+ self.d_angle[i] = d_angle2;
523+ self.d2_angle[i] = mod2;
524+ }
525+ for i in 2..N2 - 1 {
526+ let tt = tonality2[i].min(tonality2[i - 1].max(tonality2[i + 1]));
527+ tonality[i] = 0.9 * tonality[i].max(tt - 0.1);
528+ }
529+ let mut frame_tonality = 0.0f32;
530+ let mut max_frame_tonality = 0.0f32;
531+ let activity;
532+ let mut frame_noisiness = 0.0f32;
533+ let mut frame_stationarity = 0.0f32;
534+ if self.count == 0 {
535+ for b in 0..NB_TBANDS {
536+ self.low_e[b] = 1e10;
537+ self.high_e[b] = -1e10;
538+ }
539+ }
540+ let mut relative_e = 0.0f32;
541+ let mut frame_loudness = 0.0f32;
542+ let mut band_log2 = [0.0f32; NB_TBANDS + 1];
543+ let mut log_e = [0.0f32; NB_TBANDS];
544+ let bin_e = |re: &[f32], im: &[f32], i: usize| {
545+ re[i] * re[i] + re[N - i] * re[N - i] + im[i] * im[i] + im[N - i] * im[N - i]
546+ };
547+ // The energy of the very first band is special because of DC.
548+ {
549+ let x1r = 2.0 * re[0];
550+ let x2r = 2.0 * im[0];
551+ let mut e = x1r * x1r + x2r * x2r;
552+ for i in 1..4 {
553+ e += bin_e(&re, &im, i);
554+ }
555+ band_log2[0] = 0.5 * 1.442_695 * (e + 1e-10).ln();
556+ }
557+ let mut band_tonality = [0.0f32; NB_TBANDS];
558+ let mut slope = 0.0f32;
559+ for b in 0..NB_TBANDS {
560+ let (mut e, mut te, mut ne) = (0.0f32, 0.0f32, 0.0f32);
561+ for i in TBANDS[b]..TBANDS[b + 1] {
562+ let be = bin_e(&re, &im, i);
563+ e += be;
564+ te += be * tonality[i].max(0.0);
565+ ne += be * 2.0 * (0.5 - noisiness[i]);
566+ }
567+ // Check for extreme band energies that could cause NaNs later.
568+ if !(e < 1e9) || e.is_nan() {
569+ self.info[write].valid = false;
570+ return;
571+ }
572+ self.e[self.e_count][b] = e;
573+ frame_noisiness += ne / (1e-15 + e);
574+ frame_loudness += (e + 1e-10).sqrt();
575+ log_e[b] = (e + 1e-10).ln();
576+ band_log2[b + 1] = 0.5 * 1.442_695 * (e + 1e-10).ln();
577+ self.log_e[self.e_count][b] = log_e[b];
578+ if self.count == 0 {
579+ self.high_e[b] = log_e[b];
580+ self.low_e[b] = log_e[b];
581+ }
582+ if self.high_e[b] > self.low_e[b] + 7.5 {
583+ if self.high_e[b] - log_e[b] > log_e[b] - self.low_e[b] {
584+ self.high_e[b] -= 0.01;
585+ } else {
586+ self.low_e[b] += 0.01;
587+ }
588+ }
589+ if log_e[b] > self.high_e[b] {
590+ self.high_e[b] = log_e[b];
591+ self.low_e[b] = (self.high_e[b] - 15.0).max(self.low_e[b]);
592+ } else if log_e[b] < self.low_e[b] {
593+ self.low_e[b] = log_e[b];
594+ self.high_e[b] = (self.low_e[b] + 15.0).min(self.high_e[b]);
595+ }
596+ relative_e += (log_e[b] - self.low_e[b]) / (1e-5 + (self.high_e[b] - self.low_e[b]));
597+
598+ let mut l1 = 0.0f32;
599+ let mut l2 = 0.0f32;
600+ for i in 0..NB_FRAMES {
601+ l1 += self.e[i][b].sqrt();
602+ l2 += self.e[i][b];
603+ }
604+ let mut stationarity = 0.99f32.min(l1 / (1e-15 + NB_FRAMES as f32 * l2).sqrt());
605+ stationarity *= stationarity;
606+ stationarity *= stationarity;
607+ frame_stationarity += stationarity;
608+ band_tonality[b] = (te / (1e-15 + e)).max(stationarity * self.prev_band_tonality[b]);
609+ frame_tonality += band_tonality[b];
610+ if b >= NB_TBANDS - NB_TONAL_SKIP_BANDS {
611+ frame_tonality -= band_tonality[b - NB_TBANDS + NB_TONAL_SKIP_BANDS];
612+ }
613+ max_frame_tonality =
614+ max_frame_tonality.max((1.0 + 0.03 * (b as f32 - NB_TBANDS as f32)) * frame_tonality);
615+ slope += band_tonality[b] * (b as f32 - 8.0);
616+ self.prev_band_tonality[b] = band_tonality[b];
617+ }
618+
619+ let mut leakage_from = [0.0f32; NB_TBANDS + 1];
620+ let mut leakage_to = [0.0f32; NB_TBANDS + 1];
621+ leakage_from[0] = band_log2[0];
622+ leakage_to[0] = band_log2[0] - LEAKAGE_OFFSET;
623+ for b in 1..NB_TBANDS + 1 {
624+ let leak_slope = LEAKAGE_SLOPE * (TBANDS[b] - TBANDS[b - 1]) as f32 / 4.0;
625+ leakage_from[b] = (leakage_from[b - 1] + leak_slope).min(band_log2[b]);
626+ leakage_to[b] = (leakage_to[b - 1] - leak_slope).max(band_log2[b] - LEAKAGE_OFFSET);
627+ }
628+ for b in (0..NB_TBANDS - 1).rev() {
629+ let leak_slope = LEAKAGE_SLOPE * (TBANDS[b + 1] - TBANDS[b]) as f32 / 4.0;
630+ leakage_from[b] = (leakage_from[b + 1] + leak_slope).min(leakage_from[b]);
631+ leakage_to[b] = (leakage_to[b + 1] - leak_slope).max(leakage_to[b]);
632+ }
633+ let mut leak_boost = [0u8; LEAK_BANDS];
634+ for b in 0..NB_TBANDS + 1 {
635+ let boost = (leakage_to[b] - band_log2[b]).max(0.0)
636+ + (band_log2[b] - (leakage_from[b] + LEAKAGE_OFFSET)).max(0.0);
637+ leak_boost[b] = (0.5 + 64.0 * boost).floor().min(255.0) as u8;
638+ }
639+
640+ let mut spec_variability = 0.0f32;
641+ for i in 0..NB_FRAMES {
642+ let mut mindist = 1e15f32;
643+ for j in 0..NB_FRAMES {
644+ let mut dist = 0.0f32;
645+ for k in 0..NB_TBANDS {
646+ let tmp = self.log_e[i][k] - self.log_e[j][k];
647+ dist += tmp * tmp;
648+ }
649+ if j != i {
650+ mindist = mindist.min(dist);
651+ }
652+ }
653+ spec_variability += mindist;
654+ }
655+ spec_variability = (spec_variability / NB_FRAMES as f32 / NB_TBANDS as f32).sqrt();
656+ let mut bandwidth_mask = 0.0f32;
657+ let mut bandwidth = 0i32;
658+ let mut max_e = 0.0f32;
659+ let mut noise_floor = 5.7e-4 / (1 << 0.max(lsb_depth - 8)) as f32;
660+ noise_floor *= noise_floor;
661+ let mut below_max_pitch = 0.0f32;
662+ let mut above_max_pitch = 0.0f32;
663+ let mut is_masked = [false; NB_TBANDS + 1];
664+ for b in 0..NB_TBANDS {
665+ let band_start = TBANDS[b];
666+ let band_end = TBANDS[b + 1];
667+ let mut e = 0.0f32;
668+ for i in band_start..band_end {
669+ e += bin_e(&re, &im, i);
670+ }
671+ max_e = max_e.max(e);
672+ if band_start < 64 {
673+ below_max_pitch += e;
674+ } else {
675+ above_max_pitch += e;
676+ }
677+ self.mean_e[b] = ((1.0 - alpha_e2) * self.mean_e[b]).max(e);
678+ let em = e.max(self.mean_e[b]);
679+ let width = (band_end - band_start) as f32;
680+ if e * 1e9 > max_e && (em > 3.0 * noise_floor * width || e > noise_floor * width) {
681+ bandwidth = b as i32 + 1;
682+ }
683+ is_masked[b] = e < if self.prev_bandwidth >= b as i32 + 1 { 0.01 } else { 0.05 } * bandwidth_mask;
684+ bandwidth_mask = (0.05 * bandwidth_mask).max(e);
685+ }
686+ // The last two bands have no spectrum, only the energy above 12 kHz.
687+ if self.fs == 48000 {
688+ let b = NB_TBANDS;
689+ let e = hp_ener * (1.0 / (60.0 * 60.0));
690+ let noise_ratio = if self.prev_bandwidth == 20 { 10.0 } else { 30.0 };
691+ above_max_pitch += e;
692+ self.mean_e[b] = ((1.0 - alpha_e2) * self.mean_e[b]).max(e);
693+ let em = e.max(self.mean_e[b]);
694+ if em > 3.0 * noise_ratio * noise_floor * 160.0 || e > noise_ratio * noise_floor * 160.0 {
695+ bandwidth = 20;
696+ }
697+ is_masked[b] = e < if self.prev_bandwidth == 20 { 0.01 } else { 0.05 } * bandwidth_mask;
698+ }
699+ let max_pitch_ratio = if above_max_pitch > below_max_pitch {
700+ below_max_pitch / above_max_pitch
701+ } else {
702+ 1.0
703+ };
704+ // Resampling aliasing can leave energy in the first band being cut.
705+ if bandwidth == 20 && is_masked[NB_TBANDS] {
706+ bandwidth -= 2;
707+ } else if bandwidth > 0 && bandwidth <= NB_TBANDS as i32 && is_masked[bandwidth as usize - 1] {
708+ bandwidth -= 1;
709+ }
710+ if self.count <= 2 {
711+ bandwidth = 20;
712+ }
713+ frame_loudness = 20.0 * frame_loudness.log10();
714+ self.e_tracker = (self.e_tracker - 0.003).max(frame_loudness);
715+ self.low_e_count *= 1.0 - alpha_e;
716+ if frame_loudness < self.e_tracker - 30.0 {
717+ self.low_e_count += alpha_e;
718+ }
719+
720+ let mut bfcc = [0.0f32; 8];
721+ let mut mid_e = [0.0f32; 8];
722+ for i in 0..8 {
723+ let mut sum = 0.0f32;
724+ for b in 0..16 {
725+ sum += DCT_TABLE[i * 16 + b] * log_e[b];
726+ }
727+ bfcc[i] = sum;
728+ }
729+ for i in 0..8 {
730+ let mut sum = 0.0f32;
731+ for b in 0..16 {
732+ sum += DCT_TABLE[i * 16 + b] * 0.5 * (self.high_e[b] + self.low_e[b]);
733+ }
734+ mid_e[i] = sum;
735+ }
736+
737+ frame_stationarity /= NB_TBANDS as f32;
738+ relative_e /= NB_TBANDS as f32;
739+ if self.count < 10 {
740+ relative_e = 0.5;
741+ }
742+ frame_noisiness /= NB_TBANDS as f32;
743+ activity = frame_noisiness + (1.0 - frame_noisiness) * relative_e;
744+ let mut frame_tonality = max_frame_tonality / (NB_TBANDS - NB_TONAL_SKIP_BANDS) as f32;
745+ frame_tonality = frame_tonality.max(self.prev_tonality * 0.8);
746+ self.prev_tonality = frame_tonality;
747+ slope /= 8.0 * 8.0;
748+ let tonality_slope = slope;
749+
750+ self.e_count = (self.e_count + 1) % NB_FRAMES;
751+ self.count = (self.count + 1).min(ANALYSIS_COUNT_MAX);
752+
753+ let mut features = [0.0f32; 25];
754+ for i in 0..4 {
755+ features[i] = -0.122_99 * (bfcc[i] + self.mem[i + 24])
756+ + 0.491_95 * (self.mem[i] + self.mem[i + 16])
757+ + 0.696_93 * self.mem[i + 8]
758+ - 1.434_9 * self.cmean[i];
759+ }
760+ for i in 0..4 {
761+ self.cmean[i] = (1.0 - alpha) * self.cmean[i] + alpha * bfcc[i];
762+ }
763+ for i in 0..4 {
764+ features[4 + i] =
765+ 0.632_46 * (bfcc[i] - self.mem[i + 24]) + 0.316_23 * (self.mem[i] - self.mem[i + 16]);
766+ }
767+ for i in 0..3 {
768+ features[8 + i] = 0.534_52 * (bfcc[i] + self.mem[i + 24])
769+ - 0.267_26 * (self.mem[i] + self.mem[i + 16])
770+ - 0.534_52 * self.mem[i + 8];
771+ }
772+ if self.count > 5 {
773+ for i in 0..9 {
774+ self.std[i] = (1.0 - alpha) * self.std[i] + alpha * features[i] * features[i];
775+ }
776+ }
777+ for i in 0..4 {
778+ features[i] = bfcc[i] - mid_e[i];
779+ }
780+ for i in 0..8 {
781+ self.mem[i + 24] = self.mem[i + 16];
782+ self.mem[i + 16] = self.mem[i + 8];
783+ self.mem[i + 8] = self.mem[i];
784+ self.mem[i] = bfcc[i];
785+ }
786+ for i in 0..9 {
787+ features[11 + i] = self.std[i].sqrt() - STD_FEATURE_BIAS[i];
788+ }
789+ features[18] = spec_variability - 0.78;
790+ features[20] = frame_tonality - 0.154_723;
791+ features[21] = activity - 0.724_643;
792+ features[22] = frame_stationarity - 0.743_717;
793+ features[23] = tonality_slope + 0.069_216;
794+ features[24] = self.low_e_count - 0.067_930;
795+
796+ let mut layer_out = [0.0f32; MAX_NEURONS];
797+ let mut frame_probs = [0.0f32; 2];
798+ compute_dense(&LAYER0_BIAS, &LAYER0_WEIGHTS, 25, 32, false, &mut layer_out, &features);
799+ let mut state = self.rnn_state;
800+ compute_gru(&LAYER1_BIAS, &LAYER1_WEIGHTS, &LAYER1_RECUR_WEIGHTS, 32, 24, &mut state, &layer_out);
801+ self.rnn_state = state;
802+ compute_dense(&LAYER2_BIAS, &LAYER2_WEIGHTS, 24, 2, true, &mut frame_probs, &self.rnn_state);
803+
804+ self.prev_bandwidth = bandwidth;
805+ self.info[write] = AnalysisInfo {
806+ valid: true,
807+ tonality: frame_tonality,
808+ tonality_slope,
809+ noisiness: frame_noisiness,
810+ activity,
811+ music_prob: frame_probs[0],
812+ music_prob_min: 0.0,
813+ music_prob_max: 0.0,
814+ activity_probability: frame_probs[1],
815+ max_pitch_ratio,
816+ bandwidth,
817+ leak_boost,
818+ };
819+ }
820+
821+ /// libopus `tonality_get_info()`: picks the window that covers the frame
822+ /// about to be coded and smooths `music_prob` over the look-ahead.
823+ fn get_info(&mut self, info_out: &mut AnalysisInfo, len: i32) {
824+ let mut pos = self.read_pos;
825+ let mut curr_lookahead = self.write_pos as i32 - self.read_pos as i32;
826+ if curr_lookahead < 0 {
827+ curr_lookahead += DETECT_SIZE as i32;
828+ }
829+ self.read_subframe += len / (self.fs as i32 / 400);
830+ while self.read_subframe >= 8 {
831+ self.read_subframe -= 8;
832+ self.read_pos += 1;
833+ }
834+ if self.read_pos >= DETECT_SIZE {
835+ self.read_pos -= DETECT_SIZE;
836+ }
837+ // On long frames, look at the second analysis window rather than the first.
838+ if len > self.fs as i32 / 50 && pos != self.write_pos {
839+ pos += 1;
840+ if pos == DETECT_SIZE {
841+ pos = 0;
842+ }
843+ }
844+ if pos == self.write_pos {
845+ pos = (pos + DETECT_SIZE - 1) % DETECT_SIZE;
846+ }
847+ let pos0 = pos;
848+ *info_out = self.info[pos];
849+ if !info_out.valid {
850+ return;
851+ }
852+ let mut tonality_max = info_out.tonality;
853+ let mut tonality_avg = info_out.tonality;
854+ let mut tonality_count = 1;
855+ // Look at the neighbouring frames and pick the largest bandwidth found.
856+ let mut bandwidth_span = 6;
857+ for _ in 0..3 {
858+ pos += 1;
859+ if pos == DETECT_SIZE {
860+ pos = 0;
861+ }
862+ if pos == self.write_pos {
863+ break;
864+ }
865+ tonality_max = tonality_max.max(self.info[pos].tonality);
866+ tonality_avg += self.info[pos].tonality;
867+ tonality_count += 1;
868+ info_out.bandwidth = info_out.bandwidth.max(self.info[pos].bandwidth);
869+ bandwidth_span -= 1;
870+ }
871+ pos = pos0;
872+ for _ in 0..bandwidth_span {
873+ pos = (pos + DETECT_SIZE - 1) % DETECT_SIZE;
874+ if pos == self.write_pos {
875+ break;
876+ }
877+ info_out.bandwidth = info_out.bandwidth.max(self.info[pos].bandwidth);
878+ }
879+ info_out.tonality = (tonality_avg / tonality_count as f32).max(tonality_max - 0.2);
880+
881+ let mut mpos = pos0;
882+ let mut vpos = pos0;
883+ // With enough look-ahead, compensate for the ~5-frame delay in the
884+ // music prob and the ~1 frame delay in the VAD prob.
885+ if curr_lookahead > 15 {
886+ mpos = (mpos + 5) % DETECT_SIZE;
887+ vpos = (vpos + 1) % DETECT_SIZE;
888+ }
889+ // The "badness function" minimisation of libopus's comment block: what
890+ // is computed is the threshold at which switching now is optimal.
891+ let mut prob_min = 1.0f32;
892+ let mut prob_max = 0.0f32;
893+ let vad_prob = self.info[vpos].activity_probability;
894+ let mut prob_count = 0.1f32.max(vad_prob);
895+ let mut prob_avg = 0.1f32.max(vad_prob) * self.info[mpos].music_prob;
896+ loop {
897+ mpos = (mpos + 1) % DETECT_SIZE;
898+ if mpos == self.write_pos {
899+ break;
900+ }
901+ vpos = (vpos + 1) % DETECT_SIZE;
902+ if vpos == self.write_pos {
903+ break;
904+ }
905+ let pos_vad = self.info[vpos].activity_probability;
906+ prob_min = ((prob_avg - TRANSITION_PENALTY * (vad_prob - pos_vad)) / prob_count).min(prob_min);
907+ prob_max = ((prob_avg + TRANSITION_PENALTY * (vad_prob - pos_vad)) / prob_count).max(prob_max);
908+ prob_count += 0.1f32.max(pos_vad);
909+ prob_avg += 0.1f32.max(pos_vad) * self.info[mpos].music_prob;
910+ }
911+ info_out.music_prob = prob_avg / prob_count;
912+ prob_min = (prob_avg / prob_count).min(prob_min);
913+ prob_max = (prob_avg / prob_count).max(prob_max);
914+ prob_min = prob_min.max(0.0);
915+ prob_max = prob_max.min(1.0);
916+
917+ // Without enough look-ahead, do our best to make a decent decision.
918+ if curr_lookahead < 10 {
919+ let mut pmin = prob_min;
920+ let mut pmax = prob_max;
921+ pos = pos0;
922+ for _ in 0..(self.count - 1).min(15) {
923+ pos = (pos + DETECT_SIZE - 1) % DETECT_SIZE;
924+ pmin = pmin.min(self.info[pos].music_prob);
925+ pmax = pmax.max(self.info[pos].music_prob);
926+ }
927+ // Bias against switching on active audio.
928+ pmin = 0.0f32.max(pmin - 0.1 * vad_prob);
929+ pmax = 1.0f32.min(pmax + 0.1 * vad_prob);
930+ prob_min += (1.0 - 0.1 * curr_lookahead as f32) * (pmin - prob_min);
931+ prob_max += (1.0 - 0.1 * curr_lookahead as f32) * (pmax - prob_max);
932+ }
933+ info_out.music_prob_min = prob_min;
934+ info_out.music_prob_max = prob_max;
935+ }
936+}
937+
938+// ---------------------------------------------------------------------------
939+// Tables copied verbatim from libopus v1.6: `src/analysis.c` (`dct_table`,
940+// `analysis_window`, `std_feature_bias`) and `src/mlp_data.c` (the Keras-
941+// generated `i8` weights of the 25x32 dense layer, the 24-unit GRU and the
942+// 2-output sigmoid layer). They have no closed form; do not "simplify" them.
943+// ---------------------------------------------------------------------------
944+
945+static DCT_TABLE: [f32; 128] = [
946+ 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, 0.250000,
947+ 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, 0.250000, 0.250000,
948+ 0.351851, 0.338330, 0.311806, 0.273300, 0.224292, 0.166664, 0.102631, 0.034654,
949+ -0.034654, -0.102631, -0.166664, -0.224292, -0.273300, -0.311806, -0.338330, -0.351851,
950+ 0.346760, 0.293969, 0.196424, 0.068975, -0.068975, -0.196424, -0.293969, -0.346760,
951+ -0.346760, -0.293969, -0.196424, -0.068975, 0.068975, 0.196424, 0.293969, 0.346760,
952+ 0.338330, 0.224292, 0.034654, -0.166664, -0.311806, -0.351851, -0.273300, -0.102631,
953+ 0.102631, 0.273300, 0.351851, 0.311806, 0.166664, -0.034654, -0.224292, -0.338330,
954+ 0.326641, 0.135299, -0.135299, -0.326641, -0.326641, -0.135299, 0.135299, 0.326641,
955+ 0.326641, 0.135299, -0.135299, -0.326641, -0.326641, -0.135299, 0.135299, 0.326641,
956+ 0.311806, 0.034654, -0.273300, -0.338330, -0.102631, 0.224292, 0.351851, 0.166664,
957+ -0.166664, -0.351851, -0.224292, 0.102631, 0.338330, 0.273300, -0.034654, -0.311806,
958+ 0.293969, -0.068975, -0.346760, -0.196424, 0.196424, 0.346760, 0.068975, -0.293969,
959+ -0.293969, 0.068975, 0.346760, 0.196424, -0.196424, -0.346760, -0.068975, 0.293969,
960+ 0.273300, -0.166664, -0.338330, 0.034654, 0.351851, 0.102631, -0.311806, -0.224292,
961+ 0.224292, 0.311806, -0.102631, -0.351851, -0.034654, 0.338330, 0.166664, -0.273300,
962+];
963+
964+static ANALYSIS_WINDOW: [f32; 240] = [
965+ 0.000043, 0.000171, 0.000385, 0.000685, 0.001071, 0.001541, 0.002098, 0.002739,
966+ 0.003466, 0.004278, 0.005174, 0.006156, 0.007222, 0.008373, 0.009607, 0.010926,
967+ 0.012329, 0.013815, 0.015385, 0.017037, 0.018772, 0.020590, 0.022490, 0.024472,
968+ 0.026535, 0.028679, 0.030904, 0.033210, 0.035595, 0.038060, 0.040604, 0.043227,
969+ 0.045928, 0.048707, 0.051564, 0.054497, 0.057506, 0.060591, 0.063752, 0.066987,
970+ 0.070297, 0.073680, 0.077136, 0.080665, 0.084265, 0.087937, 0.091679, 0.095492,
971+ 0.099373, 0.103323, 0.107342, 0.111427, 0.115579, 0.119797, 0.124080, 0.128428,
972+ 0.132839, 0.137313, 0.141849, 0.146447, 0.151105, 0.155823, 0.160600, 0.165435,
973+ 0.170327, 0.175276, 0.180280, 0.185340, 0.190453, 0.195619, 0.200838, 0.206107,
974+ 0.211427, 0.216797, 0.222215, 0.227680, 0.233193, 0.238751, 0.244353, 0.250000,
975+ 0.255689, 0.261421, 0.267193, 0.273005, 0.278856, 0.284744, 0.290670, 0.296632,
976+ 0.302628, 0.308658, 0.314721, 0.320816, 0.326941, 0.333097, 0.339280, 0.345492,
977+ 0.351729, 0.357992, 0.364280, 0.370590, 0.376923, 0.383277, 0.389651, 0.396044,
978+ 0.402455, 0.408882, 0.415325, 0.421783, 0.428254, 0.434737, 0.441231, 0.447736,
979+ 0.454249, 0.460770, 0.467298, 0.473832, 0.480370, 0.486912, 0.493455, 0.500000,
980+ 0.506545, 0.513088, 0.519630, 0.526168, 0.532702, 0.539230, 0.545751, 0.552264,
981+ 0.558769, 0.565263, 0.571746, 0.578217, 0.584675, 0.591118, 0.597545, 0.603956,
982+ 0.610349, 0.616723, 0.623077, 0.629410, 0.635720, 0.642008, 0.648271, 0.654508,
983+ 0.660720, 0.666903, 0.673059, 0.679184, 0.685279, 0.691342, 0.697372, 0.703368,
984+ 0.709330, 0.715256, 0.721144, 0.726995, 0.732807, 0.738579, 0.744311, 0.750000,
985+ 0.755647, 0.761249, 0.766807, 0.772320, 0.777785, 0.783203, 0.788573, 0.793893,
986+ 0.799162, 0.804381, 0.809547, 0.814660, 0.819720, 0.824724, 0.829673, 0.834565,
987+ 0.839400, 0.844177, 0.848895, 0.853553, 0.858151, 0.862687, 0.867161, 0.871572,
988+ 0.875920, 0.880203, 0.884421, 0.888573, 0.892658, 0.896677, 0.900627, 0.904508,
989+ 0.908321, 0.912063, 0.915735, 0.919335, 0.922864, 0.926320, 0.929703, 0.933013,
990+ 0.936248, 0.939409, 0.942494, 0.945503, 0.948436, 0.951293, 0.954072, 0.956773,
991+ 0.959396, 0.961940, 0.964405, 0.966790, 0.969096, 0.971321, 0.973465, 0.975528,
992+ 0.977510, 0.979410, 0.981228, 0.982963, 0.984615, 0.986185, 0.987671, 0.989074,
993+ 0.990393, 0.991627, 0.992778, 0.993844, 0.994826, 0.995722, 0.996534, 0.997261,
994+ 0.997902, 0.998459, 0.998929, 0.999315, 0.999615, 0.999829, 0.999957, 1.000000,
995+];
996+
997+static STD_FEATURE_BIAS: [f32; 9] = [
998+ 5.684947, 3.475288, 1.770634, 1.599784, 3.773215,
999+ 2.163313, 1.260756, 1.116868, 1.918795,
1000+];
1001+
1002+static LAYER0_WEIGHTS: [i8; 800] = [
1003+ -30, -9, 2, -12, 5, -1, 8, 9,
1004+ 9, 8, -13, 18, -17, -34, -5, 17,
1005+ -11, 0, -4, 10, 2, 10, 15, -8,
1006+ 2, -1, 0, 5, 13, -3, -16, 1,
1007+ -5, 3, 7, -28, -13, 6, 36, -3,
1008+ 19, -60, -17, -28, 7, -11, -30, -7,
1009+ 2, -42, -21, -3, 6, -22, 33, -9,
1010+ 7, -30, 21, -14, 24, -11, -20, -18,
1011+ -5, -12, 12, -49, -50, -49, 16, 9,
1012+ -37, -1, 9, 34, -13, -31, -31, 12,
1013+ 16, 44, -42, 2, -9, 8, -18, -6,
1014+ 9, 36, 19, 11, 13, 12, -21, 3,
1015+ -28, -12, 3, 33, 25, -14, 11, 1,
1016+ -94, -39, 18, -12, -11, -15, -7, 49,
1017+ 52, 10, -43, 9, 57, 8, 21, -6,
1018+ 14, -15, 44, -8, 7, -30, -13, -2,
1019+ -9, 25, -2, -127, 18, -11, -52, 26,
1020+ -27, 27, 10, -10, 7, 43, 6, -24,
1021+ 41, 10, -18, -27, 10, 17, 9, 10,
1022+ -17, -10, 20, -6, 22, 55, 35, -80,
1023+ 36, 25, -24, -36, 15, 9, -19, 88,
1024+ 19, 64, -51, -35, 17, 0, -7, 41,
1025+ -16, 27, 4, 15, -1, 18, -16, 47,
1026+ -39, -54, -8, 13, -25, -20, 102, -18,
1027+ -5, 44, 11, -28, 71, 2, -51, -5,
1028+ 5, 2, -83, -9, -29, 8, 21, -53,
1029+ 58, -37, -7, 13, 38, 9, 34, -1,
1030+ -41, 21, 4, -24, -36, -33, -21, 32,
1031+ 75, -2, 1, -68, -1, 47, -29, 32,
1032+ 20, 12, -65, -87, 5, 16, -12, 24,
1033+ 40, 15, 7, 19, -26, -17, 17, 6,
1034+ -2, -37, -30, -9, 32, -127, -39, 0,
1035+ -31, -27, 4, -22, 23, -6, -77, 35,
1036+ -61, 32, -37, -24, 13, -11, -1, -40,
1037+ -3, 17, -7, 13, 11, 59, -19, 10,
1038+ 6, -18, 0, 13, 3, -6, -23, 19,
1039+ 11, -17, 13, -1, -80, 40, -53, 69,
1040+ -29, -54, 0, -4, 33, -25, -2, 38,
1041+ 35, 36, -15, 46, 2, -13, -16, -8,
1042+ -8, 12, -24, -9, -55, -5, -9, 32,
1043+ 11, 7, 12, -18, -10, -86, -38, 54,
1044+ 37, -25, 18, -43, 7, -27, -27, -54,
1045+ 13, 9, 22, 70, 6, 35, -7, 23,
1046+ -15, -44, -6, 7, -66, -85, 32, 40,
1047+ -19, -9, -7, 12, -15, 7, 2, 6,
1048+ -35, 11, 28, 0, 26, 14, 1, 1,
1049+ 4, 12, 18, 35, 22, -18, -3, 14,
1050+ -1, 7, 14, -8, -14, -3, 4, -3,
1051+ -19, -7, -1, -25, -27, 25, -26, -2,
1052+ 33, -22, -27, -25, 4, -9, 7, 21,
1053+ 26, -30, 10, -9, -20, 11, 27, 10,
1054+ 5, -18, 14, -4, 2, -17, -5, -7,
1055+ -9, -13, 15, 29, 1, -10, -16, -10,
1056+ 35, 36, -7, -22, -44, 17, 30, 22,
1057+ 21, -1, 22, -11, 32, -8, -7, 5,
1058+ -10, 5, 30, -20, 29, -20, -34, 12,
1059+ -4, -6, 6, -13, 10, -5, -68, -1,
1060+ 24, 9, 19, -24, -64, 31, 19, 27,
1061+ -26, 75, -45, 41, 39, -42, 8, 6,
1062+ 23, -30, 16, -25, 30, 34, 8, -38,
1063+ -3, 18, 16, -31, 22, -4, -9, 1,
1064+ 20, 9, 38, -32, 0, -45, 0, -6,
1065+ -13, 11, -25, -32, -22, 31, -24, -11,
1066+ -11, -4, -4, 20, -34, 22, 20, 9,
1067+ -25, 27, -5, 28, -29, 29, 6, 21,
1068+ -6, -18, 54, 4, -46, 23, 21, -14,
1069+ -31, 36, -41, -24, 4, 22, 10, 11,
1070+ 7, 36, -32, -13, -52, -17, 24, 28,
1071+ -37, -36, -1, 24, 9, -38, 35, 48,
1072+ 18, 2, -1, 45, 10, 39, 24, -38,
1073+ 13, 8, -16, 8, 25, 11, 7, -29,
1074+ -11, 7, 20, -30, -38, -45, 14, -18,
1075+ -28, -9, 65, 61, 22, -53, -38, -16,
1076+ 36, 46, 20, -39, 32, -61, -6, -6,
1077+ -36, -33, -18, -28, 56, 101, 45, 11,
1078+ -28, -23, -29, -61, 20, -47, 2, 48,
1079+ 27, -17, 1, 40, 1, 3, -51, 15,
1080+ 35, 28, 22, 35, 53, -61, -29, 12,
1081+ -6, -21, 10, 3, -20, 2, -25, 1,
1082+ -6, 31, 11, -3, 1, -10, -52, 6,
1083+ 126, -105, 122, 127, -128, 127, 127, -128,
1084+ 127, 108, 12, 127, 48, -128, -36, -128,
1085+ 127, 127, -128, -128, 127, 89, -128, 127,
1086+ -128, -128, -128, 127, 127, -128, -128, -93,
1087+ -82, 20, 125, 65, -82, 127, 38, -74,
1088+ 81, 88, -88, 79, 51, -47, -111, -26,
1089+ 14, 83, -88, -112, 24, 35, -101, 98,
1090+ -99, -48, -45, 46, 83, -60, -79, 45,
1091+ -20, -41, 9, 4, 52, 54, 93, -10,
1092+ 4, 13, 3, 123, 6, 94, -111, -69,
1093+ -14, -31, 10, 12, 53, -79, -11, -21,
1094+ -2, -44, -72, 92, 65, -57, 56, -38,
1095+ 127, -56, -128, 127, 127, -128, 86, 117,
1096+ -75, -128, 127, -19, -99, -112, 127, -128,
1097+ 127, -48, 114, 118, -128, -128, 117, -17,
1098+ -6, 121, -128, 127, -128, 82, 54, -106,
1099+ 127, 127, -33, 100, -39, -23, 18, -78,
1100+ -34, -29, -1, -30, 127, -26, 127, -128,
1101+ 126, -128, 27, -23, -79, -120, -127, 127,
1102+ 72, 66, 29, 7, -66, -56, -117, -128,
1103+];
1104+
1105+static LAYER0_BIAS: [i8; 32] = [
1106+ 51, -16, 1, 13, -5, -6, -16, -7,
1107+ 11, -6, 106, 26, 28, -14, 21, -29,
1108+ 7, 18, -18, -17, 21, -17, -9, 20,
1109+ -25, -3, -34, 48, 11, -13, -31, -20,
1110+];
1111+
1112+static LAYER1_WEIGHTS: [i8; 2304] = [
1113+ 22, -1, -7, 7, 29, -27, -31, -17,
1114+ -13, 33, 44, -8, 11, 33, 24, 78,
1115+ 15, 19, 30, -2, -24, 5, 49, 5,
1116+ 36, 29, -14, -11, -48, -33, 21, -42,
1117+ -38, -12, 55, -37, 54, -8, 1, 36,
1118+ 17, 0, 51, 31, 59, 7, -12, 53,
1119+ 4, 32, -14, 48, 5, -10, -16, -8,
1120+ 1, -16, -56, -24, -6, 18, -2, 23,
1121+ 6, 46, -6, -10, 20, 35, -44, -15,
1122+ -49, 36, 16, 5, -7, -79, -67, 12,
1123+ 70, -3, -79, -54, -85, -24, 47, -22,
1124+ 33, 21, 69, -1, 11, 22, 14, -16,
1125+ -16, -22, -28, -11, 11, -41, 31, -26,
1126+ -33, -19, -4, 27, 32, -50, 5, -10,
1127+ -38, -22, -8, 35, -31, 1, -41, -15,
1128+ -11, 44, 28, -17, -41, -23, 17, 2,
1129+ -23, -26, -13, -13, -17, 6, 14, -31,
1130+ -25, 9, -19, 39, -8, 4, 31, -1,
1131+ -45, -11, -28, -92, -46, -15, 21, 118,
1132+ -22, 45, -51, 11, -20, -20, -15, 13,
1133+ -21, -97, -29, -32, -23, -42, 94, 1,
1134+ 23, -8, 63, -3, -46, 19, -26, 32,
1135+ -40, -74, -26, 26, -4, -13, 30, -20,
1136+ -30, -25, -14, -31, -45, -43, 4, -60,
1137+ -48, -12, -34, 2, 2, 3, 13, 15,
1138+ 11, 16, 5, 46, -9, -55, -16, -57,
1139+ 29, 14, 38, -50, -2, -44, -11, -8,
1140+ 52, -27, -38, -7, 20, 47, 17, -59,
1141+ 0, 47, 46, -63, 35, -17, 19, 33,
1142+ 68, -19, 2, 15, -16, 28, -16, -103,
1143+ 26, -35, 47, -39, -60, 30, 31, -23,
1144+ -52, -13, 116, 47, -25, 30, 40, 30,
1145+ -22, 2, 12, -27, -18, 31, -10, 27,
1146+ -8, -66, 12, 14, 4, -26, -28, -13,
1147+ 3, 13, -26, -51, 37, 5, 2, -21,
1148+ 47, 3, 13, 25, -41, -27, -8, -4,
1149+ 5, -76, -33, 28, 10, 9, -46, -74,
1150+ 19, 28, 25, 31, 54, -55, 68, 38,
1151+ -24, -32, 2, 4, 68, 11, -1, 99,
1152+ 5, 16, -2, -74, 40, 26, -26, 33,
1153+ 31, -1, -68, 14, -6, 25, 9, 29,
1154+ 60, 61, 7, -7, 0, -24, 7, 77,
1155+ 4, -1, 16, -7, 13, -15, -19, 28,
1156+ -31, -24, -16, 37, 24, 13, 30, 10,
1157+ -30, 11, 11, -10, 22, 60, 28, 45,
1158+ -3, -40, -62, -5, -102, 9, -32, -27,
1159+ -54, 21, 15, -5, 37, -43, -11, 37,
1160+ -19, 47, -64, -128, -27, -114, 21, -66,
1161+ 59, 46, -3, -12, -87, -9, 4, 19,
1162+ -113, -36, 78, 57, -26, -38, -77, -10,
1163+ 6, 6, -75, 25, -97, -11, 33, -46,
1164+ 1, 13, -21, -33, -20, 16, -6, -3,
1165+ -11, -4, -27, 38, 8, -41, -2, -33,
1166+ 18, 19, -26, 1, -29, -22, -4, -14,
1167+ -55, -11, -80, -3, 11, 34, 90, 51,
1168+ 11, 17, 43, 36, 127, -32, 29, 103,
1169+ 9, 27, 13, 64, 56, 70, -14, 3,
1170+ -12, 10, 37, 3, 12, -22, -10, 46,
1171+ 28, 10, 20, 26, -24, 18, 9, 7,
1172+ 14, 34, -5, -7, 31, -14, -56, 11,
1173+ -18, -8, -17, -7, -10, -40, 10, -33,
1174+ -32, -43, 5, 9, 11, -4, 10, 50,
1175+ -12, -5, 46, 9, 7, 1, 11, 15,
1176+ 91, -17, 7, -50, 23, 6, -30, -99,
1177+ 0, -17, 14, 8, -10, -25, -30, -69,
1178+ -62, 31, 127, 114, -23, 101, -5, -54,
1179+ -6, -22, 7, -56, 39, 18, -29, 0,
1180+ 46, 8, -79, 4, -21, 18, -32, 62,
1181+ -12, -8, -12, -58, 31, -32, 17, 6,
1182+ -24, 25, 24, 9, -4, -19, 45, 6,
1183+ 17, -14, 5, -27, 16, -4, -41, 25,
1184+ -36, 5, 15, 12, 50, 27, 25, 23,
1185+ -44, -69, -9, -19, -48, -8, 4, 12,
1186+ -6, 13, -19, -30, -36, 26, 37, -1,
1187+ -3, -30, -42, -14, -10, -20, 26, -54,
1188+ -27, -44, 4, 73, -26, 90, 32, -69,
1189+ -29, -16, 3, 103, 15, -17, 37, 24,
1190+ -23, -31, 33, -37, -64, 25, 13, -81,
1191+ -28, -32, 27, 5, -35, -23, 15, -22,
1192+ 19, -7, 9, 30, 19, -23, 27, -13,
1193+ 43, 29, -29, -6, 9, -40, -33, -33,
1194+ -32, 9, 11, -48, -8, -23, -52, 46,
1195+ 17, -22, -42, 35, -15, -41, 16, 34,
1196+ 31, -42, -19, -11, 55, 7, -39, 89,
1197+ -11, -33, 20, -14, 22, 32, 3, -17,
1198+ -6, 14, 34, 1, 55, -21, -90, -8,
1199+ 18, 27, 13, -29, 21, 15, -33, -51,
1200+ -9, -11, 4, -16, -18, 23, -4, -4,
1201+ 48, 1, 7, 29, -14, -12, -16, 17,
1202+ 35, 8, 0, -7, -2, 9, 8, 17,
1203+ -6, 53, -32, -21, -50, 5, 99, -60,
1204+ -5, -53, 10, -31, 12, -5, 7, 80,
1205+ 36, 18, -31, 9, 98, 36, -63, -35,
1206+ 4, -13, -28, -24, 28, -13, 18, 16,
1207+ -1, -18, -34, 10, 20, 7, 4, 29,
1208+ 11, 25, -7, 36, 14, 45, 24, 1,
1209+ -16, 30, 6, 35, -6, -11, -24, 13,
1210+ -1, 27, 39, 20, 48, -11, -4, -13,
1211+ 28, 11, -31, -18, 31, -29, 22, -2,
1212+ -20, -16, 5, 30, -12, -28, -3, 93,
1213+ -16, 23, 18, -29, 6, -54, -37, 28,
1214+ -3, -3, -47, -3, -36, -55, -3, 41,
1215+ -10, 47, -2, 23, 42, -7, -71, -27,
1216+ 83, -64, 7, -24, 8, 26, -17, 15,
1217+ 12, 31, -30, -38, -13, -33, -56, 4,
1218+ -17, 20, 18, 1, -30, -5, -6, -31,
1219+ -14, -37, 0, 22, 10, -30, 37, -17,
1220+ 18, 6, 5, 23, -36, -32, 14, 18,
1221+ -13, -61, -52, -69, 44, -30, 16, 18,
1222+ -4, -25, 14, 81, 26, -8, -23, -59,
1223+ 52, -104, 17, 119, -32, 26, 17, 1,
1224+ 23, 45, 29, -64, -57, -14, 73, 21,
1225+ -13, -13, 9, -68, -7, -52, 3, 24,
1226+ -39, 44, -15, 27, 14, 19, -9, -28,
1227+ -11, 5, 3, -34, -2, 2, 22, -6,
1228+ -23, 4, 3, 13, -22, -13, -10, -18,
1229+ 29, 6, 44, -13, -24, -8, 2, 30,
1230+ 14, 43, 6, 17, -73, -6, -7, 20,
1231+ -80, -7, -7, -28, 15, -69, -38, -5,
1232+ -100, -35, 15, -79, 23, 29, -18, -27,
1233+ 21, -66, -37, 8, -22, -39, 48, 4,
1234+ -13, 1, -9, 11, -29, 22, 6, -49,
1235+ 32, -14, 47, -18, -4, 44, -52, -74,
1236+ 43, 30, 23, -14, 5, 0, -27, 4,
1237+ -7, 10, -4, 10, 1, -16, 11, -18,
1238+ -2, -5, 2, -11, 0, -20, -4, 38,
1239+ 74, 59, 39, 64, -10, 26, -3, -40,
1240+ -68, 3, -30, -51, 8, -19, -27, -46,
1241+ 51, 52, 54, 36, 90, 92, 14, 13,
1242+ -5, 0, 16, -62, 16, 11, -47, -37,
1243+ -6, -5, 21, 54, -57, 32, 42, -6,
1244+ 62, -9, 16, 21, 24, 9, -10, -4,
1245+ 33, 50, 13, -15, 1, -35, -48, 18,
1246+ -11, -17, -67, -13, 21, 38, -44, 36,
1247+ -16, 29, 17, 5, -10, 18, 17, -32,
1248+ 2, 8, 22, -56, -15, -32, 40, 43,
1249+ 19, 46, -7, -100, -96, 19, 53, 24,
1250+ 21, -26, -48, -101, -82, 61, 38, -85,
1251+ -28, -34, -1, 63, -5, -5, 39, 39,
1252+ -38, 32, -12, -28, 20, 40, -8, 2,
1253+ 31, 12, -35, -13, 20, -25, 30, 8,
1254+ 3, -13, -9, -20, 2, -13, 24, 37,
1255+ -10, 33, 6, 20, -16, -24, -6, -6,
1256+ -19, -5, 22, 21, 10, 11, -4, -39,
1257+ -1, 6, 49, 41, -15, -57, 21, -62,
1258+ 77, -69, -13, 0, -74, 1, -7, -38,
1259+ -8, 6, 63, 28, 4, 26, -52, 82,
1260+ 63, 13, 45, -33, 44, -52, -65, -21,
1261+ -46, -49, 64, -17, 32, 24, 68, -39,
1262+ -16, -5, -26, 28, 5, -61, -28, 2,
1263+ 24, 11, -12, -33, 9, -37, -3, -28,
1264+ 22, -37, -12, 19, 0, -18, -2, 14,
1265+ 1, 4, 8, -9, -2, 43, -17, -2,
1266+ -66, -31, 56, -40, -87, -36, -2, -4,
1267+ -42, -45, -1, 31, -43, -15, 27, 63,
1268+ -11, 32, -10, -33, 27, -19, 4, 15,
1269+ -26, -34, 29, -4, -39, -65, 14, -20,
1270+ -21, -17, -36, 13, 59, 47, -38, -33,
1271+ 13, -37, -8, -37, -7, -6, -76, -31,
1272+ -12, -46, 7, 24, -21, -30, -14, 9,
1273+ 15, -12, -13, 47, -27, -25, -1, -39,
1274+ 0, 20, -9, 6, 7, 4, 3, 7,
1275+ 39, 50, 22, -7, 14, -20, 1, 70,
1276+ -28, 29, -41, 10, -16, -5, -28, -2,
1277+ -37, 32, -18, 17, 62, -11, -20, -50,
1278+ 36, 21, -62, -12, -56, 52, 50, 17,
1279+ 3, 48, 44, -41, -25, 3, 16, -3,
1280+ 0, 33, -6, 15, 27, 34, -25, 22,
1281+ 9, 17, -11, 36, 16, -2, 12, 21,
1282+ -52, 45, -2, -10, 46, 21, -18, 67,
1283+ -28, -13, 30, 37, 42, 16, -9, 11,
1284+ 75, 7, -64, -40, -10, 29, 57, -23,
1285+ 5, 53, -77, 3, -17, -5, 47, -55,
1286+ -35, -36, -13, 52, -53, -71, 52, -111,
1287+ -23, -26, -28, 29, -43, 55, -19, 43,
1288+ -19, 54, -12, -33, -44, -39, -19, -10,
1289+ -31, -10, 21, 38, -57, -20, 2, -25,
1290+ 8, -6, 50, 12, 15, 25, -25, 15,
1291+ -30, -6, 9, 25, 37, 19, -4, 31,
1292+ -22, 2, 4, 2, 36, 7, 3, -34,
1293+ -80, 36, -10, -2, -5, 31, -36, 49,
1294+ -70, 20, -36, 21, 24, 25, -46, -51,
1295+ 36, -58, -48, -40, -10, 55, 71, 47,
1296+ 10, -1, 1, 2, -46, -68, 16, 13,
1297+ 0, -74, -29, 73, -52, -18, -11, 7,
1298+ -44, -82, -32, -70, -28, -1, -39, -68,
1299+ -6, -41, 12, -22, -16, 40, -11, -25,
1300+ 51, -9, 21, 4, 4, -34, 7, -78,
1301+ 16, 6, -38, -30, -2, -44, 32, 0,
1302+ 22, 64, 5, -72, -2, -14, -10, -16,
1303+ -8, -25, 12, 102, -58, 37, -10, -23,
1304+ 15, 49, 7, -7, 2, -20, -32, 45,
1305+ -6, 48, 28, 30, 33, -1, 22, -6,
1306+ 30, 65, -17, 29, 74, 37, -26, -10,
1307+ 15, -24, 19, -66, 22, -10, -31, -1,
1308+ -18, -9, 11, 37, -4, 45, 5, 41,
1309+ 17, 1, 1, 24, -58, 41, 5, -51,
1310+ 14, 8, 43, 16, -10, -1, 45, 32,
1311+ -64, 3, -33, -25, -3, -27, -68, 12,
1312+ 23, -11, -13, -37, -40, 4, -21, -12,
1313+ 32, -23, -19, 76, 41, -23, -24, -44,
1314+ -65, -1, -15, 1, 71, 63, 5, 20,
1315+ -3, 21, -23, 31, -32, 18, -2, 27,
1316+ 31, 46, -5, -39, -5, -35, 18, -18,
1317+ -40, -10, 3, 12, 2, -2, -22, 40,
1318+ 5, -6, 60, 36, 3, 29, -27, 10,
1319+ 25, -54, 5, 26, 39, 35, -24, -37,
1320+ 30, -91, 28, -4, -21, -27, -39, -6,
1321+ 5, 12, -128, 38, -16, 29, -95, -29,
1322+ 82, -2, 35, 2, 12, 8, -22, 10,
1323+ 80, -47, 2, -25, -73, -79, 16, -30,
1324+ -32, -66, 48, 21, -45, -11, -47, 14,
1325+ -27, -17, -7, 15, -44, -14, -44, -26,
1326+ -32, 26, -23, 17, -7, -28, 26, -6,
1327+ 28, 6, -26, 2, 13, -14, -23, -14,
1328+ 19, 46, 16, 2, -33, -21, 28, -17,
1329+ -42, 44, -37, 1, -39, 28, 84, -46,
1330+ 15, 10, 13, -44, 72, -26, 26, 32,
1331+ -28, -12, -83, 2, 10, -30, -44, -10,
1332+ -28, 53, 45, 65, 0, -25, 57, 36,
1333+ -33, 6, 29, 44, -53, 11, 19, -2,
1334+ -27, 35, 32, 49, 4, 23, 38, 36,
1335+ 24, 10, 51, -39, 4, -7, 26, 37,
1336+ -35, 11, -47, -18, 28, 16, -35, 42,
1337+ 17, -21, -41, 28, 14, -12, 11, -45,
1338+ 7, -43, -15, 18, -5, 38, -40, -50,
1339+ -30, -21, 9, -98, 13, 12, 23, 75,
1340+ -56, -7, -3, -4, -1, -34, 12, -49,
1341+ 11, 26, -18, -28, -17, 33, 13, -14,
1342+ 40, 24, -72, -37, 10, 17, -6, 22,
1343+ 16, 16, -6, -12, -30, -14, 10, 40,
1344+ -23, 12, 15, -3, -15, 13, -56, -4,
1345+ -30, 1, -3, -17, 27, 50, -5, 64,
1346+ -36, -19, 7, 29, 22, 25, 9, -16,
1347+ -58, -69, -40, -61, -71, -14, 42, 93,
1348+ 26, 11, -6, -58, -11, 70, -52, 19,
1349+ 9, -30, -33, 11, -37, -47, -21, -22,
1350+ -40, 10, 47, 4, -23, 17, 48, 41,
1351+ -48, 14, 10, 15, 34, -23, -2, -47,
1352+ 23, -32, -13, -10, -26, -26, -4, 16,
1353+ 38, -14, 0, -12, -7, -7, 20, 44,
1354+ -1, -32, -27, -16, 4, -6, -18, 14,
1355+ 5, 4, -29, 28, 7, -7, 15, -11,
1356+ -20, -45, -36, 16, 84, 34, -59, -30,
1357+ 22, 126, 8, 68, 79, -17, 21, -68,
1358+ 37, 5, 15, 63, 49, 127, -90, 85,
1359+ 43, 7, 16, 9, 6, -45, -57, -43,
1360+ 57, 11, -23, -11, -29, 60, -26, 0,
1361+ 7, 42, -24, 10, 23, -25, 8, -7,
1362+ -40, 19, -17, 35, 4, 27, -39, -91,
1363+ 27, -36, 34, 2, 16, -24, 25, 7,
1364+ -21, 5, 17, 10, -22, -30, 9, -17,
1365+ -61, -26, 33, 21, 58, -51, -14, 69,
1366+ -38, 20, 7, 80, -4, -65, -6, -27,
1367+ 53, -12, 47, -1, -15, 1, 60, 102,
1368+ -79, -4, 12, 9, 22, 37, -8, -4,
1369+ 37, 2, -3, -15, -16, -11, -5, 19,
1370+ -6, -43, 20, -25, -18, 10, -27, 0,
1371+ -28, -27, -11, 10, -18, -2, -4, -16,
1372+ 26, 14, -6, 7, -6, 1, 53, -2,
1373+ -29, 23, 9, -30, -6, -4, -6, 56,
1374+ 70, 0, -33, -20, -17, -9, -24, 46,
1375+ -5, -105, 47, -46, -51, 20, 20, -53,
1376+ -81, -1, -7, 75, -5, -21, -65, 12,
1377+ -52, 22, -50, -12, 49, 54, 76, -81,
1378+ 10, 45, -41, -59, 18, -19, 25, 14,
1379+ -31, -53, -5, 12, 31, 84, -23, 2,
1380+ 7, 2, 10, -32, 39, -2, -12, 1,
1381+ -9, 0, -10, -11, 9, 15, -8, -2,
1382+ 2, -1, 10, 14, -5, -40, 19, -7,
1383+ -7, 26, -4, 2, 1, -27, 35, 32,
1384+ 21, -31, 26, 43, -9, 4, -32, 40,
1385+ -62, -52, 36, 22, 38, 22, 36, -96,
1386+ 6, -10, -23, -49, 15, -33, -18, -3,
1387+ 0, 41, 21, -19, 21, 23, -39, -23,
1388+ -6, 6, 47, 56, 4, 74, 0, -98,
1389+ 29, -47, -14, -36, 21, -22, 22, 16,
1390+ 13, 12, 16, -5, 13, 17, -13, -15,
1391+ 1, -34, -26, 26, 12, 32, 27, 13,
1392+ -67, 27, 2, 8, 10, 18, 16, 20,
1393+ -17, -17, 57, -64, 5, 14, 19, 31,
1394+ -18, -44, -46, -16, 4, -25, 17, -126,
1395+ -24, 39, 4, 8, 55, -25, -34, 39,
1396+ -16, 3, 9, 71, 72, -31, -55, 6,
1397+ 10, -25, 32, -85, -21, 18, -8, 15,
1398+ 12, -27, -7, 1, -21, -2, -5, 48,
1399+ -16, 18, 1, -22, -26, 16, 14, -31,
1400+ 27, -6, -15, -21, 4, -14, 18, -36,
1401+];
1402+
1403+static LAYER1_RECUR_WEIGHTS: [i8; 1728] = [
1404+ 20, 67, -99, 12, 41, -25, 49, -44,
1405+ 35, 81, 110, 47, 34, -66, -14, 14,
1406+ -60, 34, 29, -73, 10, 41, 35, 89,
1407+ 7, -35, 22, 7, 27, -20, -6, 56,
1408+ 26, 66, 6, 33, -55, 53, 1, -21,
1409+ 14, 17, 68, 55, 59, 0, 18, -9,
1410+ 5, -41, 6, -5, -114, -12, 29, 42,
1411+ -23, 10, 81, -27, 20, -53, -30, -62,
1412+ 40, 95, 25, -4, 3, 18, -8, -15,
1413+ -29, -82, 2, -57, -3, -61, -29, -29,
1414+ 49, 2, -55, 5, -69, -99, -49, -51,
1415+ 6, -25, 12, 89, 44, -33, 5, 41,
1416+ 1, 23, -37, -37, -28, -48, 3, 4,
1417+ -41, -30, -57, -35, -39, -1, -13, -56,
1418+ -5, 50, 49, 41, -4, -4, 33, -22,
1419+ -1, 33, 34, 18, 40, -42, 12, 1,
1420+ -6, -2, 18, 17, 39, 44, 11, 65,
1421+ -60, -45, 10, 91, 21, 9, -62, -11,
1422+ 8, 69, 37, 24, -30, 21, 26, -27,
1423+ 1, -28, 24, 66, -8, 6, -71, 34,
1424+ 24, 44, 58, -78, -19, 57, 17, -60,
1425+ 1, 12, -3, -1, -40, 22, 11, -5,
1426+ 25, 12, 1, 72, 79, 7, -50, 23,
1427+ 18, 13, 21, -11, -20, 5, 77, -94,
1428+ 24, 15, 57, -51, 3, 36, 53, -1,
1429+ 4, 14, 30, -31, 22, 40, 32, -11,
1430+ -34, -36, -59, 58, 25, 21, -54, -23,
1431+ 40, 46, 18, 0, 12, 54, -96, -99,
1432+ -59, 5, 119, -38, 50, 55, 12, -16,
1433+ 67, 0, 34, 35, 39, 35, -1, 69,
1434+ 24, 27, -30, -35, -4, -70, 2, -44,
1435+ -7, -6, 19, -9, 60, 44, -21, -10,
1436+ 37, 43, -16, -3, 30, -15, -65, 31,
1437+ -55, 18, -98, 76, 64, 25, 24, -18,
1438+ -7, -68, -10, 38, 27, -60, 36, 33,
1439+ 16, 30, 34, -39, -37, 31, 12, 53,
1440+ -54, 14, -26, -49, -128, -13, -5, -22,
1441+ -11, -85, 55, -8, -51, -11, -33, -10,
1442+ -31, -76, -41, 23, 44, -40, -54, -127,
1443+ -101, 19, -23, -15, 15, 27, 58, -60,
1444+ 8, 14, -33, 1, 48, -9, -11, -123,
1445+ 3, 53, 23, 4, -28, 22, 2, -29,
1446+ -67, 36, 12, 7, 55, -21, 88, 20,
1447+ -1, -21, -17, 3, 41, 32, -10, -14,
1448+ -5, -57, 67, 57, 21, 23, -2, -27,
1449+ -73, -24, 120, 21, 18, -35, 42, -7,
1450+ 3, -45, -25, 76, -34, 50, 11, -54,
1451+ -91, 3, -113, -20, -5, 47, 15, -47,
1452+ 17, 27, -3, -26, -7, 10, 7, 74,
1453+ -40, 64, -7, -5, -24, -49, -24, -3,
1454+ -10, 27, -17, -8, -3, 14, -27, 33,
1455+ 13, 39, 28, -7, -38, 29, 16, 44,
1456+ 19, 55, -3, 9, -13, -57, 43, 43,
1457+ 31, 0, -93, -17, 19, -56, 4, -12,
1458+ -25, 37, -85, -13, -118, 33, -17, 56,
1459+ 71, -80, -4, 6, -11, -18, 47, -52,
1460+ 25, 9, 48, -107, 1, 21, 20, -3,
1461+ 10, -16, -4, 24, 17, 31, -61, -18,
1462+ -50, 24, -10, 12, 71, 26, 11, -3,
1463+ 4, 1, 0, -7, -40, 18, 38, -34,
1464+ 38, 17, 8, -34, 2, 21, 123, -32,
1465+ -26, 43, 14, -34, -1, -9, 37, -16,
1466+ 6, -17, -62, 68, 22, 17, 11, -75,
1467+ 33, -80, 62, -9, -75, 76, 36, -41,
1468+ -8, -40, -11, -71, 40, -39, 62, -49,
1469+ -81, 16, -9, -52, 52, 61, 17, -103,
1470+ -27, -10, -8, -54, -57, 21, 23, -16,
1471+ -52, 36, 18, 10, -5, 8, 15, -29,
1472+ 5, -19, -37, 8, -53, 6, 19, -37,
1473+ 38, -17, 48, 10, 0, 81, 46, 70,
1474+ -29, 101, 11, 44, -44, -3, 24, 11,
1475+ 3, 14, -9, 11, 14, -45, 13, 46,
1476+ -3, -57, 68, 44, 63, 98, 25, -28,
1477+ -23, 15, 32, -10, 53, -6, -2, -9,
1478+ -6, 16, -107, -11, -11, -28, 59, 57,
1479+ -22, 38, 42, 83, 27, 5, 29, -30,
1480+ 12, -21, -13, 31, 38, -21, 58, -10,
1481+ -10, -15, -2, -5, 11, 12, -73, -28,
1482+ -38, 22, 2, -25, 73, -52, -12, -55,
1483+ 32, -63, 21, 51, 33, 52, -26, 55,
1484+ -26, -26, 57, -32, -4, -52, -61, 21,
1485+ -33, -91, -51, 69, -90, -53, -38, -44,
1486+ 12, -76, -20, 77, -45, -7, 86, 43,
1487+ -109, -33, -105, -40, -121, -10, 0, -72,
1488+ 45, -51, -75, -49, -38, -1, -62, 18,
1489+ -1, 30, -44, -14, -10, -67, 40, -10,
1490+ -34, 46, -64, -32, 29, -13, 33, 3,
1491+ -32, -5, 28, -27, -25, 93, 24, 68,
1492+ -40, 57, 23, -3, -21, -58, 17, -39,
1493+ -17, -22, -89, 11, 18, -46, 27, 24,
1494+ 46, 127, 61, 87, 31, 127, -36, 47,
1495+ -23, 47, 127, -24, 110, 122, 30, 100,
1496+ 0, 96, -12, 6, 50, 44, -13, 73,
1497+ 4, 55, -11, -15, 49, 42, -6, 20,
1498+ -35, 58, 18, 38, 42, 72, 19, -21,
1499+ 11, 9, -37, 7, 29, 31, 16, -17,
1500+ 13, -50, 19, 5, -23, 51, -16, -5,
1501+ 4, -24, 76, 10, -53, -28, -7, -65,
1502+ 74, 40, -16, -29, 32, -16, -49, -35,
1503+ -3, 59, -96, -50, -43, -43, -61, -15,
1504+ -8, -36, -34, -33, -14, 11, -3, -39,
1505+ 4, -114, -123, -11, -49, -21, 14, -56,
1506+ 1, 43, -63, 26, 40, 18, -10, -26,
1507+ -14, -15, -35, -35, -11, 32, -44, -67,
1508+ 2, 22, 7, 3, -9, -30, -51, -28,
1509+ 28, 6, -22, 16, 34, -25, -52, -54,
1510+ -8, -6, 5, 8, 20, -16, -17, -44,
1511+ 27, 3, 31, -5, -48, -1, -3, 116,
1512+ 11, 71, -31, -47, 109, 50, -22, -12,
1513+ -57, 32, 66, 8, -25, -93, -54, -10,
1514+ 19, -76, -34, 97, 48, -36, -18, -30,
1515+ -39, -26, -12, 28, 14, 12, -12, -31,
1516+ 38, 2, 10, 4, -40, 20, 16, -61,
1517+ 2, 64, 39, 5, 15, 33, 40, -61,
1518+ -49, 93, -10, 33, 28, -11, -27, -18,
1519+ 39, -62, -6, -6, 62, 11, -8, 38,
1520+ -67, 12, 27, 39, -27, 123, -18, -6,
1521+ -65, 83, -64, 20, 19, -11, 33, 24,
1522+ 17, 56, 78, 7, -15, 54, -101, -9,
1523+ 115, -96, 50, 51, 35, 34, 27, 37,
1524+ -40, -11, 8, -36, 42, -45, 2, -23,
1525+ 0, 67, -8, -9, -13, 50, -14, -27,
1526+ 4, 0, -8, -14, 30, -9, 29, 15,
1527+ 9, -38, 37, -8, 50, -46, 54, 41,
1528+ -11, -8, -11, -26, 39, 45, 14, -26,
1529+ -17, -27, 69, 38, 39, 98, 66, 0,
1530+ 42, 123, -101, -19, -83, 117, -32, 56,
1531+ 10, 12, -88, 79, -53, 56, 63, 95,
1532+ -62, 9, 36, -13, -79, -16, 37, -46,
1533+ 35, -34, 14, 17, -54, 5, 21, -7,
1534+ 7, 63, 56, 15, 27, -76, -25, 4,
1535+ -26, -63, 28, -67, -52, 43, -47, -70,
1536+ 40, -12, 40, -66, -37, 0, 35, 37,
1537+ -53, 4, -17, -51, 11, 21, 14, -34,
1538+ -4, 24, -42, 29, 22, 7, 28, 12,
1539+ 37, 39, -39, -19, 65, -60, -50, -2,
1540+ 1, 82, 39, 19, -23, -43, -22, -67,
1541+ -35, -34, 32, 102, 81, 127, 36, 67,
1542+ -45, 1, -67, -52, -4, 35, 20, 28,
1543+ 71, 86, -35, -9, -83, -34, 12, 9,
1544+ -23, 2, 14, 28, -23, 7, -25, 45,
1545+ 7, 17, -37, 0, -19, 31, 26, 40,
1546+ -27, -16, 17, 5, -21, 23, 24, 96,
1547+ -55, 52, -19, -14, -6, 1, 50, -34,
1548+ 86, -53, 38, 2, -52, -36, -13, 60,
1549+ -85, -120, 32, 7, -12, 22, 70, -7,
1550+ -94, 38, -76, -31, -20, 15, -28, 7,
1551+ 6, 40, 53, 88, 3, 38, 18, -8,
1552+ -22, -23, 51, 37, -9, 13, -32, 25,
1553+ -21, 27, 31, 20, 18, -9, -13, 1,
1554+ 21, -24, -13, 39, 15, -11, -29, -36,
1555+ 18, 15, 8, 27, 21, -94, -1, -22,
1556+ 49, 66, -1, 6, -3, -40, -18, 6,
1557+ 28, 12, 33, -59, 62, 60, -48, 90,
1558+ -1, 108, 9, 18, -2, 27, 77, -65,
1559+ 82, -48, -38, -19, -11, 127, 50, 66,
1560+ 18, -13, -22, 60, -38, 40, -14, -26,
1561+ -13, 38, 67, 57, 30, 33, 26, 36,
1562+ 38, -17, 27, -28, 20, 12, -64, 18,
1563+ 5, -33, -27, 13, -26, 32, 35, -5,
1564+ -48, -14, 92, 43, -47, -14, 40, 11,
1565+ 51, 66, 22, -63, -16, -61, 4, -28,
1566+ 27, 20, -33, -30, -21, -29, -53, 31,
1567+ -40, 24, 43, -4, -19, 21, 67, 20,
1568+ 100, -16, -93, 78, -6, -18, -52, -37,
1569+ -9, 66, -31, -8, 26, 18, 4, 24,
1570+ -22, 17, -2, -13, 27, 0, 8, -18,
1571+ -25, 5, -21, -24, -7, 18, -93, 21,
1572+ 7, 2, -75, 69, 50, -5, -15, -17,
1573+ 60, -42, 55, 1, -4, 3, 10, 46,
1574+ 16, -13, 45, -7, -10, -44, -108, 49,
1575+ 2, -15, -64, -12, -72, 32, -38, -45,
1576+ 10, -54, 13, -13, -27, -36, -64, 58,
1577+ -62, -101, 88, -86, -71, -39, -9, -128,
1578+ 32, 15, -4, 54, -16, -39, -26, -36,
1579+ 46, 48, -64, -10, 19, 30, -13, 34,
1580+ -8, 50, 60, -22, -6, -11, -30, 5,
1581+ 50, 32, 56, 0, 25, 6, 68, 11,
1582+ -29, 45, -9, -12, 4, 1, 18, -49,
1583+ 0, -38, -19, 90, 29, 35, 51, 8,
1584+ -48, 96, -1, -12, -9, -32, -63, -65,
1585+ -7, 38, 89, 28, -85, -28, -23, -25,
1586+ -128, 56, 79, -36, 99, -6, -37, 7,
1587+ -13, -69, -46, -29, 25, 64, -21, 17,
1588+ 1, 42, -66, 1, 80, 26, -32, 21,
1589+ 15, 15, 6, 6, -10, 15, 127, 5,
1590+ 38, 27, 87, -57, -25, 11, 72, -21,
1591+ -5, 11, -13, -66, 78, 36, -3, 41,
1592+ -21, 8, -33, 23, 73, 28, 57, -25,
1593+ -5, 4, -22, -47, 15, 4, -57, -72,
1594+ 33, 1, 18, 2, 53, -71, -99, -21,
1595+ -3, -111, 108, 71, -14, 82, 25, 61,
1596+ -48, 5, 9, -51, -20, -25, -3, 14,
1597+ -33, 14, -3, -34, 22, 12, -19, -38,
1598+ -16, 2, 21, 16, 26, -31, 75, 44,
1599+ -31, 16, 26, 66, 17, -9, -22, -22,
1600+ 22, -44, 22, 27, 2, 58, -14, 10,
1601+ -73, -42, 55, -25, -61, 72, -1, 30,
1602+ -58, -25, 63, 26, -48, -40, 26, -30,
1603+ 60, 8, -17, -1, -18, -20, 43, -20,
1604+ -4, -28, 127, -106, 29, 70, 64, -27,
1605+ 39, -33, -5, -88, -40, -52, 26, 44,
1606+ -17, 23, 2, -49, 22, -9, -8, 86,
1607+ 49, -43, -60, 1, 10, 45, 36, -53,
1608+ -4, 33, 38, 48, -72, 1, 19, 21,
1609+ -65, 4, -5, -62, 27, -25, 17, -6,
1610+ 6, -45, -39, -46, 4, 26, 127, -9,
1611+ 18, -33, -18, -3, 33, 2, -5, 15,
1612+ -26, -22, -117, -63, -17, -59, 61, -74,
1613+ 7, -47, -58, -128, -67, 15, -16, -128,
1614+ 12, 2, 20, 9, -48, -40, 43, 3,
1615+ -40, -16, -38, -6, -22, -28, -16, -59,
1616+ -22, 6, -5, 11, -12, -66, -40, 27,
1617+ -62, -44, -19, 38, -3, 39, -8, 40,
1618+ -24, 13, 21, 50, -60, -22, 53, -29,
1619+ -6, 1, 22, -59, 0, 17, -39, 115,
1620+];
1621+
1622+static LAYER1_BIAS: [i8; 72] = [
1623+ -42, 20, 16, 0, 105, 60, 1, -97,
1624+ 24, 60, 18, 13, 62, 25, 127, 34,
1625+ 79, 55, 118, 127, 95, 31, -4, 87,
1626+ 21, 12, 2, -14, 18, 23, 8, 17,
1627+ -1, -8, 5, 4, 24, 37, 21, 13,
1628+ 36, 13, 17, 18, 37, 30, 33, 1,
1629+ 8, -16, -11, -5, -31, -3, -5, 0,
1630+ 6, 3, 58, -7, -1, -16, 5, -13,
1631+ 16, 10, -2, -14, 11, -4, 3, -11,
1632+];
1633+
1634+static LAYER2_WEIGHTS: [i8; 48] = [
1635+ -113, -88, 31, -128, -126, -61, 85, -35,
1636+ 118, -128, -61, 127, -128, -17, -128, 127,
1637+ 104, -9, -128, 33, 45, 127, 5, 83,
1638+ 84, -128, -85, -128, -45, 48, -53, -128,
1639+ 46, 127, -17, 125, 117, -41, -117, -91,
1640+ -127, -68, -1, -89, -80, 32, 106, 7,
1641+];
1642+
1643+static LAYER2_BIAS: [i8; 2] = [
1644+ 14, 117,
1645+];
crates/ec-opus/src/celt_enc.rsmodified+91 -0
@@ -32,6 +32,7 @@
32 32
33 use ec_core::{Error, Result};33 use ec_core::{Error, Result};
34 34
35+use crate::analysis::{AnalysisInfo, TonalityAnalysis};
35 use crate::celt::{36 use crate::celt::{
36 self, BETA_COEF, BETA_INTRA, BITRES, CACHE_CAPS, E_BANDS, E_MEANS, E_PROB_MODEL, LOG_N,37 self, BETA_COEF, BETA_INTRA, BITRES, CACHE_CAPS, E_BANDS, E_MEANS, E_PROB_MODEL, LOG_N,
37 MAX_FINE_BITS, NB_BANDS, OVERLAP, PRED_COEF, PREEMPH, QTHETA_OFFSET, QTHETA_OFFSET_TWOPHASE,38 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) {
59 })60 })
60 }61 }
61 62
63+/// Which consumers of the [`crate::analysis`] tonality analysis are live.
64+///
65+/// The analysis itself runs whenever `EC_OPUS_ANALYSIS` is not `0`; each
66+/// downstream term was measured on the 12-row library gate on its own, so
67+/// each keeps its own switch (`1`/`0`) around the shipped default:
68+/// `EC_OPUS_TRIM_TONAL` (`alloc_trim`'s `tonality_slope` term),
69+/// `EC_OPUS_TRIM13` (the continuous 1.3 trim the term belongs to),
70+/// `EC_OPUS_VBR_TONAL` (`compute_vbr`'s tonality boost) and
71+/// `EC_OPUS_VBR_ACT` (`compute_vbr`'s low-activity cut).
72+fn analysis_params() -> (bool, bool, bool, bool) {
73+ static P: std::sync::OnceLock<(bool, bool, bool, bool)> = std::sync::OnceLock::new();
74+ *P.get_or_init(|| {
75+ let b = |name: &str, dflt: bool| {
76+ std::env::var(name).map(|v| v != "0").unwrap_or(dflt)
77+ };
78+ (
79+ b("EC_OPUS_ANALYSIS", true),
80+ b("EC_OPUS_TRIM_TONAL", false),
81+ b("EC_OPUS_VBR_TONAL", false),
82+ b("EC_OPUS_VBR_ACT", false),
83+ )
84+ })
85+}
86+
62 const CACHE_BITS: &[u8] = &crate::celt::CACHE_BITS;87 const CACHE_BITS: &[u8] = &crate::celt::CACHE_BITS;
63 const INV_TABLE: [u8; 128] = [88 const INV_TABLE: [u8; 128] = [
64 255,255,156,110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25,89 255,255,156,110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25,
@@ -351,6 +376,18 @@ pub struct CeltFrameDiag {
351 pub pulses: [i32; NB_BANDS],376 pub pulses: [i32; NB_BANDS],
352 /// Per-band fine-energy precision bits.377 /// Per-band fine-energy precision bits.
353 pub fine_quant: [i32; NB_BANDS],378 pub fine_quant: [i32; NB_BANDS],
379+ /// Whether the tonality analysis produced a usable window for this frame.
380+ pub analysis_valid: bool,
381+ /// `AnalysisInfo::music_prob` — 0 is speech, 1 is music.
382+ pub music_prob: f32,
383+ /// `AnalysisInfo::tonality`.
384+ pub tonality: f32,
385+ /// `AnalysisInfo::tonality_slope`, `alloc_trim`'s input.
386+ pub tonality_slope: f32,
387+ /// `AnalysisInfo::activity`, `compute_vbr`'s input.
388+ pub activity: f32,
389+ /// `AnalysisInfo::bandwidth`, the detected bandwidth band index.
390+ pub analysis_bandwidth: i32,
354 }391 }
355 392
356 impl Default for CeltFrameDiag {393 impl Default for CeltFrameDiag {
@@ -371,6 +408,12 @@ impl Default for CeltFrameDiag {
371 band_log_e: [0.0; 2 * NB_BANDS],408 band_log_e: [0.0; 2 * NB_BANDS],
372 pulses: [0; NB_BANDS],409 pulses: [0; NB_BANDS],
373 fine_quant: [0; NB_BANDS],410 fine_quant: [0; NB_BANDS],
411+ analysis_valid: false,
412+ music_prob: 0.0,
413+ tonality: 0.0,
414+ tonality_slope: 0.0,
415+ activity: 0.0,
416+ analysis_bandwidth: 0,
374 }417 }
375 }418 }
376 }419 }
@@ -448,6 +491,13 @@ pub struct CeltEncoder {
448 urow: Vec<u32>,491 urow: Vec<u32>,
449 /// Per-frame diagnostics captured at the end of the last `encode` call.492 /// Per-frame diagnostics captured at the end of the last `encode` call.
450 last_diag: CeltFrameDiag,493 last_diag: CeltFrameDiag,
494+ /// libopus `st->analysis`: the tonality/music-probability estimator, run
495+ /// on the *undelayed* API input at the top of every `encode` call exactly
496+ /// where `opus_encode()` runs `run_analysis()`.
497+ analysis: TonalityAnalysis,
498+ /// The window that covers the frame being coded, or the default
499+ /// (`valid == false`) state when the analysis is off.
500+ info: AnalysisInfo,
451 }501 }
452 502
453 impl CeltEncoder {503 impl CeltEncoder {
@@ -505,6 +555,8 @@ impl CeltEncoder {
505 pvq_sign: vec![0; max_n],555 pvq_sign: vec![0; max_n],
506 urow: vec![0; 1280],556 urow: vec![0; 1280],
507 last_diag: CeltFrameDiag::default(),557 last_diag: CeltFrameDiag::default(),
558+ analysis: TonalityAnalysis::new((48000 / upsample) as u32),
559+ info: AnalysisInfo::default(),
508 }560 }
509 }561 }
510 562
@@ -547,6 +599,8 @@ impl CeltEncoder {
547 self.vbr_count = 0;599 self.vbr_count = 0;
548 self.stereo_saving = 0.0;600 self.stereo_saving = 0.0;
549 self.spec_avg = 0.0;601 self.spec_avg = 0.0;
602+ self.analysis.reset();
603+ self.info = AnalysisInfo::default();
550 }604 }
551 605
552 /// Encodes one frame of interleaved `f32` (`frame_size` samples per606 /// Encodes one frame of interleaved `f32` (`frame_size` samples per
@@ -592,6 +646,16 @@ impl CeltEncoder {
592 }646 }
593 let end = end.clamp(start + 1, NB_BANDS);647 let end = end.clamp(start + 1, NB_BANDS);
594 648
649+ // libopus `opus_encode_native` runs the tonality analysis on the raw
650+ // API frame before anything else; the CELT layer's own delay does not
651+ // apply to it, so this reads `pcm` and not the delayed buffer. 24 is
652+ // libopus's `lsb_depth` default for the float API.
653+ self.info = if analysis_params().0 {
654+ self.analysis.run(pcm, in_n, c, 24)
655+ } else {
656+ AnalysisInfo::default()
657+ };
658+
595 let mut nb_compressed = enc.storage();659 let mut nb_compressed = enc.storage();
596 let mut nb_available = nb_compressed as i32;660 let mut nb_available = nb_compressed as i32;
597 // The target rate in 1/8-bit units per frame, VBR only.661 // The target rate in 1/8-bit units per frame, VBR only.
@@ -942,6 +1006,7 @@ impl CeltEncoder {
942 let base_target =1006 let base_target =
943 vbr_rate + (self.vbr_offset >> lm_diff) - ((40 * c as i32 + 20) << BITRES);1007 vbr_rate + (self.vbr_offset >> lm_diff) - ((40 * c as i32 + 20) << BITRES);
944 let mut target = base_target;1008 let mut target = base_target;
1009+ let (_, _, vbr_tonal, vbr_act) = analysis_params();
945 // compute_vbr (libopus celt_encoder.c:1605-1716), float-mode.1010 // compute_vbr (libopus celt_encoder.c:1605-1716), float-mode.
946 // Skipped: activity, tonality, surround_mask (analysis->valid=1011 // Skipped: activity, tonality, surround_mask (analysis->valid=
947 // false, has_surround_mask=0, pitch_change=0, lfe=0). The qext1012 // false, has_surround_mask=0, pitch_change=0, lfe=0). The qext
@@ -956,6 +1021,10 @@ impl CeltEncoder {
956 if c == 2 {1021 if c == 2 {
957 coded_bins += E_BANDS[self.intensity.min(coded_bands)] << lm;1022 coded_bins += E_BANDS[self.intensity.min(coded_bands)] << lm;
958 }1023 }
1024+ // Low-activity cut (C:1632-1633).
1025+ if vbr_act && self.info.valid && self.info.activity < 0.4 {
1026+ target -= ((coded_bins << BITRES) as f32 * (0.4 - self.info.activity)) as i32;
1027+ }
959 // Stereo savings (C:1636-1649)1028 // Stereo savings (C:1636-1649)
960 if c == 2 {1029 if c == 2 {
961 let coded_stereo_bands = self.intensity.min(coded_bands);1030 let coded_stereo_bands = self.intensity.min(coded_bands);
@@ -1010,6 +1079,12 @@ impl CeltEncoder {
1010 let k_eff = if fires { k } else { 1.0 };1079 let k_eff = if fires { k } else { 1.0 };
1011 target += (k_eff * (tf_estimate - off) * target as f32) as i32;1080 target += (k_eff * (tf_estimate - off) * target as f32) as i32;
1012 }1081 }
1082+ // Tonality boost (C:1658-1669), compensating for the average.
1083+ // `pitch_change` is 0 here (no prefilter), so its term is absent.
1084+ if vbr_tonal && self.info.valid {
1085+ let tonal = (self.info.tonality - 0.15).max(0.0) - 0.12;
1086+ target += ((coded_bins << BITRES) as f32 * 1.2 * tonal) as i32;
1087+ }
1013 // floor depth cap (C:1683-1695): SHR32/MULT16_32_Q15 are identity.1088 // floor depth cap (C:1683-1695): SHR32/MULT16_32_Q15 are identity.
1014 {1089 {
1015 let bins = E_BANDS[NB_BANDS - 2] << lm;1090 let bins = E_BANDS[NB_BANDS - 2] << lm;
@@ -1228,6 +1303,12 @@ impl CeltEncoder {
1228 band_log_e,1303 band_log_e,
1229 pulses: self.pulses,1304 pulses: self.pulses,
1230 fine_quant: self.fine_quant,1305 fine_quant: self.fine_quant,
1306+ analysis_valid: self.info.valid,
1307+ music_prob: self.info.music_prob,
1308+ tonality: self.info.tonality,
1309+ tonality_slope: self.info.tonality_slope,
1310+ activity: self.info.activity,
1311+ analysis_bandwidth: self.info.bandwidth,
1231 };1312 };
1232 Ok(nb_compressed)1313 Ok(nb_compressed)
1233 }1314 }
@@ -1651,14 +1732,24 @@ impl CeltEncoder {
1651 * (2 + 2 * i as i32 - NB_BANDS as i32) as f32;1732 * (2 + 2 * i as i32 - NB_BANDS as i32) as f32;
1652 }1733 }
1653 }1734 }
1735+ // libopus's `analysis->valid` term (celt_encoder.c:935-939): a tonal
1736+ // spectrum wants a lower trim. It is only defined on the continuous
1737+ // 1.3 trim; on the discrete ladder it can only be applied rounded.
1738+ let tonal_trim = if analysis_params().1 && self.info.valid {
1739+ (2.0 * (self.info.tonality_slope + 0.05)).clamp(-2.0, 2.0)
1740+ } else {
1741+ 0.0
1742+ };
1654 if cont {1743 if cont {
1655 // libopus divides the same sum by `C*(end-1)`; the ladder above1744 // libopus divides the same sum by `C*(end-1)`; the ladder above
1656 // carries an extra factor of two in its thresholds.1745 // carries an extra factor of two in its thresholds.
1657 let diff = diff / (c * (end - 1)) as f32;1746 let diff = diff / (c * (end - 1)) as f32;
1658 trim_f -= ((diff + 1.0) / 6.0).clamp(-2.0, 2.0);1747 trim_f -= ((diff + 1.0) / 6.0).clamp(-2.0, 2.0);
1659 trim_f -= 2.0 * tf_estimate;1748 trim_f -= 2.0 * tf_estimate;
1749+ trim_f -= tonal_trim;
1660 return (trim_f + 0.5).floor().clamp(0.0, 10.0) as i32;1750 return (trim_f + 0.5).floor().clamp(0.0, 10.0) as i32;
1661 }1751 }
1752+ trim -= tonal_trim.round_ties_even() as i32;
1662 diff /= (2 * c * (end - 1)) as f32;1753 diff /= (2 * c * (end - 1)) as f32;
1663 if diff > 2.0 {1754 if diff > 2.0 {
1664 trim -= 1;1755 trim -= 1;
crates/ec-opus/src/lib.rsmodified+1 -0
@@ -61,6 +61,7 @@
61 #![forbid(unsafe_code)]61 #![forbid(unsafe_code)]
62 #![warn(missing_docs)]62 #![warn(missing_docs)]
63 63
64+pub(crate) mod analysis;
64 pub mod celt;65 pub mod celt;
65 pub mod celt_enc;66 pub mod celt_enc;
66 pub mod encoder;67 pub mod encoder;
crates/ec-opus/tests/conformance.rsmodified+70 -0
@@ -5716,3 +5716,73 @@ fn frame_decisions_vs_libopus() {
5716 }5716 }
5717 5717
5718 const NB_BANDS_DIAG: usize = ec_opus::celt::NB_BANDS;5718 const NB_BANDS_DIAG: usize = ec_opus::celt::NB_BANDS;
5719+
5720+/// The ported tonality analysis (`crates/ec-opus/src/analysis.rs`) must
5721+/// actually tell speech from music, since `music_prob` is what libopus's mode
5722+/// and bandwidth decisions read. Drives the real entry surface
5723+/// (`Encoder::encode_float`) over 30 s of each gate source and reads the
5724+/// per-frame value back through [`CeltFrameDiag`]. Speech (hein) must land
5725+/// clearly below the two music sources (reell, reelo).
5726+#[test]
5727+#[ignore = "needs the local library sources; run with --ignored"]
5728+fn analysis_music_prob_separates_speech_from_music() {
5729+ const SECS: f64 = 30.0;
5730+ const FRAME: usize = 960;
5731+ const CHANNELS: usize = 2;
5732+ let sources: &[(&str, &str, bool)] = &[
5733+ ("hein", "~/Downloads/reelm.mp3", false),
5734+ ("reell", "~/Music/reell.mp4", true),
5735+ ("reelo", "~/Music/reelo.mp3", true),
5736+ ];
5737+ let mut means: Vec<(String, bool, f64)> = Vec::new();
5738+ for (tag, path, is_music) in sources {
5739+ let src = shellexpand(path);
5740+ if !src.exists() {
5741+ eprintln!("SKIP {tag}: missing {}", src.display());
5742+ continue;
5743+ }
5744+ let pcm = ffmpeg_decode_pcm(&src, SECS);
5745+ let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder");
5746+ enc.set_bitrate(96_000);
5747+ enc.set_vbr_constrained(true);
5748+ let mut out = vec![0u8; 4000];
5749+ let mut sum = 0.0f64;
5750+ let mut n = 0usize;
5751+ let mut valid = 0usize;
5752+ for chunk in pcm.chunks_exact(FRAME * CHANNELS) {
5753+ enc.encode_float(chunk, FRAME, &mut out).expect("encode");
5754+ let d = enc.last_celt_diag();
5755+ n += 1;
5756+ if d.analysis_valid {
5757+ valid += 1;
5758+ sum += f64::from(d.music_prob);
5759+ }
5760+ }
5761+ assert!(valid * 10 > n * 9, "{tag}: analysis valid on only {valid}/{n} frames");
5762+ let mean = sum / valid as f64;
5763+ println!("music_prob {tag}: mean {mean:.3} over {valid}/{n} frames (music={is_music})");
5764+ means.push(((*tag).to_string(), *is_music, mean));
5765+ }
5766+ if means.len() < 2 {
5767+ eprintln!("SKIP: fewer than two sources present");
5768+ return;
5769+ }
5770+ let speech: Vec<_> = means.iter().filter(|m| !m.1).collect();
5771+ let music: Vec<_> = means.iter().filter(|m| m.1).collect();
5772+ for s in &speech {
5773+ assert!(s.2 < 0.5, "{}: speech music_prob {:.3} should be < 0.5", s.0, s.2);
5774+ for m in &music {
5775+ assert!(
5776+ m.2 - s.2 > 0.2,
5777+ "{} ({:.3}) does not separate from {} ({:.3}) by 0.2",
5778+ m.0,
5779+ m.2,
5780+ s.0,
5781+ s.2
5782+ );
5783+ }
5784+ }
5785+ for m in &music {
5786+ assert!(m.2 > 0.5, "{}: music music_prob {:.3} should be > 0.5", m.0, m.2);
5787+ }
5788+}