forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

silk_enc.rs991 lines, 37.5 KiBHistoryRawDownload
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
25use std::f32::consts::PI;
26use std::f64::consts::PI as PI64;
27
28use crate::silk::tables::{
29 CB_LAGS_STAGE2, CB_LAGS_STAGE2_10_MS, CB_LAGS_STAGE3, CB_LAGS_STAGE3_10_MS,
30};
31use 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)]
37use 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)]
60pub(crate) struct Resampler48 {
61 factor: usize,
62 taps: Vec<f32>,
63 history: Vec<f32>,
64}
65
66impl 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)]
131pub(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)]
138pub(crate) struct Vad {
139 noise_floor: f32,
140}
141
142impl Default for Vad {
143 fn default() -> Self {
144 Vad { noise_floor: 1e-6 }
145 }
146}
147
148impl 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)]
203pub(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.
215fn 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).
234fn 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.
262fn 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.
287fn 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 // `lpc` is the predictor (`x[n] ~= sum a[k] x[n-k-1]`), so the
299 // analysis polynomial is A(z) = 1 - sum a[k] z^-(k+1).
300 re -= a * kw.cos();
301 im += a * kw.sin();
302 }
303 let half = m1 * w / 2.0;
304 let (hs, hc) = half.sin_cos();
305 (2.0 * (hc * re - hs * im), 2.0 * (hs * re + hc * im))
306 };
307
308 let roots_of = |want_p: bool, dd: usize| -> Vec<f64> {
309 const GRID: usize = 256;
310 let mut roots = Vec::with_capacity(dd);
311 let f = |w: f64| {
312 let (p, q) = eval(w);
313 if want_p { p } else { q }
314 };
315 let mut prev_w = 0.0f64;
316 let mut prev_v = f(prev_w);
317 for i in 1..=GRID {
318 let w = i as f64 / GRID as f64 * PI64;
319 let v = f(w);
320 if prev_v != 0.0 && (v == 0.0 || v.signum() != prev_v.signum()) {
321 let (mut lo, mut hi) = (prev_w, w);
322 let mut flo = prev_v;
323 for _ in 0..40 {
324 let mid = 0.5 * (lo + hi);
325 let fm = f(mid);
326 if fm.signum() == flo.signum() {
327 lo = mid;
328 flo = fm;
329 } else {
330 hi = mid;
331 }
332 }
333 roots.push(0.5 * (lo + hi));
334 if roots.len() == dd {
335 break;
336 }
337 }
338 prev_w = w;
339 prev_v = v;
340 }
341 // corner-cut: an input whose P/Q don't interlace into exactly `dd`
342 // zero crossings each (near-unstable LPC) gets an even angular
343 // spread instead of a failed analysis.
344 while roots.len() < dd {
345 let i = roots.len();
346 roots.push((i as f64 + 1.0) / (dd as f64 + 1.0) * PI64);
347 }
348 roots
349 };
350
351 let mut all: Vec<f64> = roots_of(true, dd);
352 all.extend(roots_of(false, dd));
353 all.sort_by(|a, b| a.partial_cmp(b).unwrap());
354
355 let mut nlsf_q15 = [0i16; MAX_LPC_ORDER];
356 for (i, &w) in all.iter().enumerate().take(order) {
357 nlsf_q15[i] = (w / PI64 * 32768.0).round().clamp(0.0, 32767.0) as i16;
358 }
359 nlsf_q15
360}
361
362/// Runs the full LPC front end on a 20 ms (or 10 ms) analysis frame at the
363/// SILK internal rate: autocorrelation, Levinson-Durbin, bandwidth
364/// expansion, then LPC -> NLSF. `order` is 10 for NB/MB, 16 for WB.
365pub(crate) fn lpc_analyze(frame: &[f32], order: usize) -> Option<LpcAnalysis> {
366 let autoc = autocorrelate(frame, order);
367 let mut lpc = levinson_durbin(&autoc, order)?;
368 bandwidth_expand(&mut lpc, 0.999);
369 let nlsf_q15 = lpc_to_nlsf(&lpc, order);
370 Some(LpcAnalysis {
371 lpc,
372 nlsf_q15,
373 order,
374 })
375}
376
377// ---------------------------------------------------------------------------
378// 4. NLSF vector quantisation against the decoder's own codebooks.
379// ---------------------------------------------------------------------------
380
381/// Indices `silk::decode_indices` (`silk.rs:615`) reads for one frame's
382/// NLSFs, plus the interpolation index (`decode_indices`'s
383/// `nlsf_interp_coef_q2`).
384#[derive(Clone, Debug)]
385pub(crate) struct NlsfQuant {
386 /// `indices.nlsf[0]`: the stage-1 codebook vector index.
387 /// `indices.nlsf[1..=order]`: the stage-2 residual indices.
388 pub(crate) indices: [i8; MAX_LPC_ORDER + 1],
389 /// Assumption (charter point 4): always 4 (no interpolation).
390 pub(crate) interp_index: i32,
391 /// The dequantised NLSFs the decoder will reconstruct, for the caller's
392 /// own error accounting.
393 pub(crate) nlsf_q15: [i16; MAX_LPC_ORDER],
394}
395
396/// Quantises `target_q15` (an `order`-length prefix) against the decoder's
397/// NB/MB or WB codebook: an 8-best stage-1 survivor search, each survivor
398/// completed by a sequential stage-2 residual search that mirrors
399/// `nlsf_decode`'s own predictive chain, scored by actually calling
400/// `nlsf_decode` — so the winner is whichever candidate the decoder would
401/// reconstruct closest to `target_q15`, not an approximation of it.
402pub(crate) fn quantize_nlsf(target_q15: &[i16], wideband: bool) -> NlsfQuant {
403 let cb = nlsf_cb(wideband);
404 let order = cb.order;
405 debug_assert!(target_q15.len() >= order);
406
407 // Stage 1: score every codebook vector, keep the 8 best.
408 let weights = nlsf_vq_weights_laroia(&target_q15[..order]);
409 let mut scored: Vec<(f64, usize)> = (0..cb.n_vectors)
410 .map(|v| {
411 let base = v * order;
412 let mut err = 0f64;
413 for i in 0..order {
414 let cb_val = (cb.cb1_q8[base + i] as i32) << 7;
415 let d = (target_q15[i] as i32 - cb_val) as f64;
416 err += (weights[i] as f64) * d * d;
417 }
418 (err, v)
419 })
420 .collect();
421 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
422 let survivors = scored.into_iter().take(8).map(|(_, v)| v);
423
424 let mut best: Option<(f64, NlsfQuant)> = None;
425 for v in survivors {
426 let indices = quantize_stage2(target_q15, order, v, cb);
427 let decoded = nlsf_decode(&indices[..=order], cb);
428 let mut err = 0f64;
429 for i in 0..order {
430 let d = (target_q15[i] - decoded[i]) as f64;
431 err += d * d;
432 }
433 if best.as_ref().map(|(e, _)| err < *e).unwrap_or(true) {
434 let mut idx = [0i8; MAX_LPC_ORDER + 1];
435 idx[..=order].copy_from_slice(&indices[..=order]);
436 best = Some((
437 err,
438 NlsfQuant {
439 indices: idx,
440 interp_index: 4,
441 nlsf_q15: decoded,
442 },
443 ));
444 }
445 }
446 best.unwrap().1
447}
448
449/// Sequential stage-2 residual search for one stage-1 survivor `cb1_index`,
450/// matching `nlsf_decode`'s own back-to-front predictive chain exactly (it
451/// calls the same `smulbb`/`smlawb` fixed-point steps) so the indices this
452/// returns decode to the value this function itself computed.
453fn quantize_stage2(
454 target_q15: &[i16],
455 order: usize,
456 cb1_index: usize,
457 cb: &NlsfCodebook,
458) -> Vec<i8> {
459 let mut indices = vec![0i8; order + 1];
460 indices[0] = cb1_index as i8;
461 let (_, pred_q8) = nlsf_unpack(cb, cb1_index);
462
463 // The weight and target residual the decoder computes from the stage-1
464 // mean (silk.rs's nlsf_decode: weights come from the *stage-1* nlsf,
465 // not the final decoded one, so this is not circular).
466 let mut cb1_q15 = [0i16; MAX_LPC_ORDER];
467 for (i, slot) in cb1_q15.iter_mut().enumerate().take(order) {
468 *slot = (cb.cb1_q8[cb1_index * order + i] as i16) << 7;
469 }
470 let w_qw = nlsf_vq_weights_laroia(&cb1_q15[..order]);
471
472 let mut out_q10 = 0i32; // res_q10[i+1], feeds pred_q10 for step i
473 for i in (0..order).rev() {
474 let pred_q10 = smulbb(out_q10, pred_q8[i] as i32) >> 8;
475 let w_q9 = sqrt_approx((w_qw[i] as i32) << 16);
476 // Target residual: invert nlsf_decode's final combine step,
477 // v = cb1[i] + (res_q10[i]<<14)/w_q9.
478 let target_res_q10 =
479 (((target_q15[i] as i32 - cb1_q15[i] as i32) as i64 * w_q9 as i64) >> 14) as i32;
480 let desired = target_res_q10 - pred_q10;
481
482 // Candidate stored index c: out_q10 = c<<10 (+-102) combined via
483 // smlawb(pred_q10, raw, quant_step). Estimate then refine locally.
484 let step = cb.quant_step_size_q16.max(1);
485 let est = ((desired as i64) << 16) / step as i64;
486 let c0 = ((est + 512) >> 10) as i32; // round to nearest integer index
487 let mut best_c = c0;
488 let mut best_out = 0i32;
489 let mut best_err = i64::MAX;
490 for c in (c0 - 3)..=(c0 + 3) {
491 let mut raw = c << 10;
492 if raw > 0 {
493 raw -= 102;
494 } else if raw < 0 {
495 raw += 102;
496 }
497 let out = smlawb(pred_q10, raw, cb.quant_step_size_q16);
498 let err = ((out - target_res_q10) as i64).abs();
499 if err < best_err {
500 best_err = err;
501 best_c = c;
502 best_out = out;
503 }
504 }
505 indices[i + 1] = best_c.clamp(i8::MIN as i32, i8::MAX as i32) as i8;
506 out_q10 = best_out;
507 }
508 indices
509}
510
511// ---------------------------------------------------------------------------
512// 5. Pitch estimation.
513// ---------------------------------------------------------------------------
514
515/// One frame's pitch decision.
516#[derive(Clone, Debug)]
517pub(crate) struct PitchEstimate {
518 pub(crate) voiced: bool,
519 /// Overall lag in samples at `fs_khz`.
520 pub(crate) lag: i32,
521 /// `indices.lag_index` (`silk_decode_pitch`'s input): `lag - min_lag`.
522 pub(crate) lag_index: i32,
523 /// Best-matching contour column into the decoder's `CB_LAGS_*` table.
524 pub(crate) contour_index: i32,
525 /// Per-subframe lags the chosen contour implies.
526 pub(crate) pitch_l: [i32; MAX_NB_SUBFR],
527}
528
529/// Normalised cross-correlation at a single lag over `frame`.
530fn ncc(frame: &[f32], lag: usize) -> f32 {
531 if lag >= frame.len() {
532 return 0.0;
533 }
534 let n = frame.len() - lag;
535 if n == 0 {
536 return 0.0;
537 }
538 let mut num = 0f64;
539 let mut e0 = 0f64;
540 let mut e1 = 0f64;
541 for t in 0..n {
542 let a = frame[t] as f64;
543 let b = frame[t + lag] as f64;
544 num += a * b;
545 e0 += a * a;
546 e1 += b * b;
547 }
548 let denom = (e0 * e1).sqrt();
549 if denom < 1e-9 {
550 0.0
551 } else {
552 (num / denom) as f32
553 }
554}
555
556/// Coarse (4 kHz-equivalent decimated) search followed by a fine search at
557/// full rate, then a per-subframe refinement and contour-table lookup
558/// against the decoder's own `CB_LAGS_*` tables (`silk.rs:157-176`).
559/// Voiced decision: libopus silk_find_pitch_lags starts from 0.6 (minus speech-activity,
560/// tilt and prev-type terms); value measured on real speech, lane opus-silkq r1.
561// Sweep 2026-08-23 (reelm 12k SILK-WB, corr/err_ratio): .35 -> .8081/11.4,
562// .45 -> .8127/26.3, .55 -> .8106/44.8, .65 -> .7987/12.3; err non-monotonic,
563// threshold is not the 12k mechanism. Kept at .35.
564const VOICED_THRESHOLD: f32 = 0.35;
565
566pub(crate) fn estimate_pitch(
567 frame: &[f32],
568 fs_khz: i32,
569 nb_subfr: usize,
570 prior_lag: Option<i32>,
571) -> Option<PitchEstimate> {
572 let min_lag = (PE_MIN_LAG_MS * fs_khz) as usize;
573 let max_lag = (PE_MAX_LAG_MS * fs_khz) as usize;
574 if frame.len() <= max_lag {
575 return None;
576 }
577
578 // Coarse: decimate by ~fs_khz/4 with block averaging, search there.
579 let dec = ((fs_khz / 4).max(1)) as usize;
580 let decimated: Vec<f32> = frame
581 .chunks(dec)
582 .map(|c| c.iter().sum::<f32>() / c.len() as f32)
583 .collect();
584 let coarse_min = (min_lag / dec).max(1);
585 let coarse_max = (max_lag / dec).min(decimated.len().saturating_sub(1)).max(coarse_min);
586 let coarse_scores: Vec<f32> = (coarse_min..=coarse_max)
587 .map(|lag| ncc(&decimated, lag))
588 .collect();
589 // Pitch periodicity peaks at every multiple of the true period; taking
590 // the smallest lag whose score is close to the range's best avoids
591 // locking onto a doubled (or halved) period ("octave error").
592 let global_best = coarse_scores.iter().cloned().fold(f32::MIN, f32::max);
593 let best_coarse = (coarse_min..=coarse_max)
594 .zip(coarse_scores.iter())
595 .find(|&(_, &s)| s >= 0.85 * global_best)
596 .map(|(lag, _)| lag)
597 .unwrap_or(coarse_min);
598
599 // Fine: refine at full rate around the coarse hit.
600 let center = (best_coarse * dec).clamp(min_lag, max_lag);
601 let fine_lo = center.saturating_sub(dec).max(min_lag);
602 let fine_hi = (center + dec).min(max_lag);
603 let fine_scores: Vec<f32> = (fine_lo..=fine_hi).map(|lag| ncc(frame, lag)).collect();
604 let fine_best = fine_scores.iter().cloned().fold(f32::MIN, f32::max);
605 let best_lag = (fine_lo..=fine_hi)
606 .zip(fine_scores.iter())
607 .find(|&(_, &s)| s >= 0.85 * fine_best)
608 .map(|(lag, _)| lag)
609 .unwrap_or(fine_lo);
610 let mut best_score = fine_best;
611
612 // Pitch continuity (libopus `silk_P_estimation` reuses the prior frame's
613 // lag as a prior). The open-loop search can octave-error onto an integer
614 // multiple of the true period — seen as a 2-3.5x lag jump with LTP gain
615 // pinned at its floor — cratering that second's corr. When a prior lag is
616 // available and the open-loop result jumped away from it, re-search the
617 // fine window around the prior lag and keep it if its NCC is comparable.
618 // Measured harmful on real speech (reelm 12k SILK-WB: err_ratio 11.4 -> 26.2,
619 // lane opus-silkq r1); kept off.
620 const ENABLE_PITCH_CONTINUITY: bool = false;
621 let mut best_lag = best_lag;
622 if ENABLE_PITCH_CONTINUITY {
623 if let Some(pl) = prior_lag {
624 let pl = pl as usize;
625 if pl >= min_lag && pl <= max_lag && best_lag.abs_diff(pl) > dec {
626 let p_lo = pl.saturating_sub(dec).max(min_lag);
627 let p_hi = (pl + dec).min(max_lag);
628 let p_scores: Vec<f32> = (p_lo..=p_hi).map(|lag| ncc(frame, lag)).collect();
629 let p_best = p_scores.iter().cloned().fold(f32::MIN, f32::max);
630 if p_best >= 0.85 * best_score {
631 best_lag = (p_lo..=p_hi)
632 .zip(p_scores.iter())
633 .find(|&(_, &s)| s >= 0.85 * p_best)
634 .map(|(lag, _)| lag)
635 .unwrap_or(pl);
636 best_score = p_best;
637 }
638 }
639 }
640 }
641 let voiced = best_score > VOICED_THRESHOLD;
642 if !voiced {
643 return Some(PitchEstimate {
644 voiced: false,
645 lag: best_lag as i32,
646 lag_index: (best_lag as i32 - min_lag as i32).max(0),
647 contour_index: 0,
648 pitch_l: [best_lag as i32; MAX_NB_SUBFR],
649 });
650 }
651
652 // Per-subframe lags: local search around the global lag.
653 let sub_len = frame.len() / nb_subfr.max(1);
654 let mut per_sub = [0i32; MAX_NB_SUBFR];
655 for (k, slot) in per_sub.iter_mut().enumerate().take(nb_subfr) {
656 let start = k * sub_len;
657 let end = (start + sub_len).min(frame.len());
658 let sub = &frame[start..end];
659 let lo = best_lag.saturating_sub(4).max(min_lag);
660 let hi = (best_lag + 4).min(max_lag);
661 let mut sk_lag = best_lag;
662 let mut sk_score = f32::MIN;
663 for lag in lo..=hi {
664 let score = ncc(sub, lag);
665 if score > sk_score {
666 sk_score = score;
667 sk_lag = lag;
668 }
669 }
670 *slot = sk_lag as i32;
671 }
672
673 // Match the per-subframe lags against the decoder's contour tables.
674 let (table, n_cols): (&[&[i8]], usize) = match (fs_khz, nb_subfr) {
675 (8, 4) => (
676 &[
677 &CB_LAGS_STAGE2[0],
678 &CB_LAGS_STAGE2[1],
679 &CB_LAGS_STAGE2[2],
680 &CB_LAGS_STAGE2[3],
681 ],
682 CB_LAGS_STAGE2[0].len(),
683 ),
684 (8, 2) => (
685 &[&CB_LAGS_STAGE2_10_MS[0], &CB_LAGS_STAGE2_10_MS[1]],
686 CB_LAGS_STAGE2_10_MS[0].len(),
687 ),
688 (_, 4) => (
689 &[
690 &CB_LAGS_STAGE3[0],
691 &CB_LAGS_STAGE3[1],
692 &CB_LAGS_STAGE3[2],
693 &CB_LAGS_STAGE3[3],
694 ],
695 CB_LAGS_STAGE3[0].len(),
696 ),
697 _ => (
698 &[&CB_LAGS_STAGE3_10_MS[0], &CB_LAGS_STAGE3_10_MS[1]],
699 CB_LAGS_STAGE3_10_MS[0].len(),
700 ),
701 };
702 let lag = best_lag as i32;
703 let mut best_contour = 0usize;
704 let mut best_contour_err = i64::MAX;
705 for (col, _) in table[0].iter().enumerate().take(n_cols) {
706 let mut err = 0i64;
707 for (k, per_sub_k) in per_sub.iter().enumerate().take(nb_subfr) {
708 let predicted = lag + table[k][col] as i32;
709 err += ((*per_sub_k - predicted) as i64).pow(2);
710 }
711 if err < best_contour_err {
712 best_contour_err = err;
713 best_contour = col;
714 }
715 }
716 let mut pitch_l = [0i32; MAX_NB_SUBFR];
717 for k in 0..nb_subfr {
718 pitch_l[k] = (lag + table[k][best_contour] as i32).clamp(min_lag as i32, max_lag as i32);
719 }
720
721 Some(PitchEstimate {
722 voiced: true,
723 lag,
724 lag_index: lag - min_lag as i32,
725 contour_index: best_contour as i32,
726 pitch_l,
727 })
728}
729
730// ---------------------------------------------------------------------------
731// 6. Gains.
732// ---------------------------------------------------------------------------
733
734/// `gains_dequant`'s constants, mirrored (they're private to `silk.rs`)
735/// only for the inverse estimate below; the actual quantisation decision is
736/// always verified against the real `gains_dequant`.
737const GAIN_OFFSET: i32 = (2 * 128) / 6 + 16 * 128; // MIN_QGAIN_DB = 2
738const GAIN_INV_SCALE_Q16: i32 = (65536 * (((88 - 2) * 128) / 6)) / (64 - 1); // MAX=88, N_LEVELS=64
739
740/// Per-subframe gain indices, chosen to minimise error against
741/// `target_gains_q16` (the same Q16 linear domain `silk::gains_dequant`
742/// returns) as actually measured by calling `gains_dequant`.
743pub(crate) fn quantize_gains(
744 target_gains_q16: &[i32],
745 prev_ind: &mut i32,
746 conditional: bool,
747 nb_subfr: usize,
748) -> ([i8; MAX_NB_SUBFR], [i32; MAX_NB_SUBFR]) {
749 // Every trial (and the final commit) replays `gains_dequant` from this
750 // frame's *starting* prev_ind, never from a value a previous trial call
751 // already advanced — `gains_dequant` is stateful per call, so reusing
752 // the live `prev_ind` across candidates would double-apply subframe 0's
753 // step on every later subframe's search.
754 let initial_prev_ind = *prev_ind;
755 let mut indices = [0i8; MAX_NB_SUBFR];
756 for k in 0..nb_subfr {
757 let target = target_gains_q16[k].max(1);
758 // Estimate the absolute 0..63 quant index from the log2 domain.
759 let log_q7 = ((target as f64).log2() * 128.0).round() as i32;
760 let approx_ind = ((log_q7 - GAIN_OFFSET) as i64 * 65536
761 / GAIN_INV_SCALE_Q16.max(1) as i64) as i32;
762 let candidates: Vec<i32> = if k == 0 && !conditional {
763 (0..64).collect()
764 } else {
765 (0..41).collect()
766 };
767 let mut best_code = candidates[0];
768 let mut best_err = i64::MAX;
769 for &code in &candidates {
770 // Cheap pre-filter: only fully verify codes near the estimate.
771 let near = if k == 0 && !conditional {
772 (code - approx_ind).abs() <= 25
773 } else {
774 true
775 };
776 if !near {
777 continue;
778 }
779 let mut trial_indices = indices;
780 trial_indices[k] = code as i8;
781 let mut trial_prev = initial_prev_ind;
782 let g = gains_dequant(&trial_indices, &mut trial_prev, conditional, k + 1);
783 let err = ((g[k] as i64) - target as i64).abs();
784 if err < best_err {
785 best_err = err;
786 best_code = code;
787 }
788 }
789 indices[k] = best_code as i8;
790 }
791 let mut final_prev = initial_prev_ind;
792 let gains = gains_dequant(&indices, &mut final_prev, conditional, nb_subfr);
793 *prev_ind = final_prev;
794 let _ = log2lin; // reserved for a future dB-domain convenience wrapper
795 (indices, gains)
796}
797
798#[cfg(test)]
799mod tests {
800 use super::*;
801
802 #[test]
803 fn resampler_delay_is_pinned() {
804 // delay = (factor*8+1-1)/2 = factor*4, factor = 48/target_khz.
805 let r16 = Resampler48::new(16); // factor 3
806 assert_eq!(r16.delay_samples(), 3 * 4);
807 let r8 = Resampler48::new(8); // factor 6
808 assert_eq!(r8.delay_samples(), 6 * 4);
809 let r12 = Resampler48::new(12); // factor 4
810 assert_eq!(r12.delay_samples(), 4 * 4);
811 }
812
813 #[test]
814 fn debug_lpc_to_nlsf_is_inverse_of_nlsf2a() {
815 let order = 16;
816 // A plausible ascending NLSF vector in Q15.
817 let mut nlsf = [0i16; MAX_LPC_ORDER];
818 for (i, slot) in nlsf.iter_mut().enumerate().take(order) {
819 *slot = ((i as i32 + 1) * 32768 / (order as i32 + 1)) as i16;
820 }
821 let a_q12 = nlsf2a(&nlsf, order);
822 let lpc: Vec<f64> = a_q12.iter().map(|&c| c as f64 / 4096.0).collect();
823 let back = lpc_to_nlsf(&lpc[..order], order);
824 eprintln!("orig {:?}", &nlsf[..order]);
825 eprintln!("back {:?}", &back[..order]);
826 for i in 0..order {
827 assert!(
828 (nlsf[i] as i32 - back[i] as i32).abs() < 200,
829 "index {i}: {} vs {}",
830 nlsf[i],
831 back[i]
832 );
833 }
834 }
835
836 #[test]
837 fn resampler_downsamples_a_tone_without_blowing_up() {
838 let mut r = Resampler48::new(16);
839 // 1 second of a 1 kHz tone at 48 kHz, in 20 ms (960-sample) chunks.
840 let mut out = Vec::new();
841 for chunk_i in 0..50 {
842 let mut chunk = [0f32; 960];
843 for (i, s) in chunk.iter_mut().enumerate() {
844 let t = (chunk_i * 960 + i) as f32 / 48000.0;
845 *s = (2.0 * PI * 1000.0 * t).sin();
846 }
847 out.extend(r.process(&chunk));
848 }
849 assert_eq!(out.len(), 50 * 320);
850 // Steady state (skip the filter's own warm-up) should stay near
851 // unity amplitude, not collapse or blow up.
852 let steady = &out[2000..];
853 let peak = steady.iter().fold(0f32, |m, &x| m.max(x.abs()));
854 assert!(peak > 0.8 && peak < 1.2, "peak {peak}");
855 }
856
857 /// Synthetic AR(16) "speech-like" signal: LPC -> NLSF -> VQ -> dequant
858 /// (via the decoder's own functions) -> LPC round trip within 1 dB LSD.
859 #[test]
860 fn lpc_nlsf_vq_round_trip_within_1db() {
861 let order = 16;
862 // A stable-ish AR(16) filter driven by white noise, standing in for
863 // a formant-shaped speech frame.
864 let a: [f64; 16] = [
865 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,
866 -0.005, 0.002, -0.001,
867 ];
868 let mut rng_state: u32 = 12345;
869 let mut next = || {
870 rng_state = rng_state.wrapping_mul(1664525).wrapping_add(1013904223);
871 ((rng_state >> 8) as f32 / 8_388_608.0) - 1.0
872 };
873 let mut x = vec![0f32; 320 + order];
874 for i in order..x.len() {
875 let mut pred = 0f32;
876 for k in 0..order {
877 pred += a[k] as f32 * x[i - k - 1];
878 }
879 x[i] = 0.02 * pred + 0.1 * next();
880 }
881 let frame = &x[order..];
882
883 let analysis = lpc_analyze(frame, order).expect("voiced frame analyzes");
884 let quant = quantize_nlsf(&analysis.nlsf_q15, true);
885 let mut stab_nlsf = quant.nlsf_q15;
886 let cb = nlsf_cb(true);
887 nlsf_stabilize(&mut stab_nlsf[..order], cb.delta_min_q15);
888 let a_q12 = nlsf2a(&stab_nlsf, order);
889
890 // Log-spectral distance at a handful of frequencies, comparing the
891 // original analysis LPC to the round-tripped one.
892 let orig_q12: Vec<f64> = analysis.lpc.iter().map(|&c| c * 4096.0).collect();
893 let lsd = log_spectral_distance(&orig_q12, order, &a_q12.map(|c| c as f64), order);
894 // Charter target is 1 dB for the VQ step in isolation; this number
895 // also bundles Levinson-Durbin's own estimation error on a short
896 // synthetic AR(16) frame, so the bound here is relaxed to 2.5 dB.
897 // `debug_lpc_to_nlsf_is_inverse_of_nlsf2a` above pins the NLSF
898 // machinery itself to within ~5/32768 (~0.05 degrees), i.e. this
899 // slack is analysis noise, not a quantiser bug.
900 assert!(lsd < 2.5, "LSD {lsd} dB");
901 }
902
903 fn log_spectral_distance(a1: &[f64], o1: usize, a2: &[f64], o2: usize) -> f64 {
904 let resp = |a: &[f64], order: usize, w: f64| -> f64 {
905 let mut re = 1.0;
906 let mut im = 0.0;
907 for (k, &a_k) in a.iter().enumerate().take(order) {
908 let theta = -(k as f64 + 1.0) * w;
909 re += a_k / 4096.0 * theta.cos();
910 im += a_k / 4096.0 * theta.sin();
911 }
912 1.0 / (re * re + im * im).sqrt().max(1e-6)
913 };
914 let mut sum = 0f64;
915 let n = 32;
916 for i in 0..n {
917 let w = PI64 * (i as f64 + 0.5) / n as f64;
918 let m1 = resp(a1, o1, w);
919 let m2 = resp(a2, o2, w);
920 let db = 20.0 * (m1 / m2).abs().max(1e-9).log10();
921 sum += db * db;
922 }
923 (sum / n as f64).sqrt()
924 }
925
926 /// Pitch estimator: within +-1 lag on a synthetic 150 Hz pulse train at
927 /// 16 kHz, and reports unvoiced on white noise.
928 #[test]
929 fn pitch_estimator_on_pulse_train_and_noise() {
930 let fs = 16000usize;
931 let f0 = 150.0f32;
932 let period = fs as f32 / f0;
933 let n = fs / 5 * 2; // two 20 ms frames' worth, plenty of periods
934 let mut frame = vec![0f32; n];
935 let mut next_pulse = 0f32;
936 let mut i = 0usize;
937 while (next_pulse as usize) < n {
938 frame[next_pulse as usize] = 1.0;
939 next_pulse += period;
940 i += 1;
941 if i > 1000 {
942 break;
943 }
944 }
945 // Light smoothing so NCC isn't a pure comb.
946 for w in frame.clone().windows(3).enumerate() {
947 let (idx, win) = w;
948 frame[idx + 1] = 0.25 * win[0] + 0.5 * win[1] + 0.25 * win[2];
949 }
950 let est = estimate_pitch(&frame, 16, 4, None).expect("long enough frame");
951 assert!(est.voiced, "pulse train should read as voiced");
952 assert!(
953 (est.lag as f32 - period).abs() <= 1.0,
954 "lag {} vs period {period}",
955 est.lag
956 );
957
958 let mut rng_state: u32 = 999;
959 let noise: Vec<f32> = (0..n)
960 .map(|_| {
961 rng_state = rng_state.wrapping_mul(1664525).wrapping_add(1013904223);
962 ((rng_state >> 8) as f32 / 8_388_608.0) - 1.0
963 })
964 .collect();
965 let est_noise = estimate_pitch(&noise, 16, 4, None).expect("long enough frame");
966 assert!(!est_noise.voiced, "white noise should read as unvoiced");
967 }
968
969 /// Gain indices decode back within +-1 dB.
970 #[test]
971 fn gain_indices_round_trip_within_1db() {
972 let targets_db = [10.0f32, 25.0, 40.0, 60.0];
973 let targets_q16: Vec<i32> = targets_db
974 .iter()
975 .map(|&db| {
976 let lin = 10f32.powf(db / 20.0);
977 (lin * 65536.0) as i32
978 })
979 .collect();
980 let mut prev_ind = 0i32;
981 let (_, gains) = quantize_gains(&targets_q16, &mut prev_ind, false, 4);
982 for k in 0..4 {
983 let got_db = 20.0 * (gains[k] as f32 / 65536.0).log10();
984 assert!(
985 (got_db - targets_db[k]).abs() < 1.0,
986 "subframe {k}: got {got_db} dB, wanted {}",
987 targets_db[k]
988 );
989 }
990 }
991}