diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index 1ca1b316..ed49fb76 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -4,10 +4,10 @@ //! 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), SILK -//! (TOC configs 0/1/4/5/8/9, mono or stereo NB/MB/WB 10 or 20 ms; mono also -//! 40/60 ms through [`SilkEncoder`]), 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). +//! (TOC configs 0..11, mono NB/MB/WB 10/20/40/60 ms; stereo NB/MB/WB 10/20 ms, +//! with 40/60 ms carried as code-3 packets of 20 ms SILK frames), or Hybrid +//! (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). //! //! 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 @@ -28,6 +28,7 @@ use crate::silk_enc_write::{SilkEncoder, SilkStereoEncoder}; /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`). const MAX_FRAME_BYTES: usize = 1275; +const MAX_SILK_PACKET_BYTES: usize = 1 + 1 + 2 * 2 + 3 * MAX_FRAME_BYTES; /// SILK's round-trip algorithmic delay in 48 kHz samples: the analysis /// resampler (`SilkEncoder::delay_samples`) on the way in plus the decoder's @@ -84,9 +85,9 @@ pub struct Encoder { silk_stereo_nb: Option, silk_stereo_mb: Option, silk_stereo_wb: Option, - /// Scratch space for the SILK payload, sized once so the steady-state + /// Scratch space for the SILK packet payload, sized once so the steady-state /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. - silk_buf: [u8; MAX_FRAME_BYTES + 1], + silk_buf: [u8; MAX_SILK_PACKET_BYTES], /// Hybrid: the last [`HYBRID_SILK_DELAY_48K`] samples of SILK-layer input. silk_delay: Vec, /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so @@ -137,7 +138,7 @@ impl Encoder { silk_stereo_nb: None, silk_stereo_mb: None, silk_stereo_wb: None, - silk_buf: [0u8; MAX_FRAME_BYTES + 1], + silk_buf: [0u8; MAX_SILK_PACKET_BYTES], silk_delay: Vec::new(), silk_stuff: Vec::new(), }) @@ -146,7 +147,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 - /// (SILK longer than 20 ms through this wrapper or 10 ms Hybrid) fall back to CELT. + /// (10 ms Hybrid) fall back to CELT. pub fn set_mode(&mut self, mode: Option) { self.mode = mode; } @@ -165,15 +166,14 @@ 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, 10 or 20 ms frames, when the application/bitrate or an + /// SILK (10, 20, 40 or 60 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. + /// 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(fs_khz) = self.silk_choice(frame_48k) { @@ -244,26 +244,30 @@ impl Encoder { Some(Mode::Celt) | Some(Mode::Hybrid) => None, Some(Mode::Silk) => Some(forced()), None => { - if self.application == Application::Voip && self.bitrate < 20_000 { - Some(if matches!(self.bandwidth, Some(Bandwidth::Medium)) { - 12 - } else if self.bitrate > 10_000 { - 16 - } else { - 8 - }) - } else { - None + if self.application == Application::Voip { + let per_channel = self.bitrate / self.channels as u32; + if per_channel < 20_000 { + return Some(match self.bandwidth { + Some(Bandwidth::Narrow) => 8, + Some(Bandwidth::Medium) => 12, + Some(_) => 16, + None if per_channel <= 12_000 => 8, + None if per_channel <= 16_000 => 12, + None => 16, + }); + } } + None } } } /// `wants_silk` narrowed to what this encoder can actually code as SILK: - /// mono or stereo, 10 or 20 ms (480 or 960 samples at 48 kHz) frames. + /// mono 10/20/40/60 ms, stereo 10/20 ms directly, or stereo 40/60 ms as + /// code-3 packets of 20 ms SILK frames. fn silk_choice(&self, frame_48k: usize) -> Option { let fs_khz = self.wants_silk()?; - if !matches!(frame_48k, 480 | 960) { + if !matches!(frame_48k, 480 | 960 | 1920 | 2880) { return None; } Some(fs_khz) @@ -275,12 +279,13 @@ impl Encoder { /// is the better speech coder too), at the bitrate's own bandwidth /// (SWB/FB; narrower requests are CELT's). Mono and stereo, 10 or 20 ms. fn hybrid_choice(&self, frame_48k: usize) -> Option { - let lo = 20_000 * self.channels as u32; - let hi = 40_000 * self.channels as u32; + let per_channel = self.bitrate / self.channels as u32; let wanted = match self.mode { Some(Mode::Hybrid) => true, Some(_) => false, - None => self.application == Application::Voip && (lo..hi).contains(&self.bitrate), + None => { + self.application == Application::Voip && (20_000..40_000).contains(&per_channel) + } }; if !wanted || !matches!(frame_48k, 480 | 960) { return None; @@ -360,6 +365,79 @@ impl Encoder { } } + fn write_frame_len(out: &mut [u8], pos: &mut usize, len: usize) -> Result<()> { + if len > MAX_FRAME_BYTES { + return Err(Error::corrupt(format!( + "opus encode: frame payload of {len} bytes exceeds {MAX_FRAME_BYTES}" + ))); + } + if len < 252 { + out[*pos] = len as u8; + *pos += 1; + } else { + let b0 = 252 + ((len - 252) & 3); + out[*pos] = b0 as u8; + out[*pos + 1] = ((len - b0) / 4) as u8; + *pos += 2; + } + Ok(()) + } + + fn encode_stereo_silk_multiframe( + &mut self, + fs_khz: usize, + frame_48k: usize, + ) -> Result<(u8, &[u8])> { + let frame_count = frame_48k / 960; + debug_assert!(matches!(frame_count, 2 | 3)); + let mut frames = [[0u8; MAX_FRAME_BYTES + 1]; 3]; + let mut lens = [0usize; 3]; + let toc = { + let enc = match fs_khz { + 8 => self + .silk_stereo_nb + .get_or_insert_with(|| SilkStereoEncoder::new(false)), + 12 => self + .silk_stereo_mb + .get_or_insert_with(SilkStereoEncoder::new_mediumband), + _ => self + .silk_stereo_wb + .get_or_insert_with(|| SilkStereoEncoder::new(true)), + }; + enc.set_bitrate(self.bitrate); + for i in 0..frame_count { + let from = i * 2 * 960; + lens[i] = enc.encode_frame_ms( + &self.silk_stuff[from..from + 2 * 960], + &mut frames[i], + 20, + )?; + debug_assert!(i == 0 || frames[i][0] == frames[0][0]); + } + self.final_range = enc.final_range(); + frames[0][0] | 0x03 + }; + let mut pos = 0usize; + self.silk_buf[pos] = 0x80 | frame_count as u8; + pos += 1; + for &len in &lens[..frame_count - 1] { + Self::write_frame_len(&mut self.silk_buf, &mut pos, len - 1)?; + } + for i in 0..frame_count { + let len = lens[i] - 1; + if pos + len > self.silk_buf.len() { + return Err(Error::corrupt(format!( + "opus encode: SILK packet needs {} bytes, buffer holds {}", + pos + len, + self.silk_buf.len() + ))); + } + self.silk_buf[pos..pos + len].copy_from_slice(&frames[i][1..lens[i]]); + pos += len; + } + Ok((toc, &self.silk_buf[..pos])) + } + /// Picks SILK or CELT for one frame and encodes it, returning the TOC /// byte and the payload bytes (excluding TOC), borrowed from scratch /// space owned by `self` — no allocation on the steady-state path. @@ -375,6 +453,9 @@ impl Encoder { if let Some(fs_khz) = self.silk_choice(frame_48k) { if self.channels == 2 { 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); + } let enc = match fs_khz { 8 => self .silk_stereo_nb @@ -570,8 +651,7 @@ impl Encoder { let cap = cap.min(MAX_FRAME_BYTES); let frame_48k = frame_size * self.upsample; let frame_ms = frame_48k / 48; - let budget = - ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize; + let budget = ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize; let budget = budget.saturating_sub(1).clamp(2, cap); if cap < HYBRID_CELT_MIN_BYTES + 2 { return Err(Error::corrupt( @@ -713,7 +793,7 @@ mod tests { assert_eq!(e.look_ahead(960), 58, "20ms NB SILK"); e.set_bitrate(16000); - assert_eq!(e.look_ahead(960), 50, "20ms WB SILK"); + assert_eq!(e.look_ahead(960), 54, "20ms MB SILK"); e.set_bitrate(32000); assert_eq!(e.look_ahead(960), 120, "20ms hybrid, CELT's overlap"); @@ -724,4 +804,27 @@ mod tests { e.set_bitrate(64_000); assert_eq!(e.look_ahead(960), 120, "stereo 20ms hybrid"); } + + #[test] + fn voip_auto_mode_is_monotonic_per_channel() { + for channels in [1usize, 2] { + let mut e = Encoder::new(48000, channels, Application::Voip).unwrap(); + let mut last = 0u8; + for per_channel in 500..=45_000u32 { + e.set_bitrate(per_channel * channels as u32); + let class = if e.silk_choice(960).is_some() { + 0 + } else if e.hybrid_choice(960).is_some() { + 1 + } else { + 2 + }; + assert!( + class >= last, + "{channels}ch {per_channel} bps/channel regressed from {last} to {class}" + ); + last = class; + } + } + } } diff --git a/crates/ec-opus/src/silk_enc_write.rs b/crates/ec-opus/src/silk_enc_write.rs index 0b08f754..324f8a6d 100644 --- a/crates/ec-opus/src/silk_enc_write.rs +++ b/crates/ec-opus/src/silk_enc_write.rs @@ -181,6 +181,7 @@ impl SilkEncoder { None, conditional, prev_signal_type, + frames_per_packet == 1, )?; prev_signal_type = trial.signal_type; frames.push(trial); @@ -238,7 +239,7 @@ impl SilkEncoder { enc: &mut RangeEncoder, frame_ms: usize, ) -> Result<()> { - let trial = self.encode_inner(pcm48, frame_ms, Some(enc), false, 0)?; + let trial = self.encode_inner(pcm48, frame_ms, Some(enc), false, 0, true)?; self.voiced_frames += usize::from(trial.voiced); Ok(()) } @@ -288,6 +289,7 @@ impl SilkEncoder { shared: Option<&mut RangeEncoder>, conditional: bool, prev_signal_type: i32, + single_frame_packet: bool, ) -> Result { assert!( matches!(frame_ms, 10 | 20), @@ -485,9 +487,9 @@ impl SilkEncoder { // vector that best predicts the residual from the *reconstructed* // history, then quantise sample by sample with the shaped output error // fed back into the target, under the decoder's seed-driven sign flips. - let pulse_lambda = match (frame_ms, fs) { - (20, 8) => 1.25, - (10, 16) => 1.45, + let pulse_lambda = match (single_frame_packet, frame_ms, fs) { + (true, 20, 8) => 1.25, + (_, 10, 16) => 1.45, _ => PULSE_LAMBDA, }; let run = |per: usize, gains_q16: &[i32; MAX_NB_SUBFR]| -> Run { @@ -786,8 +788,12 @@ impl SilkStereoEncoder { side.push(s); side_energy += s * s; } - let mid_trial = self.mid.encode_inner(&mid, frame_ms, None, false, 0)?; - let side_trial = self.side.encode_inner(&side, frame_ms, None, false, 0)?; + let mid_trial = self + .mid + .encode_inner(&mid, frame_ms, None, false, 0, true)?; + let side_trial = self + .side + .encode_inner(&side, frame_ms, None, false, 0, true)?; let mid_only = side_energy < 1.0e-10; write_stereo_packet_header(enc, &mid_trial, &side_trial, mid_only); write_stereo_zero_pred(enc); @@ -842,8 +848,12 @@ impl SilkStereoEncoder { side.push(s); side_energy += s * s; } - let mid_trial = self.mid.encode_inner(&mid, frame_ms, None, false, 0)?; - let side_trial = self.side.encode_inner(&side, frame_ms, None, false, 0)?; + let mid_trial = self + .mid + .encode_inner(&mid, frame_ms, None, false, 0, true)?; + let side_trial = self + .side + .encode_inner(&side, frame_ms, None, false, 0, true)?; let mid_only = side_energy < 1.0e-10; self.range.reset(1275); diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 1d865b0b..ee9f9cda 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -772,7 +772,7 @@ fn real_library_sweep() { // Encoder: self-consistency (range-exact against our own decoder) // --------------------------------------------------------------------------- -use ec_opus::{Application, Bandwidth, Encoder, MultistreamEncoder}; +use ec_opus::{Application, Bandwidth, Encoder, Mode, MultistreamEncoder, Packet}; /// A deterministic music-like test signal: several detuned partials plus a /// swept component per channel, loud enough to exercise every band. @@ -875,52 +875,357 @@ fn encoder_roundtrips_at_every_rate() { } } -/// The mode `Encoder` actually picks, read back from the packet's own TOC -/// byte: Voip below 20 kbps mono selects SILK (NB at/under 10 kbps, WB -/// above), Voip 20-40 kbps mono selects Hybrid, and Audio at any rate stays -/// on CELT. #[test] -fn encoder_mode_follows_application_and_bitrate() { - // `None` for the two CELT rows: any CELT config is correct there, the - // exact one is `auto_bandwidth`'s call, not mode selection's. +fn encoder_mode_follows_application_bitrate_channels_and_frame_size() { + #[derive(Clone, Copy, Debug)] + struct Case { + app: Application, + channels: usize, + bps: u32, + frame: usize, + mode_request: Option, + bandwidth_request: Option, + mode: Mode, + bandwidth: Bandwidth, + config: u8, + code: u8, + frames: usize, + } + let cases = [ - (Application::Voip, 8_000u32, Some(1u8)), - (Application::Voip, 16_000, Some(9)), - (Application::Audio, 64_000, None), - (Application::Voip, 32_000, Some(15)), - (Application::Voip, 48_000, None), + Case { + app: Application::Voip, + channels: 1, + bps: 8_000, + frame: 480, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Narrow, + config: 0, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 1, + bps: 12_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Narrow, + config: 1, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 1, + bps: 13_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Medium, + config: 5, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 1, + bps: 16_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Medium, + config: 5, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 1, + bps: 19_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Wide, + config: 9, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 1, + bps: 20_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Hybrid, + bandwidth: Bandwidth::SuperWide, + config: 13, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 1, + bps: 39_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Hybrid, + bandwidth: Bandwidth::Full, + config: 15, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 1, + bps: 40_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Celt, + bandwidth: Bandwidth::Full, + config: 31, + code: 0, + frames: 1, + }, + Case { + app: Application::Audio, + channels: 1, + bps: 16_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Celt, + bandwidth: Bandwidth::SuperWide, + config: 27, + code: 0, + frames: 1, + }, + Case { + app: Application::Audio, + channels: 1, + bps: 64_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Celt, + bandwidth: Bandwidth::Full, + config: 31, + code: 0, + frames: 1, + }, + Case { + app: Application::LowDelay, + channels: 1, + bps: 16_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Celt, + bandwidth: Bandwidth::SuperWide, + config: 27, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 2, + bps: 16_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Narrow, + config: 1, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 2, + bps: 24_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Narrow, + config: 1, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 2, + bps: 32_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Medium, + config: 5, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 2, + bps: 38_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Wide, + config: 9, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 2, + bps: 40_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Hybrid, + bandwidth: Bandwidth::SuperWide, + config: 13, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 2, + bps: 78_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Hybrid, + bandwidth: Bandwidth::Full, + config: 15, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 2, + bps: 80_000, + frame: 960, + mode_request: None, + bandwidth_request: None, + mode: Mode::Celt, + bandwidth: Bandwidth::Full, + config: 31, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 2, + bps: 32_000, + frame: 480, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Medium, + config: 4, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 2, + bps: 32_000, + frame: 1920, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Medium, + config: 5, + code: 3, + frames: 2, + }, + Case { + app: Application::Voip, + channels: 2, + bps: 32_000, + frame: 2880, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Medium, + config: 5, + code: 3, + frames: 3, + }, + Case { + app: Application::Voip, + channels: 1, + bps: 16_000, + frame: 1920, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Medium, + config: 6, + code: 0, + frames: 1, + }, + Case { + app: Application::Voip, + channels: 1, + bps: 19_000, + frame: 2880, + mode_request: None, + bandwidth_request: None, + mode: Mode::Silk, + bandwidth: Bandwidth::Wide, + config: 11, + code: 0, + frames: 1, + }, + Case { + app: Application::Audio, + channels: 1, + bps: 64_000, + frame: 480, + mode_request: Some(Mode::Silk), + bandwidth_request: Some(Bandwidth::Medium), + mode: Mode::Silk, + bandwidth: Bandwidth::Medium, + config: 4, + code: 0, + frames: 1, + }, ]; - for (app, bps, want_config) in cases { - let mut enc = Encoder::new(48000, 1, app).unwrap(); - enc.set_bitrate(bps); - let pcm = vec![0.0f32; 960]; - let mut out = vec![0u8; 1500]; - let n = enc.encode_float(&pcm, 960, &mut out).unwrap(); - let toc = ec_opus::Toc::new(out[0]); - match want_config { - Some(want) => assert_eq!( - toc.config, want, - "{app:?} at {bps} bps: TOC config {} (wanted {want})", - toc.config - ), - None => assert_eq!( - toc.mode(), - ec_opus::Mode::Celt, - "{app:?} at {bps} bps: TOC config {} is not CELT", - toc.config - ), - } - 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"); + for case in cases { + let mut enc = Encoder::new(48000, case.channels, case.app).unwrap(); + enc.set_bitrate(case.bps); + enc.set_mode(case.mode_request); + enc.set_bandwidth(case.bandwidth_request); + let pcm = vec![0.0f32; case.frame * case.channels]; + let mut out = vec![0u8; 4096]; + let n = enc.encode_float(&pcm, case.frame, &mut out).unwrap(); + let packet = Packet::parse(&out[..n], false).unwrap(); + let toc = packet.toc; + assert_eq!(toc.mode(), case.mode, "{case:?}"); + assert_eq!(toc.bandwidth(), case.bandwidth, "{case:?}"); + assert_eq!(toc.config, case.config, "{case:?}"); + assert_eq!(toc.code, case.code, "{case:?}"); + assert_eq!(toc.stereo, case.channels == 2, "{case:?}"); + assert_eq!(packet.frames.len(), case.frames, "{case:?}"); + assert_eq!(packet.samples_48k(), case.frame, "{case:?}"); + assert!(n > 1, "{case:?}: empty packet"); + } } /// All four CELT frame sizes survive the loop, and constrained VBR both @@ -1751,7 +2056,7 @@ fn silk_mediumband_and_10ms_roundtrip() { fn silk_multiframe_packets_roundtrip() { let full = speech_like(); let pcm = &full[..46_080]; - for (tag, enc, frame_ms, config, cutoff, bps) in [ + for (tag, enc, frame_ms, config, cutoff, bps, floor) in [ ( "NB40", SilkEncoder::new(false), @@ -1759,10 +2064,19 @@ fn silk_multiframe_packets_roundtrip() { 2u8, 3500.0, 16_000u32, + 0.9329f64, ), - ("MB40", SilkEncoder::new_mediumband(), 40, 6, 5500.0, 20_000), - ("WB40", SilkEncoder::new(true), 40, 10, 7000.0, 24_000), - ("WB60", SilkEncoder::new(true), 60, 11, 7000.0, 24_000), + ( + "MB40", + SilkEncoder::new_mediumband(), + 40, + 6, + 5500.0, + 20_000, + 0.94, + ), + ("WB40", SilkEncoder::new(true), 40, 10, 7000.0, 24_000, 0.95), + ("WB60", SilkEncoder::new(true), 60, 11, 7000.0, 24_000, 0.93), ] { let (decoded, packets, voiced) = silk_roundtrip_ms(enc, pcm, frame_ms, Some(bps)); let toc = ec_opus::Toc::new(packets[0][0]); @@ -1776,7 +2090,7 @@ fn silk_multiframe_packets_roundtrip() { "silk {tag}: corr {corr:.4} at lag {lag}, voiced {voiced}/{} frames, {kbps:.2} kbps", packets.len() ); - assert!(corr >= 0.70, "{tag}: corr {corr:.4}"); + assert!(corr >= floor, "{tag}: corr {corr:.4} below {floor:.4}"); assert!(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, 2500); @@ -1827,13 +2141,25 @@ fn aligned_channel_corr(reference: &[f32], decoded: &[f32], channels: usize, ch: fn silk_stereo_speech_roundtrip() { let pcm = stereo_speech_pair(); let total = pcm.len() / 2; - for (tag, bandwidth, per_channel_bps, cutoff, config) in [ - ("NB20", Bandwidth::Narrow, 16_000u32, 3500.0, 1u8), - ("MB20", Bandwidth::Medium, 20_000, 5500.0, 5), - ("WB20", Bandwidth::Wide, 24_000, 7000.0, 9), + for (tag, bandwidth, per_channel_bps, cutoff, frame, config, code, frames) in [ + ( + "NB20", + Bandwidth::Narrow, + 16_000u32, + 3500.0, + 960usize, + 1u8, + 0u8, + 1usize, + ), + ("MB20", Bandwidth::Medium, 20_000, 5500.0, 960, 5, 0, 1), + ("WB20", Bandwidth::Wide, 24_000, 7000.0, 960, 9, 0, 1), + ("NB40", Bandwidth::Narrow, 16_000, 3500.0, 1920, 1, 3, 2), + ("MB40", Bandwidth::Medium, 20_000, 5500.0, 1920, 5, 3, 2), + ("WB60", Bandwidth::Wide, 24_000, 7000.0, 2880, 9, 3, 3), ] { - let frame = if tag.ends_with("10") { 480 } else { 960 }; let frame_ms = frame / 48; + let mono_frame_ms = frame_ms.min(20); let mut mono_floor = [0.0f64; 2]; for ch in 0..2 { let mono: Vec = pcm.chunks_exact(2).map(|f| f[ch]).collect(); @@ -1843,7 +2169,8 @@ fn silk_stereo_speech_roundtrip() { _ => SilkEncoder::new(true), }; let reference = lowpass(&mono, cutoff); - let (decoded, _, _) = silk_roundtrip_ms(silk, &mono, frame_ms, Some(per_channel_bps)); + let (decoded, _, _) = + silk_roundtrip_ms(silk, &mono, mono_frame_ms, Some(per_channel_bps)); mono_floor[ch] = aligned_corr(&reference, &decoded, 2000).0; } let mut enc = Encoder::new(48000, 2, Application::Voip).unwrap(); @@ -1851,7 +2178,7 @@ fn silk_stereo_speech_roundtrip() { enc.set_bandwidth(Some(bandwidth)); enc.set_bitrate(per_channel_bps * 2); let mut dec = Decoder::new(48000, 2).unwrap(); - let mut out = vec![0u8; 1500]; + let mut out = vec![0u8; 4096]; let mut buf = vec![0.0f32; 5760 * 2]; let mut decoded = Vec::new(); let mut packets = Vec::new(); @@ -1859,8 +2186,12 @@ fn silk_stereo_speech_roundtrip() { padded.resize(pcm.len().div_ceil(frame * 2) * frame * 2 + frame * 2, 0.0); for block in padded.chunks(frame * 2) { let len = enc.encode_float(block, frame, &mut out).expect("encode"); - let toc = ec_opus::Toc::new(out[0]); + let packet = Packet::parse(&out[..len], false).unwrap(); + let toc = packet.toc; assert_eq!(toc.config, config, "{tag}: wrong TOC config"); + assert_eq!(toc.code, code, "{tag}: wrong TOC code"); + assert_eq!(packet.frames.len(), frames, "{tag}: frame count"); + assert_eq!(packet.samples_48k(), frame, "{tag}: packet samples"); assert!(toc.stereo, "{tag}: SILK TOC is not stereo"); let n = dec.decode_float(&out[..len], &mut buf).expect("decode"); assert_eq!(n, frame, "{tag}: decoded frame size");