forge
Explore
Log in

Don't you dare go Hollow

Repair silk auto mode

Browse files at this commit

04dded9d306611814cb8043ebd9558b260e5bfc3Ahmet Kaan GümüşParent: 43dd76b
  • fix
    • repair silk auto mode
Show full message
fix(opus): repair silk auto mode
crates/ec-opus/src/encoder.rsmodified+132 -29
@@ -4,10 +4,10 @@
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), SILK6 //! default) picks CELT (TOC configs 16..31, every rate and frame size), SILK
7-//! (TOC configs 0/1/4/5/8/9, mono or stereo NB/MB/WB 10 or 20 ms; mono also7+//! (TOC configs 0..11, mono NB/MB/WB 10/20/40/60 ms; stereo NB/MB/WB 10/20 ms,
8-//! 40/60 ms through [`SilkEncoder`]), or Hybrid (TOC configs 13/15, mono8+//! with 40/60 ms carried as code-3 packets of 20 ms SILK frames), or Hybrid
9-//! SWB/FB 20 ms: SILK at 16 kHz under CELT from band 17 up, one range-coded9+//! (TOC configs 13/15, mono or stereo SWB/FB 10 or 20 ms: SILK at 16 kHz under
10-//! stream; stereo and other frame sizes fall back to CELT).10+//! CELT from band 17 up, one range-coded stream).
11 //!11 //!
12 //! 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
13 //! 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
@@ -28,6 +28,7 @@ use crate::silk_enc_write::{SilkEncoder, SilkStereoEncoder};
28 28
29 /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`).29 /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`).
30 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;
31 32
32 /// SILK's round-trip algorithmic delay in 48 kHz samples: the analysis33 /// SILK's round-trip algorithmic delay in 48 kHz samples: the analysis
33 /// resampler (`SilkEncoder::delay_samples`) on the way in plus the decoder's34 /// resampler (`SilkEncoder::delay_samples`) on the way in plus the decoder's
@@ -84,9 +85,9 @@ pub struct Encoder {
84 silk_stereo_nb: Option<SilkStereoEncoder>,85 silk_stereo_nb: Option<SilkStereoEncoder>,
85 silk_stereo_mb: Option<SilkStereoEncoder>,86 silk_stereo_mb: Option<SilkStereoEncoder>,
86 silk_stereo_wb: Option<SilkStereoEncoder>,87 silk_stereo_wb: Option<SilkStereoEncoder>,
87- /// Scratch space for the SILK payload, sized once so the steady-state88+ /// Scratch space for the SILK packet payload, sized once so the steady-state
88 /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate.89 /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate.
89- silk_buf: [u8; MAX_FRAME_BYTES + 1],90+ silk_buf: [u8; MAX_SILK_PACKET_BYTES],
90 /// 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.
91 silk_delay: Vec<f32>,92 silk_delay: Vec<f32>,
92 /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so93 /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so
@@ -137,7 +138,7 @@ impl Encoder {
137 silk_stereo_nb: None,138 silk_stereo_nb: None,
138 silk_stereo_mb: None,139 silk_stereo_mb: None,
139 silk_stereo_wb: None,140 silk_stereo_wb: None,
140- silk_buf: [0u8; MAX_FRAME_BYTES + 1],141+ silk_buf: [0u8; MAX_SILK_PACKET_BYTES],
141 silk_delay: Vec::new(),142 silk_delay: Vec::new(),
142 silk_stuff: Vec::new(),143 silk_stuff: Vec::new(),
143 })144 })
@@ -146,7 +147,7 @@ impl Encoder {
146 /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and147 /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and
147 /// `hybrid_choice` make from the application and bitrate; pass `None` to148 /// `hybrid_choice` make from the application and bitrate; pass `None` to
148 /// restore the automatic pick. Requests this encoder cannot honour149 /// restore the automatic pick. Requests this encoder cannot honour
149- /// (SILK longer than 20 ms through this wrapper or 10 ms Hybrid) fall back to CELT.150+ /// (10 ms Hybrid) fall back to CELT.
150 pub fn set_mode(&mut self, mode: Option<Mode>) {151 pub fn set_mode(&mut self, mode: Option<Mode>) {
151 self.mode = mode;152 self.mode = mode;
152 }153 }
@@ -165,15 +166,14 @@ impl Encoder {
165 /// channel, native rate) frame: the decoded stream lags the input by166 /// channel, native rate) frame: the decoded stream lags the input by
166 /// 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`
167 /// 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.
168- /// 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
169 /// explicit [`Encoder::set_mode`] select it — the same170 /// explicit [`Encoder::set_mode`] select it — the same
170 /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches171 /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches
171 /// on, so this always matches which layer actually codes the frame):172 /// on, so this always matches which layer actually codes the frame):
172 /// [`SILK_LOOK_AHEAD_48K_NB`], [`SILK_LOOK_AHEAD_48K_MB`] or173 /// [`SILK_LOOK_AHEAD_48K_NB`], [`SILK_LOOK_AHEAD_48K_MB`] or
173 /// [`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
174 /// delayed to meet it ([`HYBRID_SILK_DELAY_48K`]). Any other frame size175 /// delayed to meet it ([`HYBRID_SILK_DELAY_48K`]). Any other frame size
175- /// (or SILK/Hybrid's mono requirement unmet) falls back to CELT here176+ /// falls back to CELT here exactly as `encode_toc_and_payload` does.
176- /// exactly as `encode_toc_and_payload` does.
177 pub fn look_ahead(&self, frame_size: usize) -> usize {177 pub fn look_ahead(&self, frame_size: usize) -> usize {
178 let frame_48k = frame_size * self.upsample;178 let frame_48k = frame_size * self.upsample;
179 if let Some(fs_khz) = self.silk_choice(frame_48k) {179 if let Some(fs_khz) = self.silk_choice(frame_48k) {
@@ -244,26 +244,30 @@ impl Encoder {
244 Some(Mode::Celt) | Some(Mode::Hybrid) => None,244 Some(Mode::Celt) | Some(Mode::Hybrid) => None,
245 Some(Mode::Silk) => Some(forced()),245 Some(Mode::Silk) => Some(forced()),
246 None => {246 None => {
247- if self.application == Application::Voip && self.bitrate < 20_000 {247+ if self.application == Application::Voip {
248- Some(if matches!(self.bandwidth, Some(Bandwidth::Medium)) {248+ let per_channel = self.bitrate / self.channels as u32;
249- 12249+ if per_channel < 20_000 {
250- } else if self.bitrate > 10_000 {250+ return Some(match self.bandwidth {
251- 16251+ Some(Bandwidth::Narrow) => 8,
252- } else {252+ Some(Bandwidth::Medium) => 12,
253- 8253+ Some(_) => 16,
254- })254+ None if per_channel <= 12_000 => 8,
255- } else {255+ None if per_channel <= 16_000 => 12,
256- None256+ None => 16,
257+ });
258+ }
257 }259 }
260+ None
258 }261 }
259 }262 }
260 }263 }
261 264
262 /// `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:
263- /// mono or stereo, 10 or 20 ms (480 or 960 samples at 48 kHz) frames.266+ /// mono 10/20/40/60 ms, stereo 10/20 ms directly, or stereo 40/60 ms as
267+ /// code-3 packets of 20 ms SILK frames.
264 fn silk_choice(&self, frame_48k: usize) -> Option<usize> {268 fn silk_choice(&self, frame_48k: usize) -> Option<usize> {
265 let fs_khz = self.wants_silk()?;269 let fs_khz = self.wants_silk()?;
266- if !matches!(frame_48k, 480 | 960) {270+ if !matches!(frame_48k, 480 | 960 | 1920 | 2880) {
267 return None;271 return None;
268 }272 }
269 Some(fs_khz)273 Some(fs_khz)
@@ -275,12 +279,13 @@ impl Encoder {
275 /// is the better speech coder too), at the bitrate's own bandwidth279 /// is the better speech coder too), at the bitrate's own bandwidth
276 /// (SWB/FB; narrower requests are CELT's). Mono and stereo, 10 or 20 ms.280 /// (SWB/FB; narrower requests are CELT's). Mono and stereo, 10 or 20 ms.
277 fn hybrid_choice(&self, frame_48k: usize) -> Option<Bandwidth> {281 fn hybrid_choice(&self, frame_48k: usize) -> Option<Bandwidth> {
278- let lo = 20_000 * self.channels as u32;282+ let per_channel = self.bitrate / self.channels as u32;
279- let hi = 40_000 * self.channels as u32;
280 let wanted = match self.mode {283 let wanted = match self.mode {
281 Some(Mode::Hybrid) => true,284 Some(Mode::Hybrid) => true,
282 Some(_) => false,285 Some(_) => false,
283- None => self.application == Application::Voip && (lo..hi).contains(&self.bitrate),286+ None => {
287+ self.application == Application::Voip && (20_000..40_000).contains(&per_channel)
288+ }
284 };289 };
285 if !wanted || !matches!(frame_48k, 480 | 960) {290 if !wanted || !matches!(frame_48k, 480 | 960) {
286 return None;291 return None;
@@ -360,6 +365,79 @@ impl Encoder {
360 }365 }
361 }366 }
362 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+
363 /// 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
364 /// byte and the payload bytes (excluding TOC), borrowed from scratch442 /// byte and the payload bytes (excluding TOC), borrowed from scratch
365 /// space owned by `self` — no allocation on the steady-state path.443 /// space owned by `self` — no allocation on the steady-state path.
@@ -375,6 +453,9 @@ impl Encoder {
375 if let Some(fs_khz) = self.silk_choice(frame_48k) {453 if let Some(fs_khz) = self.silk_choice(frame_48k) {
376 if self.channels == 2 {454 if self.channels == 2 {
377 Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);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+ }
378 let enc = match fs_khz {459 let enc = match fs_khz {
379 8 => self460 8 => self
380 .silk_stereo_nb461 .silk_stereo_nb
@@ -570,8 +651,7 @@ impl Encoder {
570 let cap = cap.min(MAX_FRAME_BYTES);651 let cap = cap.min(MAX_FRAME_BYTES);
571 let frame_48k = frame_size * self.upsample;652 let frame_48k = frame_size * self.upsample;
572 let frame_ms = frame_48k / 48;653 let frame_ms = frame_48k / 48;
573- let budget =654+ let budget = ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize;
574- ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize;
575 let budget = budget.saturating_sub(1).clamp(2, cap);655 let budget = budget.saturating_sub(1).clamp(2, cap);
576 if cap < HYBRID_CELT_MIN_BYTES + 2 {656 if cap < HYBRID_CELT_MIN_BYTES + 2 {
577 return Err(Error::corrupt(657 return Err(Error::corrupt(
@@ -713,7 +793,7 @@ mod tests {
713 assert_eq!(e.look_ahead(960), 58, "20ms NB SILK");793 assert_eq!(e.look_ahead(960), 58, "20ms NB SILK");
714 794
715 e.set_bitrate(16000);795 e.set_bitrate(16000);
716- assert_eq!(e.look_ahead(960), 50, "20ms WB SILK");796+ assert_eq!(e.look_ahead(960), 54, "20ms MB SILK");
717 797
718 e.set_bitrate(32000);798 e.set_bitrate(32000);
719 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");
@@ -724,4 +804,27 @@ mod tests {
724 e.set_bitrate(64_000);804 e.set_bitrate(64_000);
725 assert_eq!(e.look_ahead(960), 120, "stereo 20ms hybrid");805 assert_eq!(e.look_ahead(960), 120, "stereo 20ms hybrid");
726 }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+ }
829+ }
727 }830 }
crates/ec-opus/src/silk_enc_write.rsmodified+18 -8
@@ -181,6 +181,7 @@ impl SilkEncoder {
181 None,181 None,
182 conditional,182 conditional,
183 prev_signal_type,183 prev_signal_type,
184+ frames_per_packet == 1,
184 )?;185 )?;
185 prev_signal_type = trial.signal_type;186 prev_signal_type = trial.signal_type;
186 frames.push(trial);187 frames.push(trial);
@@ -238,7 +239,7 @@ impl SilkEncoder {
238 enc: &mut RangeEncoder,239 enc: &mut RangeEncoder,
239 frame_ms: usize,240 frame_ms: usize,
240 ) -> Result<()> {241 ) -> Result<()> {
241- let trial = self.encode_inner(pcm48, frame_ms, Some(enc), false, 0)?;242+ let trial = self.encode_inner(pcm48, frame_ms, Some(enc), false, 0, true)?;
242 self.voiced_frames += usize::from(trial.voiced);243 self.voiced_frames += usize::from(trial.voiced);
243 Ok(())244 Ok(())
244 }245 }
@@ -288,6 +289,7 @@ impl SilkEncoder {
288 shared: Option<&mut RangeEncoder>,289 shared: Option<&mut RangeEncoder>,
289 conditional: bool,290 conditional: bool,
290 prev_signal_type: i32,291 prev_signal_type: i32,
292+ single_frame_packet: bool,
291 ) -> Result<Trial> {293 ) -> Result<Trial> {
292 assert!(294 assert!(
293 matches!(frame_ms, 10 | 20),295 matches!(frame_ms, 10 | 20),
@@ -485,9 +487,9 @@ impl SilkEncoder {
485 // vector that best predicts the residual from the *reconstructed*487 // vector that best predicts the residual from the *reconstructed*
486 // history, then quantise sample by sample with the shaped output error488 // history, then quantise sample by sample with the shaped output error
487 // 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.
488- let pulse_lambda = match (frame_ms, fs) {490+ let pulse_lambda = match (single_frame_packet, frame_ms, fs) {
489- (20, 8) => 1.25,491+ (true, 20, 8) => 1.25,
490- (10, 16) => 1.45,492+ (_, 10, 16) => 1.45,
491 _ => PULSE_LAMBDA,493 _ => PULSE_LAMBDA,
492 };494 };
493 let run = |per: usize, gains_q16: &[i32; MAX_NB_SUBFR]| -> Run {495 let run = |per: usize, gains_q16: &[i32; MAX_NB_SUBFR]| -> Run {
@@ -786,8 +788,12 @@ impl SilkStereoEncoder {
786 side.push(s);788 side.push(s);
787 side_energy += s * s;789 side_energy += s * s;
788 }790 }
789- let mid_trial = self.mid.encode_inner(&mid, frame_ms, None, false, 0)?;791+ let mid_trial = self
790- let side_trial = self.side.encode_inner(&side, frame_ms, None, false, 0)?;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)?;
791 let mid_only = side_energy < 1.0e-10;797 let mid_only = side_energy < 1.0e-10;
792 write_stereo_packet_header(enc, &mid_trial, &side_trial, mid_only);798 write_stereo_packet_header(enc, &mid_trial, &side_trial, mid_only);
793 write_stereo_zero_pred(enc);799 write_stereo_zero_pred(enc);
@@ -842,8 +848,12 @@ impl SilkStereoEncoder {
842 side.push(s);848 side.push(s);
843 side_energy += s * s;849 side_energy += s * s;
844 }850 }
845- let mid_trial = self.mid.encode_inner(&mid, frame_ms, None, false, 0)?;851+ let mid_trial = self
846- let side_trial = self.side.encode_inner(&side, frame_ms, None, false, 0)?;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)?;
847 let mid_only = side_energy < 1.0e-10;857 let mid_only = side_energy < 1.0e-10;
848 858
849 self.range.reset(1275);859 self.range.reset(1275);
crates/ec-opus/tests/conformance.rsmodified+387 -56
@@ -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 mono selects Hybrid, and Audio at any rate stays
881-/// on CELT.
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
@@ -1751,7 +2056,7 @@ fn silk_mediumband_and_10ms_roundtrip() {
1751 fn silk_multiframe_packets_roundtrip() {2056 fn silk_multiframe_packets_roundtrip() {
1752 let full = speech_like();2057 let full = speech_like();
1753 let pcm = &full[..46_080];2058 let pcm = &full[..46_080];
1754- for (tag, enc, frame_ms, config, cutoff, bps) in [2059+ for (tag, enc, frame_ms, config, cutoff, bps, floor) in [
1755 (2060 (
1756 "NB40",2061 "NB40",
1757 SilkEncoder::new(false),2062 SilkEncoder::new(false),
@@ -1759,10 +2064,19 @@ fn silk_multiframe_packets_roundtrip() {
1759 2u8,2064 2u8,
1760 3500.0,2065 3500.0,
1761 16_000u32,2066 16_000u32,
2067+ 0.9329f64,
1762 ),2068 ),
1763- ("MB40", SilkEncoder::new_mediumband(), 40, 6, 5500.0, 20_000),2069+ (
1764- ("WB40", SilkEncoder::new(true), 40, 10, 7000.0, 24_000),2070+ "MB40",
1765- ("WB60", SilkEncoder::new(true), 60, 11, 7000.0, 24_000),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),
1766 ] {2080 ] {
1767 let (decoded, packets, voiced) = silk_roundtrip_ms(enc, pcm, frame_ms, Some(bps));2081 let (decoded, packets, voiced) = silk_roundtrip_ms(enc, pcm, frame_ms, Some(bps));
1768 let toc = ec_opus::Toc::new(packets[0][0]);2082 let toc = ec_opus::Toc::new(packets[0][0]);
@@ -1776,7 +2090,7 @@ fn silk_multiframe_packets_roundtrip() {
1776 "silk {tag}: corr {corr:.4} at lag {lag}, voiced {voiced}/{} frames, {kbps:.2} kbps",2090 "silk {tag}: corr {corr:.4} at lag {lag}, voiced {voiced}/{} frames, {kbps:.2} kbps",
1777 packets.len()2091 packets.len()
1778 );2092 );
1779- assert!(corr >= 0.70, "{tag}: corr {corr:.4}");2093+ assert!(corr >= floor, "{tag}: corr {corr:.4} below {floor:.4}");
1780 assert!(voiced > 0, "{tag}: no frame coded with LTP");2094 assert!(voiced > 0, "{tag}: no frame coded with LTP");
1781 if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len()) {2095 if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len()) {
1782 let (c, _) = aligned_corr(&oracle, &decoded, 2500);2096 let (c, _) = aligned_corr(&oracle, &decoded, 2500);
@@ -1827,13 +2141,25 @@ fn aligned_channel_corr(reference: &[f32], decoded: &[f32], channels: usize, ch:
1827 fn silk_stereo_speech_roundtrip() {2141 fn silk_stereo_speech_roundtrip() {
1828 let pcm = stereo_speech_pair();2142 let pcm = stereo_speech_pair();
1829 let total = pcm.len() / 2;2143 let total = pcm.len() / 2;
1830- for (tag, bandwidth, per_channel_bps, cutoff, config) in [2144+ for (tag, bandwidth, per_channel_bps, cutoff, frame, config, code, frames) in [
1831- ("NB20", Bandwidth::Narrow, 16_000u32, 3500.0, 1u8),2145+ (
1832- ("MB20", Bandwidth::Medium, 20_000, 5500.0, 5),2146+ "NB20",
1833- ("WB20", Bandwidth::Wide, 24_000, 7000.0, 9),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),
1834 ] {2160 ] {
1835- let frame = if tag.ends_with("10") { 480 } else { 960 };
1836 let frame_ms = frame / 48;2161 let frame_ms = frame / 48;
2162+ let mono_frame_ms = frame_ms.min(20);
1837 let mut mono_floor = [0.0f64; 2];2163 let mut mono_floor = [0.0f64; 2];
1838 for ch in 0..2 {2164 for ch in 0..2 {
1839 let mono: Vec<f32> = pcm.chunks_exact(2).map(|f| f[ch]).collect();2165 let mono: Vec<f32> = pcm.chunks_exact(2).map(|f| f[ch]).collect();
@@ -1843,7 +2169,8 @@ fn silk_stereo_speech_roundtrip() {
1843 _ => SilkEncoder::new(true),2169 _ => SilkEncoder::new(true),
1844 };2170 };
1845 let reference = lowpass(&mono, cutoff);2171 let reference = lowpass(&mono, cutoff);
1846- let (decoded, _, _) = silk_roundtrip_ms(silk, &mono, frame_ms, Some(per_channel_bps));2172+ let (decoded, _, _) =
2173+ silk_roundtrip_ms(silk, &mono, mono_frame_ms, Some(per_channel_bps));
1847 mono_floor[ch] = aligned_corr(&reference, &decoded, 2000).0;2174 mono_floor[ch] = aligned_corr(&reference, &decoded, 2000).0;
1848 }2175 }
1849 let mut enc = Encoder::new(48000, 2, Application::Voip).unwrap();2176 let mut enc = Encoder::new(48000, 2, Application::Voip).unwrap();
@@ -1851,7 +2178,7 @@ fn silk_stereo_speech_roundtrip() {
1851 enc.set_bandwidth(Some(bandwidth));2178 enc.set_bandwidth(Some(bandwidth));
1852 enc.set_bitrate(per_channel_bps * 2);2179 enc.set_bitrate(per_channel_bps * 2);
1853 let mut dec = Decoder::new(48000, 2).unwrap();2180 let mut dec = Decoder::new(48000, 2).unwrap();
1854- let mut out = vec![0u8; 1500];2181+ let mut out = vec![0u8; 4096];
1855 let mut buf = vec![0.0f32; 5760 * 2];2182 let mut buf = vec![0.0f32; 5760 * 2];
1856 let mut decoded = Vec::new();2183 let mut decoded = Vec::new();
1857 let mut packets = Vec::new();2184 let mut packets = Vec::new();
@@ -1859,8 +2186,12 @@ fn silk_stereo_speech_roundtrip() {
1859 padded.resize(pcm.len().div_ceil(frame * 2) * frame * 2 + frame * 2, 0.0);2186 padded.resize(pcm.len().div_ceil(frame * 2) * frame * 2 + frame * 2, 0.0);
1860 for block in padded.chunks(frame * 2) {2187 for block in padded.chunks(frame * 2) {
1861 let len = enc.encode_float(block, frame, &mut out).expect("encode");2188 let len = enc.encode_float(block, frame, &mut out).expect("encode");
1862- let toc = ec_opus::Toc::new(out[0]);2189+ let packet = Packet::parse(&out[..len], false).unwrap();
2190+ let toc = packet.toc;
1863 assert_eq!(toc.config, config, "{tag}: wrong TOC config");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");
1864 assert!(toc.stereo, "{tag}: SILK TOC is not stereo");2195 assert!(toc.stereo, "{tag}: SILK TOC is not stereo");
1865 let n = dec.decode_float(&out[..len], &mut buf).expect("decode");2196 let n = dec.decode_float(&out[..len], &mut buf).expect("decode");
1866 assert_eq!(n, frame, "{tag}: decoded frame size");2197 assert_eq!(n, frame, "{tag}: decoded frame size");