diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index d0460fc2..b0df48a7 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -21,12 +21,14 @@ //! - **Output is `f32`, interleaved, at the rate you asked for.** 48, 24, 16, //! 12 and 8 kHz are supported; SILK's internal rate is resampled up (by the //! normative resampler in [`silk`]) and CELT decimates on the way out. -//! - **Packet loss concealment is CELT-only.** [`Decoder::conceal`] (or an -//! empty packet to [`Decoder::decode_float`]) extends the last CELT frame: +//! - **Packet loss concealment.** [`Decoder::conceal`] (or an empty packet to +//! [`Decoder::decode_float`]) extends the last frame: a CELT frame gets //! pitch-periodic LPC extension for the first losses, then decaying -//! band-shaped noise. After a SILK or hybrid frame it yields silence, as does -//! a one-byte (DTX) frame inside a packet. [`Decoder::decode_fec`] recovers -//! a lost SILK or hybrid frame from the in-band FEC of the next packet. +//! band-shaped noise; a SILK or hybrid frame is concealed by the SILK PLC (a +//! port of libopus `silk/PLC.c`, without comfort noise). A one-byte (DTX) +//! frame inside a packet is concealed the same way. [`Decoder::decode_fec`] +//! recovers a lost SILK or hybrid frame from the in-band FEC of the next +//! packet. //! //! The crate also carries the family's Opus *encoder* — [`Encoder`] for one //! stream, [`MultistreamEncoder`] for surround — CELT-only, fullband, mono @@ -83,7 +85,7 @@ pub use multistream::MultistreamDecoder; pub use multistream_enc::MultistreamEncoder; pub use packet::{Bandwidth, Mode, Packet, Toc}; pub use range::{RangeDecoder, RangeEncoder}; -pub use silk::{SilkDecIndices, SilkDecoder}; +pub use silk::{SilkDecIndices, SilkDecoder, SilkFrameMode}; pub use silk_enc_write::SilkFrameDiag; pub use silk_enc_write::{SilkEncoder, SilkStereoEncoder}; @@ -101,7 +103,7 @@ pub struct Decoder { channels: usize, downsample: usize, celt: CeltDecoder, - /// Boxed because a `SilkDecoder` is 6304 bytes, 83% of what a `Decoder` + /// Boxed because a `SilkDecoder` is 6496 bytes, 83% of what a `Decoder` /// costs a caller taking one BY VALUE from `Decoder::new`. It is the /// decoder's largest field and its only large one; `celt` is 1448. /// `Stack`: crate::stack_budget. @@ -111,6 +113,10 @@ pub struct Decoder { /// Per-frame scratch, allocated once: the SILK layer's output and the /// redundancy frame. silk_pcm: Vec, + /// The internal SILK rate and channel count of the last SILK frame, which + /// the SILK concealment reuses. + silk_rate: u32, + silk_channels: usize, redundant: Vec, prev_mode: Option, prev_redundancy: bool, @@ -171,6 +177,8 @@ impl Decoder { silk: Box::new(SilkDecoder::new(sample_rate, channels)), celt_window: celt::overlap_window(), silk_pcm: vec![0; 5760 * channels], + silk_rate: 16000, + silk_channels: 1, redundant: vec![0.0; 240 * channels], prev_mode: None, prev_redundancy: false, @@ -233,8 +241,9 @@ impl Decoder { /// Conceals `frame_size` lost samples per channel (a multiple of 2.5 ms, /// at most 120 ms), the equivalent of the reference's `decode(NULL)`. - /// Consecutive calls decay towards background noise; the next real - /// packet cross-fades in through the MDCT overlap. + /// CELT output decays towards background noise and SILK output is + /// extrapolated by the SILK PLC; the next real packet cross-fades in + /// through the MDCT overlap. pub fn conceal(&mut self, frame_size: usize, out: &mut [f32]) -> Result { let total_48k = frame_size * self.downsample; if total_48k == 0 || !total_48k.is_multiple_of(120) || total_48k > 5760 { @@ -252,17 +261,22 @@ impl Decoder { let mut done_48k = 0usize; while done_48k < total_48k { let left = total_48k - done_48k; - let chunk = [960, 480, 240, 120] - .into_iter() - .find(|&c| c <= left) - .unwrap_or(120); + let sizes: &[usize] = match self.prev_mode { + Some(Mode::Silk | Mode::Hybrid) => &[960, 480], + _ => &[960, 480, 240, 120], + }; + let chunk = sizes.iter().copied().find(|&c| c <= left).unwrap_or(120); let a = done_48k / self.downsample * self.channels; let b = (done_48k + chunk) / self.downsample * self.channels; let dst = &mut out[a..b]; - if self.prev_mode == Some(Mode::Celt) { - self.celt.conceal(dst, chunk)?; - } else { - dst.fill(0.0); + match self.prev_mode { + Some(Mode::Celt) => { + self.celt.conceal(dst, chunk)?; + } + Some(Mode::Silk | Mode::Hybrid) if chunk >= 480 => { + self.conceal_silk(dst, chunk)?; + } + _ => dst.fill(0.0), } done_48k += chunk; } @@ -362,10 +376,11 @@ impl Decoder { let mode = toc.mode(); let stream_channels = toc.channels(); if data.len() <= 1 { - // 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; + // DTX or a dropped frame: conceal it like a lost one. + let n = out.len() / self.channels; + if self.conceal(n, out).is_err() { + out.fill(0.0); + } return Ok(0); } let mut dec = RangeDecoder::new(data); @@ -391,7 +406,14 @@ impl Decoder { _ => 16000, } }; + self.silk_rate = internal_rate; + self.silk_channels = stream_channels; let payload_ms = (frame_48k / 48).max(10); + let mode = if fec { + SilkFrameMode::Lbrr + } else { + SilkFrameMode::Normal + }; let mut done = 0usize; let mut first = true; while done < frame_out { @@ -402,7 +424,7 @@ impl Decoder { internal_rate, stream_channels, first, - fec, + mode, )?; if n == 0 { break; @@ -553,6 +575,43 @@ impl Decoder { } } +impl Decoder { + /// Conceals `dst` (one chunk of 10 or 20 ms) with the SILK PLC, on top of + /// the CELT concealment in hybrid mode. + fn conceal_silk(&mut self, dst: &mut [f32], chunk: usize) -> Result<()> { + if self.prev_mode == Some(Mode::Hybrid) { + self.celt.conceal(dst, chunk)?; + } else { + dst.fill(0.0); + } + let mut pcm = core::mem::take(&mut self.silk_pcm); + let samples = chunk / self.downsample; + pcm.clear(); + pcm.resize(samples * self.channels, 0); + let mut done = 0usize; + while done < samples { + let n = self.silk.decode( + &mut RangeDecoder::new(&[]), + &mut pcm[done * self.channels..], + chunk / 48, + self.silk_rate, + self.silk_channels, + true, + SilkFrameMode::Lost, + )?; + if n == 0 { + break; + } + done += n; + } + for (o, s) in dst.iter_mut().zip(pcm.iter()) { + *o += *s as f32 * (1.0 / 32768.0); + } + self.silk_pcm = pcm; + Ok(()) + } +} + /// 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( diff --git a/crates/ec-opus/src/silk.rs b/crates/ec-opus/src/silk.rs index 09ef8124..00a21ea8 100644 --- a/crates/ec-opus/src/silk.rs +++ b/crates/ec-opus/src/silk.rs @@ -12,10 +12,9 @@ //! 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. //! -//! LBRR (in-band FEC) frames can be decoded through the `lbrr` flag of -//! [`SilkDecoder::decode`], but SILK packet loss concealment is not implemented: -//! a lost or empty frame yields silence rather than an extrapolation. -//! Everything else in the layer is complete. +//! LBRR (in-band FEC) frames are decoded through [`SilkFrameMode::Lbrr`], and +//! lost frames are concealed by the packet loss concealment of the reference +//! (`silk/PLC.c`), selected with [`SilkFrameMode::Lost`]. // SILK is transliterated fixed-point arithmetic: the loops below index parallel // arrays by position because the reference's index arithmetic is the @@ -54,6 +53,21 @@ pub(crate) 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; +const BWE_COEF_Q16: i32 = 64881; +const BWE_AFTER_LOSS_Q16: i32 = 63570; +const V_PITCH_GAIN_START_MIN_Q14: i32 = 11469; +const V_PITCH_GAIN_START_MAX_Q14: i32 = 15565; +const RAND_BUF_SIZE: usize = 128; +const RAND_BUF_MASK: i32 = 127; +const LOG2_INV_LPC_GAIN_HIGH_THRES: i32 = 3; +const LOG2_INV_LPC_GAIN_LOW_THRES: i32 = 8; +const PITCH_DRIFT_FAC_Q16: i32 = 655; +const MAX_PITCH_LAG_MS: i32 = 18; +const HARM_ATT_Q15: [i32; NB_ATT] = [32440, 31130]; +const PLC_RAND_ATTENUATE_V_Q15: [i32; NB_ATT] = [31130, 26214]; +const PLC_RAND_ATTENUATE_UV_Q15: [i32; NB_ATT] = [32440, 29491]; +const NB_ATT: usize = 2; +const MAX_LTP_MEM: usize = 20 * 16; /// Gain quantiser constants (`gain_quant.c`). const GAIN_OFFSET: i32 = (MIN_QGAIN_DB * 128) / 6 + 16 * 128; @@ -68,6 +82,27 @@ enum CondCoding { Conditionally, } +/// What `SilkDecoder::decode` reads for a frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SilkFrameMode { + /// Regular frames, read from the range decoder. + Normal, + /// The packet's LBRR (in-band FEC) frames, where coded. + Lbrr, + /// No data for this frame: conceal it (PLC). + Lost, +} + +impl SilkFrameMode { + fn coded(self, lbrr_flag: bool) -> bool { + match self { + SilkFrameMode::Normal => true, + SilkFrameMode::Lbrr => lbrr_flag, + SilkFrameMode::Lost => false, + } + } +} + // --------------------------------------------------------------------------- // Fixed-point helpers. These are the reference's macros; they are written out // because SILK's output is defined by them bit for bit. @@ -305,6 +340,24 @@ impl Default for FrameCtrl { } } +/// Packet loss concealment state (`silk_PLC_struct`). +#[derive(Clone, Debug, Default)] +struct PlcState { + pitch_l_q8: i32, + ltp_coef_q14: [i16; LTP_ORDER], + prev_lpc_q12: [i16; MAX_LPC_ORDER], + last_frame_lost: bool, + rand_seed: i32, + rand_scale_q14: i16, + conc_energy: i32, + conc_energy_shift: i32, + prev_ltp_scale_q14: i16, + prev_gain_q16: [i32; 2], + fs_khz: usize, + nb_subfr: usize, + subfr_length: usize, +} + /// One SILK channel's inter-frame state. #[derive(Clone, Debug)] struct ChannelState { @@ -335,6 +388,8 @@ struct ChannelState { lbrr_flag: bool, lbrr_flags: [bool; 3], resampler: Resampler, + plc: PlcState, + loss_cnt: i32, } impl ChannelState { @@ -365,6 +420,8 @@ impl ChannelState { lbrr_flag: false, lbrr_flags: [false; 3], resampler: Resampler::default(), + plc: PlcState::default(), + loss_cnt: 0, } } @@ -508,8 +565,8 @@ impl SilkDecoder { /// `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. - /// With `lbrr` set, decodes the packet's LBRR (in-band FEC) frames instead - /// of the regular ones. + /// `mode` selects what is read: regular frames, the LBRR (in-band FEC) + /// frames, or nothing at all, in which case the frame is concealed. #[allow(clippy::too_many_arguments)] pub fn decode( &mut self, @@ -519,8 +576,9 @@ impl SilkDecoder { internal_rate: u32, channels_internal: usize, new_packet: bool, - lbrr: bool, + mode: SilkFrameMode, ) -> Result { + let lbrr = mode == SilkFrameMode::Lbrr; let fs_khz = (internal_rate / 1000) as usize; if new_packet { for ch in self.channels.iter_mut() { @@ -558,7 +616,7 @@ impl SilkDecoder { 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 { + if mode != SilkFrameMode::Lost && 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); @@ -619,7 +677,7 @@ impl SilkDecoder { // Stereo prediction weights for this frame. if channels_internal == 2 { let frame = self.channels[0].frames_decoded; - if !lbrr || self.channels[0].lbrr_flags[frame] { + if mode.coded(self.channels[0].lbrr_flags[frame]) { stereo_decode_pred(dec, &mut ms_pred_q13); let side_coded = if lbrr { self.channels[1].lbrr_flags[frame] @@ -663,13 +721,9 @@ impl SilkDecoder { } else { CondCoding::Conditionally }; - if !lbrr || self.channels[n].lbrr_flags[self.channels[n].frames_decoded] { - n_samples_dec = - decode_frame(&mut self.channels[n], dec, &mut buf[2..], cond, lbrr); - } else { - n_samples_dec = self.channels[n].frame_length; - buf[2..2 + n_samples_dec].fill(0); - } + let coded = mode.coded(self.channels[n].lbrr_flags[self.channels[n].frames_decoded]); + n_samples_dec = + decode_frame(&mut self.channels[n], dec, &mut buf[2..], cond, lbrr, coded); } else { buf[2..2 + n_samples_dec].fill(0); } @@ -692,7 +746,13 @@ impl SilkDecoder { 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; + if mode == SilkFrameMode::Lost { + for ch in self.channels.iter_mut().take(channels_internal) { + ch.last_gain_index = 10; + } + } else { + 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 = core::mem::take(&mut self.resample_tmp); @@ -1314,6 +1374,11 @@ fn decode_parameters(ch: &mut ChannelState, cond: CondCoding) -> FrameCtrl { 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.loss_cnt != 0 { + let order = ch.lpc_order; + bwexpander(&mut ctrl.pred_coef_q12[0][..order], BWE_AFTER_LOSS_Q16); + bwexpander(&mut ctrl.pred_coef_q12[1][..order], BWE_AFTER_LOSS_Q16); + } if ch.indices.signal_type == TYPE_VOICED { ctrl.pitch_l = decode_pitch( @@ -1338,6 +1403,289 @@ fn decode_parameters(ch: &mut ChannelState, cond: CondCoding) -> FrameCtrl { ctrl } +/// `silk_bwexpander`: moves the LPC poles towards the origin. +fn bwexpander(ar: &mut [i16], mut chirp_q16: i32) { + let chirp_minus_one = chirp_q16 - 65536; + let d = ar.len(); + for coef in ar.iter_mut().take(d - 1) { + *coef = rshift_round(chirp_q16.wrapping_mul(*coef as i32), 16) as i16; + chirp_q16 += rshift_round(chirp_q16.wrapping_mul(chirp_minus_one), 16); + } + ar[d - 1] = rshift_round(chirp_q16.wrapping_mul(ar[d - 1] as i32), 16) as i16; +} + +/// `silk_sum_sqr_shift`: energy of `x` scaled down to fit, and the shift used. +fn sum_sqr_shift(x: &[i16]) -> (i32, i32) { + let len = x.len(); + let sq = |i: usize| (x[i] as i32).wrapping_mul(x[i] as i32) as u32; + let energy = |shft: i32| { + let mut nrg = 0u32; + let mut i = 0; + while i + 1 < len { + nrg = nrg.wrapping_add((sq(i).wrapping_add(sq(i + 1))) >> shft); + i += 2; + } + if i < len { + nrg = nrg.wrapping_add(sq(i) >> shft); + } + nrg + }; + let mut shft = 31 - clz32(len as i32); + let first = (len as u32).wrapping_add(energy(shft)); + shft = (shft + 3 - clz32(first as i32)).max(0); + let nrg = energy(shft); + (nrg as i32, shft) +} + +/// `silk_PLC_energy`: energies of the last two subframes' excitation. +fn plc_energy( + exc_q14: &[i32], + prev_gain_q10: [i32; 2], + subfr_length: usize, + nb_subfr: usize, +) -> (i32, i32, i32, i32) { + let mut exc_buf = [0i16; 2 * 80]; + for k in 0..2 { + for i in 0..subfr_length { + let x = exc_q14[i + (k + nb_subfr - 2) * subfr_length]; + exc_buf[k * subfr_length + i] = + sat16(smulww(x, prev_gain_q10[k]) >> 8); + } + } + let (e1, s1) = sum_sqr_shift(&exc_buf[..subfr_length]); + let (e2, s2) = sum_sqr_shift(&exc_buf[subfr_length..2 * subfr_length]); + (e1, s1, e2, s2) +} + +impl ChannelState { + /// `silk_PLC_Reset`. + fn plc_reset(&mut self) { + self.plc.pitch_l_q8 = (self.frame_length as i32) << 7; + self.plc.prev_gain_q16 = [1 << 16; 2]; + self.plc.subfr_length = 20; + self.plc.nb_subfr = 2; + } + + /// `silk_PLC`: conceals a lost frame, or tracks the state of a coded one. + fn plc_frame(&mut self, ctrl: &mut FrameCtrl, out: &mut [i16], lost: bool) { + if self.fs_khz != self.plc.fs_khz { + self.plc_reset(); + self.plc.fs_khz = self.fs_khz; + } + if lost { + self.plc_conceal(ctrl, out); + self.loss_cnt += 1; + } else { + self.plc_update(ctrl); + } + } + + /// `silk_PLC_update`: remembers the pitch, LPC and gains of a coded frame. + fn plc_update(&mut self, ctrl: &FrameCtrl) { + let nb = self.nb_subfr; + self.prev_signal_type = self.indices.signal_type; + let mut ltp_gain_q14 = 0i32; + if self.indices.signal_type == TYPE_VOICED { + let mut j = 0usize; + while ((j * self.subfr_length) as i32) < ctrl.pitch_l[nb - 1] { + if j == nb { + break; + } + let k = nb - 1 - j; + let coefs = &ctrl.ltp_coef_q14[k * LTP_ORDER..(k + 1) * LTP_ORDER]; + let temp: i32 = coefs.iter().map(|&c| c as i32).sum(); + if temp > ltp_gain_q14 { + ltp_gain_q14 = temp; + self.plc.ltp_coef_q14.copy_from_slice(coefs); + self.plc.pitch_l_q8 = ctrl.pitch_l[k] << 8; + } + j += 1; + } + self.plc.ltp_coef_q14 = [0; LTP_ORDER]; + self.plc.ltp_coef_q14[LTP_ORDER / 2] = ltp_gain_q14 as i16; + if ltp_gain_q14 < V_PITCH_GAIN_START_MIN_Q14 { + let tmp = V_PITCH_GAIN_START_MIN_Q14 << 10; + let scale_q10 = tmp / ltp_gain_q14.max(1); + for c in self.plc.ltp_coef_q14.iter_mut() { + *c = (smulbb(*c as i32, scale_q10) >> 10) as i16; + } + } else if ltp_gain_q14 > V_PITCH_GAIN_START_MAX_Q14 { + let tmp = V_PITCH_GAIN_START_MAX_Q14 << 14; + let scale_q14 = tmp / ltp_gain_q14.max(1); + for c in self.plc.ltp_coef_q14.iter_mut() { + *c = (smulbb(*c as i32, scale_q14) >> 14) as i16; + } + } + } else { + self.plc.pitch_l_q8 = smulbb(self.fs_khz as i32, MAX_PITCH_LAG_MS) << 8; + self.plc.ltp_coef_q14 = [0; LTP_ORDER]; + } + let order = self.lpc_order; + self.plc.prev_lpc_q12[..order].copy_from_slice(&ctrl.pred_coef_q12[1][..order]); + self.plc.prev_ltp_scale_q14 = ctrl.ltp_scale_q14 as i16; + self.plc.prev_gain_q16 = [ctrl.gains_q16[nb - 2], ctrl.gains_q16[nb - 1]]; + self.plc.subfr_length = self.subfr_length; + self.plc.nb_subfr = nb; + } + + /// `silk_PLC_conceal`: synthesises one lost frame from the saved state. + fn plc_conceal(&mut self, ctrl: &mut FrameCtrl, out: &mut [i16]) { + let order = self.lpc_order; + let ltp_mem = self.ltp_mem_length; + let prev_gain_q10 = [ + self.plc.prev_gain_q16[0] >> 6, + self.plc.prev_gain_q16[1] >> 6, + ]; + if self.first_frame_after_reset { + self.plc.prev_lpc_q12 = [0; MAX_LPC_ORDER]; + } + let (energy1, shift1, energy2, shift2) = + plc_energy(&self.exc_q14, prev_gain_q10, self.subfr_length, self.nb_subfr); + let rand_base = if (energy1 >> shift2) < (energy2 >> shift1) { + ((self.plc.nb_subfr - 1) * self.plc.subfr_length).saturating_sub(RAND_BUF_SIZE) + } else { + (self.plc.nb_subfr * self.plc.subfr_length).saturating_sub(RAND_BUF_SIZE) + }; + + let mut b_q14 = self.plc.ltp_coef_q14; + let mut rand_scale_q14 = self.plc.rand_scale_q14 as i32; + let att = self.loss_cnt.min(NB_ATT as i32 - 1) as usize; + let harm_gain_q15 = HARM_ATT_Q15[att]; + let mut rand_gain_q15 = if self.prev_signal_type == TYPE_VOICED { + PLC_RAND_ATTENUATE_V_Q15[att] + } else { + PLC_RAND_ATTENUATE_UV_Q15[att] + }; + + bwexpander(&mut self.plc.prev_lpc_q12[..order], BWE_COEF_Q16); + let a_q12 = self.plc.prev_lpc_q12; + + if self.loss_cnt == 0 { + rand_scale_q14 = 1 << 14; + if self.prev_signal_type == TYPE_VOICED { + for &b in b_q14.iter() { + rand_scale_q14 -= b as i32; + } + rand_scale_q14 = rand_scale_q14.max(3277); + rand_scale_q14 = + smulbb(rand_scale_q14, self.plc.prev_ltp_scale_q14 as i32) >> 14; + } else { + let inv_gain_q30 = lpc_inverse_pred_gain(&self.plc.prev_lpc_q12[..order]); + let mut down_scale_q30 = + ((1 << 30) >> LOG2_INV_LPC_GAIN_HIGH_THRES).min(inv_gain_q30); + down_scale_q30 = ((1 << 30) >> LOG2_INV_LPC_GAIN_LOW_THRES).max(down_scale_q30); + down_scale_q30 <<= LOG2_INV_LPC_GAIN_HIGH_THRES; + rand_gain_q15 = smulwb(down_scale_q30, rand_gain_q15) >> 14; + } + } + + let mut rand_seed = self.plc.rand_seed; + let mut lag = rshift_round(self.plc.pitch_l_q8, 8); + let idx = (ltp_mem as i32 - lag - order as i32 - (LTP_ORDER / 2) as i32) as usize; + let mut s_ltp = [0i16; MAX_LTP_MEM]; + lpc_analysis_filter( + &mut s_ltp[idx..ltp_mem], + &self.out_buf[idx..ltp_mem], + &a_q12, + ltp_mem - idx, + order, + ); + let inv_gain_q30 = inverse32_var_q(self.plc.prev_gain_q16[1], 46).min(i32::MAX >> 1); + let mut s_ltp_q14 = [0i32; MAX_LTP_MEM + MAX_FRAME_LENGTH]; + for i in idx + order..ltp_mem { + s_ltp_q14[i] = smulwb(inv_gain_q30, s_ltp[i] as i32); + } + + let mut sltp_buf_idx = ltp_mem; + for _ in 0..self.nb_subfr { + let pred0 = sltp_buf_idx + LTP_ORDER / 2 - lag as usize; + for i in 0..self.subfr_length { + let pred = pred0 + i; + let mut ltp_pred_q12 = 2i32; + for j in 0..LTP_ORDER { + ltp_pred_q12 = smlawb(ltp_pred_q12, s_ltp_q14[pred - j], b_q14[j] as i32); + } + rand_seed = silk_rand(rand_seed); + let ridx = ((rand_seed >> 25) & RAND_BUF_MASK) as usize; + s_ltp_q14[sltp_buf_idx] = smlawb( + ltp_pred_q12, + self.exc_q14[rand_base + ridx], + rand_scale_q14, + ) << 2; + sltp_buf_idx += 1; + } + for b in b_q14.iter_mut() { + *b = (smulbb(harm_gain_q15, *b as i32) >> 15) as i16; + } + rand_scale_q14 = smulbb(rand_scale_q14, rand_gain_q15) >> 15; + self.plc.pitch_l_q8 = + smlawb(self.plc.pitch_l_q8, self.plc.pitch_l_q8, PITCH_DRIFT_FAC_Q16); + self.plc.pitch_l_q8 = self + .plc + .pitch_l_q8 + .min(smulbb(MAX_PITCH_LAG_MS, self.fs_khz as i32) << 8); + lag = rshift_round(self.plc.pitch_l_q8, 8); + } + + let base = ltp_mem - MAX_LPC_ORDER; + s_ltp_q14[base..base + MAX_LPC_ORDER].copy_from_slice(&self.s_lpc_q14); + for i in 0..self.frame_length { + let s = base + MAX_LPC_ORDER + i; + let mut lpc_pred_q10 = (order >> 1) as i32; + for j in 0..order { + lpc_pred_q10 = smlawb(lpc_pred_q10, s_ltp_q14[s - j - 1], a_q12[j] as i32); + } + s_ltp_q14[s] = s_ltp_q14[s].saturating_add(lshift_sat32(lpc_pred_q10, 4)); + out[i] = sat16(rshift_round(smulww(s_ltp_q14[s], prev_gain_q10[1]), 8)); + } + let end = base + self.frame_length; + self.s_lpc_q14 + .copy_from_slice(&s_ltp_q14[end..end + MAX_LPC_ORDER]); + + self.plc.rand_seed = rand_seed; + self.plc.rand_scale_q14 = rand_scale_q14 as i16; + self.plc.ltp_coef_q14 = b_q14; + ctrl.pitch_l = [lag; MAX_NB_SUBFR]; + } + + /// `silk_PLC_glue_frames`: smooths the start of the first frame after a loss. + fn plc_glue_frames(&mut self, frame: &mut [i16]) { + let length = frame.len() as i32; + if self.loss_cnt != 0 { + let (e, s) = sum_sqr_shift(frame); + self.plc.conc_energy = e; + self.plc.conc_energy_shift = s; + self.plc.last_frame_lost = true; + return; + } + if self.plc.last_frame_lost { + let (mut energy, energy_shift) = sum_sqr_shift(frame); + if energy_shift > self.plc.conc_energy_shift { + self.plc.conc_energy >>= energy_shift - self.plc.conc_energy_shift; + } else if energy_shift < self.plc.conc_energy_shift { + energy >>= self.plc.conc_energy_shift - energy_shift; + } + if energy > self.plc.conc_energy { + let lz = clz32(self.plc.conc_energy) - 1; + self.plc.conc_energy <<= lz; + energy >>= (24 - lz).max(0); + let frac_q24 = self.plc.conc_energy / energy.max(1); + let mut gain_q16 = sqrt_approx(frac_q24) << 4; + let mut slope_q16 = ((1 << 16) - gain_q16) / length; + slope_q16 <<= 2; + for v in frame.iter_mut() { + *v = smulwb(gain_q16, *v as i32) as i16; + gain_q16 += slope_q16; + if gain_q16 > (1 << 16) { + break; + } + } + } + } + self.plc.last_frame_lost = false; + } +} + /// `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) { @@ -1353,7 +1701,7 @@ fn lpc_analysis_filter(out: &mut [i16], input: &[i16], b_q12: &[i16], len: usize } /// `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]) { +fn decode_core(ch: &mut ChannelState, ctrl: &mut 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; @@ -1382,6 +1730,19 @@ fn decode_core(ch: &mut ChannelState, ctrl: &FrameCtrl, xq: &mut [i16], pulses: let mut res_q14 = [0i32; 5 * 16]; for k in 0..ch.nb_subfr { + let mut signal_type = ch.indices.signal_type; + // Avoid an abrupt switch from voiced PLC to unvoiced normal decoding. + if ch.loss_cnt != 0 + && ch.prev_signal_type == TYPE_VOICED + && ch.indices.signal_type != TYPE_VOICED + && k < MAX_NB_SUBFR / 2 + { + let b = &mut ctrl.ltp_coef_q14[k * LTP_ORDER..(k + 1) * LTP_ORDER]; + b.fill(0); + b[LTP_ORDER / 2] = 4096; + signal_type = TYPE_VOICED; + ctrl.pitch_l[k] = ch.lag_prev; + } 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; @@ -1397,7 +1758,7 @@ fn decode_core(ch: &mut ChannelState, ctrl: &FrameCtrl, xq: &mut [i16], pulses: }; ch.prev_gain_q16 = ctrl.gains_q16[k]; - if ch.indices.signal_type == TYPE_VOICED { + if 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. @@ -1431,7 +1792,7 @@ fn decode_core(ch: &mut ChannelState, ctrl: &FrameCtrl, xq: &mut [i16], pulses: // Long-term prediction. let exc_base = k * ch.subfr_length; - let pres_q14: &[i32] = if ch.indices.signal_type == TYPE_VOICED { + let pres_q14: &[i32] = if 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; @@ -1476,32 +1837,41 @@ fn decode_frame( out: &mut [i16], cond: CondCoding, lbrr: bool, + coded: bool, ) -> usize { - let frame_index = ch.frames_decoded; - decode_indices(ch, dec, frame_index, lbrr, 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; + let mut ctrl = FrameCtrl::default(); + if coded { + let frame_index = ch.frames_decoded; + decode_indices(ch, dec, frame_index, lbrr, 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, + ); + ctrl = decode_parameters(ch, cond); + if cond == CondCoding::IndependentlyNoLtpScaling { + ctrl.ltp_scale_q14 = LTPSCALES_TABLE_Q14[0] as i32; + } + decode_core(ch, &mut ctrl, out, &pulses); + ch.plc_frame(&mut ctrl, out, false); + ch.loss_cnt = 0; + ch.prev_signal_type = ch.indices.signal_type; + ch.first_frame_after_reset = false; + } else { + ch.plc_frame(&mut ctrl, out, true); } - 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 + let fl = ch.frame_length; + let mv_len = ch.ltp_mem_length - fl; + ch.out_buf.copy_within(fl..fl + mv_len, 0); + ch.out_buf[mv_len..mv_len + fl].copy_from_slice(&out[..fl]); + ch.plc_glue_frames(&mut out[..fl]); + ch.lag_prev = ctrl.pitch_l[ch.nb_subfr - 1]; + fl } /// `silk_stereo_decode_pred` (Section 4.2.7.1). diff --git a/crates/ec-opus/src/silk_enc_write.rs b/crates/ec-opus/src/silk_enc_write.rs index 62fd1699..a62ba347 100644 --- a/crates/ec-opus/src/silk_enc_write.rs +++ b/crates/ec-opus/src/silk_enc_write.rs @@ -375,7 +375,7 @@ impl SilkEncoder { fs as u32 * 1000, 1, first, - false, + crate::silk::SilkFrameMode::Normal, )?; if n == 0 { break; @@ -1309,7 +1309,7 @@ impl SilkStereoEncoder { fs as u32 * 1000, 2, true, - false, + crate::silk::SilkFrameMode::Normal, )?; debug_assert_eq!(n, frame_ms * fs); self.mirror_range = dec.range(); @@ -1627,7 +1627,7 @@ mod tests { if wb { 16000 } else { 8000 }, 1, true, - false, + crate::silk::SilkFrameMode::Normal, ) .unwrap(); assert_eq!(n, if wb { 320 } else { 160 }); diff --git a/crates/ec-opus/src/stack_budget.rs b/crates/ec-opus/src/stack_budget.rs index 39e451e3..8a069b89 100755 --- a/crates/ec-opus/src/stack_budget.rs +++ b/crates/ec-opus/src/stack_budget.rs @@ -114,7 +114,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ // -- lib.rs ----------------------------------------------------------- ( "Decoder", - Some(1568), + Some(1576), true, "Decoder::new -> Result. Was 7576, 92.5% of the budget, \ because a 6304-byte SilkDecoder sat inline; that field is now a Box", @@ -218,10 +218,10 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ // -- silk.rs ---------------------------------------------------------- ( "SilkDecoder", - Some(6304), + Some(6496), true, "silk::SilkDecoder::new -> Self, and it is `pub use`d at the crate \ - root, so 6304 bytes is a caller's by-value cost TODAY even though \ + root, so 6496 bytes is a caller's by-value cost TODAY even though \ Decoder::new moves it straight into a Box. At 77% of the budget it \ is the LARGEST budgeted row in the table, and the one that says how \ little headroom the budget would have left if it had stayed inline", @@ -235,7 +235,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ // -- silk_enc_write.rs ------------------------------------------------ ( "SilkEncoder", - Some(6688), + Some(6880), false, "silk_enc_write::SilkEncoder::new -> Self. `pub`, `pub use`d at the \ crate root, and returned by value -- but every field that holds one \ @@ -243,7 +243,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ ), ( "SilkStereoEncoder", - Some(19856), + Some(20432), false, "silk_enc_write::SilkStereoEncoder::new -> Self. The largest single \ type in the crate at 2.42x the budget, and the reason three of the \ diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 709e877d..8c41bb66 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -4513,7 +4513,7 @@ fn collect_indices(packets: &[Vec]) -> Vec<(ec_opus::SilkDecIndices, usize)> continue; } let mut dec = ec_opus::RangeDecoder::new(frame_data); - let _ = silk.decode(&mut dec, &mut silk_pcm, payload_ms, internal_rate, 1, first, false); + let _ = silk.decode(&mut dec, &mut silk_pcm, payload_ms, internal_rate, 1, first, ec_opus::SilkFrameMode::Normal); let ix = silk.last_indices(); let bytes = frame_data.len(); results.push((ix, bytes)); diff --git a/crates/ec-opus/tests/plc.rs b/crates/ec-opus/tests/plc.rs index a5d0cfa7..d8764947 100644 --- a/crates/ec-opus/tests/plc.rs +++ b/crates/ec-opus/tests/plc.rs @@ -103,6 +103,8 @@ fn inband_fec_recovers_a_lost_frame() { a.extend_from_slice(&buf[..k]); let k = if i == 20 { lossy.decode_fec(&packets[21], FRAME, &mut buf).unwrap() + } else if i == 30 { + lossy.conceal(FRAME, &mut buf).unwrap() } else { lossy.decode_float(p, &mut buf).unwrap() }; @@ -111,7 +113,9 @@ fn inband_fec_recovers_a_lost_frame() { let f = |i: usize| i * FRAME..(i + 1) * FRAME; let c20 = corr(&a[f(20)], &b[f(20)]); let c22 = corr(&a[f(22)], &b[f(22)]); - eprintln!("fec c20 {c20:.3} c22 {c22:.3}"); + let c30 = corr(&a[f(30)], &b[f(30)]); + eprintln!("fec c20 {c20:.3} c22 {c22:.3} plc c30 {c30:.3}"); + assert!(c30 > 0.3); assert!(c20 > 0.7); assert!(c22 > 0.95); }