forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB84fa44cTahinli2 months ago3331 commits

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