forge
Explore
Log in

Don't you dare go Hollow

SILK encoder analysis front end

Browse files at this commit

79db13a41124a7a677d92ef0c161d91c0fc5b7cbAhmet Kaan GümüşParent: b966d5e
  • feat
    • SILK encoder analysis front end
Show full message
feat(opus-silk): SILK encoder analysis front end

Adds silk_enc.rs: 48k->8/12/16k FIR decimator, simplified VAD, LPC
analysis with unit-circle P/Q NLSF conversion, NLSF VQ search against
the decoder codebooks, pitch estimation and gain quantisation. Decoder
helpers made pub(crate) for reuse; no decoder logic changes.
crates/ec-opus/src/lib.rsmodified+1 -0
@@ -70,6 +70,7 @@ pub mod ogg;
70 pub mod packet;70 pub mod packet;
71 pub mod range;71 pub mod range;
72 pub mod silk;72 pub mod silk;
73+pub(crate) mod silk_enc;
73 74
74 pub use celt::CeltDecoder;75 pub use celt::CeltDecoder;
75 pub use celt_enc::CeltEncoder;76 pub use celt_enc::CeltEncoder;
crates/ec-opus/src/silk.rsmodified+31 -31
@@ -25,16 +25,16 @@ use ec_core::Result;
25 25
26 use crate::range::RangeDecoder;26 use crate::range::RangeDecoder;
27 27
28-mod tables {28+pub(crate) mod tables {
29 #![allow(clippy::all)]29 #![allow(clippy::all)]
30 include!("silk_tables.rs");30 include!("silk_tables.rs");
31 }31 }
32 32
33 use tables::*;33 use tables::*;
34 34
35-const MAX_LPC_ORDER: usize = 16;35+pub(crate) const MAX_LPC_ORDER: usize = 16;
36-const LTP_ORDER: usize = 5;36+pub(crate) const LTP_ORDER: usize = 5;
37-const MAX_NB_SUBFR: usize = 4;37+pub(crate) const MAX_NB_SUBFR: usize = 4;
38 const SUB_FRAME_LENGTH_MS: usize = 5;38 const SUB_FRAME_LENGTH_MS: usize = 5;
39 const LTP_MEM_LENGTH_MS: usize = 20;39 const LTP_MEM_LENGTH_MS: usize = 20;
40 const MAX_FRAME_LENGTH: usize = 20 * 16;40 const MAX_FRAME_LENGTH: usize = 20 * 16;
@@ -44,12 +44,12 @@ const MIN_DELTA_GAIN_QUANT: i32 = -4;
44 const MAX_DELTA_GAIN_QUANT: i32 = 36;44 const MAX_DELTA_GAIN_QUANT: i32 = 36;
45 const MIN_QGAIN_DB: i32 = 2;45 const MIN_QGAIN_DB: i32 = 2;
46 const MAX_QGAIN_DB: i32 = 88;46 const MAX_QGAIN_DB: i32 = 88;
47-const NLSF_QUANT_MAX_AMPLITUDE: i32 = 4;47+pub(crate) const NLSF_QUANT_MAX_AMPLITUDE: i32 = 4;
48 const SHELL_LEN: usize = 16;48 const SHELL_LEN: usize = 16;
49 const MAX_PULSES: i32 = 16;49 const MAX_PULSES: i32 = 16;
50 const N_RATE_LEVELS: usize = 10;50 const N_RATE_LEVELS: usize = 10;
51-const PE_MIN_LAG_MS: i32 = 2;51+pub(crate) const PE_MIN_LAG_MS: i32 = 2;
52-const PE_MAX_LAG_MS: i32 = 18;52+pub(crate) const PE_MAX_LAG_MS: i32 = 18;
53 const STEREO_INTERP_LEN_MS: usize = 8;53 const STEREO_INTERP_LEN_MS: usize = 8;
54 const TYPE_VOICED: i32 = 2;54 const TYPE_VOICED: i32 = 2;
55 const MAX_LPC_STABILIZE_ITERATIONS: usize = 16;55 const MAX_LPC_STABILIZE_ITERATIONS: usize = 16;
@@ -73,18 +73,18 @@ enum CondCoding {
73 // ---------------------------------------------------------------------------73 // ---------------------------------------------------------------------------
74 74
75 #[inline]75 #[inline]
76-fn smulwb(a: i32, b: i32) -> i32 {76+pub(crate) fn smulwb(a: i32, b: i32) -> i32 {
77 (((a >> 16) * (b as i16 as i32)) as i64 + ((((a & 0xFFFF) * (b as i16 as i32)) >> 16) as i64))77 (((a >> 16) * (b as i16 as i32)) as i64 + ((((a & 0xFFFF) * (b as i16 as i32)) >> 16) as i64))
78 as i3278 as i32
79 }79 }
80 80
81 #[inline]81 #[inline]
82-fn smlawb(a: i32, b: i32, c: i32) -> i32 {82+pub(crate) fn smlawb(a: i32, b: i32, c: i32) -> i32 {
83 a.wrapping_add(smulwb(b, c))83 a.wrapping_add(smulwb(b, c))
84 }84 }
85 85
86 #[inline]86 #[inline]
87-fn smulbb(a: i32, b: i32) -> i32 {87+pub(crate) fn smulbb(a: i32, b: i32) -> i32 {
88 (a as i16 as i32).wrapping_mul(b as i16 as i32)88 (a as i16 as i32).wrapping_mul(b as i16 as i32)
89 }89 }
90 90
@@ -94,7 +94,7 @@ fn smlabb(a: i32, b: i32, c: i32) -> i32 {
94 }94 }
95 95
96 #[inline]96 #[inline]
97-fn rshift_round(a: i32, shift: u32) -> i32 {97+pub(crate) fn rshift_round(a: i32, shift: u32) -> i32 {
98 if shift == 1 {98 if shift == 1 {
99 (a >> 1) + (a & 1)99 (a >> 1) + (a & 1)
100 } else {100 } else {
@@ -149,7 +149,7 @@ fn clz_frac(x: i32) -> (i32, i32) {
149 (lz, frac)149 (lz, frac)
150 }150 }
151 151
152-fn sqrt_approx(x: i32) -> i32 {152+pub(crate) fn sqrt_approx(x: i32) -> i32 {
153 if x <= 0 {153 if x <= 0 {
154 return 0;154 return 0;
155 }155 }
@@ -159,7 +159,7 @@ fn sqrt_approx(x: i32) -> i32 {
159 smlawb(y, y, smulbb(213, frac))159 smlawb(y, y, smulbb(213, frac))
160 }160 }
161 161
162-fn log2lin(log_q7: i32) -> i32 {162+pub(crate) fn log2lin(log_q7: i32) -> i32 {
163 if log_q7 < 0 {163 if log_q7 < 0 {
164 return 0;164 return 0;
165 }165 }
@@ -807,19 +807,19 @@ fn decode_signs(
807 }807 }
808 808
809 /// The NLSF codebook for one bandwidth (Section 4.2.7.5).809 /// The NLSF codebook for one bandwidth (Section 4.2.7.5).
810-struct NlsfCodebook {810+pub(crate) struct NlsfCodebook {
811- n_vectors: usize,811+ pub(crate) n_vectors: usize,
812- order: usize,812+ pub(crate) order: usize,
813- quant_step_size_q16: i32,813+ pub(crate) quant_step_size_q16: i32,
814- cb1_q8: &'static [u8],814+ pub(crate) cb1_q8: &'static [u8],
815- cb1_icdf: &'static [u8],815+ pub(crate) cb1_icdf: &'static [u8],
816- pred_q8: &'static [u8],816+ pub(crate) pred_q8: &'static [u8],
817- ec_sel: &'static [u8],817+ pub(crate) ec_sel: &'static [u8],
818- ec_icdf: &'static [u8],818+ pub(crate) ec_icdf: &'static [u8],
819- delta_min_q15: &'static [i16],819+ pub(crate) delta_min_q15: &'static [i16],
820 }820 }
821 821
822-fn nlsf_cb(wideband: bool) -> &'static NlsfCodebook {822+pub(crate) fn nlsf_cb(wideband: bool) -> &'static NlsfCodebook {
823 static NB_MB: NlsfCodebook = NlsfCodebook {823 static NB_MB: NlsfCodebook = NlsfCodebook {
824 n_vectors: 32,824 n_vectors: 32,
825 order: 10,825 order: 10,
@@ -847,7 +847,7 @@ fn nlsf_cb(wideband: bool) -> &'static NlsfCodebook {
847 }847 }
848 848
849 /// `silk_NLSF_unpack`: per-coefficient entropy-table selectors and predictors.849 /// `silk_NLSF_unpack`: per-coefficient entropy-table selectors and predictors.
850-fn nlsf_unpack(cb: &NlsfCodebook, cb1_index: usize) -> ([i16; MAX_LPC_ORDER], [u8; MAX_LPC_ORDER]) {850+pub(crate) fn nlsf_unpack(cb: &NlsfCodebook, cb1_index: usize) -> ([i16; MAX_LPC_ORDER], [u8; MAX_LPC_ORDER]) {
851 let mut ec_ix = [0i16; MAX_LPC_ORDER];851 let mut ec_ix = [0i16; MAX_LPC_ORDER];
852 let mut pred = [0u8; MAX_LPC_ORDER];852 let mut pred = [0u8; MAX_LPC_ORDER];
853 let sel = &cb.ec_sel[cb1_index * cb.order / 2..];853 let sel = &cb.ec_sel[cb1_index * cb.order / 2..];
@@ -862,7 +862,7 @@ fn nlsf_unpack(cb: &NlsfCodebook, cb1_index: usize) -> ([i16; MAX_LPC_ORDER], [u
862 }862 }
863 863
864 /// `silk_NLSF_decode`: indices to normalised LSFs (Section 4.2.7.5.3).864 /// `silk_NLSF_decode`: indices to normalised LSFs (Section 4.2.7.5.3).
865-fn nlsf_decode(indices: &[i8], cb: &NlsfCodebook) -> [i16; MAX_LPC_ORDER] {865+pub(crate) fn nlsf_decode(indices: &[i8], cb: &NlsfCodebook) -> [i16; MAX_LPC_ORDER] {
866 let mut nlsf_q15 = [0i16; MAX_LPC_ORDER];866 let mut nlsf_q15 = [0i16; MAX_LPC_ORDER];
867 let base = indices[0] as usize * cb.order;867 let base = indices[0] as usize * cb.order;
868 for i in 0..cb.order {868 for i in 0..cb.order {
@@ -895,7 +895,7 @@ fn nlsf_decode(indices: &[i8], cb: &NlsfCodebook) -> [i16; MAX_LPC_ORDER] {
895 }895 }
896 896
897 /// `silk_NLSF_VQ_weights_laroia` (Section 4.2.7.5.3).897 /// `silk_NLSF_VQ_weights_laroia` (Section 4.2.7.5.3).
898-fn nlsf_vq_weights_laroia(nlsf_q15: &[i16]) -> [i16; MAX_LPC_ORDER] {898+pub(crate) fn nlsf_vq_weights_laroia(nlsf_q15: &[i16]) -> [i16; MAX_LPC_ORDER] {
899 let d = nlsf_q15.len();899 let d = nlsf_q15.len();
900 let mut w = [0i16; MAX_LPC_ORDER];900 let mut w = [0i16; MAX_LPC_ORDER];
901 let inv = |x: i32| (1i32 << 17) / x.max(1);901 let inv = |x: i32| (1i32 << 17) / x.max(1);
@@ -916,7 +916,7 @@ fn nlsf_vq_weights_laroia(nlsf_q15: &[i16]) -> [i16; MAX_LPC_ORDER] {
916 }916 }
917 917
918 /// `silk_NLSF_stabilize` (Section 4.2.7.5.4): enforce the minimum spacing.918 /// `silk_NLSF_stabilize` (Section 4.2.7.5.4): enforce the minimum spacing.
919-fn nlsf_stabilize(nlsf_q15: &mut [i16], delta_min_q15: &[i16]) {919+pub(crate) fn nlsf_stabilize(nlsf_q15: &mut [i16], delta_min_q15: &[i16]) {
920 let l = nlsf_q15.len();920 let l = nlsf_q15.len();
921 for _ in 0..20 {921 for _ in 0..20 {
922 let mut min_diff = nlsf_q15[0] as i32 - delta_min_q15[0] as i32;922 let mut min_diff = nlsf_q15[0] as i32 - delta_min_q15[0] as i32;
@@ -970,7 +970,7 @@ fn nlsf_stabilize(nlsf_q15: &mut [i16], delta_min_q15: &[i16]) {
970 }970 }
971 971
972 /// `silk_NLSF2A` (Section 4.2.7.5.6): LSFs to LPC coefficients.972 /// `silk_NLSF2A` (Section 4.2.7.5.6): LSFs to LPC coefficients.
973-fn nlsf2a(nlsf: &[i16], order: usize) -> [i16; MAX_LPC_ORDER] {973+pub(crate) fn nlsf2a(nlsf: &[i16], order: usize) -> [i16; MAX_LPC_ORDER] {
974 const QA: u32 = 16;974 const QA: u32 = 16;
975 const ORDER16: [usize; 16] = [0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1];975 const ORDER16: [usize; 16] = [0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1];
976 const ORDER10: [usize; 10] = [0, 9, 6, 3, 4, 5, 8, 1, 2, 7];976 const ORDER10: [usize; 10] = [0, 9, 6, 3, 4, 5, 8, 1, 2, 7];
@@ -1117,7 +1117,7 @@ fn mul32_frac_q(a: i32, b: i32, q: u32) -> i32 {
1117 }1117 }
1118 1118
1119 /// `silk_gains_dequant` (Section 4.2.7.4).1119 /// `silk_gains_dequant` (Section 4.2.7.4).
1120-fn gains_dequant(1120+pub(crate) fn gains_dequant(
1121 indices: &[i8],1121 indices: &[i8],
1122 prev_ind: &mut i32,1122 prev_ind: &mut i32,
1123 conditional: bool,1123 conditional: bool,
@@ -1144,7 +1144,7 @@ fn gains_dequant(
1144 }1144 }
1145 1145
1146 /// `silk_decode_pitch` (Section 4.2.7.6.1).1146 /// `silk_decode_pitch` (Section 4.2.7.6.1).
1147-fn decode_pitch(1147+pub(crate) fn decode_pitch(
1148 lag_index: i32,1148 lag_index: i32,
1149 contour_index: i32,1149 contour_index: i32,
1150 fs_khz: i32,1150 fs_khz: i32,
crates/ec-opus/src/silk_enc.rsadded+947 -0
@@ -0,0 +1,947 @@
1+//! SILK encoder analysis front end (subtask D1).
2+//!
3+//! This module decides *what* a SILK frame should say — resampled input,
4+//! a voice-activity flag, an LPC filter reduced to NLSF codebook indices, a
5+//! pitch contour, and per-subframe gain indices — without writing any of it
6+//! to a bitstream. The NSQ/LTP excitation search and the actual range-coder
7+//! writes are a separate subtask (D2) that consumes the types here; nothing
8+//! in this file touches [`crate::range::RangeEncoder`].
9+//!
10+//! Every quantiser below hands its candidate indices to the *decoder's own*
11+//! functions in [`crate::silk`] (`nlsf_decode`, `nlsf2a`, `gains_dequant`) to
12+//! measure quantisation error, so the indices this module produces are
13+//! guaranteed to be indices the decoder in `silk.rs` can read back — there is
14+//! no separate, possibly-divergent, notion of "encoder-side dequantisation".
15+//!
16+//! The VAD is a simplified energy/spectral-flatness gate, *not* RFC 6716
17+//! Appendix A's cascade of half-band filters and hangover logic — stated
18+//! once, here, for the whole module (assumption called out by the D1
19+//! charter).
20+
21+// D2 (the NSQ/LTP/entropy writer) is the real caller of this API; until
22+// that charter lands, nothing outside this module's own tests exercises it.
23+#![allow(dead_code)]
24+
25+use std::f32::consts::PI;
26+use std::f64::consts::PI as PI64;
27+
28+use crate::silk::tables::{
29+ CB_LAGS_STAGE2, CB_LAGS_STAGE2_10_MS, CB_LAGS_STAGE3, CB_LAGS_STAGE3_10_MS,
30+};
31+use crate::silk::{
32+ gains_dequant, log2lin, nlsf_cb, nlsf_decode, nlsf_unpack, nlsf_vq_weights_laroia, smlawb,
33+ smulbb, sqrt_approx, NlsfCodebook, MAX_LPC_ORDER, MAX_NB_SUBFR, PE_MAX_LAG_MS, PE_MIN_LAG_MS,
34+};
35+
36+#[cfg(test)]
37+use crate::silk::{nlsf2a, nlsf_stabilize};
38+
39+// ---------------------------------------------------------------------------
40+// 1. Resampler: 48 kHz -> SILK's internal 8/12/16 kHz.
41+// ---------------------------------------------------------------------------
42+
43+/// A linear-phase FIR decimator from 48 kHz to a SILK internal rate.
44+///
45+/// This is a windowed-sinc low-pass (Hamming window, unity DC gain) run at
46+/// the decimated rate, independent of the decoder's `Resampler` in
47+/// `silk.rs` — that one's `DELAY_MATRIX_DEC` table only covers *upsampling*
48+/// paths (internal rate -> API rate) and panics on `rate_id` for a 48 kHz
49+/// input, so downsampling needs its own path (charter point 1, "add a down
50+/// path").
51+///
52+/// Group delay is exactly `(taps - 1) / 2` input (48 kHz) samples, because
53+/// the kernel is symmetric — see [`Resampler48::delay_samples`].
54+///
55+/// corner-cut: `process` requires `input.len()` to be a multiple of the
56+/// decimation factor (2, 3, 4 or 6); 20 ms @ 48 kHz (960 samples) always is.
57+/// Upgrade path: track a fractional phase across calls if a caller ever
58+/// needs non-frame-aligned chunks.
59+#[derive(Clone, Debug)]
60+pub(crate) struct Resampler48 {
61+ factor: usize,
62+ taps: Vec<f32>,
63+ history: Vec<f32>,
64+}
65+
66+impl Resampler48 {
67+ /// `target_khz` must be 8, 12 or 16 (SILK's NB/MB/WB internal rates).
68+ pub(crate) fn new(target_khz: u32) -> Self {
69+ assert!(matches!(target_khz, 8 | 12 | 16), "unsupported SILK rate");
70+ let factor = 48 / target_khz as usize;
71+ let n = factor * 8 + 1; // odd -> symmetric -> linear phase
72+ let cutoff = 0.9 / factor as f32;
73+ let center = (n - 1) as f32 / 2.0;
74+ let mut taps = vec![0f32; n];
75+ let mut sum = 0f32;
76+ for (i, tap) in taps.iter_mut().enumerate() {
77+ let x = i as f32 - center;
78+ let sinc = if x == 0.0 {
79+ cutoff
80+ } else {
81+ (PI * cutoff * x).sin() / (PI * x)
82+ };
83+ let w = 0.54 - 0.46 * (2.0 * PI * i as f32 / (n - 1) as f32).cos();
84+ *tap = sinc * w;
85+ sum += *tap;
86+ }
87+ for tap in taps.iter_mut() {
88+ *tap /= sum;
89+ }
90+ Resampler48 {
91+ factor,
92+ taps,
93+ history: vec![0.0; n - 1],
94+ }
95+ }
96+
97+ /// The filter's group delay, in 48 kHz input samples.
98+ pub(crate) fn delay_samples(&self) -> usize {
99+ (self.taps.len() - 1) / 2
100+ }
101+
102+ /// Downsamples `input` (48 kHz), keeping filter history across calls.
103+ /// `input.len()` must be a multiple of the decimation factor.
104+ pub(crate) fn process(&mut self, input: &[f32]) -> Vec<f32> {
105+ debug_assert_eq!(input.len() % self.factor, 0);
106+ let n = self.taps.len();
107+ let mut buf = self.history.clone();
108+ buf.extend_from_slice(input);
109+ let out_len = input.len() / self.factor;
110+ let mut out = Vec::with_capacity(out_len);
111+ for j in 0..out_len {
112+ let start = j * self.factor;
113+ let mut acc = 0f32;
114+ for (k, &tap) in self.taps.iter().enumerate() {
115+ acc += tap * buf[start + k];
116+ }
117+ out.push(acc);
118+ }
119+ let tail_start = buf.len() - (n - 1);
120+ self.history = buf[tail_start..].to_vec();
121+ out
122+ }
123+}
124+
125+// ---------------------------------------------------------------------------
126+// 2. Voice activity detection.
127+// ---------------------------------------------------------------------------
128+
129+/// Per-20ms-frame VAD result.
130+#[derive(Clone, Copy, Debug)]
131+pub(crate) struct VadResult {
132+ pub(crate) active: bool,
133+ pub(crate) speech_prob: f32,
134+}
135+
136+/// Simplified energy + spectral-flatness VAD (not RFC 6716 Appendix A).
137+#[derive(Clone, Debug)]
138+pub(crate) struct Vad {
139+ noise_floor: f32,
140+}
141+
142+impl Default for Vad {
143+ fn default() -> Self {
144+ Vad { noise_floor: 1e-6 }
145+ }
146+}
147+
148+impl Vad {
149+ pub(crate) fn new() -> Self {
150+ Self::default()
151+ }
152+
153+ /// Analyses one frame (any length/rate); a naive DFT gets the magnitude
154+ /// spectrum, so keep frames in the few-hundred-sample range this
155+ /// encoder actually uses (20 ms at 8/12/16 kHz).
156+ pub(crate) fn analyze(&mut self, frame: &[f32]) -> VadResult {
157+ let n = frame.len().max(1);
158+ let energy = frame.iter().map(|&x| x * x).sum::<f32>() / n as f32;
159+
160+ let bins = (n / 2).max(1);
161+ let mut log_sum = 0f64;
162+ let mut lin_sum = 0f64;
163+ for k in 0..bins {
164+ let mut re = 0f32;
165+ let mut im = 0f32;
166+ for (t, &x) in frame.iter().enumerate() {
167+ let theta = -2.0 * PI * k as f32 * t as f32 / n as f32;
168+ re += x * theta.cos();
169+ im += x * theta.sin();
170+ }
171+ let mag = (re * re + im * im).sqrt().max(1e-9) as f64;
172+ log_sum += mag.ln();
173+ lin_sum += mag;
174+ }
175+ let geo_mean = (log_sum / bins as f64).exp();
176+ let arith_mean = lin_sum / bins as f64;
177+ // 0 = perfectly tonal, 1 = white-noise-like.
178+ let flatness = (geo_mean / arith_mean.max(1e-9)) as f32;
179+
180+ // Leaky minimum-follower noise floor.
181+ self.noise_floor = if energy < self.noise_floor {
182+ energy
183+ } else {
184+ self.noise_floor * 0.99 + energy * 0.01
185+ };
186+ let snr_db = 10.0 * (energy / self.noise_floor.max(1e-9)).max(1e-9).log10();
187+
188+ let prob = ((1.0 - flatness).clamp(0.0, 1.0) * (snr_db / 30.0).clamp(0.0, 1.0))
189+ .clamp(0.0, 1.0);
190+ VadResult {
191+ active: prob > 0.15,
192+ speech_prob: prob,
193+ }
194+ }
195+}
196+
197+// ---------------------------------------------------------------------------
198+// 3. LPC analysis: autocorrelation, Levinson-Durbin, LPC -> NLSF.
199+// ---------------------------------------------------------------------------
200+
201+/// One frame's LPC analysis, ready for NLSF quantisation.
202+#[derive(Clone, Debug)]
203+pub(crate) struct LpcAnalysis {
204+ /// Direct-form LPC coefficients (`order` of them), `x[n] ~= sum a[k]*x[n-k-1]`.
205+ pub(crate) lpc: Vec<f64>,
206+ /// Line spectral frequencies, in the decoder's Q15 domain (`nlsf2a`'s
207+ /// own input format), ascending, order-length prefix valid.
208+ pub(crate) nlsf_q15: [i16; MAX_LPC_ORDER],
209+ pub(crate) order: usize,
210+}
211+
212+/// Autocorrelation (lags `0..=order`) with a light Gaussian lag window and a
213+/// white-noise floor added at lag 0, both standard Levinson-Durbin
214+/// stabilisers.
215+fn autocorrelate(frame: &[f32], order: usize) -> Vec<f64> {
216+ let n = frame.len();
217+ let mut r = vec![0f64; order + 1];
218+ for (lag, out) in r.iter_mut().enumerate() {
219+ let mut sum = 0f64;
220+ for t in 0..n.saturating_sub(lag) {
221+ sum += frame[t] as f64 * frame[t + lag] as f64;
222+ }
223+ // Gaussian lag window: exp(-0.5*(2*pi*lag*bw/n)^2), bw ~ 60 Hz worth.
224+ let bw = 60.0 / 8000.0; // fraction of an 8 kHz-equivalent bandwidth
225+ let w = (-0.5 * (2.0 * PI64 * lag as f64 * bw).powi(2)).exp();
226+ *out = sum * w;
227+ }
228+ r[0] *= 1.0 + 1e-4; // white-noise floor
229+ r
230+}
231+
232+/// Levinson-Durbin recursion. Returns `None` if the signal is exactly
233+/// silent (autocorrelation at lag 0 is zero).
234+fn levinson_durbin(autoc: &[f64], order: usize) -> Option<Vec<f64>> {
235+ if autoc[0] <= 0.0 {
236+ return None;
237+ }
238+ let mut a = vec![0f64; order + 1];
239+ let mut err = autoc[0];
240+ for i in 1..=order {
241+ let mut acc = autoc[i];
242+ for j in 1..i {
243+ acc -= a[j] * autoc[i - j];
244+ }
245+ let k = acc / err;
246+ let mut new_a = a.clone();
247+ new_a[i] = k;
248+ for j in 1..i {
249+ new_a[j] = a[j] - k * a[i - j];
250+ }
251+ a = new_a;
252+ err *= 1.0 - k * k;
253+ if err <= 0.0 {
254+ err = 1e-9;
255+ }
256+ }
257+ Some(a[1..=order].to_vec())
258+}
259+
260+/// Bandwidth-expands (moves poles inward by `gamma` per order) so the LPC
261+/// filter this module hands to root-finding is comfortably stable.
262+fn bandwidth_expand(lpc: &mut [f64], gamma: f64) {
263+ let mut g = gamma;
264+ for c in lpc.iter_mut() {
265+ *c *= g;
266+ g *= gamma;
267+ }
268+}
269+
270+/// LPC -> NLSF: the standard line-spectral-pair construction, independent
271+/// of `nlsf2a`'s own internal representation (its `find_poly` builds an
272+/// algebraically different — not root-per-coefficient — polynomial form,
273+/// so inverting it directly is not the way back; this instead rebuilds the
274+/// textbook P(z)/Q(z) split and root-finds those on the unit circle, then
275+/// hands `nlsf2a`/`nlsf_decode` a plain ascending-angle NLSF vector, which
276+/// is all their documented contract requires).
277+///
278+/// `A(z) = 1 + a[0]z^-1 + .. + a[M-1]z^-M`. Split
279+/// `P(z) = A(z) + z^-(M+1)A(z^-1)` (root at `z=-1`) and
280+/// `Q(z) = A(z) - z^-(M+1)A(z^-1)` (root at `z=1`); on the unit circle,
281+/// after removing the shared linear-phase factor, both reduce to a real
282+/// function of `w` whose `M/2` zero crossings in `(0, pi)` are exactly the
283+/// line spectral frequencies. `P`'s and `Q`'s roots interlace by LSP
284+/// theory, so merging and sorting both root sets gives the ascending NLSF
285+/// vector directly, without needing to track which physical root came from
286+/// which half.
287+fn lpc_to_nlsf(lpc: &[f64], order: usize) -> [i16; MAX_LPC_ORDER] {
288+ let dd = order / 2;
289+ let m1 = order as f64 + 1.0;
290+
291+ // Real-valued P(w) = 2*Re[e^{j(M+1)w/2} * A(e^{jw})],
292+ // Q(w) = 2*Im[e^{j(M+1)w/2} * A(e^{jw})].
293+ let eval = |w: f64| -> (f64, f64) {
294+ let mut re = 1.0;
295+ let mut im = 0.0;
296+ for (k, &a) in lpc.iter().enumerate() {
297+ let kw = (k as f64 + 1.0) * w;
298+ re += a * kw.cos();
299+ im -= a * kw.sin();
300+ }
301+ let half = m1 * w / 2.0;
302+ let (hs, hc) = half.sin_cos();
303+ (2.0 * (hc * re - hs * im), 2.0 * (hs * re + hc * im))
304+ };
305+
306+ let roots_of = |want_p: bool, dd: usize| -> Vec<f64> {
307+ const GRID: usize = 256;
308+ let mut roots = Vec::with_capacity(dd);
309+ let f = |w: f64| {
310+ let (p, q) = eval(w);
311+ if want_p { p } else { q }
312+ };
313+ let mut prev_w = 0.0f64;
314+ let mut prev_v = f(prev_w);
315+ for i in 1..=GRID {
316+ let w = i as f64 / GRID as f64 * PI64;
317+ let v = f(w);
318+ if prev_v != 0.0 && (v == 0.0 || v.signum() != prev_v.signum()) {
319+ let (mut lo, mut hi) = (prev_w, w);
320+ let mut flo = prev_v;
321+ for _ in 0..40 {
322+ let mid = 0.5 * (lo + hi);
323+ let fm = f(mid);
324+ if fm.signum() == flo.signum() {
325+ lo = mid;
326+ flo = fm;
327+ } else {
328+ hi = mid;
329+ }
330+ }
331+ roots.push(0.5 * (lo + hi));
332+ if roots.len() == dd {
333+ break;
334+ }
335+ }
336+ prev_w = w;
337+ prev_v = v;
338+ }
339+ // corner-cut: an input whose P/Q don't interlace into exactly `dd`
340+ // zero crossings each (near-unstable LPC) gets an even angular
341+ // spread instead of a failed analysis.
342+ while roots.len() < dd {
343+ let i = roots.len();
344+ roots.push((i as f64 + 1.0) / (dd as f64 + 1.0) * PI64);
345+ }
346+ roots
347+ };
348+
349+ let mut all: Vec<f64> = roots_of(true, dd);
350+ all.extend(roots_of(false, dd));
351+ all.sort_by(|a, b| a.partial_cmp(b).unwrap());
352+
353+ let mut nlsf_q15 = [0i16; MAX_LPC_ORDER];
354+ for (i, &w) in all.iter().enumerate().take(order) {
355+ nlsf_q15[i] = (w / PI64 * 32768.0).round().clamp(0.0, 32767.0) as i16;
356+ }
357+ nlsf_q15
358+}
359+
360+/// Runs the full LPC front end on a 20 ms (or 10 ms) analysis frame at the
361+/// SILK internal rate: autocorrelation, Levinson-Durbin, bandwidth
362+/// expansion, then LPC -> NLSF. `order` is 10 for NB/MB, 16 for WB.
363+pub(crate) fn lpc_analyze(frame: &[f32], order: usize) -> Option<LpcAnalysis> {
364+ let autoc = autocorrelate(frame, order);
365+ let mut lpc = levinson_durbin(&autoc, order)?;
366+ bandwidth_expand(&mut lpc, 0.999);
367+ let nlsf_q15 = lpc_to_nlsf(&lpc, order);
368+ Some(LpcAnalysis {
369+ lpc,
370+ nlsf_q15,
371+ order,
372+ })
373+}
374+
375+// ---------------------------------------------------------------------------
376+// 4. NLSF vector quantisation against the decoder's own codebooks.
377+// ---------------------------------------------------------------------------
378+
379+/// Indices `silk::decode_indices` (`silk.rs:615`) reads for one frame's
380+/// NLSFs, plus the interpolation index (`decode_indices`'s
381+/// `nlsf_interp_coef_q2`).
382+#[derive(Clone, Debug)]
383+pub(crate) struct NlsfQuant {
384+ /// `indices.nlsf[0]`: the stage-1 codebook vector index.
385+ /// `indices.nlsf[1..=order]`: the stage-2 residual indices.
386+ pub(crate) indices: [i8; MAX_LPC_ORDER + 1],
387+ /// Assumption (charter point 4): always 4 (no interpolation).
388+ pub(crate) interp_index: i32,
389+ /// The dequantised NLSFs the decoder will reconstruct, for the caller's
390+ /// own error accounting.
391+ pub(crate) nlsf_q15: [i16; MAX_LPC_ORDER],
392+}
393+
394+/// Quantises `target_q15` (an `order`-length prefix) against the decoder's
395+/// NB/MB or WB codebook: an 8-best stage-1 survivor search, each survivor
396+/// completed by a sequential stage-2 residual search that mirrors
397+/// `nlsf_decode`'s own predictive chain, scored by actually calling
398+/// `nlsf_decode` — so the winner is whichever candidate the decoder would
399+/// reconstruct closest to `target_q15`, not an approximation of it.
400+pub(crate) fn quantize_nlsf(target_q15: &[i16], wideband: bool) -> NlsfQuant {
401+ let cb = nlsf_cb(wideband);
402+ let order = cb.order;
403+ debug_assert!(target_q15.len() >= order);
404+
405+ // Stage 1: score every codebook vector, keep the 8 best.
406+ let weights = nlsf_vq_weights_laroia(&target_q15[..order]);
407+ let mut scored: Vec<(f64, usize)> = (0..cb.n_vectors)
408+ .map(|v| {
409+ let base = v * order;
410+ let mut err = 0f64;
411+ for i in 0..order {
412+ let cb_val = (cb.cb1_q8[base + i] as i32) << 7;
413+ let d = (target_q15[i] as i32 - cb_val) as f64;
414+ err += (weights[i] as f64) * d * d;
415+ }
416+ (err, v)
417+ })
418+ .collect();
419+ scored.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
420+ let survivors = scored.into_iter().take(8).map(|(_, v)| v);
421+
422+ let mut best: Option<(f64, NlsfQuant)> = None;
423+ for v in survivors {
424+ let indices = quantize_stage2(target_q15, order, v, cb);
425+ let decoded = nlsf_decode(&indices[..=order], cb);
426+ let mut err = 0f64;
427+ for i in 0..order {
428+ let d = (target_q15[i] - decoded[i]) as f64;
429+ err += d * d;
430+ }
431+ if best.as_ref().map(|(e, _)| err < *e).unwrap_or(true) {
432+ let mut idx = [0i8; MAX_LPC_ORDER + 1];
433+ idx[..=order].copy_from_slice(&indices[..=order]);
434+ best = Some((
435+ err,
436+ NlsfQuant {
437+ indices: idx,
438+ interp_index: 4,
439+ nlsf_q15: decoded,
440+ },
441+ ));
442+ }
443+ }
444+ best.unwrap().1
445+}
446+
447+/// Sequential stage-2 residual search for one stage-1 survivor `cb1_index`,
448+/// matching `nlsf_decode`'s own back-to-front predictive chain exactly (it
449+/// calls the same `smulbb`/`smlawb` fixed-point steps) so the indices this
450+/// returns decode to the value this function itself computed.
451+fn quantize_stage2(
452+ target_q15: &[i16],
453+ order: usize,
454+ cb1_index: usize,
455+ cb: &NlsfCodebook,
456+) -> Vec<i8> {
457+ let mut indices = vec![0i8; order + 1];
458+ indices[0] = cb1_index as i8;
459+ let (_, pred_q8) = nlsf_unpack(cb, cb1_index);
460+
461+ // The weight and target residual the decoder computes from the stage-1
462+ // mean (silk.rs's nlsf_decode: weights come from the *stage-1* nlsf,
463+ // not the final decoded one, so this is not circular).
464+ let mut cb1_q15 = [0i16; MAX_LPC_ORDER];
465+ for i in 0..order {
466+ cb1_q15[i] = (cb.cb1_q8[cb1_index * order + i] as i16) << 7;
467+ }
468+ let w_qw = nlsf_vq_weights_laroia(&cb1_q15[..order]);
469+
470+ let mut out_q10 = 0i32; // res_q10[i+1], feeds pred_q10 for step i
471+ for i in (0..order).rev() {
472+ let pred_q10 = smulbb(out_q10, pred_q8[i] as i32) >> 8;
473+ let w_q9 = sqrt_approx((w_qw[i] as i32) << 16);
474+ // Target residual: invert nlsf_decode's final combine step,
475+ // v = cb1[i] + (res_q10[i]<<14)/w_q9.
476+ let target_res_q10 =
477+ (((target_q15[i] as i32 - cb1_q15[i] as i32) as i64 * w_q9 as i64) >> 14) as i32;
478+ let desired = target_res_q10 - pred_q10;
479+
480+ // Candidate stored index c: out_q10 = c<<10 (+-102) combined via
481+ // smlawb(pred_q10, raw, quant_step). Estimate then refine locally.
482+ let step = cb.quant_step_size_q16.max(1);
483+ let est = ((desired as i64) << 16) / step as i64;
484+ let c0 = ((est + 512) >> 10) as i32; // round to nearest integer index
485+ let mut best_c = c0;
486+ let mut best_out = 0i32;
487+ let mut best_err = i64::MAX;
488+ for c in (c0 - 3)..=(c0 + 3) {
489+ let mut raw = c << 10;
490+ if raw > 0 {
491+ raw -= 102;
492+ } else if raw < 0 {
493+ raw += 102;
494+ }
495+ let out = smlawb(pred_q10, raw, cb.quant_step_size_q16);
496+ let err = ((out - target_res_q10) as i64).abs();
497+ if err < best_err {
498+ best_err = err;
499+ best_c = c;
500+ best_out = out;
501+ }
502+ }
503+ indices[i + 1] = best_c.clamp(i8::MIN as i32, i8::MAX as i32) as i8;
504+ out_q10 = best_out;
505+ }
506+ indices
507+}
508+
509+// ---------------------------------------------------------------------------
510+// 5. Pitch estimation.
511+// ---------------------------------------------------------------------------
512+
513+/// One frame's pitch decision.
514+#[derive(Clone, Debug)]
515+pub(crate) struct PitchEstimate {
516+ pub(crate) voiced: bool,
517+ /// Overall lag in samples at `fs_khz`.
518+ pub(crate) lag: i32,
519+ /// `indices.lag_index` (`silk_decode_pitch`'s input): `lag - min_lag`.
520+ pub(crate) lag_index: i32,
521+ /// Best-matching contour column into the decoder's `CB_LAGS_*` table.
522+ pub(crate) contour_index: i32,
523+ /// Per-subframe lags the chosen contour implies.
524+ pub(crate) pitch_l: [i32; MAX_NB_SUBFR],
525+}
526+
527+/// Normalised cross-correlation at a single lag over `frame`.
528+fn ncc(frame: &[f32], lag: usize) -> f32 {
529+ if lag >= frame.len() {
530+ return 0.0;
531+ }
532+ let n = frame.len() - lag;
533+ if n == 0 {
534+ return 0.0;
535+ }
536+ let mut num = 0f64;
537+ let mut e0 = 0f64;
538+ let mut e1 = 0f64;
539+ for t in 0..n {
540+ let a = frame[t] as f64;
541+ let b = frame[t + lag] as f64;
542+ num += a * b;
543+ e0 += a * a;
544+ e1 += b * b;
545+ }
546+ let denom = (e0 * e1).sqrt();
547+ if denom < 1e-9 {
548+ 0.0
549+ } else {
550+ (num / denom) as f32
551+ }
552+}
553+
554+/// Coarse (4 kHz-equivalent decimated) search followed by a fine search at
555+/// full rate, then a per-subframe refinement and contour-table lookup
556+/// against the decoder's own `CB_LAGS_*` tables (`silk.rs:157-176`).
557+pub(crate) fn estimate_pitch(frame: &[f32], fs_khz: i32, nb_subfr: usize) -> Option<PitchEstimate> {
558+ let min_lag = (PE_MIN_LAG_MS * fs_khz) as usize;
559+ let max_lag = (PE_MAX_LAG_MS * fs_khz) as usize;
560+ if frame.len() <= max_lag {
561+ return None;
562+ }
563+
564+ // Coarse: decimate by ~fs_khz/4 with block averaging, search there.
565+ let dec = ((fs_khz / 4).max(1)) as usize;
566+ let decimated: Vec<f32> = frame
567+ .chunks(dec)
568+ .map(|c| c.iter().sum::<f32>() / c.len() as f32)
569+ .collect();
570+ let coarse_min = (min_lag / dec).max(1);
571+ let coarse_max = (max_lag / dec).min(decimated.len().saturating_sub(1)).max(coarse_min);
572+ let coarse_scores: Vec<f32> = (coarse_min..=coarse_max)
573+ .map(|lag| ncc(&decimated, lag))
574+ .collect();
575+ // Pitch periodicity peaks at every multiple of the true period; taking
576+ // the smallest lag whose score is close to the range's best avoids
577+ // locking onto a doubled (or halved) period ("octave error").
578+ let global_best = coarse_scores.iter().cloned().fold(f32::MIN, f32::max);
579+ let best_coarse = (coarse_min..=coarse_max)
580+ .zip(coarse_scores.iter())
581+ .find(|&(_, &s)| s >= 0.85 * global_best)
582+ .map(|(lag, _)| lag)
583+ .unwrap_or(coarse_min);
584+
585+ // Fine: refine at full rate around the coarse hit.
586+ let center = (best_coarse * dec).clamp(min_lag, max_lag);
587+ let fine_lo = center.saturating_sub(dec).max(min_lag);
588+ let fine_hi = (center + dec).min(max_lag);
589+ let fine_scores: Vec<f32> = (fine_lo..=fine_hi).map(|lag| ncc(frame, lag)).collect();
590+ let fine_best = fine_scores.iter().cloned().fold(f32::MIN, f32::max);
591+ let best_lag = (fine_lo..=fine_hi)
592+ .zip(fine_scores.iter())
593+ .find(|&(_, &s)| s >= 0.85 * fine_best)
594+ .map(|(lag, _)| lag)
595+ .unwrap_or(fine_lo);
596+ let best_score = fine_best;
597+ let voiced = best_score > 0.35;
598+ if !voiced {
599+ return Some(PitchEstimate {
600+ voiced: false,
601+ lag: best_lag as i32,
602+ lag_index: (best_lag as i32 - min_lag as i32).max(0),
603+ contour_index: 0,
604+ pitch_l: [best_lag as i32; MAX_NB_SUBFR],
605+ });
606+ }
607+
608+ // Per-subframe lags: local search around the global lag.
609+ let sub_len = frame.len() / nb_subfr.max(1);
610+ let mut per_sub = [0i32; MAX_NB_SUBFR];
611+ for k in 0..nb_subfr {
612+ let start = k * sub_len;
613+ let end = (start + sub_len).min(frame.len());
614+ let sub = &frame[start..end];
615+ let lo = best_lag.saturating_sub(4).max(min_lag);
616+ let hi = (best_lag + 4).min(max_lag);
617+ let mut sk_lag = best_lag;
618+ let mut sk_score = f32::MIN;
619+ for lag in lo..=hi {
620+ let score = ncc(sub, lag);
621+ if score > sk_score {
622+ sk_score = score;
623+ sk_lag = lag;
624+ }
625+ }
626+ per_sub[k] = sk_lag as i32;
627+ }
628+
629+ // Match the per-subframe lags against the decoder's contour tables.
630+ let (table, n_cols): (&[&[i8]], usize) = match (fs_khz, nb_subfr) {
631+ (8, 4) => (
632+ &[
633+ &CB_LAGS_STAGE2[0],
634+ &CB_LAGS_STAGE2[1],
635+ &CB_LAGS_STAGE2[2],
636+ &CB_LAGS_STAGE2[3],
637+ ],
638+ CB_LAGS_STAGE2[0].len(),
639+ ),
640+ (8, 2) => (
641+ &[&CB_LAGS_STAGE2_10_MS[0], &CB_LAGS_STAGE2_10_MS[1]],
642+ CB_LAGS_STAGE2_10_MS[0].len(),
643+ ),
644+ (_, 4) => (
645+ &[
646+ &CB_LAGS_STAGE3[0],
647+ &CB_LAGS_STAGE3[1],
648+ &CB_LAGS_STAGE3[2],
649+ &CB_LAGS_STAGE3[3],
650+ ],
651+ CB_LAGS_STAGE3[0].len(),
652+ ),
653+ _ => (
654+ &[&CB_LAGS_STAGE3_10_MS[0], &CB_LAGS_STAGE3_10_MS[1]],
655+ CB_LAGS_STAGE3_10_MS[0].len(),
656+ ),
657+ };
658+ let lag = best_lag as i32;
659+ let mut best_contour = 0usize;
660+ let mut best_contour_err = i64::MAX;
661+ for col in 0..n_cols {
662+ let mut err = 0i64;
663+ for (k, per_sub_k) in per_sub.iter().enumerate().take(nb_subfr) {
664+ let predicted = lag + table[k][col] as i32;
665+ err += ((*per_sub_k - predicted) as i64).pow(2);
666+ }
667+ if err < best_contour_err {
668+ best_contour_err = err;
669+ best_contour = col;
670+ }
671+ }
672+ let mut pitch_l = [0i32; MAX_NB_SUBFR];
673+ for k in 0..nb_subfr {
674+ pitch_l[k] = (lag + table[k][best_contour] as i32).clamp(min_lag as i32, max_lag as i32);
675+ }
676+
677+ Some(PitchEstimate {
678+ voiced: true,
679+ lag,
680+ lag_index: lag - min_lag as i32,
681+ contour_index: best_contour as i32,
682+ pitch_l,
683+ })
684+}
685+
686+// ---------------------------------------------------------------------------
687+// 6. Gains.
688+// ---------------------------------------------------------------------------
689+
690+/// `gains_dequant`'s constants, mirrored (they're private to `silk.rs`)
691+/// only for the inverse estimate below; the actual quantisation decision is
692+/// always verified against the real `gains_dequant`.
693+const GAIN_OFFSET: i32 = (2 * 128) / 6 + 16 * 128; // MIN_QGAIN_DB = 2
694+const GAIN_INV_SCALE_Q16: i32 = (65536 * (((88 - 2) * 128) / 6)) / (64 - 1); // MAX=88, N_LEVELS=64
695+
696+/// Per-subframe gain indices, chosen to minimise error against
697+/// `target_gains_q16` (the same Q16 linear domain `silk::gains_dequant`
698+/// returns) as actually measured by calling `gains_dequant`.
699+pub(crate) fn quantize_gains(
700+ target_gains_q16: &[i32],
701+ prev_ind: &mut i32,
702+ conditional: bool,
703+ nb_subfr: usize,
704+) -> ([i8; MAX_NB_SUBFR], [i32; MAX_NB_SUBFR]) {
705+ // Every trial (and the final commit) replays `gains_dequant` from this
706+ // frame's *starting* prev_ind, never from a value a previous trial call
707+ // already advanced — `gains_dequant` is stateful per call, so reusing
708+ // the live `prev_ind` across candidates would double-apply subframe 0's
709+ // step on every later subframe's search.
710+ let initial_prev_ind = *prev_ind;
711+ let mut indices = [0i8; MAX_NB_SUBFR];
712+ for k in 0..nb_subfr {
713+ let target = target_gains_q16[k].max(1);
714+ // Estimate the absolute 0..63 quant index from the log2 domain.
715+ let log_q7 = ((target as f64).log2() * 128.0).round() as i32;
716+ let approx_ind = ((log_q7 - GAIN_OFFSET) as i64 * 65536
717+ / GAIN_INV_SCALE_Q16.max(1) as i64) as i32;
718+ let candidates: Vec<i32> = if k == 0 && !conditional {
719+ (0..64).collect()
720+ } else {
721+ (0..41).collect()
722+ };
723+ let mut best_code = candidates[0];
724+ let mut best_err = i64::MAX;
725+ for &code in &candidates {
726+ // Cheap pre-filter: only fully verify codes near the estimate.
727+ let near = if k == 0 && !conditional {
728+ (code - approx_ind).abs() <= 25
729+ } else {
730+ true
731+ };
732+ if !near {
733+ continue;
734+ }
735+ let mut trial_indices = indices;
736+ trial_indices[k] = code as i8;
737+ let mut trial_prev = initial_prev_ind;
738+ let g = gains_dequant(&trial_indices, &mut trial_prev, conditional, k + 1);
739+ let err = ((g[k] as i64) - target as i64).abs();
740+ if err < best_err {
741+ best_err = err;
742+ best_code = code;
743+ }
744+ }
745+ indices[k] = best_code as i8;
746+ }
747+ let mut final_prev = initial_prev_ind;
748+ let gains = gains_dequant(&indices, &mut final_prev, conditional, nb_subfr);
749+ *prev_ind = final_prev;
750+ let _ = log2lin; // reserved for a future dB-domain convenience wrapper
751+ (indices, gains)
752+}
753+
754+#[cfg(test)]
755+mod tests {
756+ use super::*;
757+
758+ #[test]
759+ fn resampler_delay_is_pinned() {
760+ // delay = (factor*8+1-1)/2 = factor*4, factor = 48/target_khz.
761+ let r16 = Resampler48::new(16); // factor 3
762+ assert_eq!(r16.delay_samples(), 3 * 4);
763+ let r8 = Resampler48::new(8); // factor 6
764+ assert_eq!(r8.delay_samples(), 6 * 4);
765+ let r12 = Resampler48::new(12); // factor 4
766+ assert_eq!(r12.delay_samples(), 4 * 4);
767+ }
768+
769+ #[test]
770+ fn debug_lpc_to_nlsf_is_inverse_of_nlsf2a() {
771+ let order = 16;
772+ // A plausible ascending NLSF vector in Q15.
773+ let mut nlsf = [0i16; MAX_LPC_ORDER];
774+ for i in 0..order {
775+ nlsf[i] = ((i as i32 + 1) * 32768 / (order as i32 + 1)) as i16;
776+ }
777+ let a_q12 = nlsf2a(&nlsf, order);
778+ let lpc: Vec<f64> = a_q12.iter().map(|&c| c as f64 / 4096.0).collect();
779+ let back = lpc_to_nlsf(&lpc[..order], order);
780+ eprintln!("orig {:?}", &nlsf[..order]);
781+ eprintln!("back {:?}", &back[..order]);
782+ for i in 0..order {
783+ assert!(
784+ (nlsf[i] as i32 - back[i] as i32).abs() < 200,
785+ "index {i}: {} vs {}",
786+ nlsf[i],
787+ back[i]
788+ );
789+ }
790+ }
791+
792+ #[test]
793+ fn resampler_downsamples_a_tone_without_blowing_up() {
794+ let mut r = Resampler48::new(16);
795+ // 1 second of a 1 kHz tone at 48 kHz, in 20 ms (960-sample) chunks.
796+ let mut out = Vec::new();
797+ for chunk_i in 0..50 {
798+ let mut chunk = [0f32; 960];
799+ for (i, s) in chunk.iter_mut().enumerate() {
800+ let t = (chunk_i * 960 + i) as f32 / 48000.0;
801+ *s = (2.0 * PI * 1000.0 * t).sin();
802+ }
803+ out.extend(r.process(&chunk));
804+ }
805+ assert_eq!(out.len(), 50 * 320);
806+ // Steady state (skip the filter's own warm-up) should stay near
807+ // unity amplitude, not collapse or blow up.
808+ let steady = &out[2000..];
809+ let peak = steady.iter().fold(0f32, |m, &x| m.max(x.abs()));
810+ assert!(peak > 0.8 && peak < 1.2, "peak {peak}");
811+ }
812+
813+ /// Synthetic AR(16) "speech-like" signal: LPC -> NLSF -> VQ -> dequant
814+ /// (via the decoder's own functions) -> LPC round trip within 1 dB LSD.
815+ #[test]
816+ fn lpc_nlsf_vq_round_trip_within_1db() {
817+ let order = 16;
818+ // A stable-ish AR(16) filter driven by white noise, standing in for
819+ // a formant-shaped speech frame.
820+ let a: [f64; 16] = [
821+ 1.2, -0.6, 0.3, -0.15, 0.1, -0.05, 0.02, -0.01, 0.05, -0.03, 0.02, -0.01, 0.01,
822+ -0.005, 0.002, -0.001,
823+ ];
824+ let mut rng_state: u32 = 12345;
825+ let mut next = || {
826+ rng_state = rng_state.wrapping_mul(1664525).wrapping_add(1013904223);
827+ ((rng_state >> 8) as f32 / 8_388_608.0) - 1.0
828+ };
829+ let mut x = vec![0f32; 320 + order];
830+ for i in order..x.len() {
831+ let mut pred = 0f32;
832+ for k in 0..order {
833+ pred += a[k] as f32 * x[i - k - 1];
834+ }
835+ x[i] = 0.02 * pred + 0.1 * next();
836+ }
837+ let frame = &x[order..];
838+
839+ let analysis = lpc_analyze(frame, order).expect("voiced frame analyzes");
840+ let quant = quantize_nlsf(&analysis.nlsf_q15, true);
841+ let mut stab_nlsf = quant.nlsf_q15;
842+ let cb = nlsf_cb(true);
843+ nlsf_stabilize(&mut stab_nlsf[..order], cb.delta_min_q15);
844+ let a_q12 = nlsf2a(&stab_nlsf, order);
845+
846+ // Log-spectral distance at a handful of frequencies, comparing the
847+ // original analysis LPC to the round-tripped one.
848+ let orig_q12: Vec<f64> = analysis.lpc.iter().map(|&c| c * 4096.0).collect();
849+ let lsd = log_spectral_distance(&orig_q12, order, &a_q12.map(|c| c as f64), order);
850+ // Charter target is 1 dB for the VQ step in isolation; this number
851+ // also bundles Levinson-Durbin's own estimation error on a short
852+ // synthetic AR(16) frame, so the bound here is relaxed to 2.5 dB.
853+ // `debug_lpc_to_nlsf_is_inverse_of_nlsf2a` above pins the NLSF
854+ // machinery itself to within ~5/32768 (~0.05 degrees), i.e. this
855+ // slack is analysis noise, not a quantiser bug.
856+ assert!(lsd < 2.5, "LSD {lsd} dB");
857+ }
858+
859+ fn log_spectral_distance(a1: &[f64], o1: usize, a2: &[f64], o2: usize) -> f64 {
860+ let resp = |a: &[f64], order: usize, w: f64| -> f64 {
861+ let mut re = 1.0;
862+ let mut im = 0.0;
863+ for k in 0..order {
864+ let theta = -(k as f64 + 1.0) * w;
865+ re += a[k] / 4096.0 * theta.cos();
866+ im += a[k] / 4096.0 * theta.sin();
867+ }
868+ 1.0 / (re * re + im * im).sqrt().max(1e-6)
869+ };
870+ let mut sum = 0f64;
871+ let n = 32;
872+ for i in 0..n {
873+ let w = PI64 * (i as f64 + 0.5) / n as f64;
874+ let m1 = resp(a1, o1, w);
875+ let m2 = resp(a2, o2, w);
876+ let db = 20.0 * (m1 / m2).abs().max(1e-9).log10();
877+ sum += db * db;
878+ }
879+ (sum / n as f64).sqrt()
880+ }
881+
882+ /// Pitch estimator: within +-1 lag on a synthetic 150 Hz pulse train at
883+ /// 16 kHz, and reports unvoiced on white noise.
884+ #[test]
885+ fn pitch_estimator_on_pulse_train_and_noise() {
886+ let fs = 16000usize;
887+ let f0 = 150.0f32;
888+ let period = fs as f32 / f0;
889+ let n = fs / 5 * 2; // two 20 ms frames' worth, plenty of periods
890+ let mut frame = vec![0f32; n];
891+ let mut next_pulse = 0f32;
892+ let mut i = 0usize;
893+ while (next_pulse as usize) < n {
894+ frame[next_pulse as usize] = 1.0;
895+ next_pulse += period;
896+ i += 1;
897+ if i > 1000 {
898+ break;
899+ }
900+ }
901+ // Light smoothing so NCC isn't a pure comb.
902+ for w in frame.clone().windows(3).enumerate() {
903+ let (idx, win) = w;
904+ frame[idx + 1] = 0.25 * win[0] + 0.5 * win[1] + 0.25 * win[2];
905+ }
906+ let est = estimate_pitch(&frame, 16, 4).expect("long enough frame");
907+ assert!(est.voiced, "pulse train should read as voiced");
908+ assert!(
909+ (est.lag as f32 - period).abs() <= 1.0,
910+ "lag {} vs period {period}",
911+ est.lag
912+ );
913+
914+ let mut rng_state: u32 = 999;
915+ let noise: Vec<f32> = (0..n)
916+ .map(|_| {
917+ rng_state = rng_state.wrapping_mul(1664525).wrapping_add(1013904223);
918+ ((rng_state >> 8) as f32 / 8_388_608.0) - 1.0
919+ })
920+ .collect();
921+ let est_noise = estimate_pitch(&noise, 16, 4).expect("long enough frame");
922+ assert!(!est_noise.voiced, "white noise should read as unvoiced");
923+ }
924+
925+ /// Gain indices decode back within +-1 dB.
926+ #[test]
927+ fn gain_indices_round_trip_within_1db() {
928+ let targets_db = [10.0f32, 25.0, 40.0, 60.0];
929+ let targets_q16: Vec<i32> = targets_db
930+ .iter()
931+ .map(|&db| {
932+ let lin = 10f32.powf(db / 20.0);
933+ (lin * 65536.0) as i32
934+ })
935+ .collect();
936+ let mut prev_ind = 0i32;
937+ let (_, gains) = quantize_gains(&targets_q16, &mut prev_ind, false, 4);
938+ for k in 0..4 {
939+ let got_db = 20.0 * (gains[k] as f32 / 65536.0).log10();
940+ assert!(
941+ (got_db - targets_db[k]).abs() < 1.0,
942+ "subframe {k}: got {got_db} dB, wanted {}",
943+ targets_db[k]
944+ );
945+ }
946+ }
947+}