forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

silk.rs2287 lines, 84.3 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//! LBRR (in-band FEC) frames are decoded through [`SilkFrameMode::Lbrr`], and
16//! lost frames are concealed by the packet loss concealment of the reference
17//! (`silk/PLC.c`), selected with [`SilkFrameMode::Lost`], and comfort noise
18//! (`silk/CNG.c`) is mixed into frames while the signal is noise-like.
19
20// SILK is transliterated fixed-point arithmetic: the loops below index parallel
21// arrays by position because the reference's index arithmetic is the
22// specification. Iterator forms would hide that correspondence.
23#![allow(clippy::needless_range_loop)]
24
25use ec_core::Result;
26
27use crate::range::RangeDecoder;
28pub(crate) use crate::silk_fix::*;
29
30pub(crate) mod tables {
31 #![allow(clippy::all)]
32 include!("silk_tables.rs");
33}
34
35use tables::*;
36
37pub(crate) const MAX_LPC_ORDER: usize = 16;
38pub(crate) const LTP_ORDER: usize = 5;
39pub(crate) const MAX_NB_SUBFR: usize = 4;
40const SUB_FRAME_LENGTH_MS: usize = 5;
41const LTP_MEM_LENGTH_MS: usize = 20;
42const MAX_FRAME_LENGTH: usize = 20 * 16;
43const QUANT_LEVEL_ADJUST_Q10: i32 = 80;
44const N_LEVELS_QGAIN: i32 = 64;
45const MIN_DELTA_GAIN_QUANT: i32 = -4;
46const MAX_DELTA_GAIN_QUANT: i32 = 36;
47const MIN_QGAIN_DB: i32 = 2;
48const MAX_QGAIN_DB: i32 = 88;
49pub(crate) const NLSF_QUANT_MAX_AMPLITUDE: i32 = 4;
50const SHELL_LEN: usize = 16;
51const MAX_PULSES: i32 = 16;
52const N_RATE_LEVELS: usize = 10;
53pub(crate) const PE_MIN_LAG_MS: i32 = 2;
54pub(crate) const PE_MAX_LAG_MS: i32 = 18;
55const STEREO_INTERP_LEN_MS: usize = 8;
56const TYPE_NO_VOICE_ACTIVITY: i32 = 0;
57const TYPE_VOICED: i32 = 2;
58const CNG_BUF_MASK_MAX: i32 = 255;
59const CNG_GAIN_SMTH_Q16: i32 = 4634;
60const CNG_NLSF_SMTH_Q16: i32 = 16348;
61const CNG_GAIN_SMTH_THRESHOLD_Q16: i32 = 46396;
62const MAX_LPC_STABILIZE_ITERATIONS: usize = 16;
63const BWE_COEF_Q16: i32 = 64881;
64const BWE_AFTER_LOSS_Q16: i32 = 63570;
65const V_PITCH_GAIN_START_MIN_Q14: i32 = 11469;
66const V_PITCH_GAIN_START_MAX_Q14: i32 = 15565;
67const RAND_BUF_SIZE: usize = 128;
68const RAND_BUF_MASK: i32 = 127;
69const LOG2_INV_LPC_GAIN_HIGH_THRES: i32 = 3;
70const LOG2_INV_LPC_GAIN_LOW_THRES: i32 = 8;
71const PITCH_DRIFT_FAC_Q16: i32 = 655;
72const MAX_PITCH_LAG_MS: i32 = 18;
73const HARM_ATT_Q15: [i32; NB_ATT] = [32440, 31130];
74const PLC_RAND_ATTENUATE_V_Q15: [i32; NB_ATT] = [31130, 26214];
75const PLC_RAND_ATTENUATE_UV_Q15: [i32; NB_ATT] = [32440, 29491];
76const NB_ATT: usize = 2;
77const MAX_LTP_MEM: usize = 20 * 16;
78
79/// Gain quantiser constants (`gain_quant.c`).
80const GAIN_OFFSET: i32 = (MIN_QGAIN_DB * 128) / 6 + 16 * 128;
81const GAIN_INV_SCALE_Q16: i32 =
82 (65536 * (((MAX_QGAIN_DB - MIN_QGAIN_DB) * 128) / 6)) / (N_LEVELS_QGAIN - 1);
83
84/// How a frame's parameters relate to the previous frame's.
85#[derive(Clone, Copy, PartialEq, Eq, Debug)]
86enum CondCoding {
87 Independently,
88 IndependentlyNoLtpScaling,
89 Conditionally,
90}
91
92/// What `SilkDecoder::decode` reads for a frame.
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94pub enum SilkFrameMode {
95 /// Regular frames, read from the range decoder.
96 Normal,
97 /// The packet's LBRR (in-band FEC) frames, where coded.
98 Lbrr,
99 /// No data for this frame: conceal it (PLC).
100 Lost,
101}
102
103impl SilkFrameMode {
104 fn coded(self, lbrr_flag: bool) -> bool {
105 match self {
106 SilkFrameMode::Normal => true,
107 SilkFrameMode::Lbrr => lbrr_flag,
108 SilkFrameMode::Lost => false,
109 }
110 }
111}
112
113// ---------------------------------------------------------------------------
114// Decoder state
115// ---------------------------------------------------------------------------
116
117/// Per-frame parameters decoded from the bitstream.
118#[derive(Clone, Debug, Default)]
119struct Indices {
120 signal_type: i32,
121 quant_offset_type: i32,
122 gains: [i8; MAX_NB_SUBFR],
123 nlsf: [i8; MAX_LPC_ORDER + 1],
124 nlsf_interp_coef_q2: i32,
125 lag_index: i32,
126 contour_index: i32,
127 per_index: usize,
128 ltp_index: [usize; MAX_NB_SUBFR],
129 ltp_scale_index: usize,
130 seed: i32,
131}
132
133/// Public snapshot of per-frame SILK parameters as decoded from the
134/// bitstream — used by the oracle diagnostic to compare our encoder's
135/// packets against ffmpeg-libopus's.
136#[derive(Clone, Debug, Default)]
137pub struct SilkDecIndices {
138 /// 0 = inactive/unvoiced, 1 = unvoiced, 2 = voiced (SILK `SignalType`).
139 pub signal_type: i32,
140 /// Quantization offset flavor: 0 = low-bitrate offset, 1 = default offset.
141 pub quant_offset_type: i32,
142 /// Per-subframe coded excitation gains; each is an index into the gain
143 /// dequantization table, not a linear gain.
144 pub gains: [i8; 4],
145 /// Quantized normalized LSF coefficients; 17 entries (`MAX_LPC_ORDER + 1`),
146 /// the last being the interpolated residual-energy weight.
147 pub nlsf: [i8; 17],
148 /// Interpolation weight between the previous and current frame's NLSFs,
149 /// Q2 in [0, 4] (4 = no interpolation).
150 pub nlsf_interp_coef_q2: i32,
151 /// Raw pitch lag index; the lag in samples is derived from this plus the
152 /// frame's lag range and minimum lag.
153 pub lag_index: i32,
154 /// Index into the pitch-contour codebook for the current bandwidth and
155 /// subframe count.
156 pub contour_index: i32,
157 /// Periodicity index selecting the LTP filter scaling per subframe.
158 pub per_index: usize,
159 /// Per-subframe LTP codebook indices; `usize::MAX` means LTP is off for
160 /// that subframe.
161 pub ltp_index: [usize; 4],
162 /// Index of the LTP gain scaling factor applied to all subframes.
163 pub ltp_scale_index: usize,
164 /// Pseudorandom seed for excitation sign/pulse decoding.
165 pub seed: i32,
166 /// Diagnostic-only counter of SILK frames this state has decoded.
167 pub frames_decoded: usize,
168}
169
170/// Everything `decode_parameters` produces for one frame.
171#[derive(Clone, Debug)]
172struct FrameCtrl {
173 gains_q16: [i32; MAX_NB_SUBFR],
174 pred_coef_q12: [[i16; MAX_LPC_ORDER]; 2],
175 ltp_coef_q14: [i16; LTP_ORDER * MAX_NB_SUBFR],
176 ltp_scale_q14: i32,
177 pitch_l: [i32; MAX_NB_SUBFR],
178}
179
180impl Default for FrameCtrl {
181 fn default() -> Self {
182 FrameCtrl {
183 gains_q16: [0; MAX_NB_SUBFR],
184 pred_coef_q12: [[0; MAX_LPC_ORDER]; 2],
185 ltp_coef_q14: [0; LTP_ORDER * MAX_NB_SUBFR],
186 ltp_scale_q14: 0,
187 pitch_l: [0; MAX_NB_SUBFR],
188 }
189 }
190}
191
192/// Packet loss concealment state (`silk_PLC_struct`).
193#[derive(Clone, Debug, Default)]
194struct PlcState {
195 pitch_l_q8: i32,
196 ltp_coef_q14: [i16; LTP_ORDER],
197 prev_lpc_q12: [i16; MAX_LPC_ORDER],
198 last_frame_lost: bool,
199 rand_seed: i32,
200 rand_scale_q14: i16,
201 conc_energy: i32,
202 conc_energy_shift: i32,
203 prev_ltp_scale_q14: i16,
204 prev_gain_q16: [i32; 2],
205 fs_khz: usize,
206 nb_subfr: usize,
207 subfr_length: usize,
208}
209
210/// Comfort noise state (`silk_CNG_struct`).
211#[derive(Clone, Debug)]
212struct CngState {
213 exc_buf_q14: [i32; MAX_FRAME_LENGTH],
214 smth_nlsf_q15: [i16; MAX_LPC_ORDER],
215 synth_state: [i32; MAX_LPC_ORDER],
216 smth_gain_q16: i32,
217 rand_seed: i32,
218 fs_khz: usize,
219}
220
221impl Default for CngState {
222 fn default() -> Self {
223 CngState {
224 exc_buf_q14: [0; MAX_FRAME_LENGTH],
225 smth_nlsf_q15: [0; MAX_LPC_ORDER],
226 synth_state: [0; MAX_LPC_ORDER],
227 smth_gain_q16: 0,
228 rand_seed: 0,
229 fs_khz: 0,
230 }
231 }
232}
233
234/// One SILK channel's inter-frame state.
235#[derive(Clone, Debug)]
236struct ChannelState {
237 fs_khz: usize,
238 frame_length: usize,
239 subfr_length: usize,
240 ltp_mem_length: usize,
241 nb_subfr: usize,
242 lpc_order: usize,
243 frames_per_packet: usize,
244 frames_decoded: usize,
245 /// Wideband uses the 16th-order codebook, NB/MB the 10th-order one.
246 wb_codebook: bool,
247 indices: Indices,
248 /// Synthesis history, `ltp_mem_length + frame_length` samples.
249 out_buf: [i16; MAX_FRAME_LENGTH + MAX_FRAME_LENGTH],
250 s_lpc_q14: [i32; MAX_LPC_ORDER],
251 exc_q14: [i32; MAX_FRAME_LENGTH],
252 prev_nlsf_q15: [i16; MAX_LPC_ORDER],
253 prev_gain_q16: i32,
254 last_gain_index: i32,
255 prev_signal_type: i32,
256 ec_prev_signal_type: i32,
257 ec_prev_lag_index: i32,
258 lag_prev: i32,
259 first_frame_after_reset: bool,
260 vad_flags: [bool; 3],
261 lbrr_flag: bool,
262 lbrr_flags: [bool; 3],
263 resampler: Resampler,
264 plc: PlcState,
265 cng: Box<CngState>,
266 loss_cnt: i32,
267}
268
269impl ChannelState {
270 fn new() -> ChannelState {
271 ChannelState {
272 fs_khz: 0,
273 frame_length: 0,
274 subfr_length: 0,
275 ltp_mem_length: 0,
276 nb_subfr: 0,
277 lpc_order: 0,
278 frames_per_packet: 1,
279 frames_decoded: 0,
280 wb_codebook: false,
281 indices: Indices::default(),
282 out_buf: [0; MAX_FRAME_LENGTH * 2],
283 s_lpc_q14: [0; MAX_LPC_ORDER],
284 exc_q14: [0; MAX_FRAME_LENGTH],
285 prev_nlsf_q15: [0; MAX_LPC_ORDER],
286 prev_gain_q16: 65536,
287 last_gain_index: 10,
288 prev_signal_type: 0,
289 ec_prev_signal_type: 0,
290 ec_prev_lag_index: 0,
291 lag_prev: 100,
292 first_frame_after_reset: true,
293 vad_flags: [false; 3],
294 lbrr_flag: false,
295 lbrr_flags: [false; 3],
296 resampler: Resampler::default(),
297 plc: PlcState::default(),
298 cng: Box::default(),
299 loss_cnt: 0,
300 }
301 }
302
303 /// `silk_decoder_set_fs`: geometry for an internal rate.
304 fn set_fs(&mut self, fs_khz: usize, api_rate: u32) {
305 self.subfr_length = SUB_FRAME_LENGTH_MS * fs_khz;
306 let frame_length = self.nb_subfr * self.subfr_length;
307 if self.fs_khz != fs_khz || self.resampler.fs_out_khz * 1000 != api_rate as usize {
308 self.resampler = Resampler::new(fs_khz, api_rate as usize / 1000);
309 }
310 if self.fs_khz != fs_khz {
311 self.ltp_mem_length = LTP_MEM_LENGTH_MS * fs_khz;
312 if fs_khz == 16 {
313 self.lpc_order = MAX_LPC_ORDER;
314 self.wb_codebook = true;
315 } else {
316 self.lpc_order = 10;
317 self.wb_codebook = false;
318 }
319 self.first_frame_after_reset = true;
320 self.lag_prev = 100;
321 self.last_gain_index = 10;
322 self.prev_signal_type = 0;
323 self.out_buf.fill(0);
324 self.s_lpc_q14.fill(0);
325 }
326 self.fs_khz = fs_khz;
327 self.frame_length = frame_length;
328 }
329
330 fn pitch_contour_icdf(&self) -> &'static [u8] {
331 match (self.fs_khz, self.nb_subfr) {
332 (8, 4) => &PITCH_CONTOUR_NB_ICDF,
333 (8, _) => &PITCH_CONTOUR_10_MS_NB_ICDF,
334 (_, 4) => &PITCH_CONTOUR_ICDF,
335 _ => &PITCH_CONTOUR_10_MS_ICDF,
336 }
337 }
338
339 fn pitch_lag_low_bits_icdf(&self) -> &'static [u8] {
340 match self.fs_khz {
341 16 => &UNIFORM8_ICDF,
342 12 => &UNIFORM6_ICDF,
343 _ => &UNIFORM4_ICDF,
344 }
345 }
346}
347
348/// Stereo prediction state carried between frames.
349#[derive(Clone, Debug, Default)]
350struct StereoState {
351 pred_prev_q13: [i32; 2],
352 s_mid: [i16; 2],
353 s_side: [i16; 2],
354}
355
356/// The SILK decoder for one Opus stream (one or two channels).
357#[derive(Clone, Debug)]
358pub struct SilkDecoder {
359 channels: [ChannelState; 2],
360 stereo: StereoState,
361 channels_internal: usize,
362 channels_api: usize,
363 api_rate: u32,
364 prev_decode_only_middle: bool,
365 /// Resampler output for one channel, allocated once.
366 resample_tmp: Vec<i16>,
367}
368
369impl SilkDecoder {
370 /// A decoder producing `channels_api` channels at `api_rate` Hz.
371 pub fn new(api_rate: u32, channels_api: usize) -> SilkDecoder {
372 SilkDecoder {
373 channels: [ChannelState::new(), ChannelState::new()],
374 stereo: StereoState::default(),
375 channels_internal: 1,
376 channels_api,
377 api_rate,
378 prev_decode_only_middle: false,
379 resample_tmp: vec![0; 5760],
380 }
381 }
382
383 /// Snapshot of the last decoded frame's index parameters for channel 0.
384 /// Used by the oracle diagnostic to inspect what the bitstream coded.
385 pub fn last_indices(&self) -> SilkDecIndices {
386 let ix = &self.channels[0].indices;
387 SilkDecIndices {
388 signal_type: ix.signal_type,
389 quant_offset_type: ix.quant_offset_type,
390 gains: ix.gains,
391 nlsf: ix.nlsf,
392 nlsf_interp_coef_q2: ix.nlsf_interp_coef_q2,
393 lag_index: ix.lag_index,
394 contour_index: ix.contour_index,
395 per_index: ix.per_index,
396 ltp_index: ix.ltp_index,
397 ltp_scale_index: ix.ltp_scale_index,
398 seed: ix.seed,
399 frames_decoded: self.channels[0].frames_decoded,
400 }
401 }
402
403 /// Whether the first SILK frame of `payload` carries LBRR (FEC) data for the mid channel.
404 pub fn has_lbrr(payload: &[u8], payload_ms: usize) -> bool {
405 if payload.is_empty() {
406 return false;
407 }
408 let frames_per_packet = match payload_ms {
409 40 => 2,
410 60 => 3,
411 _ => 1,
412 };
413 let mut dec = RangeDecoder::new(payload);
414 for _ in 0..frames_per_packet {
415 dec.dec_bit_logp(1);
416 }
417 dec.dec_bit_logp(1)
418 }
419
420 /// Drops all inter-packet state.
421 pub fn reset(&mut self) {
422 let api_rate = self.api_rate;
423 let channels_api = self.channels_api;
424 *self = SilkDecoder::new(api_rate, channels_api);
425 }
426
427 /// Decodes the SILK part of one Opus frame.
428 ///
429 /// `payload_ms` is the Opus frame duration (10, 20, 40 or 60 ms),
430 /// `internal_rate` the SILK sample rate the TOC implies (8000, 12000 or
431 /// 16000 Hz), and `channels_internal` how many channels the packet codes.
432 /// Output is interleaved `i16` at the API rate, `channels_api` channels.
433 /// `mode` selects what is read: regular frames, the LBRR (in-band FEC)
434 /// frames, or nothing at all, in which case the frame is concealed.
435 #[allow(clippy::too_many_arguments)]
436 pub fn decode(
437 &mut self,
438 dec: &mut RangeDecoder,
439 out: &mut [i16],
440 payload_ms: usize,
441 internal_rate: u32,
442 channels_internal: usize,
443 new_packet: bool,
444 mode: SilkFrameMode,
445 ) -> Result<usize> {
446 let lbrr = mode == SilkFrameMode::Lbrr;
447 let fs_khz = (internal_rate / 1000) as usize;
448 if new_packet {
449 for ch in self.channels.iter_mut() {
450 ch.frames_decoded = 0;
451 }
452 }
453 let (frames_per_packet, nb_subfr) = match payload_ms {
454 10 => (1, 2),
455 20 => (1, 4),
456 40 => (2, 4),
457 60 => (3, 4),
458 _ => (1, 4),
459 };
460 // A stream that gains a second channel starts it from scratch.
461 if channels_internal > self.channels_internal {
462 self.channels[1] = ChannelState::new();
463 }
464 if self.channels[0].frames_decoded == 0 {
465 for ch in self.channels.iter_mut().take(channels_internal) {
466 ch.frames_per_packet = frames_per_packet;
467 ch.nb_subfr = nb_subfr;
468 ch.set_fs(fs_khz, self.api_rate);
469 }
470 }
471 if self.channels_api == 2 && channels_internal == 2 && self.channels_internal == 1 {
472 // The side channel starts from the mid channel's resampler state,
473 // so the two stay in phase across the mono-to-stereo switch.
474 self.stereo.pred_prev_q13 = [0; 2];
475 self.stereo.s_side = [0; 2];
476 self.channels[1].resampler = self.channels[0].resampler.clone();
477 }
478 self.channels_internal = channels_internal;
479
480 let mut ms_pred_q13 = [0i32; 2];
481 let mut decode_only_middle = false;
482
483 // Header bits: per-frame VAD flags and the LBRR flag (Section 4.2.3).
484 if mode != SilkFrameMode::Lost && self.channels[0].frames_decoded == 0 {
485 for n in 0..channels_internal {
486 for i in 0..self.channels[n].frames_per_packet {
487 self.channels[n].vad_flags[i] = dec.dec_bit_logp(1);
488 }
489 self.channels[n].lbrr_flag = dec.dec_bit_logp(1);
490 }
491 for n in 0..channels_internal {
492 self.channels[n].lbrr_flags = [false; 3];
493 if self.channels[n].lbrr_flag {
494 if self.channels[n].frames_per_packet == 1 {
495 self.channels[n].lbrr_flags[0] = true;
496 } else {
497 let icdf: &[u8] = if self.channels[n].frames_per_packet == 2 {
498 &LBRR_FLAGS_2_ICDF
499 } else {
500 &LBRR_FLAGS_3_ICDF
501 };
502 let sym = dec.dec_icdf(icdf, 8) as i32 + 1;
503 for i in 0..self.channels[n].frames_per_packet {
504 self.channels[n].lbrr_flags[i] = (sym >> i) & 1 != 0;
505 }
506 }
507 }
508 }
509 // Skip the LBRR frames: they are only useful for concealment, but
510 // their symbols must still be consumed to stay in sync.
511 let skip = if lbrr {
512 0
513 } else {
514 self.channels[0].frames_per_packet
515 };
516 for i in 0..skip {
517 for n in 0..channels_internal {
518 if self.channels[n].lbrr_flags[i] {
519 if channels_internal == 2 && n == 0 {
520 stereo_decode_pred(dec, &mut ms_pred_q13);
521 if !self.channels[1].lbrr_flags[i] {
522 let _ = dec.dec_icdf(&STEREO_ONLY_CODE_MID_ICDF, 8);
523 }
524 }
525 let cond = if i > 0 && self.channels[n].lbrr_flags[i - 1] {
526 CondCoding::Conditionally
527 } else {
528 CondCoding::Independently
529 };
530 let ch = &mut self.channels[n];
531 decode_indices(ch, dec, i, true, cond);
532 let mut pulses = [0i32; MAX_FRAME_LENGTH + SHELL_LEN];
533 let n = ch.frame_length;
534 decode_pulses(
535 dec,
536 &mut pulses,
537 n,
538 ch.indices.signal_type,
539 ch.indices.quant_offset_type,
540 );
541 }
542 }
543 }
544 }
545
546 // Stereo prediction weights for this frame.
547 if channels_internal == 2 {
548 let frame = self.channels[0].frames_decoded;
549 if mode.coded(self.channels[0].lbrr_flags[frame]) {
550 stereo_decode_pred(dec, &mut ms_pred_q13);
551 let side_coded = if lbrr {
552 self.channels[1].lbrr_flags[frame]
553 } else {
554 self.channels[1].vad_flags[frame]
555 };
556 if !side_coded {
557 decode_only_middle = dec.dec_icdf(&STEREO_ONLY_CODE_MID_ICDF, 8) != 0;
558 }
559 } else {
560 ms_pred_q13 = self.stereo.pred_prev_q13;
561 }
562 }
563 if channels_internal == 2 && !decode_only_middle && self.prev_decode_only_middle {
564 self.channels[1].out_buf.fill(0);
565 self.channels[1].s_lpc_q14.fill(0);
566 self.channels[1].lag_prev = 100;
567 self.channels[1].last_gain_index = 10;
568 self.channels[1].prev_signal_type = 0;
569 self.channels[1].first_frame_after_reset = true;
570 }
571
572 let has_side = !decode_only_middle;
573 let mut mid = [0i16; MAX_FRAME_LENGTH + 2];
574 let mut side = [0i16; MAX_FRAME_LENGTH + 2];
575 let mut n_samples_dec = 0usize;
576 for n in 0..channels_internal {
577 let buf: &mut [i16] = if n == 0 { &mut mid } else { &mut side };
578 if n == 0 || has_side {
579 let frame_index = self.channels[0].frames_decoded as i32 - n as i32;
580 let cond = if frame_index <= 0 {
581 CondCoding::Independently
582 } else if lbrr {
583 if self.channels[n].lbrr_flags[(frame_index - 1) as usize] {
584 CondCoding::Conditionally
585 } else {
586 CondCoding::Independently
587 }
588 } else if n > 0 && self.prev_decode_only_middle {
589 CondCoding::IndependentlyNoLtpScaling
590 } else {
591 CondCoding::Conditionally
592 };
593 let coded =
594 mode.coded(self.channels[n].lbrr_flags[self.channels[n].frames_decoded]);
595 n_samples_dec =
596 decode_frame(&mut self.channels[n], dec, &mut buf[2..], cond, lbrr, coded);
597 } else {
598 buf[2..2 + n_samples_dec].fill(0);
599 }
600 self.channels[n].frames_decoded += 1;
601 }
602
603 // Stereo unmixing, then resampling to the output rate.
604 if self.channels_api == 2 && channels_internal == 2 {
605 stereo_ms_to_lr(
606 &mut self.stereo,
607 &mut mid,
608 &mut side,
609 &ms_pred_q13,
610 self.channels[0].fs_khz,
611 n_samples_dec,
612 );
613 } else {
614 mid[0] = self.stereo.s_mid[0];
615 mid[1] = self.stereo.s_mid[1];
616 self.stereo.s_mid[0] = mid[n_samples_dec];
617 self.stereo.s_mid[1] = mid[n_samples_dec + 1];
618 }
619 if mode == SilkFrameMode::Lost {
620 for ch in self.channels.iter_mut().take(channels_internal) {
621 ch.last_gain_index = 10;
622 }
623 } else {
624 self.prev_decode_only_middle = decode_only_middle;
625 }
626
627 let out_len = n_samples_dec * self.api_rate as usize / (self.channels[0].fs_khz * 1000);
628 let mut tmp = core::mem::take(&mut self.resample_tmp);
629 tmp.clear();
630 tmp.resize(out_len, 0);
631 let chans = self.channels_api.min(channels_internal);
632 for n in 0..chans {
633 let src: &[i16] = if n == 0 { &mid[1..] } else { &side[1..] };
634 let state = &mut self.channels[n].resampler;
635 state.process(&mut tmp, &src[..n_samples_dec], n_samples_dec);
636 if self.channels_api == 2 {
637 for i in 0..out_len {
638 out[n + 2 * i] = tmp[i];
639 }
640 } else {
641 out[..out_len].copy_from_slice(&tmp[..out_len]);
642 }
643 }
644 self.resample_tmp = tmp;
645 // A mono stream fed to a stereo output is duplicated.
646 if self.channels_api == 2 && channels_internal == 1 {
647 for i in 0..out_len {
648 out[1 + 2 * i] = out[2 * i];
649 }
650 }
651 Ok(out_len)
652 }
653}
654
655/// `silk_decode_indices` (Section 4.2.7).
656fn decode_indices(
657 ch: &mut ChannelState,
658 dec: &mut RangeDecoder,
659 frame_index: usize,
660 decode_lbrr: bool,
661 cond: CondCoding,
662) {
663 let ix = if decode_lbrr || ch.vad_flags[frame_index] {
664 dec.dec_icdf(&TYPE_OFFSET_VAD_ICDF, 8) as i32 + 2
665 } else {
666 dec.dec_icdf(&TYPE_OFFSET_NO_VAD_ICDF, 8) as i32
667 };
668 ch.indices.signal_type = ix >> 1;
669 ch.indices.quant_offset_type = ix & 1;
670
671 // Subframe gains (Section 4.2.7.4).
672 if cond == CondCoding::Conditionally {
673 ch.indices.gains[0] = dec.dec_icdf(&DELTA_GAIN_ICDF, 8) as i8;
674 } else {
675 let msb = dec.dec_icdf(&GAIN_ICDF[ch.indices.signal_type as usize], 8) as i32;
676 let lsb = dec.dec_icdf(&UNIFORM8_ICDF, 8) as i32;
677 ch.indices.gains[0] = ((msb << 3) + lsb) as i8;
678 }
679 for i in 1..ch.nb_subfr {
680 ch.indices.gains[i] = dec.dec_icdf(&DELTA_GAIN_ICDF, 8) as i8;
681 }
682
683 // Normalised LSFs (Section 4.2.7.5).
684 let cb = nlsf_cb(ch.wb_codebook);
685 let stage1_icdf = &cb.cb1_icdf[(ch.indices.signal_type as usize >> 1) * cb.n_vectors..];
686 ch.indices.nlsf[0] = dec.dec_icdf(stage1_icdf, 8) as i8;
687 let (ec_ix, _pred) = nlsf_unpack(cb, ch.indices.nlsf[0] as usize);
688 for i in 0..cb.order {
689 let mut ix = dec.dec_icdf(&cb.ec_icdf[ec_ix[i] as usize..], 8) as i32;
690 if ix == 0 {
691 ix -= dec.dec_icdf(&NLSF_EXT_ICDF, 8) as i32;
692 } else if ix == 2 * NLSF_QUANT_MAX_AMPLITUDE {
693 ix += dec.dec_icdf(&NLSF_EXT_ICDF, 8) as i32;
694 }
695 ch.indices.nlsf[i + 1] = (ix - NLSF_QUANT_MAX_AMPLITUDE) as i8;
696 }
697 ch.indices.nlsf_interp_coef_q2 = if ch.nb_subfr == MAX_NB_SUBFR {
698 dec.dec_icdf(&NLSF_INTERPOLATION_FACTOR_ICDF, 8) as i32
699 } else {
700 4
701 };
702
703 // Pitch and LTP (Section 4.2.7.6).
704 if ch.indices.signal_type == TYPE_VOICED {
705 let mut absolute = true;
706 if cond == CondCoding::Conditionally && ch.ec_prev_signal_type == TYPE_VOICED {
707 let delta = dec.dec_icdf(&PITCH_DELTA_ICDF, 8) as i32;
708 if delta > 0 {
709 ch.indices.lag_index = ch.ec_prev_lag_index + delta - 9;
710 absolute = false;
711 }
712 }
713 if absolute {
714 ch.indices.lag_index =
715 dec.dec_icdf(&PITCH_LAG_ICDF, 8) as i32 * (ch.fs_khz as i32 >> 1);
716 ch.indices.lag_index += dec.dec_icdf(ch.pitch_lag_low_bits_icdf(), 8) as i32;
717 }
718 ch.ec_prev_lag_index = ch.indices.lag_index;
719 ch.indices.contour_index = dec.dec_icdf(ch.pitch_contour_icdf(), 8) as i32;
720 ch.indices.per_index = dec.dec_icdf(&LTP_PER_INDEX_ICDF, 8);
721 let gain_icdf: &[u8] = match ch.indices.per_index {
722 0 => &LTP_GAIN_ICDF_0,
723 1 => &LTP_GAIN_ICDF_1,
724 _ => &LTP_GAIN_ICDF_2,
725 };
726 for k in 0..ch.nb_subfr {
727 ch.indices.ltp_index[k] = dec.dec_icdf(gain_icdf, 8);
728 }
729 ch.indices.ltp_scale_index = if cond == CondCoding::Independently {
730 dec.dec_icdf(&LTPSCALE_ICDF, 8)
731 } else {
732 0
733 };
734 }
735 ch.ec_prev_signal_type = ch.indices.signal_type;
736 ch.indices.seed = dec.dec_icdf(&UNIFORM4_ICDF, 8) as i32;
737}
738
739/// `silk_decode_pulses` (Section 4.2.7.8): the excitation.
740fn decode_pulses(
741 dec: &mut RangeDecoder,
742 pulses: &mut [i32],
743 frame_length: usize,
744 signal_type: i32,
745 quant_offset_type: i32,
746) {
747 // A 12 kHz 10 ms frame is 120 samples, which is not a whole number of
748 // 16-sample shell blocks: the last block runs past the frame and its extra
749 // pulses are discarded, so `pulses` must have room for them.
750 debug_assert!(pulses.len() >= frame_length.div_ceil(SHELL_LEN) * SHELL_LEN);
751 let rate_level = dec.dec_icdf(&RATE_LEVELS_ICDF[signal_type as usize >> 1], 8);
752 let mut iter = frame_length >> 4;
753 if iter * SHELL_LEN < frame_length {
754 iter += 1;
755 }
756 let mut sum_pulses = [0i32; MAX_FRAME_LENGTH / SHELL_LEN + 1];
757 let mut n_lshifts = [0i32; MAX_FRAME_LENGTH / SHELL_LEN + 1];
758 for i in 0..iter {
759 sum_pulses[i] = dec.dec_icdf(&PULSES_PER_BLOCK_ICDF[rate_level], 8) as i32;
760 while sum_pulses[i] == MAX_PULSES + 1 {
761 n_lshifts[i] += 1;
762 let icdf = &PULSES_PER_BLOCK_ICDF[N_RATE_LEVELS - 1][usize::from(n_lshifts[i] == 10)..];
763 sum_pulses[i] = dec.dec_icdf(icdf, 8) as i32;
764 }
765 }
766 for i in 0..iter {
767 let block = &mut pulses[i * SHELL_LEN..];
768 if sum_pulses[i] > 0 {
769 shell_decode(dec, block, sum_pulses[i]);
770 } else {
771 block[..SHELL_LEN].fill(0);
772 }
773 }
774 // Least significant bits for blocks that overflowed the pulse count.
775 for i in 0..iter {
776 if n_lshifts[i] > 0 {
777 let block = &mut pulses[i * SHELL_LEN..];
778 for k in 0..SHELL_LEN {
779 let mut abs_q = block[k];
780 for _ in 0..n_lshifts[i] {
781 abs_q <<= 1;
782 abs_q += dec.dec_icdf(&LSB_ICDF, 8) as i32;
783 }
784 block[k] = abs_q;
785 }
786 sum_pulses[i] |= n_lshifts[i] << 5;
787 }
788 }
789 decode_signs(
790 dec,
791 pulses,
792 signal_type,
793 quant_offset_type,
794 &sum_pulses[..iter],
795 );
796}
797
798/// One 16-sample shell block (Section 4.2.7.8.3).
799fn shell_decode(dec: &mut RangeDecoder, pulses0: &mut [i32], total: i32) {
800 fn split(dec: &mut RangeDecoder, p: i32, table: &[u8]) -> (i32, i32) {
801 if p > 0 {
802 let a = dec.dec_icdf(&table[SHELL_CODE_TABLE_OFFSETS[p as usize] as usize..], 8) as i32;
803 (a, p - a)
804 } else {
805 (0, 0)
806 }
807 }
808 let mut p3 = [0i32; 2];
809 let mut p2 = [0i32; 4];
810 let mut p1 = [0i32; 8];
811 (p3[0], p3[1]) = split(dec, total, &SHELL_CODE_TABLE3);
812 (p2[0], p2[1]) = split(dec, p3[0], &SHELL_CODE_TABLE2);
813 (p1[0], p1[1]) = split(dec, p2[0], &SHELL_CODE_TABLE1);
814 (pulses0[0], pulses0[1]) = split(dec, p1[0], &SHELL_CODE_TABLE0);
815 (pulses0[2], pulses0[3]) = split(dec, p1[1], &SHELL_CODE_TABLE0);
816 (p1[2], p1[3]) = split(dec, p2[1], &SHELL_CODE_TABLE1);
817 (pulses0[4], pulses0[5]) = split(dec, p1[2], &SHELL_CODE_TABLE0);
818 (pulses0[6], pulses0[7]) = split(dec, p1[3], &SHELL_CODE_TABLE0);
819 (p2[2], p2[3]) = split(dec, p3[1], &SHELL_CODE_TABLE2);
820 (p1[4], p1[5]) = split(dec, p2[2], &SHELL_CODE_TABLE1);
821 (pulses0[8], pulses0[9]) = split(dec, p1[4], &SHELL_CODE_TABLE0);
822 (pulses0[10], pulses0[11]) = split(dec, p1[5], &SHELL_CODE_TABLE0);
823 (p1[6], p1[7]) = split(dec, p2[3], &SHELL_CODE_TABLE1);
824 (pulses0[12], pulses0[13]) = split(dec, p1[6], &SHELL_CODE_TABLE0);
825 (pulses0[14], pulses0[15]) = split(dec, p1[7], &SHELL_CODE_TABLE0);
826}
827
828/// Excitation signs (Section 4.2.7.8.5).
829fn decode_signs(
830 dec: &mut RangeDecoder,
831 pulses: &mut [i32],
832 signal_type: i32,
833 quant_offset_type: i32,
834 sum_pulses: &[i32],
835) {
836 let base = 7 * (quant_offset_type + (signal_type << 1)) as usize;
837 for (i, &p) in sum_pulses.iter().enumerate() {
838 if p > 0 {
839 let icdf = [SIGN_ICDF[base + (p & 0x1F).min(6) as usize], 0];
840 for j in 0..SHELL_LEN {
841 let idx = i * SHELL_LEN + j;
842 if idx < pulses.len() && pulses[idx] > 0 {
843 pulses[idx] *= 2 * dec.dec_icdf(&icdf, 8) as i32 - 1;
844 }
845 }
846 }
847 }
848}
849
850/// The NLSF codebook for one bandwidth (Section 4.2.7.5).
851pub(crate) struct NlsfCodebook {
852 pub(crate) n_vectors: usize,
853 pub(crate) order: usize,
854 pub(crate) quant_step_size_q16: i32,
855 pub(crate) cb1_q8: &'static [u8],
856 pub(crate) cb1_icdf: &'static [u8],
857 pub(crate) pred_q8: &'static [u8],
858 pub(crate) ec_sel: &'static [u8],
859 pub(crate) ec_icdf: &'static [u8],
860 pub(crate) delta_min_q15: &'static [i16],
861}
862
863pub(crate) fn nlsf_cb(wideband: bool) -> &'static NlsfCodebook {
864 static NB_MB: NlsfCodebook = NlsfCodebook {
865 n_vectors: 32,
866 order: 10,
867 // 0.18 in Q16.
868 quant_step_size_q16: 11796,
869 cb1_q8: &NLSF_CB1_NB_MB_Q8,
870 cb1_icdf: &NLSF_CB1_ICDF_NB_MB,
871 pred_q8: &NLSF_PRED_NB_MB_Q8,
872 ec_sel: &NLSF_CB2_SELECT_NB_MB,
873 ec_icdf: &NLSF_CB2_ICDF_NB_MB,
874 delta_min_q15: &NLSF_DELTA_MIN_NB_MB_Q15,
875 };
876 static WB: NlsfCodebook = NlsfCodebook {
877 n_vectors: 32,
878 order: 16,
879 quant_step_size_q16: 9830,
880 cb1_q8: &NLSF_CB1_WB_Q8,
881 cb1_icdf: &NLSF_CB1_ICDF_WB,
882 pred_q8: &NLSF_PRED_WB_Q8,
883 ec_sel: &NLSF_CB2_SELECT_WB,
884 ec_icdf: &NLSF_CB2_ICDF_WB,
885 delta_min_q15: &NLSF_DELTA_MIN_WB_Q15,
886 };
887 if wideband { &WB } else { &NB_MB }
888}
889
890/// `silk_NLSF_unpack`: per-coefficient entropy-table selectors and predictors.
891pub(crate) fn nlsf_unpack(
892 cb: &NlsfCodebook,
893 cb1_index: usize,
894) -> ([i16; MAX_LPC_ORDER], [u8; MAX_LPC_ORDER]) {
895 let mut ec_ix = [0i16; MAX_LPC_ORDER];
896 let mut pred = [0u8; MAX_LPC_ORDER];
897 let sel = &cb.ec_sel[cb1_index * cb.order / 2..];
898 for i in (0..cb.order).step_by(2) {
899 let entry = sel[i / 2];
900 ec_ix[i] = (((entry >> 1) & 7) as i16) * (2 * NLSF_QUANT_MAX_AMPLITUDE as i16 + 1);
901 pred[i] = cb.pred_q8[i + (entry & 1) as usize * (cb.order - 1)];
902 ec_ix[i + 1] = (((entry >> 5) & 7) as i16) * (2 * NLSF_QUANT_MAX_AMPLITUDE as i16 + 1);
903 pred[i + 1] = cb.pred_q8[i + ((entry >> 4) & 1) as usize * (cb.order - 1) + 1];
904 }
905 (ec_ix, pred)
906}
907
908/// `silk_NLSF_decode`: indices to normalised LSFs (Section 4.2.7.5.3).
909pub(crate) fn nlsf_decode(indices: &[i8], cb: &NlsfCodebook) -> [i16; MAX_LPC_ORDER] {
910 let mut nlsf_q15 = [0i16; MAX_LPC_ORDER];
911 let base = indices[0] as usize * cb.order;
912 for i in 0..cb.order {
913 nlsf_q15[i] = (cb.cb1_q8[base + i] as i16) << 7;
914 }
915 let (_, pred_q8) = nlsf_unpack(cb, indices[0] as usize);
916 // Residual dequantisation, back to front so the prediction chains.
917 let mut res_q10 = [0i16; MAX_LPC_ORDER];
918 let mut out_q10 = 0i32;
919 for i in (0..cb.order).rev() {
920 let pred_q10 = smulbb(out_q10, pred_q8[i] as i32) >> 8;
921 out_q10 = (indices[i + 1] as i32) << 10;
922 if out_q10 > 0 {
923 out_q10 -= 102; // 0.1 in Q10
924 } else if out_q10 < 0 {
925 out_q10 += 102;
926 }
927 out_q10 = smlawb(pred_q10, out_q10, cb.quant_step_size_q16);
928 res_q10[i] = out_q10 as i16;
929 }
930 // Weight by the Laroia measure, add, then enforce the minimum spacing.
931 let w_qw = nlsf_vq_weights_laroia(&nlsf_q15[..cb.order]);
932 for i in 0..cb.order {
933 let w_q9 = sqrt_approx((w_qw[i] as i32) << 16);
934 let v = nlsf_q15[i] as i32 + (((res_q10[i] as i32) << 14) / w_q9);
935 nlsf_q15[i] = v.clamp(0, 32767) as i16;
936 }
937 nlsf_stabilize(&mut nlsf_q15[..cb.order], cb.delta_min_q15);
938 nlsf_q15
939}
940
941/// `silk_NLSF_VQ_weights_laroia` (Section 4.2.7.5.3).
942pub(crate) fn nlsf_vq_weights_laroia(nlsf_q15: &[i16]) -> [i16; MAX_LPC_ORDER] {
943 let d = nlsf_q15.len();
944 let mut w = [0i16; MAX_LPC_ORDER];
945 let inv = |x: i32| (1i32 << 17) / x.max(1);
946 let mut tmp1 = inv(nlsf_q15[0] as i32);
947 let mut tmp2 = inv(nlsf_q15[1] as i32 - nlsf_q15[0] as i32);
948 w[0] = (tmp1 + tmp2).min(32767) as i16;
949 let mut k = 1;
950 while k < d - 1 {
951 tmp1 = inv(nlsf_q15[k + 1] as i32 - nlsf_q15[k] as i32);
952 w[k] = (tmp1 + tmp2).min(32767) as i16;
953 tmp2 = inv(nlsf_q15[k + 2] as i32 - nlsf_q15[k + 1] as i32);
954 w[k + 1] = (tmp1 + tmp2).min(32767) as i16;
955 k += 2;
956 }
957 tmp1 = inv((1 << 15) - nlsf_q15[d - 1] as i32);
958 w[d - 1] = (tmp1 + tmp2).min(32767) as i16;
959 w
960}
961
962/// `silk_NLSF_stabilize` (Section 4.2.7.5.4): enforce the minimum spacing.
963pub(crate) fn nlsf_stabilize(nlsf_q15: &mut [i16], delta_min_q15: &[i16]) {
964 let l = nlsf_q15.len();
965 for _ in 0..20 {
966 let mut min_diff = nlsf_q15[0] as i32 - delta_min_q15[0] as i32;
967 let mut i_min = 0usize;
968 for i in 1..l {
969 let diff = nlsf_q15[i] as i32 - (nlsf_q15[i - 1] as i32 + delta_min_q15[i] as i32);
970 if diff < min_diff {
971 min_diff = diff;
972 i_min = i;
973 }
974 }
975 let diff = (1 << 15) - (nlsf_q15[l - 1] as i32 + delta_min_q15[l] as i32);
976 if diff < min_diff {
977 min_diff = diff;
978 i_min = l;
979 }
980 if min_diff >= 0 {
981 return;
982 }
983 if i_min == 0 {
984 nlsf_q15[0] = delta_min_q15[0];
985 } else if i_min == l {
986 nlsf_q15[l - 1] = ((1 << 15) - delta_min_q15[l] as i32) as i16;
987 } else {
988 let mut min_center = 0i32;
989 for k in 0..i_min {
990 min_center += delta_min_q15[k] as i32;
991 }
992 min_center += delta_min_q15[i_min] as i32 >> 1;
993 let mut max_center = 1i32 << 15;
994 for k in (i_min + 1..=l).rev() {
995 max_center -= delta_min_q15[k] as i32;
996 }
997 max_center -= delta_min_q15[i_min] as i32 >> 1;
998 let center = rshift_round(nlsf_q15[i_min - 1] as i32 + nlsf_q15[i_min] as i32, 1)
999 .clamp(min_center, max_center);
1000 nlsf_q15[i_min - 1] = (center - (delta_min_q15[i_min] as i32 >> 1)) as i16;
1001 nlsf_q15[i_min] = nlsf_q15[i_min - 1] + delta_min_q15[i_min];
1002 }
1003 }
1004 // Last resort: sort and clamp (the reference's fallback after 20 loops).
1005 nlsf_q15.sort_unstable();
1006 nlsf_q15[0] = nlsf_q15[0].max(delta_min_q15[0]);
1007 for i in 1..l {
1008 nlsf_q15[i] = nlsf_q15[i].max(nlsf_q15[i - 1].saturating_add(delta_min_q15[i]));
1009 }
1010 nlsf_q15[l - 1] = nlsf_q15[l - 1].min(((1 << 15) - delta_min_q15[l] as i32) as i16);
1011 for i in (0..l - 1).rev() {
1012 nlsf_q15[i] = nlsf_q15[i].min(nlsf_q15[i + 1] - delta_min_q15[i + 1]);
1013 }
1014}
1015
1016/// `silk_NLSF2A` (Section 4.2.7.5.6): LSFs to LPC coefficients.
1017pub(crate) fn nlsf2a(nlsf: &[i16], order: usize) -> [i16; MAX_LPC_ORDER] {
1018 const QA: u32 = 16;
1019 const ORDER16: [usize; 16] = [0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1];
1020 const ORDER10: [usize; 10] = [0, 9, 6, 3, 4, 5, 8, 1, 2, 7];
1021 let ordering: &[usize] = if order == 16 { &ORDER16 } else { &ORDER10 };
1022
1023 let mut cos_lsf_qa = [0i32; MAX_LPC_ORDER];
1024 for k in 0..order {
1025 let f_int = (nlsf[k] >> 8) as usize;
1026 let f_frac = nlsf[k] as i32 - ((f_int as i32) << 8);
1027 let cos_val = LSFCOSTAB_FIX_Q12[f_int] as i32;
1028 let delta = LSFCOSTAB_FIX_Q12[f_int + 1] as i32 - cos_val;
1029 cos_lsf_qa[ordering[k]] = rshift_round((cos_val << 8) + delta * f_frac, 20 - QA);
1030 }
1031 let dd = order / 2;
1032 let p = nlsf2a_find_poly(&cos_lsf_qa, dd, 0);
1033 let q = nlsf2a_find_poly(&cos_lsf_qa, dd, 1);
1034
1035 let mut a32_qa1 = [0i32; MAX_LPC_ORDER];
1036 for k in 0..dd {
1037 let ptmp = p[k + 1] + p[k];
1038 let qtmp = q[k + 1] - q[k];
1039 a32_qa1[k] = -qtmp - ptmp;
1040 a32_qa1[order - k - 1] = qtmp - ptmp;
1041 }
1042
1043 // Clamp into Q12 without letting the filter blow up.
1044 let mut a_q12 = [0i16; MAX_LPC_ORDER];
1045 let mut i = 0;
1046 while i < 10 {
1047 let mut maxabs = 0i32;
1048 let mut idx = 0usize;
1049 for k in 0..order {
1050 let absval = a32_qa1[k].abs();
1051 if absval > maxabs {
1052 maxabs = absval;
1053 idx = k;
1054 }
1055 }
1056 let maxabs_q12 = rshift_round(maxabs, QA + 1 - 12);
1057 if maxabs_q12 > 32767 {
1058 let maxabs_q12 = maxabs_q12.min(163838);
1059 let sc_q16 =
1060 65470 - ((maxabs_q12 - 32767) << 14) / ((maxabs_q12 * (idx as i32 + 1)) >> 2);
1061 bwexpander_32(&mut a32_qa1[..order], sc_q16);
1062 } else {
1063 break;
1064 }
1065 i += 1;
1066 }
1067 if i == 10 {
1068 for k in 0..order {
1069 a_q12[k] = sat16(rshift_round(a32_qa1[k], QA + 1 - 12));
1070 a32_qa1[k] = (a_q12[k] as i32) << (QA + 1 - 12);
1071 }
1072 } else {
1073 for k in 0..order {
1074 a_q12[k] = rshift_round(a32_qa1[k], QA + 1 - 12) as i16;
1075 }
1076 }
1077 // Bandwidth expansion until the prediction gain is sane.
1078 for i in 0..MAX_LPC_STABILIZE_ITERATIONS {
1079 if lpc_inverse_pred_gain(&a_q12[..order]) < 107374 {
1080 bwexpander_32(&mut a32_qa1[..order], 65536 - (2 << i));
1081 for k in 0..order {
1082 a_q12[k] = rshift_round(a32_qa1[k], QA + 1 - 12) as i16;
1083 }
1084 } else {
1085 break;
1086 }
1087 }
1088 a_q12
1089}
1090
1091fn nlsf2a_find_poly(cos_lsf_qa: &[i32], dd: usize, offset: usize) -> [i32; MAX_LPC_ORDER / 2 + 1] {
1092 const QA: u32 = 16;
1093 let mut out = [0i32; MAX_LPC_ORDER / 2 + 1];
1094 out[0] = 1 << QA;
1095 out[1] = -cos_lsf_qa[offset];
1096 for k in 1..dd {
1097 let ftmp = cos_lsf_qa[2 * k + offset];
1098 out[k + 1] = (out[k - 1] << 1) - rshift_round64(ftmp as i64 * out[k] as i64, QA) as i32;
1099 for n in (2..=k).rev() {
1100 out[n] += out[n - 2] - rshift_round64(ftmp as i64 * out[n - 1] as i64, QA) as i32;
1101 }
1102 out[1] -= ftmp;
1103 }
1104 out
1105}
1106
1107fn bwexpander_32(ar: &mut [i32], chirp_q16: i32) {
1108 let mut chirp = chirp_q16;
1109 let chirp_minus_one = chirp_q16 - 65536;
1110 let d = ar.len();
1111 for coef in ar.iter_mut().take(d - 1) {
1112 *coef = smulww(chirp, *coef);
1113 chirp += rshift_round(chirp.wrapping_mul(chirp_minus_one), 16);
1114 }
1115 ar[d - 1] = smulww(chirp, ar[d - 1]);
1116}
1117
1118/// `silk_LPC_inverse_pred_gain` (Section 4.2.7.5.8), in Q30.
1119fn lpc_inverse_pred_gain(a_q12: &[i16]) -> i32 {
1120 const QA: u32 = 24;
1121 const A_LIMIT: i32 = 16773022; // 0.99975 in Q24
1122 let order = a_q12.len();
1123 let mut a = [[0i32; MAX_LPC_ORDER]; 2];
1124 let mut dc_resp = 0i32;
1125 for k in 0..order {
1126 dc_resp += a_q12[k] as i32;
1127 a[order & 1][k] = (a_q12[k] as i32) << (QA - 12);
1128 }
1129 if dc_resp >= 4096 {
1130 return 0;
1131 }
1132 let mut cur = order & 1;
1133 let mut inv_gain_q30 = 1i32 << 30;
1134 for k in (1..order).rev() {
1135 if a[cur][k] > A_LIMIT || a[cur][k] < -A_LIMIT {
1136 return 0;
1137 }
1138 let rc_q31 = -(a[cur][k] << (31 - QA));
1139 let rc_mult1_q30 = (1i32 << 30) - smmul(rc_q31, rc_q31);
1140 let mult2q = 32 - clz32(rc_mult1_q30.abs());
1141 let rc_mult2 = inverse32_var_q(rc_mult1_q30, (mult2q + 30) as u32);
1142 inv_gain_q30 = smmul(inv_gain_q30, rc_mult1_q30) << 2;
1143 let old = cur;
1144 cur = k & 1;
1145 for n in 0..k {
1146 let tmp = a[old][n] - mul32_frac_q(a[old][k - n - 1], rc_q31, 31);
1147 a[cur][n] = mul32_frac_q(tmp, rc_mult2, mult2q as u32);
1148 }
1149 }
1150 if a[cur][0] > A_LIMIT || a[cur][0] < -A_LIMIT {
1151 return 0;
1152 }
1153 let rc_q31 = -(a[cur][0] << (31 - QA));
1154 let rc_mult1_q30 = (1i32 << 30) - smmul(rc_q31, rc_q31);
1155 smmul(inv_gain_q30, rc_mult1_q30) << 2
1156}
1157
1158#[inline]
1159fn mul32_frac_q(a: i32, b: i32, q: u32) -> i32 {
1160 rshift_round64(a as i64 * b as i64, q) as i32
1161}
1162
1163/// `silk_gains_dequant` (Section 4.2.7.4).
1164pub(crate) fn gains_dequant(
1165 indices: &[i8],
1166 prev_ind: &mut i32,
1167 conditional: bool,
1168 nb_subfr: usize,
1169) -> [i32; MAX_NB_SUBFR] {
1170 let mut gains = [0i32; MAX_NB_SUBFR];
1171 for k in 0..nb_subfr {
1172 if k == 0 && !conditional {
1173 // A gain may not drop more than 16 steps below the last one.
1174 *prev_ind = (indices[k] as i32).max(*prev_ind - 16);
1175 } else {
1176 let ind_tmp = indices[k] as i32 + MIN_DELTA_GAIN_QUANT;
1177 let threshold = 2 * MAX_DELTA_GAIN_QUANT - N_LEVELS_QGAIN + *prev_ind;
1178 if ind_tmp > threshold {
1179 *prev_ind += (ind_tmp << 1) - threshold;
1180 } else {
1181 *prev_ind += ind_tmp;
1182 }
1183 }
1184 *prev_ind = (*prev_ind).clamp(0, N_LEVELS_QGAIN - 1);
1185 gains[k] = log2lin((smulwb(GAIN_INV_SCALE_Q16, *prev_ind) + GAIN_OFFSET).min(3967));
1186 }
1187 gains
1188}
1189
1190/// `silk_decode_pitch` (Section 4.2.7.6.1).
1191pub(crate) fn decode_pitch(
1192 lag_index: i32,
1193 contour_index: i32,
1194 fs_khz: i32,
1195 nb_subfr: usize,
1196) -> [i32; MAX_NB_SUBFR] {
1197 let mut pitch = [0i32; MAX_NB_SUBFR];
1198 let min_lag = PE_MIN_LAG_MS * fs_khz;
1199 let max_lag = PE_MAX_LAG_MS * fs_khz;
1200 let lag = min_lag + lag_index;
1201 for k in 0..nb_subfr {
1202 let offset = if fs_khz == 8 {
1203 if nb_subfr == 4 {
1204 CB_LAGS_STAGE2[k][contour_index as usize]
1205 } else {
1206 CB_LAGS_STAGE2_10_MS[k][contour_index as usize]
1207 }
1208 } else if nb_subfr == 4 {
1209 CB_LAGS_STAGE3[k][contour_index as usize]
1210 } else {
1211 CB_LAGS_STAGE3_10_MS[k][contour_index as usize]
1212 };
1213 pitch[k] = (lag + offset as i32).clamp(min_lag, max_lag);
1214 }
1215 pitch
1216}
1217
1218/// `silk_decode_parameters`.
1219fn decode_parameters(ch: &mut ChannelState, cond: CondCoding) -> FrameCtrl {
1220 let mut ctrl = FrameCtrl {
1221 gains_q16: gains_dequant(
1222 &ch.indices.gains,
1223 &mut ch.last_gain_index,
1224 cond == CondCoding::Conditionally,
1225 ch.nb_subfr,
1226 ),
1227 ..Default::default()
1228 };
1229 let cb = nlsf_cb(ch.wb_codebook);
1230 let nlsf_q15 = nlsf_decode(&ch.indices.nlsf, cb);
1231 ctrl.pred_coef_q12[1] = nlsf2a(&nlsf_q15[..ch.lpc_order], ch.lpc_order);
1232
1233 if ch.first_frame_after_reset {
1234 ch.indices.nlsf_interp_coef_q2 = 4;
1235 }
1236 if ch.indices.nlsf_interp_coef_q2 < 4 {
1237 // Interpolate the first half of the frame from the previous LSFs.
1238 let mut nlsf0 = [0i16; MAX_LPC_ORDER];
1239 for i in 0..ch.lpc_order {
1240 nlsf0[i] = (ch.prev_nlsf_q15[i] as i32
1241 + ((ch.indices.nlsf_interp_coef_q2
1242 * (nlsf_q15[i] as i32 - ch.prev_nlsf_q15[i] as i32))
1243 >> 2)) as i16;
1244 }
1245 ctrl.pred_coef_q12[0] = nlsf2a(&nlsf0[..ch.lpc_order], ch.lpc_order);
1246 } else {
1247 ctrl.pred_coef_q12[0] = ctrl.pred_coef_q12[1];
1248 }
1249 ch.prev_nlsf_q15[..ch.lpc_order].copy_from_slice(&nlsf_q15[..ch.lpc_order]);
1250 if ch.loss_cnt != 0 {
1251 let order = ch.lpc_order;
1252 bwexpander(&mut ctrl.pred_coef_q12[0][..order], BWE_AFTER_LOSS_Q16);
1253 bwexpander(&mut ctrl.pred_coef_q12[1][..order], BWE_AFTER_LOSS_Q16);
1254 }
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_bwexpander`: moves the LPC poles towards the origin.
1280fn bwexpander(ar: &mut [i16], mut chirp_q16: i32) {
1281 let chirp_minus_one = chirp_q16 - 65536;
1282 let d = ar.len();
1283 for coef in ar.iter_mut().take(d - 1) {
1284 *coef = rshift_round(chirp_q16.wrapping_mul(*coef as i32), 16) as i16;
1285 chirp_q16 += rshift_round(chirp_q16.wrapping_mul(chirp_minus_one), 16);
1286 }
1287 ar[d - 1] = rshift_round(chirp_q16.wrapping_mul(ar[d - 1] as i32), 16) as i16;
1288}
1289
1290/// `silk_sum_sqr_shift`: energy of `x` scaled down to fit, and the shift used.
1291fn sum_sqr_shift(x: &[i16]) -> (i32, i32) {
1292 let len = x.len();
1293 let sq = |i: usize| (x[i] as i32).wrapping_mul(x[i] as i32) as u32;
1294 let energy = |shft: i32| {
1295 let mut nrg = 0u32;
1296 let mut i = 0;
1297 while i + 1 < len {
1298 nrg = nrg.wrapping_add((sq(i).wrapping_add(sq(i + 1))) >> shft);
1299 i += 2;
1300 }
1301 if i < len {
1302 nrg = nrg.wrapping_add(sq(i) >> shft);
1303 }
1304 nrg
1305 };
1306 let mut shft = 31 - clz32(len as i32);
1307 let first = (len as u32).wrapping_add(energy(shft));
1308 shft = (shft + 3 - clz32(first as i32)).max(0);
1309 let nrg = energy(shft);
1310 (nrg as i32, shft)
1311}
1312
1313/// `silk_PLC_energy`: energies of the last two subframes' excitation.
1314fn plc_energy(
1315 exc_q14: &[i32],
1316 prev_gain_q10: [i32; 2],
1317 subfr_length: usize,
1318 nb_subfr: usize,
1319) -> (i32, i32, i32, i32) {
1320 let mut exc_buf = [0i16; 2 * 80];
1321 for k in 0..2 {
1322 for i in 0..subfr_length {
1323 let x = exc_q14[i + (k + nb_subfr - 2) * subfr_length];
1324 exc_buf[k * subfr_length + i] = sat16(smulww(x, prev_gain_q10[k]) >> 8);
1325 }
1326 }
1327 let (e1, s1) = sum_sqr_shift(&exc_buf[..subfr_length]);
1328 let (e2, s2) = sum_sqr_shift(&exc_buf[subfr_length..2 * subfr_length]);
1329 (e1, s1, e2, s2)
1330}
1331
1332impl ChannelState {
1333 /// `silk_PLC_Reset`.
1334 fn plc_reset(&mut self) {
1335 self.plc.pitch_l_q8 = (self.frame_length as i32) << 7;
1336 self.plc.prev_gain_q16 = [1 << 16; 2];
1337 self.plc.subfr_length = 20;
1338 self.plc.nb_subfr = 2;
1339 }
1340
1341 /// `silk_PLC`: conceals a lost frame, or tracks the state of a coded one.
1342 fn plc_frame(&mut self, ctrl: &mut FrameCtrl, out: &mut [i16], lost: bool) {
1343 if self.fs_khz != self.plc.fs_khz {
1344 self.plc_reset();
1345 self.plc.fs_khz = self.fs_khz;
1346 }
1347 if lost {
1348 self.plc_conceal(ctrl, out);
1349 self.loss_cnt += 1;
1350 } else {
1351 self.plc_update(ctrl);
1352 }
1353 }
1354
1355 /// `silk_PLC_update`: remembers the pitch, LPC and gains of a coded frame.
1356 fn plc_update(&mut self, ctrl: &FrameCtrl) {
1357 let nb = self.nb_subfr;
1358 self.prev_signal_type = self.indices.signal_type;
1359 let mut ltp_gain_q14 = 0i32;
1360 if self.indices.signal_type == TYPE_VOICED {
1361 let mut j = 0usize;
1362 while ((j * self.subfr_length) as i32) < ctrl.pitch_l[nb - 1] {
1363 if j == nb {
1364 break;
1365 }
1366 let k = nb - 1 - j;
1367 let coefs = &ctrl.ltp_coef_q14[k * LTP_ORDER..(k + 1) * LTP_ORDER];
1368 let temp: i32 = coefs.iter().map(|&c| c as i32).sum();
1369 if temp > ltp_gain_q14 {
1370 ltp_gain_q14 = temp;
1371 self.plc.ltp_coef_q14.copy_from_slice(coefs);
1372 self.plc.pitch_l_q8 = ctrl.pitch_l[k] << 8;
1373 }
1374 j += 1;
1375 }
1376 self.plc.ltp_coef_q14 = [0; LTP_ORDER];
1377 self.plc.ltp_coef_q14[LTP_ORDER / 2] = ltp_gain_q14 as i16;
1378 if ltp_gain_q14 < V_PITCH_GAIN_START_MIN_Q14 {
1379 let tmp = V_PITCH_GAIN_START_MIN_Q14 << 10;
1380 let scale_q10 = tmp / ltp_gain_q14.max(1);
1381 for c in self.plc.ltp_coef_q14.iter_mut() {
1382 *c = (smulbb(*c as i32, scale_q10) >> 10) as i16;
1383 }
1384 } else if ltp_gain_q14 > V_PITCH_GAIN_START_MAX_Q14 {
1385 let tmp = V_PITCH_GAIN_START_MAX_Q14 << 14;
1386 let scale_q14 = tmp / ltp_gain_q14.max(1);
1387 for c in self.plc.ltp_coef_q14.iter_mut() {
1388 *c = (smulbb(*c as i32, scale_q14) >> 14) as i16;
1389 }
1390 }
1391 } else {
1392 self.plc.pitch_l_q8 = smulbb(self.fs_khz as i32, MAX_PITCH_LAG_MS) << 8;
1393 self.plc.ltp_coef_q14 = [0; LTP_ORDER];
1394 }
1395 let order = self.lpc_order;
1396 self.plc.prev_lpc_q12[..order].copy_from_slice(&ctrl.pred_coef_q12[1][..order]);
1397 self.plc.prev_ltp_scale_q14 = ctrl.ltp_scale_q14 as i16;
1398 self.plc.prev_gain_q16 = [ctrl.gains_q16[nb - 2], ctrl.gains_q16[nb - 1]];
1399 self.plc.subfr_length = self.subfr_length;
1400 self.plc.nb_subfr = nb;
1401 }
1402
1403 /// `silk_PLC_conceal`: synthesises one lost frame from the saved state.
1404 fn plc_conceal(&mut self, ctrl: &mut FrameCtrl, out: &mut [i16]) {
1405 let order = self.lpc_order;
1406 let ltp_mem = self.ltp_mem_length;
1407 let prev_gain_q10 = [
1408 self.plc.prev_gain_q16[0] >> 6,
1409 self.plc.prev_gain_q16[1] >> 6,
1410 ];
1411 if self.first_frame_after_reset {
1412 self.plc.prev_lpc_q12 = [0; MAX_LPC_ORDER];
1413 }
1414 let (energy1, shift1, energy2, shift2) = plc_energy(
1415 &self.exc_q14,
1416 prev_gain_q10,
1417 self.subfr_length,
1418 self.nb_subfr,
1419 );
1420 let rand_base = if (energy1 >> shift2) < (energy2 >> shift1) {
1421 ((self.plc.nb_subfr - 1) * self.plc.subfr_length).saturating_sub(RAND_BUF_SIZE)
1422 } else {
1423 (self.plc.nb_subfr * self.plc.subfr_length).saturating_sub(RAND_BUF_SIZE)
1424 };
1425
1426 let mut b_q14 = self.plc.ltp_coef_q14;
1427 let mut rand_scale_q14 = self.plc.rand_scale_q14 as i32;
1428 let att = self.loss_cnt.min(NB_ATT as i32 - 1) as usize;
1429 let harm_gain_q15 = HARM_ATT_Q15[att];
1430 let mut rand_gain_q15 = if self.prev_signal_type == TYPE_VOICED {
1431 PLC_RAND_ATTENUATE_V_Q15[att]
1432 } else {
1433 PLC_RAND_ATTENUATE_UV_Q15[att]
1434 };
1435
1436 bwexpander(&mut self.plc.prev_lpc_q12[..order], BWE_COEF_Q16);
1437 let a_q12 = self.plc.prev_lpc_q12;
1438
1439 if self.loss_cnt == 0 {
1440 rand_scale_q14 = 1 << 14;
1441 if self.prev_signal_type == TYPE_VOICED {
1442 for &b in b_q14.iter() {
1443 rand_scale_q14 -= b as i32;
1444 }
1445 rand_scale_q14 = rand_scale_q14.max(3277);
1446 rand_scale_q14 = smulbb(rand_scale_q14, self.plc.prev_ltp_scale_q14 as i32) >> 14;
1447 } else {
1448 let inv_gain_q30 = lpc_inverse_pred_gain(&self.plc.prev_lpc_q12[..order]);
1449 let mut down_scale_q30 =
1450 ((1 << 30) >> LOG2_INV_LPC_GAIN_HIGH_THRES).min(inv_gain_q30);
1451 down_scale_q30 = ((1 << 30) >> LOG2_INV_LPC_GAIN_LOW_THRES).max(down_scale_q30);
1452 down_scale_q30 <<= LOG2_INV_LPC_GAIN_HIGH_THRES;
1453 rand_gain_q15 = smulwb(down_scale_q30, rand_gain_q15) >> 14;
1454 }
1455 }
1456
1457 let mut rand_seed = self.plc.rand_seed;
1458 let mut lag = rshift_round(self.plc.pitch_l_q8, 8);
1459 let idx = (ltp_mem as i32 - lag - order as i32 - (LTP_ORDER / 2) as i32) as usize;
1460 let mut s_ltp = [0i16; MAX_LTP_MEM];
1461 lpc_analysis_filter(
1462 &mut s_ltp[idx..ltp_mem],
1463 &self.out_buf[idx..ltp_mem],
1464 &a_q12,
1465 ltp_mem - idx,
1466 order,
1467 );
1468 let inv_gain_q30 = inverse32_var_q(self.plc.prev_gain_q16[1], 46).min(i32::MAX >> 1);
1469 let mut s_ltp_q14 = [0i32; MAX_LTP_MEM + MAX_FRAME_LENGTH];
1470 for i in idx + order..ltp_mem {
1471 s_ltp_q14[i] = smulwb(inv_gain_q30, s_ltp[i] as i32);
1472 }
1473
1474 let mut sltp_buf_idx = ltp_mem;
1475 for _ in 0..self.nb_subfr {
1476 let pred0 = sltp_buf_idx + LTP_ORDER / 2 - lag as usize;
1477 for i in 0..self.subfr_length {
1478 let pred = pred0 + i;
1479 let mut ltp_pred_q12 = 2i32;
1480 for j in 0..LTP_ORDER {
1481 ltp_pred_q12 = smlawb(ltp_pred_q12, s_ltp_q14[pred - j], b_q14[j] as i32);
1482 }
1483 rand_seed = silk_rand(rand_seed);
1484 let ridx = ((rand_seed >> 25) & RAND_BUF_MASK) as usize;
1485 s_ltp_q14[sltp_buf_idx] =
1486 smlawb(ltp_pred_q12, self.exc_q14[rand_base + ridx], rand_scale_q14) << 2;
1487 sltp_buf_idx += 1;
1488 }
1489 for b in b_q14.iter_mut() {
1490 *b = (smulbb(harm_gain_q15, *b as i32) >> 15) as i16;
1491 }
1492 rand_scale_q14 = smulbb(rand_scale_q14, rand_gain_q15) >> 15;
1493 self.plc.pitch_l_q8 = smlawb(
1494 self.plc.pitch_l_q8,
1495 self.plc.pitch_l_q8,
1496 PITCH_DRIFT_FAC_Q16,
1497 );
1498 self.plc.pitch_l_q8 = self
1499 .plc
1500 .pitch_l_q8
1501 .min(smulbb(MAX_PITCH_LAG_MS, self.fs_khz as i32) << 8);
1502 lag = rshift_round(self.plc.pitch_l_q8, 8);
1503 }
1504
1505 let base = ltp_mem - MAX_LPC_ORDER;
1506 s_ltp_q14[base..base + MAX_LPC_ORDER].copy_from_slice(&self.s_lpc_q14);
1507 for i in 0..self.frame_length {
1508 let s = base + MAX_LPC_ORDER + i;
1509 let mut lpc_pred_q10 = (order >> 1) as i32;
1510 for j in 0..order {
1511 lpc_pred_q10 = smlawb(lpc_pred_q10, s_ltp_q14[s - j - 1], a_q12[j] as i32);
1512 }
1513 s_ltp_q14[s] = s_ltp_q14[s].saturating_add(lshift_sat32(lpc_pred_q10, 4));
1514 out[i] = sat16(rshift_round(smulww(s_ltp_q14[s], prev_gain_q10[1]), 8));
1515 }
1516 let end = base + self.frame_length;
1517 self.s_lpc_q14
1518 .copy_from_slice(&s_ltp_q14[end..end + MAX_LPC_ORDER]);
1519
1520 self.plc.rand_seed = rand_seed;
1521 self.plc.rand_scale_q14 = rand_scale_q14 as i16;
1522 self.plc.ltp_coef_q14 = b_q14;
1523 ctrl.pitch_l = [lag; MAX_NB_SUBFR];
1524 }
1525
1526 /// `silk_PLC_glue_frames`: smooths the start of the first frame after a loss.
1527 fn plc_glue_frames(&mut self, frame: &mut [i16]) {
1528 let length = frame.len() as i32;
1529 if self.loss_cnt != 0 {
1530 let (e, s) = sum_sqr_shift(frame);
1531 self.plc.conc_energy = e;
1532 self.plc.conc_energy_shift = s;
1533 self.plc.last_frame_lost = true;
1534 return;
1535 }
1536 if self.plc.last_frame_lost {
1537 let (mut energy, energy_shift) = sum_sqr_shift(frame);
1538 if energy_shift > self.plc.conc_energy_shift {
1539 self.plc.conc_energy >>= energy_shift - self.plc.conc_energy_shift;
1540 } else if energy_shift < self.plc.conc_energy_shift {
1541 energy >>= self.plc.conc_energy_shift - energy_shift;
1542 }
1543 if energy > self.plc.conc_energy {
1544 let lz = clz32(self.plc.conc_energy) - 1;
1545 self.plc.conc_energy <<= lz;
1546 energy >>= (24 - lz).max(0);
1547 let frac_q24 = self.plc.conc_energy / energy.max(1);
1548 let mut gain_q16 = sqrt_approx(frac_q24) << 4;
1549 let mut slope_q16 = ((1 << 16) - gain_q16) / length;
1550 slope_q16 <<= 2;
1551 for v in frame.iter_mut() {
1552 *v = smulwb(gain_q16, *v as i32) as i16;
1553 gain_q16 += slope_q16;
1554 if gain_q16 > (1 << 16) {
1555 break;
1556 }
1557 }
1558 }
1559 }
1560 self.plc.last_frame_lost = false;
1561 }
1562}
1563
1564/// `silk_CNG_exc`: draws the comfort noise excitation from the saved history.
1565fn cng_exc(exc: &mut [i32], exc_buf: &[i32], rand_seed: &mut i32) {
1566 let mut exc_mask = CNG_BUF_MASK_MAX;
1567 while exc_mask > exc.len() as i32 {
1568 exc_mask >>= 1;
1569 }
1570 let mut seed = *rand_seed;
1571 for v in exc.iter_mut() {
1572 seed = silk_rand(seed);
1573 let idx = ((seed >> 24) & exc_mask) as usize;
1574 *v = exc_buf[idx];
1575 }
1576 *rand_seed = seed;
1577}
1578
1579impl ChannelState {
1580 /// `silk_CNG_Reset`.
1581 fn cng_reset(&mut self) {
1582 let order = self.lpc_order;
1583 let step = 32767 / (order as i32 + 1);
1584 let mut acc = 0i32;
1585 for i in 0..order {
1586 acc += step;
1587 self.cng.smth_nlsf_q15[i] = acc as i16;
1588 }
1589 self.cng.smth_gain_q16 = 0;
1590 self.cng.rand_seed = 3176576;
1591 }
1592
1593 /// `silk_CNG`: mixes comfort noise into `frame`.
1594 fn cng(&mut self, ctrl: &FrameCtrl, frame: &mut [i16]) {
1595 if self.fs_khz != self.cng.fs_khz {
1596 self.cng_reset();
1597 self.cng.fs_khz = self.fs_khz;
1598 }
1599 let order = self.lpc_order;
1600 let sl = self.subfr_length;
1601 let nb = self.nb_subfr;
1602 if self.loss_cnt == 0 && self.prev_signal_type == TYPE_NO_VOICE_ACTIVITY {
1603 for i in 0..order {
1604 let d = self.prev_nlsf_q15[i] as i32 - self.cng.smth_nlsf_q15[i] as i32;
1605 self.cng.smth_nlsf_q15[i] =
1606 (self.cng.smth_nlsf_q15[i] as i32 + smulwb(d, CNG_NLSF_SMTH_Q16)) as i16;
1607 }
1608 let mut max_gain = 0;
1609 let mut subfr = 0;
1610 for i in 0..nb {
1611 if ctrl.gains_q16[i] > max_gain {
1612 max_gain = ctrl.gains_q16[i];
1613 subfr = i;
1614 }
1615 }
1616 self.cng.exc_buf_q14.copy_within(0..(nb - 1) * sl, sl);
1617 self.cng.exc_buf_q14[..sl].copy_from_slice(&self.exc_q14[subfr * sl..(subfr + 1) * sl]);
1618 for i in 0..nb {
1619 let g = ctrl.gains_q16[i];
1620 self.cng.smth_gain_q16 += smulwb(g - self.cng.smth_gain_q16, CNG_GAIN_SMTH_Q16);
1621 if smulww(self.cng.smth_gain_q16, CNG_GAIN_SMTH_THRESHOLD_Q16) > g {
1622 self.cng.smth_gain_q16 = g;
1623 }
1624 }
1625 }
1626 if self.loss_cnt != 0 {
1627 let length = frame.len();
1628 let smth = self.cng.smth_gain_q16;
1629 let mut gain_q16 = smulww(self.plc.rand_scale_q14 as i32, self.plc.prev_gain_q16[1]);
1630 if gain_q16 >= 1 << 21 || smth > 1 << 23 {
1631 gain_q16 = smultt(gain_q16, gain_q16);
1632 gain_q16 = smultt(smth, smth).wrapping_sub(gain_q16 << 5);
1633 gain_q16 = sqrt_approx(gain_q16) << 16;
1634 } else {
1635 gain_q16 = smulww(gain_q16, gain_q16);
1636 gain_q16 = smulww(smth, smth).wrapping_sub(gain_q16 << 5);
1637 gain_q16 = sqrt_approx(gain_q16) << 8;
1638 }
1639 let gain_q10 = gain_q16 >> 6;
1640
1641 let mut sig = [0i32; MAX_FRAME_LENGTH + MAX_LPC_ORDER];
1642 cng_exc(
1643 &mut sig[MAX_LPC_ORDER..MAX_LPC_ORDER + length],
1644 &self.cng.exc_buf_q14,
1645 &mut self.cng.rand_seed,
1646 );
1647 let a_q12 = nlsf2a(&self.cng.smth_nlsf_q15, order);
1648 sig[..MAX_LPC_ORDER].copy_from_slice(&self.cng.synth_state);
1649 for i in 0..length {
1650 let mut pred = (order >> 1) as i32;
1651 for j in 0..order {
1652 pred = smlawb(pred, sig[MAX_LPC_ORDER + i - j - 1], a_q12[j] as i32);
1653 }
1654 let s = MAX_LPC_ORDER + i;
1655 sig[s] = sig[s].saturating_add(lshift_sat32(pred, 4));
1656 let noise = sat16(rshift_round(smulww(sig[s], gain_q10), 8));
1657 frame[i] = sat16(frame[i] as i32 + noise as i32);
1658 }
1659 self.cng
1660 .synth_state
1661 .copy_from_slice(&sig[length..length + MAX_LPC_ORDER]);
1662 } else {
1663 self.cng.synth_state[..order].fill(0);
1664 }
1665 }
1666}
1667
1668/// `silk_LPC_analysis_filter`: the whitening filter used to rebuild the LTP
1669/// state from previously decoded output.
1670pub(crate) fn lpc_analysis_filter(
1671 out: &mut [i16],
1672 input: &[i16],
1673 b_q12: &[i16],
1674 len: usize,
1675 d: usize,
1676) {
1677 for ix in d..len {
1678 let mut acc = 0i32;
1679 for j in 0..d {
1680 acc = acc.wrapping_add(smulbb(input[ix - 1 - j] as i32, b_q12[j] as i32));
1681 }
1682 let v = ((input[ix] as i32) << 12).wrapping_sub(acc);
1683 out[ix] = sat16(rshift_round(v, 12));
1684 }
1685 out[..d].fill(0);
1686}
1687
1688/// `silk_decode_core` (Section 4.2.7.9): excitation to output samples.
1689fn decode_core(ch: &mut ChannelState, ctrl: &mut FrameCtrl, xq: &mut [i16], pulses: &[i32]) {
1690 let offset_q10 = QUANTIZATION_OFFSETS_Q10[ch.indices.signal_type as usize >> 1]
1691 [ch.indices.quant_offset_type as usize] as i32;
1692 let nlsf_interpolated = ch.indices.nlsf_interp_coef_q2 < 4;
1693
1694 // Excitation: pulses with a quantisation offset and a pseudo-random sign.
1695 let mut rand_seed = ch.indices.seed;
1696 for i in 0..ch.frame_length {
1697 rand_seed = silk_rand(rand_seed);
1698 let mut e = pulses[i] << 14;
1699 if e > 0 {
1700 e -= QUANT_LEVEL_ADJUST_Q10 << 4;
1701 } else if e < 0 {
1702 e += QUANT_LEVEL_ADJUST_Q10 << 4;
1703 }
1704 e += offset_q10 << 4;
1705 ch.exc_q14[i] = if rand_seed < 0 { -e } else { e };
1706 rand_seed = rand_seed.wrapping_add(pulses[i]);
1707 }
1708
1709 let mut s_lpc_q14 = [0i32; MAX_LPC_ORDER + 5 * 16];
1710 s_lpc_q14[..MAX_LPC_ORDER].copy_from_slice(&ch.s_lpc_q14);
1711 let mut s_ltp = [0i16; MAX_FRAME_LENGTH];
1712 let mut s_ltp_q15 = [0i32; 2 * MAX_FRAME_LENGTH];
1713 let mut sltp_buf_idx = ch.ltp_mem_length;
1714 let mut lag = 0usize;
1715 let mut res_q14 = [0i32; 5 * 16];
1716
1717 for k in 0..ch.nb_subfr {
1718 let mut signal_type = ch.indices.signal_type;
1719 // Avoid an abrupt switch from voiced PLC to unvoiced normal decoding.
1720 if ch.loss_cnt != 0
1721 && ch.prev_signal_type == TYPE_VOICED
1722 && ch.indices.signal_type != TYPE_VOICED
1723 && k < MAX_NB_SUBFR / 2
1724 {
1725 let b = &mut ctrl.ltp_coef_q14[k * LTP_ORDER..(k + 1) * LTP_ORDER];
1726 b.fill(0);
1727 b[LTP_ORDER / 2] = 4096;
1728 signal_type = TYPE_VOICED;
1729 ctrl.pitch_l[k] = ch.lag_prev;
1730 }
1731 let a_q12 = &ctrl.pred_coef_q12[k >> 1];
1732 let b_q14 = &ctrl.ltp_coef_q14[k * LTP_ORDER..k * LTP_ORDER + LTP_ORDER];
1733 let gain_q10 = ctrl.gains_q16[k] >> 6;
1734 let mut inv_gain_q31 = inverse32_var_q(ctrl.gains_q16[k], 47);
1735 let gain_adj_q16 = if ctrl.gains_q16[k] != ch.prev_gain_q16 {
1736 let adj = div32_var_q(ch.prev_gain_q16, ctrl.gains_q16[k], 16);
1737 for v in s_lpc_q14.iter_mut().take(MAX_LPC_ORDER) {
1738 *v = smulww(adj, *v);
1739 }
1740 adj
1741 } else {
1742 1 << 16
1743 };
1744 ch.prev_gain_q16 = ctrl.gains_q16[k];
1745
1746 if signal_type == TYPE_VOICED {
1747 lag = ctrl.pitch_l[k] as usize;
1748 if k == 0 || (k == 2 && nlsf_interpolated) {
1749 // Rebuild the LTP history by whitening past output.
1750 let start_idx = ch.ltp_mem_length - lag - ch.lpc_order - LTP_ORDER / 2;
1751 if k == 2 {
1752 let n = 2 * ch.subfr_length;
1753 let base = ch.ltp_mem_length;
1754 ch.out_buf[base..base + n].copy_from_slice(&xq[..n]);
1755 }
1756 lpc_analysis_filter(
1757 &mut s_ltp[start_idx..],
1758 &ch.out_buf[start_idx + k * ch.subfr_length..],
1759 a_q12,
1760 ch.ltp_mem_length - start_idx,
1761 ch.lpc_order,
1762 );
1763 if k == 0 {
1764 inv_gain_q31 = smulwb(inv_gain_q31, ctrl.ltp_scale_q14) << 2;
1765 }
1766 for i in 0..lag + LTP_ORDER / 2 {
1767 s_ltp_q15[sltp_buf_idx - i - 1] =
1768 smulwb(inv_gain_q31, s_ltp[ch.ltp_mem_length - i - 1] as i32);
1769 }
1770 } else if gain_adj_q16 != 1 << 16 {
1771 for i in 0..lag + LTP_ORDER / 2 {
1772 s_ltp_q15[sltp_buf_idx - i - 1] =
1773 smulww(gain_adj_q16, s_ltp_q15[sltp_buf_idx - i - 1]);
1774 }
1775 }
1776 }
1777
1778 // Long-term prediction.
1779 let exc_base = k * ch.subfr_length;
1780 let pres_q14: &[i32] = if signal_type == TYPE_VOICED {
1781 let pred_base = sltp_buf_idx - lag + LTP_ORDER / 2;
1782 for i in 0..ch.subfr_length {
1783 let pred_idx = pred_base + i;
1784 let mut ltp_pred_q13 = 2i32;
1785 for (j, &b) in b_q14.iter().enumerate() {
1786 ltp_pred_q13 = smlawb(ltp_pred_q13, s_ltp_q15[pred_idx - j], b as i32);
1787 }
1788 res_q14[i] = ch.exc_q14[exc_base + i].wrapping_add(ltp_pred_q13 << 1);
1789 s_ltp_q15[sltp_buf_idx] = res_q14[i] << 1;
1790 sltp_buf_idx += 1;
1791 }
1792 &res_q14[..ch.subfr_length]
1793 } else {
1794 &ch.exc_q14[exc_base..exc_base + ch.subfr_length]
1795 };
1796
1797 // Short-term (LPC) synthesis.
1798 for i in 0..ch.subfr_length {
1799 let mut lpc_pred_q10 = (ch.lpc_order >> 1) as i32;
1800 for j in 0..ch.lpc_order {
1801 lpc_pred_q10 = smlawb(
1802 lpc_pred_q10,
1803 s_lpc_q14[MAX_LPC_ORDER + i - 1 - j],
1804 a_q12[j] as i32,
1805 );
1806 }
1807 s_lpc_q14[MAX_LPC_ORDER + i] = pres_q14[i].wrapping_add(lpc_pred_q10 << 4);
1808 xq[k * ch.subfr_length + i] = sat16(rshift_round(
1809 smulww(s_lpc_q14[MAX_LPC_ORDER + i], gain_q10),
1810 8,
1811 ));
1812 }
1813 s_lpc_q14.copy_within(ch.subfr_length..ch.subfr_length + MAX_LPC_ORDER, 0);
1814 }
1815 ch.s_lpc_q14.copy_from_slice(&s_lpc_q14[..MAX_LPC_ORDER]);
1816}
1817
1818/// `silk_decode_frame`: one SILK frame of one channel.
1819fn decode_frame(
1820 ch: &mut ChannelState,
1821 dec: &mut RangeDecoder,
1822 out: &mut [i16],
1823 cond: CondCoding,
1824 lbrr: bool,
1825 coded: bool,
1826) -> usize {
1827 let mut ctrl = FrameCtrl::default();
1828 if coded {
1829 let frame_index = ch.frames_decoded;
1830 decode_indices(ch, dec, frame_index, lbrr, cond);
1831 let mut pulses = [0i32; MAX_FRAME_LENGTH + SHELL_LEN];
1832 decode_pulses(
1833 dec,
1834 &mut pulses,
1835 ch.frame_length,
1836 ch.indices.signal_type,
1837 ch.indices.quant_offset_type,
1838 );
1839 ctrl = decode_parameters(ch, cond);
1840 if cond == CondCoding::IndependentlyNoLtpScaling {
1841 ctrl.ltp_scale_q14 = LTPSCALES_TABLE_Q14[0] as i32;
1842 }
1843 decode_core(ch, &mut ctrl, out, &pulses);
1844 ch.plc_frame(&mut ctrl, out, false);
1845 ch.loss_cnt = 0;
1846 ch.prev_signal_type = ch.indices.signal_type;
1847 ch.first_frame_after_reset = false;
1848 } else {
1849 ch.plc_frame(&mut ctrl, out, true);
1850 }
1851
1852 // Slide the synthesis history.
1853 let fl = ch.frame_length;
1854 let mv_len = ch.ltp_mem_length - fl;
1855 ch.out_buf.copy_within(fl..fl + mv_len, 0);
1856 ch.out_buf[mv_len..mv_len + fl].copy_from_slice(&out[..fl]);
1857 ch.cng(&ctrl, &mut out[..fl]);
1858 ch.plc_glue_frames(&mut out[..fl]);
1859 ch.lag_prev = ctrl.pitch_l[ch.nb_subfr - 1];
1860 fl
1861}
1862
1863/// `silk_stereo_decode_pred` (Section 4.2.7.1).
1864fn stereo_decode_pred(dec: &mut RangeDecoder, pred_q13: &mut [i32; 2]) {
1865 let n = dec.dec_icdf(&STEREO_PRED_JOINT_ICDF, 8) as i32;
1866 let mut ix = [[0i32; 3]; 2];
1867 ix[0][2] = n / 5;
1868 ix[1][2] = n - 5 * ix[0][2];
1869 for row in ix.iter_mut() {
1870 row[0] = dec.dec_icdf(&UNIFORM3_ICDF, 8) as i32;
1871 row[1] = dec.dec_icdf(&UNIFORM5_ICDF, 8) as i32;
1872 }
1873 for n in 0..2 {
1874 let i0 = (ix[n][0] + 3 * ix[n][2]) as usize;
1875 let low = STEREO_PRED_QUANT_Q13[i0] as i32;
1876 // 0.5/5 in Q16.
1877 let step = smulwb(STEREO_PRED_QUANT_Q13[i0 + 1] as i32 - low, 6554);
1878 pred_q13[n] = smlabb(low, step, 2 * ix[n][1] + 1);
1879 }
1880 pred_q13[0] -= pred_q13[1];
1881}
1882
1883/// `silk_stereo_MS_to_LR` (Section 4.2.8): mid/side back to left/right.
1884fn stereo_ms_to_lr(
1885 state: &mut StereoState,
1886 x1: &mut [i16],
1887 x2: &mut [i16],
1888 pred_q13: &[i32; 2],
1889 fs_khz: usize,
1890 frame_length: usize,
1891) {
1892 x1[0] = state.s_mid[0];
1893 x1[1] = state.s_mid[1];
1894 x2[0] = state.s_side[0];
1895 x2[1] = state.s_side[1];
1896 state.s_mid[0] = x1[frame_length];
1897 state.s_mid[1] = x1[frame_length + 1];
1898 state.s_side[0] = x2[frame_length];
1899 state.s_side[1] = x2[frame_length + 1];
1900
1901 let interp = STEREO_INTERP_LEN_MS * fs_khz;
1902 let mut pred0 = state.pred_prev_q13[0];
1903 let mut pred1 = state.pred_prev_q13[1];
1904 let denom_q16 = (1i32 << 16) / interp as i32;
1905 let delta0 = rshift_round(smulbb(pred_q13[0] - state.pred_prev_q13[0], denom_q16), 16);
1906 let delta1 = rshift_round(smulbb(pred_q13[1] - state.pred_prev_q13[1], denom_q16), 16);
1907 for n in 0..frame_length {
1908 if n < interp {
1909 pred0 += delta0;
1910 pred1 += delta1;
1911 } else {
1912 pred0 = pred_q13[0];
1913 pred1 = pred_q13[1];
1914 }
1915 let sum = ((x1[n] as i32 + x1[n + 2] as i32) + ((x1[n + 1] as i32) << 1)) << 9;
1916 let mut acc = smlawb((x2[n + 1] as i32) << 8, sum, pred0);
1917 acc = smlawb(acc, (x1[n + 1] as i32) << 11, pred1);
1918 x2[n + 1] = sat16(rshift_round(acc, 8));
1919 }
1920 state.pred_prev_q13[0] = pred_q13[0];
1921 state.pred_prev_q13[1] = pred_q13[1];
1922
1923 for n in 0..frame_length {
1924 let sum = x1[n + 1] as i32 + x2[n + 1] as i32;
1925 let diff = x1[n + 1] as i32 - x2[n + 1] as i32;
1926 x1[n + 1] = sat16(sum);
1927 x2[n + 1] = sat16(diff);
1928 }
1929}
1930
1931// ---------------------------------------------------------------------------
1932// Resampling (Section 4.2.9)
1933// ---------------------------------------------------------------------------
1934
1935/// The SILK output resampler: 8/12/16 kHz internal to the API rate.
1936///
1937/// The RFC calls the resampler non-normative but its *delay* normative, so this
1938/// is the reference's structure — a 2x all-pass upsampler followed by a
1939/// 12-phase fractional FIR, with the same per-rate input delay.
1940#[derive(Clone, Debug, Default)]
1941pub(crate) struct Resampler {
1942 fs_in_khz: usize,
1943 fs_out_khz: usize,
1944 input_delay: usize,
1945 batch_size: usize,
1946 inv_ratio_q16: i32,
1947 /// All-pass state for the 2x upsampler.
1948 s_iir: [i32; 6],
1949 /// FIR history.
1950 s_fir: [i16; 8],
1951 delay_buf: DelayBuf,
1952 /// Upsampler scratch, allocated once.
1953 fir_buf: Vec<i16>,
1954 /// Down-sampling coefficients, when the output rate is the lower one.
1955 down: Option<DownFir>,
1956}
1957
1958/// Fixed-size delay line; a newtype only because `[i16; 48]` has no `Default`.
1959#[derive(Clone, Copy, Debug)]
1960struct DelayBuf([i16; 48]);
1961
1962impl Default for DelayBuf {
1963 fn default() -> Self {
1964 DelayBuf([0; 48])
1965 }
1966}
1967
1968impl core::ops::Deref for DelayBuf {
1969 type Target = [i16; 48];
1970 fn deref(&self) -> &[i16; 48] {
1971 &self.0
1972 }
1973}
1974
1975impl core::ops::DerefMut for DelayBuf {
1976 fn deref_mut(&mut self) -> &mut [i16; 48] {
1977 &mut self.0
1978 }
1979}
1980
1981#[derive(Clone, Debug)]
1982struct DownFir {
1983 fracs: usize,
1984 order: usize,
1985 coefs: &'static [i16],
1986 state: [i32; 2],
1987 buf: Vec<i32>,
1988}
1989
1990/// `rateID` in the reference: an index into the delay matrix.
1991fn rate_id(rate: usize) -> usize {
1992 (((rate >> 12) - usize::from(rate > 16000)) >> usize::from(rate > 24000)) - 1
1993}
1994
1995const DELAY_MATRIX_DEC: [[u8; 5]; 3] = [[4, 0, 2, 0, 0], [0, 9, 4, 7, 4], [0, 3, 12, 7, 7]];
1996
1997impl Resampler {
1998 pub(crate) fn new(fs_in_khz: usize, fs_out_khz: usize) -> Resampler {
1999 let input_delay =
2000 DELAY_MATRIX_DEC[rate_id(fs_in_khz * 1000)][rate_id(fs_out_khz * 1000)] as usize;
2001 Self::with_delay(fs_in_khz, fs_out_khz, input_delay)
2002 }
2003
2004 fn with_delay(fs_in_khz: usize, fs_out_khz: usize, input_delay: usize) -> Resampler {
2005 let fs_in = fs_in_khz * 1000;
2006 let fs_out = fs_out_khz * 1000;
2007 let mut r = Resampler {
2008 fs_in_khz,
2009 fs_out_khz,
2010 input_delay,
2011 batch_size: fs_in_khz * 10,
2012 ..Default::default()
2013 };
2014 let mut up2x = 0;
2015 if fs_out > fs_in && fs_out != 2 * fs_in {
2016 up2x = 1;
2017 } else if fs_out < fs_in {
2018 let (fracs, order, coefs): (usize, usize, &'static [i16]) = if fs_out * 4 == fs_in * 3 {
2019 (3, 18, &RESAMPLER_3_4_COEFS)
2020 } else if fs_out * 3 == fs_in * 2 {
2021 (2, 18, &RESAMPLER_2_3_COEFS)
2022 } else if fs_out * 2 == fs_in {
2023 (1, 24, &RESAMPLER_1_2_COEFS)
2024 } else if fs_out * 3 == fs_in {
2025 (1, 36, &RESAMPLER_1_3_COEFS)
2026 } else if fs_out * 4 == fs_in {
2027 (1, 36, &RESAMPLER_1_4_COEFS)
2028 } else {
2029 (1, 36, &RESAMPLER_1_6_COEFS)
2030 };
2031 r.down = Some(DownFir {
2032 fracs,
2033 order,
2034 coefs,
2035 state: [0; 2],
2036 buf: vec![0; 480 + 36],
2037 });
2038 }
2039 r.inv_ratio_q16 = ((((fs_in as i64) << (14 + up2x)) / fs_out as i64) as i32) << 2;
2040 while smulww(r.inv_ratio_q16, fs_out as i32) < ((fs_in as i32) << up2x) {
2041 r.inv_ratio_q16 += 1;
2042 }
2043 r
2044 }
2045
2046 /// Resamples `in_len` input samples into `in_len * out/in` outputs.
2047 ///
2048 /// The first `Fs_in_kHz` samples come from the delay line (the normative
2049 /// per-rate input delay); the rest are read straight from `input`, and its
2050 /// tail is kept for the next call.
2051 pub(crate) fn process(&mut self, out: &mut [i16], input: &[i16], in_len: usize) {
2052 let n_first = self.fs_in_khz - self.input_delay;
2053 let mut head = [0i16; 48];
2054 head[..self.input_delay].copy_from_slice(&self.delay_buf[..self.input_delay]);
2055 head[self.input_delay..self.fs_in_khz].copy_from_slice(&input[..n_first]);
2056 let n_head = self.fs_in_khz;
2057 let rest = &input[n_first..n_first + (in_len - self.fs_in_khz)];
2058 let split = self.fs_out_khz;
2059 let rest_out = (in_len - self.fs_in_khz) * self.fs_out_khz / self.fs_in_khz;
2060 if self.fs_in_khz == self.fs_out_khz {
2061 out[..n_head].copy_from_slice(&head[..n_head]);
2062 out[split..split + rest_out].copy_from_slice(rest);
2063 } else if self.down.is_some() {
2064 self.down_fir(&mut out[..split], &head[..n_head]);
2065 self.down_fir(&mut out[split..split + rest_out], rest);
2066 } else if self.fs_out_khz == 2 * self.fs_in_khz {
2067 self.up2_hq(&mut out[..split], &head[..n_head]);
2068 self.up2_hq(&mut out[split..split + rest_out], rest);
2069 } else {
2070 self.iir_fir(&mut out[..split], &head[..n_head]);
2071 self.iir_fir(&mut out[split..split + rest_out], rest);
2072 }
2073 self.delay_buf[..self.input_delay]
2074 .copy_from_slice(&input[in_len - self.input_delay..in_len]);
2075 }
2076
2077 /// `silk_resampler_private_up2_HQ`: 2x all-pass upsampling.
2078 fn up2_hq(&mut self, out: &mut [i16], input: &[i16]) {
2079 for (k, &sample) in input.iter().enumerate() {
2080 let in32 = (sample as i32) << 10;
2081 let mut y = in32 - self.s_iir[0];
2082 let mut x = smulwb(y, RESAMPLER_UP2_HQ_0[0] as i32);
2083 let mut out32_1 = self.s_iir[0] + x;
2084 self.s_iir[0] = in32 + x;
2085 y = out32_1 - self.s_iir[1];
2086 x = smulwb(y, RESAMPLER_UP2_HQ_0[1] as i32);
2087 let mut out32_2 = self.s_iir[1] + x;
2088 self.s_iir[1] = out32_1 + x;
2089 y = out32_2 - self.s_iir[2];
2090 x = smlawb(y, y, RESAMPLER_UP2_HQ_0[2] as i32);
2091 out32_1 = self.s_iir[2] + x;
2092 self.s_iir[2] = out32_2 + x;
2093 out[2 * k] = sat16(rshift_round(out32_1, 10));
2094
2095 y = in32 - self.s_iir[3];
2096 x = smulwb(y, RESAMPLER_UP2_HQ_1[0] as i32);
2097 out32_1 = self.s_iir[3] + x;
2098 self.s_iir[3] = in32 + x;
2099 y = out32_1 - self.s_iir[4];
2100 x = smulwb(y, RESAMPLER_UP2_HQ_1[1] as i32);
2101 out32_2 = self.s_iir[4] + x;
2102 self.s_iir[4] = out32_1 + x;
2103 y = out32_2 - self.s_iir[5];
2104 x = smlawb(y, y, RESAMPLER_UP2_HQ_1[2] as i32);
2105 out32_1 = self.s_iir[5] + x;
2106 self.s_iir[5] = out32_2 + x;
2107 out[2 * k + 1] = sat16(rshift_round(out32_1, 10));
2108 }
2109 }
2110
2111 /// `silk_resampler_private_IIR_FIR`: 2x upsample then fractional FIR.
2112 fn iir_fir(&mut self, out: &mut [i16], input: &[i16]) {
2113 let mut written = 0usize;
2114 let mut pos = 0usize;
2115 let mut buf = core::mem::take(&mut self.fir_buf);
2116 buf.clear();
2117 buf.resize(2 * self.batch_size + 8, 0);
2118 buf[..8].copy_from_slice(&self.s_fir);
2119 let mut n_samples_in = 0;
2120 while pos < input.len() {
2121 n_samples_in = (input.len() - pos).min(self.batch_size);
2122 self.up2_hq(
2123 &mut buf[8..8 + 2 * n_samples_in],
2124 &input[pos..pos + n_samples_in],
2125 );
2126 let max_index_q16 = (n_samples_in as i32) << 17;
2127 let mut index_q16 = 0i32;
2128 while index_q16 < max_index_q16 {
2129 let table_index = smulwb(index_q16 & 0xFFFF, 12) as usize;
2130 let b = &buf[(index_q16 >> 16) as usize..];
2131 let mut res = smulbb(b[0] as i32, RESAMPLER_FRAC_FIR_12[table_index][0] as i32);
2132 res = smlabb(
2133 res,
2134 b[1] as i32,
2135 RESAMPLER_FRAC_FIR_12[table_index][1] as i32,
2136 );
2137 res = smlabb(
2138 res,
2139 b[2] as i32,
2140 RESAMPLER_FRAC_FIR_12[table_index][2] as i32,
2141 );
2142 res = smlabb(
2143 res,
2144 b[3] as i32,
2145 RESAMPLER_FRAC_FIR_12[table_index][3] as i32,
2146 );
2147 res = smlabb(
2148 res,
2149 b[4] as i32,
2150 RESAMPLER_FRAC_FIR_12[11 - table_index][3] as i32,
2151 );
2152 res = smlabb(
2153 res,
2154 b[5] as i32,
2155 RESAMPLER_FRAC_FIR_12[11 - table_index][2] as i32,
2156 );
2157 res = smlabb(
2158 res,
2159 b[6] as i32,
2160 RESAMPLER_FRAC_FIR_12[11 - table_index][1] as i32,
2161 );
2162 res = smlabb(
2163 res,
2164 b[7] as i32,
2165 RESAMPLER_FRAC_FIR_12[11 - table_index][0] as i32,
2166 );
2167 if written < out.len() {
2168 out[written] = sat16(rshift_round(res, 15));
2169 }
2170 written += 1;
2171 index_q16 += self.inv_ratio_q16;
2172 }
2173 pos += n_samples_in;
2174 if pos < input.len() {
2175 buf.copy_within(2 * n_samples_in..2 * n_samples_in + 8, 0);
2176 }
2177 }
2178 self.s_fir
2179 .copy_from_slice(&buf[2 * n_samples_in..2 * n_samples_in + 8]);
2180 self.fir_buf = buf;
2181 }
2182
2183 /// `silk_resampler_private_down_FIR`, for output rates below the internal
2184 /// rate (an AR2 pre-filter, then a polyphase FIR).
2185 fn down_fir(&mut self, out: &mut [i16], input: &[i16]) {
2186 let inv_ratio = self.inv_ratio_q16;
2187 let d = self.down.as_mut().expect("down-sampling state");
2188 let order = d.order;
2189 let mut buf = core::mem::take(&mut d.buf);
2190 // AR2 pre-filter into Q8.
2191 let a_q14 = [d.coefs[0], d.coefs[1]];
2192 for (k, &s) in input.iter().enumerate() {
2193 let out32 = d.state[0] + ((s as i32) << 8);
2194 buf[order + k] = out32;
2195 let out32 = out32 << 2;
2196 d.state[0] = smlawb(d.state[1], out32, a_q14[0] as i32);
2197 d.state[1] = smulwb(out32, a_q14[1] as i32);
2198 }
2199 let fir = &d.coefs[2..];
2200 let fracs = d.fracs;
2201 let mut written = 0usize;
2202 let max_index_q16 = (input.len() as i32) << 16;
2203 let mut index_q16 = 0i32;
2204 while index_q16 < max_index_q16 && written < out.len() {
2205 let base = (index_q16 >> 16) as usize;
2206 let interpol_ind = smulwb(index_q16 & 0xFFFF, fracs as i32) as usize;
2207 let coefs = &fir[interpol_ind * (order / 2)..];
2208 let mut res = 0i64;
2209 for j in 0..order / 2 {
2210 res += buf[base + j] as i64 * coefs[j] as i64;
2211 res += buf[base + order - 1 - j] as i64 * coefs[j] as i64;
2212 }
2213 out[written] = sat16(rshift_round((res >> 16) as i32, 6));
2214 written += 1;
2215 index_q16 += inv_ratio;
2216 }
2217 let keep = order;
2218 buf.copy_within(input.len()..input.len() + keep, 0);
2219 d.buf = buf;
2220 }
2221}
2222
2223#[cfg(test)]
2224mod tests {
2225 use super::*;
2226
2227 #[test]
2228 fn fixed_point_helpers_match_their_definitions() {
2229 // Spot values computed from the reference macro definitions.
2230 assert_eq!(smulwb(1 << 20, 3), 48);
2231 assert_eq!(smulbb(-5, 7), -35);
2232 assert_eq!(rshift_round(7, 1), 4);
2233 assert_eq!(rshift_round(-7, 2), -2);
2234 assert_eq!(sat16(40000), 32767);
2235 assert_eq!(sat16(-40000), -32768);
2236 // log2lin is the exponential the gain quantiser uses: 2^(q/128).
2237 for q in [0i32, 128, 1000, 3967] {
2238 let got = log2lin(q) as f64;
2239 let want = (q as f64 / 128.0).exp2();
2240 assert!(
2241 (got - want).abs() / want < 0.02,
2242 "log2lin({q}) = {got}, want {want}"
2243 );
2244 }
2245 // sqrt_approx returns sqrt(x) in the same Q domain. It is a coarse
2246 // approximation whose relative error only settles below ~1 % once the
2247 // input has enough significant bits, which is where SILK uses it (the
2248 // NLSF weights are shifted up by 16 first).
2249 for x in [1 << 18, 1234567, 1 << 24, 1 << 30] {
2250 let y = sqrt_approx(x) as f64;
2251 let want = (x as f64).sqrt();
2252 assert!(
2253 (y - want).abs() / want < 0.02,
2254 "sqrt({x}) = {y}, want {want}"
2255 );
2256 }
2257 }
2258
2259 #[test]
2260 fn gains_are_monotonic_in_the_index() {
2261 let mut prev = 0;
2262 let mut last = 0;
2263 for i in 0..64i8 {
2264 let g = gains_dequant(&[i, 0, 0, 0], &mut prev, false, 1)[0];
2265 assert!(g > last, "gain for index {i} did not increase");
2266 last = g;
2267 prev = i as i32;
2268 }
2269 }
2270
2271 #[test]
2272 fn nlsf_stabilize_enforces_the_minimum_spacing() {
2273 let cb = nlsf_cb(false);
2274 let mut nlsf = [100i16, 120, 130, 140, 150, 160, 170, 180, 190, 32700];
2275 nlsf_stabilize(&mut nlsf, cb.delta_min_q15);
2276 for i in 1..10 {
2277 assert!(
2278 nlsf[i] - nlsf[i - 1] >= cb.delta_min_q15[i],
2279 "spacing at {i}: {} < {}",
2280 nlsf[i] - nlsf[i - 1],
2281 cb.delta_min_q15[i]
2282 );
2283 }
2284 assert!(nlsf[0] >= cb.delta_min_q15[0]);
2285 assert!((1 << 15) - nlsf[9] as i32 >= cb.delta_min_q15[10] as i32);
2286 }
2287}