diff --git a/crates/ec-opus/src/celt.rs b/crates/ec-opus/src/celt.rs index 74fece79..07c1c032 100644 --- a/crates/ec-opus/src/celt.rs +++ b/crates/ec-opus/src/celt.rs @@ -280,7 +280,7 @@ fn isqrt32(x: u32) -> u32 { } /// The CELT low-overlap window (Section 4.3.7), computed rather than tabulated. -fn overlap_window() -> Vec { +pub(crate) fn overlap_window() -> Vec { (0..OVERLAP) .map(|i| { let inner = (core::f64::consts::FRAC_PI_2 * (i as f64 + 0.5) / OVERLAP as f64).sin(); diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index 644e1989..346aaa96 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -29,10 +29,12 @@ pub mod celt; pub mod packet; pub mod range; +pub mod silk; pub use celt::CeltDecoder; pub use packet::{Bandwidth, Mode, Packet, Toc}; pub use range::RangeDecoder; +pub use silk::SilkDecoder; use ec_core::{Error, Result}; @@ -48,6 +50,9 @@ pub struct Decoder { channels: usize, downsample: usize, celt: CeltDecoder, + silk: SilkDecoder, + /// The CELT overlap window, reused for redundancy cross-fades. + celt_window: Vec, prev_mode: Option, prev_redundancy: bool, range_final: u32, @@ -81,6 +86,8 @@ impl Decoder { channels, downsample, celt: CeltDecoder::new(channels, downsample), + silk: SilkDecoder::new(sample_rate, channels), + celt_window: celt::overlap_window(), prev_mode: None, prev_redundancy: false, range_final: 0, @@ -107,6 +114,7 @@ impl Decoder { /// Drops all inter-packet state; call after a seek. pub fn reset(&mut self) { self.celt.reset(); + self.silk.reset(); self.prev_mode = None; self.prev_redundancy = false; self.range_final = 0; @@ -161,6 +169,11 @@ impl Decoder { } /// Decodes one Opus frame (one entropy-coded unit) of a packet. + /// + /// The three modes share this path: SILK fills the low band, CELT the high + /// one, and a hybrid frame is their sum. The order of everything read from + /// the range decoder here is normative — SILK, then the redundancy flags, + /// then CELT (RFC 6716, Sections 4.2, 4.5.1 and 4.3). fn decode_frame( &mut self, data: &[u8], @@ -171,28 +184,199 @@ impl Decoder { let mode = toc.mode(); let stream_channels = toc.channels(); if data.len() <= 1 { - // DTX or a dropped frame: no PLC in this decoder, so emit silence. + // DTX or a dropped frame. There is no PLC here (the container + // layer feeds this decoder whole packets), so the frame is silent. out.fill(0.0); + self.prev_mode = None; return Ok(0); } let mut dec = RangeDecoder::new(data); + let mut len = data.len(); + let frame_out = frame_48k / self.downsample; + let f5 = 240 / self.downsample; + let f2_5 = 120 / self.downsample; + // --- SILK layer ----------------------------------------------------- + let mut silk_pcm = vec![0i16; frame_out * self.channels]; if mode != Mode::Celt { - return Err(Error::unsupported( - "Opus SILK layer", - "only the CELT layer is implemented in this build", - )); + if self.prev_mode == Some(Mode::Celt) { + self.silk.reset(); + } + let internal_rate = if mode == Mode::Hybrid { + 16000 + } else { + match toc.bandwidth() { + Bandwidth::Narrow => 8000, + Bandwidth::Medium => 12000, + _ => 16000, + } + }; + let payload_ms = (frame_48k / 48).max(10); + let mut done = 0usize; + let mut first = true; + while done < frame_out { + let n = self.silk.decode( + &mut dec, + &mut silk_pcm[done * self.channels..], + payload_ms, + internal_rate, + stream_channels, + first, + )?; + if n == 0 { + break; + } + done += n; + first = false; + } } - // A mode switch invalidates the MDCT overlap and energy history. - if self.prev_mode.is_some_and(|p| p != mode) && !self.prev_redundancy { - self.celt.reset(); + // --- Redundancy (Section 4.5.1) ------------------------------------- + let mut redundancy = false; + let mut celt_to_silk = false; + let mut redundancy_bytes = 0usize; + if mode != Mode::Celt + && dec.tell() as usize + 17 + 20 * usize::from(mode == Mode::Hybrid) <= 8 * len + { + redundancy = if mode == Mode::Hybrid { + dec.dec_bit_logp(12) + } else { + true + }; + if redundancy { + celt_to_silk = dec.dec_bit_logp(1); + redundancy_bytes = if mode == Mode::Hybrid { + dec.dec_uint(256) as usize + 2 + } else { + len - ((dec.tell() as usize + 7) >> 3) + }; + if redundancy_bytes > len { + redundancy_bytes = 0; + redundancy = false; + } else { + len -= redundancy_bytes; + if len * 8 < dec.tell() as usize { + len = 0; + redundancy_bytes = 0; + redundancy = false; + } + dec.shrink(len); + } + } } + let end_band = toc.bandwidth().celt_end_band(); - self.celt - .decode(&mut dec, out, frame_48k, 0, end_band, stream_channels)?; + let start_band = if mode == Mode::Celt { 0 } else { 17 }; + let mut redundant = vec![0.0f32; f5 * self.channels]; + + // A redundancy frame that precedes the main one is decoded first. + let mut redundant_rng = 0u32; + if redundancy && celt_to_silk { + let tail = &data[len..len + redundancy_bytes]; + let mut rdec = RangeDecoder::new(tail); + self.celt + .decode(&mut rdec, &mut redundant, 240, 0, end_band, stream_channels)?; + redundant_rng = rdec.range(); + } + + // --- CELT layer ----------------------------------------------------- + if mode != Mode::Silk { + // A mode switch invalidates the MDCT overlap and energy history. + if self.prev_mode.is_some_and(|p| p != mode) && !self.prev_redundancy { + self.celt.reset(); + } + self.celt.decode( + &mut dec, + out, + frame_48k.min(960), + start_band, + end_band, + stream_channels, + )?; + } else { + out.fill(0.0); + // Fade the CELT layer out when leaving hybrid, as the reference + // does, by decoding one silent 2.5 ms frame. + if self.prev_mode == Some(Mode::Hybrid) && !(redundancy && celt_to_silk) { + let silence = [0xFFu8, 0xFF]; + let mut sdec = RangeDecoder::new(&silence); + let mut tmp = vec![0.0f32; f2_5 * self.channels]; + self.celt + .decode(&mut sdec, &mut tmp, 120, 0, end_band, stream_channels)?; + } + } + + // Sum the two layers. + if mode != Mode::Celt { + for (o, s) in out.iter_mut().zip(silk_pcm.iter()) { + *o += *s as f32 * (1.0 / 32768.0); + } + } + + // A redundancy frame that follows the main one is cross-faded in. + if redundancy && !celt_to_silk { + self.celt.reset(); + let tail = &data[len..len + redundancy_bytes]; + let mut rdec = RangeDecoder::new(tail); + self.celt + .decode(&mut rdec, &mut redundant, 240, 0, end_band, stream_channels)?; + redundant_rng = rdec.range(); + let base = (frame_out - f2_5) * self.channels; + smooth_fade( + &mut out[base..], + &redundant[f2_5 * self.channels..], + f2_5, + self.channels, + &self.celt_window, + self.downsample, + ); + } + if redundancy && celt_to_silk { + for c in 0..self.channels { + for i in 0..f2_5 { + out[self.channels * i + c] = redundant[self.channels * i + c]; + } + } + // Then fade from the redundancy frame into the frame proper. + let split = f2_5 * self.channels; + for c in 0..self.channels { + for i in 0..f2_5 { + let w = { + let x = self.celt_window[i * self.downsample]; + x * x + }; + let idx = split + i * self.channels + c; + if idx < out.len() && idx < redundant.len() { + out[idx] = w * out[idx] + (1.0 - w) * redundant[idx]; + } + } + } + } + self.prev_mode = Some(mode); - self.prev_redundancy = false; - Ok(dec.range()) + self.prev_redundancy = redundancy && !celt_to_silk; + Ok(dec.range() ^ redundant_rng) + } +} + +/// Cross-fades `b` over `a` across `overlap` samples using the CELT window, +/// the shape the reference uses for redundancy and mode transitions. +fn smooth_fade( + a: &mut [f32], + b: &[f32], + overlap: usize, + channels: usize, + window: &[f32], + downsample: usize, +) { + let inc = downsample; + for c in 0..channels { + for i in 0..overlap { + let w = window[i * inc] * window[i * inc]; + let idx = i * channels + c; + if idx < a.len() && idx < b.len() { + a[idx] = w * b[idx] + (1.0 - w) * a[idx]; + } + } } } diff --git a/crates/ec-opus/src/range.rs b/crates/ec-opus/src/range.rs index 72b6156f..23dfe8ca 100644 --- a/crates/ec-opus/src/range.rs +++ b/crates/ec-opus/src/range.rs @@ -224,6 +224,15 @@ impl<'a> RangeDecoder<'a> { } } + /// Shrinks the frame to `len` bytes, which is what the redundancy framing + /// does when it reserves the tail of a packet for a second CELT frame + /// (RFC 6716, Section 4.5.1). Bytes already read are unaffected. + pub fn shrink(&mut self, len: usize) { + if len <= self.buf.len() { + self.buf = &self.buf[..len]; + } + } + /// Declares the rest of the frame consumed, so [`RangeDecoder::tell`] /// reports the whole frame. CELT does this for a silent frame, whose /// remaining bits carry nothing (RFC 6716, Section 4.3). diff --git a/crates/ec-opus/src/silk.rs b/crates/ec-opus/src/silk.rs new file mode 100644 index 00000000..eeb6e14f --- /dev/null +++ b/crates/ec-opus/src/silk.rs @@ -0,0 +1,1806 @@ +//! The SILK (linear-prediction) layer of Opus — RFC 6716 Section 4.2. +//! +//! SILK is a speech coder: each 20 ms frame carries an LPC filter (as line +//! spectral frequencies), a per-subframe gain, an optional long-term (pitch) +//! predictor, and a pulse-coded excitation. Decoding runs that chain backwards +//! — excitation, LTP synthesis, LPC synthesis — then unmixes stereo and +//! resamples from the internal 8/12/16 kHz to the output rate. +//! +//! Unlike CELT, SILK has no floating-point form: every operation below is the +//! exact integer arithmetic of the normative decoder (RFC 6716 Section 6 makes +//! the Appendix A reference implementation normative, and Section 4.2 is +//! written as fixed-point pseudo-code for the same reason). The tables are the +//! ones the RFC tabulates in Section 4.2, in the layout the reference uses. +//! +//! Packet loss concealment is not implemented: this decoder is fed complete +//! packets by the container layer, so a lost or empty frame yields silence +//! rather than an extrapolation. Everything else in the layer is complete. + +// SILK is transliterated fixed-point arithmetic: the loops below index parallel +// arrays by position because the reference's index arithmetic is the +// specification. Iterator forms would hide that correspondence. +#![allow(clippy::needless_range_loop)] + +use ec_core::Result; + +use crate::range::RangeDecoder; + +mod tables { + #![allow(clippy::all)] + include!("silk_tables.rs"); +} + +use tables::*; + +const MAX_LPC_ORDER: usize = 16; +const LTP_ORDER: usize = 5; +const MAX_NB_SUBFR: usize = 4; +const SUB_FRAME_LENGTH_MS: usize = 5; +const LTP_MEM_LENGTH_MS: usize = 20; +const MAX_FRAME_LENGTH: usize = 20 * 16; +const QUANT_LEVEL_ADJUST_Q10: i32 = 80; +const N_LEVELS_QGAIN: i32 = 64; +const MIN_DELTA_GAIN_QUANT: i32 = -4; +const MAX_DELTA_GAIN_QUANT: i32 = 36; +const MIN_QGAIN_DB: i32 = 2; +const MAX_QGAIN_DB: i32 = 88; +const NLSF_QUANT_MAX_AMPLITUDE: i32 = 4; +const SHELL_LEN: usize = 16; +const MAX_PULSES: i32 = 16; +const N_RATE_LEVELS: usize = 10; +const PE_MIN_LAG_MS: i32 = 2; +const PE_MAX_LAG_MS: i32 = 18; +const STEREO_INTERP_LEN_MS: usize = 8; +const TYPE_VOICED: i32 = 2; +const MAX_LPC_STABILIZE_ITERATIONS: usize = 16; + +/// Gain quantiser constants (`gain_quant.c`). +const GAIN_OFFSET: i32 = (MIN_QGAIN_DB * 128) / 6 + 16 * 128; +const GAIN_INV_SCALE_Q16: i32 = + (65536 * (((MAX_QGAIN_DB - MIN_QGAIN_DB) * 128) / 6)) / (N_LEVELS_QGAIN - 1); + +/// How a frame's parameters relate to the previous frame's. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum CondCoding { + Independently, + IndependentlyNoLtpScaling, + Conditionally, +} + +// --------------------------------------------------------------------------- +// Fixed-point helpers. These are the reference's macros; they are written out +// because SILK's output is defined by them bit for bit. +// --------------------------------------------------------------------------- + +#[inline] +fn smulwb(a: i32, b: i32) -> i32 { + (((a >> 16) * (b as i16 as i32)) as i64 + ((((a & 0xFFFF) * (b as i16 as i32)) >> 16) as i64)) + as i32 +} + +#[inline] +fn smlawb(a: i32, b: i32, c: i32) -> i32 { + a.wrapping_add(smulwb(b, c)) +} + +#[inline] +fn smulbb(a: i32, b: i32) -> i32 { + (a as i16 as i32).wrapping_mul(b as i16 as i32) +} + +#[inline] +fn smlabb(a: i32, b: i32, c: i32) -> i32 { + a.wrapping_add(smulbb(b, c)) +} + +#[inline] +fn rshift_round(a: i32, shift: u32) -> i32 { + if shift == 1 { + (a >> 1) + (a & 1) + } else { + ((a >> (shift - 1)) + 1) >> 1 + } +} + +#[inline] +fn rshift_round64(a: i64, shift: u32) -> i64 { + if shift == 1 { + (a >> 1) + (a & 1) + } else { + ((a >> (shift - 1)) + 1) >> 1 + } +} + +#[inline] +fn smulww(a: i32, b: i32) -> i32 { + smulwb(a, b).wrapping_add(a.wrapping_mul(rshift_round(b, 16))) +} + +#[inline] +fn smlaww(a: i32, b: i32, c: i32) -> i32 { + smlawb(a, b, c).wrapping_add(b.wrapping_mul(rshift_round(c, 16))) +} + +/// `silk_SMMUL`: the top 32 bits of a 32x32 product. +#[inline] +fn smmul(a: i32, b: i32) -> i32 { + ((a as i64 * b as i64) >> 32) as i32 +} + +#[inline] +fn sat16(a: i32) -> i16 { + a.clamp(-32768, 32767) as i16 +} + +#[inline] +fn clz32(x: i32) -> i32 { + if x == 0 { + 32 + } else { + (x as u32).leading_zeros() as i32 + } +} + +/// `silk_CLZ_FRAC`: leading zeros plus the seven bits below the leading one. +#[inline] +fn clz_frac(x: i32) -> (i32, i32) { + let lz = clz32(x); + let frac = (x as u32).rotate_right((24 - lz) as u32) as i32 & 0x7F; + (lz, frac) +} + +fn sqrt_approx(x: i32) -> i32 { + if x <= 0 { + return 0; + } + let (lz, frac) = clz_frac(x); + let mut y = if lz & 1 != 0 { 32768 } else { 46214 }; + y >>= lz >> 1; + smlawb(y, y, smulbb(213, frac)) +} + + +fn log2lin(log_q7: i32) -> i32 { + if log_q7 < 0 { + return 0; + } + let mut out = 1i32 << (log_q7 >> 7); + let frac = log_q7 & 0x7F; + let adj = smlawb(frac, smulbb(frac, 128 - frac), -174); + if log_q7 < 2048 { + out += ((out as i64 * adj as i64) >> 7) as i32; + } else { + out = out.wrapping_add((out >> 7).wrapping_mul(adj)); + } + out +} + +/// `silk_INVERSE32_varQ`: `(1 << q) / b`, to about 30 bits. +fn inverse32_var_q(b32: i32, qres: u32) -> i32 { + debug_assert!(b32 != 0); + let b_headrm = clz32(b32.abs()) - 1; + let b32_nrm = b32 << b_headrm; + let b32_inv = (i32::MAX >> 2) / (b32_nrm >> 16); + let mut result = b32_inv << 16; + let err_q32 = ((1 << 29) - smulwb(b32_nrm, b32_inv)) << 3; + result = smlaww(result, err_q32, b32_inv); + let lshift = 61 - b_headrm - qres as i32; + if lshift <= 0 { + lshift_sat32(result, -lshift) + } else if lshift < 32 { + result >> lshift + } else { + 0 + } +} + +/// `silk_DIV32_varQ`: `(a << q) / b`. +fn div32_var_q(a32: i32, b32: i32, qres: u32) -> i32 { + debug_assert!(b32 != 0); + let a_headrm = clz32(a32.abs()) - 1; + let mut a32_nrm = a32 << a_headrm; + let b_headrm = clz32(b32.abs()) - 1; + let b32_nrm = b32 << b_headrm; + let b32_inv = (i32::MAX >> 2) / (b32_nrm >> 16); + let mut result = smulwb(a32_nrm, b32_inv); + a32_nrm = a32_nrm.wrapping_sub(smmul(b32_nrm, result).wrapping_shl(3)); + result = smlawb(result, a32_nrm, b32_inv); + let lshift = 29 + a_headrm - b_headrm - qres as i32; + if lshift < 0 { + lshift_sat32(result, -lshift) + } else if lshift < 32 { + result >> lshift + } else { + 0 + } +} + +fn lshift_sat32(a: i32, shift: i32) -> i32 { + let lim = i32::MAX >> shift; + a.clamp(-lim - 1, lim) << shift +} + +/// `silk_RAND`: the excitation sign PRNG. +#[inline] +fn silk_rand(seed: i32) -> i32 { + (907633515i32).wrapping_add(seed.wrapping_mul(196314165)) +} + +// --------------------------------------------------------------------------- +// Decoder state +// --------------------------------------------------------------------------- + +/// Per-frame parameters decoded from the bitstream. +#[derive(Clone, Debug, Default)] +struct Indices { + signal_type: i32, + quant_offset_type: i32, + gains: [i8; MAX_NB_SUBFR], + nlsf: [i8; MAX_LPC_ORDER + 1], + nlsf_interp_coef_q2: i32, + lag_index: i32, + contour_index: i32, + per_index: usize, + ltp_index: [usize; MAX_NB_SUBFR], + ltp_scale_index: usize, + seed: i32, +} + +/// Everything `decode_parameters` produces for one frame. +#[derive(Clone, Debug)] +struct FrameCtrl { + gains_q16: [i32; MAX_NB_SUBFR], + pred_coef_q12: [[i16; MAX_LPC_ORDER]; 2], + ltp_coef_q14: [i16; LTP_ORDER * MAX_NB_SUBFR], + ltp_scale_q14: i32, + pitch_l: [i32; MAX_NB_SUBFR], +} + +impl Default for FrameCtrl { + fn default() -> Self { + FrameCtrl { + gains_q16: [0; MAX_NB_SUBFR], + pred_coef_q12: [[0; MAX_LPC_ORDER]; 2], + ltp_coef_q14: [0; LTP_ORDER * MAX_NB_SUBFR], + ltp_scale_q14: 0, + pitch_l: [0; MAX_NB_SUBFR], + } + } +} + +/// One SILK channel's inter-frame state. +#[derive(Clone, Debug)] +struct ChannelState { + fs_khz: usize, + frame_length: usize, + subfr_length: usize, + ltp_mem_length: usize, + nb_subfr: usize, + lpc_order: usize, + frames_per_packet: usize, + frames_decoded: usize, + /// Wideband uses the 16th-order codebook, NB/MB the 10th-order one. + wb_codebook: bool, + indices: Indices, + /// Synthesis history, `ltp_mem_length + frame_length` samples. + out_buf: [i16; MAX_FRAME_LENGTH + MAX_FRAME_LENGTH], + s_lpc_q14: [i32; MAX_LPC_ORDER], + exc_q14: [i32; MAX_FRAME_LENGTH], + prev_nlsf_q15: [i16; MAX_LPC_ORDER], + prev_gain_q16: i32, + last_gain_index: i32, + prev_signal_type: i32, + ec_prev_signal_type: i32, + ec_prev_lag_index: i32, + lag_prev: i32, + first_frame_after_reset: bool, + vad_flags: [bool; 3], + lbrr_flag: bool, + lbrr_flags: [bool; 3], + resampler: Resampler, +} + +impl ChannelState { + fn new() -> ChannelState { + ChannelState { + fs_khz: 0, + frame_length: 0, + subfr_length: 0, + ltp_mem_length: 0, + nb_subfr: 0, + lpc_order: 0, + frames_per_packet: 1, + frames_decoded: 0, + wb_codebook: false, + indices: Indices::default(), + out_buf: [0; MAX_FRAME_LENGTH * 2], + s_lpc_q14: [0; MAX_LPC_ORDER], + exc_q14: [0; MAX_FRAME_LENGTH], + prev_nlsf_q15: [0; MAX_LPC_ORDER], + prev_gain_q16: 65536, + last_gain_index: 10, + prev_signal_type: 0, + ec_prev_signal_type: 0, + ec_prev_lag_index: 0, + lag_prev: 100, + first_frame_after_reset: true, + vad_flags: [false; 3], + lbrr_flag: false, + lbrr_flags: [false; 3], + resampler: Resampler::default(), + } + } + + /// `silk_decoder_set_fs`: geometry for an internal rate. + fn set_fs(&mut self, fs_khz: usize, api_rate: u32) { + self.subfr_length = SUB_FRAME_LENGTH_MS * fs_khz; + let frame_length = self.nb_subfr * self.subfr_length; + if self.fs_khz != fs_khz || self.resampler.fs_out_khz * 1000 != api_rate as usize { + self.resampler = Resampler::new(fs_khz, api_rate as usize / 1000); + } + if self.fs_khz != fs_khz { + self.ltp_mem_length = LTP_MEM_LENGTH_MS * fs_khz; + if fs_khz == 16 { + self.lpc_order = MAX_LPC_ORDER; + self.wb_codebook = true; + } else { + self.lpc_order = 10; + self.wb_codebook = false; + } + self.first_frame_after_reset = true; + self.lag_prev = 100; + self.last_gain_index = 10; + self.prev_signal_type = 0; + self.out_buf.fill(0); + self.s_lpc_q14.fill(0); + } + self.fs_khz = fs_khz; + self.frame_length = frame_length; + } + + fn pitch_contour_icdf(&self) -> &'static [u8] { + match (self.fs_khz, self.nb_subfr) { + (8, 4) => &PITCH_CONTOUR_NB_ICDF, + (8, _) => &PITCH_CONTOUR_10_MS_NB_ICDF, + (_, 4) => &PITCH_CONTOUR_ICDF, + _ => &PITCH_CONTOUR_10_MS_ICDF, + } + } + + fn pitch_lag_low_bits_icdf(&self) -> &'static [u8] { + match self.fs_khz { + 16 => &UNIFORM8_ICDF, + 12 => &UNIFORM6_ICDF, + _ => &UNIFORM4_ICDF, + } + } +} + +/// Stereo prediction state carried between frames. +#[derive(Clone, Debug, Default)] +struct StereoState { + pred_prev_q13: [i32; 2], + s_mid: [i16; 2], + s_side: [i16; 2], +} + +/// The SILK decoder for one Opus stream (one or two channels). +#[derive(Clone, Debug)] +pub struct SilkDecoder { + channels: [ChannelState; 2], + stereo: StereoState, + channels_internal: usize, + channels_api: usize, + api_rate: u32, + prev_decode_only_middle: bool, +} + +impl SilkDecoder { + /// A decoder producing `channels_api` channels at `api_rate` Hz. + pub fn new(api_rate: u32, channels_api: usize) -> SilkDecoder { + SilkDecoder { + channels: [ChannelState::new(), ChannelState::new()], + stereo: StereoState::default(), + channels_internal: 1, + channels_api, + api_rate, + prev_decode_only_middle: false, + } + } + + /// Drops all inter-packet state. + pub fn reset(&mut self) { + let api_rate = self.api_rate; + let channels_api = self.channels_api; + *self = SilkDecoder::new(api_rate, channels_api); + } + + /// Decodes the SILK part of one Opus frame. + /// + /// `payload_ms` is the Opus frame duration (10, 20, 40 or 60 ms), + /// `internal_rate` the SILK sample rate the TOC implies (8000, 12000 or + /// 16000 Hz), and `channels_internal` how many channels the packet codes. + /// Output is interleaved `i16` at the API rate, `channels_api` channels. + pub fn decode( + &mut self, + dec: &mut RangeDecoder, + out: &mut [i16], + payload_ms: usize, + internal_rate: u32, + channels_internal: usize, + new_packet: bool, + ) -> Result { + let fs_khz = (internal_rate / 1000) as usize; + if new_packet { + for ch in self.channels.iter_mut() { + ch.frames_decoded = 0; + } + } + let (frames_per_packet, nb_subfr) = match payload_ms { + 10 => (1, 2), + 20 => (1, 4), + 40 => (2, 4), + 60 => (3, 4), + _ => (1, 4), + }; + // A stream that gains a second channel starts it from scratch. + if channels_internal > self.channels_internal { + self.channels[1] = ChannelState::new(); + } + if self.channels[0].frames_decoded == 0 { + for ch in self.channels.iter_mut().take(channels_internal) { + ch.frames_per_packet = frames_per_packet; + ch.nb_subfr = nb_subfr; + ch.set_fs(fs_khz, self.api_rate); + } + } + if self.channels_api == 2 && channels_internal == 2 && self.channels_internal == 1 { + // The side channel starts from the mid channel's resampler state, + // so the two stay in phase across the mono-to-stereo switch. + self.stereo.pred_prev_q13 = [0; 2]; + self.stereo.s_side = [0; 2]; + self.channels[1].resampler = self.channels[0].resampler.clone(); + } + self.channels_internal = channels_internal; + + let mut ms_pred_q13 = [0i32; 2]; + let mut decode_only_middle = false; + + // Header bits: per-frame VAD flags and the LBRR flag (Section 4.2.3). + if self.channels[0].frames_decoded == 0 { + for n in 0..channels_internal { + for i in 0..self.channels[n].frames_per_packet { + self.channels[n].vad_flags[i] = dec.dec_bit_logp(1); + } + self.channels[n].lbrr_flag = dec.dec_bit_logp(1); + } + for n in 0..channels_internal { + self.channels[n].lbrr_flags = [false; 3]; + if self.channels[n].lbrr_flag { + if self.channels[n].frames_per_packet == 1 { + self.channels[n].lbrr_flags[0] = true; + } else { + let icdf: &[u8] = if self.channels[n].frames_per_packet == 2 { + &LBRR_FLAGS_2_ICDF + } else { + &LBRR_FLAGS_3_ICDF + }; + let sym = dec.dec_icdf(icdf, 8) as i32 + 1; + for i in 0..self.channels[n].frames_per_packet { + self.channels[n].lbrr_flags[i] = (sym >> i) & 1 != 0; + } + } + } + } + // Skip the LBRR frames: they are only useful for concealment, but + // their symbols must still be consumed to stay in sync. + for i in 0..self.channels[0].frames_per_packet { + for n in 0..channels_internal { + if self.channels[n].lbrr_flags[i] { + if channels_internal == 2 && n == 0 { + stereo_decode_pred(dec, &mut ms_pred_q13); + if !self.channels[1].lbrr_flags[i] { + let _ = dec.dec_icdf(&STEREO_ONLY_CODE_MID_ICDF, 8); + } + } + let cond = if i > 0 && self.channels[n].lbrr_flags[i - 1] { + CondCoding::Conditionally + } else { + CondCoding::Independently + }; + let ch = &mut self.channels[n]; + decode_indices(ch, dec, i, true, cond); + let mut pulses = [0i32; MAX_FRAME_LENGTH + SHELL_LEN]; + let n = ch.frame_length; + decode_pulses( + dec, + &mut pulses, + n, + ch.indices.signal_type, + ch.indices.quant_offset_type, + ); + } + } + } + } + + // Stereo prediction weights for this frame. + if channels_internal == 2 { + stereo_decode_pred(dec, &mut ms_pred_q13); + let frame = self.channels[0].frames_decoded; + if !self.channels[1].vad_flags[frame] { + decode_only_middle = dec.dec_icdf(&STEREO_ONLY_CODE_MID_ICDF, 8) != 0; + } + } + if channels_internal == 2 && !decode_only_middle && self.prev_decode_only_middle { + self.channels[1].out_buf.fill(0); + self.channels[1].s_lpc_q14.fill(0); + self.channels[1].lag_prev = 100; + self.channels[1].last_gain_index = 10; + self.channels[1].prev_signal_type = 0; + self.channels[1].first_frame_after_reset = true; + } + + let has_side = !decode_only_middle; + let mut mid = [0i16; MAX_FRAME_LENGTH + 2]; + let mut side = [0i16; MAX_FRAME_LENGTH + 2]; + let mut n_samples_dec = 0usize; + for n in 0..channels_internal { + let buf: &mut [i16] = if n == 0 { &mut mid } else { &mut side }; + if n == 0 || has_side { + let frame_index = self.channels[0].frames_decoded as i32 - n as i32; + let cond = if frame_index <= 0 { + CondCoding::Independently + } else if n > 0 && self.prev_decode_only_middle { + CondCoding::IndependentlyNoLtpScaling + } else { + CondCoding::Conditionally + }; + n_samples_dec = decode_frame(&mut self.channels[n], dec, &mut buf[2..], cond); + } else { + buf[2..2 + n_samples_dec].fill(0); + } + self.channels[n].frames_decoded += 1; + } + + // Stereo unmixing, then resampling to the output rate. + if self.channels_api == 2 && channels_internal == 2 { + stereo_ms_to_lr( + &mut self.stereo, + &mut mid, + &mut side, + &ms_pred_q13, + self.channels[0].fs_khz, + n_samples_dec, + ); + } else { + mid[0] = self.stereo.s_mid[0]; + mid[1] = self.stereo.s_mid[1]; + self.stereo.s_mid[0] = mid[n_samples_dec]; + self.stereo.s_mid[1] = mid[n_samples_dec + 1]; + } + self.prev_decode_only_middle = decode_only_middle; + + let out_len = n_samples_dec * self.api_rate as usize / (self.channels[0].fs_khz * 1000); + let mut tmp = vec![0i16; out_len]; + let chans = self.channels_api.min(channels_internal); + for n in 0..chans { + let src: &[i16] = if n == 0 { &mid[1..] } else { &side[1..] }; + let state = &mut self.channels[n].resampler; + state.process(&mut tmp, &src[..n_samples_dec], n_samples_dec); + if self.channels_api == 2 { + for i in 0..out_len { + out[n + 2 * i] = tmp[i]; + } + } else { + out[..out_len].copy_from_slice(&tmp[..out_len]); + } + } + // A mono stream fed to a stereo output is duplicated. + if self.channels_api == 2 && channels_internal == 1 { + for i in 0..out_len { + out[1 + 2 * i] = out[2 * i]; + } + } + Ok(out_len) + } +} + +/// `silk_decode_indices` (Section 4.2.7). +fn decode_indices( + ch: &mut ChannelState, + dec: &mut RangeDecoder, + frame_index: usize, + decode_lbrr: bool, + cond: CondCoding, +) { + let ix = if decode_lbrr || ch.vad_flags[frame_index] { + dec.dec_icdf(&TYPE_OFFSET_VAD_ICDF, 8) as i32 + 2 + } else { + dec.dec_icdf(&TYPE_OFFSET_NO_VAD_ICDF, 8) as i32 + }; + ch.indices.signal_type = ix >> 1; + ch.indices.quant_offset_type = ix & 1; + + // Subframe gains (Section 4.2.7.4). + if cond == CondCoding::Conditionally { + ch.indices.gains[0] = dec.dec_icdf(&DELTA_GAIN_ICDF, 8) as i8; + } else { + let msb = dec.dec_icdf(&GAIN_ICDF[ch.indices.signal_type as usize], 8) as i32; + let lsb = dec.dec_icdf(&UNIFORM8_ICDF, 8) as i32; + ch.indices.gains[0] = ((msb << 3) + lsb) as i8; + } + for i in 1..ch.nb_subfr { + ch.indices.gains[i] = dec.dec_icdf(&DELTA_GAIN_ICDF, 8) as i8; + } + + // Normalised LSFs (Section 4.2.7.5). + let cb = nlsf_cb(ch.wb_codebook); + let stage1_icdf = &cb.cb1_icdf[(ch.indices.signal_type as usize >> 1) * cb.n_vectors..]; + ch.indices.nlsf[0] = dec.dec_icdf(stage1_icdf, 8) as i8; + let (ec_ix, _pred) = nlsf_unpack(cb, ch.indices.nlsf[0] as usize); + for i in 0..cb.order { + let mut ix = dec.dec_icdf(&cb.ec_icdf[ec_ix[i] as usize..], 8) as i32; + if ix == 0 { + ix -= dec.dec_icdf(&NLSF_EXT_ICDF, 8) as i32; + } else if ix == 2 * NLSF_QUANT_MAX_AMPLITUDE { + ix += dec.dec_icdf(&NLSF_EXT_ICDF, 8) as i32; + } + ch.indices.nlsf[i + 1] = (ix - NLSF_QUANT_MAX_AMPLITUDE) as i8; + } + ch.indices.nlsf_interp_coef_q2 = if ch.nb_subfr == MAX_NB_SUBFR { + dec.dec_icdf(&NLSF_INTERPOLATION_FACTOR_ICDF, 8) as i32 + } else { + 4 + }; + + // Pitch and LTP (Section 4.2.7.6). + if ch.indices.signal_type == TYPE_VOICED { + let mut absolute = true; + if cond == CondCoding::Conditionally && ch.ec_prev_signal_type == TYPE_VOICED { + let delta = dec.dec_icdf(&PITCH_DELTA_ICDF, 8) as i32; + if delta > 0 { + ch.indices.lag_index = ch.ec_prev_lag_index + delta - 9; + absolute = false; + } + } + if absolute { + ch.indices.lag_index = + dec.dec_icdf(&PITCH_LAG_ICDF, 8) as i32 * (ch.fs_khz as i32 >> 1); + ch.indices.lag_index += dec.dec_icdf(ch.pitch_lag_low_bits_icdf(), 8) as i32; + } + ch.ec_prev_lag_index = ch.indices.lag_index; + ch.indices.contour_index = dec.dec_icdf(ch.pitch_contour_icdf(), 8) as i32; + ch.indices.per_index = dec.dec_icdf(<P_PER_INDEX_ICDF, 8); + let gain_icdf: &[u8] = match ch.indices.per_index { + 0 => <P_GAIN_ICDF_0, + 1 => <P_GAIN_ICDF_1, + _ => <P_GAIN_ICDF_2, + }; + for k in 0..ch.nb_subfr { + ch.indices.ltp_index[k] = dec.dec_icdf(gain_icdf, 8); + } + ch.indices.ltp_scale_index = if cond == CondCoding::Independently { + dec.dec_icdf(<PSCALE_ICDF, 8) + } else { + 0 + }; + } + ch.ec_prev_signal_type = ch.indices.signal_type; + ch.indices.seed = dec.dec_icdf(&UNIFORM4_ICDF, 8) as i32; +} + +/// `silk_decode_pulses` (Section 4.2.7.8): the excitation. +fn decode_pulses( + dec: &mut RangeDecoder, + pulses: &mut [i32], + frame_length: usize, + signal_type: i32, + quant_offset_type: i32, +) { + // A 12 kHz 10 ms frame is 120 samples, which is not a whole number of + // 16-sample shell blocks: the last block runs past the frame and its extra + // pulses are discarded, so `pulses` must have room for them. + debug_assert!(pulses.len() >= frame_length.div_ceil(SHELL_LEN) * SHELL_LEN); + let rate_level = dec.dec_icdf(&RATE_LEVELS_ICDF[signal_type as usize >> 1], 8); + let mut iter = frame_length >> 4; + if iter * SHELL_LEN < frame_length { + iter += 1; + } + let mut sum_pulses = [0i32; MAX_FRAME_LENGTH / SHELL_LEN + 1]; + let mut n_lshifts = [0i32; MAX_FRAME_LENGTH / SHELL_LEN + 1]; + for i in 0..iter { + sum_pulses[i] = dec.dec_icdf(&PULSES_PER_BLOCK_ICDF[rate_level], 8) as i32; + while sum_pulses[i] == MAX_PULSES + 1 { + n_lshifts[i] += 1; + let icdf = &PULSES_PER_BLOCK_ICDF[N_RATE_LEVELS - 1][usize::from(n_lshifts[i] == 10)..]; + sum_pulses[i] = dec.dec_icdf(icdf, 8) as i32; + } + } + for i in 0..iter { + let block = &mut pulses[i * SHELL_LEN..]; + if sum_pulses[i] > 0 { + shell_decode(dec, block, sum_pulses[i]); + } else { + block[..SHELL_LEN].fill(0); + } + } + // Least significant bits for blocks that overflowed the pulse count. + for i in 0..iter { + if n_lshifts[i] > 0 { + let block = &mut pulses[i * SHELL_LEN..]; + for k in 0..SHELL_LEN { + let mut abs_q = block[k]; + for _ in 0..n_lshifts[i] { + abs_q <<= 1; + abs_q += dec.dec_icdf(&LSB_ICDF, 8) as i32; + } + block[k] = abs_q; + } + sum_pulses[i] |= n_lshifts[i] << 5; + } + } + decode_signs( + dec, + pulses, + signal_type, + quant_offset_type, + &sum_pulses[..iter], + ); +} + +/// One 16-sample shell block (Section 4.2.7.8.3). +fn shell_decode(dec: &mut RangeDecoder, pulses0: &mut [i32], total: i32) { + fn split(dec: &mut RangeDecoder, p: i32, table: &[u8]) -> (i32, i32) { + if p > 0 { + let a = dec.dec_icdf(&table[SHELL_CODE_TABLE_OFFSETS[p as usize] as usize..], 8) as i32; + (a, p - a) + } else { + (0, 0) + } + } + let mut p3 = [0i32; 2]; + let mut p2 = [0i32; 4]; + let mut p1 = [0i32; 8]; + (p3[0], p3[1]) = split(dec, total, &SHELL_CODE_TABLE3); + (p2[0], p2[1]) = split(dec, p3[0], &SHELL_CODE_TABLE2); + (p1[0], p1[1]) = split(dec, p2[0], &SHELL_CODE_TABLE1); + (pulses0[0], pulses0[1]) = split(dec, p1[0], &SHELL_CODE_TABLE0); + (pulses0[2], pulses0[3]) = split(dec, p1[1], &SHELL_CODE_TABLE0); + (p1[2], p1[3]) = split(dec, p2[1], &SHELL_CODE_TABLE1); + (pulses0[4], pulses0[5]) = split(dec, p1[2], &SHELL_CODE_TABLE0); + (pulses0[6], pulses0[7]) = split(dec, p1[3], &SHELL_CODE_TABLE0); + (p2[2], p2[3]) = split(dec, p3[1], &SHELL_CODE_TABLE2); + (p1[4], p1[5]) = split(dec, p2[2], &SHELL_CODE_TABLE1); + (pulses0[8], pulses0[9]) = split(dec, p1[4], &SHELL_CODE_TABLE0); + (pulses0[10], pulses0[11]) = split(dec, p1[5], &SHELL_CODE_TABLE0); + (p1[6], p1[7]) = split(dec, p2[3], &SHELL_CODE_TABLE1); + (pulses0[12], pulses0[13]) = split(dec, p1[6], &SHELL_CODE_TABLE0); + (pulses0[14], pulses0[15]) = split(dec, p1[7], &SHELL_CODE_TABLE0); +} + +/// Excitation signs (Section 4.2.7.8.5). +fn decode_signs( + dec: &mut RangeDecoder, + pulses: &mut [i32], + signal_type: i32, + quant_offset_type: i32, + sum_pulses: &[i32], +) { + let base = 7 * (quant_offset_type + (signal_type << 1)) as usize; + for (i, &p) in sum_pulses.iter().enumerate() { + if p > 0 { + let icdf = [SIGN_ICDF[base + (p & 0x1F).min(6) as usize], 0]; + for j in 0..SHELL_LEN { + let idx = i * SHELL_LEN + j; + if idx < pulses.len() && pulses[idx] > 0 { + pulses[idx] *= 2 * dec.dec_icdf(&icdf, 8) as i32 - 1; + } + } + } + } +} + +/// The NLSF codebook for one bandwidth (Section 4.2.7.5). +struct NlsfCodebook { + n_vectors: usize, + order: usize, + quant_step_size_q16: i32, + cb1_q8: &'static [u8], + cb1_icdf: &'static [u8], + pred_q8: &'static [u8], + ec_sel: &'static [u8], + ec_icdf: &'static [u8], + delta_min_q15: &'static [i16], +} + +fn nlsf_cb(wideband: bool) -> &'static NlsfCodebook { + static NB_MB: NlsfCodebook = NlsfCodebook { + n_vectors: 32, + order: 10, + // 0.18 in Q16. + quant_step_size_q16: 11796, + cb1_q8: &NLSF_CB1_NB_MB_Q8, + cb1_icdf: &NLSF_CB1_ICDF_NB_MB, + pred_q8: &NLSF_PRED_NB_MB_Q8, + ec_sel: &NLSF_CB2_SELECT_NB_MB, + ec_icdf: &NLSF_CB2_ICDF_NB_MB, + delta_min_q15: &NLSF_DELTA_MIN_NB_MB_Q15, + }; + static WB: NlsfCodebook = NlsfCodebook { + n_vectors: 32, + order: 16, + quant_step_size_q16: 9830, + cb1_q8: &NLSF_CB1_WB_Q8, + cb1_icdf: &NLSF_CB1_ICDF_WB, + pred_q8: &NLSF_PRED_WB_Q8, + ec_sel: &NLSF_CB2_SELECT_WB, + ec_icdf: &NLSF_CB2_ICDF_WB, + delta_min_q15: &NLSF_DELTA_MIN_WB_Q15, + }; + if wideband { &WB } else { &NB_MB } +} + +/// `silk_NLSF_unpack`: per-coefficient entropy-table selectors and predictors. +fn nlsf_unpack(cb: &NlsfCodebook, cb1_index: usize) -> ([i16; MAX_LPC_ORDER], [u8; MAX_LPC_ORDER]) { + let mut ec_ix = [0i16; MAX_LPC_ORDER]; + let mut pred = [0u8; MAX_LPC_ORDER]; + let sel = &cb.ec_sel[cb1_index * cb.order / 2..]; + for i in (0..cb.order).step_by(2) { + let entry = sel[i / 2]; + ec_ix[i] = (((entry >> 1) & 7) as i16) * (2 * NLSF_QUANT_MAX_AMPLITUDE as i16 + 1); + pred[i] = cb.pred_q8[i + (entry & 1) as usize * (cb.order - 1)]; + ec_ix[i + 1] = (((entry >> 5) & 7) as i16) * (2 * NLSF_QUANT_MAX_AMPLITUDE as i16 + 1); + pred[i + 1] = cb.pred_q8[i + ((entry >> 4) & 1) as usize * (cb.order - 1) + 1]; + } + (ec_ix, pred) +} + +/// `silk_NLSF_decode`: indices to normalised LSFs (Section 4.2.7.5.3). +fn nlsf_decode(indices: &[i8], cb: &NlsfCodebook) -> [i16; MAX_LPC_ORDER] { + let mut nlsf_q15 = [0i16; MAX_LPC_ORDER]; + let base = indices[0] as usize * cb.order; + for i in 0..cb.order { + nlsf_q15[i] = (cb.cb1_q8[base + i] as i16) << 7; + } + let (_, pred_q8) = nlsf_unpack(cb, indices[0] as usize); + // Residual dequantisation, back to front so the prediction chains. + let mut res_q10 = [0i16; MAX_LPC_ORDER]; + let mut out_q10 = 0i32; + for i in (0..cb.order).rev() { + let pred_q10 = smulbb(out_q10, pred_q8[i] as i32) >> 8; + out_q10 = (indices[i + 1] as i32) << 10; + if out_q10 > 0 { + out_q10 -= 102; // 0.1 in Q10 + } else if out_q10 < 0 { + out_q10 += 102; + } + out_q10 = smlawb(pred_q10, out_q10, cb.quant_step_size_q16); + res_q10[i] = out_q10 as i16; + } + // Weight by the Laroia measure, add, then enforce the minimum spacing. + let w_qw = nlsf_vq_weights_laroia(&nlsf_q15[..cb.order]); + for i in 0..cb.order { + let w_q9 = sqrt_approx((w_qw[i] as i32) << 16); + let v = nlsf_q15[i] as i32 + (((res_q10[i] as i32) << 14) / w_q9); + nlsf_q15[i] = v.clamp(0, 32767) as i16; + } + nlsf_stabilize(&mut nlsf_q15[..cb.order], cb.delta_min_q15); + nlsf_q15 +} + +/// `silk_NLSF_VQ_weights_laroia` (Section 4.2.7.5.3). +fn nlsf_vq_weights_laroia(nlsf_q15: &[i16]) -> [i16; MAX_LPC_ORDER] { + let d = nlsf_q15.len(); + let mut w = [0i16; MAX_LPC_ORDER]; + let inv = |x: i32| (1i32 << 17) / x.max(1); + let mut tmp1 = inv(nlsf_q15[0] as i32); + let mut tmp2 = inv(nlsf_q15[1] as i32 - nlsf_q15[0] as i32); + w[0] = (tmp1 + tmp2).min(32767) as i16; + let mut k = 1; + while k < d - 1 { + tmp1 = inv(nlsf_q15[k + 1] as i32 - nlsf_q15[k] as i32); + w[k] = (tmp1 + tmp2).min(32767) as i16; + tmp2 = inv(nlsf_q15[k + 2] as i32 - nlsf_q15[k + 1] as i32); + w[k + 1] = (tmp1 + tmp2).min(32767) as i16; + k += 2; + } + tmp1 = inv((1 << 15) - nlsf_q15[d - 1] as i32); + w[d - 1] = (tmp1 + tmp2).min(32767) as i16; + w +} + +/// `silk_NLSF_stabilize` (Section 4.2.7.5.4): enforce the minimum spacing. +fn nlsf_stabilize(nlsf_q15: &mut [i16], delta_min_q15: &[i16]) { + let l = nlsf_q15.len(); + for _ in 0..20 { + let mut min_diff = nlsf_q15[0] as i32 - delta_min_q15[0] as i32; + let mut i_min = 0usize; + for i in 1..l { + let diff = nlsf_q15[i] as i32 - (nlsf_q15[i - 1] as i32 + delta_min_q15[i] as i32); + if diff < min_diff { + min_diff = diff; + i_min = i; + } + } + let diff = (1 << 15) - (nlsf_q15[l - 1] as i32 + delta_min_q15[l] as i32); + if diff < min_diff { + min_diff = diff; + i_min = l; + } + if min_diff >= 0 { + return; + } + if i_min == 0 { + nlsf_q15[0] = delta_min_q15[0]; + } else if i_min == l { + nlsf_q15[l - 1] = ((1 << 15) - delta_min_q15[l] as i32) as i16; + } else { + let mut min_center = 0i32; + for k in 0..i_min { + min_center += delta_min_q15[k] as i32; + } + min_center += delta_min_q15[i_min] as i32 >> 1; + let mut max_center = 1i32 << 15; + for k in (i_min + 1..=l).rev() { + max_center -= delta_min_q15[k] as i32; + } + max_center -= delta_min_q15[i_min] as i32 >> 1; + let center = rshift_round(nlsf_q15[i_min - 1] as i32 + nlsf_q15[i_min] as i32, 1) + .clamp(min_center, max_center); + nlsf_q15[i_min - 1] = (center - (delta_min_q15[i_min] as i32 >> 1)) as i16; + nlsf_q15[i_min] = nlsf_q15[i_min - 1] + delta_min_q15[i_min]; + } + } + // Last resort: sort and clamp (the reference's fallback after 20 loops). + nlsf_q15.sort_unstable(); + nlsf_q15[0] = nlsf_q15[0].max(delta_min_q15[0]); + for i in 1..l { + nlsf_q15[i] = nlsf_q15[i].max(nlsf_q15[i - 1].saturating_add(delta_min_q15[i])); + } + nlsf_q15[l - 1] = nlsf_q15[l - 1].min(((1 << 15) - delta_min_q15[l] as i32) as i16); + for i in (0..l - 1).rev() { + nlsf_q15[i] = nlsf_q15[i].min(nlsf_q15[i + 1] - delta_min_q15[i + 1]); + } +} + +/// `silk_NLSF2A` (Section 4.2.7.5.6): LSFs to LPC coefficients. +fn nlsf2a(nlsf: &[i16], order: usize) -> [i16; MAX_LPC_ORDER] { + const QA: u32 = 16; + const ORDER16: [usize; 16] = [0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1]; + const ORDER10: [usize; 10] = [0, 9, 6, 3, 4, 5, 8, 1, 2, 7]; + let ordering: &[usize] = if order == 16 { &ORDER16 } else { &ORDER10 }; + + let mut cos_lsf_qa = [0i32; MAX_LPC_ORDER]; + for k in 0..order { + let f_int = (nlsf[k] >> 8) as usize; + let f_frac = nlsf[k] as i32 - ((f_int as i32) << 8); + let cos_val = LSFCOSTAB_FIX_Q12[f_int] as i32; + let delta = LSFCOSTAB_FIX_Q12[f_int + 1] as i32 - cos_val; + cos_lsf_qa[ordering[k]] = rshift_round((cos_val << 8) + delta * f_frac, 20 - QA); + } + let dd = order / 2; + let p = nlsf2a_find_poly(&cos_lsf_qa, dd, 0); + let q = nlsf2a_find_poly(&cos_lsf_qa, dd, 1); + + let mut a32_qa1 = [0i32; MAX_LPC_ORDER]; + for k in 0..dd { + let ptmp = p[k + 1] + p[k]; + let qtmp = q[k + 1] - q[k]; + a32_qa1[k] = -qtmp - ptmp; + a32_qa1[order - k - 1] = qtmp - ptmp; + } + + // Clamp into Q12 without letting the filter blow up. + let mut a_q12 = [0i16; MAX_LPC_ORDER]; + let mut i = 0; + while i < 10 { + let mut maxabs = 0i32; + let mut idx = 0usize; + for k in 0..order { + let absval = a32_qa1[k].abs(); + if absval > maxabs { + maxabs = absval; + idx = k; + } + } + let maxabs_q12 = rshift_round(maxabs, QA + 1 - 12); + if maxabs_q12 > 32767 { + let maxabs_q12 = maxabs_q12.min(163838); + let sc_q16 = + 65471 - ((maxabs_q12 - 32767) << 14) / ((maxabs_q12 * (idx as i32 + 1)) >> 2); + bwexpander_32(&mut a32_qa1[..order], sc_q16); + } else { + break; + } + i += 1; + } + if i == 10 { + for k in 0..order { + a_q12[k] = sat16(rshift_round(a32_qa1[k], QA + 1 - 12)); + a32_qa1[k] = (a_q12[k] as i32) << (QA + 1 - 12); + } + } else { + for k in 0..order { + a_q12[k] = rshift_round(a32_qa1[k], QA + 1 - 12) as i16; + } + } + // Bandwidth expansion until the prediction gain is sane. + for i in 0..MAX_LPC_STABILIZE_ITERATIONS { + if lpc_inverse_pred_gain(&a_q12[..order]) < 107374 { + bwexpander_32(&mut a32_qa1[..order], 65536 - (2 << i)); + for k in 0..order { + a_q12[k] = rshift_round(a32_qa1[k], QA + 1 - 12) as i16; + } + } else { + break; + } + } + a_q12 +} + +fn nlsf2a_find_poly(cos_lsf_qa: &[i32], dd: usize, offset: usize) -> [i32; MAX_LPC_ORDER / 2 + 1] { + const QA: u32 = 16; + let mut out = [0i32; MAX_LPC_ORDER / 2 + 1]; + out[0] = 1 << QA; + out[1] = -cos_lsf_qa[offset]; + for k in 1..dd { + let ftmp = cos_lsf_qa[2 * k + offset]; + out[k + 1] = (out[k - 1] << 1) - rshift_round64(ftmp as i64 * out[k] as i64, QA) as i32; + for n in (2..=k).rev() { + out[n] += out[n - 2] - rshift_round64(ftmp as i64 * out[n - 1] as i64, QA) as i32; + } + out[1] -= ftmp; + } + out +} + +fn bwexpander_32(ar: &mut [i32], chirp_q16: i32) { + let mut chirp = chirp_q16; + let chirp_minus_one = chirp_q16 - 65536; + let d = ar.len(); + for coef in ar.iter_mut().take(d - 1) { + *coef = smulww(chirp, *coef); + chirp += rshift_round(chirp.wrapping_mul(chirp_minus_one), 16); + } + ar[d - 1] = smulww(chirp, ar[d - 1]); +} + +/// `silk_LPC_inverse_pred_gain` (Section 4.2.7.5.8), in Q30. +fn lpc_inverse_pred_gain(a_q12: &[i16]) -> i32 { + const QA: u32 = 24; + const A_LIMIT: i32 = 16773022; // 0.99975 in Q24 + let order = a_q12.len(); + let mut a = [[0i32; MAX_LPC_ORDER]; 2]; + let mut dc_resp = 0i32; + for k in 0..order { + dc_resp += a_q12[k] as i32; + a[order & 1][k] = (a_q12[k] as i32) << (QA - 12); + } + if dc_resp >= 4096 { + return 0; + } + let mut cur = order & 1; + let mut inv_gain_q30 = 1i32 << 30; + for k in (1..order).rev() { + if a[cur][k] > A_LIMIT || a[cur][k] < -A_LIMIT { + return 0; + } + let rc_q31 = -(a[cur][k] << (31 - QA)); + let rc_mult1_q30 = (1i32 << 30) - smmul(rc_q31, rc_q31); + let mult2q = 32 - clz32(rc_mult1_q30.abs()); + let rc_mult2 = inverse32_var_q(rc_mult1_q30, (mult2q + 30) as u32); + inv_gain_q30 = smmul(inv_gain_q30, rc_mult1_q30) << 2; + let old = cur; + cur = k & 1; + for n in 0..k { + let tmp = a[old][n] - mul32_frac_q(a[old][k - n - 1], rc_q31, 31); + a[cur][n] = mul32_frac_q(tmp, rc_mult2, mult2q as u32); + } + } + if a[cur][0] > A_LIMIT || a[cur][0] < -A_LIMIT { + return 0; + } + let rc_q31 = -(a[cur][0] << (31 - QA)); + let rc_mult1_q30 = (1i32 << 30) - smmul(rc_q31, rc_q31); + smmul(inv_gain_q30, rc_mult1_q30) << 2 +} + +#[inline] +fn mul32_frac_q(a: i32, b: i32, q: u32) -> i32 { + rshift_round64(a as i64 * b as i64, q) as i32 +} + +/// `silk_gains_dequant` (Section 4.2.7.4). +fn gains_dequant( + indices: &[i8], + prev_ind: &mut i32, + conditional: bool, + nb_subfr: usize, +) -> [i32; MAX_NB_SUBFR] { + let mut gains = [0i32; MAX_NB_SUBFR]; + for k in 0..nb_subfr { + if k == 0 && !conditional { + // A gain may not drop more than 16 steps below the last one. + *prev_ind = (indices[k] as i32).max(*prev_ind - 16); + } else { + let ind_tmp = indices[k] as i32 + MIN_DELTA_GAIN_QUANT; + let threshold = 2 * MAX_DELTA_GAIN_QUANT - N_LEVELS_QGAIN + *prev_ind; + if ind_tmp > threshold { + *prev_ind += (ind_tmp << 1) - threshold; + } else { + *prev_ind += ind_tmp; + } + } + *prev_ind = (*prev_ind).clamp(0, N_LEVELS_QGAIN - 1); + gains[k] = log2lin((smulwb(GAIN_INV_SCALE_Q16, *prev_ind) + GAIN_OFFSET).min(3967)); + } + gains +} + +/// `silk_decode_pitch` (Section 4.2.7.6.1). +fn decode_pitch( + lag_index: i32, + contour_index: i32, + fs_khz: i32, + nb_subfr: usize, +) -> [i32; MAX_NB_SUBFR] { + let mut pitch = [0i32; MAX_NB_SUBFR]; + let min_lag = PE_MIN_LAG_MS * fs_khz; + let max_lag = PE_MAX_LAG_MS * fs_khz; + let lag = min_lag + lag_index; + for k in 0..nb_subfr { + let offset = if fs_khz == 8 { + if nb_subfr == 4 { + CB_LAGS_STAGE2[k][contour_index as usize] + } else { + CB_LAGS_STAGE2_10_MS[k][contour_index as usize] + } + } else if nb_subfr == 4 { + CB_LAGS_STAGE3[k][contour_index as usize] + } else { + CB_LAGS_STAGE3_10_MS[k][contour_index as usize] + }; + pitch[k] = (lag + offset as i32).clamp(min_lag, max_lag); + } + pitch +} + +/// `silk_decode_parameters`. +fn decode_parameters(ch: &mut ChannelState, cond: CondCoding) -> FrameCtrl { + let mut ctrl = FrameCtrl { + gains_q16: gains_dequant( + &ch.indices.gains, + &mut ch.last_gain_index, + cond == CondCoding::Conditionally, + ch.nb_subfr, + ), + ..Default::default() + }; + let cb = nlsf_cb(ch.wb_codebook); + let nlsf_q15 = nlsf_decode(&ch.indices.nlsf, cb); + ctrl.pred_coef_q12[1] = nlsf2a(&nlsf_q15[..ch.lpc_order], ch.lpc_order); + + if ch.first_frame_after_reset { + ch.indices.nlsf_interp_coef_q2 = 4; + } + if ch.indices.nlsf_interp_coef_q2 < 4 { + // Interpolate the first half of the frame from the previous LSFs. + let mut nlsf0 = [0i16; MAX_LPC_ORDER]; + for i in 0..ch.lpc_order { + nlsf0[i] = (ch.prev_nlsf_q15[i] as i32 + + ((ch.indices.nlsf_interp_coef_q2 + * (nlsf_q15[i] as i32 - ch.prev_nlsf_q15[i] as i32)) + >> 2)) as i16; + } + ctrl.pred_coef_q12[0] = nlsf2a(&nlsf0[..ch.lpc_order], ch.lpc_order); + } else { + ctrl.pred_coef_q12[0] = ctrl.pred_coef_q12[1]; + } + ch.prev_nlsf_q15[..ch.lpc_order].copy_from_slice(&nlsf_q15[..ch.lpc_order]); + + if ch.indices.signal_type == TYPE_VOICED { + ctrl.pitch_l = decode_pitch( + ch.indices.lag_index, + ch.indices.contour_index, + ch.fs_khz as i32, + ch.nb_subfr, + ); + let cbk: &[[i8; 5]] = match ch.indices.per_index { + 0 => <P_GAIN_VQ_0, + 1 => <P_GAIN_VQ_1, + _ => <P_GAIN_VQ_2, + }; + for k in 0..ch.nb_subfr { + let v = &cbk[ch.indices.ltp_index[k]]; + for i in 0..LTP_ORDER { + ctrl.ltp_coef_q14[k * LTP_ORDER + i] = (v[i] as i16) << 7; + } + } + ctrl.ltp_scale_q14 = LTPSCALES_TABLE_Q14[ch.indices.ltp_scale_index] as i32; + } + ctrl +} + +/// `silk_LPC_analysis_filter`: the whitening filter used to rebuild the LTP +/// state from previously decoded output. +fn lpc_analysis_filter(out: &mut [i16], input: &[i16], b_q12: &[i16], len: usize, d: usize) { + for ix in d..len { + let mut acc = 0i32; + for j in 0..d { + acc = acc.wrapping_add(smulbb(input[ix - 1 - j] as i32, b_q12[j] as i32)); + } + let v = ((input[ix] as i32) << 12).wrapping_sub(acc); + out[ix] = sat16(rshift_round(v, 12)); + } + out[..d].fill(0); +} + +/// `silk_decode_core` (Section 4.2.7.9): excitation to output samples. +fn decode_core(ch: &mut ChannelState, ctrl: &FrameCtrl, xq: &mut [i16], pulses: &[i32]) { + let offset_q10 = QUANTIZATION_OFFSETS_Q10[ch.indices.signal_type as usize >> 1] + [ch.indices.quant_offset_type as usize] as i32; + let nlsf_interpolated = ch.indices.nlsf_interp_coef_q2 < 4; + + // Excitation: pulses with a quantisation offset and a pseudo-random sign. + let mut rand_seed = ch.indices.seed; + for i in 0..ch.frame_length { + rand_seed = silk_rand(rand_seed); + let mut e = pulses[i] << 14; + if e > 0 { + e -= QUANT_LEVEL_ADJUST_Q10 << 4; + } else if e < 0 { + e += QUANT_LEVEL_ADJUST_Q10 << 4; + } + e += offset_q10 << 4; + ch.exc_q14[i] = if rand_seed < 0 { -e } else { e }; + rand_seed = rand_seed.wrapping_add(pulses[i]); + } + + let mut s_lpc_q14 = [0i32; MAX_LPC_ORDER + 5 * 16]; + s_lpc_q14[..MAX_LPC_ORDER].copy_from_slice(&ch.s_lpc_q14); + let mut s_ltp = [0i16; MAX_FRAME_LENGTH]; + let mut s_ltp_q15 = [0i32; 2 * MAX_FRAME_LENGTH]; + let mut sltp_buf_idx = ch.ltp_mem_length; + let mut lag = 0usize; + let mut res_q14 = [0i32; 5 * 16]; + + for k in 0..ch.nb_subfr { + let a_q12 = &ctrl.pred_coef_q12[k >> 1]; + let b_q14 = &ctrl.ltp_coef_q14[k * LTP_ORDER..k * LTP_ORDER + LTP_ORDER]; + let gain_q10 = ctrl.gains_q16[k] >> 6; + let mut inv_gain_q31 = inverse32_var_q(ctrl.gains_q16[k], 47); + let gain_adj_q16 = if ctrl.gains_q16[k] != ch.prev_gain_q16 { + let adj = div32_var_q(ch.prev_gain_q16, ctrl.gains_q16[k], 16); + for v in s_lpc_q14.iter_mut().take(MAX_LPC_ORDER) { + *v = smulww(adj, *v); + } + adj + } else { + 1 << 16 + }; + ch.prev_gain_q16 = ctrl.gains_q16[k]; + + if ch.indices.signal_type == TYPE_VOICED { + lag = ctrl.pitch_l[k] as usize; + if k == 0 || (k == 2 && nlsf_interpolated) { + // Rebuild the LTP history by whitening past output. + let start_idx = ch.ltp_mem_length - lag - ch.lpc_order - LTP_ORDER / 2; + if k == 2 { + let n = 2 * ch.subfr_length; + let base = ch.ltp_mem_length; + ch.out_buf[base..base + n].copy_from_slice(&xq[..n]); + } + lpc_analysis_filter( + &mut s_ltp[start_idx..], + &ch.out_buf[start_idx + k * ch.subfr_length..], + a_q12, + ch.ltp_mem_length - start_idx, + ch.lpc_order, + ); + if k == 0 { + inv_gain_q31 = smulwb(inv_gain_q31, ctrl.ltp_scale_q14) << 2; + } + for i in 0..lag + LTP_ORDER / 2 { + s_ltp_q15[sltp_buf_idx - i - 1] = + smulwb(inv_gain_q31, s_ltp[ch.ltp_mem_length - i - 1] as i32); + } + } else if gain_adj_q16 != 1 << 16 { + for i in 0..lag + LTP_ORDER / 2 { + s_ltp_q15[sltp_buf_idx - i - 1] = + smulww(gain_adj_q16, s_ltp_q15[sltp_buf_idx - i - 1]); + } + } + } + + // Long-term prediction. + let exc_base = k * ch.subfr_length; + let pres_q14: &[i32] = if ch.indices.signal_type == TYPE_VOICED { + let pred_base = sltp_buf_idx - lag + LTP_ORDER / 2; + for i in 0..ch.subfr_length { + let pred_idx = pred_base + i; + let mut ltp_pred_q13 = 2i32; + for (j, &b) in b_q14.iter().enumerate() { + ltp_pred_q13 = smlawb(ltp_pred_q13, s_ltp_q15[pred_idx - j], b as i32); + } + res_q14[i] = ch.exc_q14[exc_base + i].wrapping_add(ltp_pred_q13 << 1); + s_ltp_q15[sltp_buf_idx] = res_q14[i] << 1; + sltp_buf_idx += 1; + } + &res_q14[..ch.subfr_length] + } else { + &ch.exc_q14[exc_base..exc_base + ch.subfr_length] + }; + + // Short-term (LPC) synthesis. + for i in 0..ch.subfr_length { + let mut lpc_pred_q10 = (ch.lpc_order >> 1) as i32; + for j in 0..ch.lpc_order { + lpc_pred_q10 = smlawb( + lpc_pred_q10, + s_lpc_q14[MAX_LPC_ORDER + i - 1 - j], + a_q12[j] as i32, + ); + } + s_lpc_q14[MAX_LPC_ORDER + i] = pres_q14[i].wrapping_add(lpc_pred_q10 << 4); + xq[k * ch.subfr_length + i] = sat16(rshift_round( + smulww(s_lpc_q14[MAX_LPC_ORDER + i], gain_q10), + 8, + )); + } + s_lpc_q14.copy_within(ch.subfr_length..ch.subfr_length + MAX_LPC_ORDER, 0); + } + ch.s_lpc_q14.copy_from_slice(&s_lpc_q14[..MAX_LPC_ORDER]); +} + +/// `silk_decode_frame`: one SILK frame of one channel. +fn decode_frame( + ch: &mut ChannelState, + dec: &mut RangeDecoder, + out: &mut [i16], + cond: CondCoding, +) -> usize { + let frame_index = ch.frames_decoded; + decode_indices(ch, dec, frame_index, false, cond); + let mut pulses = [0i32; MAX_FRAME_LENGTH + SHELL_LEN]; + decode_pulses( + dec, + &mut pulses, + ch.frame_length, + ch.indices.signal_type, + ch.indices.quant_offset_type, + ); + let mut ctrl = decode_parameters(ch, cond); + if cond == CondCoding::IndependentlyNoLtpScaling { + ctrl.ltp_scale_q14 = LTPSCALES_TABLE_Q14[0] as i32; + } + decode_core(ch, &ctrl, out, &pulses); + ch.prev_signal_type = ch.indices.signal_type; + ch.first_frame_after_reset = false; + ch.lag_prev = ctrl.pitch_l[ch.nb_subfr - 1]; + + // Slide the synthesis history. + let mv_len = ch.ltp_mem_length - ch.frame_length; + ch.out_buf + .copy_within(ch.frame_length..ch.frame_length + mv_len, 0); + ch.out_buf[mv_len..mv_len + ch.frame_length].copy_from_slice(&out[..ch.frame_length]); + ch.frame_length +} + +/// `silk_stereo_decode_pred` (Section 4.2.7.1). +fn stereo_decode_pred(dec: &mut RangeDecoder, pred_q13: &mut [i32; 2]) { + let n = dec.dec_icdf(&STEREO_PRED_JOINT_ICDF, 8) as i32; + let mut ix = [[0i32; 3]; 2]; + ix[0][2] = n / 5; + ix[1][2] = n - 5 * ix[0][2]; + for row in ix.iter_mut() { + row[0] = dec.dec_icdf(&UNIFORM3_ICDF, 8) as i32; + row[1] = dec.dec_icdf(&UNIFORM5_ICDF, 8) as i32; + } + for n in 0..2 { + let i0 = (ix[n][0] + 3 * ix[n][2]) as usize; + let low = STEREO_PRED_QUANT_Q13[i0] as i32; + // 0.5/5 in Q16. + let step = smulwb(STEREO_PRED_QUANT_Q13[i0 + 1] as i32 - low, 6554); + pred_q13[n] = smlabb(low, step, 2 * ix[n][1] + 1); + } + pred_q13[0] -= pred_q13[1]; +} + +/// `silk_stereo_MS_to_LR` (Section 4.2.8): mid/side back to left/right. +fn stereo_ms_to_lr( + state: &mut StereoState, + x1: &mut [i16], + x2: &mut [i16], + pred_q13: &[i32; 2], + fs_khz: usize, + frame_length: usize, +) { + x1[0] = state.s_mid[0]; + x1[1] = state.s_mid[1]; + x2[0] = state.s_side[0]; + x2[1] = state.s_side[1]; + state.s_mid[0] = x1[frame_length]; + state.s_mid[1] = x1[frame_length + 1]; + state.s_side[0] = x2[frame_length]; + state.s_side[1] = x2[frame_length + 1]; + + let interp = STEREO_INTERP_LEN_MS * fs_khz; + let mut pred0 = state.pred_prev_q13[0]; + let mut pred1 = state.pred_prev_q13[1]; + let denom_q16 = (1i32 << 16) / interp as i32; + let delta0 = rshift_round(smulbb(pred_q13[0] - state.pred_prev_q13[0], denom_q16), 16); + let delta1 = rshift_round(smulbb(pred_q13[1] - state.pred_prev_q13[1], denom_q16), 16); + for n in 0..frame_length { + if n < interp { + pred0 += delta0; + pred1 += delta1; + } else { + pred0 = pred_q13[0]; + pred1 = pred_q13[1]; + } + let sum = ((x1[n] as i32 + x1[n + 2] as i32) + ((x1[n + 1] as i32) << 1)) << 9; + let mut acc = smlawb((x2[n + 1] as i32) << 8, sum, pred0); + acc = smlawb(acc, (x1[n + 1] as i32) << 11, pred1); + x2[n + 1] = sat16(rshift_round(acc, 8)); + } + state.pred_prev_q13[0] = pred_q13[0]; + state.pred_prev_q13[1] = pred_q13[1]; + + for n in 0..frame_length { + let sum = x1[n + 1] as i32 + x2[n + 1] as i32; + let diff = x1[n + 1] as i32 - x2[n + 1] as i32; + x1[n + 1] = sat16(sum); + x2[n + 1] = sat16(diff); + } +} + +// --------------------------------------------------------------------------- +// Resampling (Section 4.2.9) +// --------------------------------------------------------------------------- + +/// The SILK output resampler: 8/12/16 kHz internal to the API rate. +/// +/// The RFC calls the resampler non-normative but its *delay* normative, so this +/// is the reference's structure — a 2x all-pass upsampler followed by a +/// 12-phase fractional FIR, with the same per-rate input delay. +#[derive(Clone, Debug, Default)] +struct Resampler { + fs_in_khz: usize, + fs_out_khz: usize, + input_delay: usize, + batch_size: usize, + inv_ratio_q16: i32, + /// All-pass state for the 2x upsampler. + s_iir: [i32; 6], + /// FIR history. + s_fir: [i16; 8], + delay_buf: DelayBuf, + /// Down-sampling coefficients, when the output rate is the lower one. + down: Option, +} + +/// Fixed-size delay line; a newtype only because `[i16; 48]` has no `Default`. +#[derive(Clone, Copy, Debug)] +struct DelayBuf([i16; 48]); + +impl Default for DelayBuf { + fn default() -> Self { + DelayBuf([0; 48]) + } +} + +impl core::ops::Deref for DelayBuf { + type Target = [i16; 48]; + fn deref(&self) -> &[i16; 48] { + &self.0 + } +} + +impl core::ops::DerefMut for DelayBuf { + fn deref_mut(&mut self) -> &mut [i16; 48] { + &mut self.0 + } +} + +#[derive(Clone, Debug)] +struct DownFir { + fracs: usize, + order: usize, + coefs: &'static [i16], + state: [i32; 2], + buf: Vec, +} + +/// `rateID` in the reference: an index into the delay matrix. +fn rate_id(rate: usize) -> usize { + (((rate >> 12) - usize::from(rate > 16000)) >> usize::from(rate > 24000)) - 1 +} + +const DELAY_MATRIX_DEC: [[u8; 5]; 3] = [[4, 0, 2, 0, 0], [0, 9, 4, 7, 4], [0, 3, 12, 7, 7]]; + +impl Resampler { + fn new(fs_in_khz: usize, fs_out_khz: usize) -> Resampler { + let fs_in = fs_in_khz * 1000; + let fs_out = fs_out_khz * 1000; + let mut r = Resampler { + fs_in_khz, + fs_out_khz, + input_delay: DELAY_MATRIX_DEC[rate_id(fs_in)][rate_id(fs_out)] as usize, + batch_size: fs_in_khz * 10, + ..Default::default() + }; + let mut up2x = 0; + if fs_out > fs_in && fs_out != 2 * fs_in { + up2x = 1; + } else if fs_out < fs_in { + let (fracs, order, coefs): (usize, usize, &'static [i16]) = if fs_out * 4 == fs_in * 3 { + (3, 18, &RESAMPLER_3_4_COEFS) + } else if fs_out * 3 == fs_in * 2 { + (2, 18, &RESAMPLER_2_3_COEFS) + } else if fs_out * 2 == fs_in { + (1, 24, &RESAMPLER_1_2_COEFS) + } else if fs_out * 3 == fs_in { + (1, 36, &RESAMPLER_1_3_COEFS) + } else if fs_out * 4 == fs_in { + (1, 36, &RESAMPLER_1_4_COEFS) + } else { + (1, 36, &RESAMPLER_1_6_COEFS) + }; + r.down = Some(DownFir { + fracs, + order, + coefs, + state: [0; 2], + buf: vec![0; 480 + 36], + }); + } + r.inv_ratio_q16 = ((((fs_in as i64) << (14 + up2x)) / fs_out as i64) as i32) << 2; + while smulww(r.inv_ratio_q16, fs_out as i32) < ((fs_in as i32) << up2x) { + r.inv_ratio_q16 += 1; + } + r + } + + /// Resamples `in_len` input samples into `in_len * out/in` outputs. + /// + /// The first `Fs_in_kHz` samples come from the delay line (the normative + /// per-rate input delay); the rest are read straight from `input`, and its + /// tail is kept for the next call. + fn process(&mut self, out: &mut [i16], input: &[i16], in_len: usize) { + let n_first = self.fs_in_khz - self.input_delay; + let mut head = [0i16; 48]; + head[..self.input_delay].copy_from_slice(&self.delay_buf[..self.input_delay]); + head[self.input_delay..self.fs_in_khz].copy_from_slice(&input[..n_first]); + let head = &head[..self.fs_in_khz]; + let rest = &input[n_first..n_first + (in_len - self.fs_in_khz)]; + let split = self.fs_out_khz; + let rest_out = (in_len - self.fs_in_khz) * self.fs_out_khz / self.fs_in_khz; + if self.fs_in_khz == self.fs_out_khz { + out[..self.fs_in_khz].copy_from_slice(head); + out[split..split + rest_out].copy_from_slice(rest); + } else if self.down.is_some() { + let head = head.to_vec(); + self.down_fir(&mut out[..split], &head); + self.down_fir(&mut out[split..split + rest_out], rest); + } else if self.fs_out_khz == 2 * self.fs_in_khz { + let head = head.to_vec(); + self.up2_hq(&mut out[..split], &head); + self.up2_hq(&mut out[split..split + rest_out], rest); + } else { + let head = head.to_vec(); + self.iir_fir(&mut out[..split], &head); + self.iir_fir(&mut out[split..split + rest_out], rest); + } + self.delay_buf[..self.input_delay] + .copy_from_slice(&input[in_len - self.input_delay..in_len]); + } + + /// `silk_resampler_private_up2_HQ`: 2x all-pass upsampling. + fn up2_hq(&mut self, out: &mut [i16], input: &[i16]) { + for (k, &sample) in input.iter().enumerate() { + let in32 = (sample as i32) << 10; + let mut y = in32 - self.s_iir[0]; + let mut x = smulwb(y, RESAMPLER_UP2_HQ_0[0] as i32); + let mut out32_1 = self.s_iir[0] + x; + self.s_iir[0] = in32 + x; + y = out32_1 - self.s_iir[1]; + x = smulwb(y, RESAMPLER_UP2_HQ_0[1] as i32); + let mut out32_2 = self.s_iir[1] + x; + self.s_iir[1] = out32_1 + x; + y = out32_2 - self.s_iir[2]; + x = smlawb(y, y, RESAMPLER_UP2_HQ_0[2] as i32); + out32_1 = self.s_iir[2] + x; + self.s_iir[2] = out32_2 + x; + out[2 * k] = sat16(rshift_round(out32_1, 10)); + + y = in32 - self.s_iir[3]; + x = smulwb(y, RESAMPLER_UP2_HQ_1[0] as i32); + out32_1 = self.s_iir[3] + x; + self.s_iir[3] = in32 + x; + y = out32_1 - self.s_iir[4]; + x = smulwb(y, RESAMPLER_UP2_HQ_1[1] as i32); + out32_2 = self.s_iir[4] + x; + self.s_iir[4] = out32_1 + x; + y = out32_2 - self.s_iir[5]; + x = smlawb(y, y, RESAMPLER_UP2_HQ_1[2] as i32); + out32_1 = self.s_iir[5] + x; + self.s_iir[5] = out32_2 + x; + out[2 * k + 1] = sat16(rshift_round(out32_1, 10)); + } + } + + /// `silk_resampler_private_IIR_FIR`: 2x upsample then fractional FIR. + fn iir_fir(&mut self, out: &mut [i16], input: &[i16]) { + let mut written = 0usize; + let mut pos = 0usize; + let mut buf = vec![0i16; 2 * self.batch_size + 8]; + buf[..8].copy_from_slice(&self.s_fir); + let mut n_samples_in = 0; + while pos < input.len() { + n_samples_in = (input.len() - pos).min(self.batch_size); + self.up2_hq( + &mut buf[8..8 + 2 * n_samples_in], + &input[pos..pos + n_samples_in], + ); + let max_index_q16 = (n_samples_in as i32) << 17; + let mut index_q16 = 0i32; + while index_q16 < max_index_q16 { + let table_index = smulwb(index_q16 & 0xFFFF, 12) as usize; + let b = &buf[(index_q16 >> 16) as usize..]; + let mut res = smulbb(b[0] as i32, RESAMPLER_FRAC_FIR_12[table_index][0] as i32); + res = smlabb( + res, + b[1] as i32, + RESAMPLER_FRAC_FIR_12[table_index][1] as i32, + ); + res = smlabb( + res, + b[2] as i32, + RESAMPLER_FRAC_FIR_12[table_index][2] as i32, + ); + res = smlabb( + res, + b[3] as i32, + RESAMPLER_FRAC_FIR_12[table_index][3] as i32, + ); + res = smlabb( + res, + b[4] as i32, + RESAMPLER_FRAC_FIR_12[11 - table_index][3] as i32, + ); + res = smlabb( + res, + b[5] as i32, + RESAMPLER_FRAC_FIR_12[11 - table_index][2] as i32, + ); + res = smlabb( + res, + b[6] as i32, + RESAMPLER_FRAC_FIR_12[11 - table_index][1] as i32, + ); + res = smlabb( + res, + b[7] as i32, + RESAMPLER_FRAC_FIR_12[11 - table_index][0] as i32, + ); + if written < out.len() { + out[written] = sat16(rshift_round(res, 15)); + } + written += 1; + index_q16 += self.inv_ratio_q16; + } + pos += n_samples_in; + if pos < input.len() { + buf.copy_within(2 * n_samples_in..2 * n_samples_in + 8, 0); + } + } + self.s_fir + .copy_from_slice(&buf[2 * n_samples_in..2 * n_samples_in + 8]); + } + + /// `silk_resampler_private_down_FIR`, for output rates below the internal + /// rate (an AR2 pre-filter, then a polyphase FIR). + fn down_fir(&mut self, out: &mut [i16], input: &[i16]) { + let inv_ratio = self.inv_ratio_q16; + let d = self.down.as_mut().expect("down-sampling state"); + let order = d.order; + let mut buf = core::mem::take(&mut d.buf); + // AR2 pre-filter into Q8. + let a_q14 = [d.coefs[0], d.coefs[1]]; + for (k, &s) in input.iter().enumerate() { + let out32 = d.state[0] + ((s as i32) << 8); + buf[order + k] = out32; + let out32 = out32 << 2; + d.state[0] = smlawb(d.state[1], out32, a_q14[0] as i32); + d.state[1] = smulwb(out32, a_q14[1] as i32); + } + let fir = &d.coefs[2..]; + let fracs = d.fracs; + let mut written = 0usize; + let max_index_q16 = (input.len() as i32) << 16; + let mut index_q16 = 0i32; + while index_q16 < max_index_q16 && written < out.len() { + let base = (index_q16 >> 16) as usize; + let interpol_ind = smulwb(index_q16 & 0xFFFF, fracs as i32) as usize; + let coefs = &fir[interpol_ind * (order / 2)..]; + let mut res = 0i64; + for j in 0..order / 2 { + res += buf[base + j] as i64 * coefs[j] as i64; + res += buf[base + order - 1 - j] as i64 * coefs[j] as i64; + } + out[written] = sat16(rshift_round((res >> 16) as i32, 6)); + written += 1; + index_q16 += inv_ratio; + } + let keep = order; + buf.copy_within(input.len()..input.len() + keep, 0); + d.buf = buf; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fixed_point_helpers_match_their_definitions() { + // Spot values computed from the reference macro definitions. + assert_eq!(smulwb(1 << 20, 3), 48); + assert_eq!(smulbb(-5, 7), -35); + assert_eq!(rshift_round(7, 1), 4); + assert_eq!(rshift_round(-7, 2), -2); + assert_eq!(sat16(40000), 32767); + assert_eq!(sat16(-40000), -32768); + // log2lin is the exponential the gain quantiser uses: 2^(q/128). + for q in [0i32, 128, 1000, 3967] { + let got = log2lin(q) as f64; + let want = (q as f64 / 128.0).exp2(); + assert!( + (got - want).abs() / want < 0.02, + "log2lin({q}) = {got}, want {want}" + ); + } + // sqrt_approx returns sqrt(x) in the same Q domain. It is a coarse + // approximation whose relative error only settles below ~1 % once the + // input has enough significant bits, which is where SILK uses it (the + // NLSF weights are shifted up by 16 first). + for x in [1 << 18, 1234567, 1 << 24, 1 << 30] { + let y = sqrt_approx(x) as f64; + let want = (x as f64).sqrt(); + assert!( + (y - want).abs() / want < 0.02, + "sqrt({x}) = {y}, want {want}" + ); + } + } + + #[test] + fn gains_are_monotonic_in_the_index() { + let mut prev = 0; + let mut last = 0; + for i in 0..64i8 { + let g = gains_dequant(&[i, 0, 0, 0], &mut prev, false, 1)[0]; + assert!(g > last, "gain for index {i} did not increase"); + last = g; + prev = i as i32; + } + } + + #[test] + fn nlsf_stabilize_enforces_the_minimum_spacing() { + let cb = nlsf_cb(false); + let mut nlsf = [100i16, 120, 130, 140, 150, 160, 170, 180, 190, 32700]; + nlsf_stabilize(&mut nlsf, cb.delta_min_q15); + for i in 1..10 { + assert!( + nlsf[i] - nlsf[i - 1] >= cb.delta_min_q15[i], + "spacing at {i}: {} < {}", + nlsf[i] - nlsf[i - 1], + cb.delta_min_q15[i] + ); + } + assert!(nlsf[0] >= cb.delta_min_q15[0]); + assert!((1 << 15) - nlsf[9] as i32 >= cb.delta_min_q15[10] as i32); + } +} diff --git a/crates/ec-opus/src/silk_tables.rs b/crates/ec-opus/src/silk_tables.rs new file mode 100644 index 00000000..8234136f --- /dev/null +++ b/crates/ec-opus/src/silk_tables.rs @@ -0,0 +1,176 @@ +pub const GAIN_ICDF: [[u8; 8]; 3] = [ + [224, 112, 44, 15, 3, 2, 1, 0], + [254, 237, 192, 132, 70, 23, 4, 0], + [255, 252, 226, 155, 61, 11, 2, 0], +]; +pub const DELTA_GAIN_ICDF: [u8; 41] = [250, 245, 234, 203, 71, 50, 42, 38, 35, 33, 31, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; +pub const LTP_PER_INDEX_ICDF: [u8; 3] = [179, 99, 0]; +pub const LTP_GAIN_ICDF_0: [u8; 8] = [71, 56, 43, 30, 21, 12, 6, 0]; +pub const LTP_GAIN_ICDF_1: [u8; 16] = [199, 165, 144, 124, 109, 96, 84, 71, 61, 51, 42, 32, 23, 15, 8, 0]; +pub const LTP_GAIN_ICDF_2: [u8; 32] = [241, 225, 211, 199, 187, 175, 164, 153, 142, 132, 123, 114, 105, 96, 88, 80, 72, 64, 57, 50, 44, 38, 33, 29, 24, 20, 16, 12, 9, 5, 2, 0]; +pub const LTP_GAIN_VQ_0: [[i8; 5]; 8] = [ + [4, 6, 24, 7, 5], + [0, 0, 2, 0, 0], + [12, 28, 41, 13, -4], + [-9, 15, 42, 25, 14], + [1, -2, 62, 41, -9], + [-10, 37, 65, -4, 3], + [-6, 4, 66, 7, -8], + [16, 14, 38, -3, 33], +]; +pub const LTP_GAIN_VQ_1: [[i8; 5]; 16] = [ + [13, 22, 39, 23, 12], + [-1, 36, 64, 27, -6], + [-7, 10, 55, 43, 17], + [1, 1, 8, 1, 1], + [6, -11, 74, 53, -9], + [-12, 55, 76, -12, 8], + [-3, 3, 93, 27, -4], + [26, 39, 59, 3, -8], + [2, 0, 77, 11, 9], + [-8, 22, 44, -6, 7], + [40, 9, 26, 3, 9], + [-7, 20, 101, -7, 4], + [3, -8, 42, 26, 0], + [-15, 33, 68, 2, 23], + [-2, 55, 46, -2, 15], + [3, -1, 21, 16, 41], +]; +pub const LTP_GAIN_VQ_2: [[i8; 5]; 32] = [ + [-6, 27, 61, 39, 5], + [-11, 42, 88, 4, 1], + [-2, 60, 65, 6, -4], + [-1, -5, 73, 56, 1], + [-9, 19, 94, 29, -9], + [0, 12, 99, 6, 4], + [8, -19, 102, 46, -13], + [3, 2, 13, 3, 2], + [9, -21, 84, 72, -18], + [-11, 46, 104, -22, 8], + [18, 38, 48, 23, 0], + [-16, 70, 83, -21, 11], + [5, -11, 117, 22, -8], + [-6, 23, 117, -12, 3], + [3, -8, 95, 28, 4], + [-10, 15, 77, 60, -15], + [-1, 4, 124, 2, -4], + [3, 38, 84, 24, -25], + [2, 13, 42, 13, 31], + [21, -4, 56, 46, -1], + [-1, 35, 79, -13, 19], + [-7, 65, 88, -9, -14], + [20, 4, 81, 49, -29], + [20, 0, 75, 3, -17], + [5, -9, 44, 92, -8], + [1, -3, 22, 69, 31], + [-6, 95, 41, -12, 5], + [39, 67, 16, -4, 1], + [0, -6, 120, 55, -36], + [-13, 44, 122, 4, -24], + [81, 5, 11, 3, 7], + [2, 0, 9, 10, 88], +]; +pub const STEREO_PRED_QUANT_Q13: [i16; 16] = [-13732, -10050, -8266, -7526, -6500, -5000, -2950, -820, 820, 2950, 5000, 6500, 7526, 8266, 10050, 13732]; +pub const STEREO_PRED_JOINT_ICDF: [u8; 25] = [249, 247, 246, 245, 244, 234, 210, 202, 201, 200, 197, 174, 82, 59, 56, 55, 54, 46, 22, 12, 11, 10, 9, 7, 0]; +pub const STEREO_ONLY_CODE_MID_ICDF: [u8; 2] = [64, 0]; +pub const LBRR_FLAGS_2_ICDF: [u8; 3] = [203, 150, 0]; +pub const LBRR_FLAGS_3_ICDF: [u8; 7] = [215, 195, 166, 125, 110, 82, 0]; +pub const LSB_ICDF: [u8; 2] = [120, 0]; +pub const LTPSCALE_ICDF: [u8; 3] = [128, 64, 0]; +pub const TYPE_OFFSET_VAD_ICDF: [u8; 4] = [232, 158, 10, 0]; +pub const TYPE_OFFSET_NO_VAD_ICDF: [u8; 2] = [230, 0]; +pub const NLSF_INTERPOLATION_FACTOR_ICDF: [u8; 5] = [243, 221, 192, 181, 0]; +pub const QUANTIZATION_OFFSETS_Q10: [[i16; 2]; 2] = [ + [100, 240], + [32, 100], +]; +pub const LTPSCALES_TABLE_Q14: [i16; 3] = [15565, 12288, 8192]; +pub const UNIFORM3_ICDF: [u8; 3] = [171, 85, 0]; +pub const UNIFORM4_ICDF: [u8; 4] = [192, 128, 64, 0]; +pub const UNIFORM5_ICDF: [u8; 5] = [205, 154, 102, 51, 0]; +pub const UNIFORM6_ICDF: [u8; 6] = [213, 171, 128, 85, 43, 0]; +pub const UNIFORM8_ICDF: [u8; 8] = [224, 192, 160, 128, 96, 64, 32, 0]; +pub const NLSF_EXT_ICDF: [u8; 7] = [100, 40, 16, 7, 3, 1, 0]; +pub const PITCH_LAG_ICDF: [u8; 32] = [253, 250, 244, 233, 212, 182, 150, 131, 120, 110, 98, 85, 72, 60, 49, 40, 32, 25, 19, 15, 13, 11, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; +pub const PITCH_DELTA_ICDF: [u8; 21] = [210, 208, 206, 203, 199, 193, 183, 168, 142, 104, 74, 52, 37, 27, 20, 14, 10, 6, 4, 2, 0]; +pub const PITCH_CONTOUR_ICDF: [u8; 34] = [223, 201, 183, 167, 152, 138, 124, 111, 98, 88, 79, 70, 62, 56, 50, 44, 39, 35, 31, 27, 24, 21, 18, 16, 14, 12, 10, 8, 6, 4, 3, 2, 1, 0]; +pub const PITCH_CONTOUR_NB_ICDF: [u8; 11] = [188, 176, 155, 138, 119, 97, 67, 43, 26, 10, 0]; +pub const PITCH_CONTOUR_10_MS_ICDF: [u8; 12] = [165, 119, 80, 61, 47, 35, 27, 20, 14, 9, 4, 0]; +pub const PITCH_CONTOUR_10_MS_NB_ICDF: [u8; 3] = [113, 63, 0]; +pub const PULSES_PER_BLOCK_ICDF: [[u8; 18]; 10] = [ + [125, 51, 26, 18, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0], + [198, 105, 45, 22, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0], + [213, 162, 116, 83, 59, 43, 32, 24, 18, 15, 12, 9, 7, 6, 5, 3, 2, 0], + [239, 187, 116, 59, 28, 16, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0], + [250, 229, 188, 135, 86, 51, 30, 19, 13, 10, 8, 6, 5, 4, 3, 2, 1, 0], + [249, 235, 213, 185, 156, 128, 103, 83, 66, 53, 42, 33, 26, 21, 17, 13, 10, 0], + [254, 249, 235, 206, 164, 118, 77, 46, 27, 16, 10, 7, 5, 4, 3, 2, 1, 0], + [255, 253, 249, 239, 220, 191, 156, 119, 85, 57, 37, 23, 15, 10, 6, 4, 2, 0], + [255, 253, 251, 246, 237, 223, 203, 179, 152, 124, 98, 75, 55, 40, 29, 21, 15, 0], + [255, 254, 253, 247, 220, 162, 106, 67, 42, 28, 18, 12, 9, 6, 4, 3, 2, 0], +]; +pub const RATE_LEVELS_ICDF: [[u8; 9]; 2] = [ + [241, 190, 178, 132, 87, 74, 41, 14, 0], + [223, 193, 157, 140, 106, 57, 39, 18, 0], +]; +pub const SHELL_CODE_TABLE0: [u8; 152] = [128, 0, 214, 42, 0, 235, 128, 21, 0, 244, 184, 72, 11, 0, 248, 214, 128, 42, 7, 0, 248, 225, 170, 80, 25, 5, 0, 251, 236, 198, 126, 54, 18, 3, 0, 250, 238, 211, 159, 82, 35, 15, 5, 0, 250, 231, 203, 168, 128, 88, 53, 25, 6, 0, 252, 238, 216, 185, 148, 108, 71, 40, 18, 4, 0, 253, 243, 225, 199, 166, 128, 90, 57, 31, 13, 3, 0, 254, 246, 233, 212, 183, 147, 109, 73, 44, 23, 10, 2, 0, 255, 250, 240, 223, 198, 166, 128, 90, 58, 33, 16, 6, 1, 0, 255, 251, 244, 231, 210, 181, 146, 110, 75, 46, 25, 12, 5, 1, 0, 255, 253, 248, 238, 221, 196, 164, 128, 92, 60, 35, 18, 8, 3, 1, 0, 255, 253, 249, 242, 229, 208, 180, 146, 110, 76, 48, 27, 14, 7, 3, 1, 0]; +pub const SHELL_CODE_TABLE1: [u8; 152] = [129, 0, 207, 50, 0, 236, 129, 20, 0, 245, 185, 72, 10, 0, 249, 213, 129, 42, 6, 0, 250, 226, 169, 87, 27, 4, 0, 251, 233, 194, 130, 62, 20, 4, 0, 250, 236, 207, 160, 99, 47, 17, 3, 0, 255, 240, 217, 182, 131, 81, 41, 11, 1, 0, 255, 254, 233, 201, 159, 107, 61, 20, 2, 1, 0, 255, 249, 233, 206, 170, 128, 86, 50, 23, 7, 1, 0, 255, 250, 238, 217, 186, 148, 108, 70, 39, 18, 6, 1, 0, 255, 252, 243, 226, 200, 166, 128, 90, 56, 30, 13, 4, 1, 0, 255, 252, 245, 231, 209, 180, 146, 110, 76, 47, 25, 11, 4, 1, 0, 255, 253, 248, 237, 219, 194, 163, 128, 93, 62, 37, 19, 8, 3, 1, 0, 255, 254, 250, 241, 226, 205, 177, 145, 111, 79, 51, 30, 15, 6, 2, 1, 0]; +pub const SHELL_CODE_TABLE2: [u8; 152] = [129, 0, 203, 54, 0, 234, 129, 23, 0, 245, 184, 73, 10, 0, 250, 215, 129, 41, 5, 0, 252, 232, 173, 86, 24, 3, 0, 253, 240, 200, 129, 56, 15, 2, 0, 253, 244, 217, 164, 94, 38, 10, 1, 0, 253, 245, 226, 189, 132, 71, 27, 7, 1, 0, 253, 246, 231, 203, 159, 105, 56, 23, 6, 1, 0, 255, 248, 235, 213, 179, 133, 85, 47, 19, 5, 1, 0, 255, 254, 243, 221, 194, 159, 117, 70, 37, 12, 2, 1, 0, 255, 254, 248, 234, 208, 171, 128, 85, 48, 22, 8, 2, 1, 0, 255, 254, 250, 240, 220, 189, 149, 107, 67, 36, 16, 6, 2, 1, 0, 255, 254, 251, 243, 227, 201, 166, 128, 90, 55, 29, 13, 5, 2, 1, 0, 255, 254, 252, 246, 234, 213, 183, 147, 109, 73, 43, 22, 10, 4, 2, 1, 0]; +pub const SHELL_CODE_TABLE3: [u8; 152] = [130, 0, 200, 58, 0, 231, 130, 26, 0, 244, 184, 76, 12, 0, 249, 214, 130, 43, 6, 0, 252, 232, 173, 87, 24, 3, 0, 253, 241, 203, 131, 56, 14, 2, 0, 254, 246, 221, 167, 94, 35, 8, 1, 0, 254, 249, 232, 193, 130, 65, 23, 5, 1, 0, 255, 251, 239, 211, 162, 99, 45, 15, 4, 1, 0, 255, 251, 243, 223, 186, 131, 74, 33, 11, 3, 1, 0, 255, 252, 245, 230, 202, 158, 105, 57, 24, 8, 2, 1, 0, 255, 253, 247, 235, 214, 179, 132, 84, 44, 19, 7, 2, 1, 0, 255, 254, 250, 240, 223, 196, 159, 112, 69, 36, 15, 6, 2, 1, 0, 255, 254, 253, 245, 231, 209, 176, 136, 93, 55, 27, 11, 3, 2, 1, 0, 255, 254, 253, 252, 239, 221, 194, 158, 117, 76, 42, 18, 4, 3, 2, 1, 0]; +pub const SHELL_CODE_TABLE_OFFSETS: [u8; 17] = [0, 0, 2, 5, 9, 14, 20, 27, 35, 44, 54, 65, 77, 90, 104, 119, 135]; +pub const SIGN_ICDF: [u8; 42] = [254, 49, 67, 77, 82, 93, 99, 198, 11, 18, 24, 31, 36, 45, 255, 46, 66, 78, 87, 94, 104, 208, 14, 21, 32, 42, 51, 66, 255, 94, 104, 109, 112, 115, 118, 248, 53, 69, 80, 88, 95, 102]; +pub const NLSF_CB1_NB_MB_Q8: [u8; 320] = [12, 35, 60, 83, 108, 132, 157, 180, 206, 228, 15, 32, 55, 77, 101, 125, 151, 175, 201, 225, 19, 42, 66, 89, 114, 137, 162, 184, 209, 230, 12, 25, 50, 72, 97, 120, 147, 172, 200, 223, 26, 44, 69, 90, 114, 135, 159, 180, 205, 225, 13, 22, 53, 80, 106, 130, 156, 180, 205, 228, 15, 25, 44, 64, 90, 115, 142, 168, 196, 222, 19, 24, 62, 82, 100, 120, 145, 168, 190, 214, 22, 31, 50, 79, 103, 120, 151, 170, 203, 227, 21, 29, 45, 65, 106, 124, 150, 171, 196, 224, 30, 49, 75, 97, 121, 142, 165, 186, 209, 229, 19, 25, 52, 70, 93, 116, 143, 166, 192, 219, 26, 34, 62, 75, 97, 118, 145, 167, 194, 217, 25, 33, 56, 70, 91, 113, 143, 165, 196, 223, 21, 34, 51, 72, 97, 117, 145, 171, 196, 222, 20, 29, 50, 67, 90, 117, 144, 168, 197, 221, 22, 31, 48, 66, 95, 117, 146, 168, 196, 222, 24, 33, 51, 77, 116, 134, 158, 180, 200, 224, 21, 28, 70, 87, 106, 124, 149, 170, 194, 217, 26, 33, 53, 64, 83, 117, 152, 173, 204, 225, 27, 34, 65, 95, 108, 129, 155, 174, 210, 225, 20, 26, 72, 99, 113, 131, 154, 176, 200, 219, 34, 43, 61, 78, 93, 114, 155, 177, 205, 229, 23, 29, 54, 97, 124, 138, 163, 179, 209, 229, 30, 38, 56, 89, 118, 129, 158, 178, 200, 231, 21, 29, 49, 63, 85, 111, 142, 163, 193, 222, 27, 48, 77, 103, 133, 158, 179, 196, 215, 232, 29, 47, 74, 99, 124, 151, 176, 198, 220, 237, 33, 42, 61, 76, 93, 121, 155, 174, 207, 225, 29, 53, 87, 112, 136, 154, 170, 188, 208, 227, 24, 30, 52, 84, 131, 150, 166, 186, 203, 229, 37, 48, 64, 84, 104, 118, 156, 177, 201, 230]; +pub const NLSF_CB1_ICDF_NB_MB: [u8; 64] = [212, 178, 148, 129, 108, 96, 85, 82, 79, 77, 61, 59, 57, 56, 51, 49, 48, 45, 42, 41, 40, 38, 36, 34, 31, 30, 21, 12, 10, 3, 1, 0, 255, 245, 244, 236, 233, 225, 217, 203, 190, 176, 175, 161, 149, 136, 125, 114, 102, 91, 81, 71, 60, 52, 43, 35, 28, 20, 19, 18, 12, 11, 5, 0]; +pub const NLSF_CB2_SELECT_NB_MB: [u8; 160] = [16, 0, 0, 0, 0, 99, 66, 36, 36, 34, 36, 34, 34, 34, 34, 83, 69, 36, 52, 34, 116, 102, 70, 68, 68, 176, 102, 68, 68, 34, 65, 85, 68, 84, 36, 116, 141, 152, 139, 170, 132, 187, 184, 216, 137, 132, 249, 168, 185, 139, 104, 102, 100, 68, 68, 178, 218, 185, 185, 170, 244, 216, 187, 187, 170, 244, 187, 187, 219, 138, 103, 155, 184, 185, 137, 116, 183, 155, 152, 136, 132, 217, 184, 184, 170, 164, 217, 171, 155, 139, 244, 169, 184, 185, 170, 164, 216, 223, 218, 138, 214, 143, 188, 218, 168, 244, 141, 136, 155, 170, 168, 138, 220, 219, 139, 164, 219, 202, 216, 137, 168, 186, 246, 185, 139, 116, 185, 219, 185, 138, 100, 100, 134, 100, 102, 34, 68, 68, 100, 68, 168, 203, 221, 218, 168, 167, 154, 136, 104, 70, 164, 246, 171, 137, 139, 137, 155, 218, 219, 139]; +pub const NLSF_CB2_ICDF_NB_MB: [u8; 72] = [255, 254, 253, 238, 14, 3, 2, 1, 0, 255, 254, 252, 218, 35, 3, 2, 1, 0, 255, 254, 250, 208, 59, 4, 2, 1, 0, 255, 254, 246, 194, 71, 10, 2, 1, 0, 255, 252, 236, 183, 82, 8, 2, 1, 0, 255, 252, 235, 180, 90, 17, 2, 1, 0, 255, 248, 224, 171, 97, 30, 4, 1, 0, 255, 254, 236, 173, 95, 37, 7, 1, 0]; +pub const NLSF_PRED_NB_MB_Q8: [u8; 18] = [179, 138, 140, 148, 151, 149, 153, 151, 163, 116, 67, 82, 59, 92, 72, 100, 89, 92]; +pub const NLSF_DELTA_MIN_NB_MB_Q15: [i16; 11] = [250, 3, 6, 3, 3, 3, 4, 3, 3, 3, 461]; +pub const NLSF_CB1_WB_Q8: [u8; 512] = [7, 23, 38, 54, 69, 85, 100, 116, 131, 147, 162, 178, 193, 208, 223, 239, 13, 25, 41, 55, 69, 83, 98, 112, 127, 142, 157, 171, 187, 203, 220, 236, 15, 21, 34, 51, 61, 78, 92, 106, 126, 136, 152, 167, 185, 205, 225, 240, 10, 21, 36, 50, 63, 79, 95, 110, 126, 141, 157, 173, 189, 205, 221, 237, 17, 20, 37, 51, 59, 78, 89, 107, 123, 134, 150, 164, 184, 205, 224, 240, 10, 15, 32, 51, 67, 81, 96, 112, 129, 142, 158, 173, 189, 204, 220, 236, 8, 21, 37, 51, 65, 79, 98, 113, 126, 138, 155, 168, 179, 192, 209, 218, 12, 15, 34, 55, 63, 78, 87, 108, 118, 131, 148, 167, 185, 203, 219, 236, 16, 19, 32, 36, 56, 79, 91, 108, 118, 136, 154, 171, 186, 204, 220, 237, 11, 28, 43, 58, 74, 89, 105, 120, 135, 150, 165, 180, 196, 211, 226, 241, 6, 16, 33, 46, 60, 75, 92, 107, 123, 137, 156, 169, 185, 199, 214, 225, 11, 19, 30, 44, 57, 74, 89, 105, 121, 135, 152, 169, 186, 202, 218, 234, 12, 19, 29, 46, 57, 71, 88, 100, 120, 132, 148, 165, 182, 199, 216, 233, 17, 23, 35, 46, 56, 77, 92, 106, 123, 134, 152, 167, 185, 204, 222, 237, 14, 17, 45, 53, 63, 75, 89, 107, 115, 132, 151, 171, 188, 206, 221, 240, 9, 16, 29, 40, 56, 71, 88, 103, 119, 137, 154, 171, 189, 205, 222, 237, 16, 19, 36, 48, 57, 76, 87, 105, 118, 132, 150, 167, 185, 202, 218, 236, 12, 17, 29, 54, 71, 81, 94, 104, 126, 136, 149, 164, 182, 201, 221, 237, 15, 28, 47, 62, 79, 97, 115, 129, 142, 155, 168, 180, 194, 208, 223, 238, 8, 14, 30, 45, 62, 78, 94, 111, 127, 143, 159, 175, 192, 207, 223, 239, 17, 30, 49, 62, 79, 92, 107, 119, 132, 145, 160, 174, 190, 204, 220, 235, 14, 19, 36, 45, 61, 76, 91, 108, 121, 138, 154, 172, 189, 205, 222, 238, 12, 18, 31, 45, 60, 76, 91, 107, 123, 138, 154, 171, 187, 204, 221, 236, 13, 17, 31, 43, 53, 70, 83, 103, 114, 131, 149, 167, 185, 203, 220, 237, 17, 22, 35, 42, 58, 78, 93, 110, 125, 139, 155, 170, 188, 206, 224, 240, 8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239, 13, 16, 41, 66, 73, 86, 95, 111, 128, 137, 150, 163, 183, 206, 225, 241, 17, 25, 37, 52, 63, 75, 92, 102, 119, 132, 144, 160, 175, 191, 212, 231, 19, 31, 49, 65, 83, 100, 117, 133, 147, 161, 174, 187, 200, 213, 227, 242, 18, 31, 52, 68, 88, 103, 117, 126, 138, 149, 163, 177, 192, 207, 223, 239, 16, 29, 47, 61, 76, 90, 106, 119, 133, 147, 161, 176, 193, 209, 224, 240, 15, 21, 35, 50, 61, 73, 86, 97, 110, 119, 129, 141, 175, 198, 218, 237]; +pub const NLSF_CB1_ICDF_WB: [u8; 64] = [225, 204, 201, 184, 183, 175, 158, 154, 153, 135, 119, 115, 113, 110, 109, 99, 98, 95, 79, 68, 52, 50, 48, 45, 43, 32, 31, 27, 18, 10, 3, 0, 255, 251, 235, 230, 212, 201, 196, 182, 167, 166, 163, 151, 138, 124, 110, 104, 90, 78, 76, 70, 69, 57, 45, 34, 24, 21, 11, 6, 5, 4, 3, 0]; +pub const NLSF_CB2_SELECT_WB: [u8; 256] = [0, 0, 0, 0, 0, 0, 0, 1, 100, 102, 102, 68, 68, 36, 34, 96, 164, 107, 158, 185, 180, 185, 139, 102, 64, 66, 36, 34, 34, 0, 1, 32, 208, 139, 141, 191, 152, 185, 155, 104, 96, 171, 104, 166, 102, 102, 102, 132, 1, 0, 0, 0, 0, 16, 16, 0, 80, 109, 78, 107, 185, 139, 103, 101, 208, 212, 141, 139, 173, 153, 123, 103, 36, 0, 0, 0, 0, 0, 0, 1, 48, 0, 0, 0, 0, 0, 0, 32, 68, 135, 123, 119, 119, 103, 69, 98, 68, 103, 120, 118, 118, 102, 71, 98, 134, 136, 157, 184, 182, 153, 139, 134, 208, 168, 248, 75, 189, 143, 121, 107, 32, 49, 34, 34, 34, 0, 17, 2, 210, 235, 139, 123, 185, 137, 105, 134, 98, 135, 104, 182, 100, 183, 171, 134, 100, 70, 68, 70, 66, 66, 34, 131, 64, 166, 102, 68, 36, 2, 1, 0, 134, 166, 102, 68, 34, 34, 66, 132, 212, 246, 158, 139, 107, 107, 87, 102, 100, 219, 125, 122, 137, 118, 103, 132, 114, 135, 137, 105, 171, 106, 50, 34, 164, 214, 141, 143, 185, 151, 121, 103, 192, 34, 0, 0, 0, 0, 0, 1, 208, 109, 74, 187, 134, 249, 159, 137, 102, 110, 154, 118, 87, 101, 119, 101, 0, 2, 0, 36, 36, 66, 68, 35, 96, 164, 102, 100, 36, 0, 2, 33, 167, 138, 174, 102, 100, 84, 2, 2, 100, 107, 120, 119, 36, 197, 24, 0]; +pub const NLSF_CB2_ICDF_WB: [u8; 72] = [255, 254, 253, 244, 12, 3, 2, 1, 0, 255, 254, 252, 224, 38, 3, 2, 1, 0, 255, 254, 251, 209, 57, 4, 2, 1, 0, 255, 254, 244, 195, 69, 4, 2, 1, 0, 255, 251, 232, 184, 84, 7, 2, 1, 0, 255, 254, 240, 186, 86, 14, 2, 1, 0, 255, 254, 239, 178, 91, 30, 5, 1, 0, 255, 248, 227, 177, 100, 19, 2, 1, 0]; +pub const NLSF_PRED_WB_Q8: [u8; 30] = [175, 148, 160, 176, 178, 173, 174, 164, 177, 174, 196, 182, 198, 192, 182, 68, 62, 66, 60, 72, 117, 85, 90, 118, 136, 151, 142, 160, 142, 155]; +pub const NLSF_DELTA_MIN_WB_Q15: [i16; 17] = [100, 3, 40, 3, 3, 3, 5, 14, 14, 10, 11, 3, 8, 9, 7, 3, 347]; +pub const LSFCOSTAB_FIX_Q12: [i16; 129] = [8192, 8190, 8182, 8170, 8152, 8130, 8104, 8072, 8034, 7994, 7946, 7896, 7840, 7778, 7714, 7644, 7568, 7490, 7406, 7318, 7226, 7128, 7026, 6922, 6812, 6698, 6580, 6458, 6332, 6204, 6070, 5934, 5792, 5648, 5502, 5352, 5198, 5040, 4880, 4718, 4552, 4382, 4212, 4038, 3862, 3684, 3502, 3320, 3136, 2948, 2760, 2570, 2378, 2186, 1990, 1794, 1598, 1400, 1202, 1002, 802, 602, 402, 202, 0, -202, -402, -602, -802, -1002, -1202, -1400, -1598, -1794, -1990, -2186, -2378, -2570, -2760, -2948, -3136, -3320, -3502, -3684, -3862, -4038, -4212, -4382, -4552, -4718, -4880, -5040, -5198, -5352, -5502, -5648, -5792, -5934, -6070, -6204, -6332, -6458, -6580, -6698, -6812, -6922, -7026, -7128, -7226, -7318, -7406, -7490, -7568, -7644, -7714, -7778, -7840, -7896, -7946, -7994, -8034, -8072, -8104, -8130, -8152, -8170, -8182, -8190, -8192]; +pub const RESAMPLER_UP2_HQ_0: [i16; 3] = [1746, 14986, -26453]; +pub const RESAMPLER_UP2_HQ_1: [i16; 3] = [6854, 25769, -9994]; +pub const RESAMPLER_FRAC_FIR_12: [[i16; 4]; 12] = [ + [189, -600, 617, 30567], + [117, -159, -1070, 29704], + [52, 221, -2392, 28276], + [-4, 529, -3350, 26341], + [-48, 758, -3956, 23973], + [-80, 905, -4235, 21254], + [-99, 972, -4222, 18278], + [-107, 967, -3957, 15143], + [-103, 896, -3487, 11950], + [-91, 773, -2865, 8798], + [-71, 611, -2143, 5784], + [-46, 425, -1375, 2996], +]; +pub const RESAMPLER_3_4_COEFS: [i16; 29] = [-20694, -13867, -49, 64, 17, -157, 353, -496, 163, 11047, 22205, -39, 6, 91, -170, 186, 23, -896, 6336, 19928, -19, -36, 102, -89, -24, 328, -951, 2568, 15909]; +pub const RESAMPLER_2_3_COEFS: [i16; 20] = [-14457, -14019, 64, 128, -122, 36, 310, -768, 584, 9267, 17733, 12, 128, 18, -142, 288, -117, -865, 4123, 14459]; +pub const RESAMPLER_1_2_COEFS: [i16; 14] = [616, -14323, -10, 39, 58, -46, -84, 120, 184, -315, -541, 1284, 5380, 9024]; +pub const RESAMPLER_1_3_COEFS: [i16; 20] = [16102, -15162, -13, 0, 20, 26, 5, -31, -43, -4, 65, 90, 7, -157, -248, -44, 593, 1583, 2612, 3271]; +pub const RESAMPLER_1_4_COEFS: [i16; 20] = [22500, -15099, 3, -14, -20, -15, 2, 25, 37, 25, -16, -71, -107, -79, 50, 292, 623, 982, 1288, 1464]; +pub const RESAMPLER_1_6_COEFS: [i16; 20] = [27540, -15257, 17, 12, 8, 1, -10, -22, -30, -32, -22, 3, 44, 100, 168, 243, 317, 381, 429, 455]; +pub const CB_LAGS_STAGE2: [[i8; 11]; 4] = [ + [0, 2, -1, -1, -1, 0, 0, 1, 1, 0, 1], + [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0], + [0, -1, 2, 1, 0, 1, 1, 0, 0, -1, -1], +]; +pub const CB_LAGS_STAGE3: [[i8; 34]; 4] = [ + [0, 0, 1, -1, 0, 1, -1, 0, -1, 1, -2, 2, -2, -2, 2, -3, 2, 3, -3, -4, 3, -4, 4, 4, -5, 5, -6, -5, 6, -7, 6, 5, 8, -9], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0, 1, -1, -1, 1, -1, 2, 1, -1, 2, -2, -2, 2, -2, 2, 2, 3, -3], + [0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, -1, 1, 0, 0, 2, 1, -1, 2, -1, -1, 2, -1, 2, 2, -1, 3, -2, -2, -2, 3], + [0, 1, 0, 0, 1, 0, 1, -1, 2, -1, 2, -1, 2, 3, -2, 3, -2, -2, 4, 4, -3, 5, -3, -4, 6, -4, 6, 5, -5, 8, -6, -5, -7, 9], +]; +pub const CB_LAGS_STAGE2_10_MS: [[i8; 3]; 2] = [ + [0, 1, 0], + [0, 0, 1], +]; +pub const CB_LAGS_STAGE3_10_MS: [[i8; 12]; 2] = [ + [0, 0, 1, -1, 1, -1, 2, -2, 2, -2, 3, -3], + [0, 1, 0, 1, -1, 2, -1, 2, -2, 3, -2, 3], +]; diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 434745e6..ce507366 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -316,12 +316,29 @@ fn read_i16(path: &Path) -> Vec { .collect() } -/// The CELT-only vectors, which need no SILK layer. -const CELT_VECTORS: [&str; 3] = ["testvector01", "testvector07", "testvector11"]; +/// Every vector in the RFC 6716 suite, in the order the RFC lists them. +const VECTORS: [&str; 12] = [ + "testvector01", + "testvector02", + "testvector03", + "testvector04", + "testvector05", + "testvector06", + "testvector07", + "testvector08", + "testvector09", + "testvector10", + "testvector11", + "testvector12", +]; +/// The conformance test of RFC 6716 Section 6, both halves of it: the decoder's +/// range coder state MUST match the reference on every packet, and the output +/// MUST stay within the `opus_compare` threshold (quality >= 0). #[test] -fn celt_vectors_match_the_reference_range_state() { - for name in CELT_VECTORS { +fn rfc6716_test_vectors() { + let mut table = Vec::new(); + for name in VECTORS { let path = vectors_dir().join(format!("{name}.bit")); if !path.exists() { eprintln!("{name}: missing, skipped (run scripts/fetch-vectors.sh)"); @@ -329,23 +346,32 @@ fn celt_vectors_match_the_reference_range_state() { } let packets = read_vector(&path); let (pcm, matched, decoded) = decode_vector(&packets); - println!( - "{name}: {matched}/{decoded} packets bit-exact, {} samples", - pcm.len() / 2 + let reference = read_i16(&vectors_dir().join(format!("{name}.dec"))); + let mine = to_i16(&pcm); + assert_eq!( + reference.len(), + mine.len(), + "{name}: decoded {} samples, reference has {}", + mine.len() / 2, + reference.len() / 2 ); + let identical = reference.iter().zip(&mine).filter(|(a, b)| a == b).count(); + let quality = opus_compare(&reference, &mine, 2); + table.push(format!( + "{name}: {matched}/{decoded} packets range-exact, \ + {:.4} % samples identical, quality {quality:.2} %", + 100.0 * identical as f64 / reference.len() as f64 + )); assert_eq!( matched, decoded, - "{name}: range state diverged from the reference" + "{name}: range coder state diverged from the reference" ); - - let reference = read_i16(&vectors_dir().join(format!("{name}.dec"))); - let mine = to_i16(&pcm); - let n = reference.len().min(mine.len()); - let q = opus_compare(&reference[..n], &mine[..n], 2); - println!("{name}: opus_compare quality {q:.1} %"); assert!( - q >= 0.0, - "{name}: opus_compare quality {q:.1} % (must be >= 0)" + quality >= 0.0, + "{name}: opus_compare quality {quality:.2} %" ); } + for line in table { + println!("{line}"); + } }