diff --git a/crates/ec-opus/src/celt.rs b/crates/ec-opus/src/celt.rs index bc968faf..d59b5669 100644 --- a/crates/ec-opus/src/celt.rs +++ b/crates/ec-opus/src/celt.rs @@ -2735,6 +2735,12 @@ fn frame_lm(frame_size: usize) -> Result { } impl CeltDecoder { + /// Sets the band range the next concealment covers (hybrid FEC: 17..end). + pub fn set_conceal_bands(&mut self, start: usize, end: usize) { + self.plc.start = start; + self.plc.end = end.min(NB_BANDS); + } + /// Packet loss concealment for one lost frame of `frame_size` 48 kHz /// samples: pitch-periodic LPC extension for the first losses, then /// band-shaped noise decaying towards the background level. diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index 2f35a5ee..c2ca7dc6 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -9,6 +9,9 @@ //! (TOC configs 13/15, mono or stereo SWB/FB 10 or 20 ms: SILK at 16 kHz under //! CELT from band 17 up, one range-coded stream). //! +//! In-band FEC (SILK LBRR, [`Encoder::set_inband_fec`]) is mono SILK and +//! hybrid 10/20 ms only. +//! //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and //! the coded bandwidth is capped at the input's own Nyquist, so the images //! the stuffing puts there are never coded and the decoder's decimation @@ -149,6 +152,11 @@ pub struct Encoder { analysis_on: bool, /// Whether the detected bandwidth may lower the coded one (`EC_OPUS_BW_DETECT`). bw_detect: bool, + inband_fec: bool, + packet_loss_perc: u8, + lbrr_coded: bool, + fec_bandwidth: Option, + last_silk: Option, } fn toc_bandwidth(toc: u8) -> Bandwidth { @@ -232,6 +240,11 @@ impl Encoder { info: AnalysisInfo::default(), analysis_on: crate::celt_enc::analysis_params().0, bw_detect: crate::celt_enc::analysis_params().5, + inband_fec: false, + packet_loss_perc: 0, + lbrr_coded: false, + fec_bandwidth: None, + last_silk: None, }; // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how // the gate rows at `set_libopus_input_alignment` were produced. @@ -374,6 +387,16 @@ impl Encoder { self.bitrate = bps.clamp(500, 510_000); } + /// OPUS_SET_INBAND_FEC: code LBRR (in-band FEC) when the loss rate and bitrate justify it; prefers SILK/hybrid over CELT under loss. + pub fn set_inband_fec(&mut self, on: bool) { + self.inband_fec = on; + } + + /// OPUS_SET_PACKET_LOSS_PERC: expected packet loss, 0..=100 (clamped). + pub fn set_packet_loss_perc(&mut self, perc: u8) { + self.packet_loss_perc = perc.min(100); + } + /// Current target bitrate. pub fn bitrate(&self) -> u32 { self.bitrate @@ -427,6 +450,9 @@ impl Encoder { self.final_range = 0; self.analysis.reset(); self.info = AnalysisInfo::default(); + self.lbrr_coded = false; + self.fec_bandwidth = None; + self.last_silk = None; } /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) @@ -442,7 +468,10 @@ impl Encoder { match self.mode { Some(Mode::Celt) | Some(Mode::Hybrid) => None, Some(Mode::Silk) => { - let bw = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth()); + let bw = self + .fec_bandwidth + .or(self.bandwidth) + .unwrap_or_else(|| self.auto_bandwidth()); Some(silk_fs_khz(bw)) } None => { @@ -452,7 +481,8 @@ impl Encoder { return None; } let bw = self - .bandwidth + .fec_bandwidth + .or(self.bandwidth) .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)); // 40/60 ms frames are SILK-only (Hybrid supports 10/20 ms): // cap at Wide so a high equiv rate does not fall through to @@ -500,7 +530,8 @@ impl Encoder { return None; } let bw = self - .bandwidth + .fec_bandwidth + .or(self.bandwidth) .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)); match bw { Bandwidth::SuperWide | Bandwidth::Full => Some(bw), @@ -671,6 +702,7 @@ impl Encoder { cap: usize, ) -> Result<(u8, &[u8])> { let frame_48k = frame_size * self.upsample; + self.fec_bandwidth = None; if frame_48k > 960 && self.silk_choice(frame_48k).is_none() { return self.encode_multiframe(pcm, frame_size, cap); } @@ -683,9 +715,13 @@ impl Encoder { } else { AnalysisInfo::default() }; + let (fec, fec_bw) = self.fec_for(frame_48k); + self.lbrr_coded = fec; + self.fec_bandwidth = fec_bw; if let Some(fs_khz) = self.silk_choice(frame_48k) { let budget = self.packet_budget(frame_48k, cap); if self.channels == 2 { + self.last_silk = None; Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff); if frame_48k > 960 { return self.encode_stereo_silk_multiframe(fs_khz, frame_48k); @@ -709,6 +745,11 @@ impl Encoder { return Ok((self.silk_buf[0], &self.silk_buf[1..n])); } Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); + let (lbrr, loss, same) = ( + self.lbrr_coded, + self.packet_loss_perc, + self.last_silk == Some(fs_khz as u8), + ); let enc = match fs_khz { 8 => self .silk_nb @@ -720,6 +761,10 @@ impl Encoder { .silk_wb .get_or_insert_with(|| Box::new(SilkEncoder::new(true))), }; + if !same { + enc.drop_lbrr(); + } + enc.set_lbrr(lbrr, loss); // Keep SILK's own reservoir-based rate control tracking the // Encoder's current target on every frame — cheap (an Option // store) and catches set_bitrate calls made between frames. @@ -728,6 +773,7 @@ impl Encoder { let n = enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf[..], frame_48k / 48)?; self.final_range = enc.final_range(); + self.last_silk = Some(fs_khz as u8); return Ok((self.silk_buf[0], &self.silk_buf[1..n])); } if let Some(bandwidth) = self.hybrid_choice(frame_48k) { @@ -740,6 +786,7 @@ impl Encoder { &self.range.data()[..n], )); } + self.last_silk = None; let (toc, frame_48k, end) = self.toc(frame_size)?; let n = self.encode_frame(pcm, frame_48k, end, cap)?; Ok((toc, &self.range.data()[..n])) @@ -824,7 +871,10 @@ impl Encoder { } }; let bandwidth = self.bandwidth.unwrap_or_else(|| { - self.auto_bandwidth_at(self.equiv_rate(frame_48k), self.voice_est()) + self.auto_bandwidth_at( + self.equiv_rate_for(frame_48k, Some(Mode::Celt)), + self.voice_est(), + ) }); let bw_idx: u8 = match bandwidth { Bandwidth::Narrow => 0, @@ -854,6 +904,10 @@ impl Encoder { /// the complexity multiplier. Loss is 0 and complexity ≥ 5, so the /// are both no-ops. fn equiv_rate(&self, frame_48k: usize) -> i32 { + self.equiv_rate_for(frame_48k, None) + } + + fn equiv_rate_for(&self, frame_48k: usize, mode: Option) -> i32 { let frame_rate = 48000 / frame_48k as i32; let mut equiv = self.bitrate as i32; if frame_rate > 50 { @@ -863,9 +917,70 @@ impl Encoder { equiv -= equiv / 12; } equiv = equiv * (90 + DEFAULT_COMPLEXITY) / 100; + let loss = self.packet_loss_perc as i32; + match mode { + Some(Mode::Silk) | Some(Mode::Hybrid) => equiv -= equiv * loss / (6 * loss + 10), + Some(Mode::Celt) => {} + None => equiv -= equiv * loss / (12 * loss + 20), + } equiv } + fn fec_for(&self, frame_48k: usize) -> (bool, Option) { + if !self.inband_fec + || self.channels != 1 + || !matches!(frame_48k, 480 | 960) + || self.mode == Some(Mode::Celt) + { + return (false, None); + } + if self.mode.is_none() && !self.auto_silk(self.equiv_rate(frame_48k), self.voice_est()) { + return (false, None); + } + let silk_equiv = self.equiv_rate_for(frame_48k, Some(Mode::Silk)); + let ve = self.voice_est(); + let bw = self + .bandwidth + .unwrap_or_else(|| self.auto_bandwidth_at(silk_equiv, ve)); + let (fec, b) = self.decide_fec(bw, silk_equiv); + (fec, (fec && b != bw).then_some(b)) + } + + fn decide_fec(&self, bw: Bandwidth, rate: i32) -> (bool, Bandwidth) { + const FEC_THRESHOLDS: [i32; 10] = [12000, 1000, 14000, 1000, 16000, 1000, 20000, 1000, 22000, 1000]; + const BANDWIDTHS: [Bandwidth; 5] = [ + Bandwidth::Narrow, + Bandwidth::Medium, + Bandwidth::Wide, + Bandwidth::SuperWide, + Bandwidth::Full, + ]; + let loss = self.packet_loss_perc as i32; + if !self.inband_fec || loss == 0 { + return (false, bw); + } + let mut b = BANDWIDTHS.iter().position(|&x| x == bw).unwrap_or(0); + loop { + let mut thres = FEC_THRESHOLDS[2 * b]; + let hyst = FEC_THRESHOLDS[2 * b + 1]; + if self.lbrr_coded { + thres -= hyst; + } else { + thres += hyst; + } + thres = ((thres as i64 * (125 - loss.min(25)) as i64 * 655) >> 16) as i32; + if rate > thres { + return (true, BANDWIDTHS[b]); + } else if loss <= 5 { + return (false, bw); + } else if b > 0 { + b -= 1; + } else { + return (false, bw); + } + } + } + /// Voice activity estimate: VoIP → 115, Audio and LowDelay → 48 /// (`opus_encoder.c` `tonality_analysis` proxy — no analysis is modelled, /// so the application alone decides). @@ -883,6 +998,9 @@ impl Encoder { if self.application == Application::LowDelay { return false; } + if self.inband_fec && self.packet_loss_perc as i32 > (128 - ve) >> 4 { + return true; + } let threshold = MODE_THRESHOLD_MUSIC + ((ve * ve * (MODE_THRESHOLD_VOICE - MODE_THRESHOLD_MUSIC)) >> 14); let threshold = if self.application == Application::Voip { @@ -1147,8 +1265,12 @@ impl Encoder { .copy_from_slice(&self.silk_stuff[silk_len - d..silk_len]); self.range.reset(cap); - let silk_rate = Self::hybrid_silk_rate(self.bitrate, bandwidth); + let silk_rate = Self::hybrid_silk_rate( + self.bitrate, + if self.lbrr_coded { Bandwidth::Full } else { bandwidth }, + ); if self.channels == 2 { + self.last_silk = None; let silk = self .silk_stereo_wb .get_or_insert_with(|| Box::new(SilkStereoEncoder::new(true))); @@ -1156,12 +1278,22 @@ impl Encoder { silk.set_max_bytes(silk_max); silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?; } else { + let (lbrr, loss, same) = ( + self.lbrr_coded, + self.packet_loss_perc, + self.last_silk == Some(16), + ); let silk = self .silk_wb .get_or_insert_with(|| Box::new(SilkEncoder::new(true))); + if !same { + silk.drop_lbrr(); + } + silk.set_lbrr(lbrr, loss); silk.set_bitrate(silk_rate); silk.set_max_bytes(silk_max); silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?; + self.last_silk = Some(16); } let silk_bytes = (self.range.tell() as usize).div_ceil(8); let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap); diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index 7ea61a78..d0460fc2 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -25,7 +25,8 @@ //! empty packet to [`Decoder::decode_float`]) extends the last CELT frame: //! 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. +//! 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. //! //! The crate also carries the family's Opus *encoder* — [`Encoder`] for one //! stream, [`MultistreamEncoder`] for surround — CELT-only, fullband, mono @@ -268,6 +269,52 @@ impl Decoder { Ok(frame_size) } + /// Recovers a lost frame from the in-band FEC (SILK LBRR) carried in the packet + /// that follows it, like libopus `opus_decode(next_packet, frame_size, decode_fec=1)`. + /// Falls back to [`Decoder::conceal`] when `next_packet` carries no LBRR data. + /// Returns samples per channel (`frame_size`). + pub fn decode_fec( + &mut self, + next_packet: &[u8], + frame_size: usize, + out: &mut [f32], + ) -> Result { + if next_packet.is_empty() || frame_size * self.downsample > 5760 { + return self.conceal(frame_size, out); + } + let needed = frame_size * self.channels; + if out.len() < needed { + return Err(Error::corrupt(format!( + "opus: output buffer holds {} samples, FEC needs {needed}", + out.len() + ))); + } + let parsed = Packet::parse(next_packet, false)?; + let toc = parsed.toc; + let mode = toc.mode(); + let frame_48k = toc.frame_size_48k(); + let packet_frame = frame_48k / self.downsample; + let Some(&first) = parsed.frames.first() else { + return self.conceal(frame_size, out); + }; + if frame_size < packet_frame + || mode == Mode::Celt + || self.prev_mode == Some(Mode::Celt) + || first.len() <= 1 + || !SilkDecoder::has_lbrr(first, (frame_48k / 48).max(10)) + { + return self.conceal(frame_size, out); + } + let lead = frame_size - packet_frame; + if lead > 0 { + self.conceal(lead, &mut out[..lead * self.channels])?; + } + let dst = &mut out[lead * self.channels..needed]; + self.range_final = self.decode_frame(first, dst, toc, frame_48k, true)?; + self.last_packet_size = frame_size; + Ok(frame_size) + } + fn decode_impl( &mut self, data: &[u8], @@ -289,7 +336,7 @@ impl Decoder { let mut range = 0u32; for frame in &parsed.frames { let dst = &mut out[done * self.channels..(done + frame_out) * self.channels]; - range = self.decode_frame(frame, dst, toc, frame_48k)?; + range = self.decode_frame(frame, dst, toc, frame_48k, false)?; done += frame_out; } self.range_final = range; @@ -302,13 +349,15 @@ impl Decoder { /// 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). + /// then CELT (RFC 6716, Sections 4.2, 4.5.1 and 4.3). With `fec` set, the + /// SILK layer decodes LBRR frames and the CELT layer is concealed instead. fn decode_frame( &mut self, data: &[u8], out: &mut [f32], toc: Toc, frame_48k: usize, + fec: bool, ) -> Result { let mode = toc.mode(); let stream_channels = toc.channels(); @@ -353,6 +402,7 @@ impl Decoder { internal_rate, stream_channels, first, + fec, )?; if n == 0 { break; @@ -366,7 +416,8 @@ impl Decoder { let mut redundancy = false; let mut celt_to_silk = false; let mut redundancy_bytes = 0usize; - if mode != Mode::Celt + if !fec + && mode != Mode::Celt && dec.tell() as usize + 17 + 20 * usize::from(mode == Mode::Hybrid) <= 8 * len { redundancy = if mode == Mode::Hybrid { @@ -418,14 +469,19 @@ impl Decoder { 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, - )?; + if fec { + self.celt.set_conceal_bands(start_band, end_band); + self.celt.conceal(out, frame_48k.min(960))?; + } else { + 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 diff --git a/crates/ec-opus/src/silk.rs b/crates/ec-opus/src/silk.rs index 4186aea7..09ef8124 100644 --- a/crates/ec-opus/src/silk.rs +++ b/crates/ec-opus/src/silk.rs @@ -12,9 +12,10 @@ //! 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. +//! 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. // SILK is transliterated fixed-point arithmetic: the loops below index parallel // arrays by position because the reference's index arithmetic is the @@ -477,6 +478,23 @@ impl SilkDecoder { } } + /// Whether the first SILK frame of `payload` carries LBRR (FEC) data for the mid channel. + pub fn has_lbrr(payload: &[u8], payload_ms: usize) -> bool { + if payload.is_empty() { + return false; + } + let frames_per_packet = match payload_ms { + 40 => 2, + 60 => 3, + _ => 1, + }; + let mut dec = RangeDecoder::new(payload); + for _ in 0..frames_per_packet { + dec.dec_bit_logp(1); + } + dec.dec_bit_logp(1) + } + /// Drops all inter-packet state. pub fn reset(&mut self) { let api_rate = self.api_rate; @@ -490,6 +508,9 @@ 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. + #[allow(clippy::too_many_arguments)] pub fn decode( &mut self, dec: &mut RangeDecoder, @@ -498,6 +519,7 @@ impl SilkDecoder { internal_rate: u32, channels_internal: usize, new_packet: bool, + lbrr: bool, ) -> Result { let fs_khz = (internal_rate / 1000) as usize; if new_packet { @@ -563,7 +585,8 @@ impl SilkDecoder { } // 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 { + let skip = if lbrr { 0 } else { self.channels[0].frames_per_packet }; + for i in 0..skip { for n in 0..channels_internal { if self.channels[n].lbrr_flags[i] { if channels_internal == 2 && n == 0 { @@ -595,10 +618,19 @@ impl SilkDecoder { // 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 !lbrr || 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] + } else { + self.channels[1].vad_flags[frame] + }; + if !side_coded { + decode_only_middle = dec.dec_icdf(&STEREO_ONLY_CODE_MID_ICDF, 8) != 0; + } + } else { + ms_pred_q13 = self.stereo.pred_prev_q13; } } if channels_internal == 2 && !decode_only_middle && self.prev_decode_only_middle { @@ -620,12 +652,24 @@ impl SilkDecoder { let frame_index = self.channels[0].frames_decoded as i32 - n as i32; let cond = if frame_index <= 0 { CondCoding::Independently + } else if lbrr { + if self.channels[n].lbrr_flags[(frame_index - 1) as usize] { + CondCoding::Conditionally + } else { + 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); + 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); + } } else { buf[2..2 + n_samples_dec].fill(0); } @@ -1431,9 +1475,10 @@ fn decode_frame( dec: &mut RangeDecoder, out: &mut [i16], cond: CondCoding, + lbrr: bool, ) -> usize { let frame_index = ch.frames_decoded; - decode_indices(ch, dec, frame_index, false, cond); + decode_indices(ch, dec, frame_index, lbrr, cond); let mut pulses = [0i32; MAX_FRAME_LENGTH + SHELL_LEN]; decode_pulses( dec, diff --git a/crates/ec-opus/src/silk_enc_write.rs b/crates/ec-opus/src/silk_enc_write.rs index 0d0bd8bc..62fd1699 100644 --- a/crates/ec-opus/src/silk_enc_write.rs +++ b/crates/ec-opus/src/silk_enc_write.rs @@ -95,6 +95,10 @@ pub struct SilkEncoder { shape_gq: Vec, prev_pitch_lag: i32, last_diag: SilkFrameDiag, + lbrr_enabled: bool, + lbrr_gain_increases: i32, + pending_lbrr: Option>, + lbrr_in_packet: Option>, } /// Noise-shaping constants: AR (denominator) and MA (numerator) bandwidth @@ -176,6 +180,10 @@ impl SilkEncoder { shape_u: vec![0.0; 20 * fs_khz], shape_gq: vec![0.0; 20 * fs_khz], last_diag: SilkFrameDiag::default(), + lbrr_enabled: false, + lbrr_gain_increases: 7, + pending_lbrr: None, + lbrr_in_packet: None, } } @@ -208,6 +216,25 @@ impl SilkEncoder { self.max_bytes = max; } + /// libopus `silk_setup_LBRR`: enables LBRR (in-band FEC) for the next frames at `loss_perc` % expected loss. + pub fn set_lbrr(&mut self, enabled: bool, loss_perc: u8) { + if enabled { + self.lbrr_gain_increases = if self.lbrr_enabled { + (7 - ((loss_perc as i32 * 13107) >> 16)).max(3) + } else { + 7 + }; + } else { + self.pending_lbrr = None; + } + self.lbrr_enabled = enabled; + } + + /// Drops the LBRR frame waiting for the next packet (that packet will not follow the frame it protects). + pub fn drop_lbrr(&mut self) { + self.pending_lbrr = None; + } + fn reset_state(&mut self) { *self = Self::with_fs_khz(self.fs_khz); } @@ -271,7 +298,8 @@ impl SilkEncoder { } self.range.reset(1275); let refs: Vec<&Trial> = frames.iter().collect(); - write_packet_header(&mut self.range, &refs); + let lbrr = self.lbrr_in_packet.take(); + write_packet_header(&mut self.range, &refs, lbrr.as_deref()); prev_signal_type = 0; for (i, frame) in frames.iter().enumerate() { write_frame_data(&mut self.range, frame, i > 0, prev_signal_type); @@ -347,6 +375,7 @@ impl SilkEncoder { fs as u32 * 1000, 1, first, + false, )?; if n == 0 { break; @@ -380,6 +409,12 @@ impl SilkEncoder { 48 * frame_ms, "SilkEncoder input is 48 kHz mono" ); + let pending = if single_frame_packet { + self.pending_lbrr.take() + } else { + self.pending_lbrr = None; + None + }; let fs = self.fs_khz; let order = if fs == 16 { MAX_LPC_ORDER } else { 10 }; let nb_subfr = frame_ms / 5; @@ -721,7 +756,7 @@ impl SilkEncoder { }; let enc = &mut self.range; enc.reset(1275); - write_packet_header(enc, &[&trial]); + write_packet_header(enc, &[&trial], pending.as_deref()); write_frame_data(enc, &trial, conditional, prev_signal_type); enc.done(); debug_assert!(!enc.error()); @@ -733,7 +768,8 @@ impl SilkEncoder { // Rate control: a common gain offset moves every subframe's pulse // magnitudes together; the reservoir carries each packet's miss. - let mut best = trial(if CARRY_RATE_STEP { self.rate_step } else { 0 }); + let mut chosen_step = if CARRY_RATE_STEP { self.rate_step } else { 0 }; + let mut best = trial(chosen_step); if let Some(bps) = self.target_bps { let mut frame_bits = bps as f32 * frame_ms as f32 / 1000.0; // A packet cap is a promise to fill it: the CBR packet is padded to @@ -842,6 +878,7 @@ impl SilkEncoder { } b0 = bits_of(&best); } + chosen_step = best_step; self.rate_ema += (s_ctl as f32 - self.rate_ema) * CARRY_EMA; self.rate_step = (self.rate_ema.round() as i32).clamp(-MAX_RATE_STEP, MAX_RATE_STEP); self.reservoir = if LIBOPUS_RESERVOIR { @@ -854,11 +891,18 @@ impl SilkEncoder { ) }; } + let new_lbrr = if self.lbrr_enabled && single_frame_packet && best.vad_flag { + Some(Box::new(trial(chosen_step + self.lbrr_gain_increases))) + } else { + None + }; if let Some(enc) = shared { let trial_ref = &best; - write_packet_header(enc, &[trial_ref]); + write_packet_header(enc, &[trial_ref], pending.as_deref()); write_frame_data(enc, trial_ref, conditional, prev_signal_type); } + self.pending_lbrr = new_lbrr; + self.lbrr_in_packet = pending; self.prev_gain_index = best.prev_gain_index; self.shape_d.copy_from_slice(&best.run.d[n..]); self.shape_u.copy_from_slice(&best.run.u[n..]); @@ -1265,6 +1309,7 @@ impl SilkStereoEncoder { fs as u32 * 1000, 2, true, + false, )?; debug_assert_eq!(n, frame_ms * fs); self.mirror_range = dec.range(); @@ -1287,6 +1332,7 @@ fn write_stereo_zero_pred(enc: &mut RangeEncoder) { enc.enc_icdf(2, &UNIFORM5_ICDF, 8); } /// One closed-loop quantisation of a frame. +#[derive(Clone, Debug)] struct Run { ltp_index: [usize; MAX_NB_SUBFR], pulses: Vec, @@ -1296,6 +1342,7 @@ struct Run { gq: Vec, } +#[derive(Clone, Debug)] struct Trial { bytes: Vec, range: u32, @@ -1319,11 +1366,16 @@ struct Trial { seed_index: i32, } -fn write_packet_header(enc: &mut RangeEncoder, frames: &[&Trial]) { +fn write_packet_header(enc: &mut RangeEncoder, frames: &[&Trial], lbrr: Option<&Trial>) { for frame in frames { enc.enc_bit_logp(frame.vad_flag, 1); } - enc.enc_bit_logp(false, 1); + enc.enc_bit_logp(lbrr.is_some(), 1); + if let Some(t) = lbrr + && frames.len() == 1 + { + write_frame_data(enc, t, false, 0); + } } fn write_frame_data( @@ -1575,6 +1627,7 @@ mod tests { if wb { 16000 } else { 8000 }, 1, true, + false, ) .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 dcb9a9a6..39e451e3 100755 --- a/crates/ec-opus/src/stack_budget.rs +++ b/crates/ec-opus/src/stack_budget.rs @@ -69,8 +69,8 @@ //! that holds one is a `Box`, which //! [`the_crate_private_silk_encoders_stay_behind_a_box`] pins by source. //! -//! **Where the number sits.** At 8 KiB with the worst budgeted return at 4,072 -//! bytes ([`Encoder`]), the worst a caller owes is `2 x 4072 = 8,144` bytes -- +//! **Where the number sits.** At 8 KiB with the worst budgeted return at 4,080 +//! bytes ([`Encoder`]), the worst a caller owes is `2 x 4080 = 8,160` bytes -- //! **0.39%** of a 2 MiB thread -- and the budget sits 2.01x above the //! incumbent. The pre-fix `Encoder` (87,024 B) is **10.62x over** and the //! pre-fix `Decoder` (7,576 B) sat at 92.5% of it, so the historical defect @@ -122,7 +122,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ // -- encoder.rs ------------------------------------------------------- ( "Encoder", - Some(4072), + Some(4080), true, "Encoder::new -> Result. Was 87024, 10.62x the budget: six \ inline Option/Option slots (79176 \ @@ -235,7 +235,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ // -- silk_enc_write.rs ------------------------------------------------ ( "SilkEncoder", - Some(6664), + Some(6688), 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(19808), + Some(19856), 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 651c61c8..709e877d 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); + let _ = silk.decode(&mut dec, &mut silk_pcm, payload_ms, internal_rate, 1, first, false); 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 68545ffe..a5d0cfa7 100644 --- a/crates/ec-opus/tests/plc.rs +++ b/crates/ec-opus/tests/plc.rs @@ -77,3 +77,41 @@ fn concealment_tracks_and_recovers() { assert!(c50 > 0.9); assert!(jump < 2.0 * jump_ref); } + +#[test] +fn inband_fec_recovers_a_lost_frame() { + let pcm = voice(40); + let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); + enc.set_bitrate(48000); + enc.set_bandwidth(Some(ec_opus::Bandwidth::Full)); + enc.set_inband_fec(true); + enc.set_packet_loss_perc(15); + let mut pkt = vec![0u8; 1500]; + let packets: Vec> = pcm + .chunks_exact(FRAME) + .map(|f| { + let n = enc.encode_float(f, FRAME, &mut pkt).unwrap(); + pkt[..n].to_vec() + }) + .collect(); + let mut clean = Decoder::new(48000, 1).unwrap(); + let mut lossy = Decoder::new(48000, 1).unwrap(); + let mut buf = vec![0f32; 5760]; + let (mut a, mut b) = (Vec::new(), Vec::new()); + for (i, p) in packets.iter().enumerate() { + let k = clean.decode_float(p, &mut buf).unwrap(); + a.extend_from_slice(&buf[..k]); + let k = if i == 20 { + lossy.decode_fec(&packets[21], FRAME, &mut buf).unwrap() + } else { + lossy.decode_float(p, &mut buf).unwrap() + }; + b.extend_from_slice(&buf[..k]); + } + 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}"); + assert!(c20 > 0.7); + assert!(c22 > 0.95); +}