forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-silk2': SILK 40/60 ms and stereo packets, hybrid mode for SWB/FB mono and stereo, per-channel automatic mode table

Browse files at this commit

a8db269c07760efe6453ea45a839a885bf8ea12cAhmet Kaan GümüşParent: e01bc6f04dded9
crates/ec-opus/src/encoder.rsmodified+246 -67
@@ -1,14 +1,13 @@
1-//! The Opus packet encoder: CELT and mono SILK, 8 to 48 kHz in.1+//! The Opus packet encoder: CELT, SILK and hybrid, 8 to 48 kHz in.
2 //!2 //!
3 //! One [`Encoder`] produces ordinary code-0 Opus packets (RFC 6716 Section 3)3 //! One [`Encoder`] produces ordinary code-0 Opus packets (RFC 6716 Section 3)
4 //! or the self-delimited variant of Appendix B that the multistream framing4 //! or the self-delimited variant of Appendix B that the multistream framing
5 //! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s5 //! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s
6-//! default) picks CELT (TOC configs 16..31, every rate and frame size) or6+//! default) picks CELT (TOC configs 16..31, every rate and frame size), SILK
7-//! SILK (TOC configs 0/1/4/5/8/9, mono NB/MB/WB 10 or 20 ms only —7+//! (TOC configs 0..11, mono NB/MB/WB 10/20/40/60 ms; stereo NB/MB/WB 10/20 ms,
8-//! stereo SILK and SILK at other frame sizes fall back to CELT, documented8+//! with 40/60 ms carried as code-3 packets of 20 ms SILK frames), or Hybrid
9-//! at the fallback site) or Hybrid (TOC configs 13/15, mono SWB/FB 20 ms:9+//! (TOC configs 13/15, mono or stereo SWB/FB 10 or 20 ms: SILK at 16 kHz under
10-//! SILK at 16 kHz under CELT from band 17 up, one range-coded stream;10+//! CELT from band 17 up, one range-coded stream).
11-//! stereo and other frame sizes fall back to CELT).
12 //!11 //!
13 //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and12 //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and
14 //! the coded bandwidth is capped at the input's own Nyquist, so the images13 //! the coded bandwidth is capped at the input's own Nyquist, so the images
@@ -25,10 +24,11 @@ use ec_core::{Error, Result};
25 use crate::celt_enc::CeltEncoder;24 use crate::celt_enc::CeltEncoder;
26 use crate::packet::{Bandwidth, Mode};25 use crate::packet::{Bandwidth, Mode};
27 use crate::range::RangeEncoder;26 use crate::range::RangeEncoder;
28-use crate::silk_enc_write::SilkEncoder;27+use crate::silk_enc_write::{SilkEncoder, SilkStereoEncoder};
29 28
30 /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`).29 /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`).
31 const MAX_FRAME_BYTES: usize = 1275;30 const MAX_FRAME_BYTES: usize = 1275;
31+const MAX_SILK_PACKET_BYTES: usize = 1 + 1 + 2 * 2 + 3 * MAX_FRAME_BYTES;
32 32
33 /// SILK's round-trip algorithmic delay in 48 kHz samples: the analysis33 /// SILK's round-trip algorithmic delay in 48 kHz samples: the analysis
34 /// resampler (`SilkEncoder::delay_samples`) on the way in plus the decoder's34 /// resampler (`SilkEncoder::delay_samples`) on the way in plus the decoder's
@@ -82,9 +82,12 @@ pub struct Encoder {
82 silk_nb: Option<SilkEncoder>,82 silk_nb: Option<SilkEncoder>,
83 silk_mb: Option<SilkEncoder>,83 silk_mb: Option<SilkEncoder>,
84 silk_wb: Option<SilkEncoder>,84 silk_wb: Option<SilkEncoder>,
85- /// Scratch space for the SILK payload, sized once so the steady-state85+ silk_stereo_nb: Option<SilkStereoEncoder>,
86+ silk_stereo_mb: Option<SilkStereoEncoder>,
87+ silk_stereo_wb: Option<SilkStereoEncoder>,
88+ /// Scratch space for the SILK packet payload, sized once so the steady-state
86 /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate.89 /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate.
87- silk_buf: [u8; MAX_FRAME_BYTES + 1],90+ silk_buf: [u8; MAX_SILK_PACKET_BYTES],
88 /// Hybrid: the last [`HYBRID_SILK_DELAY_48K`] samples of SILK-layer input.91 /// Hybrid: the last [`HYBRID_SILK_DELAY_48K`] samples of SILK-layer input.
89 silk_delay: Vec<f32>,92 silk_delay: Vec<f32>,
90 /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so93 /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so
@@ -132,7 +135,10 @@ impl Encoder {
132 silk_nb: None,135 silk_nb: None,
133 silk_mb: None,136 silk_mb: None,
134 silk_wb: None,137 silk_wb: None,
135- silk_buf: [0u8; MAX_FRAME_BYTES + 1],138+ silk_stereo_nb: None,
139+ silk_stereo_mb: None,
140+ silk_stereo_wb: None,
141+ silk_buf: [0u8; MAX_SILK_PACKET_BYTES],
136 silk_delay: Vec::new(),142 silk_delay: Vec::new(),
137 silk_stuff: Vec::new(),143 silk_stuff: Vec::new(),
138 })144 })
@@ -141,7 +147,7 @@ impl Encoder {
141 /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and147 /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and
142 /// `hybrid_choice` make from the application and bitrate; pass `None` to148 /// `hybrid_choice` make from the application and bitrate; pass `None` to
143 /// restore the automatic pick. Requests this encoder cannot honour149 /// restore the automatic pick. Requests this encoder cannot honour
144- /// (stereo SILK/Hybrid, SILK longer than 20 ms, or 10 ms Hybrid) fall back to CELT.150+ /// (10 ms Hybrid) fall back to CELT.
145 pub fn set_mode(&mut self, mode: Option<Mode>) {151 pub fn set_mode(&mut self, mode: Option<Mode>) {
146 self.mode = mode;152 self.mode = mode;
147 }153 }
@@ -160,15 +166,14 @@ impl Encoder {
160 /// channel, native rate) frame: the decoded stream lags the input by166 /// channel, native rate) frame: the decoded stream lags the input by
161 /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate`167 /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate`
162 /// cancels it exactly. CELT: one MDCT overlap, 120 samples at 48 kHz.168 /// cancels it exactly. CELT: one MDCT overlap, 120 samples at 48 kHz.
163- /// SILK (mono, 10 or 20 ms frames, when the application/bitrate or an169+ /// SILK (10, 20, 40 or 60 ms frames, when the application/bitrate or an
164 /// explicit [`Encoder::set_mode`] select it — the same170 /// explicit [`Encoder::set_mode`] select it — the same
165 /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches171 /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches
166 /// on, so this always matches which layer actually codes the frame):172 /// on, so this always matches which layer actually codes the frame):
167 /// [`SILK_LOOK_AHEAD_48K_NB`], [`SILK_LOOK_AHEAD_48K_MB`] or173 /// [`SILK_LOOK_AHEAD_48K_NB`], [`SILK_LOOK_AHEAD_48K_MB`] or
168 /// [`SILK_LOOK_AHEAD_48K_WB`]. Hybrid: CELT's 120, the SILK layer being174 /// [`SILK_LOOK_AHEAD_48K_WB`]. Hybrid: CELT's 120, the SILK layer being
169 /// delayed to meet it ([`HYBRID_SILK_DELAY_48K`]). Any other frame size175 /// delayed to meet it ([`HYBRID_SILK_DELAY_48K`]). Any other frame size
170- /// (or SILK/Hybrid's mono requirement unmet) falls back to CELT here176+ /// falls back to CELT here exactly as `encode_toc_and_payload` does.
171- /// exactly as `encode_toc_and_payload` does.
172 pub fn look_ahead(&self, frame_size: usize) -> usize {177 pub fn look_ahead(&self, frame_size: usize) -> usize {
173 let frame_48k = frame_size * self.upsample;178 let frame_48k = frame_size * self.upsample;
174 if let Some(fs_khz) = self.silk_choice(frame_48k) {179 if let Some(fs_khz) = self.silk_choice(frame_48k) {
@@ -219,6 +224,9 @@ impl Encoder {
219 self.silk_nb = None;224 self.silk_nb = None;
220 self.silk_mb = None;225 self.silk_mb = None;
221 self.silk_wb = None;226 self.silk_wb = None;
227+ self.silk_stereo_nb = None;
228+ self.silk_stereo_mb = None;
229+ self.silk_stereo_wb = None;
222 self.silk_delay.clear();230 self.silk_delay.clear();
223 self.final_range = 0;231 self.final_range = 0;
224 }232 }
@@ -236,47 +244,50 @@ impl Encoder {
236 Some(Mode::Celt) | Some(Mode::Hybrid) => None,244 Some(Mode::Celt) | Some(Mode::Hybrid) => None,
237 Some(Mode::Silk) => Some(forced()),245 Some(Mode::Silk) => Some(forced()),
238 None => {246 None => {
239- if self.application == Application::Voip && self.bitrate < 20_000 {247+ if self.application == Application::Voip {
240- Some(if matches!(self.bandwidth, Some(Bandwidth::Medium)) {248+ let per_channel = self.bitrate / self.channels as u32;
241- 12249+ if per_channel < 20_000 {
242- } else if self.bitrate > 10_000 {250+ return Some(match self.bandwidth {
243- 16251+ Some(Bandwidth::Narrow) => 8,
244- } else {252+ Some(Bandwidth::Medium) => 12,
245- 8253+ Some(_) => 16,
246- })254+ None if per_channel <= 12_000 => 8,
247- } else {255+ None if per_channel <= 16_000 => 12,
248- None256+ None => 16,
257+ });
258+ }
249 }259 }
260+ None
250 }261 }
251 }262 }
252 }263 }
253 264
254 /// `wants_silk` narrowed to what this encoder can actually code as SILK:265 /// `wants_silk` narrowed to what this encoder can actually code as SILK:
255- /// mono, 10 or 20 ms (480 or 960 samples at 48 kHz) frames only. Stereo266+ /// mono 10/20/40/60 ms, stereo 10/20 ms directly, or stereo 40/60 ms as
256- /// SILK and longer SILK packets are future work; both fall back to CELT.267+ /// code-3 packets of 20 ms SILK frames.
257 fn silk_choice(&self, frame_48k: usize) -> Option<usize> {268 fn silk_choice(&self, frame_48k: usize) -> Option<usize> {
258 let fs_khz = self.wants_silk()?;269 let fs_khz = self.wants_silk()?;
259- if self.channels != 1 || !matches!(frame_48k, 480 | 960) {270+ if !matches!(frame_48k, 480 | 960 | 1920 | 2880) {
260 return None;271 return None;
261 }272 }
262 Some(fs_khz)273 Some(fs_khz)
263 }274 }
264 275
265 /// Whether this frame goes out as a hybrid packet, and at which of the two276 /// Whether this frame goes out as a hybrid packet, and at which of the two
266- /// hybrid bandwidths. Automatic: VoIP from 20 kbps (where SILK alone277+ /// hybrid bandwidths. Automatic: VoIP from 20 kbps per coded channel
267- /// stops) to 40 kbps (where CELT alone is the better speech coder too),278+ /// (where SILK alone stops) to 40 kbps per coded channel (where CELT alone
268- /// at the bitrate's own bandwidth (SWB/FB; narrower requests are CELT's).279+ /// is the better speech coder too), at the bitrate's own bandwidth
269- /// Mono 20 ms only — stereo Hybrid (which needs stereo SILK) and the280+ /// (SWB/FB; narrower requests are CELT's). Mono and stereo, 10 or 20 ms.
270- /// 10 ms hybrid configs are not implemented and fall back to CELT.
271 fn hybrid_choice(&self, frame_48k: usize) -> Option<Bandwidth> {281 fn hybrid_choice(&self, frame_48k: usize) -> Option<Bandwidth> {
282+ let per_channel = self.bitrate / self.channels as u32;
272 let wanted = match self.mode {283 let wanted = match self.mode {
273 Some(Mode::Hybrid) => true,284 Some(Mode::Hybrid) => true,
274 Some(_) => false,285 Some(_) => false,
275 None => {286 None => {
276- self.application == Application::Voip && (20_000..40_000).contains(&self.bitrate)287+ self.application == Application::Voip && (20_000..40_000).contains(&per_channel)
277 }288 }
278 };289 };
279- if !wanted || self.channels != 1 || frame_48k != 960 {290+ if !wanted || !matches!(frame_48k, 480 | 960) {
280 return None;291 return None;
281 }292 }
282 let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth());293 let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth());
@@ -339,6 +350,94 @@ impl Encoder {
339 }350 }
340 }351 }
341 352
353+ fn zero_stuff_stereo(pcm: &[f32], frame_size: usize, upsample: usize, out: &mut Vec<f32>) {
354+ if upsample == 1 {
355+ out.clear();
356+ out.extend_from_slice(&pcm[..2 * frame_size]);
357+ return;
358+ }
359+ out.resize(2 * frame_size * upsample, 0.0);
360+ out.fill(0.0);
361+ for i in 0..frame_size {
362+ let dst = 2 * i * upsample;
363+ out[dst] = pcm[2 * i] * upsample as f32;
364+ out[dst + 1] = pcm[2 * i + 1] * upsample as f32;
365+ }
366+ }
367+
368+ fn write_frame_len(out: &mut [u8], pos: &mut usize, len: usize) -> Result<()> {
369+ if len > MAX_FRAME_BYTES {
370+ return Err(Error::corrupt(format!(
371+ "opus encode: frame payload of {len} bytes exceeds {MAX_FRAME_BYTES}"
372+ )));
373+ }
374+ if len < 252 {
375+ out[*pos] = len as u8;
376+ *pos += 1;
377+ } else {
378+ let b0 = 252 + ((len - 252) & 3);
379+ out[*pos] = b0 as u8;
380+ out[*pos + 1] = ((len - b0) / 4) as u8;
381+ *pos += 2;
382+ }
383+ Ok(())
384+ }
385+
386+ fn encode_stereo_silk_multiframe(
387+ &mut self,
388+ fs_khz: usize,
389+ frame_48k: usize,
390+ ) -> Result<(u8, &[u8])> {
391+ let frame_count = frame_48k / 960;
392+ debug_assert!(matches!(frame_count, 2 | 3));
393+ let mut frames = [[0u8; MAX_FRAME_BYTES + 1]; 3];
394+ let mut lens = [0usize; 3];
395+ let toc = {
396+ let enc = match fs_khz {
397+ 8 => self
398+ .silk_stereo_nb
399+ .get_or_insert_with(|| SilkStereoEncoder::new(false)),
400+ 12 => self
401+ .silk_stereo_mb
402+ .get_or_insert_with(SilkStereoEncoder::new_mediumband),
403+ _ => self
404+ .silk_stereo_wb
405+ .get_or_insert_with(|| SilkStereoEncoder::new(true)),
406+ };
407+ enc.set_bitrate(self.bitrate);
408+ for i in 0..frame_count {
409+ let from = i * 2 * 960;
410+ lens[i] = enc.encode_frame_ms(
411+ &self.silk_stuff[from..from + 2 * 960],
412+ &mut frames[i],
413+ 20,
414+ )?;
415+ debug_assert!(i == 0 || frames[i][0] == frames[0][0]);
416+ }
417+ self.final_range = enc.final_range();
418+ frames[0][0] | 0x03
419+ };
420+ let mut pos = 0usize;
421+ self.silk_buf[pos] = 0x80 | frame_count as u8;
422+ pos += 1;
423+ for &len in &lens[..frame_count - 1] {
424+ Self::write_frame_len(&mut self.silk_buf, &mut pos, len - 1)?;
425+ }
426+ for i in 0..frame_count {
427+ let len = lens[i] - 1;
428+ if pos + len > self.silk_buf.len() {
429+ return Err(Error::corrupt(format!(
430+ "opus encode: SILK packet needs {} bytes, buffer holds {}",
431+ pos + len,
432+ self.silk_buf.len()
433+ )));
434+ }
435+ self.silk_buf[pos..pos + len].copy_from_slice(&frames[i][1..lens[i]]);
436+ pos += len;
437+ }
438+ Ok((toc, &self.silk_buf[..pos]))
439+ }
440+
342 /// Picks SILK or CELT for one frame and encodes it, returning the TOC441 /// Picks SILK or CELT for one frame and encodes it, returning the TOC
343 /// byte and the payload bytes (excluding TOC), borrowed from scratch442 /// byte and the payload bytes (excluding TOC), borrowed from scratch
344 /// space owned by `self` — no allocation on the steady-state path.443 /// space owned by `self` — no allocation on the steady-state path.
@@ -352,6 +451,28 @@ impl Encoder {
352 ) -> Result<(u8, &[u8])> {451 ) -> Result<(u8, &[u8])> {
353 let frame_48k = frame_size * self.upsample;452 let frame_48k = frame_size * self.upsample;
354 if let Some(fs_khz) = self.silk_choice(frame_48k) {453 if let Some(fs_khz) = self.silk_choice(frame_48k) {
454+ if self.channels == 2 {
455+ Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);
456+ if frame_48k > 960 {
457+ return self.encode_stereo_silk_multiframe(fs_khz, frame_48k);
458+ }
459+ let enc = match fs_khz {
460+ 8 => self
461+ .silk_stereo_nb
462+ .get_or_insert_with(|| SilkStereoEncoder::new(false)),
463+ 12 => self
464+ .silk_stereo_mb
465+ .get_or_insert_with(SilkStereoEncoder::new_mediumband),
466+ _ => self
467+ .silk_stereo_wb
468+ .get_or_insert_with(|| SilkStereoEncoder::new(true)),
469+ };
470+ enc.set_bitrate(self.bitrate);
471+ let n =
472+ enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf, frame_48k / 48)?;
473+ self.final_range = enc.final_range();
474+ return Ok((self.silk_buf[0], &self.silk_buf[1..n]));
475+ }
355 Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);476 Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);
356 let enc = match fs_khz {477 let enc = match fs_khz {
357 8 => self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)),478 8 => self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)),
@@ -368,12 +489,13 @@ impl Encoder {
368 }489 }
369 if let Some(bandwidth) = self.hybrid_choice(frame_48k) {490 if let Some(bandwidth) = self.hybrid_choice(frame_48k) {
370 let n = self.encode_hybrid(pcm, frame_size, bandwidth, cap)?;491 let n = self.encode_hybrid(pcm, frame_size, bandwidth, cap)?;
371- let config = if bandwidth == Bandwidth::Full {492+ let config = 12
372- 15u8493+ + if bandwidth == Bandwidth::Full { 2u8 } else { 0 }
373- } else {494+ + if frame_48k == 960 { 1 } else { 0 };
374- 13495+ return Ok((
375- };496+ (config << 3) | (u8::from(self.channels == 2) << 2),
376- return Ok((config << 3, &self.range.data()[..n]));497+ &self.range.data()[..n],
498+ ));
377 }499 }
378 let (toc, frame_48k, end) = self.toc(frame_size)?;500 let (toc, frame_48k, end) = self.toc(frame_size)?;
379 let n = self.encode_frame(pcm, frame_48k, end, cap)?;501 let n = self.encode_frame(pcm, frame_48k, end, cap)?;
@@ -512,9 +634,9 @@ impl Encoder {
512 Ok(1 + len_bytes + n)634 Ok(1 + len_bytes + n)
513 }635 }
514 636
515- /// One hybrid frame (mono, 20 ms, `bandwidth` SWB or FB) into the637+ /// One hybrid frame (10 or 20 ms, mono or stereo, `bandwidth` SWB or FB)
516- /// internal range coder, returning its byte length: the SILK layer's638+ /// into the internal range coder, returning its byte length: the SILK
517- /// symbols (WB, 16 kHz internal, fed the input delayed by639+ /// layer's symbols (WB, 16 kHz internal, fed the input delayed by
518 /// [`HYBRID_SILK_DELAY_48K`]), the no-redundancy flag under the decoder's640 /// [`HYBRID_SILK_DELAY_48K`]), the no-redundancy flag under the decoder's
519 /// exact presence rule, then the CELT layer from band 17 in the same641 /// exact presence rule, then the CELT layer from band 17 in the same
520 /// coder. CBR: the packet is the bitrate's size unless SILK alone needs642 /// coder. CBR: the packet is the bitrate's size unless SILK alone needs
@@ -527,25 +649,45 @@ impl Encoder {
527 cap: usize,649 cap: usize,
528 ) -> Result<usize> {650 ) -> Result<usize> {
529 let cap = cap.min(MAX_FRAME_BYTES);651 let cap = cap.min(MAX_FRAME_BYTES);
530- let budget = ((self.bitrate as u64 * 960 + 4 * 48000) / (8 * 48000)) as usize;652+ let frame_48k = frame_size * self.upsample;
653+ let frame_ms = frame_48k / 48;
654+ let budget = ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize;
531 let budget = budget.saturating_sub(1).clamp(2, cap);655 let budget = budget.saturating_sub(1).clamp(2, cap);
532 if cap < HYBRID_CELT_MIN_BYTES + 2 {656 if cap < HYBRID_CELT_MIN_BYTES + 2 {
533 return Err(Error::corrupt(657 return Err(Error::corrupt(
534 "opus encode: output buffer smaller than the minimum hybrid packet",658 "opus encode: output buffer smaller than the minimum hybrid packet",
535 ));659 ));
536 }660 }
537- Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);661+ if self.channels == 2 {
538- let d = HYBRID_SILK_DELAY_48K;662+ Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);
539- self.silk_delay.resize(d, 0.0);663+ } else {
540- let mut delayed = Vec::with_capacity(960);664+ Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);
665+ }
666+ let d = HYBRID_SILK_DELAY_48K * self.channels;
667+ if self.silk_delay.len() != d {
668+ self.silk_delay.clear();
669+ self.silk_delay.resize(d, 0.0);
670+ }
671+ let silk_len = frame_48k * self.channels;
672+ let mut delayed = Vec::with_capacity(silk_len);
541 delayed.extend_from_slice(&self.silk_delay);673 delayed.extend_from_slice(&self.silk_delay);
542- delayed.extend_from_slice(&self.silk_stuff[..960 - d]);674+ delayed.extend_from_slice(&self.silk_stuff[..silk_len - d]);
543- self.silk_delay.copy_from_slice(&self.silk_stuff[960 - d..]);675+ self.silk_delay
676+ .copy_from_slice(&self.silk_stuff[silk_len - d..silk_len]);
544 677
545 self.range.reset(cap);678 self.range.reset(cap);
546- let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true));679+ let silk_rate = Self::hybrid_silk_rate(self.bitrate, bandwidth);
547- silk.set_bitrate(Self::hybrid_silk_rate(self.bitrate, bandwidth));680+ if self.channels == 2 {
548- silk.encode_hybrid(&delayed, &mut self.range)?;681+ let silk = self
682+ .silk_stereo_wb
683+ .get_or_insert_with(|| SilkStereoEncoder::new(true));
684+ silk.set_bitrate(silk_rate);
685+ silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;
686+ } else {
687+ let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true));
688+ silk.set_bitrate(silk_rate);
689+ silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;
690+ }
549 let silk_bytes = (self.range.tell() as usize).div_ceil(8);691 let silk_bytes = (self.range.tell() as usize).div_ceil(8);
550 let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap);692 let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap);
551 self.range.shrink(budget);693 self.range.shrink(budget);
@@ -553,15 +695,27 @@ impl Encoder {
553 if self.range.tell() as usize + 17 + 20 <= 8 * budget {695 if self.range.tell() as usize + 17 + 20 <= 8 * budget {
554 self.range.enc_bit_logp(false, 12);696 self.range.enc_bit_logp(false, 12);
555 }697 }
556- // CELT sees the same input as SILK: start band 17 alone keeps it off698+ let n = self.celt.encode(
557- // the low band (a one-pole ~6 kHz high-pass here measured identical699+ &mut self.range,
558- // full-band correlation, so there is none).700+ pcm,
559- let n = self701+ frame_48k,
560- .celt702+ 17,
561- .encode(&mut self.range, pcm, 960, 17, bandwidth.celt_end_band(), 0)?;703+ bandwidth.celt_end_band(),
704+ 0,
705+ )?;
562 self.final_range = self.range.range();706 self.final_range = self.range.range();
563 let payload = &self.range.data()[..n];707 let payload = &self.range.data()[..n];
564- self.silk_wb.as_mut().unwrap().replay(payload)?;708+ if self.channels == 2 {
709+ self.silk_stereo_wb
710+ .as_mut()
711+ .unwrap()
712+ .replay_hybrid(payload, frame_ms)?;
713+ } else {
714+ self.silk_wb
715+ .as_mut()
716+ .unwrap()
717+ .replay_hybrid(payload, frame_ms)?;
718+ }
565 Ok(n)719 Ok(n)
566 }720 }
567 721
@@ -626,10 +780,10 @@ mod tests {
626 assert_eq!(e.look_ahead(960), 60);780 assert_eq!(e.look_ahead(960), 60);
627 }781 }
628 782
629- /// `look_ahead` must use the same mono/10-or-20 ms-frame predicate783+ /// `look_ahead` must use the same 10-or-20 ms-frame predicate dispatch
630- /// dispatch does (`silk_choice`/`hybrid_choice`), not just `wants_silk`:784+ /// does (`silk_choice`/`hybrid_choice`), not just `wants_silk`: 2.5/5 ms
631- /// 2.5/5 ms frames and stereo still code as CELT, while mono 10 ms785+ /// frames still code as CELT, while 10/20 ms speech follows SILK and
632- /// speech follows SILK.786+ /// hybrid follows CELT's overlap.
633 #[test]787 #[test]
634 fn look_ahead_matches_the_frame_size_dispatch_actually_uses() {788 fn look_ahead_matches_the_frame_size_dispatch_actually_uses() {
635 let mut e = Encoder::new(48000, 1, Application::Voip).unwrap();789 let mut e = Encoder::new(48000, 1, Application::Voip).unwrap();
@@ -639,13 +793,38 @@ mod tests {
639 assert_eq!(e.look_ahead(960), 58, "20ms NB SILK");793 assert_eq!(e.look_ahead(960), 58, "20ms NB SILK");
640 794
641 e.set_bitrate(16000);795 e.set_bitrate(16000);
642- assert_eq!(e.look_ahead(960), 50, "20ms WB SILK");796+ assert_eq!(e.look_ahead(960), 54, "20ms MB SILK");
643 797
644 e.set_bitrate(32000);798 e.set_bitrate(32000);
645 assert_eq!(e.look_ahead(960), 120, "20ms hybrid, CELT's overlap");799 assert_eq!(e.look_ahead(960), 120, "20ms hybrid, CELT's overlap");
646 800
647 let mut e = Encoder::new(48000, 2, Application::Voip).unwrap();801 let mut e = Encoder::new(48000, 2, Application::Voip).unwrap();
648 e.set_bitrate(8000);802 e.set_bitrate(8000);
649- assert_eq!(e.look_ahead(960), 120, "stereo never codes as SILK/Hybrid");803+ assert_eq!(e.look_ahead(960), 58, "stereo 20ms NB SILK");
804+ e.set_bitrate(64_000);
805+ assert_eq!(e.look_ahead(960), 120, "stereo 20ms hybrid");
806+ }
807+
808+ #[test]
809+ fn voip_auto_mode_is_monotonic_per_channel() {
810+ for channels in [1usize, 2] {
811+ let mut e = Encoder::new(48000, channels, Application::Voip).unwrap();
812+ let mut last = 0u8;
813+ for per_channel in 500..=45_000u32 {
814+ e.set_bitrate(per_channel * channels as u32);
815+ let class = if e.silk_choice(960).is_some() {
816+ 0
817+ } else if e.hybrid_choice(960).is_some() {
818+ 1
819+ } else {
820+ 2
821+ };
822+ assert!(
823+ class >= last,
824+ "{channels}ch {per_channel} bps/channel regressed from {last} to {class}"
825+ );
826+ last = class;
827+ }
828+ }
650 }829 }
651 }830 }
crates/ec-opus/src/lib.rsmodified+1 -1
@@ -81,7 +81,7 @@ pub use multistream_enc::MultistreamEncoder;
81 pub use packet::{Bandwidth, Mode, Packet, Toc};81 pub use packet::{Bandwidth, Mode, Packet, Toc};
82 pub use range::{RangeDecoder, RangeEncoder};82 pub use range::{RangeDecoder, RangeEncoder};
83 pub use silk::SilkDecoder;83 pub use silk::SilkDecoder;
84-pub use silk_enc_write::SilkEncoder;84+pub use silk_enc_write::{SilkEncoder, SilkStereoEncoder};
85 85
86 use ec_core::{Error, Result};86 use ec_core::{Error, Result};
87 87
crates/ec-opus/src/silk_enc_write.rsmodified+506 -129
@@ -1,5 +1,5 @@
1 //! SILK payload writer (subtask D2a): turns the analysis in [`crate::silk_enc`]1 //! SILK payload writer (subtask D2a): turns the analysis in [`crate::silk_enc`]
2-//! into a decodable mono SILK packet, NB (8 kHz), MB (12 kHz) or WB (16 kHz).2+//! into decodable SILK packets, NB (8 kHz), MB (12 kHz) or WB (16 kHz).
3 //!3 //!
4 //! Symbol order is exactly `silk::decode()`'s, and every decision is made4 //! Symbol order is exactly `silk::decode()`'s, and every decision is made
5 //! against the decoder's own tables and reconstruction functions. The5 //! against the decoder's own tables and reconstruction functions. The
@@ -12,8 +12,7 @@
12 //! output error is fed back through short-term (bandwidth-expanded LPC),12 //! output error is fed back through short-term (bandwidth-expanded LPC),
13 //! harmonic and tilt shaping filters so the noise hides under the signal's13 //! harmonic and tilt shaping filters so the noise hides under the signal's
14 //! own spectrum, and a gain-offset rate loop sizes each packet against14 //! own spectrum, and a gain-offset rate loop sizes each packet against
15-//! [`SilkEncoder::set_bitrate`]. 40/60 ms packets and stereo are not15+//! [`SilkEncoder::set_bitrate`].
16-//! written yet.
17 16
18 // Same idiom as silk.rs: index loops mirror the decoder's position arithmetic.17 // Same idiom as silk.rs: index loops mirror the decoder's position arithmetic.
19 #![allow(clippy::needless_range_loop)]18 #![allow(clippy::needless_range_loop)]
@@ -27,7 +26,7 @@ use crate::silk::{
27 nlsf2a, silk_rand,26 nlsf2a, silk_rand,
28 };27 };
29 use crate::silk_enc::{28 use crate::silk_enc::{
30- Resampler48, Vad, estimate_pitch, lpc_analyze, quantize_gains, quantize_nlsf,29+ NlsfQuant, Resampler48, Vad, estimate_pitch, lpc_analyze, quantize_gains, quantize_nlsf,
31 };30 };
32 31
33 const SHELL_LEN: usize = 16;32 const SHELL_LEN: usize = 16;
@@ -39,7 +38,7 @@ const LEVEL_ADJUST: f32 = 80.0 / 1024.0;
39 /// with 16 such pulses in one block.38 /// with 16 such pulses in one block.
40 const MAX_PULSE: i32 = 1023;39 const MAX_PULSE: i32 = 1023;
41 40
42-/// A mono, 10 or 20 ms, NB/MB/WB SILK encoder.41+/// A mono, 10/20/40/60 ms, NB/MB/WB SILK encoder.
43 #[derive(Clone, Debug)]42 #[derive(Clone, Debug)]
44 pub struct SilkEncoder {43 pub struct SilkEncoder {
45 fs_khz: usize,44 fs_khz: usize,
@@ -76,7 +75,8 @@ const GAIN_STEP: f32 = 1.1702;
76 const RESERVOIR_FRAMES: f32 = 4.0;75 const RESERVOIR_FRAMES: f32 = 4.0;
77 /// Rate penalty per unit pulse magnitude in the quantiser's squared-error76 /// Rate penalty per unit pulse magnitude in the quantiser's squared-error
78 /// cost: a dead zone that lets the rate loop keep finer gains for the same77 /// cost: a dead zone that lets the rate loop keep finer gains for the same
79-/// bits (swept 0..2.5 on speech-like content; 1.5 maximised correlation).78+/// bits. NB 20 ms speech wants a smaller dead zone; 10 ms WB needs a
79+/// slightly smaller one than the 10 ms NB/MB rows to keep upper-band pulses.
80 const PULSE_LAMBDA: f32 = 1.5;80 const PULSE_LAMBDA: f32 = 1.5;
81 81
82 impl SilkEncoder {82 impl SilkEncoder {
@@ -128,6 +128,10 @@ impl SilkEncoder {
128 self.target_bps = Some(bps);128 self.target_bps = Some(bps);
129 }129 }
130 130
131+ fn reset_state(&mut self) {
132+ *self = Self::with_fs_khz(self.fs_khz);
133+ }
134+
131 /// Algorithmic delay in 48 kHz samples: the analysis resampler only135 /// Algorithmic delay in 48 kHz samples: the analysis resampler only
132 /// (the decoder adds its own resampler delay on the way back up).136 /// (the decoder adds its own resampler delay on the way back up).
133 pub fn delay_samples(&self) -> usize {137 pub fn delay_samples(&self) -> usize {
@@ -140,27 +144,70 @@ impl SilkEncoder {
140 self.encode_frame_ms(pcm48, out, 20)144 self.encode_frame_ms(pcm48, out, 20)
141 }145 }
142 146
143- /// Encodes 10 or 20 ms of mono 48 kHz samples as one code-0 packet in147+ /// Encodes 10, 20, 40 or 60 ms of mono 48 kHz samples as one code-0
144- /// `out`, returning its length.148+ /// packet in `out`, returning its length.
145 pub fn encode_frame_ms(149 pub fn encode_frame_ms(
146 &mut self,150 &mut self,
147 pcm48: &[f32],151 pcm48: &[f32],
148 out: &mut [u8],152 out: &mut [u8],
149 frame_ms: usize,153 frame_ms: usize,
150 ) -> Result<usize> {154 ) -> Result<usize> {
151- let Trial { bytes, range, .. } = self.encode_inner(pcm48, frame_ms, None)?;155+ let frames_per_packet = match frame_ms {
152- let len = bytes.len();156+ 10 | 20 => 1usize,
153- self.final_range = range;157+ 40 => 2,
154- let duration = match frame_ms {158+ 60 => 3,
155- 10 => 0u8,
156- 20 => 1,
157 _ => {159 _ => {
158 return Err(ec_core::Error::unsupported(160 return Err(ec_core::Error::unsupported(
159 format!("silk encode frame of {frame_ms} ms"),161 format!("silk encode frame of {frame_ms} ms"),
160- "SILK encoder writes 10 or 20 ms packets",162+ "SILK encoder writes 10, 20, 40 or 60 ms packets",
161 ));163 ));
162 }164 }
163 };165 };
166+ assert_eq!(
167+ pcm48.len(),
168+ 48 * frame_ms,
169+ "SilkEncoder input is 48 kHz mono"
170+ );
171+ let mut frames = Vec::with_capacity(frames_per_packet);
172+ let sub_ms = if frame_ms == 10 { 10 } else { 20 };
173+ let mut prev_signal_type = 0;
174+ for i in 0..frames_per_packet {
175+ let from = i * sub_ms * 48;
176+ let to = from + sub_ms * 48;
177+ let conditional = i > 0;
178+ let trial = self.encode_inner(
179+ &pcm48[from..to],
180+ sub_ms,
181+ None,
182+ conditional,
183+ prev_signal_type,
184+ frames_per_packet == 1,
185+ )?;
186+ prev_signal_type = trial.signal_type;
187+ frames.push(trial);
188+ }
189+ if frames.iter().any(|frame| frame.voiced) {
190+ self.voiced_frames += 1;
191+ }
192+ self.range.reset(1275);
193+ let refs: Vec<&Trial> = frames.iter().collect();
194+ write_packet_header(&mut self.range, &refs);
195+ prev_signal_type = 0;
196+ for (i, frame) in frames.iter().enumerate() {
197+ write_frame_data(&mut self.range, frame, i > 0, prev_signal_type);
198+ prev_signal_type = frame.signal_type;
199+ }
200+ self.range.done();
201+ debug_assert!(!self.range.error());
202+ let len = self.range.range_bytes();
203+ self.final_range = self.range.range();
204+ let duration = match frame_ms {
205+ 10 => 0u8,
206+ 20 => 1,
207+ 40 => 2,
208+ 60 => 3,
209+ _ => unreachable!(),
210+ };
164 let base = match self.fs_khz {211 let base = match self.fs_khz {
165 8 => 0u8,212 8 => 0u8,
166 12 => 4,213 12 => 4,
@@ -175,40 +222,58 @@ impl SilkEncoder {
175 )));222 )));
176 }223 }
177 out[0] = toc;224 out[0] = toc;
178- out[1..1 + len].copy_from_slice(&bytes);225+ out[1..1 + len].copy_from_slice(&self.range.data()[..len]);
179 self.replay_ms(&out[1..1 + len], frame_ms)?;226 self.replay_ms(&out[1..1 + len], frame_ms)?;
180 debug_assert_eq!(self.mirror_range, self.final_range);227 debug_assert_eq!(self.mirror_range, self.final_range);
181 Ok(1 + len)228 Ok(1 + len)
182 }229 }
183 230
184- /// The SILK layer of a hybrid packet: codes 960 mono 48 kHz samples into231+ /// The SILK layer of a hybrid packet: codes one mono 48 kHz frame into
185 /// `enc`, the packet's shared range coder (SILK symbols first; the CELT232 /// `enc`, the packet's shared range coder (SILK symbols first; the CELT
186 /// layer continues in the same coder), without finishing it. The caller233 /// layer continues in the same coder), without finishing it. The caller
187- /// must [`SilkEncoder::replay`] the finished payload so this encoder's234+ /// must [`SilkEncoder::replay_hybrid`] the finished payload so this
188- /// decoder mirror advances.235+ /// encoder's decoder mirror advances.
189- pub fn encode_hybrid(&mut self, pcm48: &[f32], enc: &mut RangeEncoder) -> Result<()> {236+ pub fn encode_hybrid_ms(
190- self.encode_inner(pcm48, 20, Some(enc)).map(|_| ())237+ &mut self,
238+ pcm48: &[f32],
239+ enc: &mut RangeEncoder,
240+ frame_ms: usize,
241+ ) -> Result<()> {
242+ let trial = self.encode_inner(pcm48, frame_ms, Some(enc), false, 0, true)?;
243+ self.voiced_frames += usize::from(trial.voiced);
244+ Ok(())
191 }245 }
192 246
193- /// Decodes `payload` (TOC stripped) through the mirror decoder so the next247+ /// Decodes a finished hybrid payload (TOC stripped) through the mirror
194- /// frame predicts from the decoder's state; [`SilkEncoder::encode_frame`]248+ /// decoder so the next frame predicts from the decoder's state.
195- /// does this itself, [`SilkEncoder::encode_hybrid`] callers do it once249+ pub fn replay_hybrid(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
196- /// the packet is complete.250+ self.replay_ms(payload, frame_ms)
197- pub fn replay(&mut self, payload: &[u8]) -> Result<()> {
198- self.replay_ms(payload, 20)
199 }251 }
200 252
201 fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {253 fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
202 let fs = self.fs_khz;254 let fs = self.fs_khz;
203 let mut dec = RangeDecoder::new(payload);255 let mut dec = RangeDecoder::new(payload);
204- self.mirror.decode(256+ let total = frame_ms * fs;
205- &mut dec,257+ if self.mirror_out.len() < total {
206- &mut self.mirror_out,258+ self.mirror_out.resize(total, 0);
207- frame_ms,259+ }
208- fs as u32 * 1000,260+ let mut done = 0usize;
209- 1,261+ let mut first = true;
210- true,262+ while done < total {
211- )?;263+ let n = self.mirror.decode(
264+ &mut dec,
265+ &mut self.mirror_out[done..],
266+ frame_ms,
267+ fs as u32 * 1000,
268+ 1,
269+ first,
270+ )?;
271+ if n == 0 {
272+ break;
273+ }
274+ done += n;
275+ first = false;
276+ }
212 self.mirror_range = dec.range();277 self.mirror_range = dec.range();
213 Ok(())278 Ok(())
214 }279 }
@@ -222,6 +287,9 @@ impl SilkEncoder {
222 pcm48: &[f32],287 pcm48: &[f32],
223 frame_ms: usize,288 frame_ms: usize,
224 shared: Option<&mut RangeEncoder>,289 shared: Option<&mut RangeEncoder>,
290+ conditional: bool,
291+ prev_signal_type: i32,
292+ single_frame_packet: bool,
225 ) -> Result<Trial> {293 ) -> Result<Trial> {
226 assert!(294 assert!(
227 matches!(frame_ms, 10 | 20),295 matches!(frame_ms, 10 | 20),
@@ -419,6 +487,11 @@ impl SilkEncoder {
419 // vector that best predicts the residual from the *reconstructed*487 // vector that best predicts the residual from the *reconstructed*
420 // history, then quantise sample by sample with the shaped output error488 // history, then quantise sample by sample with the shaped output error
421 // fed back into the target, under the decoder's seed-driven sign flips.489 // fed back into the target, under the decoder's seed-driven sign flips.
490+ let pulse_lambda = match (single_frame_packet, frame_ms, fs) {
491+ (true, 20, 8) => 1.25,
492+ (_, 10, 16) => 1.45,
493+ _ => PULSE_LAMBDA,
494+ };
422 let run = |per: usize, gains_q16: &[i32; MAX_NB_SUBFR]| -> Run {495 let run = |per: usize, gains_q16: &[i32; MAX_NB_SUBFR]| -> Run {
423 let cbk = codebook(per);496 let cbk = codebook(per);
424 let mut r = r.clone();497 let mut r = r.clone();
@@ -486,7 +559,7 @@ impl SilkEncoder {
486 .filter(|p| p.abs() <= MAX_PULSE)559 .filter(|p| p.abs() <= MAX_PULSE)
487 .min_by(|&a, &b| {560 .min_by(|&a, &b| {
488 let cost = |p: i32| {561 let cost = |p: i32| {
489- (recon(p) - target).powi(2) + PULSE_LAMBDA * p.abs() as f32562+ (recon(p) - target).powi(2) + pulse_lambda * p.abs() as f32
490 };563 };
491 cost(a).partial_cmp(&cost(b)).unwrap()564 cost(a).partial_cmp(&cost(b)).unwrap()
492 })565 })
@@ -516,85 +589,7 @@ impl SilkEncoder {
516 }589 }
517 };590 };
518 591
519- // Bitstream writer, in decode()'s order; shared by the sizing trials592+ let fs = self.fs_khz;
520- // and the hybrid path's shared coder.
521- let write = |enc: &mut RangeEncoder, gain_idx: &[i8], per_index: usize, run: &Run| {
522- enc.enc_bit_logp(vad_flag, 1); // VAD flag
523- enc.enc_bit_logp(false, 1); // LBRR flag
524- // Frame type.
525- if vad_flag {
526- enc.enc_icdf(
527- ((signal_type << 1) | quant_offset_type as i32) as usize - 2,
528- &TYPE_OFFSET_VAD_ICDF,
529- 8,
530- );
531- } else {
532- enc.enc_icdf(quant_offset_type, &TYPE_OFFSET_NO_VAD_ICDF, 8);
533- }
534- // Gains: one frame per packet, so always independently coded.
535- enc.enc_icdf(
536- (gain_idx[0] as usize) >> 3,
537- &GAIN_ICDF[signal_type as usize],
538- 8,
539- );
540- enc.enc_icdf((gain_idx[0] as usize) & 7, &UNIFORM8_ICDF, 8);
541- for k in 1..nb_subfr {
542- enc.enc_icdf(gain_idx[k] as usize, &DELTA_GAIN_ICDF, 8);
543- }
544- // NLSFs.
545- let cb = nlsf_cb(wb);
546- let stage1_icdf = &cb.cb1_icdf[(signal_type as usize >> 1) * cb.n_vectors..];
547- enc.enc_icdf(nq.indices[0] as usize, stage1_icdf, 8);
548- let (ec_ix, _) = crate::silk::nlsf_unpack(cb, nq.indices[0] as usize);
549- for i in 0..order {
550- let q = nq.indices[i + 1] as i32;
551- let icdf = &cb.ec_icdf[ec_ix[i] as usize..];
552- if q <= -4 {
553- enc.enc_icdf(0, icdf, 8);
554- enc.enc_icdf((-4 - q) as usize, &NLSF_EXT_ICDF, 8);
555- } else if q >= 4 {
556- enc.enc_icdf(8, icdf, 8);
557- enc.enc_icdf((q - 4) as usize, &NLSF_EXT_ICDF, 8);
558- } else {
559- enc.enc_icdf((q + 4) as usize, icdf, 8);
560- }
561- }
562- if nb_subfr == MAX_NB_SUBFR {
563- enc.enc_icdf(nq.interp_index as usize, &NLSF_INTERPOLATION_FACTOR_ICDF, 8);
564- }
565- // Pitch + LTP. (One frame per packet: the decoder only takes the
566- // lag-delta code path for the 2nd+ frame of a packet, so the
567- // absolute lag is always coded here.)
568- if voiced {
569- let half = fs as i32 >> 1;
570- enc.enc_icdf((lag_index / half) as usize, &PITCH_LAG_ICDF, 8);
571- let low_icdf: &[u8] = match fs {
572- 16 => &UNIFORM8_ICDF,
573- 12 => &UNIFORM6_ICDF,
574- _ => &UNIFORM4_ICDF,
575- };
576- enc.enc_icdf((lag_index % half) as usize, low_icdf, 8);
577- let contour_icdf: &[u8] = match (fs, nb_subfr) {
578- (8, 4) => &PITCH_CONTOUR_NB_ICDF,
579- (8, _) => &PITCH_CONTOUR_10_MS_NB_ICDF,
580- (_, 4) => &PITCH_CONTOUR_ICDF,
581- _ => &PITCH_CONTOUR_10_MS_ICDF,
582- };
583- enc.enc_icdf(contour_index as usize, contour_icdf, 8);
584- enc.enc_icdf(per_index, &LTP_PER_INDEX_ICDF, 8);
585- let gain_icdf: &[u8] = match per_index {
586- 0 => &LTP_GAIN_ICDF_0,
587- 1 => &LTP_GAIN_ICDF_1,
588- _ => &LTP_GAIN_ICDF_2,
589- };
590- for k in 0..nb_subfr {
591- enc.enc_icdf(run.ltp_index[k], gain_icdf, 8);
592- }
593- enc.enc_icdf(ltp_scale_index, &LTPSCALE_ICDF, 8);
594- }
595- enc.enc_icdf(seed_index as usize, &UNIFORM4_ICDF, 8);
596- encode_pulses(enc, &run.pulses, signal_type, quant_offset_type as i32);
597- };
598 // One full trial at a common gain offset (in quantiser steps): returns593 // One full trial at a common gain offset (in quantiser steps): returns
599 // the coded packet body so the rate loop can read its exact size.594 // the coded packet body so the rate loop can read its exact size.
600 let candidates: Vec<usize> = if voiced { vec![0, 1, 2] } else { vec![0] };595 let candidates: Vec<usize> = if voiced { vec![0, 1, 2] } else { vec![0] };
@@ -605,28 +600,45 @@ impl SilkEncoder {
605 *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32;600 *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32;
606 }601 }
607 let mut prev_gain_index = self.prev_gain_index;602 let mut prev_gain_index = self.prev_gain_index;
608- let (gain_idx, gains_q16) = quantize_gains(&t, &mut prev_gain_index, false, nb_subfr);603+ let (gain_idx, gains_q16) =
604+ quantize_gains(&t, &mut prev_gain_index, conditional, nb_subfr);
609 let (per_index, run) = candidates605 let (per_index, run) = candidates
610 .iter()606 .iter()
611 .map(|&per| (per, run(per, &gains_q16)))607 .map(|&per| (per, run(per, &gains_q16)))
612 .min_by(|a, b| a.1.err.partial_cmp(&b.1.err).unwrap())608 .min_by(|a, b| a.1.err.partial_cmp(&b.1.err).unwrap())
613 .unwrap();609 .unwrap();
614 610
615- // --- Bitstream, in decode()'s order. ---611+ let mut trial = Trial {
612+ bytes: Vec::new(),
613+ range: 0,
614+ prev_gain_index,
615+ gain_idx,
616+ per_index,
617+ run,
618+ vad_flag,
619+ signal_type,
620+ quant_offset_type,
621+ wb,
622+ order,
623+ nb_subfr,
624+ fs,
625+ lag_index,
626+ contour_index,
627+ voiced,
628+ ltp_scale_index,
629+ nq: nq.clone(),
630+ seed_index,
631+ };
616 let enc = &mut self.range;632 let enc = &mut self.range;
617 enc.reset(1275);633 enc.reset(1275);
618- write(enc, &gain_idx, per_index, &run);634+ write_packet_header(enc, &[&trial]);
635+ write_frame_data(enc, &trial, conditional, prev_signal_type);
619 enc.done();636 enc.done();
620 debug_assert!(!enc.error());637 debug_assert!(!enc.error());
621 let len = enc.range_bytes();638 let len = enc.range_bytes();
622- Trial {639+ trial.bytes = enc.data()[..len].to_vec();
623- bytes: enc.data()[..len].to_vec(),640+ trial.range = enc.range();
624- range: enc.range(),641+ trial
625- prev_gain_index,
626- gain_idx,
627- per_index,
628- run,
629- }
630 };642 };
631 643
632 // Rate control: a common gain offset moves every subframe's pulse644 // Rate control: a common gain offset moves every subframe's pulse
@@ -664,10 +676,11 @@ impl SilkEncoder {
664 );676 );
665 }677 }
666 if let Some(enc) = shared {678 if let Some(enc) = shared {
667- write(enc, &best.gain_idx, best.per_index, &best.run);679+ let trial_ref = &best;
680+ write_packet_header(enc, &[trial_ref]);
681+ write_frame_data(enc, trial_ref, conditional, prev_signal_type);
668 }682 }
669 self.prev_gain_index = best.prev_gain_index;683 self.prev_gain_index = best.prev_gain_index;
670- self.voiced_frames += usize::from(voiced);
671 self.shape_d.copy_from_slice(&best.run.d[n..]);684 self.shape_d.copy_from_slice(&best.run.d[n..]);
672 self.shape_u.copy_from_slice(&best.run.u[n..]);685 self.shape_u.copy_from_slice(&best.run.u[n..]);
673 self.shape_gq.copy_from_slice(&best.run.gq[n..]);686 self.shape_gq.copy_from_slice(&best.run.gq[n..]);
@@ -675,6 +688,258 @@ impl SilkEncoder {
675 }688 }
676 }689 }
677 690
691+/// A stereo, 10 or 20 ms, NB/MB/WB SILK encoder.
692+#[derive(Clone, Debug)]
693+pub struct SilkStereoEncoder {
694+ fs_khz: usize,
695+ mid: SilkEncoder,
696+ side: SilkEncoder,
697+ range: RangeEncoder,
698+ mirror: SilkDecoder,
699+ final_range: u32,
700+ mirror_range: u32,
701+ mirror_out: Vec<i16>,
702+ target_bps: Option<u32>,
703+ prev_mid_only: bool,
704+ voiced_frames: usize,
705+}
706+
707+impl SilkStereoEncoder {
708+ /// Narrowband or wideband stereo encoder.
709+ pub fn new(wideband: bool) -> SilkStereoEncoder {
710+ Self::with_fs_khz(if wideband { 16 } else { 8 })
711+ }
712+
713+ /// Mediumband stereo encoder.
714+ pub fn new_mediumband() -> SilkStereoEncoder {
715+ Self::with_fs_khz(12)
716+ }
717+
718+ fn with_fs_khz(fs_khz: usize) -> SilkStereoEncoder {
719+ SilkStereoEncoder {
720+ fs_khz,
721+ mid: SilkEncoder::with_fs_khz(fs_khz),
722+ side: SilkEncoder::with_fs_khz(fs_khz),
723+ range: RangeEncoder::new(),
724+ mirror: SilkDecoder::new(fs_khz as u32 * 1000, 2),
725+ final_range: 0,
726+ mirror_range: 0,
727+ mirror_out: vec![0; 2 * 20 * fs_khz],
728+ target_bps: None,
729+ prev_mid_only: false,
730+ voiced_frames: 0,
731+ }
732+ }
733+
734+ /// The range coder state after the last packet.
735+ pub fn final_range(&self) -> u32 {
736+ self.final_range
737+ }
738+
739+ /// Packets so far coded with a long-term predictor in either channel.
740+ pub fn voiced_frames(&self) -> usize {
741+ self.voiced_frames
742+ }
743+
744+ /// Target bit rate in bits per second for the whole stereo packet.
745+ pub fn set_bitrate(&mut self, bps: u32) {
746+ self.target_bps = Some(bps);
747+ let per_channel = (bps / 2).max(500);
748+ self.mid.set_bitrate(per_channel);
749+ self.side.set_bitrate(per_channel);
750+ }
751+
752+ /// Algorithmic delay in 48 kHz samples.
753+ pub fn delay_samples(&self) -> usize {
754+ self.mid.delay_samples()
755+ }
756+
757+ /// The SILK layer of a hybrid packet: codes one interleaved stereo 48 kHz
758+ /// frame into the packet's shared range coder without finishing it.
759+ pub fn encode_hybrid_ms(
760+ &mut self,
761+ pcm48: &[f32],
762+ enc: &mut RangeEncoder,
763+ frame_ms: usize,
764+ ) -> Result<()> {
765+ assert!(
766+ matches!(frame_ms, 10 | 20),
767+ "SilkStereoEncoder codes 10 or 20 ms stereo frames"
768+ );
769+ assert_eq!(
770+ pcm48.len(),
771+ 2 * 48 * frame_ms,
772+ "SilkStereoEncoder input is 48 kHz stereo"
773+ );
774+ if self.prev_mid_only {
775+ self.side.reset_state();
776+ if let Some(bps) = self.target_bps {
777+ self.side.set_bitrate((bps / 2).max(500));
778+ }
779+ }
780+ let samples = 48 * frame_ms;
781+ let mut mid = Vec::with_capacity(samples);
782+ let mut side = Vec::with_capacity(samples);
783+ let mut side_energy = 0.0f32;
784+ for lr in pcm48.chunks_exact(2) {
785+ let m = 0.5 * (lr[0] + lr[1]);
786+ let s = 0.5 * (lr[0] - lr[1]);
787+ mid.push(m);
788+ side.push(s);
789+ side_energy += s * s;
790+ }
791+ let mid_trial = self
792+ .mid
793+ .encode_inner(&mid, frame_ms, None, false, 0, true)?;
794+ let side_trial = self
795+ .side
796+ .encode_inner(&side, frame_ms, None, false, 0, true)?;
797+ let mid_only = side_energy < 1.0e-10;
798+ write_stereo_packet_header(enc, &mid_trial, &side_trial, mid_only);
799+ write_stereo_zero_pred(enc);
800+ if !side_trial.vad_flag {
801+ enc.enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8);
802+ }
803+ write_frame_data(enc, &mid_trial, false, 0);
804+ if !mid_only {
805+ write_frame_data(enc, &side_trial, false, 0);
806+ }
807+ self.mid.replay_ms(&mid_trial.bytes, frame_ms)?;
808+ if mid_only {
809+ self.side.reset_state();
810+ } else {
811+ self.side.replay_ms(&side_trial.bytes, frame_ms)?;
812+ }
813+ self.prev_mid_only = mid_only;
814+ self.voiced_frames += usize::from(mid_trial.voiced || side_trial.voiced);
815+ Ok(())
816+ }
817+
818+ /// Encodes one 10 or 20 ms interleaved stereo frame at 48 kHz.
819+ pub fn encode_frame_ms(
820+ &mut self,
821+ pcm48: &[f32],
822+ out: &mut [u8],
823+ frame_ms: usize,
824+ ) -> Result<usize> {
825+ assert!(
826+ matches!(frame_ms, 10 | 20),
827+ "SilkStereoEncoder codes 10 or 20 ms stereo frames"
828+ );
829+ assert_eq!(
830+ pcm48.len(),
831+ 2 * 48 * frame_ms,
832+ "SilkStereoEncoder input is 48 kHz stereo"
833+ );
834+ if self.prev_mid_only {
835+ self.side.reset_state();
836+ if let Some(bps) = self.target_bps {
837+ self.side.set_bitrate((bps / 2).max(500));
838+ }
839+ }
840+ let samples = 48 * frame_ms;
841+ let mut mid = Vec::with_capacity(samples);
842+ let mut side = Vec::with_capacity(samples);
843+ let mut side_energy = 0.0f32;
844+ for lr in pcm48.chunks_exact(2) {
845+ let m = 0.5 * (lr[0] + lr[1]);
846+ let s = 0.5 * (lr[0] - lr[1]);
847+ mid.push(m);
848+ side.push(s);
849+ side_energy += s * s;
850+ }
851+ let mid_trial = self
852+ .mid
853+ .encode_inner(&mid, frame_ms, None, false, 0, true)?;
854+ let side_trial = self
855+ .side
856+ .encode_inner(&side, frame_ms, None, false, 0, true)?;
857+ let mid_only = side_energy < 1.0e-10;
858+
859+ self.range.reset(1275);
860+ write_stereo_packet_header(&mut self.range, &mid_trial, &side_trial, mid_only);
861+ write_stereo_zero_pred(&mut self.range);
862+ if !side_trial.vad_flag {
863+ self.range
864+ .enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8);
865+ }
866+ write_frame_data(&mut self.range, &mid_trial, false, 0);
867+ if !mid_only {
868+ write_frame_data(&mut self.range, &side_trial, false, 0);
869+ }
870+ self.range.done();
871+ debug_assert!(!self.range.error());
872+ let len = self.range.range_bytes();
873+ self.final_range = self.range.range();
874+ let duration = if frame_ms == 10 { 0u8 } else { 1 };
875+ let base = match self.fs_khz {
876+ 8 => 0u8,
877+ 12 => 4,
878+ _ => 8,
879+ };
880+ if out.len() < 1 + len {
881+ return Err(ec_core::Error::corrupt(format!(
882+ "silk stereo encode: packet needs {} bytes, buffer holds {}",
883+ 1 + len,
884+ out.len()
885+ )));
886+ }
887+ out[0] = ((base + duration) << 3) | 0x04;
888+ out[1..1 + len].copy_from_slice(&self.range.data()[..len]);
889+ self.replay_ms(&out[1..1 + len], frame_ms)?;
890+ self.mid.replay_ms(&mid_trial.bytes, frame_ms)?;
891+ if mid_only {
892+ self.side.reset_state();
893+ } else {
894+ self.side.replay_ms(&side_trial.bytes, frame_ms)?;
895+ }
896+ self.prev_mid_only = mid_only;
897+ self.voiced_frames += usize::from(mid_trial.voiced || side_trial.voiced);
898+ debug_assert_eq!(self.mirror_range, self.final_range);
899+ Ok(1 + len)
900+ }
901+
902+ /// Decodes a finished hybrid payload (TOC stripped) through the stereo
903+ /// mirror so the range state can be checked against the packet encoder.
904+ pub fn replay_hybrid(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
905+ self.replay_ms(payload, frame_ms)
906+ }
907+
908+ fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
909+ let fs = self.fs_khz;
910+ let mut dec = RangeDecoder::new(payload);
911+ let total = 2 * frame_ms * fs;
912+ if self.mirror_out.len() < total {
913+ self.mirror_out.resize(total, 0);
914+ }
915+ let n = self.mirror.decode(
916+ &mut dec,
917+ &mut self.mirror_out[..total],
918+ frame_ms,
919+ fs as u32 * 1000,
920+ 2,
921+ true,
922+ )?;
923+ debug_assert_eq!(n, frame_ms * fs);
924+ self.mirror_range = dec.range();
925+ Ok(())
926+ }
927+}
928+
929+fn write_stereo_packet_header(enc: &mut RangeEncoder, mid: &Trial, side: &Trial, mid_only: bool) {
930+ enc.enc_bit_logp(mid.vad_flag, 1);
931+ enc.enc_bit_logp(false, 1);
932+ enc.enc_bit_logp(if mid_only { false } else { side.vad_flag }, 1);
933+ enc.enc_bit_logp(false, 1);
934+}
935+
936+fn write_stereo_zero_pred(enc: &mut RangeEncoder) {
937+ enc.enc_icdf(12, &STEREO_PRED_JOINT_ICDF, 8);
938+ enc.enc_icdf(1, &UNIFORM3_ICDF, 8);
939+ enc.enc_icdf(2, &UNIFORM5_ICDF, 8);
940+ enc.enc_icdf(1, &UNIFORM3_ICDF, 8);
941+ enc.enc_icdf(2, &UNIFORM5_ICDF, 8);
942+}
678 /// One closed-loop quantisation of a frame.943 /// One closed-loop quantisation of a frame.
679 struct Run {944 struct Run {
680 ltp_index: [usize; MAX_NB_SUBFR],945 ltp_index: [usize; MAX_NB_SUBFR],
@@ -685,7 +950,6 @@ struct Run {
685 gq: Vec<f32>,950 gq: Vec<f32>,
686 }951 }
687 952
688-/// One coded candidate of a frame at a given gain offset.
689 struct Trial {953 struct Trial {
690 bytes: Vec<u8>,954 bytes: Vec<u8>,
691 range: u32,955 range: u32,
@@ -693,6 +957,119 @@ struct Trial {
693 gain_idx: [i8; MAX_NB_SUBFR],957 gain_idx: [i8; MAX_NB_SUBFR],
694 per_index: usize,958 per_index: usize,
695 run: Run,959 run: Run,
960+ vad_flag: bool,
961+ signal_type: i32,
962+ quant_offset_type: usize,
963+ wb: bool,
964+ order: usize,
965+ nb_subfr: usize,
966+ fs: usize,
967+ lag_index: i32,
968+ contour_index: i32,
969+ voiced: bool,
970+ ltp_scale_index: usize,
971+ nq: NlsfQuant,
972+ seed_index: i32,
973+}
974+
975+fn write_packet_header(enc: &mut RangeEncoder, frames: &[&Trial]) {
976+ for frame in frames {
977+ enc.enc_bit_logp(frame.vad_flag, 1);
978+ }
979+ enc.enc_bit_logp(false, 1);
980+}
981+
982+fn write_frame_data(
983+ enc: &mut RangeEncoder,
984+ frame: &Trial,
985+ conditional: bool,
986+ prev_signal_type: i32,
987+) {
988+ if frame.vad_flag {
989+ enc.enc_icdf(
990+ ((frame.signal_type << 1) | frame.quant_offset_type as i32) as usize - 2,
991+ &TYPE_OFFSET_VAD_ICDF,
992+ 8,
993+ );
994+ } else {
995+ enc.enc_icdf(frame.quant_offset_type, &TYPE_OFFSET_NO_VAD_ICDF, 8);
996+ }
997+ if conditional {
998+ enc.enc_icdf(frame.gain_idx[0] as usize, &DELTA_GAIN_ICDF, 8);
999+ } else {
1000+ enc.enc_icdf(
1001+ (frame.gain_idx[0] as usize) >> 3,
1002+ &GAIN_ICDF[frame.signal_type as usize],
1003+ 8,
1004+ );
1005+ enc.enc_icdf((frame.gain_idx[0] as usize) & 7, &UNIFORM8_ICDF, 8);
1006+ }
1007+ for k in 1..frame.nb_subfr {
1008+ enc.enc_icdf(frame.gain_idx[k] as usize, &DELTA_GAIN_ICDF, 8);
1009+ }
1010+ let cb = nlsf_cb(frame.wb);
1011+ let stage1_icdf = &cb.cb1_icdf[(frame.signal_type as usize >> 1) * cb.n_vectors..];
1012+ enc.enc_icdf(frame.nq.indices[0] as usize, stage1_icdf, 8);
1013+ let (ec_ix, _) = crate::silk::nlsf_unpack(cb, frame.nq.indices[0] as usize);
1014+ for i in 0..frame.order {
1015+ let q = frame.nq.indices[i + 1] as i32;
1016+ let icdf = &cb.ec_icdf[ec_ix[i] as usize..];
1017+ if q <= -4 {
1018+ enc.enc_icdf(0, icdf, 8);
1019+ enc.enc_icdf((-4 - q) as usize, &NLSF_EXT_ICDF, 8);
1020+ } else if q >= 4 {
1021+ enc.enc_icdf(8, icdf, 8);
1022+ enc.enc_icdf((q - 4) as usize, &NLSF_EXT_ICDF, 8);
1023+ } else {
1024+ enc.enc_icdf((q + 4) as usize, icdf, 8);
1025+ }
1026+ }
1027+ if frame.nb_subfr == MAX_NB_SUBFR {
1028+ enc.enc_icdf(
1029+ frame.nq.interp_index as usize,
1030+ &NLSF_INTERPOLATION_FACTOR_ICDF,
1031+ 8,
1032+ );
1033+ }
1034+ if frame.voiced {
1035+ if conditional && prev_signal_type == 2 {
1036+ enc.enc_icdf(0, &PITCH_DELTA_ICDF, 8);
1037+ }
1038+ let half = frame.fs as i32 >> 1;
1039+ enc.enc_icdf((frame.lag_index / half) as usize, &PITCH_LAG_ICDF, 8);
1040+ let low_icdf: &[u8] = match frame.fs {
1041+ 16 => &UNIFORM8_ICDF,
1042+ 12 => &UNIFORM6_ICDF,
1043+ _ => &UNIFORM4_ICDF,
1044+ };
1045+ enc.enc_icdf((frame.lag_index % half) as usize, low_icdf, 8);
1046+ let contour_icdf: &[u8] = match (frame.fs, frame.nb_subfr) {
1047+ (8, 4) => &PITCH_CONTOUR_NB_ICDF,
1048+ (8, _) => &PITCH_CONTOUR_10_MS_NB_ICDF,
1049+ (_, 4) => &PITCH_CONTOUR_ICDF,
1050+ _ => &PITCH_CONTOUR_10_MS_ICDF,
1051+ };
1052+ enc.enc_icdf(frame.contour_index as usize, contour_icdf, 8);
1053+ enc.enc_icdf(frame.per_index, &LTP_PER_INDEX_ICDF, 8);
1054+ let gain_icdf: &[u8] = match frame.per_index {
1055+ 0 => &LTP_GAIN_ICDF_0,
1056+ 1 => &LTP_GAIN_ICDF_1,
1057+ _ => &LTP_GAIN_ICDF_2,
1058+ };
1059+ for k in 0..frame.nb_subfr {
1060+ enc.enc_icdf(frame.run.ltp_index[k], gain_icdf, 8);
1061+ }
1062+ if !conditional {
1063+ enc.enc_icdf(frame.ltp_scale_index, &LTPSCALE_ICDF, 8);
1064+ }
1065+ }
1066+ enc.enc_icdf(frame.seed_index as usize, &UNIFORM4_ICDF, 8);
1067+ encode_pulses(
1068+ enc,
1069+ &frame.run.pulses,
1070+ frame.signal_type,
1071+ frame.quant_offset_type as i32,
1072+ );
696 }1073 }
697 1074
698 /// Bits an ICDF symbol costs, for choosing among equivalent codings.1075 /// Bits an ICDF symbol costs, for choosing among equivalent codings.
crates/ec-opus/tests/conformance.rsmodified+694 -57
@@ -772,7 +772,7 @@ fn real_library_sweep() {
772 // Encoder: self-consistency (range-exact against our own decoder)772 // Encoder: self-consistency (range-exact against our own decoder)
773 // ---------------------------------------------------------------------------773 // ---------------------------------------------------------------------------
774 774
775-use ec_opus::{Application, Bandwidth, Encoder, MultistreamEncoder};775+use ec_opus::{Application, Bandwidth, Encoder, Mode, MultistreamEncoder, Packet};
776 776
777 /// A deterministic music-like test signal: several detuned partials plus a777 /// A deterministic music-like test signal: several detuned partials plus a
778 /// swept component per channel, loud enough to exercise every band.778 /// swept component per channel, loud enough to exercise every band.
@@ -875,52 +875,357 @@ fn encoder_roundtrips_at_every_rate() {
875 }875 }
876 }876 }
877 877
878-/// The mode `Encoder` actually picks, read back from the packet's own TOC
879-/// byte: Voip below 20 kbps mono selects SILK (NB at/under 10 kbps, WB
880-/// above), Voip 20-40 kbps and Audio at any rate stay on CELT (Hybrid is
881-/// unimplemented and Mode 20-40 kbps needs it, D4).
882 #[test]878 #[test]
883-fn encoder_mode_follows_application_and_bitrate() {879+fn encoder_mode_follows_application_bitrate_channels_and_frame_size() {
884- // `None` for the two CELT rows: any CELT config is correct there, the880+ #[derive(Clone, Copy, Debug)]
885- // exact one is `auto_bandwidth`'s call, not mode selection's.881+ struct Case {
882+ app: Application,
883+ channels: usize,
884+ bps: u32,
885+ frame: usize,
886+ mode_request: Option<Mode>,
887+ bandwidth_request: Option<Bandwidth>,
888+ mode: Mode,
889+ bandwidth: Bandwidth,
890+ config: u8,
891+ code: u8,
892+ frames: usize,
893+ }
894+
886 let cases = [895 let cases = [
887- (Application::Voip, 8_000u32, Some(1u8)),896+ Case {
888- (Application::Voip, 16_000, Some(9)),897+ app: Application::Voip,
889- (Application::Audio, 64_000, None),898+ channels: 1,
890- (Application::Voip, 32_000, Some(15)),899+ bps: 8_000,
891- (Application::Voip, 48_000, None),900+ frame: 480,
901+ mode_request: None,
902+ bandwidth_request: None,
903+ mode: Mode::Silk,
904+ bandwidth: Bandwidth::Narrow,
905+ config: 0,
906+ code: 0,
907+ frames: 1,
908+ },
909+ Case {
910+ app: Application::Voip,
911+ channels: 1,
912+ bps: 12_000,
913+ frame: 960,
914+ mode_request: None,
915+ bandwidth_request: None,
916+ mode: Mode::Silk,
917+ bandwidth: Bandwidth::Narrow,
918+ config: 1,
919+ code: 0,
920+ frames: 1,
921+ },
922+ Case {
923+ app: Application::Voip,
924+ channels: 1,
925+ bps: 13_000,
926+ frame: 960,
927+ mode_request: None,
928+ bandwidth_request: None,
929+ mode: Mode::Silk,
930+ bandwidth: Bandwidth::Medium,
931+ config: 5,
932+ code: 0,
933+ frames: 1,
934+ },
935+ Case {
936+ app: Application::Voip,
937+ channels: 1,
938+ bps: 16_000,
939+ frame: 960,
940+ mode_request: None,
941+ bandwidth_request: None,
942+ mode: Mode::Silk,
943+ bandwidth: Bandwidth::Medium,
944+ config: 5,
945+ code: 0,
946+ frames: 1,
947+ },
948+ Case {
949+ app: Application::Voip,
950+ channels: 1,
951+ bps: 19_000,
952+ frame: 960,
953+ mode_request: None,
954+ bandwidth_request: None,
955+ mode: Mode::Silk,
956+ bandwidth: Bandwidth::Wide,
957+ config: 9,
958+ code: 0,
959+ frames: 1,
960+ },
961+ Case {
962+ app: Application::Voip,
963+ channels: 1,
964+ bps: 20_000,
965+ frame: 960,
966+ mode_request: None,
967+ bandwidth_request: None,
968+ mode: Mode::Hybrid,
969+ bandwidth: Bandwidth::SuperWide,
970+ config: 13,
971+ code: 0,
972+ frames: 1,
973+ },
974+ Case {
975+ app: Application::Voip,
976+ channels: 1,
977+ bps: 39_000,
978+ frame: 960,
979+ mode_request: None,
980+ bandwidth_request: None,
981+ mode: Mode::Hybrid,
982+ bandwidth: Bandwidth::Full,
983+ config: 15,
984+ code: 0,
985+ frames: 1,
986+ },
987+ Case {
988+ app: Application::Voip,
989+ channels: 1,
990+ bps: 40_000,
991+ frame: 960,
992+ mode_request: None,
993+ bandwidth_request: None,
994+ mode: Mode::Celt,
995+ bandwidth: Bandwidth::Full,
996+ config: 31,
997+ code: 0,
998+ frames: 1,
999+ },
1000+ Case {
1001+ app: Application::Audio,
1002+ channels: 1,
1003+ bps: 16_000,
1004+ frame: 960,
1005+ mode_request: None,
1006+ bandwidth_request: None,
1007+ mode: Mode::Celt,
1008+ bandwidth: Bandwidth::SuperWide,
1009+ config: 27,
1010+ code: 0,
1011+ frames: 1,
1012+ },
1013+ Case {
1014+ app: Application::Audio,
1015+ channels: 1,
1016+ bps: 64_000,
1017+ frame: 960,
1018+ mode_request: None,
1019+ bandwidth_request: None,
1020+ mode: Mode::Celt,
1021+ bandwidth: Bandwidth::Full,
1022+ config: 31,
1023+ code: 0,
1024+ frames: 1,
1025+ },
1026+ Case {
1027+ app: Application::LowDelay,
1028+ channels: 1,
1029+ bps: 16_000,
1030+ frame: 960,
1031+ mode_request: None,
1032+ bandwidth_request: None,
1033+ mode: Mode::Celt,
1034+ bandwidth: Bandwidth::SuperWide,
1035+ config: 27,
1036+ code: 0,
1037+ frames: 1,
1038+ },
1039+ Case {
1040+ app: Application::Voip,
1041+ channels: 2,
1042+ bps: 16_000,
1043+ frame: 960,
1044+ mode_request: None,
1045+ bandwidth_request: None,
1046+ mode: Mode::Silk,
1047+ bandwidth: Bandwidth::Narrow,
1048+ config: 1,
1049+ code: 0,
1050+ frames: 1,
1051+ },
1052+ Case {
1053+ app: Application::Voip,
1054+ channels: 2,
1055+ bps: 24_000,
1056+ frame: 960,
1057+ mode_request: None,
1058+ bandwidth_request: None,
1059+ mode: Mode::Silk,
1060+ bandwidth: Bandwidth::Narrow,
1061+ config: 1,
1062+ code: 0,
1063+ frames: 1,
1064+ },
1065+ Case {
1066+ app: Application::Voip,
1067+ channels: 2,
1068+ bps: 32_000,
1069+ frame: 960,
1070+ mode_request: None,
1071+ bandwidth_request: None,
1072+ mode: Mode::Silk,
1073+ bandwidth: Bandwidth::Medium,
1074+ config: 5,
1075+ code: 0,
1076+ frames: 1,
1077+ },
1078+ Case {
1079+ app: Application::Voip,
1080+ channels: 2,
1081+ bps: 38_000,
1082+ frame: 960,
1083+ mode_request: None,
1084+ bandwidth_request: None,
1085+ mode: Mode::Silk,
1086+ bandwidth: Bandwidth::Wide,
1087+ config: 9,
1088+ code: 0,
1089+ frames: 1,
1090+ },
1091+ Case {
1092+ app: Application::Voip,
1093+ channels: 2,
1094+ bps: 40_000,
1095+ frame: 960,
1096+ mode_request: None,
1097+ bandwidth_request: None,
1098+ mode: Mode::Hybrid,
1099+ bandwidth: Bandwidth::SuperWide,
1100+ config: 13,
1101+ code: 0,
1102+ frames: 1,
1103+ },
1104+ Case {
1105+ app: Application::Voip,
1106+ channels: 2,
1107+ bps: 78_000,
1108+ frame: 960,
1109+ mode_request: None,
1110+ bandwidth_request: None,
1111+ mode: Mode::Hybrid,
1112+ bandwidth: Bandwidth::Full,
1113+ config: 15,
1114+ code: 0,
1115+ frames: 1,
1116+ },
1117+ Case {
1118+ app: Application::Voip,
1119+ channels: 2,
1120+ bps: 80_000,
1121+ frame: 960,
1122+ mode_request: None,
1123+ bandwidth_request: None,
1124+ mode: Mode::Celt,
1125+ bandwidth: Bandwidth::Full,
1126+ config: 31,
1127+ code: 0,
1128+ frames: 1,
1129+ },
1130+ Case {
1131+ app: Application::Voip,
1132+ channels: 2,
1133+ bps: 32_000,
1134+ frame: 480,
1135+ mode_request: None,
1136+ bandwidth_request: None,
1137+ mode: Mode::Silk,
1138+ bandwidth: Bandwidth::Medium,
1139+ config: 4,
1140+ code: 0,
1141+ frames: 1,
1142+ },
1143+ Case {
1144+ app: Application::Voip,
1145+ channels: 2,
1146+ bps: 32_000,
1147+ frame: 1920,
1148+ mode_request: None,
1149+ bandwidth_request: None,
1150+ mode: Mode::Silk,
1151+ bandwidth: Bandwidth::Medium,
1152+ config: 5,
1153+ code: 3,
1154+ frames: 2,
1155+ },
1156+ Case {
1157+ app: Application::Voip,
1158+ channels: 2,
1159+ bps: 32_000,
1160+ frame: 2880,
1161+ mode_request: None,
1162+ bandwidth_request: None,
1163+ mode: Mode::Silk,
1164+ bandwidth: Bandwidth::Medium,
1165+ config: 5,
1166+ code: 3,
1167+ frames: 3,
1168+ },
1169+ Case {
1170+ app: Application::Voip,
1171+ channels: 1,
1172+ bps: 16_000,
1173+ frame: 1920,
1174+ mode_request: None,
1175+ bandwidth_request: None,
1176+ mode: Mode::Silk,
1177+ bandwidth: Bandwidth::Medium,
1178+ config: 6,
1179+ code: 0,
1180+ frames: 1,
1181+ },
1182+ Case {
1183+ app: Application::Voip,
1184+ channels: 1,
1185+ bps: 19_000,
1186+ frame: 2880,
1187+ mode_request: None,
1188+ bandwidth_request: None,
1189+ mode: Mode::Silk,
1190+ bandwidth: Bandwidth::Wide,
1191+ config: 11,
1192+ code: 0,
1193+ frames: 1,
1194+ },
1195+ Case {
1196+ app: Application::Audio,
1197+ channels: 1,
1198+ bps: 64_000,
1199+ frame: 480,
1200+ mode_request: Some(Mode::Silk),
1201+ bandwidth_request: Some(Bandwidth::Medium),
1202+ mode: Mode::Silk,
1203+ bandwidth: Bandwidth::Medium,
1204+ config: 4,
1205+ code: 0,
1206+ frames: 1,
1207+ },
892 ];1208 ];
893- for (app, bps, want_config) in cases {
894- let mut enc = Encoder::new(48000, 1, app).unwrap();
895- enc.set_bitrate(bps);
896- let pcm = vec![0.0f32; 960];
897- let mut out = vec![0u8; 1500];
898- let n = enc.encode_float(&pcm, 960, &mut out).unwrap();
899- let toc = ec_opus::Toc::new(out[0]);
900- match want_config {
901- Some(want) => assert_eq!(
902- toc.config, want,
903- "{app:?} at {bps} bps: TOC config {} (wanted {want})",
904- toc.config
905- ),
906- None => assert_eq!(
907- toc.mode(),
908- ec_opus::Mode::Celt,
909- "{app:?} at {bps} bps: TOC config {} is not CELT",
910- toc.config
911- ),
912- }
913- assert!(n > 1, "{app:?} at {bps} bps: empty packet");
914- }
915 1209
916- let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap();1210+ for case in cases {
917- enc.set_mode(Some(ec_opus::Mode::Silk));1211+ let mut enc = Encoder::new(48000, case.channels, case.app).unwrap();
918- enc.set_bandwidth(Some(Bandwidth::Medium));1212+ enc.set_bitrate(case.bps);
919- let pcm = vec![0.0f32; 480];1213+ enc.set_mode(case.mode_request);
920- let mut out = vec![0u8; 1500];1214+ enc.set_bandwidth(case.bandwidth_request);
921- let n = enc.encode_float(&pcm, 480, &mut out).unwrap();1215+ let pcm = vec![0.0f32; case.frame * case.channels];
922- assert_eq!(ec_opus::Toc::new(out[0]).config, 4, "forced 10 ms MB SILK");1216+ let mut out = vec![0u8; 4096];
923- assert!(n > 1, "forced 10 ms MB SILK empty packet");1217+ let n = enc.encode_float(&pcm, case.frame, &mut out).unwrap();
1218+ let packet = Packet::parse(&out[..n], false).unwrap();
1219+ let toc = packet.toc;
1220+ assert_eq!(toc.mode(), case.mode, "{case:?}");
1221+ assert_eq!(toc.bandwidth(), case.bandwidth, "{case:?}");
1222+ assert_eq!(toc.config, case.config, "{case:?}");
1223+ assert_eq!(toc.code, case.code, "{case:?}");
1224+ assert_eq!(toc.stereo, case.channels == 2, "{case:?}");
1225+ assert_eq!(packet.frames.len(), case.frames, "{case:?}");
1226+ assert_eq!(packet.samples_48k(), case.frame, "{case:?}");
1227+ assert!(n > 1, "{case:?}: empty packet");
1228+ }
924 }1229 }
925 1230
926 /// All four CELT frame sizes survive the loop, and constrained VBR both1231 /// 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]
972 ec_opus::ogg::opus_head(channels as u8, pre_skip, 48000, 0, mapping)1277 ec_opus::ogg::opus_head(channels as u8, pre_skip, 48000, 0, mapping)
973 }1278 }
974 1279
975-/// Muxes 20 ms packets into an Ogg-Opus file whose final granule trims the1280+/// Muxes packets into an Ogg-Opus file whose final granule trims the stream
976-/// stream to exactly `total_samples` — RFC 7845 end-trimming plus the1281+/// to exactly `total_samples` — RFC 7845 end-trimming plus the pre-skip
977-/// pre-skip accounting.1282+/// accounting.
978 fn write_ogg_opus(1283 fn write_ogg_opus(
979 path: &Path,1284 path: &Path,
980 packets: &[Vec<u8>],1285 packets: &[Vec<u8>],
@@ -996,16 +1301,17 @@ fn write_ogg_opus(
996 let mut pts = 0i64;1301 let mut pts = 0i64;
997 for (idx, p) in packets.iter().enumerate() {1302 for (idx, p) in packets.iter().enumerate() {
998 let last = idx == packets.len() - 1;1303 let last = idx == packets.len() - 1;
1304+ let packet_dur = ec_opus::Packet::parse(p, false).unwrap().samples_48k() as i64;
999 let dur = if last {1305 let dur = if last {
1000 total_samples as i64 + pre_skip - pts1306 total_samples as i64 + pre_skip - pts
1001 } else {1307 } else {
1002- 9601308+ packet_dur
1003 };1309 };
1004 let pkt = CorePacket::new(0, tb, p.clone())1310 let pkt = CorePacket::new(0, tb, p.clone())
1005 .with_pts(pts)1311 .with_pts(pts)
1006 .with_duration(dur);1312 .with_duration(dur);
1007 mux.write_packet(&pkt).unwrap();1313 mux.write_packet(&pkt).unwrap();
1008- pts += 960;1314+ pts += packet_dur;
1009 }1315 }
1010 mux.finish().unwrap();1316 mux.finish().unwrap();
1011 }1317 }
@@ -1036,7 +1342,14 @@ fn encode_packets(enc: &mut Encoder, pcm: &[f32], channels: usize) -> Vec<Vec<u8
1036 }1342 }
1037 1343
1038 fn temp_path(name: &str) -> PathBuf {1344 fn temp_path(name: &str) -> PathBuf {
1039- std::env::temp_dir().join(format!("ec-opus-enc-{}-{name}", std::process::id()))1345+ let root = std::env::var_os("EC_OPUS_SCRATCH")
1346+ .map(PathBuf::from)
1347+ .unwrap_or_else(|| {
1348+ let home = std::env::var_os("HOME").expect("HOME set for encoder scratch");
1349+ PathBuf::from(home).join(".cache/silk2")
1350+ });
1351+ fs::create_dir_all(&root).unwrap();
1352+ root.join(format!("ec-opus-enc-{}-{name}", std::process::id()))
1040 }1353 }
1041 1354
1042 /// The full product rate table, mono and stereo, decoded by libopus: the1355 /// The full product rate table, mono and stereo, decoded by libopus: the
@@ -1706,11 +2019,11 @@ fn silk_mono_nb_wb_roundtrip() {
1706 #[test]2019 #[test]
1707 fn silk_mediumband_and_10ms_roundtrip() {2020 fn silk_mediumband_and_10ms_roundtrip() {
1708 let pcm = speech_like();2021 let pcm = speech_like();
1709- for (tag, fs_khz, frame_ms, config, cutoff, bps) in [2022+ for (tag, fs_khz, frame_ms, config, cutoff, bps, floor) in [
1710- ("NB10", 8usize, 10usize, 0u8, 3500.0, 12_000u32),2023+ ("NB10", 8usize, 10usize, 0u8, 3500.0, 12_000u32, 0.89f64),
1711- ("MB10", 12, 10, 4, 5500.0, 16_000),2024+ ("MB10", 12, 10, 4, 5500.0, 16_000, 0.91),
1712- ("WB10", 16, 10, 8, 7000.0, 20_000),2025+ ("WB10", 16, 10, 8, 7000.0, 20_000, 0.93),
1713- ("MB20", 12, 20, 5, 5500.0, 16_000),2026+ ("MB20", 12, 20, 5, 5500.0, 16_000, 0.95),
1714 ] {2027 ] {
1715 let enc = match fs_khz {2028 let enc = match fs_khz {
1716 8 => SilkEncoder::new(false),2029 8 => SilkEncoder::new(false),
@@ -1727,7 +2040,7 @@ fn silk_mediumband_and_10ms_roundtrip() {
1727 "silk {tag}: corr {corr:.4} at lag {lag}, voiced {voiced}/{} frames, {kbps:.2} kbps",2040 "silk {tag}: corr {corr:.4} at lag {lag}, voiced {voiced}/{} frames, {kbps:.2} kbps",
1728 packets.len()2041 packets.len()
1729 );2042 );
1730- assert!(corr >= 0.75, "{tag}: corr {corr:.4}");2043+ assert!(corr >= floor, "{tag}: corr {corr:.4}");
1731 assert!(2044 assert!(
1732 frame_ms == 10 || voiced > 0,2045 frame_ms == 10 || voiced > 0,
1733 "{tag}: no frame coded with LTP"2046 "{tag}: no frame coded with LTP"
@@ -1739,6 +2052,207 @@ fn silk_mediumband_and_10ms_roundtrip() {
1739 }2052 }
1740 }2053 }
1741 2054
2055+#[test]
2056+fn silk_multiframe_packets_roundtrip() {
2057+ let full = speech_like();
2058+ let pcm = &full[..46_080];
2059+ for (tag, enc, frame_ms, config, cutoff, bps, floor) in [
2060+ (
2061+ "NB40",
2062+ SilkEncoder::new(false),
2063+ 40usize,
2064+ 2u8,
2065+ 3500.0,
2066+ 16_000u32,
2067+ 0.9329f64,
2068+ ),
2069+ (
2070+ "MB40",
2071+ SilkEncoder::new_mediumband(),
2072+ 40,
2073+ 6,
2074+ 5500.0,
2075+ 20_000,
2076+ 0.94,
2077+ ),
2078+ ("WB40", SilkEncoder::new(true), 40, 10, 7000.0, 24_000, 0.95),
2079+ ("WB60", SilkEncoder::new(true), 60, 11, 7000.0, 24_000, 0.93),
2080+ ] {
2081+ let (decoded, packets, voiced) = silk_roundtrip_ms(enc, pcm, frame_ms, Some(bps));
2082+ let toc = ec_opus::Toc::new(packets[0][0]);
2083+ assert_eq!(toc.config, config, "{tag}: wrong TOC config");
2084+ assert_eq!(toc.code, 0, "{tag}: multiframe SILK uses one Opus frame");
2085+ let reference = lowpass(pcm, cutoff);
2086+ let (corr, lag) = aligned_corr(&reference, &decoded, 2500);
2087+ let bytes: usize = packets.iter().map(Vec::len).sum();
2088+ let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64);
2089+ eprintln!(
2090+ "silk {tag}: corr {corr:.4} at lag {lag}, voiced {voiced}/{} frames, {kbps:.2} kbps",
2091+ packets.len()
2092+ );
2093+ assert!(corr >= floor, "{tag}: corr {corr:.4} below {floor:.4}");
2094+ assert!(voiced > 0, "{tag}: no frame coded with LTP");
2095+ if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len()) {
2096+ let (c, _) = aligned_corr(&oracle, &decoded, 2500);
2097+ assert!(
2098+ c >= 0.99,
2099+ "{tag}: internal decode vs external decode corr {c:.4}"
2100+ );
2101+ }
2102+ if Command::new("gst-launch-1.0")
2103+ .arg("--version")
2104+ .output()
2105+ .is_ok()
2106+ {
2107+ let path = temp_path(&format!("silk-{tag}-gst.opus"));
2108+ write_ogg_opus(&path, &packets, opus_head(1, 120, None), 1, pcm.len(), 120);
2109+ let location = format!("location={}", path.display());
2110+ let out = Command::new("gst-launch-1.0")
2111+ .args([
2112+ "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink",
2113+ ])
2114+ .output()
2115+ .unwrap();
2116+ let stderr = String::from_utf8_lossy(&out.stderr);
2117+ assert!(out.status.success(), "{tag}: gst decode: {stderr}");
2118+ let _ = fs::remove_file(&path);
2119+ }
2120+ }
2121+}
2122+
2123+fn stereo_speech_pair() -> Vec<f32> {
2124+ let left = speech_like();
2125+ let mut out = Vec::with_capacity(left.len() * 2);
2126+ for (i, &l) in left.iter().enumerate() {
2127+ let t = i as f64 / 48000.0;
2128+ let r = 0.78 * l + 0.12 * (std::f64::consts::TAU * 310.0 * t).sin() as f32;
2129+ out.push(l);
2130+ out.push(r);
2131+ }
2132+ out
2133+}
2134+
2135+fn aligned_channel_corr(reference: &[f32], decoded: &[f32], channels: usize, ch: usize) -> f64 {
2136+ let b: Vec<f32> = decoded.chunks_exact(channels).map(|f| f[ch]).collect();
2137+ aligned_corr(reference, &b, 2000).0
2138+}
2139+
2140+#[test]
2141+fn silk_stereo_speech_roundtrip() {
2142+ let pcm = stereo_speech_pair();
2143+ let total = pcm.len() / 2;
2144+ for (tag, bandwidth, per_channel_bps, cutoff, frame, config, code, frames) in [
2145+ (
2146+ "NB20",
2147+ Bandwidth::Narrow,
2148+ 16_000u32,
2149+ 3500.0,
2150+ 960usize,
2151+ 1u8,
2152+ 0u8,
2153+ 1usize,
2154+ ),
2155+ ("MB20", Bandwidth::Medium, 20_000, 5500.0, 960, 5, 0, 1),
2156+ ("WB20", Bandwidth::Wide, 24_000, 7000.0, 960, 9, 0, 1),
2157+ ("NB40", Bandwidth::Narrow, 16_000, 3500.0, 1920, 1, 3, 2),
2158+ ("MB40", Bandwidth::Medium, 20_000, 5500.0, 1920, 5, 3, 2),
2159+ ("WB60", Bandwidth::Wide, 24_000, 7000.0, 2880, 9, 3, 3),
2160+ ] {
2161+ let frame_ms = frame / 48;
2162+ let mono_frame_ms = frame_ms.min(20);
2163+ let mut mono_floor = [0.0f64; 2];
2164+ for ch in 0..2 {
2165+ let mono: Vec<f32> = pcm.chunks_exact(2).map(|f| f[ch]).collect();
2166+ let silk = match bandwidth {
2167+ Bandwidth::Narrow => SilkEncoder::new(false),
2168+ Bandwidth::Medium => SilkEncoder::new_mediumband(),
2169+ _ => SilkEncoder::new(true),
2170+ };
2171+ let reference = lowpass(&mono, cutoff);
2172+ let (decoded, _, _) =
2173+ silk_roundtrip_ms(silk, &mono, mono_frame_ms, Some(per_channel_bps));
2174+ mono_floor[ch] = aligned_corr(&reference, &decoded, 2000).0;
2175+ }
2176+ let mut enc = Encoder::new(48000, 2, Application::Voip).unwrap();
2177+ enc.set_mode(Some(ec_opus::Mode::Silk));
2178+ enc.set_bandwidth(Some(bandwidth));
2179+ enc.set_bitrate(per_channel_bps * 2);
2180+ let mut dec = Decoder::new(48000, 2).unwrap();
2181+ let mut out = vec![0u8; 4096];
2182+ let mut buf = vec![0.0f32; 5760 * 2];
2183+ let mut decoded = Vec::new();
2184+ let mut packets = Vec::new();
2185+ let mut padded = pcm.clone();
2186+ padded.resize(pcm.len().div_ceil(frame * 2) * frame * 2 + frame * 2, 0.0);
2187+ for block in padded.chunks(frame * 2) {
2188+ let len = enc.encode_float(block, frame, &mut out).expect("encode");
2189+ let packet = Packet::parse(&out[..len], false).unwrap();
2190+ let toc = packet.toc;
2191+ assert_eq!(toc.config, config, "{tag}: wrong TOC config");
2192+ assert_eq!(toc.code, code, "{tag}: wrong TOC code");
2193+ assert_eq!(packet.frames.len(), frames, "{tag}: frame count");
2194+ assert_eq!(packet.samples_48k(), frame, "{tag}: packet samples");
2195+ assert!(toc.stereo, "{tag}: SILK TOC is not stereo");
2196+ let n = dec.decode_float(&out[..len], &mut buf).expect("decode");
2197+ assert_eq!(n, frame, "{tag}: decoded frame size");
2198+ assert_eq!(dec.final_range(), enc.final_range(), "{tag}: range state");
2199+ decoded.extend_from_slice(&buf[..n * 2]);
2200+ packets.push(out[..len].to_vec());
2201+ }
2202+ let bytes: usize = packets.iter().map(Vec::len).sum();
2203+ let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64);
2204+ for ch in 0..2 {
2205+ let source: Vec<f32> = pcm.chunks_exact(2).map(|f| f[ch]).collect();
2206+ let reference = lowpass(&source, cutoff);
2207+ let corr = aligned_channel_corr(&reference, &decoded, 2, ch);
2208+ eprintln!(
2209+ "silk stereo {tag} ch{ch}: corr {corr:.4}, mono {:.4}, {kbps:.2} kbps",
2210+ mono_floor[ch]
2211+ );
2212+ assert!(
2213+ corr + 0.01 >= mono_floor[ch],
2214+ "{tag} ch{ch}: stereo corr {corr:.4} trails mono {:.4}",
2215+ mono_floor[ch]
2216+ );
2217+ }
2218+ if Command::new("ffmpeg").arg("-version").output().is_ok() {
2219+ let path = temp_path(&format!("silk-stereo-{tag}.opus"));
2220+ write_ogg_opus(
2221+ &path,
2222+ &packets,
2223+ opus_head(2, enc.look_ahead(frame) as u16, None),
2224+ 2,
2225+ total,
2226+ enc.look_ahead(frame) as i64,
2227+ );
2228+ let out = Command::new("ffmpeg")
2229+ .args(["-v", "warning", "-c:a", "libopus", "-i"])
2230+ .arg(&path)
2231+ .args(["-f", "null", "-"])
2232+ .output()
2233+ .unwrap();
2234+ let stderr = String::from_utf8_lossy(&out.stderr);
2235+ assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}");
2236+ if Command::new("gst-launch-1.0")
2237+ .arg("--version")
2238+ .output()
2239+ .is_ok()
2240+ {
2241+ let location = format!("location={}", path.display());
2242+ let out = Command::new("gst-launch-1.0")
2243+ .args([
2244+ "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!",
2245+ "fakesink",
2246+ ])
2247+ .output()
2248+ .unwrap();
2249+ let stderr = String::from_utf8_lossy(&out.stderr);
2250+ assert!(out.status.success(), "{tag}: gst decode: {stderr}");
2251+ }
2252+ let _ = fs::remove_file(&path);
2253+ }
2254+ }
2255+}
1742 #[test]2256 #[test]
1743 fn silk_compares_to_celt_on_speech_at_speech_rates() {2257 fn silk_compares_to_celt_on_speech_at_speech_rates() {
1744 let pcm = speech_like();2258 let pcm = speech_like();
@@ -1775,8 +2289,8 @@ fn silk_compares_to_celt_on_speech_at_speech_rates() {
1775 );2289 );
1776 assert!(silk_corr >= 0.95, "{tag}: SILK corr {silk_corr:.4}");2290 assert!(silk_corr >= 0.95, "{tag}: SILK corr {silk_corr:.4}");
1777 assert!(2291 assert!(
1778- silk_corr + 0.01 >= celt_corr,2292+ silk_corr >= celt_corr,
1779- "{tag}: SILK {silk_corr:.4} trails CELT {celt_corr:.4} by >0.01"2293+ "{tag}: SILK {silk_corr:.4} trails CELT {celt_corr:.4}"
1780 );2294 );
1781 }2295 }
1782 }2296 }
@@ -2019,3 +2533,126 @@ fn hybrid_fb_roundtrip() {
2019 );2533 );
2020 }2534 }
2021 }2535 }
2536+
2537+fn hybrid_roundtrip_shape(
2538+ pcm: &[f32],
2539+ channels: usize,
2540+ frame: usize,
2541+ bps: u32,
2542+ bandwidth: Option<Bandwidth>,
2543+) -> (Vec<f32>, Vec<Vec<u8>>) {
2544+ let mut enc = Encoder::new(48000, channels, Application::Voip).unwrap();
2545+ enc.set_bitrate(bps);
2546+ enc.set_bandwidth(bandwidth);
2547+ let mut dec = Decoder::new(48000, channels).unwrap();
2548+ let mut out = vec![0u8; 1500];
2549+ let mut buf = vec![0f32; 5760 * channels];
2550+ let (mut decoded, mut packets) = (Vec::new(), Vec::new());
2551+ let mut padded = pcm.to_vec();
2552+ padded.resize(
2553+ pcm.len().div_ceil(frame * channels) * frame * channels + frame * channels,
2554+ 0.0,
2555+ );
2556+ for block in padded.chunks(frame * channels) {
2557+ let len = enc
2558+ .encode_float(block, frame, &mut out)
2559+ .expect("hybrid encode");
2560+ let n = dec
2561+ .decode_float(&out[..len], &mut buf)
2562+ .expect("hybrid decode");
2563+ assert_eq!(n, frame);
2564+ assert_eq!(dec.final_range(), enc.final_range(), "range state diverged");
2565+ decoded.extend_from_slice(&buf[..n * channels]);
2566+ packets.push(out[..len].to_vec());
2567+ }
2568+ (decoded, packets)
2569+}
2570+
2571+#[test]
2572+fn hybrid_shapes_roundtrip() {
2573+ for (tag, channels, frame, bps, bandwidth, config, floor) in [
2574+ (
2575+ "mono-swb10",
2576+ 1usize,
2577+ 480usize,
2578+ 24_000u32,
2579+ Bandwidth::SuperWide,
2580+ 12u8,
2581+ 0.75f64,
2582+ ),
2583+ ("mono-fb10", 1, 480, 32_000, Bandwidth::Full, 14, 0.75),
2584+ (
2585+ "stereo-swb20",
2586+ 2,
2587+ 960,
2588+ 48_000,
2589+ Bandwidth::SuperWide,
2590+ 13,
2591+ 0.75,
2592+ ),
2593+ ("stereo-fb20", 2, 960, 64_000, Bandwidth::Full, 15, 0.75),
2594+ ("stereo-fb10", 2, 480, 64_000, Bandwidth::Full, 14, 0.70),
2595+ ] {
2596+ let pcm = if channels == 1 {
2597+ speech_like()
2598+ } else {
2599+ stereo_speech_pair()
2600+ };
2601+ let (decoded, packets) =
2602+ hybrid_roundtrip_shape(&pcm, channels, frame, bps, Some(bandwidth));
2603+ let toc = ec_opus::Toc::new(packets[0][0]);
2604+ assert_eq!(toc.config, config, "{tag}: TOC config {}", toc.config);
2605+ assert_eq!(toc.stereo, channels == 2, "{tag}: TOC stereo flag");
2606+ let mut worst = 1.0f64;
2607+ for ch in 0..channels {
2608+ let source: Vec<f32> = pcm.chunks_exact(channels).map(|f| f[ch]).collect();
2609+ let got: Vec<f32> = decoded.chunks_exact(channels).map(|f| f[ch]).collect();
2610+ let (corr, lag) = aligned_corr(&source, &got, 400);
2611+ worst = worst.min(corr);
2612+ eprintln!("hybrid {tag} ch{ch}: corr {corr:.4} at lag {lag}");
2613+ }
2614+ assert!(worst >= floor, "{tag}: worst corr {worst:.4}");
2615+ let total = pcm.len() / channels;
2616+ let path = temp_path(&format!("hybrid-{tag}.opus"));
2617+ write_ogg_opus(
2618+ &path,
2619+ &packets,
2620+ opus_head(channels, 120, None),
2621+ channels,
2622+ total,
2623+ 120,
2624+ );
2625+ if Command::new("ffmpeg").arg("-version").output().is_ok() {
2626+ let out = Command::new("ffmpeg")
2627+ .args(["-v", "warning", "-c:a", "libopus", "-i"])
2628+ .arg(&path)
2629+ .args(["-f", "null", "-"])
2630+ .output()
2631+ .unwrap();
2632+ let stderr = String::from_utf8_lossy(&out.stderr);
2633+ assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}");
2634+ }
2635+ if Command::new("gst-launch-1.0")
2636+ .arg("--version")
2637+ .output()
2638+ .is_ok()
2639+ {
2640+ let location = format!("location={}", path.display());
2641+ let out = Command::new("gst-launch-1.0")
2642+ .args([
2643+ "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink",
2644+ ])
2645+ .output()
2646+ .unwrap();
2647+ let stderr = String::from_utf8_lossy(&out.stderr);
2648+ assert!(out.status.success(), "{tag}: gst decode: {stderr}");
2649+ }
2650+ let _ = fs::remove_file(&path);
2651+ }
2652+
2653+ let speech = stereo_speech_pair();
2654+ let (_, packets) = hybrid_roundtrip_shape(&speech, 2, 960, 64_000, None);
2655+ let toc = ec_opus::Toc::new(packets[0][0]);
2656+ assert_eq!(toc.mode(), ec_opus::Mode::Hybrid);
2657+ assert!(toc.stereo);
2658+}