diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index bb40b3f3..ed49fb76 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -1,14 +1,13 @@ -//! The Opus packet encoder: CELT and mono SILK, 8 to 48 kHz in. +//! The Opus packet encoder: CELT, SILK and hybrid, 8 to 48 kHz in. //! //! One [`Encoder`] produces ordinary code-0 Opus packets (RFC 6716 Section 3) //! 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 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). +//! default) picks CELT (TOC configs 16..31, every rate and frame size), SILK +//! (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 @@ -25,10 +24,11 @@ use ec_core::{Error, Result}; use crate::celt_enc::CeltEncoder; use crate::packet::{Bandwidth, Mode}; use crate::range::RangeEncoder; -use crate::silk_enc_write::SilkEncoder; +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 @@ -82,9 +82,12 @@ pub struct Encoder { silk_nb: Option, silk_mb: Option, silk_wb: Option, - /// Scratch space for the SILK payload, sized once so the steady-state + silk_stereo_nb: Option, + silk_stereo_mb: Option, + silk_stereo_wb: Option, + /// 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 @@ -132,7 +135,10 @@ impl Encoder { silk_nb: None, silk_mb: None, silk_wb: None, - silk_buf: [0u8; MAX_FRAME_BYTES + 1], + silk_stereo_nb: None, + silk_stereo_mb: None, + silk_stereo_wb: None, + silk_buf: [0u8; MAX_SILK_PACKET_BYTES], silk_delay: Vec::new(), silk_stuff: Vec::new(), }) @@ -141,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 - /// (stereo SILK/Hybrid, SILK longer than 20 ms, 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; } @@ -160,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) { @@ -219,6 +224,9 @@ impl Encoder { self.silk_nb = None; self.silk_mb = None; self.silk_wb = None; + self.silk_stereo_nb = None; + self.silk_stereo_mb = None; + self.silk_stereo_wb = None; self.silk_delay.clear(); self.final_range = 0; } @@ -236,47 +244,50 @@ 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, 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. + /// 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 self.channels != 1 || !matches!(frame_48k, 480 | 960) { + if !matches!(frame_48k, 480 | 960 | 1920 | 2880) { return None; } Some(fs_khz) } /// Whether this frame goes out as a hybrid packet, and at which of the two - /// hybrid bandwidths. Automatic: VoIP from 20 kbps (where SILK alone - /// stops) to 40 kbps (where CELT alone is the better speech coder too), - /// at the bitrate's own bandwidth (SWB/FB; narrower requests are CELT's). - /// Mono 20 ms only — stereo Hybrid (which needs stereo SILK) and the - /// 10 ms hybrid configs are not implemented and fall back to CELT. + /// hybrid bandwidths. Automatic: VoIP from 20 kbps per coded channel + /// (where SILK alone stops) to 40 kbps per coded channel (where CELT alone + /// 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 per_channel = self.bitrate / self.channels as u32; let wanted = match self.mode { 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(&per_channel) } }; - if !wanted || self.channels != 1 || frame_48k != 960 { + if !wanted || !matches!(frame_48k, 480 | 960) { return None; } let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth()); @@ -339,6 +350,94 @@ impl Encoder { } } + fn zero_stuff_stereo(pcm: &[f32], frame_size: usize, upsample: usize, out: &mut Vec) { + if upsample == 1 { + out.clear(); + out.extend_from_slice(&pcm[..2 * frame_size]); + return; + } + out.resize(2 * frame_size * upsample, 0.0); + out.fill(0.0); + for i in 0..frame_size { + let dst = 2 * i * upsample; + out[dst] = pcm[2 * i] * upsample as f32; + out[dst + 1] = pcm[2 * i + 1] * upsample as f32; + } + } + + 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. @@ -352,6 +451,28 @@ impl Encoder { ) -> Result<(u8, &[u8])> { let frame_48k = frame_size * self.upsample; 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 + .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); + 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])); + } Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); let enc = match fs_khz { 8 => self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)), @@ -368,12 +489,13 @@ impl Encoder { } 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 - }; - return Ok((config << 3, &self.range.data()[..n])); + let config = 12 + + if bandwidth == Bandwidth::Full { 2u8 } else { 0 } + + if frame_48k == 960 { 1 } else { 0 }; + return Ok(( + (config << 3) | (u8::from(self.channels == 2) << 2), + &self.range.data()[..n], + )); } let (toc, frame_48k, end) = self.toc(frame_size)?; let n = self.encode_frame(pcm, frame_48k, end, cap)?; @@ -512,9 +634,9 @@ impl Encoder { Ok(1 + len_bytes + n) } - /// One hybrid frame (mono, 20 ms, `bandwidth` SWB or FB) into the - /// internal range coder, returning its byte length: the SILK layer's - /// symbols (WB, 16 kHz internal, fed the input delayed by + /// One hybrid frame (10 or 20 ms, mono or stereo, `bandwidth` SWB or FB) + /// into the internal range coder, returning its byte length: the SILK + /// layer's symbols (WB, 16 kHz internal, fed the input delayed by /// [`HYBRID_SILK_DELAY_48K`]), the no-redundancy flag under the decoder's /// exact presence rule, then the CELT layer from band 17 in the same /// coder. CBR: the packet is the bitrate's size unless SILK alone needs @@ -527,25 +649,45 @@ impl Encoder { cap: usize, ) -> Result { let cap = cap.min(MAX_FRAME_BYTES); - let budget = ((self.bitrate as u64 * 960 + 4 * 48000) / (8 * 48000)) as usize; + 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 = budget.saturating_sub(1).clamp(2, cap); if cap < HYBRID_CELT_MIN_BYTES + 2 { return Err(Error::corrupt( "opus encode: output buffer smaller than the minimum hybrid packet", )); } - Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); - let d = HYBRID_SILK_DELAY_48K; - self.silk_delay.resize(d, 0.0); - let mut delayed = Vec::with_capacity(960); + if self.channels == 2 { + Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff); + } else { + Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); + } + let d = HYBRID_SILK_DELAY_48K * self.channels; + if self.silk_delay.len() != d { + self.silk_delay.clear(); + self.silk_delay.resize(d, 0.0); + } + let silk_len = frame_48k * self.channels; + let mut delayed = Vec::with_capacity(silk_len); delayed.extend_from_slice(&self.silk_delay); - delayed.extend_from_slice(&self.silk_stuff[..960 - d]); - self.silk_delay.copy_from_slice(&self.silk_stuff[960 - d..]); + delayed.extend_from_slice(&self.silk_stuff[..silk_len - d]); + self.silk_delay + .copy_from_slice(&self.silk_stuff[silk_len - d..silk_len]); self.range.reset(cap); - let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)); - silk.set_bitrate(Self::hybrid_silk_rate(self.bitrate, bandwidth)); - silk.encode_hybrid(&delayed, &mut self.range)?; + let silk_rate = Self::hybrid_silk_rate(self.bitrate, bandwidth); + if self.channels == 2 { + let silk = self + .silk_stereo_wb + .get_or_insert_with(|| SilkStereoEncoder::new(true)); + silk.set_bitrate(silk_rate); + silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?; + } else { + let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)); + silk.set_bitrate(silk_rate); + silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?; + } let silk_bytes = (self.range.tell() as usize).div_ceil(8); let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap); self.range.shrink(budget); @@ -553,15 +695,27 @@ impl Encoder { if self.range.tell() as usize + 17 + 20 <= 8 * budget { self.range.enc_bit_logp(false, 12); } - // 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, + frame_48k, + 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)?; + if self.channels == 2 { + self.silk_stereo_wb + .as_mut() + .unwrap() + .replay_hybrid(payload, frame_ms)?; + } else { + self.silk_wb + .as_mut() + .unwrap() + .replay_hybrid(payload, frame_ms)?; + } Ok(n) } @@ -626,10 +780,10 @@ mod tests { assert_eq!(e.look_ahead(960), 60); } - /// `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. + /// `look_ahead` must use the same 10-or-20 ms-frame predicate dispatch + /// does (`silk_choice`/`hybrid_choice`), not just `wants_silk`: 2.5/5 ms + /// frames still code as CELT, while 10/20 ms speech follows SILK and + /// hybrid follows CELT's overlap. #[test] fn look_ahead_matches_the_frame_size_dispatch_actually_uses() { let mut e = Encoder::new(48000, 1, Application::Voip).unwrap(); @@ -639,13 +793,38 @@ 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"); let mut e = Encoder::new(48000, 2, Application::Voip).unwrap(); e.set_bitrate(8000); - assert_eq!(e.look_ahead(960), 120, "stereo never codes as SILK/Hybrid"); + assert_eq!(e.look_ahead(960), 58, "stereo 20ms NB SILK"); + 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/lib.rs b/crates/ec-opus/src/lib.rs index 91faa230..0f407f0d 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -81,7 +81,7 @@ pub use multistream_enc::MultistreamEncoder; pub use packet::{Bandwidth, Mode, Packet, Toc}; pub use range::{RangeDecoder, RangeEncoder}; pub use silk::SilkDecoder; -pub use silk_enc_write::SilkEncoder; +pub use silk_enc_write::{SilkEncoder, SilkStereoEncoder}; use ec_core::{Error, Result}; diff --git a/crates/ec-opus/src/silk_enc_write.rs b/crates/ec-opus/src/silk_enc_write.rs index 4f03aac6..324f8a6d 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 SILK packet, NB (8 kHz), MB (12 kHz) or WB (16 kHz). +//! into decodable SILK packets, 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,8 +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`]. 40/60 ms packets and stereo are not -//! written yet. +//! [`SilkEncoder::set_bitrate`]. // Same idiom as silk.rs: index loops mirror the decoder's position arithmetic. #![allow(clippy::needless_range_loop)] @@ -27,7 +26,7 @@ use crate::silk::{ nlsf2a, silk_rand, }; use crate::silk_enc::{ - Resampler48, Vad, estimate_pitch, lpc_analyze, quantize_gains, quantize_nlsf, + NlsfQuant, Resampler48, Vad, estimate_pitch, lpc_analyze, quantize_gains, quantize_nlsf, }; const SHELL_LEN: usize = 16; @@ -39,7 +38,7 @@ const LEVEL_ADJUST: f32 = 80.0 / 1024.0; /// with 16 such pulses in one block. const MAX_PULSE: i32 = 1023; -/// A mono, 10 or 20 ms, NB/MB/WB SILK encoder. +/// A mono, 10/20/40/60 ms, NB/MB/WB SILK encoder. #[derive(Clone, Debug)] pub struct SilkEncoder { fs_khz: usize, @@ -76,7 +75,8 @@ const GAIN_STEP: f32 = 1.1702; const RESERVOIR_FRAMES: f32 = 4.0; /// Rate penalty per unit pulse magnitude in the quantiser's squared-error /// cost: a dead zone that lets the rate loop keep finer gains for the same -/// bits (swept 0..2.5 on speech-like content; 1.5 maximised correlation). +/// bits. NB 20 ms speech wants a smaller dead zone; 10 ms WB needs a +/// slightly smaller one than the 10 ms NB/MB rows to keep upper-band pulses. const PULSE_LAMBDA: f32 = 1.5; impl SilkEncoder { @@ -128,6 +128,10 @@ impl SilkEncoder { self.target_bps = Some(bps); } + fn reset_state(&mut self) { + *self = Self::with_fs_khz(self.fs_khz); + } + /// Algorithmic delay in 48 kHz samples: the analysis resampler only /// (the decoder adds its own resampler delay on the way back up). pub fn delay_samples(&self) -> usize { @@ -140,27 +144,70 @@ impl SilkEncoder { 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. + /// Encodes 10, 20, 40 or 60 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 duration = match frame_ms { - 10 => 0u8, - 20 => 1, + let frames_per_packet = match frame_ms { + 10 | 20 => 1usize, + 40 => 2, + 60 => 3, _ => { return Err(ec_core::Error::unsupported( format!("silk encode frame of {frame_ms} ms"), - "SILK encoder writes 10 or 20 ms packets", + "SILK encoder writes 10, 20, 40 or 60 ms packets", )); } }; + assert_eq!( + pcm48.len(), + 48 * frame_ms, + "SilkEncoder input is 48 kHz mono" + ); + let mut frames = Vec::with_capacity(frames_per_packet); + let sub_ms = if frame_ms == 10 { 10 } else { 20 }; + let mut prev_signal_type = 0; + for i in 0..frames_per_packet { + let from = i * sub_ms * 48; + let to = from + sub_ms * 48; + let conditional = i > 0; + let trial = self.encode_inner( + &pcm48[from..to], + sub_ms, + None, + conditional, + prev_signal_type, + frames_per_packet == 1, + )?; + prev_signal_type = trial.signal_type; + frames.push(trial); + } + if frames.iter().any(|frame| frame.voiced) { + self.voiced_frames += 1; + } + self.range.reset(1275); + let refs: Vec<&Trial> = frames.iter().collect(); + write_packet_header(&mut self.range, &refs); + prev_signal_type = 0; + for (i, frame) in frames.iter().enumerate() { + write_frame_data(&mut self.range, frame, i > 0, prev_signal_type); + prev_signal_type = frame.signal_type; + } + self.range.done(); + debug_assert!(!self.range.error()); + let len = self.range.range_bytes(); + self.final_range = self.range.range(); + let duration = match frame_ms { + 10 => 0u8, + 20 => 1, + 40 => 2, + 60 => 3, + _ => unreachable!(), + }; let base = match self.fs_khz { 8 => 0u8, 12 => 4, @@ -175,40 +222,58 @@ impl SilkEncoder { ))); } out[0] = toc; - out[1..1 + len].copy_from_slice(&bytes); + out[1..1 + len].copy_from_slice(&self.range.data()[..len]); self.replay_ms(&out[1..1 + len], frame_ms)?; debug_assert_eq!(self.mirror_range, self.final_range); Ok(1 + len) } - /// The SILK layer of a hybrid packet: codes 960 mono 48 kHz samples into + /// The SILK layer of a hybrid packet: codes one mono 48 kHz frame into /// `enc`, the packet's shared range coder (SILK symbols first; the CELT /// layer continues in the same coder), without finishing it. The caller - /// 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, 20, Some(enc)).map(|_| ()) + /// must [`SilkEncoder::replay_hybrid`] the finished payload so this + /// encoder's decoder mirror advances. + pub fn encode_hybrid_ms( + &mut self, + pcm48: &[f32], + enc: &mut RangeEncoder, + frame_ms: usize, + ) -> Result<()> { + let trial = self.encode_inner(pcm48, frame_ms, Some(enc), false, 0, true)?; + self.voiced_frames += usize::from(trial.voiced); + Ok(()) } - /// Decodes `payload` (TOC stripped) through the mirror decoder so the next - /// frame predicts from the decoder's state; [`SilkEncoder::encode_frame`] - /// 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) + /// Decodes a finished hybrid payload (TOC stripped) through the mirror + /// decoder so the next frame predicts from the decoder's state. + pub fn replay_hybrid(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> { + self.replay_ms(payload, frame_ms) } 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, - frame_ms, - fs as u32 * 1000, - 1, - true, - )?; + let total = frame_ms * fs; + if self.mirror_out.len() < total { + self.mirror_out.resize(total, 0); + } + let mut done = 0usize; + let mut first = true; + while done < total { + let n = self.mirror.decode( + &mut dec, + &mut self.mirror_out[done..], + frame_ms, + fs as u32 * 1000, + 1, + first, + )?; + if n == 0 { + break; + } + done += n; + first = false; + } self.mirror_range = dec.range(); Ok(()) } @@ -222,6 +287,9 @@ impl SilkEncoder { pcm48: &[f32], frame_ms: usize, shared: Option<&mut RangeEncoder>, + conditional: bool, + prev_signal_type: i32, + single_frame_packet: bool, ) -> Result { assert!( matches!(frame_ms, 10 | 20), @@ -419,6 +487,11 @@ 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 (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 { let cbk = codebook(per); let mut r = r.clone(); @@ -486,7 +559,7 @@ impl SilkEncoder { .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 + (recon(p) - target).powi(2) + pulse_lambda * p.abs() as f32 }; cost(a).partial_cmp(&cost(b)).unwrap() }) @@ -516,85 +589,7 @@ impl SilkEncoder { } }; - // Bitstream writer, in decode()'s order; shared by the sizing trials - // and the hybrid path's shared coder. - let write = |enc: &mut RangeEncoder, gain_idx: &[i8], per_index: usize, run: &Run| { - enc.enc_bit_logp(vad_flag, 1); // VAD flag - 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, - ); - } 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) & 7, &UNIFORM8_ICDF, 8); - for k in 1..nb_subfr { - enc.enc_icdf(gain_idx[k] as usize, &DELTA_GAIN_ICDF, 8); - } - // NLSFs. - let cb = nlsf_cb(wb); - let stage1_icdf = &cb.cb1_icdf[(signal_type as usize >> 1) * cb.n_vectors..]; - enc.enc_icdf(nq.indices[0] as usize, stage1_icdf, 8); - let (ec_ix, _) = crate::silk::nlsf_unpack(cb, nq.indices[0] as usize); - for i in 0..order { - let q = nq.indices[i + 1] as i32; - let icdf = &cb.ec_icdf[ec_ix[i] as usize..]; - if q <= -4 { - enc.enc_icdf(0, icdf, 8); - enc.enc_icdf((-4 - q) as usize, &NLSF_EXT_ICDF, 8); - } else if q >= 4 { - enc.enc_icdf(8, icdf, 8); - enc.enc_icdf((q - 4) as usize, &NLSF_EXT_ICDF, 8); - } else { - enc.enc_icdf((q + 4) as usize, 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] = 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] = 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 { - 0 => <P_GAIN_ICDF_0, - 1 => <P_GAIN_ICDF_1, - _ => <P_GAIN_ICDF_2, - }; - 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); - } - enc.enc_icdf(seed_index as usize, &UNIFORM4_ICDF, 8); - encode_pulses(enc, &run.pulses, signal_type, quant_offset_type as i32); - }; + let fs = self.fs_khz; // One full trial at a common gain offset (in quantiser steps): returns // the coded packet body so the rate loop can read its exact size. let candidates: Vec = if voiced { vec![0, 1, 2] } else { vec![0] }; @@ -605,28 +600,45 @@ 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, conditional, nb_subfr); let (per_index, run) = candidates .iter() .map(|&per| (per, run(per, &gains_q16))) .min_by(|a, b| a.1.err.partial_cmp(&b.1.err).unwrap()) .unwrap(); - // --- Bitstream, in decode()'s order. --- + let mut trial = Trial { + bytes: Vec::new(), + range: 0, + prev_gain_index, + gain_idx, + per_index, + run, + vad_flag, + signal_type, + quant_offset_type, + wb, + order, + nb_subfr, + fs, + lag_index, + contour_index, + voiced, + ltp_scale_index, + nq: nq.clone(), + seed_index, + }; let enc = &mut self.range; enc.reset(1275); - write(enc, &gain_idx, per_index, &run); + write_packet_header(enc, &[&trial]); + write_frame_data(enc, &trial, conditional, prev_signal_type); 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(); + trial.range = enc.range(); + trial }; // Rate control: a common gain offset moves every subframe's pulse @@ -664,10 +676,11 @@ impl SilkEncoder { ); } if let Some(enc) = shared { - write(enc, &best.gain_idx, best.per_index, &best.run); + let trial_ref = &best; + write_packet_header(enc, &[trial_ref]); + write_frame_data(enc, trial_ref, conditional, prev_signal_type); } self.prev_gain_index = best.prev_gain_index; - self.voiced_frames += usize::from(voiced); self.shape_d.copy_from_slice(&best.run.d[n..]); self.shape_u.copy_from_slice(&best.run.u[n..]); self.shape_gq.copy_from_slice(&best.run.gq[n..]); @@ -675,6 +688,258 @@ impl SilkEncoder { } } +/// A stereo, 10 or 20 ms, NB/MB/WB SILK encoder. +#[derive(Clone, Debug)] +pub struct SilkStereoEncoder { + fs_khz: usize, + mid: SilkEncoder, + side: SilkEncoder, + range: RangeEncoder, + mirror: SilkDecoder, + final_range: u32, + mirror_range: u32, + mirror_out: Vec, + target_bps: Option, + prev_mid_only: bool, + voiced_frames: usize, +} + +impl SilkStereoEncoder { + /// Narrowband or wideband stereo encoder. + pub fn new(wideband: bool) -> SilkStereoEncoder { + Self::with_fs_khz(if wideband { 16 } else { 8 }) + } + + /// Mediumband stereo encoder. + pub fn new_mediumband() -> SilkStereoEncoder { + Self::with_fs_khz(12) + } + + fn with_fs_khz(fs_khz: usize) -> SilkStereoEncoder { + SilkStereoEncoder { + fs_khz, + mid: SilkEncoder::with_fs_khz(fs_khz), + side: SilkEncoder::with_fs_khz(fs_khz), + range: RangeEncoder::new(), + mirror: SilkDecoder::new(fs_khz as u32 * 1000, 2), + final_range: 0, + mirror_range: 0, + mirror_out: vec![0; 2 * 20 * fs_khz], + target_bps: None, + prev_mid_only: false, + voiced_frames: 0, + } + } + + /// The range coder state after the last packet. + pub fn final_range(&self) -> u32 { + self.final_range + } + + /// Packets so far coded with a long-term predictor in either channel. + pub fn voiced_frames(&self) -> usize { + self.voiced_frames + } + + /// Target bit rate in bits per second for the whole stereo packet. + pub fn set_bitrate(&mut self, bps: u32) { + self.target_bps = Some(bps); + let per_channel = (bps / 2).max(500); + self.mid.set_bitrate(per_channel); + self.side.set_bitrate(per_channel); + } + + /// Algorithmic delay in 48 kHz samples. + pub fn delay_samples(&self) -> usize { + self.mid.delay_samples() + } + + /// The SILK layer of a hybrid packet: codes one interleaved stereo 48 kHz + /// frame into the packet's shared range coder without finishing it. + pub fn encode_hybrid_ms( + &mut self, + pcm48: &[f32], + enc: &mut RangeEncoder, + frame_ms: usize, + ) -> Result<()> { + assert!( + matches!(frame_ms, 10 | 20), + "SilkStereoEncoder codes 10 or 20 ms stereo frames" + ); + assert_eq!( + pcm48.len(), + 2 * 48 * frame_ms, + "SilkStereoEncoder input is 48 kHz stereo" + ); + if self.prev_mid_only { + self.side.reset_state(); + if let Some(bps) = self.target_bps { + self.side.set_bitrate((bps / 2).max(500)); + } + } + let samples = 48 * frame_ms; + let mut mid = Vec::with_capacity(samples); + let mut side = Vec::with_capacity(samples); + let mut side_energy = 0.0f32; + for lr in pcm48.chunks_exact(2) { + let m = 0.5 * (lr[0] + lr[1]); + let s = 0.5 * (lr[0] - lr[1]); + mid.push(m); + side.push(s); + side_energy += s * s; + } + 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); + if !side_trial.vad_flag { + enc.enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8); + } + write_frame_data(enc, &mid_trial, false, 0); + if !mid_only { + write_frame_data(enc, &side_trial, false, 0); + } + self.mid.replay_ms(&mid_trial.bytes, frame_ms)?; + if mid_only { + self.side.reset_state(); + } else { + self.side.replay_ms(&side_trial.bytes, frame_ms)?; + } + self.prev_mid_only = mid_only; + self.voiced_frames += usize::from(mid_trial.voiced || side_trial.voiced); + Ok(()) + } + + /// Encodes one 10 or 20 ms interleaved stereo frame at 48 kHz. + pub fn encode_frame_ms( + &mut self, + pcm48: &[f32], + out: &mut [u8], + frame_ms: usize, + ) -> Result { + assert!( + matches!(frame_ms, 10 | 20), + "SilkStereoEncoder codes 10 or 20 ms stereo frames" + ); + assert_eq!( + pcm48.len(), + 2 * 48 * frame_ms, + "SilkStereoEncoder input is 48 kHz stereo" + ); + if self.prev_mid_only { + self.side.reset_state(); + if let Some(bps) = self.target_bps { + self.side.set_bitrate((bps / 2).max(500)); + } + } + let samples = 48 * frame_ms; + let mut mid = Vec::with_capacity(samples); + let mut side = Vec::with_capacity(samples); + let mut side_energy = 0.0f32; + for lr in pcm48.chunks_exact(2) { + let m = 0.5 * (lr[0] + lr[1]); + let s = 0.5 * (lr[0] - lr[1]); + mid.push(m); + side.push(s); + side_energy += s * s; + } + 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); + write_stereo_packet_header(&mut self.range, &mid_trial, &side_trial, mid_only); + write_stereo_zero_pred(&mut self.range); + if !side_trial.vad_flag { + self.range + .enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8); + } + write_frame_data(&mut self.range, &mid_trial, false, 0); + if !mid_only { + write_frame_data(&mut self.range, &side_trial, false, 0); + } + self.range.done(); + debug_assert!(!self.range.error()); + let len = self.range.range_bytes(); + self.final_range = self.range.range(); + let duration = if frame_ms == 10 { 0u8 } else { 1 }; + let base = match self.fs_khz { + 8 => 0u8, + 12 => 4, + _ => 8, + }; + if out.len() < 1 + len { + return Err(ec_core::Error::corrupt(format!( + "silk stereo encode: packet needs {} bytes, buffer holds {}", + 1 + len, + out.len() + ))); + } + out[0] = ((base + duration) << 3) | 0x04; + out[1..1 + len].copy_from_slice(&self.range.data()[..len]); + self.replay_ms(&out[1..1 + len], frame_ms)?; + self.mid.replay_ms(&mid_trial.bytes, frame_ms)?; + if mid_only { + self.side.reset_state(); + } else { + self.side.replay_ms(&side_trial.bytes, frame_ms)?; + } + self.prev_mid_only = mid_only; + self.voiced_frames += usize::from(mid_trial.voiced || side_trial.voiced); + debug_assert_eq!(self.mirror_range, self.final_range); + Ok(1 + len) + } + + /// Decodes a finished hybrid payload (TOC stripped) through the stereo + /// mirror so the range state can be checked against the packet encoder. + pub fn replay_hybrid(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> { + self.replay_ms(payload, frame_ms) + } + + fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> { + let fs = self.fs_khz; + let mut dec = RangeDecoder::new(payload); + let total = 2 * frame_ms * fs; + if self.mirror_out.len() < total { + self.mirror_out.resize(total, 0); + } + let n = self.mirror.decode( + &mut dec, + &mut self.mirror_out[..total], + frame_ms, + fs as u32 * 1000, + 2, + true, + )?; + debug_assert_eq!(n, frame_ms * fs); + self.mirror_range = dec.range(); + Ok(()) + } +} + +fn write_stereo_packet_header(enc: &mut RangeEncoder, mid: &Trial, side: &Trial, mid_only: bool) { + enc.enc_bit_logp(mid.vad_flag, 1); + enc.enc_bit_logp(false, 1); + enc.enc_bit_logp(if mid_only { false } else { side.vad_flag }, 1); + enc.enc_bit_logp(false, 1); +} + +fn write_stereo_zero_pred(enc: &mut RangeEncoder) { + enc.enc_icdf(12, &STEREO_PRED_JOINT_ICDF, 8); + enc.enc_icdf(1, &UNIFORM3_ICDF, 8); + enc.enc_icdf(2, &UNIFORM5_ICDF, 8); + enc.enc_icdf(1, &UNIFORM3_ICDF, 8); + enc.enc_icdf(2, &UNIFORM5_ICDF, 8); +} /// One closed-loop quantisation of a frame. struct Run { ltp_index: [usize; MAX_NB_SUBFR], @@ -685,7 +950,6 @@ struct Run { gq: Vec, } -/// One coded candidate of a frame at a given gain offset. struct Trial { bytes: Vec, range: u32, @@ -693,6 +957,119 @@ struct Trial { gain_idx: [i8; MAX_NB_SUBFR], per_index: usize, run: Run, + vad_flag: bool, + signal_type: i32, + quant_offset_type: usize, + wb: bool, + order: usize, + nb_subfr: usize, + fs: usize, + lag_index: i32, + contour_index: i32, + voiced: bool, + ltp_scale_index: usize, + nq: NlsfQuant, + seed_index: i32, +} + +fn write_packet_header(enc: &mut RangeEncoder, frames: &[&Trial]) { + for frame in frames { + enc.enc_bit_logp(frame.vad_flag, 1); + } + enc.enc_bit_logp(false, 1); +} + +fn write_frame_data( + enc: &mut RangeEncoder, + frame: &Trial, + conditional: bool, + prev_signal_type: i32, +) { + if frame.vad_flag { + enc.enc_icdf( + ((frame.signal_type << 1) | frame.quant_offset_type as i32) as usize - 2, + &TYPE_OFFSET_VAD_ICDF, + 8, + ); + } else { + enc.enc_icdf(frame.quant_offset_type, &TYPE_OFFSET_NO_VAD_ICDF, 8); + } + if conditional { + enc.enc_icdf(frame.gain_idx[0] as usize, &DELTA_GAIN_ICDF, 8); + } else { + enc.enc_icdf( + (frame.gain_idx[0] as usize) >> 3, + &GAIN_ICDF[frame.signal_type as usize], + 8, + ); + enc.enc_icdf((frame.gain_idx[0] as usize) & 7, &UNIFORM8_ICDF, 8); + } + for k in 1..frame.nb_subfr { + enc.enc_icdf(frame.gain_idx[k] as usize, &DELTA_GAIN_ICDF, 8); + } + let cb = nlsf_cb(frame.wb); + let stage1_icdf = &cb.cb1_icdf[(frame.signal_type as usize >> 1) * cb.n_vectors..]; + enc.enc_icdf(frame.nq.indices[0] as usize, stage1_icdf, 8); + let (ec_ix, _) = crate::silk::nlsf_unpack(cb, frame.nq.indices[0] as usize); + for i in 0..frame.order { + let q = frame.nq.indices[i + 1] as i32; + let icdf = &cb.ec_icdf[ec_ix[i] as usize..]; + if q <= -4 { + enc.enc_icdf(0, icdf, 8); + enc.enc_icdf((-4 - q) as usize, &NLSF_EXT_ICDF, 8); + } else if q >= 4 { + enc.enc_icdf(8, icdf, 8); + enc.enc_icdf((q - 4) as usize, &NLSF_EXT_ICDF, 8); + } else { + enc.enc_icdf((q + 4) as usize, icdf, 8); + } + } + if frame.nb_subfr == MAX_NB_SUBFR { + enc.enc_icdf( + frame.nq.interp_index as usize, + &NLSF_INTERPOLATION_FACTOR_ICDF, + 8, + ); + } + if frame.voiced { + if conditional && prev_signal_type == 2 { + enc.enc_icdf(0, &PITCH_DELTA_ICDF, 8); + } + let half = frame.fs as i32 >> 1; + enc.enc_icdf((frame.lag_index / half) as usize, &PITCH_LAG_ICDF, 8); + let low_icdf: &[u8] = match frame.fs { + 16 => &UNIFORM8_ICDF, + 12 => &UNIFORM6_ICDF, + _ => &UNIFORM4_ICDF, + }; + enc.enc_icdf((frame.lag_index % half) as usize, low_icdf, 8); + let contour_icdf: &[u8] = match (frame.fs, frame.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(frame.contour_index as usize, contour_icdf, 8); + enc.enc_icdf(frame.per_index, <P_PER_INDEX_ICDF, 8); + let gain_icdf: &[u8] = match frame.per_index { + 0 => <P_GAIN_ICDF_0, + 1 => <P_GAIN_ICDF_1, + _ => <P_GAIN_ICDF_2, + }; + for k in 0..frame.nb_subfr { + enc.enc_icdf(frame.run.ltp_index[k], gain_icdf, 8); + } + if !conditional { + enc.enc_icdf(frame.ltp_scale_index, <PSCALE_ICDF, 8); + } + } + enc.enc_icdf(frame.seed_index as usize, &UNIFORM4_ICDF, 8); + encode_pulses( + enc, + &frame.run.pulses, + frame.signal_type, + frame.quant_offset_type as i32, + ); } /// Bits an ICDF symbol costs, for choosing among equivalent codings. diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 5cd3efdd..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 and Audio at any rate stay on CELT (Hybrid is -/// unimplemented and Mode 20-40 kbps needs it, D4). #[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 @@ -972,9 +1277,9 @@ fn opus_head(channels: usize, pre_skip: u16, layout: Option<(usize, usize, &[u8] ec_opus::ogg::opus_head(channels as u8, pre_skip, 48000, 0, mapping) } -/// Muxes 20 ms packets into an Ogg-Opus file whose final granule trims the -/// stream to exactly `total_samples` — RFC 7845 end-trimming plus the -/// pre-skip accounting. +/// Muxes packets into an Ogg-Opus file whose final granule trims the stream +/// to exactly `total_samples` — RFC 7845 end-trimming plus the pre-skip +/// accounting. fn write_ogg_opus( path: &Path, packets: &[Vec], @@ -996,16 +1301,17 @@ fn write_ogg_opus( let mut pts = 0i64; for (idx, p) in packets.iter().enumerate() { let last = idx == packets.len() - 1; + let packet_dur = ec_opus::Packet::parse(p, false).unwrap().samples_48k() as i64; let dur = if last { total_samples as i64 + pre_skip - pts } else { - 960 + packet_dur }; let pkt = CorePacket::new(0, tb, p.clone()) .with_pts(pts) .with_duration(dur); mux.write_packet(&pkt).unwrap(); - pts += 960; + pts += packet_dur; } mux.finish().unwrap(); } @@ -1036,7 +1342,14 @@ fn encode_packets(enc: &mut Encoder, pcm: &[f32], channels: usize) -> Vec PathBuf { - std::env::temp_dir().join(format!("ec-opus-enc-{}-{name}", std::process::id())) + let root = std::env::var_os("EC_OPUS_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(|| { + let home = std::env::var_os("HOME").expect("HOME set for encoder scratch"); + PathBuf::from(home).join(".cache/silk2") + }); + fs::create_dir_all(&root).unwrap(); + root.join(format!("ec-opus-enc-{}-{name}", std::process::id())) } /// The full product rate table, mono and stereo, decoded by libopus: the @@ -1706,11 +2019,11 @@ fn silk_mono_nb_wb_roundtrip() { #[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), + for (tag, fs_khz, frame_ms, config, cutoff, bps, floor) in [ + ("NB10", 8usize, 10usize, 0u8, 3500.0, 12_000u32, 0.89f64), + ("MB10", 12, 10, 4, 5500.0, 16_000, 0.91), + ("WB10", 16, 10, 8, 7000.0, 20_000, 0.93), + ("MB20", 12, 20, 5, 5500.0, 16_000, 0.95), ] { let enc = match fs_khz { 8 => SilkEncoder::new(false), @@ -1727,7 +2040,7 @@ fn silk_mediumband_and_10ms_roundtrip() { "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!(corr >= floor, "{tag}: corr {corr:.4}"); assert!( frame_ms == 10 || voiced > 0, "{tag}: no frame coded with LTP" @@ -1739,6 +2052,207 @@ fn silk_mediumband_and_10ms_roundtrip() { } } +#[test] +fn silk_multiframe_packets_roundtrip() { + let full = speech_like(); + let pcm = &full[..46_080]; + for (tag, enc, frame_ms, config, cutoff, bps, floor) in [ + ( + "NB40", + SilkEncoder::new(false), + 40usize, + 2u8, + 3500.0, + 16_000u32, + 0.9329f64, + ), + ( + "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]); + assert_eq!(toc.config, config, "{tag}: wrong TOC config"); + assert_eq!(toc.code, 0, "{tag}: multiframe SILK uses one Opus frame"); + let reference = lowpass(pcm, cutoff); + let (corr, lag) = aligned_corr(&reference, &decoded, 2500); + 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 >= 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); + assert!( + c >= 0.99, + "{tag}: internal decode vs external decode corr {c:.4}" + ); + } + if Command::new("gst-launch-1.0") + .arg("--version") + .output() + .is_ok() + { + let path = temp_path(&format!("silk-{tag}-gst.opus")); + write_ogg_opus(&path, &packets, opus_head(1, 120, None), 1, pcm.len(), 120); + let location = format!("location={}", path.display()); + let out = Command::new("gst-launch-1.0") + .args([ + "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink", + ]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{tag}: gst decode: {stderr}"); + let _ = fs::remove_file(&path); + } + } +} + +fn stereo_speech_pair() -> Vec { + let left = speech_like(); + let mut out = Vec::with_capacity(left.len() * 2); + for (i, &l) in left.iter().enumerate() { + let t = i as f64 / 48000.0; + let r = 0.78 * l + 0.12 * (std::f64::consts::TAU * 310.0 * t).sin() as f32; + out.push(l); + out.push(r); + } + out +} + +fn aligned_channel_corr(reference: &[f32], decoded: &[f32], channels: usize, ch: usize) -> f64 { + let b: Vec = decoded.chunks_exact(channels).map(|f| f[ch]).collect(); + aligned_corr(reference, &b, 2000).0 +} + +#[test] +fn silk_stereo_speech_roundtrip() { + let pcm = stereo_speech_pair(); + let total = pcm.len() / 2; + 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_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(); + let silk = match bandwidth { + Bandwidth::Narrow => SilkEncoder::new(false), + Bandwidth::Medium => SilkEncoder::new_mediumband(), + _ => SilkEncoder::new(true), + }; + let reference = lowpass(&mono, cutoff); + 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(); + enc.set_mode(Some(ec_opus::Mode::Silk)); + 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; 4096]; + let mut buf = vec![0.0f32; 5760 * 2]; + let mut decoded = Vec::new(); + let mut packets = Vec::new(); + let mut padded = pcm.clone(); + 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 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"); + assert_eq!(dec.final_range(), enc.final_range(), "{tag}: range state"); + decoded.extend_from_slice(&buf[..n * 2]); + packets.push(out[..len].to_vec()); + } + let bytes: usize = packets.iter().map(Vec::len).sum(); + let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64); + for ch in 0..2 { + let source: Vec = pcm.chunks_exact(2).map(|f| f[ch]).collect(); + let reference = lowpass(&source, cutoff); + let corr = aligned_channel_corr(&reference, &decoded, 2, ch); + eprintln!( + "silk stereo {tag} ch{ch}: corr {corr:.4}, mono {:.4}, {kbps:.2} kbps", + mono_floor[ch] + ); + assert!( + corr + 0.01 >= mono_floor[ch], + "{tag} ch{ch}: stereo corr {corr:.4} trails mono {:.4}", + mono_floor[ch] + ); + } + if Command::new("ffmpeg").arg("-version").output().is_ok() { + let path = temp_path(&format!("silk-stereo-{tag}.opus")); + write_ogg_opus( + &path, + &packets, + opus_head(2, enc.look_ahead(frame) as u16, None), + 2, + total, + enc.look_ahead(frame) as i64, + ); + let out = Command::new("ffmpeg") + .args(["-v", "warning", "-c:a", "libopus", "-i"]) + .arg(&path) + .args(["-f", "null", "-"]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}"); + if Command::new("gst-launch-1.0") + .arg("--version") + .output() + .is_ok() + { + let location = format!("location={}", path.display()); + let out = Command::new("gst-launch-1.0") + .args([ + "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", + "fakesink", + ]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{tag}: gst decode: {stderr}"); + } + let _ = fs::remove_file(&path); + } + } +} #[test] fn silk_compares_to_celt_on_speech_at_speech_rates() { let pcm = speech_like(); @@ -1775,8 +2289,8 @@ fn silk_compares_to_celt_on_speech_at_speech_rates() { ); 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" + silk_corr >= celt_corr, + "{tag}: SILK {silk_corr:.4} trails CELT {celt_corr:.4}" ); } } @@ -2019,3 +2533,126 @@ fn hybrid_fb_roundtrip() { ); } } + +fn hybrid_roundtrip_shape( + pcm: &[f32], + channels: usize, + frame: usize, + bps: u32, + bandwidth: Option, +) -> (Vec, Vec>) { + let mut enc = Encoder::new(48000, channels, Application::Voip).unwrap(); + enc.set_bitrate(bps); + enc.set_bandwidth(bandwidth); + let mut dec = Decoder::new(48000, channels).unwrap(); + let mut out = vec![0u8; 1500]; + let mut buf = vec![0f32; 5760 * channels]; + let (mut decoded, mut packets) = (Vec::new(), Vec::new()); + let mut padded = pcm.to_vec(); + padded.resize( + pcm.len().div_ceil(frame * channels) * frame * channels + frame * channels, + 0.0, + ); + for block in padded.chunks(frame * channels) { + let len = enc + .encode_float(block, frame, &mut out) + .expect("hybrid encode"); + let n = dec + .decode_float(&out[..len], &mut buf) + .expect("hybrid decode"); + assert_eq!(n, frame); + assert_eq!(dec.final_range(), enc.final_range(), "range state diverged"); + decoded.extend_from_slice(&buf[..n * channels]); + packets.push(out[..len].to_vec()); + } + (decoded, packets) +} + +#[test] +fn hybrid_shapes_roundtrip() { + for (tag, channels, frame, bps, bandwidth, config, floor) in [ + ( + "mono-swb10", + 1usize, + 480usize, + 24_000u32, + Bandwidth::SuperWide, + 12u8, + 0.75f64, + ), + ("mono-fb10", 1, 480, 32_000, Bandwidth::Full, 14, 0.75), + ( + "stereo-swb20", + 2, + 960, + 48_000, + Bandwidth::SuperWide, + 13, + 0.75, + ), + ("stereo-fb20", 2, 960, 64_000, Bandwidth::Full, 15, 0.75), + ("stereo-fb10", 2, 480, 64_000, Bandwidth::Full, 14, 0.70), + ] { + let pcm = if channels == 1 { + speech_like() + } else { + stereo_speech_pair() + }; + let (decoded, packets) = + hybrid_roundtrip_shape(&pcm, channels, frame, bps, Some(bandwidth)); + let toc = ec_opus::Toc::new(packets[0][0]); + assert_eq!(toc.config, config, "{tag}: TOC config {}", toc.config); + assert_eq!(toc.stereo, channels == 2, "{tag}: TOC stereo flag"); + let mut worst = 1.0f64; + for ch in 0..channels { + let source: Vec = pcm.chunks_exact(channels).map(|f| f[ch]).collect(); + let got: Vec = decoded.chunks_exact(channels).map(|f| f[ch]).collect(); + let (corr, lag) = aligned_corr(&source, &got, 400); + worst = worst.min(corr); + eprintln!("hybrid {tag} ch{ch}: corr {corr:.4} at lag {lag}"); + } + assert!(worst >= floor, "{tag}: worst corr {worst:.4}"); + let total = pcm.len() / channels; + let path = temp_path(&format!("hybrid-{tag}.opus")); + write_ogg_opus( + &path, + &packets, + opus_head(channels, 120, None), + channels, + total, + 120, + ); + if Command::new("ffmpeg").arg("-version").output().is_ok() { + let out = Command::new("ffmpeg") + .args(["-v", "warning", "-c:a", "libopus", "-i"]) + .arg(&path) + .args(["-f", "null", "-"]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}"); + } + if Command::new("gst-launch-1.0") + .arg("--version") + .output() + .is_ok() + { + let location = format!("location={}", path.display()); + let out = Command::new("gst-launch-1.0") + .args([ + "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink", + ]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{tag}: gst decode: {stderr}"); + } + let _ = fs::remove_file(&path); + } + + let speech = stereo_speech_pair(); + let (_, packets) = hybrid_roundtrip_shape(&speech, 2, 960, 64_000, None); + let toc = ec_opus::Toc::new(packets[0][0]); + assert_eq!(toc.mode(), ec_opus::Mode::Hybrid); + assert!(toc.stereo); +}