forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

silk.rs1862 lines, 66.4 KiBHistoryRawDownload
1//! The SILK (linear-prediction) layer of Opus — RFC 6716 Section 4.2.
2//!
3//! SILK is a speech coder: each 20 ms frame carries an LPC filter (as line
4//! spectral frequencies), a per-subframe gain, an optional long-term (pitch)
5//! predictor, and a pulse-coded excitation. Decoding runs that chain backwards
6//! — excitation, LTP synthesis, LPC synthesis — then unmixes stereo and
7//! resamples from the internal 8/12/16 kHz to the output rate.
8//!
9//! Unlike CELT, SILK has no floating-point form: every operation below is the
10//! exact integer arithmetic of the normative decoder (RFC 6716 Section 6 makes
11//! the Appendix A reference implementation normative, and Section 4.2 is
12//! written as fixed-point pseudo-code for the same reason). The tables are the
13//! ones the RFC tabulates in Section 4.2, in the layout the reference uses.
14//!
15//! Packet loss concealment is not implemented: this decoder is fed complete
16//! packets by the container layer, so a lost or empty frame yields silence
17//! rather than an extrapolation. Everything else in the layer is complete.
18
19// SILK is transliterated fixed-point arithmetic: the loops below index parallel
20// arrays by position because the reference's index arithmetic is the
21// specification. Iterator forms would hide that correspondence.
22#![allow(clippy::needless_range_loop)]
23
24use ec_core::Result;
25
26use crate::range::RangeDecoder;
27
28pub(crate) mod tables {
29 #![allow(clippy::all)]
30 include!("silk_tables.rs");
31}
32
33use tables::*;
34
35pub(crate) const MAX_LPC_ORDER: usize = 16;
36pub(crate) const LTP_ORDER: usize = 5;
37pub(crate) const MAX_NB_SUBFR: usize = 4;
38const SUB_FRAME_LENGTH_MS: usize = 5;
39const LTP_MEM_LENGTH_MS: usize = 20;
40const MAX_FRAME_LENGTH: usize = 20 * 16;
41const QUANT_LEVEL_ADJUST_Q10: i32 = 80;
42const N_LEVELS_QGAIN: i32 = 64;
43const MIN_DELTA_GAIN_QUANT: i32 = -4;
44const MAX_DELTA_GAIN_QUANT: i32 = 36;
45const MIN_QGAIN_DB: i32 = 2;
46const MAX_QGAIN_DB: i32 = 88;
47pub(crate) const NLSF_QUANT_MAX_AMPLITUDE: i32 = 4;
48const SHELL_LEN: usize = 16;
49const MAX_PULSES: i32 = 16;
50const N_RATE_LEVELS: usize = 10;
51pub(crate) const PE_MIN_LAG_MS: i32 = 2;
52pub(crate) const PE_MAX_LAG_MS: i32 = 18;
53const STEREO_INTERP_LEN_MS: usize = 8;
54const TYPE_VOICED: i32 = 2;
55const MAX_LPC_STABILIZE_ITERATIONS: usize = 16;
56
57/// Gain quantiser constants (`gain_quant.c`).
58const GAIN_OFFSET: i32 = (MIN_QGAIN_DB * 128) / 6 + 16 * 128;
59const GAIN_INV_SCALE_Q16: i32 =
60 (65536 * (((MAX_QGAIN_DB - MIN_QGAIN_DB) * 128) / 6)) / (N_LEVELS_QGAIN - 1);
61
62/// How a frame's parameters relate to the previous frame's.
63#[derive(Clone, Copy, PartialEq, Eq, Debug)]
64enum CondCoding {
65 Independently,
66 IndependentlyNoLtpScaling,
67 Conditionally,
68}
69
70// ---------------------------------------------------------------------------
71// Fixed-point helpers. These are the reference's macros; they are written out
72// because SILK's output is defined by them bit for bit.
73// ---------------------------------------------------------------------------
74
75#[inline]
76pub(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))
78 as i32
79}
80
81#[inline]
82pub(crate) fn smlawb(a: i32, b: i32, c: i32) -> i32 {
83 a.wrapping_add(smulwb(b, c))
84}
85
86#[inline]
87pub(crate) fn smulbb(a: i32, b: i32) -> i32 {
88 (a as i16 as i32).wrapping_mul(b as i16 as i32)
89}
90
91#[inline]
92fn smlabb(a: i32, b: i32, c: i32) -> i32 {
93 a.wrapping_add(smulbb(b, c))
94}
95
96#[inline]
97pub(crate) fn rshift_round(a: i32, shift: u32) -> i32 {
98 if shift == 1 {
99 (a >> 1) + (a & 1)
100 } else {
101 ((a >> (shift - 1)) + 1) >> 1
102 }
103}
104
105#[inline]
106fn rshift_round64(a: i64, shift: u32) -> i64 {
107 if shift == 1 {
108 (a >> 1) + (a & 1)
109 } else {
110 ((a >> (shift - 1)) + 1) >> 1
111 }
112}
113
114#[inline]
115fn smulww(a: i32, b: i32) -> i32 {
116 smulwb(a, b).wrapping_add(a.wrapping_mul(rshift_round(b, 16)))
117}
118
119#[inline]
120fn smlaww(a: i32, b: i32, c: i32) -> i32 {
121 smlawb(a, b, c).wrapping_add(b.wrapping_mul(rshift_round(c, 16)))
122}
123
124/// `silk_SMMUL`: the top 32 bits of a 32x32 product.
125#[inline]
126fn smmul(a: i32, b: i32) -> i32 {
127 ((a as i64 * b as i64) >> 32) as i32
128}
129
130#[inline]
131fn sat16(a: i32) -> i16 {
132 a.clamp(-32768, 32767) as i16
133}
134
135#[inline]
136fn clz32(x: i32) -> i32 {
137 if x == 0 {
138 32
139 } else {
140 (x as u32).leading_zeros() as i32
141 }
142}
143
144/// `silk_CLZ_FRAC`: leading zeros plus the seven bits below the leading one.
145#[inline]
146fn clz_frac(x: i32) -> (i32, i32) {
147 let lz = clz32(x);
148 let frac = (x as u32).rotate_right((24 - lz) as u32) as i32 & 0x7F;
149 (lz, frac)
150}
151
152pub(crate) fn sqrt_approx(x: i32) -> i32 {
153 if x <= 0 {
154 return 0;
155 }
156 let (lz, frac) = clz_frac(x);
157 let mut y = if lz & 1 != 0 { 32768 } else { 46214 };
158 y >>= lz >> 1;
159 smlawb(y, y, smulbb(213, frac))
160}
161
162pub(crate) fn log2lin(log_q7: i32) -> i32 {
163 if log_q7 < 0 {
164 return 0;
165 }
166 let mut out = 1i32 << (log_q7 >> 7);
167 let frac = log_q7 & 0x7F;
168 let adj = smlawb(frac, smulbb(frac, 128 - frac), -174);
169 if log_q7 < 2048 {
170 out += ((out as i64 * adj as i64) >> 7) as i32;
171 } else {
172 out = out.wrapping_add((out >> 7).wrapping_mul(adj));
173 }
174 out
175}
176
177/// `silk_INVERSE32_varQ`: `(1 << q) / b`, to about 30 bits.
178fn inverse32_var_q(b32: i32, qres: u32) -> i32 {
179 debug_assert!(b32 != 0);
180 let b_headrm = clz32(b32.abs()) - 1;
181 let b32_nrm = b32 << b_headrm;
182 let b32_inv = (i32::MAX >> 2) / (b32_nrm >> 16);
183 let mut result = b32_inv << 16;
184 let err_q32 = ((1 << 29) - smulwb(b32_nrm, b32_inv)) << 3;
185 result = smlaww(result, err_q32, b32_inv);
186 let lshift = 61 - b_headrm - qres as i32;
187 if lshift <= 0 {
188 lshift_sat32(result, -lshift)
189 } else if lshift < 32 {
190 result >> lshift
191 } else {
192 0
193 }
194}
195
196/// `silk_DIV32_varQ`: `(a << q) / b`.
197fn div32_var_q(a32: i32, b32: i32, qres: u32) -> i32 {
198 debug_assert!(b32 != 0);
199 let a_headrm = clz32(a32.abs()) - 1;
200 let mut a32_nrm = a32 << a_headrm;
201 let b_headrm = clz32(b32.abs()) - 1;
202 let b32_nrm = b32 << b_headrm;
203 let b32_inv = (i32::MAX >> 2) / (b32_nrm >> 16);
204 let mut result = smulwb(a32_nrm, b32_inv);
205 a32_nrm = a32_nrm.wrapping_sub(smmul(b32_nrm, result).wrapping_shl(3));
206 result = smlawb(result, a32_nrm, b32_inv);
207 let lshift = 29 + a_headrm - b_headrm - qres as i32;
208 if lshift < 0 {
209 lshift_sat32(result, -lshift)
210 } else if lshift < 32 {
211 result >> lshift
212 } else {
213 0
214 }
215}
216
217fn lshift_sat32(a: i32, shift: i32) -> i32 {
218 let lim = i32::MAX >> shift;
219 a.clamp(-lim - 1, lim) << shift
220}
221
222/// `silk_RAND`: the excitation sign PRNG.
223#[inline]
224pub(crate) fn silk_rand(seed: i32) -> i32 {
225 (907633515i32).wrapping_add(seed.wrapping_mul(196314165))
226}
227
228// ---------------------------------------------------------------------------
229// Decoder state
230// ---------------------------------------------------------------------------
231
232/// Per-frame parameters decoded from the bitstream.
233#[derive(Clone, Debug, Default)]
234struct Indices {
235 signal_type: i32,
236 quant_offset_type: i32,
237 gains: [i8; MAX_NB_SUBFR],
238 nlsf: [i8; MAX_LPC_ORDER + 1],
239 nlsf_interp_coef_q2: i32,
240 lag_index: i32,
241 contour_index: i32,
242 per_index: usize,
243 ltp_index: [usize; MAX_NB_SUBFR],
244 ltp_scale_index: usize,
245 seed: i32,
246}
247
248/// Public snapshot of per-frame SILK parameters as decoded from the
249/// bitstream — used by the oracle diagnostic to compare our encoder's
250/// packets against ffmpeg-libopus's.
251#[derive(Clone, Debug, Default)]
252pub struct SilkDecIndices {
253 pub signal_type: i32,
254 pub quant_offset_type: i32,
255 pub gains: [i8; 4],
256 pub nlsf: [i8; 17],
257 pub nlsf_interp_coef_q2: i32,
258 pub lag_index: i32,
259 pub contour_index: i32,
260 pub per_index: usize,
261 pub ltp_index: [usize; 4],
262 pub ltp_scale_index: usize,
263 pub seed: i32,
264 pub frames_decoded: usize,
265}
266
267/// Everything `decode_parameters` produces for one frame.
268#[derive(Clone, Debug)]
269struct FrameCtrl {
270 gains_q16: [i32; MAX_NB_SUBFR],
271 pred_coef_q12: [[i16; MAX_LPC_ORDER]; 2],
272 ltp_coef_q14: [i16; LTP_ORDER * MAX_NB_SUBFR],
273 ltp_scale_q14: i32,
274 pitch_l: [i32; MAX_NB_SUBFR],
275}
276
277impl Default for FrameCtrl {
278 fn default() -> Self {
279 FrameCtrl {
280 gains_q16: [0; MAX_NB_SUBFR],
281 pred_coef_q12: [[0; MAX_LPC_ORDER]; 2],
282 ltp_coef_q14: [0; LTP_ORDER * MAX_NB_SUBFR],
283 ltp_scale_q14: 0,
284 pitch_l: [0; MAX_NB_SUBFR],
285 }
286 }
287}
288
289/// One SILK channel's inter-frame state.
290#[derive(Clone, Debug)]
291struct ChannelState {
292 fs_khz: usize,
293 frame_length: usize,
294 subfr_length: usize,
295 ltp_mem_length: usize,
296 nb_subfr: usize,
297 lpc_order: usize,
298 frames_per_packet: usize,
299 frames_decoded: usize,
300 /// Wideband uses the 16th-order codebook, NB/MB the 10th-order one.
301 wb_codebook: bool,
302 indices: Indices,
303 /// Synthesis history, `ltp_mem_length + frame_length` samples.
304 out_buf: [i16; MAX_FRAME_LENGTH + MAX_FRAME_LENGTH],
305 s_lpc_q14: [i32; MAX_LPC_ORDER],
306 exc_q14: [i32; MAX_FRAME_LENGTH],
307 prev_nlsf_q15: [i16; MAX_LPC_ORDER],
308 prev_gain_q16: i32,
309 last_gain_index: i32,
310 prev_signal_type: i32,
311 ec_prev_signal_type: i32,
312 ec_prev_lag_index: i32,
313 lag_prev: i32,
314 first_frame_after_reset: bool,
315 vad_flags: [bool; 3],
316 lbrr_flag: bool,
317 lbrr_flags: [bool; 3],
318 resampler: Resampler,
319}
320
321impl ChannelState {
322 fn new() -> ChannelState {
323 ChannelState {
324 fs_khz: 0,
325 frame_length: 0,
326 subfr_length: 0,
327 ltp_mem_length: 0,
328 nb_subfr: 0,
329 lpc_order: 0,
330 frames_per_packet: 1,
331 frames_decoded: 0,
332 wb_codebook: false,
333 indices: Indices::default(),
334 out_buf: [0; MAX_FRAME_LENGTH * 2],
335 s_lpc_q14: [0; MAX_LPC_ORDER],
336 exc_q14: [0; MAX_FRAME_LENGTH],
337 prev_nlsf_q15: [0; MAX_LPC_ORDER],
338 prev_gain_q16: 65536,
339 last_gain_index: 10,
340 prev_signal_type: 0,
341 ec_prev_signal_type: 0,
342 ec_prev_lag_index: 0,
343 lag_prev: 100,
344 first_frame_after_reset: true,
345 vad_flags: [false; 3],
346 lbrr_flag: false,
347 lbrr_flags: [false; 3],
348 resampler: Resampler::default(),
349 }
350 }
351
352 /// `silk_decoder_set_fs`: geometry for an internal rate.
353 fn set_fs(&mut self, fs_khz: usize, api_rate: u32) {
354 self.subfr_length = SUB_FRAME_LENGTH_MS * fs_khz;
355 let frame_length = self.nb_subfr * self.subfr_length;
356 if self.fs_khz != fs_khz || self.resampler.fs_out_khz * 1000 != api_rate as usize {
357 self.resampler = Resampler::new(fs_khz, api_rate as usize / 1000);
358 }
359 if self.fs_khz != fs_khz {
360 self.ltp_mem_length = LTP_MEM_LENGTH_MS * fs_khz;
361 if fs_khz == 16 {
362 self.lpc_order = MAX_LPC_ORDER;
363 self.wb_codebook = true;
364 } else {
365 self.lpc_order = 10;
366 self.wb_codebook = false;
367 }
368 self.first_frame_after_reset = true;
369 self.lag_prev = 100;
370 self.last_gain_index = 10;
371 self.prev_signal_type = 0;
372 self.out_buf.fill(0);
373 self.s_lpc_q14.fill(0);
374 }
375 self.fs_khz = fs_khz;
376 self.frame_length = frame_length;
377 }
378
379 fn pitch_contour_icdf(&self) -> &'static [u8] {
380 match (self.fs_khz, self.nb_subfr) {
381 (8, 4) => &PITCH_CONTOUR_NB_ICDF,
382 (8, _) => &PITCH_CONTOUR_10_MS_NB_ICDF,
383 (_, 4) => &PITCH_CONTOUR_ICDF,
384 _ => &PITCH_CONTOUR_10_MS_ICDF,
385 }
386 }
387
388 fn pitch_lag_low_bits_icdf(&self) -> &'static [u8] {
389 match self.fs_khz {
390 16 => &UNIFORM8_ICDF,
391 12 => &UNIFORM6_ICDF,
392 _ => &UNIFORM4_ICDF,
393 }
394 }
395}
396
397/// Stereo prediction state carried between frames.
398#[derive(Clone, Debug, Default)]
399struct StereoState {
400 pred_prev_q13: [i32; 2],
401 s_mid: [i16; 2],
402 s_side: [i16; 2],
403}
404
405/// The SILK decoder for one Opus stream (one or two channels).
406#[derive(Clone, Debug)]
407pub struct SilkDecoder {
408 channels: [ChannelState; 2],
409 stereo: StereoState,
410 channels_internal: usize,
411 channels_api: usize,
412 api_rate: u32,
413 prev_decode_only_middle: bool,
414 /// Resampler output for one channel, allocated once.
415 resample_tmp: Vec<i16>,
416}
417
418impl SilkDecoder {
419 /// A decoder producing `channels_api` channels at `api_rate` Hz.
420 pub fn new(api_rate: u32, channels_api: usize) -> SilkDecoder {
421 SilkDecoder {
422 channels: [ChannelState::new(), ChannelState::new()],
423 stereo: StereoState::default(),
424 channels_internal: 1,
425 channels_api,
426 api_rate,
427 prev_decode_only_middle: false,
428 resample_tmp: vec![0; 5760],
429 }
430 }
431
432 /// The last 20 ms of decoded output of channel 0 at the internal rate:
433 /// the synthesis history `decode_core` whitens for its LTP state. The
434 /// encoder mirrors its own packets through a `SilkDecoder` and reads this
435 /// so its LTP search runs on exactly what the real decoder will predict
436 /// from.
437 pub(crate) fn history(&self) -> &[i16] {
438 let ch = &self.channels[0];
439 &ch.out_buf[..ch.ltp_mem_length]
440 }
441
442 /// Snapshot of the last decoded frame's index parameters for channel 0.
443 /// Used by the oracle diagnostic to inspect what the bitstream coded.
444 pub fn last_indices(&self) -> SilkDecIndices {
445 let ix = &self.channels[0].indices;
446 SilkDecIndices {
447 signal_type: ix.signal_type,
448 quant_offset_type: ix.quant_offset_type,
449 gains: ix.gains,
450 nlsf: ix.nlsf,
451 nlsf_interp_coef_q2: ix.nlsf_interp_coef_q2,
452 lag_index: ix.lag_index,
453 contour_index: ix.contour_index,
454 per_index: ix.per_index,
455 ltp_index: ix.ltp_index,
456 ltp_scale_index: ix.ltp_scale_index,
457 seed: ix.seed,
458 frames_decoded: self.channels[0].frames_decoded,
459 }
460 }
461
462 /// Drops all inter-packet state.
463 pub fn reset(&mut self) {
464 let api_rate = self.api_rate;
465 let channels_api = self.channels_api;
466 *self = SilkDecoder::new(api_rate, channels_api);
467 }
468
469 /// Decodes the SILK part of one Opus frame.
470 ///
471 /// `payload_ms` is the Opus frame duration (10, 20, 40 or 60 ms),
472 /// `internal_rate` the SILK sample rate the TOC implies (8000, 12000 or
473 /// 16000 Hz), and `channels_internal` how many channels the packet codes.
474 /// Output is interleaved `i16` at the API rate, `channels_api` channels.
475 pub fn decode(
476 &mut self,
477 dec: &mut RangeDecoder,
478 out: &mut [i16],
479 payload_ms: usize,
480 internal_rate: u32,
481 channels_internal: usize,
482 new_packet: bool,
483 ) -> Result<usize> {
484 let fs_khz = (internal_rate / 1000) as usize;
485 if new_packet {
486 for ch in self.channels.iter_mut() {
487 ch.frames_decoded = 0;
488 }
489 }
490 let (frames_per_packet, nb_subfr) = match payload_ms {
491 10 => (1, 2),
492 20 => (1, 4),
493 40 => (2, 4),
494 60 => (3, 4),
495 _ => (1, 4),
496 };
497 // A stream that gains a second channel starts it from scratch.
498 if channels_internal > self.channels_internal {
499 self.channels[1] = ChannelState::new();
500 }
501 if self.channels[0].frames_decoded == 0 {
502 for ch in self.channels.iter_mut().take(channels_internal) {
503 ch.frames_per_packet = frames_per_packet;
504 ch.nb_subfr = nb_subfr;
505 ch.set_fs(fs_khz, self.api_rate);
506 }
507 }
508 if self.channels_api == 2 && channels_internal == 2 && self.channels_internal == 1 {
509 // The side channel starts from the mid channel's resampler state,
510 // so the two stay in phase across the mono-to-stereo switch.
511 self.stereo.pred_prev_q13 = [0; 2];
512 self.stereo.s_side = [0; 2];
513 self.channels[1].resampler = self.channels[0].resampler.clone();
514 }
515 self.channels_internal = channels_internal;
516
517 let mut ms_pred_q13 = [0i32; 2];
518 let mut decode_only_middle = false;
519
520 // Header bits: per-frame VAD flags and the LBRR flag (Section 4.2.3).
521 if self.channels[0].frames_decoded == 0 {
522 for n in 0..channels_internal {
523 for i in 0..self.channels[n].frames_per_packet {
524 self.channels[n].vad_flags[i] = dec.dec_bit_logp(1);
525 }
526 self.channels[n].lbrr_flag = dec.dec_bit_logp(1);
527 }
528 for n in 0..channels_internal {
529 self.channels[n].lbrr_flags = [false; 3];
530 if self.channels[n].lbrr_flag {
531 if self.channels[n].frames_per_packet == 1 {
532 self.channels[n].lbrr_flags[0] = true;
533 } else {
534 let icdf: &[u8] = if self.channels[n].frames_per_packet == 2 {
535 &LBRR_FLAGS_2_ICDF
536 } else {
537 &LBRR_FLAGS_3_ICDF
538 };
539 let sym = dec.dec_icdf(icdf, 8) as i32 + 1;
540 for i in 0..self.channels[n].frames_per_packet {
541 self.channels[n].lbrr_flags[i] = (sym >> i) & 1 != 0;
542 }
543 }
544 }
545 }
546 // Skip the LBRR frames: they are only useful for concealment, but
547 // their symbols must still be consumed to stay in sync.
548 for i in 0..self.channels[0].frames_per_packet {
549 for n in 0..channels_internal {
550 if self.channels[n].lbrr_flags[i] {
551 if channels_internal == 2 && n == 0 {
552 stereo_decode_pred(dec, &mut ms_pred_q13);
553 if !self.channels[1].lbrr_flags[i] {
554 let _ = dec.dec_icdf(&STEREO_ONLY_CODE_MID_ICDF, 8);
555 }
556 }
557 let cond = if i > 0 && self.channels[n].lbrr_flags[i - 1] {
558 CondCoding::Conditionally
559 } else {
560 CondCoding::Independently
561 };
562 let ch = &mut self.channels[n];
563 decode_indices(ch, dec, i, true, cond);
564 let mut pulses = [0i32; MAX_FRAME_LENGTH + SHELL_LEN];
565 let n = ch.frame_length;
566 decode_pulses(
567 dec,
568 &mut pulses,
569 n,
570 ch.indices.signal_type,
571 ch.indices.quant_offset_type,
572 );
573 }
574 }
575 }
576 }
577
578 // Stereo prediction weights for this frame.
579 if channels_internal == 2 {
580 stereo_decode_pred(dec, &mut ms_pred_q13);
581 let frame = self.channels[0].frames_decoded;
582 if !self.channels[1].vad_flags[frame] {
583 decode_only_middle = dec.dec_icdf(&STEREO_ONLY_CODE_MID_ICDF, 8) != 0;
584 }
585 }
586 if channels_internal == 2 && !decode_only_middle && self.prev_decode_only_middle {
587 self.channels[1].out_buf.fill(0);
588 self.channels[1].s_lpc_q14.fill(0);
589 self.channels[1].lag_prev = 100;
590 self.channels[1].last_gain_index = 10;
591 self.channels[1].prev_signal_type = 0;
592 self.channels[1].first_frame_after_reset = true;
593 }
594
595 let has_side = !decode_only_middle;
596 let mut mid = [0i16; MAX_FRAME_LENGTH + 2];
597 let mut side = [0i16; MAX_FRAME_LENGTH + 2];
598 let mut n_samples_dec = 0usize;
599 for n in 0..channels_internal {
600 let buf: &mut [i16] = if n == 0 { &mut mid } else { &mut side };
601 if n == 0 || has_side {
602 let frame_index = self.channels[0].frames_decoded as i32 - n as i32;
603 let cond = if frame_index <= 0 {
604 CondCoding::Independently
605 } else if n > 0 && self.prev_decode_only_middle {
606 CondCoding::IndependentlyNoLtpScaling
607 } else {
608 CondCoding::Conditionally
609 };
610 n_samples_dec = decode_frame(&mut self.channels[n], dec, &mut buf[2..], cond);
611 } else {
612 buf[2..2 + n_samples_dec].fill(0);
613 }
614 self.channels[n].frames_decoded += 1;
615 }
616
617 // Stereo unmixing, then resampling to the output rate.
618 if self.channels_api == 2 && channels_internal == 2 {
619 stereo_ms_to_lr(
620 &mut self.stereo,
621 &mut mid,
622 &mut side,
623 &ms_pred_q13,
624 self.channels[0].fs_khz,
625 n_samples_dec,
626 );
627 } else {
628 mid[0] = self.stereo.s_mid[0];
629 mid[1] = self.stereo.s_mid[1];
630 self.stereo.s_mid[0] = mid[n_samples_dec];
631 self.stereo.s_mid[1] = mid[n_samples_dec + 1];
632 }
633 self.prev_decode_only_middle = decode_only_middle;
634
635 let out_len = n_samples_dec * self.api_rate as usize / (self.channels[0].fs_khz * 1000);
636 let mut tmp = core::mem::take(&mut self.resample_tmp);
637 tmp.clear();
638 tmp.resize(out_len, 0);
639 let chans = self.channels_api.min(channels_internal);
640 for n in 0..chans {
641 let src: &[i16] = if n == 0 { &mid[1..] } else { &side[1..] };
642 let state = &mut self.channels[n].resampler;
643 state.process(&mut tmp, &src[..n_samples_dec], n_samples_dec);
644 if self.channels_api == 2 {
645 for i in 0..out_len {
646 out[n + 2 * i] = tmp[i];
647 }
648 } else {
649 out[..out_len].copy_from_slice(&tmp[..out_len]);
650 }
651 }
652 self.resample_tmp = tmp;
653 // A mono stream fed to a stereo output is duplicated.
654 if self.channels_api == 2 && channels_internal == 1 {
655 for i in 0..out_len {
656 out[1 + 2 * i] = out[2 * i];
657 }
658 }
659 Ok(out_len)
660 }
661}
662
663/// `silk_decode_indices` (Section 4.2.7).
664fn decode_indices(
665 ch: &mut ChannelState,
666 dec: &mut RangeDecoder,
667 frame_index: usize,
668 decode_lbrr: bool,
669 cond: CondCoding,
670) {
671 let ix = if decode_lbrr || ch.vad_flags[frame_index] {
672 dec.dec_icdf(&TYPE_OFFSET_VAD_ICDF, 8) as i32 + 2
673 } else {
674 dec.dec_icdf(&TYPE_OFFSET_NO_VAD_ICDF, 8) as i32
675 };
676 ch.indices.signal_type = ix >> 1;
677 ch.indices.quant_offset_type = ix & 1;
678
679 // Subframe gains (Section 4.2.7.4).
680 if cond == CondCoding::Conditionally {
681 ch.indices.gains[0] = dec.dec_icdf(&DELTA_GAIN_ICDF, 8) as i8;
682 } else {
683 let msb = dec.dec_icdf(&GAIN_ICDF[ch.indices.signal_type as usize], 8) as i32;
684 let lsb = dec.dec_icdf(&UNIFORM8_ICDF, 8) as i32;
685 ch.indices.gains[0] = ((msb << 3) + lsb) as i8;
686 }
687 for i in 1..ch.nb_subfr {
688 ch.indices.gains[i] = dec.dec_icdf(&DELTA_GAIN_ICDF, 8) as i8;
689 }
690
691 // Normalised LSFs (Section 4.2.7.5).
692 let cb = nlsf_cb(ch.wb_codebook);
693 let stage1_icdf = &cb.cb1_icdf[(ch.indices.signal_type as usize >> 1) * cb.n_vectors..];
694 ch.indices.nlsf[0] = dec.dec_icdf(stage1_icdf, 8) as i8;
695 let (ec_ix, _pred) = nlsf_unpack(cb, ch.indices.nlsf[0] as usize);
696 for i in 0..cb.order {
697 let mut ix = dec.dec_icdf(&cb.ec_icdf[ec_ix[i] as usize..], 8) as i32;
698 if ix == 0 {
699 ix -= dec.dec_icdf(&NLSF_EXT_ICDF, 8) as i32;
700 } else if ix == 2 * NLSF_QUANT_MAX_AMPLITUDE {
701 ix += dec.dec_icdf(&NLSF_EXT_ICDF, 8) as i32;
702 }
703 ch.indices.nlsf[i + 1] = (ix - NLSF_QUANT_MAX_AMPLITUDE) as i8;
704 }
705 ch.indices.nlsf_interp_coef_q2 = if ch.nb_subfr == MAX_NB_SUBFR {
706 dec.dec_icdf(&NLSF_INTERPOLATION_FACTOR_ICDF, 8) as i32
707 } else {
708 4
709 };
710
711 // Pitch and LTP (Section 4.2.7.6).
712 if ch.indices.signal_type == TYPE_VOICED {
713 let mut absolute = true;
714 if cond == CondCoding::Conditionally && ch.ec_prev_signal_type == TYPE_VOICED {
715 let delta = dec.dec_icdf(&PITCH_DELTA_ICDF, 8) as i32;
716 if delta > 0 {
717 ch.indices.lag_index = ch.ec_prev_lag_index + delta - 9;
718 absolute = false;
719 }
720 }
721 if absolute {
722 ch.indices.lag_index =
723 dec.dec_icdf(&PITCH_LAG_ICDF, 8) as i32 * (ch.fs_khz as i32 >> 1);
724 ch.indices.lag_index += dec.dec_icdf(ch.pitch_lag_low_bits_icdf(), 8) as i32;
725 }
726 ch.ec_prev_lag_index = ch.indices.lag_index;
727 ch.indices.contour_index = dec.dec_icdf(ch.pitch_contour_icdf(), 8) as i32;
728 ch.indices.per_index = dec.dec_icdf(&LTP_PER_INDEX_ICDF, 8);
729 let gain_icdf: &[u8] = match ch.indices.per_index {
730 0 => &LTP_GAIN_ICDF_0,
731 1 => &LTP_GAIN_ICDF_1,
732 _ => &LTP_GAIN_ICDF_2,
733 };
734 for k in 0..ch.nb_subfr {
735 ch.indices.ltp_index[k] = dec.dec_icdf(gain_icdf, 8);
736 }
737 ch.indices.ltp_scale_index = if cond == CondCoding::Independently {
738 dec.dec_icdf(&LTPSCALE_ICDF, 8)
739 } else {
740 0
741 };
742 }
743 ch.ec_prev_signal_type = ch.indices.signal_type;
744 ch.indices.seed = dec.dec_icdf(&UNIFORM4_ICDF, 8) as i32;
745}
746
747/// `silk_decode_pulses` (Section 4.2.7.8): the excitation.
748fn decode_pulses(
749 dec: &mut RangeDecoder,
750 pulses: &mut [i32],
751 frame_length: usize,
752 signal_type: i32,
753 quant_offset_type: i32,
754) {
755 // A 12 kHz 10 ms frame is 120 samples, which is not a whole number of
756 // 16-sample shell blocks: the last block runs past the frame and its extra
757 // pulses are discarded, so `pulses` must have room for them.
758 debug_assert!(pulses.len() >= frame_length.div_ceil(SHELL_LEN) * SHELL_LEN);
759 let rate_level = dec.dec_icdf(&RATE_LEVELS_ICDF[signal_type as usize >> 1], 8);
760 let mut iter = frame_length >> 4;
761 if iter * SHELL_LEN < frame_length {
762 iter += 1;
763 }
764 let mut sum_pulses = [0i32; MAX_FRAME_LENGTH / SHELL_LEN + 1];
765 let mut n_lshifts = [0i32; MAX_FRAME_LENGTH / SHELL_LEN + 1];
766 for i in 0..iter {
767 sum_pulses[i] = dec.dec_icdf(&PULSES_PER_BLOCK_ICDF[rate_level], 8) as i32;
768 while sum_pulses[i] == MAX_PULSES + 1 {
769 n_lshifts[i] += 1;
770 let icdf = &PULSES_PER_BLOCK_ICDF[N_RATE_LEVELS - 1][usize::from(n_lshifts[i] == 10)..];
771 sum_pulses[i] = dec.dec_icdf(icdf, 8) as i32;
772 }
773 }
774 for i in 0..iter {
775 let block = &mut pulses[i * SHELL_LEN..];
776 if sum_pulses[i] > 0 {
777 shell_decode(dec, block, sum_pulses[i]);
778 } else {
779 block[..SHELL_LEN].fill(0);
780 }
781 }
782 // Least significant bits for blocks that overflowed the pulse count.
783 for i in 0..iter {
784 if n_lshifts[i] > 0 {
785 let block = &mut pulses[i * SHELL_LEN..];
786 for k in 0..SHELL_LEN {
787 let mut abs_q = block[k];
788 for _ in 0..n_lshifts[i] {
789 abs_q <<= 1;
790 abs_q += dec.dec_icdf(&LSB_ICDF, 8) as i32;
791 }
792 block[k] = abs_q;
793 }
794 sum_pulses[i] |= n_lshifts[i] << 5;
795 }
796 }
797 decode_signs(
798 dec,
799 pulses,
800 signal_type,
801 quant_offset_type,
802 &sum_pulses[..iter],
803 );
804}
805
806/// One 16-sample shell block (Section 4.2.7.8.3).
807fn shell_decode(dec: &mut RangeDecoder, pulses0: &mut [i32], total: i32) {
808 fn split(dec: &mut RangeDecoder, p: i32, table: &[u8]) -> (i32, i32) {
809 if p > 0 {
810 let a = dec.dec_icdf(&table[SHELL_CODE_TABLE_OFFSETS[p as usize] as usize..], 8) as i32;
811 (a, p - a)
812 } else {
813 (0, 0)
814 }
815 }
816 let mut p3 = [0i32; 2];
817 let mut p2 = [0i32; 4];
818 let mut p1 = [0i32; 8];
819 (p3[0], p3[1]) = split(dec, total, &SHELL_CODE_TABLE3);
820 (p2[0], p2[1]) = split(dec, p3[0], &SHELL_CODE_TABLE2);
821 (p1[0], p1[1]) = split(dec, p2[0], &SHELL_CODE_TABLE1);
822 (pulses0[0], pulses0[1]) = split(dec, p1[0], &SHELL_CODE_TABLE0);
823 (pulses0[2], pulses0[3]) = split(dec, p1[1], &SHELL_CODE_TABLE0);
824 (p1[2], p1[3]) = split(dec, p2[1], &SHELL_CODE_TABLE1);
825 (pulses0[4], pulses0[5]) = split(dec, p1[2], &SHELL_CODE_TABLE0);
826 (pulses0[6], pulses0[7]) = split(dec, p1[3], &SHELL_CODE_TABLE0);
827 (p2[2], p2[3]) = split(dec, p3[1], &SHELL_CODE_TABLE2);
828 (p1[4], p1[5]) = split(dec, p2[2], &SHELL_CODE_TABLE1);
829 (pulses0[8], pulses0[9]) = split(dec, p1[4], &SHELL_CODE_TABLE0);
830 (pulses0[10], pulses0[11]) = split(dec, p1[5], &SHELL_CODE_TABLE0);
831 (p1[6], p1[7]) = split(dec, p2[3], &SHELL_CODE_TABLE1);
832 (pulses0[12], pulses0[13]) = split(dec, p1[6], &SHELL_CODE_TABLE0);
833 (pulses0[14], pulses0[15]) = split(dec, p1[7], &SHELL_CODE_TABLE0);
834}
835
836/// Excitation signs (Section 4.2.7.8.5).
837fn decode_signs(
838 dec: &mut RangeDecoder,
839 pulses: &mut [i32],
840 signal_type: i32,
841 quant_offset_type: i32,
842 sum_pulses: &[i32],
843) {
844 let base = 7 * (quant_offset_type + (signal_type << 1)) as usize;
845 for (i, &p) in sum_pulses.iter().enumerate() {
846 if p > 0 {
847 let icdf = [SIGN_ICDF[base + (p & 0x1F).min(6) as usize], 0];
848 for j in 0..SHELL_LEN {
849 let idx = i * SHELL_LEN + j;
850 if idx < pulses.len() && pulses[idx] > 0 {
851 pulses[idx] *= 2 * dec.dec_icdf(&icdf, 8) as i32 - 1;
852 }
853 }
854 }
855 }
856}
857
858/// The NLSF codebook for one bandwidth (Section 4.2.7.5).
859pub(crate) struct NlsfCodebook {
860 pub(crate) n_vectors: usize,
861 pub(crate) order: usize,
862 pub(crate) quant_step_size_q16: i32,
863 pub(crate) cb1_q8: &'static [u8],
864 pub(crate) cb1_icdf: &'static [u8],
865 pub(crate) pred_q8: &'static [u8],
866 pub(crate) ec_sel: &'static [u8],
867 pub(crate) ec_icdf: &'static [u8],
868 pub(crate) delta_min_q15: &'static [i16],
869}
870
871pub(crate) fn nlsf_cb(wideband: bool) -> &'static NlsfCodebook {
872 static NB_MB: NlsfCodebook = NlsfCodebook {
873 n_vectors: 32,
874 order: 10,
875 // 0.18 in Q16.
876 quant_step_size_q16: 11796,
877 cb1_q8: &NLSF_CB1_NB_MB_Q8,
878 cb1_icdf: &NLSF_CB1_ICDF_NB_MB,
879 pred_q8: &NLSF_PRED_NB_MB_Q8,
880 ec_sel: &NLSF_CB2_SELECT_NB_MB,
881 ec_icdf: &NLSF_CB2_ICDF_NB_MB,
882 delta_min_q15: &NLSF_DELTA_MIN_NB_MB_Q15,
883 };
884 static WB: NlsfCodebook = NlsfCodebook {
885 n_vectors: 32,
886 order: 16,
887 quant_step_size_q16: 9830,
888 cb1_q8: &NLSF_CB1_WB_Q8,
889 cb1_icdf: &NLSF_CB1_ICDF_WB,
890 pred_q8: &NLSF_PRED_WB_Q8,
891 ec_sel: &NLSF_CB2_SELECT_WB,
892 ec_icdf: &NLSF_CB2_ICDF_WB,
893 delta_min_q15: &NLSF_DELTA_MIN_WB_Q15,
894 };
895 if wideband { &WB } else { &NB_MB }
896}
897
898/// `silk_NLSF_unpack`: per-coefficient entropy-table selectors and predictors.
899pub(crate) fn nlsf_unpack(cb: &NlsfCodebook, cb1_index: usize) -> ([i16; MAX_LPC_ORDER], [u8; MAX_LPC_ORDER]) {
900 let mut ec_ix = [0i16; MAX_LPC_ORDER];
901 let mut pred = [0u8; MAX_LPC_ORDER];
902 let sel = &cb.ec_sel[cb1_index * cb.order / 2..];
903 for i in (0..cb.order).step_by(2) {
904 let entry = sel[i / 2];
905 ec_ix[i] = (((entry >> 1) & 7) as i16) * (2 * NLSF_QUANT_MAX_AMPLITUDE as i16 + 1);
906 pred[i] = cb.pred_q8[i + (entry & 1) as usize * (cb.order - 1)];
907 ec_ix[i + 1] = (((entry >> 5) & 7) as i16) * (2 * NLSF_QUANT_MAX_AMPLITUDE as i16 + 1);
908 pred[i + 1] = cb.pred_q8[i + ((entry >> 4) & 1) as usize * (cb.order - 1) + 1];
909 }
910 (ec_ix, pred)
911}
912
913/// `silk_NLSF_decode`: indices to normalised LSFs (Section 4.2.7.5.3).
914pub(crate) fn nlsf_decode(indices: &[i8], cb: &NlsfCodebook) -> [i16; MAX_LPC_ORDER] {
915 let mut nlsf_q15 = [0i16; MAX_LPC_ORDER];
916 let base = indices[0] as usize * cb.order;
917 for i in 0..cb.order {
918 nlsf_q15[i] = (cb.cb1_q8[base + i] as i16) << 7;
919 }
920 let (_, pred_q8) = nlsf_unpack(cb, indices[0] as usize);
921 // Residual dequantisation, back to front so the prediction chains.
922 let mut res_q10 = [0i16; MAX_LPC_ORDER];
923 let mut out_q10 = 0i32;
924 for i in (0..cb.order).rev() {
925 let pred_q10 = smulbb(out_q10, pred_q8[i] as i32) >> 8;
926 out_q10 = (indices[i + 1] as i32) << 10;
927 if out_q10 > 0 {
928 out_q10 -= 102; // 0.1 in Q10
929 } else if out_q10 < 0 {
930 out_q10 += 102;
931 }
932 out_q10 = smlawb(pred_q10, out_q10, cb.quant_step_size_q16);
933 res_q10[i] = out_q10 as i16;
934 }
935 // Weight by the Laroia measure, add, then enforce the minimum spacing.
936 let w_qw = nlsf_vq_weights_laroia(&nlsf_q15[..cb.order]);
937 for i in 0..cb.order {
938 let w_q9 = sqrt_approx((w_qw[i] as i32) << 16);
939 let v = nlsf_q15[i] as i32 + (((res_q10[i] as i32) << 14) / w_q9);
940 nlsf_q15[i] = v.clamp(0, 32767) as i16;
941 }
942 nlsf_stabilize(&mut nlsf_q15[..cb.order], cb.delta_min_q15);
943 nlsf_q15
944}
945
946/// `silk_NLSF_VQ_weights_laroia` (Section 4.2.7.5.3).
947pub(crate) fn nlsf_vq_weights_laroia(nlsf_q15: &[i16]) -> [i16; MAX_LPC_ORDER] {
948 let d = nlsf_q15.len();
949 let mut w = [0i16; MAX_LPC_ORDER];
950 let inv = |x: i32| (1i32 << 17) / x.max(1);
951 let mut tmp1 = inv(nlsf_q15[0] as i32);
952 let mut tmp2 = inv(nlsf_q15[1] as i32 - nlsf_q15[0] as i32);
953 w[0] = (tmp1 + tmp2).min(32767) as i16;
954 let mut k = 1;
955 while k < d - 1 {
956 tmp1 = inv(nlsf_q15[k + 1] as i32 - nlsf_q15[k] as i32);
957 w[k] = (tmp1 + tmp2).min(32767) as i16;
958 tmp2 = inv(nlsf_q15[k + 2] as i32 - nlsf_q15[k + 1] as i32);
959 w[k + 1] = (tmp1 + tmp2).min(32767) as i16;
960 k += 2;
961 }
962 tmp1 = inv((1 << 15) - nlsf_q15[d - 1] as i32);
963 w[d - 1] = (tmp1 + tmp2).min(32767) as i16;
964 w
965}
966
967/// `silk_NLSF_stabilize` (Section 4.2.7.5.4): enforce the minimum spacing.
968pub(crate) fn nlsf_stabilize(nlsf_q15: &mut [i16], delta_min_q15: &[i16]) {
969 let l = nlsf_q15.len();
970 for _ in 0..20 {
971 let mut min_diff = nlsf_q15[0] as i32 - delta_min_q15[0] as i32;
972 let mut i_min = 0usize;
973 for i in 1..l {
974 let diff = nlsf_q15[i] as i32 - (nlsf_q15[i - 1] as i32 + delta_min_q15[i] as i32);
975 if diff < min_diff {
976 min_diff = diff;
977 i_min = i;
978 }
979 }
980 let diff = (1 << 15) - (nlsf_q15[l - 1] as i32 + delta_min_q15[l] as i32);
981 if diff < min_diff {
982 min_diff = diff;
983 i_min = l;
984 }
985 if min_diff >= 0 {
986 return;
987 }
988 if i_min == 0 {
989 nlsf_q15[0] = delta_min_q15[0];
990 } else if i_min == l {
991 nlsf_q15[l - 1] = ((1 << 15) - delta_min_q15[l] as i32) as i16;
992 } else {
993 let mut min_center = 0i32;
994 for k in 0..i_min {
995 min_center += delta_min_q15[k] as i32;
996 }
997 min_center += delta_min_q15[i_min] as i32 >> 1;
998 let mut max_center = 1i32 << 15;
999 for k in (i_min + 1..=l).rev() {
1000 max_center -= delta_min_q15[k] as i32;
1001 }
1002 max_center -= delta_min_q15[i_min] as i32 >> 1;
1003 let center = rshift_round(nlsf_q15[i_min - 1] as i32 + nlsf_q15[i_min] as i32, 1)
1004 .clamp(min_center, max_center);
1005 nlsf_q15[i_min - 1] = (center - (delta_min_q15[i_min] as i32 >> 1)) as i16;
1006 nlsf_q15[i_min] = nlsf_q15[i_min - 1] + delta_min_q15[i_min];
1007 }
1008 }
1009 // Last resort: sort and clamp (the reference's fallback after 20 loops).
1010 nlsf_q15.sort_unstable();
1011 nlsf_q15[0] = nlsf_q15[0].max(delta_min_q15[0]);
1012 for i in 1..l {
1013 nlsf_q15[i] = nlsf_q15[i].max(nlsf_q15[i - 1].saturating_add(delta_min_q15[i]));
1014 }
1015 nlsf_q15[l - 1] = nlsf_q15[l - 1].min(((1 << 15) - delta_min_q15[l] as i32) as i16);
1016 for i in (0..l - 1).rev() {
1017 nlsf_q15[i] = nlsf_q15[i].min(nlsf_q15[i + 1] - delta_min_q15[i + 1]);
1018 }
1019}
1020
1021/// `silk_NLSF2A` (Section 4.2.7.5.6): LSFs to LPC coefficients.
1022pub(crate) fn nlsf2a(nlsf: &[i16], order: usize) -> [i16; MAX_LPC_ORDER] {
1023 const QA: u32 = 16;
1024 const ORDER16: [usize; 16] = [0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1];
1025 const ORDER10: [usize; 10] = [0, 9, 6, 3, 4, 5, 8, 1, 2, 7];
1026 let ordering: &[usize] = if order == 16 { &ORDER16 } else { &ORDER10 };
1027
1028 let mut cos_lsf_qa = [0i32; MAX_LPC_ORDER];
1029 for k in 0..order {
1030 let f_int = (nlsf[k] >> 8) as usize;
1031 let f_frac = nlsf[k] as i32 - ((f_int as i32) << 8);
1032 let cos_val = LSFCOSTAB_FIX_Q12[f_int] as i32;
1033 let delta = LSFCOSTAB_FIX_Q12[f_int + 1] as i32 - cos_val;
1034 cos_lsf_qa[ordering[k]] = rshift_round((cos_val << 8) + delta * f_frac, 20 - QA);
1035 }
1036 let dd = order / 2;
1037 let p = nlsf2a_find_poly(&cos_lsf_qa, dd, 0);
1038 let q = nlsf2a_find_poly(&cos_lsf_qa, dd, 1);
1039
1040 let mut a32_qa1 = [0i32; MAX_LPC_ORDER];
1041 for k in 0..dd {
1042 let ptmp = p[k + 1] + p[k];
1043 let qtmp = q[k + 1] - q[k];
1044 a32_qa1[k] = -qtmp - ptmp;
1045 a32_qa1[order - k - 1] = qtmp - ptmp;
1046 }
1047
1048 // Clamp into Q12 without letting the filter blow up.
1049 let mut a_q12 = [0i16; MAX_LPC_ORDER];
1050 let mut i = 0;
1051 while i < 10 {
1052 let mut maxabs = 0i32;
1053 let mut idx = 0usize;
1054 for k in 0..order {
1055 let absval = a32_qa1[k].abs();
1056 if absval > maxabs {
1057 maxabs = absval;
1058 idx = k;
1059 }
1060 }
1061 let maxabs_q12 = rshift_round(maxabs, QA + 1 - 12);
1062 if maxabs_q12 > 32767 {
1063 let maxabs_q12 = maxabs_q12.min(163838);
1064 let sc_q16 =
1065 65471 - ((maxabs_q12 - 32767) << 14) / ((maxabs_q12 * (idx as i32 + 1)) >> 2);
1066 bwexpander_32(&mut a32_qa1[..order], sc_q16);
1067 } else {
1068 break;
1069 }
1070 i += 1;
1071 }
1072 if i == 10 {
1073 for k in 0..order {
1074 a_q12[k] = sat16(rshift_round(a32_qa1[k], QA + 1 - 12));
1075 a32_qa1[k] = (a_q12[k] as i32) << (QA + 1 - 12);
1076 }
1077 } else {
1078 for k in 0..order {
1079 a_q12[k] = rshift_round(a32_qa1[k], QA + 1 - 12) as i16;
1080 }
1081 }
1082 // Bandwidth expansion until the prediction gain is sane.
1083 for i in 0..MAX_LPC_STABILIZE_ITERATIONS {
1084 if lpc_inverse_pred_gain(&a_q12[..order]) < 107374 {
1085 bwexpander_32(&mut a32_qa1[..order], 65536 - (2 << i));
1086 for k in 0..order {
1087 a_q12[k] = rshift_round(a32_qa1[k], QA + 1 - 12) as i16;
1088 }
1089 } else {
1090 break;
1091 }
1092 }
1093 a_q12
1094}
1095
1096fn nlsf2a_find_poly(cos_lsf_qa: &[i32], dd: usize, offset: usize) -> [i32; MAX_LPC_ORDER / 2 + 1] {
1097 const QA: u32 = 16;
1098 let mut out = [0i32; MAX_LPC_ORDER / 2 + 1];
1099 out[0] = 1 << QA;
1100 out[1] = -cos_lsf_qa[offset];
1101 for k in 1..dd {
1102 let ftmp = cos_lsf_qa[2 * k + offset];
1103 out[k + 1] = (out[k - 1] << 1) - rshift_round64(ftmp as i64 * out[k] as i64, QA) as i32;
1104 for n in (2..=k).rev() {
1105 out[n] += out[n - 2] - rshift_round64(ftmp as i64 * out[n - 1] as i64, QA) as i32;
1106 }
1107 out[1] -= ftmp;
1108 }
1109 out
1110}
1111
1112fn bwexpander_32(ar: &mut [i32], chirp_q16: i32) {
1113 let mut chirp = chirp_q16;
1114 let chirp_minus_one = chirp_q16 - 65536;
1115 let d = ar.len();
1116 for coef in ar.iter_mut().take(d - 1) {
1117 *coef = smulww(chirp, *coef);
1118 chirp += rshift_round(chirp.wrapping_mul(chirp_minus_one), 16);
1119 }
1120 ar[d - 1] = smulww(chirp, ar[d - 1]);
1121}
1122
1123/// `silk_LPC_inverse_pred_gain` (Section 4.2.7.5.8), in Q30.
1124fn lpc_inverse_pred_gain(a_q12: &[i16]) -> i32 {
1125 const QA: u32 = 24;
1126 const A_LIMIT: i32 = 16773022; // 0.99975 in Q24
1127 let order = a_q12.len();
1128 let mut a = [[0i32; MAX_LPC_ORDER]; 2];
1129 let mut dc_resp = 0i32;
1130 for k in 0..order {
1131 dc_resp += a_q12[k] as i32;
1132 a[order & 1][k] = (a_q12[k] as i32) << (QA - 12);
1133 }
1134 if dc_resp >= 4096 {
1135 return 0;
1136 }
1137 let mut cur = order & 1;
1138 let mut inv_gain_q30 = 1i32 << 30;
1139 for k in (1..order).rev() {
1140 if a[cur][k] > A_LIMIT || a[cur][k] < -A_LIMIT {
1141 return 0;
1142 }
1143 let rc_q31 = -(a[cur][k] << (31 - QA));
1144 let rc_mult1_q30 = (1i32 << 30) - smmul(rc_q31, rc_q31);
1145 let mult2q = 32 - clz32(rc_mult1_q30.abs());
1146 let rc_mult2 = inverse32_var_q(rc_mult1_q30, (mult2q + 30) as u32);
1147 inv_gain_q30 = smmul(inv_gain_q30, rc_mult1_q30) << 2;
1148 let old = cur;
1149 cur = k & 1;
1150 for n in 0..k {
1151 let tmp = a[old][n] - mul32_frac_q(a[old][k - n - 1], rc_q31, 31);
1152 a[cur][n] = mul32_frac_q(tmp, rc_mult2, mult2q as u32);
1153 }
1154 }
1155 if a[cur][0] > A_LIMIT || a[cur][0] < -A_LIMIT {
1156 return 0;
1157 }
1158 let rc_q31 = -(a[cur][0] << (31 - QA));
1159 let rc_mult1_q30 = (1i32 << 30) - smmul(rc_q31, rc_q31);
1160 smmul(inv_gain_q30, rc_mult1_q30) << 2
1161}
1162
1163#[inline]
1164fn mul32_frac_q(a: i32, b: i32, q: u32) -> i32 {
1165 rshift_round64(a as i64 * b as i64, q) as i32
1166}
1167
1168/// `silk_gains_dequant` (Section 4.2.7.4).
1169pub(crate) fn gains_dequant(
1170 indices: &[i8],
1171 prev_ind: &mut i32,
1172 conditional: bool,
1173 nb_subfr: usize,
1174) -> [i32; MAX_NB_SUBFR] {
1175 let mut gains = [0i32; MAX_NB_SUBFR];
1176 for k in 0..nb_subfr {
1177 if k == 0 && !conditional {
1178 // A gain may not drop more than 16 steps below the last one.
1179 *prev_ind = (indices[k] as i32).max(*prev_ind - 16);
1180 } else {
1181 let ind_tmp = indices[k] as i32 + MIN_DELTA_GAIN_QUANT;
1182 let threshold = 2 * MAX_DELTA_GAIN_QUANT - N_LEVELS_QGAIN + *prev_ind;
1183 if ind_tmp > threshold {
1184 *prev_ind += (ind_tmp << 1) - threshold;
1185 } else {
1186 *prev_ind += ind_tmp;
1187 }
1188 }
1189 *prev_ind = (*prev_ind).clamp(0, N_LEVELS_QGAIN - 1);
1190 gains[k] = log2lin((smulwb(GAIN_INV_SCALE_Q16, *prev_ind) + GAIN_OFFSET).min(3967));
1191 }
1192 gains
1193}
1194
1195/// `silk_decode_pitch` (Section 4.2.7.6.1).
1196pub(crate) fn decode_pitch(
1197 lag_index: i32,
1198 contour_index: i32,
1199 fs_khz: i32,
1200 nb_subfr: usize,
1201) -> [i32; MAX_NB_SUBFR] {
1202 let mut pitch = [0i32; MAX_NB_SUBFR];
1203 let min_lag = PE_MIN_LAG_MS * fs_khz;
1204 let max_lag = PE_MAX_LAG_MS * fs_khz;
1205 let lag = min_lag + lag_index;
1206 for k in 0..nb_subfr {
1207 let offset = if fs_khz == 8 {
1208 if nb_subfr == 4 {
1209 CB_LAGS_STAGE2[k][contour_index as usize]
1210 } else {
1211 CB_LAGS_STAGE2_10_MS[k][contour_index as usize]
1212 }
1213 } else if nb_subfr == 4 {
1214 CB_LAGS_STAGE3[k][contour_index as usize]
1215 } else {
1216 CB_LAGS_STAGE3_10_MS[k][contour_index as usize]
1217 };
1218 pitch[k] = (lag + offset as i32).clamp(min_lag, max_lag);
1219 }
1220 pitch
1221}
1222
1223/// `silk_decode_parameters`.
1224fn decode_parameters(ch: &mut ChannelState, cond: CondCoding) -> FrameCtrl {
1225 let mut ctrl = FrameCtrl {
1226 gains_q16: gains_dequant(
1227 &ch.indices.gains,
1228 &mut ch.last_gain_index,
1229 cond == CondCoding::Conditionally,
1230 ch.nb_subfr,
1231 ),
1232 ..Default::default()
1233 };
1234 let cb = nlsf_cb(ch.wb_codebook);
1235 let nlsf_q15 = nlsf_decode(&ch.indices.nlsf, cb);
1236 ctrl.pred_coef_q12[1] = nlsf2a(&nlsf_q15[..ch.lpc_order], ch.lpc_order);
1237
1238 if ch.first_frame_after_reset {
1239 ch.indices.nlsf_interp_coef_q2 = 4;
1240 }
1241 if ch.indices.nlsf_interp_coef_q2 < 4 {
1242 // Interpolate the first half of the frame from the previous LSFs.
1243 let mut nlsf0 = [0i16; MAX_LPC_ORDER];
1244 for i in 0..ch.lpc_order {
1245 nlsf0[i] = (ch.prev_nlsf_q15[i] as i32
1246 + ((ch.indices.nlsf_interp_coef_q2
1247 * (nlsf_q15[i] as i32 - ch.prev_nlsf_q15[i] as i32))
1248 >> 2)) as i16;
1249 }
1250 ctrl.pred_coef_q12[0] = nlsf2a(&nlsf0[..ch.lpc_order], ch.lpc_order);
1251 } else {
1252 ctrl.pred_coef_q12[0] = ctrl.pred_coef_q12[1];
1253 }
1254 ch.prev_nlsf_q15[..ch.lpc_order].copy_from_slice(&nlsf_q15[..ch.lpc_order]);
1255
1256 if ch.indices.signal_type == TYPE_VOICED {
1257 ctrl.pitch_l = decode_pitch(
1258 ch.indices.lag_index,
1259 ch.indices.contour_index,
1260 ch.fs_khz as i32,
1261 ch.nb_subfr,
1262 );
1263 let cbk: &[[i8; 5]] = match ch.indices.per_index {
1264 0 => &LTP_GAIN_VQ_0,
1265 1 => &LTP_GAIN_VQ_1,
1266 _ => &LTP_GAIN_VQ_2,
1267 };
1268 for k in 0..ch.nb_subfr {
1269 let v = &cbk[ch.indices.ltp_index[k]];
1270 for i in 0..LTP_ORDER {
1271 ctrl.ltp_coef_q14[k * LTP_ORDER + i] = (v[i] as i16) << 7;
1272 }
1273 }
1274 ctrl.ltp_scale_q14 = LTPSCALES_TABLE_Q14[ch.indices.ltp_scale_index] as i32;
1275 }
1276 ctrl
1277}
1278
1279/// `silk_LPC_analysis_filter`: the whitening filter used to rebuild the LTP
1280/// state from previously decoded output.
1281fn lpc_analysis_filter(out: &mut [i16], input: &[i16], b_q12: &[i16], len: usize, d: usize) {
1282 for ix in d..len {
1283 let mut acc = 0i32;
1284 for j in 0..d {
1285 acc = acc.wrapping_add(smulbb(input[ix - 1 - j] as i32, b_q12[j] as i32));
1286 }
1287 let v = ((input[ix] as i32) << 12).wrapping_sub(acc);
1288 out[ix] = sat16(rshift_round(v, 12));
1289 }
1290 out[..d].fill(0);
1291}
1292
1293/// `silk_decode_core` (Section 4.2.7.9): excitation to output samples.
1294fn decode_core(ch: &mut ChannelState, ctrl: &FrameCtrl, xq: &mut [i16], pulses: &[i32]) {
1295 let offset_q10 = QUANTIZATION_OFFSETS_Q10[ch.indices.signal_type as usize >> 1]
1296 [ch.indices.quant_offset_type as usize] as i32;
1297 let nlsf_interpolated = ch.indices.nlsf_interp_coef_q2 < 4;
1298
1299 // Excitation: pulses with a quantisation offset and a pseudo-random sign.
1300 let mut rand_seed = ch.indices.seed;
1301 for i in 0..ch.frame_length {
1302 rand_seed = silk_rand(rand_seed);
1303 let mut e = pulses[i] << 14;
1304 if e > 0 {
1305 e -= QUANT_LEVEL_ADJUST_Q10 << 4;
1306 } else if e < 0 {
1307 e += QUANT_LEVEL_ADJUST_Q10 << 4;
1308 }
1309 e += offset_q10 << 4;
1310 ch.exc_q14[i] = if rand_seed < 0 { -e } else { e };
1311 rand_seed = rand_seed.wrapping_add(pulses[i]);
1312 }
1313
1314 let mut s_lpc_q14 = [0i32; MAX_LPC_ORDER + 5 * 16];
1315 s_lpc_q14[..MAX_LPC_ORDER].copy_from_slice(&ch.s_lpc_q14);
1316 let mut s_ltp = [0i16; MAX_FRAME_LENGTH];
1317 let mut s_ltp_q15 = [0i32; 2 * MAX_FRAME_LENGTH];
1318 let mut sltp_buf_idx = ch.ltp_mem_length;
1319 let mut lag = 0usize;
1320 let mut res_q14 = [0i32; 5 * 16];
1321
1322 for k in 0..ch.nb_subfr {
1323 let a_q12 = &ctrl.pred_coef_q12[k >> 1];
1324 let b_q14 = &ctrl.ltp_coef_q14[k * LTP_ORDER..k * LTP_ORDER + LTP_ORDER];
1325 let gain_q10 = ctrl.gains_q16[k] >> 6;
1326 let mut inv_gain_q31 = inverse32_var_q(ctrl.gains_q16[k], 47);
1327 let gain_adj_q16 = if ctrl.gains_q16[k] != ch.prev_gain_q16 {
1328 let adj = div32_var_q(ch.prev_gain_q16, ctrl.gains_q16[k], 16);
1329 for v in s_lpc_q14.iter_mut().take(MAX_LPC_ORDER) {
1330 *v = smulww(adj, *v);
1331 }
1332 adj
1333 } else {
1334 1 << 16
1335 };
1336 ch.prev_gain_q16 = ctrl.gains_q16[k];
1337
1338 if ch.indices.signal_type == TYPE_VOICED {
1339 lag = ctrl.pitch_l[k] as usize;
1340 if k == 0 || (k == 2 && nlsf_interpolated) {
1341 // Rebuild the LTP history by whitening past output.
1342 let start_idx = ch.ltp_mem_length - lag - ch.lpc_order - LTP_ORDER / 2;
1343 if k == 2 {
1344 let n = 2 * ch.subfr_length;
1345 let base = ch.ltp_mem_length;
1346 ch.out_buf[base..base + n].copy_from_slice(&xq[..n]);
1347 }
1348 lpc_analysis_filter(
1349 &mut s_ltp[start_idx..],
1350 &ch.out_buf[start_idx + k * ch.subfr_length..],
1351 a_q12,
1352 ch.ltp_mem_length - start_idx,
1353 ch.lpc_order,
1354 );
1355 if k == 0 {
1356 inv_gain_q31 = smulwb(inv_gain_q31, ctrl.ltp_scale_q14) << 2;
1357 }
1358 for i in 0..lag + LTP_ORDER / 2 {
1359 s_ltp_q15[sltp_buf_idx - i - 1] =
1360 smulwb(inv_gain_q31, s_ltp[ch.ltp_mem_length - i - 1] as i32);
1361 }
1362 } else if gain_adj_q16 != 1 << 16 {
1363 for i in 0..lag + LTP_ORDER / 2 {
1364 s_ltp_q15[sltp_buf_idx - i - 1] =
1365 smulww(gain_adj_q16, s_ltp_q15[sltp_buf_idx - i - 1]);
1366 }
1367 }
1368 }
1369
1370 // Long-term prediction.
1371 let exc_base = k * ch.subfr_length;
1372 let pres_q14: &[i32] = if ch.indices.signal_type == TYPE_VOICED {
1373 let pred_base = sltp_buf_idx - lag + LTP_ORDER / 2;
1374 for i in 0..ch.subfr_length {
1375 let pred_idx = pred_base + i;
1376 let mut ltp_pred_q13 = 2i32;
1377 for (j, &b) in b_q14.iter().enumerate() {
1378 ltp_pred_q13 = smlawb(ltp_pred_q13, s_ltp_q15[pred_idx - j], b as i32);
1379 }
1380 res_q14[i] = ch.exc_q14[exc_base + i].wrapping_add(ltp_pred_q13 << 1);
1381 s_ltp_q15[sltp_buf_idx] = res_q14[i] << 1;
1382 sltp_buf_idx += 1;
1383 }
1384 &res_q14[..ch.subfr_length]
1385 } else {
1386 &ch.exc_q14[exc_base..exc_base + ch.subfr_length]
1387 };
1388
1389 // Short-term (LPC) synthesis.
1390 for i in 0..ch.subfr_length {
1391 let mut lpc_pred_q10 = (ch.lpc_order >> 1) as i32;
1392 for j in 0..ch.lpc_order {
1393 lpc_pred_q10 = smlawb(
1394 lpc_pred_q10,
1395 s_lpc_q14[MAX_LPC_ORDER + i - 1 - j],
1396 a_q12[j] as i32,
1397 );
1398 }
1399 s_lpc_q14[MAX_LPC_ORDER + i] = pres_q14[i].wrapping_add(lpc_pred_q10 << 4);
1400 xq[k * ch.subfr_length + i] = sat16(rshift_round(
1401 smulww(s_lpc_q14[MAX_LPC_ORDER + i], gain_q10),
1402 8,
1403 ));
1404 }
1405 s_lpc_q14.copy_within(ch.subfr_length..ch.subfr_length + MAX_LPC_ORDER, 0);
1406 }
1407 ch.s_lpc_q14.copy_from_slice(&s_lpc_q14[..MAX_LPC_ORDER]);
1408}
1409
1410/// `silk_decode_frame`: one SILK frame of one channel.
1411fn decode_frame(
1412 ch: &mut ChannelState,
1413 dec: &mut RangeDecoder,
1414 out: &mut [i16],
1415 cond: CondCoding,
1416) -> usize {
1417 let frame_index = ch.frames_decoded;
1418 decode_indices(ch, dec, frame_index, false, cond);
1419 let mut pulses = [0i32; MAX_FRAME_LENGTH + SHELL_LEN];
1420 decode_pulses(
1421 dec,
1422 &mut pulses,
1423 ch.frame_length,
1424 ch.indices.signal_type,
1425 ch.indices.quant_offset_type,
1426 );
1427 let mut ctrl = decode_parameters(ch, cond);
1428 if cond == CondCoding::IndependentlyNoLtpScaling {
1429 ctrl.ltp_scale_q14 = LTPSCALES_TABLE_Q14[0] as i32;
1430 }
1431 decode_core(ch, &ctrl, out, &pulses);
1432 ch.prev_signal_type = ch.indices.signal_type;
1433 ch.first_frame_after_reset = false;
1434 ch.lag_prev = ctrl.pitch_l[ch.nb_subfr - 1];
1435
1436 // Slide the synthesis history.
1437 let mv_len = ch.ltp_mem_length - ch.frame_length;
1438 ch.out_buf
1439 .copy_within(ch.frame_length..ch.frame_length + mv_len, 0);
1440 ch.out_buf[mv_len..mv_len + ch.frame_length].copy_from_slice(&out[..ch.frame_length]);
1441 ch.frame_length
1442}
1443
1444/// `silk_stereo_decode_pred` (Section 4.2.7.1).
1445fn stereo_decode_pred(dec: &mut RangeDecoder, pred_q13: &mut [i32; 2]) {
1446 let n = dec.dec_icdf(&STEREO_PRED_JOINT_ICDF, 8) as i32;
1447 let mut ix = [[0i32; 3]; 2];
1448 ix[0][2] = n / 5;
1449 ix[1][2] = n - 5 * ix[0][2];
1450 for row in ix.iter_mut() {
1451 row[0] = dec.dec_icdf(&UNIFORM3_ICDF, 8) as i32;
1452 row[1] = dec.dec_icdf(&UNIFORM5_ICDF, 8) as i32;
1453 }
1454 for n in 0..2 {
1455 let i0 = (ix[n][0] + 3 * ix[n][2]) as usize;
1456 let low = STEREO_PRED_QUANT_Q13[i0] as i32;
1457 // 0.5/5 in Q16.
1458 let step = smulwb(STEREO_PRED_QUANT_Q13[i0 + 1] as i32 - low, 6554);
1459 pred_q13[n] = smlabb(low, step, 2 * ix[n][1] + 1);
1460 }
1461 pred_q13[0] -= pred_q13[1];
1462}
1463
1464/// `silk_stereo_MS_to_LR` (Section 4.2.8): mid/side back to left/right.
1465fn stereo_ms_to_lr(
1466 state: &mut StereoState,
1467 x1: &mut [i16],
1468 x2: &mut [i16],
1469 pred_q13: &[i32; 2],
1470 fs_khz: usize,
1471 frame_length: usize,
1472) {
1473 x1[0] = state.s_mid[0];
1474 x1[1] = state.s_mid[1];
1475 x2[0] = state.s_side[0];
1476 x2[1] = state.s_side[1];
1477 state.s_mid[0] = x1[frame_length];
1478 state.s_mid[1] = x1[frame_length + 1];
1479 state.s_side[0] = x2[frame_length];
1480 state.s_side[1] = x2[frame_length + 1];
1481
1482 let interp = STEREO_INTERP_LEN_MS * fs_khz;
1483 let mut pred0 = state.pred_prev_q13[0];
1484 let mut pred1 = state.pred_prev_q13[1];
1485 let denom_q16 = (1i32 << 16) / interp as i32;
1486 let delta0 = rshift_round(smulbb(pred_q13[0] - state.pred_prev_q13[0], denom_q16), 16);
1487 let delta1 = rshift_round(smulbb(pred_q13[1] - state.pred_prev_q13[1], denom_q16), 16);
1488 for n in 0..frame_length {
1489 if n < interp {
1490 pred0 += delta0;
1491 pred1 += delta1;
1492 } else {
1493 pred0 = pred_q13[0];
1494 pred1 = pred_q13[1];
1495 }
1496 let sum = ((x1[n] as i32 + x1[n + 2] as i32) + ((x1[n + 1] as i32) << 1)) << 9;
1497 let mut acc = smlawb((x2[n + 1] as i32) << 8, sum, pred0);
1498 acc = smlawb(acc, (x1[n + 1] as i32) << 11, pred1);
1499 x2[n + 1] = sat16(rshift_round(acc, 8));
1500 }
1501 state.pred_prev_q13[0] = pred_q13[0];
1502 state.pred_prev_q13[1] = pred_q13[1];
1503
1504 for n in 0..frame_length {
1505 let sum = x1[n + 1] as i32 + x2[n + 1] as i32;
1506 let diff = x1[n + 1] as i32 - x2[n + 1] as i32;
1507 x1[n + 1] = sat16(sum);
1508 x2[n + 1] = sat16(diff);
1509 }
1510}
1511
1512// ---------------------------------------------------------------------------
1513// Resampling (Section 4.2.9)
1514// ---------------------------------------------------------------------------
1515
1516/// The SILK output resampler: 8/12/16 kHz internal to the API rate.
1517///
1518/// The RFC calls the resampler non-normative but its *delay* normative, so this
1519/// is the reference's structure — a 2x all-pass upsampler followed by a
1520/// 12-phase fractional FIR, with the same per-rate input delay.
1521#[derive(Clone, Debug, Default)]
1522struct Resampler {
1523 fs_in_khz: usize,
1524 fs_out_khz: usize,
1525 input_delay: usize,
1526 batch_size: usize,
1527 inv_ratio_q16: i32,
1528 /// All-pass state for the 2x upsampler.
1529 s_iir: [i32; 6],
1530 /// FIR history.
1531 s_fir: [i16; 8],
1532 delay_buf: DelayBuf,
1533 /// Upsampler scratch, allocated once.
1534 fir_buf: Vec<i16>,
1535 /// Down-sampling coefficients, when the output rate is the lower one.
1536 down: Option<DownFir>,
1537}
1538
1539/// Fixed-size delay line; a newtype only because `[i16; 48]` has no `Default`.
1540#[derive(Clone, Copy, Debug)]
1541struct DelayBuf([i16; 48]);
1542
1543impl Default for DelayBuf {
1544 fn default() -> Self {
1545 DelayBuf([0; 48])
1546 }
1547}
1548
1549impl core::ops::Deref for DelayBuf {
1550 type Target = [i16; 48];
1551 fn deref(&self) -> &[i16; 48] {
1552 &self.0
1553 }
1554}
1555
1556impl core::ops::DerefMut for DelayBuf {
1557 fn deref_mut(&mut self) -> &mut [i16; 48] {
1558 &mut self.0
1559 }
1560}
1561
1562#[derive(Clone, Debug)]
1563struct DownFir {
1564 fracs: usize,
1565 order: usize,
1566 coefs: &'static [i16],
1567 state: [i32; 2],
1568 buf: Vec<i32>,
1569}
1570
1571/// `rateID` in the reference: an index into the delay matrix.
1572fn rate_id(rate: usize) -> usize {
1573 (((rate >> 12) - usize::from(rate > 16000)) >> usize::from(rate > 24000)) - 1
1574}
1575
1576const DELAY_MATRIX_DEC: [[u8; 5]; 3] = [[4, 0, 2, 0, 0], [0, 9, 4, 7, 4], [0, 3, 12, 7, 7]];
1577
1578impl Resampler {
1579 fn new(fs_in_khz: usize, fs_out_khz: usize) -> Resampler {
1580 let fs_in = fs_in_khz * 1000;
1581 let fs_out = fs_out_khz * 1000;
1582 let mut r = Resampler {
1583 fs_in_khz,
1584 fs_out_khz,
1585 input_delay: DELAY_MATRIX_DEC[rate_id(fs_in)][rate_id(fs_out)] as usize,
1586 batch_size: fs_in_khz * 10,
1587 ..Default::default()
1588 };
1589 let mut up2x = 0;
1590 if fs_out > fs_in && fs_out != 2 * fs_in {
1591 up2x = 1;
1592 } else if fs_out < fs_in {
1593 let (fracs, order, coefs): (usize, usize, &'static [i16]) = if fs_out * 4 == fs_in * 3 {
1594 (3, 18, &RESAMPLER_3_4_COEFS)
1595 } else if fs_out * 3 == fs_in * 2 {
1596 (2, 18, &RESAMPLER_2_3_COEFS)
1597 } else if fs_out * 2 == fs_in {
1598 (1, 24, &RESAMPLER_1_2_COEFS)
1599 } else if fs_out * 3 == fs_in {
1600 (1, 36, &RESAMPLER_1_3_COEFS)
1601 } else if fs_out * 4 == fs_in {
1602 (1, 36, &RESAMPLER_1_4_COEFS)
1603 } else {
1604 (1, 36, &RESAMPLER_1_6_COEFS)
1605 };
1606 r.down = Some(DownFir {
1607 fracs,
1608 order,
1609 coefs,
1610 state: [0; 2],
1611 buf: vec![0; 480 + 36],
1612 });
1613 }
1614 r.inv_ratio_q16 = ((((fs_in as i64) << (14 + up2x)) / fs_out as i64) as i32) << 2;
1615 while smulww(r.inv_ratio_q16, fs_out as i32) < ((fs_in as i32) << up2x) {
1616 r.inv_ratio_q16 += 1;
1617 }
1618 r
1619 }
1620
1621 /// Resamples `in_len` input samples into `in_len * out/in` outputs.
1622 ///
1623 /// The first `Fs_in_kHz` samples come from the delay line (the normative
1624 /// per-rate input delay); the rest are read straight from `input`, and its
1625 /// tail is kept for the next call.
1626 fn process(&mut self, out: &mut [i16], input: &[i16], in_len: usize) {
1627 let n_first = self.fs_in_khz - self.input_delay;
1628 let mut head = [0i16; 48];
1629 head[..self.input_delay].copy_from_slice(&self.delay_buf[..self.input_delay]);
1630 head[self.input_delay..self.fs_in_khz].copy_from_slice(&input[..n_first]);
1631 let n_head = self.fs_in_khz;
1632 let rest = &input[n_first..n_first + (in_len - self.fs_in_khz)];
1633 let split = self.fs_out_khz;
1634 let rest_out = (in_len - self.fs_in_khz) * self.fs_out_khz / self.fs_in_khz;
1635 if self.fs_in_khz == self.fs_out_khz {
1636 out[..n_head].copy_from_slice(&head[..n_head]);
1637 out[split..split + rest_out].copy_from_slice(rest);
1638 } else if self.down.is_some() {
1639 self.down_fir(&mut out[..split], &head[..n_head]);
1640 self.down_fir(&mut out[split..split + rest_out], rest);
1641 } else if self.fs_out_khz == 2 * self.fs_in_khz {
1642 self.up2_hq(&mut out[..split], &head[..n_head]);
1643 self.up2_hq(&mut out[split..split + rest_out], rest);
1644 } else {
1645 self.iir_fir(&mut out[..split], &head[..n_head]);
1646 self.iir_fir(&mut out[split..split + rest_out], rest);
1647 }
1648 self.delay_buf[..self.input_delay]
1649 .copy_from_slice(&input[in_len - self.input_delay..in_len]);
1650 }
1651
1652 /// `silk_resampler_private_up2_HQ`: 2x all-pass upsampling.
1653 fn up2_hq(&mut self, out: &mut [i16], input: &[i16]) {
1654 for (k, &sample) in input.iter().enumerate() {
1655 let in32 = (sample as i32) << 10;
1656 let mut y = in32 - self.s_iir[0];
1657 let mut x = smulwb(y, RESAMPLER_UP2_HQ_0[0] as i32);
1658 let mut out32_1 = self.s_iir[0] + x;
1659 self.s_iir[0] = in32 + x;
1660 y = out32_1 - self.s_iir[1];
1661 x = smulwb(y, RESAMPLER_UP2_HQ_0[1] as i32);
1662 let mut out32_2 = self.s_iir[1] + x;
1663 self.s_iir[1] = out32_1 + x;
1664 y = out32_2 - self.s_iir[2];
1665 x = smlawb(y, y, RESAMPLER_UP2_HQ_0[2] as i32);
1666 out32_1 = self.s_iir[2] + x;
1667 self.s_iir[2] = out32_2 + x;
1668 out[2 * k] = sat16(rshift_round(out32_1, 10));
1669
1670 y = in32 - self.s_iir[3];
1671 x = smulwb(y, RESAMPLER_UP2_HQ_1[0] as i32);
1672 out32_1 = self.s_iir[3] + x;
1673 self.s_iir[3] = in32 + x;
1674 y = out32_1 - self.s_iir[4];
1675 x = smulwb(y, RESAMPLER_UP2_HQ_1[1] as i32);
1676 out32_2 = self.s_iir[4] + x;
1677 self.s_iir[4] = out32_1 + x;
1678 y = out32_2 - self.s_iir[5];
1679 x = smlawb(y, y, RESAMPLER_UP2_HQ_1[2] as i32);
1680 out32_1 = self.s_iir[5] + x;
1681 self.s_iir[5] = out32_2 + x;
1682 out[2 * k + 1] = sat16(rshift_round(out32_1, 10));
1683 }
1684 }
1685
1686 /// `silk_resampler_private_IIR_FIR`: 2x upsample then fractional FIR.
1687 fn iir_fir(&mut self, out: &mut [i16], input: &[i16]) {
1688 let mut written = 0usize;
1689 let mut pos = 0usize;
1690 let mut buf = core::mem::take(&mut self.fir_buf);
1691 buf.clear();
1692 buf.resize(2 * self.batch_size + 8, 0);
1693 buf[..8].copy_from_slice(&self.s_fir);
1694 let mut n_samples_in = 0;
1695 while pos < input.len() {
1696 n_samples_in = (input.len() - pos).min(self.batch_size);
1697 self.up2_hq(
1698 &mut buf[8..8 + 2 * n_samples_in],
1699 &input[pos..pos + n_samples_in],
1700 );
1701 let max_index_q16 = (n_samples_in as i32) << 17;
1702 let mut index_q16 = 0i32;
1703 while index_q16 < max_index_q16 {
1704 let table_index = smulwb(index_q16 & 0xFFFF, 12) as usize;
1705 let b = &buf[(index_q16 >> 16) as usize..];
1706 let mut res = smulbb(b[0] as i32, RESAMPLER_FRAC_FIR_12[table_index][0] as i32);
1707 res = smlabb(
1708 res,
1709 b[1] as i32,
1710 RESAMPLER_FRAC_FIR_12[table_index][1] as i32,
1711 );
1712 res = smlabb(
1713 res,
1714 b[2] as i32,
1715 RESAMPLER_FRAC_FIR_12[table_index][2] as i32,
1716 );
1717 res = smlabb(
1718 res,
1719 b[3] as i32,
1720 RESAMPLER_FRAC_FIR_12[table_index][3] as i32,
1721 );
1722 res = smlabb(
1723 res,
1724 b[4] as i32,
1725 RESAMPLER_FRAC_FIR_12[11 - table_index][3] as i32,
1726 );
1727 res = smlabb(
1728 res,
1729 b[5] as i32,
1730 RESAMPLER_FRAC_FIR_12[11 - table_index][2] as i32,
1731 );
1732 res = smlabb(
1733 res,
1734 b[6] as i32,
1735 RESAMPLER_FRAC_FIR_12[11 - table_index][1] as i32,
1736 );
1737 res = smlabb(
1738 res,
1739 b[7] as i32,
1740 RESAMPLER_FRAC_FIR_12[11 - table_index][0] as i32,
1741 );
1742 if written < out.len() {
1743 out[written] = sat16(rshift_round(res, 15));
1744 }
1745 written += 1;
1746 index_q16 += self.inv_ratio_q16;
1747 }
1748 pos += n_samples_in;
1749 if pos < input.len() {
1750 buf.copy_within(2 * n_samples_in..2 * n_samples_in + 8, 0);
1751 }
1752 }
1753 self.s_fir
1754 .copy_from_slice(&buf[2 * n_samples_in..2 * n_samples_in + 8]);
1755 self.fir_buf = buf;
1756 }
1757
1758 /// `silk_resampler_private_down_FIR`, for output rates below the internal
1759 /// rate (an AR2 pre-filter, then a polyphase FIR).
1760 fn down_fir(&mut self, out: &mut [i16], input: &[i16]) {
1761 let inv_ratio = self.inv_ratio_q16;
1762 let d = self.down.as_mut().expect("down-sampling state");
1763 let order = d.order;
1764 let mut buf = core::mem::take(&mut d.buf);
1765 // AR2 pre-filter into Q8.
1766 let a_q14 = [d.coefs[0], d.coefs[1]];
1767 for (k, &s) in input.iter().enumerate() {
1768 let out32 = d.state[0] + ((s as i32) << 8);
1769 buf[order + k] = out32;
1770 let out32 = out32 << 2;
1771 d.state[0] = smlawb(d.state[1], out32, a_q14[0] as i32);
1772 d.state[1] = smulwb(out32, a_q14[1] as i32);
1773 }
1774 let fir = &d.coefs[2..];
1775 let fracs = d.fracs;
1776 let mut written = 0usize;
1777 let max_index_q16 = (input.len() as i32) << 16;
1778 let mut index_q16 = 0i32;
1779 while index_q16 < max_index_q16 && written < out.len() {
1780 let base = (index_q16 >> 16) as usize;
1781 let interpol_ind = smulwb(index_q16 & 0xFFFF, fracs as i32) as usize;
1782 let coefs = &fir[interpol_ind * (order / 2)..];
1783 let mut res = 0i64;
1784 for j in 0..order / 2 {
1785 res += buf[base + j] as i64 * coefs[j] as i64;
1786 res += buf[base + order - 1 - j] as i64 * coefs[j] as i64;
1787 }
1788 out[written] = sat16(rshift_round((res >> 16) as i32, 6));
1789 written += 1;
1790 index_q16 += inv_ratio;
1791 }
1792 let keep = order;
1793 buf.copy_within(input.len()..input.len() + keep, 0);
1794 d.buf = buf;
1795 }
1796}
1797
1798#[cfg(test)]
1799mod tests {
1800 use super::*;
1801
1802 #[test]
1803 fn fixed_point_helpers_match_their_definitions() {
1804 // Spot values computed from the reference macro definitions.
1805 assert_eq!(smulwb(1 << 20, 3), 48);
1806 assert_eq!(smulbb(-5, 7), -35);
1807 assert_eq!(rshift_round(7, 1), 4);
1808 assert_eq!(rshift_round(-7, 2), -2);
1809 assert_eq!(sat16(40000), 32767);
1810 assert_eq!(sat16(-40000), -32768);
1811 // log2lin is the exponential the gain quantiser uses: 2^(q/128).
1812 for q in [0i32, 128, 1000, 3967] {
1813 let got = log2lin(q) as f64;
1814 let want = (q as f64 / 128.0).exp2();
1815 assert!(
1816 (got - want).abs() / want < 0.02,
1817 "log2lin({q}) = {got}, want {want}"
1818 );
1819 }
1820 // sqrt_approx returns sqrt(x) in the same Q domain. It is a coarse
1821 // approximation whose relative error only settles below ~1 % once the
1822 // input has enough significant bits, which is where SILK uses it (the
1823 // NLSF weights are shifted up by 16 first).
1824 for x in [1 << 18, 1234567, 1 << 24, 1 << 30] {
1825 let y = sqrt_approx(x) as f64;
1826 let want = (x as f64).sqrt();
1827 assert!(
1828 (y - want).abs() / want < 0.02,
1829 "sqrt({x}) = {y}, want {want}"
1830 );
1831 }
1832 }
1833
1834 #[test]
1835 fn gains_are_monotonic_in_the_index() {
1836 let mut prev = 0;
1837 let mut last = 0;
1838 for i in 0..64i8 {
1839 let g = gains_dequant(&[i, 0, 0, 0], &mut prev, false, 1)[0];
1840 assert!(g > last, "gain for index {i} did not increase");
1841 last = g;
1842 prev = i as i32;
1843 }
1844 }
1845
1846 #[test]
1847 fn nlsf_stabilize_enforces_the_minimum_spacing() {
1848 let cb = nlsf_cb(false);
1849 let mut nlsf = [100i16, 120, 130, 140, 150, 160, 170, 180, 190, 32700];
1850 nlsf_stabilize(&mut nlsf, cb.delta_min_q15);
1851 for i in 1..10 {
1852 assert!(
1853 nlsf[i] - nlsf[i - 1] >= cb.delta_min_q15[i],
1854 "spacing at {i}: {} < {}",
1855 nlsf[i] - nlsf[i - 1],
1856 cb.delta_min_q15[i]
1857 );
1858 }
1859 assert!(nlsf[0] >= cb.delta_min_q15[0]);
1860 assert!((1 << 15) - nlsf[9] as i32 >= cb.delta_min_q15[10] as i32);
1861 }
1862}