From 35e743eab9a062ff077d477cd9d03a0bed212b51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 21 Aug 2026 12:56:15 +0300 Subject: [PATCH] feat(opus): add 10ms mediumband silk --- crates/ec-opus/src/encoder.rs | 147 ++++++++------ crates/ec-opus/src/silk_enc_write.rs | 283 +++++++++++++++++++++------ crates/ec-opus/tests/conformance.rs | 255 +++++++++++++++++++++--- 3 files changed, 534 insertions(+), 151 deletions(-) diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index c4430f88..bb40b3f3 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -4,11 +4,11 @@ //! or the self-delimited variant of Appendix B that the multistream framing //! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s //! default) picks CELT (TOC configs 16..31, every rate and frame size) or -//! SILK (TOC configs 1/9, mono NB/WB 20 ms only — stereo SILK and SILK at -//! other frame sizes fall back to CELT, documented at the fallback site) or -//! Hybrid (TOC configs 13/15, mono SWB/FB 20 ms: SILK at 16 kHz under CELT -//! from band 17 up, one range-coded stream; stereo and other frame sizes -//! fall back to CELT). +//! SILK (TOC configs 0/1/4/5/8/9, mono NB/MB/WB 10 or 20 ms only — +//! stereo SILK and SILK at other frame sizes fall back to CELT, documented +//! at the fallback site) or Hybrid (TOC configs 13/15, mono SWB/FB 20 ms: +//! SILK at 16 kHz under CELT from band 17 up, one range-coded stream; +//! stereo and other frame sizes fall back to CELT). //! //! 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 @@ -38,6 +38,7 @@ const MAX_FRAME_BYTES: usize = 1275; /// FIR lengths differ per bandwidth, so narrowband and wideband delays /// don't have to and don't match. const SILK_LOOK_AHEAD_48K_NB: usize = 58; +const SILK_LOOK_AHEAD_48K_MB: usize = 54; const SILK_LOOK_AHEAD_48K_WB: usize = 50; /// How far the hybrid path delays the SILK layer's input so its output lines /// up with the CELT layer's at the decoder (which sums them as-is): CELT's @@ -47,8 +48,7 @@ const HYBRID_SILK_DELAY_48K: usize = 120 - SILK_LOOK_AHEAD_48K_WB; /// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent. const HYBRID_CELT_MIN_BYTES: usize = 8; -/// What the caller is encoding. This encoder is CELT-only, so the setting -/// biases the coded bandwidth rather than selecting a different layer. +/// What the caller is encoding. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Application { /// Speech: one step narrower at a given rate, where the top octave costs @@ -60,7 +60,7 @@ pub enum Application { LowDelay, } -/// One elementary Opus encoder: mono or stereo, CELT-only. +/// One elementary Opus encoder: mono or stereo. #[derive(Clone, Debug)] pub struct Encoder { celt: CeltEncoder, @@ -80,6 +80,7 @@ pub struct Encoder { /// Lazily created on first use so the mode can flip between packets /// without paying for the unused layer's state. silk_nb: Option, + silk_mb: Option, silk_wb: Option, /// Scratch space for the SILK payload, sized once so the steady-state /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. @@ -129,6 +130,7 @@ impl Encoder { final_range: 0, mode: None, silk_nb: None, + silk_mb: None, silk_wb: None, silk_buf: [0u8; MAX_FRAME_BYTES + 1], silk_delay: Vec::new(), @@ -139,7 +141,7 @@ impl Encoder { /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and /// `hybrid_choice` make from the application and bitrate; pass `None` to /// restore the automatic pick. Requests this encoder cannot honour - /// (stereo SILK/Hybrid, frames other than 20 ms) fall back to CELT. + /// (stereo SILK/Hybrid, SILK longer than 20 ms, or 10 ms Hybrid) fall back to CELT. pub fn set_mode(&mut self, mode: Option) { self.mode = mode; } @@ -158,23 +160,22 @@ impl Encoder { /// channel, native rate) frame: the decoded stream lags the input by /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate` /// cancels it exactly. CELT: one MDCT overlap, 120 samples at 48 kHz. - /// SILK (mono, 20 ms/960-sample-at-48k frames only, when the - /// application/bitrate or an explicit [`Encoder::set_mode`] select it — - /// the same [`Encoder::silk_choice`] predicate `encode_toc_and_payload` - /// dispatches on, so this always matches which layer actually codes the - /// frame): [`SILK_LOOK_AHEAD_48K_NB`] or [`SILK_LOOK_AHEAD_48K_WB`], the - /// analysis-plus-synthesis resampler round trip, click-measured per - /// bandwidth. Hybrid: CELT's 120, the SILK layer being delayed to meet - /// it ([`HYBRID_SILK_DELAY_48K`]). Any other frame size (or SILK/Hybrid's - /// mono, 20 ms requirement unmet) falls back to CELT here exactly as - /// `encode_toc_and_payload` does. + /// SILK (mono, 10 or 20 ms frames, when the application/bitrate or an + /// explicit [`Encoder::set_mode`] select it — the same + /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches + /// on, so this always matches which layer actually codes the frame): + /// [`SILK_LOOK_AHEAD_48K_NB`], [`SILK_LOOK_AHEAD_48K_MB`] or + /// [`SILK_LOOK_AHEAD_48K_WB`]. Hybrid: CELT's 120, the SILK layer being + /// delayed to meet it ([`HYBRID_SILK_DELAY_48K`]). Any other frame size + /// (or SILK/Hybrid's mono requirement unmet) falls back to CELT here + /// exactly as `encode_toc_and_payload` does. pub fn look_ahead(&self, frame_size: usize) -> usize { let frame_48k = frame_size * self.upsample; - if let Some(wideband) = self.silk_choice(frame_48k) { - let delay = if wideband { - SILK_LOOK_AHEAD_48K_WB - } else { - SILK_LOOK_AHEAD_48K_NB + if let Some(fs_khz) = self.silk_choice(frame_48k) { + let delay = match fs_khz { + 8 => SILK_LOOK_AHEAD_48K_NB, + 12 => SILK_LOOK_AHEAD_48K_MB, + _ => SILK_LOOK_AHEAD_48K_WB, }; return delay / self.upsample; } @@ -216,21 +217,33 @@ impl Encoder { pub fn reset(&mut self) { self.celt.reset(); self.silk_nb = None; + self.silk_mb = None; self.silk_wb = None; self.silk_delay.clear(); self.final_range = 0; } /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) - /// call for SILK, and if so, wideband (else narrowband). `None` means - /// CELT or Hybrid (`hybrid_choice` tells those apart). - fn wants_silk(&self) -> Option { + /// call for SILK, and if so, which SILK internal sample rate in kHz. + /// `None` means CELT or Hybrid (`hybrid_choice` tells those apart). + fn wants_silk(&self) -> Option { + let forced = || match self.bandwidth.unwrap_or_else(|| self.auto_bandwidth()) { + Bandwidth::Narrow => 8, + Bandwidth::Medium => 12, + _ => 16, + }; match self.mode { Some(Mode::Celt) | Some(Mode::Hybrid) => None, - Some(Mode::Silk) => Some(self.bitrate > 10_000), + Some(Mode::Silk) => Some(forced()), None => { if self.application == Application::Voip && self.bitrate < 20_000 { - Some(self.bitrate > 10_000) + Some(if matches!(self.bandwidth, Some(Bandwidth::Medium)) { + 12 + } else if self.bitrate > 10_000 { + 16 + } else { + 8 + }) } else { None } @@ -239,14 +252,14 @@ impl Encoder { } /// `wants_silk` narrowed to what this encoder can actually code as SILK: - /// mono, 20 ms (960 samples at 48 kHz) frames only. Stereo SILK and SILK - /// at other frame sizes are D2b's work; both fall back to CELT here. - fn silk_choice(&self, frame_48k: usize) -> Option { - let wideband = self.wants_silk()?; - if self.channels != 1 || frame_48k != 960 { + /// mono, 10 or 20 ms (480 or 960 samples at 48 kHz) frames only. Stereo + /// SILK and longer SILK packets are future work; both fall back to CELT. + fn silk_choice(&self, frame_48k: usize) -> Option { + let fs_khz = self.wants_silk()?; + if self.channels != 1 || !matches!(frame_48k, 480 | 960) { return None; } - Some(wideband) + Some(fs_khz) } /// Whether this frame goes out as a hybrid packet, and at which of the two @@ -260,8 +273,7 @@ impl Encoder { Some(Mode::Hybrid) => true, Some(_) => false, None => { - self.application == Application::Voip - && (20_000..40_000).contains(&self.bitrate) + self.application == Application::Voip && (20_000..40_000).contains(&self.bitrate) } }; if !wanted || self.channels != 1 || frame_48k != 960 { @@ -289,9 +301,19 @@ impl Encoder { (32000, 22000, 24000), (64000, 38000, 42000), ]; - let pick = |row: &(u32, u32, u32)| if bandwidth == Bandwidth::Full { row.2 } else { row.1 }; + let pick = |row: &(u32, u32, u32)| { + if bandwidth == Bandwidth::Full { + row.2 + } else { + row.1 + } + }; let total = total.min(64000); - let i = TABLE.iter().rposition(|r| r.0 <= total).unwrap().min(TABLE.len() - 2); + let i = TABLE + .iter() + .rposition(|r| r.0 <= total) + .unwrap() + .min(TABLE.len() - 2); let (lo, hi) = (&TABLE[i], &TABLE[i + 1]); pick(lo) + (pick(hi) - pick(lo)) * (total - lo.0) / (hi.0 - lo.0) } @@ -329,24 +351,28 @@ impl Encoder { cap: usize, ) -> Result<(u8, &[u8])> { let frame_48k = frame_size * self.upsample; - if let Some(wideband) = self.silk_choice(frame_48k) { + if let Some(fs_khz) = self.silk_choice(frame_48k) { Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); - let enc = if wideband { - self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)) - } else { - self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)) + let enc = match fs_khz { + 8 => self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)), + 12 => self.silk_mb.get_or_insert_with(SilkEncoder::new_mediumband), + _ => self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)), }; // 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. enc.set_bitrate(self.bitrate); - let n = enc.encode_frame(&self.silk_stuff, &mut self.silk_buf)?; + let n = enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf, frame_48k / 48)?; self.final_range = enc.final_range(); return Ok((self.silk_buf[0], &self.silk_buf[1..n])); } if let Some(bandwidth) = self.hybrid_choice(frame_48k) { let n = self.encode_hybrid(pcm, frame_size, bandwidth, cap)?; - let config = if bandwidth == Bandwidth::Full { 15u8 } else { 13 }; + let config = if bandwidth == Bandwidth::Full { + 15u8 + } else { + 13 + }; return Ok((config << 3, &self.range.data()[..n])); } let (toc, frame_48k, end) = self.toc(frame_size)?; @@ -433,7 +459,8 @@ impl Encoder { frame_size: usize, out: &mut [u8], ) -> Result { - let (toc, payload) = self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1))?; + let (toc, payload) = + self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1))?; let n = payload.len(); if out.len() < 1 + n { return Err(Error::corrupt(format!( @@ -462,7 +489,8 @@ impl Encoder { frame_size: usize, out: &mut [u8], ) -> Result { - let (toc, payload) = self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3))?; + let (toc, payload) = + self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3))?; let n = payload.len(); let len_bytes = if n < 252 { 1 } else { 2 }; if out.len() < 1 + len_bytes + n { @@ -528,14 +556,9 @@ impl Encoder { // CELT sees the same input as SILK: start band 17 alone keeps it off // the low band (a one-pole ~6 kHz high-pass here measured identical // full-band correlation, so there is none). - let n = self.celt.encode( - &mut self.range, - pcm, - 960, - 17, - bandwidth.celt_end_band(), - 0, - )?; + let n = self + .celt + .encode(&mut self.range, pcm, 960, 17, bandwidth.celt_end_band(), 0)?; self.final_range = self.range.range(); let payload = &self.range.data()[..n]; self.silk_wb.as_mut().unwrap().replay(payload)?; @@ -603,16 +626,16 @@ mod tests { assert_eq!(e.look_ahead(960), 60); } - /// `look_ahead` must use the same mono/20 ms-frame predicate dispatch - /// does (`silk_choice`/`hybrid_choice`), not just `wants_silk` — a - /// non-20 ms frame (or stereo) codes as CELT regardless of the - /// bitrate/application, so its look-ahead is CELT's 120, not SILK's. + /// `look_ahead` must use the same mono/10-or-20 ms-frame predicate + /// dispatch does (`silk_choice`/`hybrid_choice`), not just `wants_silk`: + /// 2.5/5 ms frames and stereo still code as CELT, while mono 10 ms + /// speech follows SILK. #[test] fn look_ahead_matches_the_frame_size_dispatch_actually_uses() { let mut e = Encoder::new(48000, 1, Application::Voip).unwrap(); e.set_bitrate(8000); - assert_eq!(e.look_ahead(480), 120, "sub-20ms frame falls back to CELT"); - assert_eq!(e.look_ahead(240), 120, "sub-20ms frame falls back to CELT"); + assert_eq!(e.look_ahead(480), 58, "10ms NB SILK"); + assert_eq!(e.look_ahead(240), 120, "5ms frame falls back to CELT"); assert_eq!(e.look_ahead(960), 58, "20ms NB SILK"); e.set_bitrate(16000); diff --git a/crates/ec-opus/src/silk_enc_write.rs b/crates/ec-opus/src/silk_enc_write.rs index 97d057f4..4f03aac6 100644 --- a/crates/ec-opus/src/silk_enc_write.rs +++ b/crates/ec-opus/src/silk_enc_write.rs @@ -1,5 +1,5 @@ //! SILK payload writer (subtask D2a): turns the analysis in [`crate::silk_enc`] -//! into a decodable mono 20 ms SILK packet, NB (8 kHz) or WB (16 kHz). +//! into a decodable mono SILK packet, NB (8 kHz), MB (12 kHz) or WB (16 kHz). //! //! Symbol order is exactly `silk::decode()`'s, and every decision is made //! against the decoder's own tables and reconstruction functions. The @@ -12,7 +12,7 @@ //! output error is fed back through short-term (bandwidth-expanded LPC), //! harmonic and tilt shaping filters so the noise hides under the signal's //! own spectrum, and a gain-offset rate loop sizes each packet against -//! [`SilkEncoder::set_bitrate`]. 10/40/60 ms frames and stereo are not +//! [`SilkEncoder::set_bitrate`]. 40/60 ms packets and stereo are not //! written yet. // Same idiom as silk.rs: index loops mirror the decoder's position arithmetic. @@ -23,12 +23,13 @@ use ec_core::Result; use crate::range::{RangeDecoder, RangeEncoder}; use crate::silk::tables::*; use crate::silk::{ - decode_pitch, nlsf2a, nlsf_cb, silk_rand, SilkDecoder, MAX_LPC_ORDER, MAX_NB_SUBFR, - PE_MAX_LAG_MS, PE_MIN_LAG_MS, + MAX_LPC_ORDER, MAX_NB_SUBFR, PE_MAX_LAG_MS, PE_MIN_LAG_MS, SilkDecoder, decode_pitch, nlsf_cb, + nlsf2a, silk_rand, +}; +use crate::silk_enc::{ + Resampler48, Vad, estimate_pitch, lpc_analyze, quantize_gains, quantize_nlsf, }; -use crate::silk_enc::{estimate_pitch, lpc_analyze, quantize_gains, quantize_nlsf, Resampler48, Vad}; -const NB_SUBFR: usize = 4; const SHELL_LEN: usize = 16; const LTP_ORDER: usize = 5; /// `QUANT_LEVEL_ADJUST_Q10` in `decode_core`: a non-zero pulse decodes 80/1024 @@ -38,7 +39,7 @@ const LEVEL_ADJUST: f32 = 80.0 / 1024.0; /// with 16 such pulses in one block. const MAX_PULSE: i32 = 1023; -/// A mono, 20 ms, NB or WB SILK encoder. +/// A mono, 10 or 20 ms, NB/MB/WB SILK encoder. #[derive(Clone, Debug)] pub struct SilkEncoder { fs_khz: usize, @@ -81,7 +82,16 @@ const PULSE_LAMBDA: f32 = 1.5; impl SilkEncoder { /// `wideband`: 16 kHz internal rate (TOC config 9), else 8 kHz (config 1). pub fn new(wideband: bool) -> SilkEncoder { - let fs_khz = if wideband { 16 } else { 8 }; + Self::with_fs_khz(if wideband { 16 } else { 8 }) + } + + /// Mediumband, 12 kHz internal rate (TOC config 5). + pub fn new_mediumband() -> SilkEncoder { + Self::with_fs_khz(12) + } + + fn with_fs_khz(fs_khz: usize) -> SilkEncoder { + debug_assert!(matches!(fs_khz, 8 | 12 | 16)); SilkEncoder { fs_khz, resampler: Resampler48::new(fs_khz as u32), @@ -124,13 +134,39 @@ impl SilkEncoder { self.resampler.delay_samples() } - /// Encodes 960 mono 48 kHz samples as one code-0 packet in `out`, + /// Encodes 960 mono 48 kHz samples as one 20 ms code-0 packet in `out`, /// returning its length. pub fn encode_frame(&mut self, pcm48: &[f32], out: &mut [u8]) -> Result { - let Trial { bytes, range, .. } = self.encode_inner(pcm48, None)?; + self.encode_frame_ms(pcm48, out, 20) + } + + /// Encodes 10 or 20 ms of mono 48 kHz samples as one code-0 packet in + /// `out`, returning its length. + pub fn encode_frame_ms( + &mut self, + pcm48: &[f32], + out: &mut [u8], + frame_ms: usize, + ) -> Result { + let Trial { bytes, range, .. } = self.encode_inner(pcm48, frame_ms, None)?; let len = bytes.len(); self.final_range = range; - let toc = if self.fs_khz == 16 { 9u8 << 3 } else { 1u8 << 3 }; + let duration = match frame_ms { + 10 => 0u8, + 20 => 1, + _ => { + return Err(ec_core::Error::unsupported( + format!("silk encode frame of {frame_ms} ms"), + "SILK encoder writes 10 or 20 ms packets", + )); + } + }; + let base = match self.fs_khz { + 8 => 0u8, + 12 => 4, + _ => 8, + }; + let toc = (base + duration) << 3; if out.len() < 1 + len { return Err(ec_core::Error::corrupt(format!( "silk encode: packet needs {} bytes, buffer holds {}", @@ -140,7 +176,7 @@ impl SilkEncoder { } out[0] = toc; out[1..1 + len].copy_from_slice(&bytes); - self.replay(&out[1..1 + len])?; + self.replay_ms(&out[1..1 + len], frame_ms)?; debug_assert_eq!(self.mirror_range, self.final_range); Ok(1 + len) } @@ -151,7 +187,7 @@ impl SilkEncoder { /// must [`SilkEncoder::replay`] the finished payload so this encoder's /// decoder mirror advances. pub fn encode_hybrid(&mut self, pcm48: &[f32], enc: &mut RangeEncoder) -> Result<()> { - self.encode_inner(pcm48, Some(enc)).map(|_| ()) + self.encode_inner(pcm48, 20, Some(enc)).map(|_| ()) } /// Decodes `payload` (TOC stripped) through the mirror decoder so the next @@ -159,10 +195,20 @@ impl SilkEncoder { /// does this itself, [`SilkEncoder::encode_hybrid`] callers do it once /// the packet is complete. pub fn replay(&mut self, payload: &[u8]) -> Result<()> { + self.replay_ms(payload, 20) + } + + fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> { let fs = self.fs_khz; let mut dec = RangeDecoder::new(payload); - self.mirror - .decode(&mut dec, &mut self.mirror_out, 20, fs as u32 * 1000, 1, true)?; + self.mirror.decode( + &mut dec, + &mut self.mirror_out, + frame_ms, + fs as u32 * 1000, + 1, + true, + )?; self.mirror_range = dec.range(); Ok(()) } @@ -171,12 +217,31 @@ impl SilkEncoder { /// returned trial's `bytes` are the standalone SILK payload (TOC /// excluded). With `shared`, the chosen frame's symbols are also written /// into that coder (the hybrid path). - fn encode_inner(&mut self, pcm48: &[f32], shared: Option<&mut RangeEncoder>) -> Result { - assert_eq!(pcm48.len(), 960, "SilkEncoder codes 20 ms mono frames"); + fn encode_inner( + &mut self, + pcm48: &[f32], + frame_ms: usize, + shared: Option<&mut RangeEncoder>, + ) -> Result { + assert!( + matches!(frame_ms, 10 | 20), + "SilkEncoder codes 10 or 20 ms mono frames" + ); + assert_eq!( + pcm48.len(), + 48 * frame_ms, + "SilkEncoder input is 48 kHz mono" + ); let fs = self.fs_khz; let order = if fs == 16 { MAX_LPC_ORDER } else { 10 }; - let n = 20 * fs; + let nb_subfr = frame_ms / 5; + let n = frame_ms * fs; let sub = 5 * fs; + if self.shape_d.len() != n { + self.shape_d.resize(n, 0.0); + self.shape_u.resize(n, 0.0); + self.shape_gq.resize(n, 0.0); + } let x: Vec = self .resampler .process(pcm48) @@ -186,13 +251,15 @@ impl SilkEncoder { let vad = self.vad.analyze(&x); // LPC -> NLSF indices -> the decoder's dequantised filter. - let nlsf_target = lpc_analyze(&x, order).map(|a| a.nlsf_q15).unwrap_or_else(|| { - let mut flat = [0i16; MAX_LPC_ORDER]; - for (i, v) in flat.iter_mut().enumerate().take(order) { - *v = ((i + 1) * 32768 / (order + 1)) as i16; - } - flat - }); + let nlsf_target = lpc_analyze(&x, order) + .map(|a| a.nlsf_q15) + .unwrap_or_else(|| { + let mut flat = [0i16; MAX_LPC_ORDER]; + for (i, v) in flat.iter_mut().enumerate().take(order) { + *v = ((i + 1) * 32768 / (order + 1)) as i16; + } + flat + }); let wb = fs == 16; let nq = quantize_nlsf(&nlsf_target[..order], wb); let a_q12 = nlsf2a(&nq.nlsf_q15[..order], order); @@ -224,14 +291,18 @@ impl SilkEncoder { let res: Vec = (0..n as isize).map(whiten).collect(); // Pitch / LTP. - let pitch = estimate_pitch(&x, fs as i32, NB_SUBFR).filter(|p| p.voiced); + let pitch = estimate_pitch(&x, fs as i32, nb_subfr).filter(|p| p.voiced); let voiced = pitch.is_some(); let (lag_index, contour_index, pitch_l) = match &pitch { Some(p) => { let max_index = (PE_MAX_LAG_MS - PE_MIN_LAG_MS) * fs as i32 - 1; let li = p.lag_index.clamp(0, max_index); - (li, p.contour_index, decode_pitch(li, p.contour_index, fs as i32, NB_SUBFR)) + ( + li, + p.contour_index, + decode_pitch(li, p.contour_index, fs as i32, nb_subfr), + ) } None => (0, 0, [0; MAX_NB_SUBFR]), }; @@ -259,7 +330,7 @@ impl SilkEncoder { { let mut r_ol: Vec = (-(n as isize)..0).map(whiten).collect(); r_ol.extend_from_slice(&res); - for k in 0..NB_SUBFR { + for k in 0..nb_subfr { let (e, gsum) = if voiced { LTP_GAIN_VQ_2 .iter() @@ -279,25 +350,51 @@ impl SilkEncoder { } } let vad_flag = vad.active || voiced; - let signal_type: i32 = if !vad_flag { 0 } else if voiced { 2 } else { 1 }; + let signal_type: i32 = if !vad_flag { + 0 + } else if voiced { + 2 + } else { + 1 + }; // Over-unity LTP gain: scale the previous frame's history down so // quantisation error does not build up through the pitch loop. - let ltp_scale_index = if !voiced { 0 } else if ltp_gain > 1.25 { 2 } else if ltp_gain > 1.0 { 1 } else { 0 }; + let ltp_scale_index = if !voiced { + 0 + } else if ltp_gain > 1.25 { + 2 + } else if ltp_gain > 1.0 { + 1 + } else { + 0 + }; let ltp_scale = LTPSCALES_TABLE_Q14[ltp_scale_index] as f32 / 16384.0; // Inactive or low-energy frames (and sparse voiced excitation) take the // small quantisation offset; dense unvoiced excitation the large one. - let mean_rms = targets.iter().map(|&t| t as f32 / 65536.0).sum::() / NB_SUBFR as f32; + let mean_rms = targets[..nb_subfr] + .iter() + .map(|&t| t as f32 / 65536.0) + .sum::() + / nb_subfr as f32; let quant_offset_type = usize::from(signal_type == 1 && mean_rms > 64.0); - let offset = QUANTIZATION_OFFSETS_Q10[signal_type as usize >> 1][quant_offset_type] as f32 - / 1024.0; + let offset = + QUANTIZATION_OFFSETS_Q10[signal_type as usize >> 1][quant_offset_type] as f32 / 1024.0; // Noise shaping filters, from the bandwidth-expanded LPC: the output // error d follows A(z/g2)(1 - tilt z^-1) / (A(z/g1)(1 - h z^-L)), i.e. // the quantisation noise sits under the formants and, when voiced, // under the harmonics, instead of being white at the decoder output. let (g1, g2, tilt) = (SHAPE_AR, SHAPE_MA, if voiced { SHAPE_TILT } else { 0.0 }); - let c: Vec = a.iter().enumerate().map(|(j, &aj)| aj * g1.powi(j as i32 + 1)).collect(); - let b2: Vec = a.iter().enumerate().map(|(j, &aj)| aj * g2.powi(j as i32 + 1)).collect(); + let c: Vec = a + .iter() + .enumerate() + .map(|(j, &aj)| aj * g1.powi(j as i32 + 1)) + .collect(); + let b2: Vec = a + .iter() + .enumerate() + .map(|(j, &aj)| aj * g2.powi(j as i32 + 1)) + .collect(); // (1 - B2(z))(1 - tilt z^-1) = 1 - NB(z). let mut nb = vec![0f32; order + 1]; for j in 0..order { @@ -305,7 +402,11 @@ impl SilkEncoder { nb[j + 1] -= tilt * b2[j]; } nb[0] += tilt; - let harm = if voiced { SHAPE_HARMONIC * ltp_gain.clamp(0.0, 1.0) } else { 0.0 }; + let harm = if voiced { + SHAPE_HARMONIC * ltp_gain.clamp(0.0, 1.0) + } else { + 0.0 + }; // `r`: LTP history in absolute sample units, past frame first (scaled // by ltp_scale as the decoder scales its rebuilt history), then this @@ -333,12 +434,13 @@ impl SilkEncoder { let mut pulses = vec![0i32; n]; let mut seed = seed_index; let mut err = 0f32; - for k in 0..NB_SUBFR { + for k in 0..nb_subfr { if voiced { // In-subframe taps (lag shorter than the subframe) see the // unquantised residual as a stand-in. let mut r_ol = r.clone(); - r_ol[n + k * sub..n + (k + 1) * sub].copy_from_slice(&res[k * sub..(k + 1) * sub]); + r_ol[n + k * sub..n + (k + 1) * sub] + .copy_from_slice(&res[k * sub..(k + 1) * sub]); let mut best = f32::INFINITY; for (v, b) in cbk.iter().enumerate() { let e: f32 = (0..sub) @@ -356,9 +458,17 @@ impl SilkEncoder { let idx = k * sub + i; let p = n + idx; let lpc: f32 = a.iter().enumerate().map(|(j, &aj)| aj * y[p - 1 - j]).sum(); - let pred = if voiced { ltp_pred(&r, &cbk[ltp_index[k]], k, i) } else { 0.0 }; + let pred = if voiced { + ltp_pred(&r, &cbk[ltp_index[k]], k, i) + } else { + 0.0 + }; let mut s: f32 = c.iter().enumerate().map(|(j, &cj)| cj * d[p - 1 - j]).sum(); - s -= nb.iter().enumerate().map(|(j, &bj)| bj * gq[p - 1 - j]).sum::(); + s -= nb + .iter() + .enumerate() + .map(|(j, &bj)| bj * gq[p - 1 - j]) + .sum::(); if harm > 0.0 { s += harm * u[p - lag]; } @@ -375,7 +485,9 @@ impl SilkEncoder { .into_iter() .filter(|p| p.abs() <= MAX_PULSE) .min_by(|&a, &b| { - let cost = |p: i32| (recon(p) - target).powi(2) + PULSE_LAMBDA * p.abs() as f32; + let cost = |p: i32| { + (recon(p) - target).powi(2) + PULSE_LAMBDA * p.abs() as f32 + }; cost(a).partial_cmp(&cost(b)).unwrap() }) .unwrap(); @@ -386,11 +498,22 @@ impl SilkEncoder { y[p] = r[p] + lpc; d[p] = y[p] - x[idx]; gq[p] = d[p] - s; - u[p] = d[p] - c.iter().enumerate().map(|(j, &cj)| cj * d[p - 1 - j]).sum::(); + u[p] = d[p] + - c.iter() + .enumerate() + .map(|(j, &cj)| cj * d[p - 1 - j]) + .sum::(); err += d[p] * d[p]; } } - Run { ltp_index, pulses, err, d, u, gq } + Run { + ltp_index, + pulses, + err, + d, + u, + gq, + } }; // Bitstream writer, in decode()'s order; shared by the sizing trials @@ -400,14 +523,22 @@ impl SilkEncoder { enc.enc_bit_logp(false, 1); // LBRR flag // Frame type. if vad_flag { - enc.enc_icdf(((signal_type << 1) | quant_offset_type as i32) as usize - 2, &TYPE_OFFSET_VAD_ICDF, 8); + enc.enc_icdf( + ((signal_type << 1) | quant_offset_type as i32) as usize - 2, + &TYPE_OFFSET_VAD_ICDF, + 8, + ); } else { enc.enc_icdf(quant_offset_type, &TYPE_OFFSET_NO_VAD_ICDF, 8); } // Gains: one frame per packet, so always independently coded. - enc.enc_icdf((gain_idx[0] as usize) >> 3, &GAIN_ICDF[signal_type as usize], 8); + enc.enc_icdf( + (gain_idx[0] as usize) >> 3, + &GAIN_ICDF[signal_type as usize], + 8, + ); enc.enc_icdf((gain_idx[0] as usize) & 7, &UNIFORM8_ICDF, 8); - for k in 1..NB_SUBFR { + for k in 1..nb_subfr { enc.enc_icdf(gain_idx[k] as usize, &DELTA_GAIN_ICDF, 8); } // NLSFs. @@ -428,16 +559,27 @@ impl SilkEncoder { enc.enc_icdf((q + 4) as usize, icdf, 8); } } - enc.enc_icdf(nq.interp_index as usize, &NLSF_INTERPOLATION_FACTOR_ICDF, 8); + if nb_subfr == MAX_NB_SUBFR { + enc.enc_icdf(nq.interp_index as usize, &NLSF_INTERPOLATION_FACTOR_ICDF, 8); + } // Pitch + LTP. (One frame per packet: the decoder only takes the // lag-delta code path for the 2nd+ frame of a packet, so the // absolute lag is always coded here.) if voiced { let half = fs as i32 >> 1; enc.enc_icdf((lag_index / half) as usize, &PITCH_LAG_ICDF, 8); - let low_icdf: &[u8] = if wb { &UNIFORM8_ICDF } else { &UNIFORM4_ICDF }; + let low_icdf: &[u8] = match fs { + 16 => &UNIFORM8_ICDF, + 12 => &UNIFORM6_ICDF, + _ => &UNIFORM4_ICDF, + }; enc.enc_icdf((lag_index % half) as usize, low_icdf, 8); - let contour_icdf: &[u8] = if wb { &PITCH_CONTOUR_ICDF } else { &PITCH_CONTOUR_NB_ICDF }; + let contour_icdf: &[u8] = match (fs, nb_subfr) { + (8, 4) => &PITCH_CONTOUR_NB_ICDF, + (8, _) => &PITCH_CONTOUR_10_MS_NB_ICDF, + (_, 4) => &PITCH_CONTOUR_ICDF, + _ => &PITCH_CONTOUR_10_MS_ICDF, + }; enc.enc_icdf(contour_index as usize, contour_icdf, 8); enc.enc_icdf(per_index, <P_PER_INDEX_ICDF, 8); let gain_icdf: &[u8] = match per_index { @@ -445,7 +587,7 @@ impl SilkEncoder { 1 => <P_GAIN_ICDF_1, _ => <P_GAIN_ICDF_2, }; - for k in 0..NB_SUBFR { + for k in 0..nb_subfr { enc.enc_icdf(run.ltp_index[k], gain_icdf, 8); } enc.enc_icdf(ltp_scale_index, <PSCALE_ICDF, 8); @@ -463,7 +605,7 @@ impl SilkEncoder { *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32; } let mut prev_gain_index = self.prev_gain_index; - let (gain_idx, gains_q16) = quantize_gains(&t, &mut prev_gain_index, false, NB_SUBFR); + let (gain_idx, gains_q16) = quantize_gains(&t, &mut prev_gain_index, false, nb_subfr); let (per_index, run) = candidates .iter() .map(|&per| (per, run(per, &gains_q16))) @@ -477,14 +619,21 @@ impl SilkEncoder { enc.done(); debug_assert!(!enc.error()); let len = enc.range_bytes(); - Trial { bytes: enc.data()[..len].to_vec(), range: enc.range(), prev_gain_index, gain_idx, per_index, run } + Trial { + bytes: enc.data()[..len].to_vec(), + range: enc.range(), + prev_gain_index, + gain_idx, + per_index, + run, + } }; // Rate control: a common gain offset moves every subframe's pulse // magnitudes together; the reservoir carries each packet's miss. let mut best = trial(0); if let Some(bps) = self.target_bps { - let frame_bits = bps as f32 * 0.02; + let frame_bits = bps as f32 * frame_ms as f32 / 1000.0; let target = frame_bits + self.reservoir.clamp(-frame_bits, frame_bits); let bits_of = |t: &Trial| t.bytes.len() as f32 * 8.0; let (mut s0, mut b0) = (0i32, bits_of(&best)); @@ -509,7 +658,10 @@ impl SilkEncoder { break; } } - self.reservoir = (self.reservoir + frame_bits - b0).clamp(-RESERVOIR_FRAMES * frame_bits, RESERVOIR_FRAMES * frame_bits); + self.reservoir = (self.reservoir + frame_bits - b0).clamp( + -RESERVOIR_FRAMES * frame_bits, + RESERVOIR_FRAMES * frame_bits, + ); } if let Some(enc) = shared { write(enc, &best.gain_idx, best.per_index, &best.run); @@ -543,7 +695,6 @@ struct Trial { run: Run, } - /// Bits an ICDF symbol costs, for choosing among equivalent codings. fn icdf_bits(k: usize, icdf: &[u8]) -> f32 { let hi = if k == 0 { 256 } else { icdf[k - 1] as u32 }; @@ -591,7 +742,11 @@ fn encode_pulses(enc: &mut RangeEncoder, pulses: &[i32], signal_type: i32, quant enc.enc_icdf(first, &PULSES_PER_BLOCK_ICDF[rate_level], 8); for level in 1..=shifts[i] { let icdf = &PULSES_PER_BLOCK_ICDF[9][usize::from(level == 10)..]; - let sym = if level < shifts[i] { 17 } else { sums[i] as usize }; + let sym = if level < shifts[i] { + 17 + } else { + sums[i] as usize + }; enc.enc_icdf(sym, icdf, 8); } } @@ -633,7 +788,11 @@ fn shell_encode(enc: &mut RangeEncoder, p: &[i32]) { fn join(enc: &mut RangeEncoder, a: i32, b: i32, table: &[u8]) -> i32 { let sum = a + b; if sum > 0 { - enc.enc_icdf(a as usize, &table[SHELL_CODE_TABLE_OFFSETS[sum as usize] as usize..], 8); + enc.enc_icdf( + a as usize, + &table[SHELL_CODE_TABLE_OFFSETS[sum as usize] as usize..], + 8, + ); } sum } @@ -685,7 +844,14 @@ mod tests { let len = enc.encode_frame(&x, &mut out).unwrap(); let mut rd = RangeDecoder::new(&out[1..len]); let n = dec - .decode(&mut rd, &mut pcm, 20, if wb { 16000 } else { 8000 }, 1, true) + .decode( + &mut rd, + &mut pcm, + 20, + if wb { 16000 } else { 8000 }, + 1, + true, + ) .unwrap(); assert_eq!(n, if wb { 320 } else { 160 }); assert_eq!(rd.range(), enc.final_range(), "frame {frame}"); @@ -694,4 +860,3 @@ mod tests { } } } - diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 01164d4b..5cd3efdd 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -912,6 +912,15 @@ fn encoder_mode_follows_application_and_bitrate() { } assert!(n > 1, "{app:?} at {bps} bps: empty packet"); } + + let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); + enc.set_mode(Some(ec_opus::Mode::Silk)); + enc.set_bandwidth(Some(Bandwidth::Medium)); + let pcm = vec![0.0f32; 480]; + let mut out = vec![0u8; 1500]; + let n = enc.encode_float(&pcm, 480, &mut out).unwrap(); + assert_eq!(ec_opus::Toc::new(out[0]).config, 4, "forced 10 ms MB SILK"); + assert!(n > 1, "forced 10 ms MB SILK empty packet"); } /// All four CELT frame sizes survive the loop, and constrained VBR both @@ -1045,7 +1054,14 @@ fn oracle_decodes_our_packets_across_the_rate_table() { enc.set_bitrate(kbps * 1000); let packets = encode_packets(&mut enc, &pcm, channels); let path = temp_path(&format!("{channels}ch-{kbps}k.opus")); - write_ogg_opus(&path, &packets, opus_head(channels, 120, None), channels, total, 120); + write_ogg_opus( + &path, + &packets, + opus_head(channels, 120, None), + channels, + total, + 120, + ); let Some(reference) = ffmpeg_decode(&path, channels) else { eprintln!("ffmpeg unavailable, skipped"); let _ = fs::remove_file(&path); @@ -1530,7 +1546,11 @@ fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec { let h: Vec = (0..taps) .map(|i| { let m = i as f64 - (taps - 1) as f64 / 2.0; - let sinc = if m == 0.0 { 2.0 * c } else { (2.0 * std::f64::consts::PI * c * m).sin() / (std::f64::consts::PI * m) }; + let sinc = if m == 0.0 { + 2.0 * c + } else { + (2.0 * std::f64::consts::PI * c * m).sin() / (std::f64::consts::PI * m) + }; sinc * (0.54 - 0.46 * (2.0 * std::f64::consts::PI * i as f64 / (taps - 1) as f64).cos()) }) .collect(); @@ -1541,7 +1561,11 @@ fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec { .enumerate() .map(|(k, &hk)| { let idx = n as isize + half as isize - k as isize; - if idx >= 0 && (idx as usize) < x.len() { hk * x[idx as usize] as f64 } else { 0.0 } + if idx >= 0 && (idx as usize) < x.len() { + hk * x[idx as usize] as f64 + } else { + 0.0 + } }) .sum::() as f32 }) @@ -1551,7 +1575,11 @@ fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec { /// Encodes `pcm` NB or WB, decodes each packet with our decoder asserting the /// range-coder invariant, returns (decoded 48 kHz, packets, voiced frames, /// encoder delay). -fn silk_roundtrip(pcm: &[f32], wideband: bool, bitrate: Option) -> (Vec, Vec>, usize, usize) { +fn silk_roundtrip( + pcm: &[f32], + wideband: bool, + bitrate: Option, +) -> (Vec, Vec>, usize, usize) { let mut enc = SilkEncoder::new(wideband); if let Some(bps) = bitrate { enc.set_bitrate(bps); @@ -1565,7 +1593,9 @@ fn silk_roundtrip(pcm: &[f32], wideband: bool, bitrate: Option) -> (Vec) -> (Vec, +) -> (Vec, Vec>, usize) { + if let Some(bps) = bitrate { + enc.set_bitrate(bps); + } + let frame = 48 * frame_ms; + let mut dec = Decoder::new(48000, 1).unwrap(); + let mut out = vec![0u8; 1500]; + let mut buf = vec![0f32; 5760]; + let mut decoded = Vec::new(); + let mut packets = Vec::new(); + let mut padded = pcm.to_vec(); + padded.resize(pcm.len().div_ceil(frame) * frame + frame, 0.0); + for block in padded.chunks(frame) { + let len = enc + .encode_frame_ms(block, &mut out, frame_ms) + .expect("silk encode"); + let n = dec + .decode_float(&out[..len], &mut buf) + .expect("silk decode"); + assert_eq!(n, frame); + assert_eq!(dec.final_range(), enc.final_range(), "range state diverged"); + decoded.extend_from_slice(&buf[..n]); + packets.push(out[..len].to_vec()); + } + (decoded, packets, enc.voiced_frames()) +} + /// Correlation after aligning `decoded` to `reference` at the best lag in /// `[0, max_lag)`; the peak must be interior (a peak at the search bound is /// no measurement). @@ -1612,7 +1674,10 @@ fn silk_mono_nb_wb_roundtrip() { bytes * 8 / (packets.len() * 20) ); assert!(corr >= 0.8, "{name} {tag}: corr {corr:.4}"); - assert!(lag >= delay, "{name} {tag}: aligned before the documented delay"); + assert!( + lag >= delay, + "{name} {tag}: aligned before the documented delay" + ); if *name == "synthetic" { assert!(voiced > 0, "{name} {tag}: no frame coded with LTP"); } @@ -1628,13 +1693,94 @@ fn silk_mono_nb_wb_roundtrip() { .output() .unwrap(); let stderr = String::from_utf8_lossy(&out.stderr); - assert!(out.status.success() && stderr.trim().is_empty(), "{name} {tag}: ffmpeg: {stderr}"); + assert!( + out.status.success() && stderr.trim().is_empty(), + "{name} {tag}: ffmpeg: {stderr}" + ); let _ = fs::remove_file(&path); } } } } +#[test] +fn silk_mediumband_and_10ms_roundtrip() { + let pcm = speech_like(); + for (tag, fs_khz, frame_ms, config, cutoff, bps) in [ + ("NB10", 8usize, 10usize, 0u8, 3500.0, 12_000u32), + ("MB10", 12, 10, 4, 5500.0, 16_000), + ("WB10", 16, 10, 8, 7000.0, 20_000), + ("MB20", 12, 20, 5, 5500.0, 16_000), + ] { + let enc = match fs_khz { + 8 => SilkEncoder::new(false), + 12 => SilkEncoder::new_mediumband(), + _ => SilkEncoder::new(true), + }; + let (decoded, packets, voiced) = silk_roundtrip_ms(enc, &pcm, frame_ms, Some(bps)); + assert_eq!(packets[0][0] >> 3, config, "{tag}: wrong TOC config"); + let reference = lowpass(&pcm, cutoff); + let (corr, lag) = aligned_corr(&reference, &decoded, 2000); + let bytes: usize = packets.iter().map(Vec::len).sum(); + let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64); + eprintln!( + "silk {tag}: corr {corr:.4} at lag {lag}, voiced {voiced}/{} frames, {kbps:.2} kbps", + packets.len() + ); + assert!(corr >= 0.75, "{tag}: corr {corr:.4}"); + assert!( + frame_ms == 10 || voiced > 0, + "{tag}: no frame coded with LTP" + ); + if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len()) { + let (c, _) = aligned_corr(&oracle, &decoded, 2000); + assert!(c >= 0.99, "{tag}: our decode vs oracle decode corr {c:.4}"); + } + } +} + +#[test] +fn silk_compares_to_celt_on_speech_at_speech_rates() { + let pcm = speech_like(); + for (tag, silk, bandwidth, bps, cutoff) in [ + ( + "NB16", + SilkEncoder::new(false), + Bandwidth::Narrow, + 16_000u32, + 3500.0, + ), + ( + "WB24", + SilkEncoder::new(true), + Bandwidth::Wide, + 24_000u32, + 7000.0, + ), + ] { + let reference = lowpass(&pcm, cutoff); + let (silk_decoded, silk_packets, _) = silk_roundtrip_ms(silk, &pcm, 20, Some(bps)); + let (silk_corr, silk_lag) = aligned_corr(&reference, &silk_decoded, 2000); + let mut celt = Encoder::new(48000, 1, Application::Audio).unwrap(); + celt.set_mode(Some(ec_opus::Mode::Celt)); + celt.set_bandwidth(Some(bandwidth)); + celt.set_bitrate(bps); + let (celt_decoded, celt_bytes) = roundtrip_own(&mut celt, &pcm, 1, 960); + let (celt_corr, celt_lag) = aligned_corr(&reference, &celt_decoded, 2000); + let silk_bytes: usize = silk_packets.iter().map(Vec::len).sum(); + let silk_kbps = silk_bytes as f64 * 8.0 / (silk_packets.len() as f64 * 20.0); + let celt_kbps = celt_bytes as f64 * 8.0 / 1000.0; + eprintln!( + "speech {tag}: SILK corr {silk_corr:.4} lag {silk_lag} {silk_kbps:.2} kbps; CELT corr {celt_corr:.4} lag {celt_lag} {celt_kbps:.2} kbps" + ); + assert!(silk_corr >= 0.95, "{tag}: SILK corr {silk_corr:.4}"); + assert!( + silk_corr + 0.01 >= celt_corr, + "{tag}: SILK {silk_corr:.4} trails CELT {celt_corr:.4} by >0.01" + ); + } +} + /// Reference oracle decode of `packets` as Ogg-Opus, or `None` without ffmpeg. fn oracle_decode(name: &str, packets: &[Vec], samples: usize) -> Option> { if Command::new("ffmpeg").arg("-version").output().is_err() { @@ -1649,7 +1795,10 @@ fn oracle_decode(name: &str, packets: &[Vec], samples: usize) -> Option 16.0 * 1.2 { - failures.push(format!("{name}: corr {corr:.4} (floor {floor}) at {kbps:.1} kbps")); + failures.push(format!( + "{name}: corr {corr:.4} (floor {floor}) at {kbps:.1} kbps" + )); } if let Some(oracle) = oracle_decode(&format!("silk-nsq-{name}"), &packets, pcm.len()) { let (c, _) = aligned_corr(&oracle, &decoded, 2000); @@ -1697,15 +1848,21 @@ fn silk_rate_control_tracks_target() { for (name, pcm) in &silk_sources() { for wideband in [false, true] { for kbps_target in [8u32, 12, 16, 24] { - let (decoded, packets, _, _) = silk_roundtrip(pcm, wideband, Some(kbps_target * 1000)); + let (decoded, packets, _, _) = + silk_roundtrip(pcm, wideband, Some(kbps_target * 1000)); let bytes: usize = packets.iter().map(Vec::len).sum(); let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); let reference = lowpass(pcm, if wideband { 7000.0 } else { 3500.0 }); let (corr, _) = aligned_corr(&reference, &decoded, 2000); let tag = if wideband { "WB" } else { "NB" }; - eprintln!("silk rate {name} {tag} target {kbps_target}: {kbps:.2} kbps, corr {corr:.4}"); + eprintln!( + "silk rate {name} {tag} target {kbps_target}: {kbps:.2} kbps, corr {corr:.4}" + ); let ratio = kbps / kbps_target as f64; - assert!((0.8..=1.2).contains(&ratio), "{name} {tag} target {kbps_target}: got {kbps:.2} kbps"); + assert!( + (0.8..=1.2).contains(&ratio), + "{name} {tag} target {kbps_target}: got {kbps:.2} kbps" + ); } } } @@ -1725,7 +1882,10 @@ fn silk_packets_track_encoder_bitrate() { let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); eprintln!("encoder bitrate target {kbps_target}: {kbps:.2} kbps"); let ratio = kbps / kbps_target as f64; - assert!((0.8..=1.2).contains(&ratio), "target {kbps_target}: got {kbps:.2} kbps"); + assert!( + (0.8..=1.2).contains(&ratio), + "target {kbps_target}: got {kbps:.2} kbps" + ); } } @@ -1735,7 +1895,12 @@ fn silk_packets_track_encoder_bitrate() { /// Encodes mono `pcm` as hybrid packets at `bps` and decodes them with our /// decoder, `mute` = (celt, silk) layers dropped at the decoder; asserts /// range-state parity packet for packet. Returns (decoded, packets). -fn hybrid_roundtrip(pcm: &[f32], bps: u32, bandwidth: Option, mute: (bool, bool)) -> (Vec, Vec>) { +fn hybrid_roundtrip( + pcm: &[f32], + bps: u32, + bandwidth: Option, + mute: (bool, bool), +) -> (Vec, Vec>) { let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); enc.set_bitrate(bps); enc.set_bandwidth(bandwidth); @@ -1747,8 +1912,12 @@ fn hybrid_roundtrip(pcm: &[f32], bps: u32, bandwidth: Option, mute: ( let mut padded = pcm.to_vec(); padded.resize(pcm.len().div_ceil(960) * 960 + 960, 0.0); for block in padded.chunks(960) { - let len = enc.encode_float(block, 960, &mut out).expect("hybrid encode"); - let n = dec.decode_float(&out[..len], &mut buf).expect("hybrid decode"); + let len = enc + .encode_float(block, 960, &mut out) + .expect("hybrid encode"); + let n = dec + .decode_float(&out[..len], &mut buf) + .expect("hybrid decode"); assert_eq!(n, 960); assert_eq!(dec.final_range(), enc.final_range(), "range state diverged"); decoded.extend_from_slice(&buf[..n]); @@ -1767,18 +1936,28 @@ fn hybrid_layers_align() { let at = 960 * 10 + 300; click[at] = 0.9; let peak = |x: &[f32]| { - x.iter().enumerate().max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()).unwrap().0 + x.iter() + .enumerate() + .max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()) + .unwrap() + .0 }; let (lb, _) = hybrid_roundtrip(&click, 32_000, None, (true, false)); let (hb, _) = hybrid_roundtrip(&click, 32_000, None, (false, true)); let enc = Encoder::new(48000, 1, Application::Voip).unwrap(); let (plb, phb) = (peak(&lb) as i64 - at as i64, peak(&hb) as i64 - at as i64); - eprintln!("hybrid click: LB peak +{plb}, HB peak +{phb}, look_ahead {}", { - let mut e = enc.clone(); - e.set_bitrate(32_000); - e.look_ahead(960) - }); - assert!((plb - phb).abs() <= 2, "layers misaligned: LB +{plb} vs HB +{phb}"); + eprintln!( + "hybrid click: LB peak +{plb}, HB peak +{phb}, look_ahead {}", + { + let mut e = enc.clone(); + e.set_bitrate(32_000); + e.look_ahead(960) + } + ); + assert!( + (plb - phb).abs() <= 2, + "layers misaligned: LB +{plb} vs HB +{phb}" + ); assert!((phb - 120).abs() <= 2, "HB peak +{phb}, look_ahead 120"); } @@ -1797,12 +1976,20 @@ fn hybrid_fb_roundtrip() { let (lb_corr, lb_lag) = aligned_corr(&lb_ref, &lb_only, 400); let bytes: usize = packets.iter().map(Vec::len).sum(); let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); - eprintln!("hybrid FB {name}: corr {corr:.4} at lag {lag}, LB corr {lb_corr:.4} at lag {lb_lag}, {kbps:.1} kbps"); + eprintln!( + "hybrid FB {name}: corr {corr:.4} at lag {lag}, LB corr {lb_corr:.4} at lag {lb_lag}, {kbps:.1} kbps" + ); assert!(corr >= 0.95, "{name}: full-band corr {corr:.4}"); // +-3: the wav16 fixture is a pure tone, whose phase moves the peak. - assert!((117..=123).contains(&lag), "{name}: aligned at lag {lag}, not the documented 120"); + assert!( + (117..=123).contains(&lag), + "{name}: aligned at lag {lag}, not the documented 120" + ); assert!(lb_corr >= 0.9, "{name}: low-band corr {lb_corr:.4}"); - assert!((28.0..=36.0).contains(&kbps), "{name}: {kbps:.1} kbps for a 32 kbps CBR target"); + assert!( + (28.0..=36.0).contains(&kbps), + "{name}: {kbps:.1} kbps for a 32 kbps CBR target" + ); if let Some(oracle) = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len()) { let n = oracle.len().min(decoded.len() - 120); let c = correlation(&oracle[..n], &decoded[120..120 + n]); @@ -1813,14 +2000,22 @@ fn hybrid_fb_roundtrip() { // SWB when asked for it, and the rest of the automatic hybrid range // (SILK's share leaves CELT least at the bottom of it). let speech = speech_like(); - let (_, packets) = hybrid_roundtrip(&speech, 24_000, Some(Bandwidth::SuperWide), (false, false)); + let (_, packets) = + hybrid_roundtrip(&speech, 24_000, Some(Bandwidth::SuperWide), (false, false)); assert_eq!(ec_opus::Toc::new(packets[0][0]).config, 13); for bps in [20_000u32, 24_000, 39_000] { let (decoded, packets) = hybrid_roundtrip(&speech, bps, None, (false, false)); let (corr, _) = aligned_corr(&speech, &decoded, 400); - let kbps = packets.iter().map(Vec::len).sum::() as f64 * 8.0 / (packets.len() as f64 * 20.0); - eprintln!("hybrid {bps}: config {}, corr {corr:.4}, {kbps:.1} kbps", ec_opus::Toc::new(packets[0][0]).config); + let kbps = packets.iter().map(Vec::len).sum::() as f64 * 8.0 + / (packets.len() as f64 * 20.0); + eprintln!( + "hybrid {bps}: config {}, corr {corr:.4}, {kbps:.1} kbps", + ec_opus::Toc::new(packets[0][0]).config + ); assert!(corr >= 0.9, "hybrid at {bps}: corr {corr:.4}"); - assert!(kbps <= bps as f64 / 1000.0 + 3.0, "hybrid at {bps}: {kbps:.1} kbps"); + assert!( + kbps <= bps as f64 / 1000.0 + 3.0, + "hybrid at {bps}: {kbps:.1} kbps" + ); } }