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 @@
44 //! or the self-delimited variant of Appendix B that the multistream framing
55 //! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s
66 //! 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 also
8-//! 40/60 ms through [`SilkEncoder`]), or Hybrid (TOC configs 13/15, mono
9-//! SWB/FB 20 ms: SILK at 16 kHz under CELT from band 17 up, one range-coded
10-//! stream; stereo and other frame sizes fall back to CELT).
7+//! (TOC configs 0..11, mono NB/MB/WB 10/20/40/60 ms; stereo NB/MB/WB 10/20 ms,
8+//! with 40/60 ms carried as code-3 packets of 20 ms SILK frames), or Hybrid
9+//! (TOC configs 13/15, mono or stereo SWB/FB 10 or 20 ms: SILK at 16 kHz under
10+//! CELT from band 17 up, one range-coded stream).
1111 //!
1212 //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and
1313 //! 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};
2828
2929 /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`).
3030 const MAX_FRAME_BYTES: usize = 1275;
31+const MAX_SILK_PACKET_BYTES: usize = 1 + 1 + 2 * 2 + 3 * MAX_FRAME_BYTES;
3132
3233 /// SILK's round-trip algorithmic delay in 48 kHz samples: the analysis
3334 /// resampler (`SilkEncoder::delay_samples`) on the way in plus the decoder's
@@ -84,9 +85,9 @@ pub struct Encoder {
8485 silk_stereo_nb: Option<SilkStereoEncoder>,
8586 silk_stereo_mb: Option<SilkStereoEncoder>,
8687 silk_stereo_wb: Option<SilkStereoEncoder>,
87- /// Scratch space for the SILK payload, sized once so the steady-state
88+ /// Scratch space for the SILK packet payload, sized once so the steady-state
8889 /// 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],
9091 /// Hybrid: the last [`HYBRID_SILK_DELAY_48K`] samples of SILK-layer input.
9192 silk_delay: Vec<f32>,
9293 /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so
@@ -137,7 +138,7 @@ impl Encoder {
137138 silk_stereo_nb: None,
138139 silk_stereo_mb: None,
139140 silk_stereo_wb: None,
140- silk_buf: [0u8; MAX_FRAME_BYTES + 1],
141+ silk_buf: [0u8; MAX_SILK_PACKET_BYTES],
141142 silk_delay: Vec::new(),
142143 silk_stuff: Vec::new(),
143144 })
@@ -146,7 +147,7 @@ impl Encoder {
146147 /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and
147148 /// `hybrid_choice` make from the application and bitrate; pass `None` to
148149 /// 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.
150151 pub fn set_mode(&mut self, mode: Option<Mode>) {
151152 self.mode = mode;
152153 }
@@ -165,15 +166,14 @@ impl Encoder {
165166 /// channel, native rate) frame: the decoded stream lags the input by
166167 /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate`
167168 /// 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 an
169+ /// SILK (10, 20, 40 or 60 ms frames, when the application/bitrate or an
169170 /// explicit [`Encoder::set_mode`] select it — the same
170171 /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches
171172 /// on, so this always matches which layer actually codes the frame):
172173 /// [`SILK_LOOK_AHEAD_48K_NB`], [`SILK_LOOK_AHEAD_48K_MB`] or
173174 /// [`SILK_LOOK_AHEAD_48K_WB`]. Hybrid: CELT's 120, the SILK layer being
174175 /// delayed to meet it ([`HYBRID_SILK_DELAY_48K`]). Any other frame size
175- /// (or SILK/Hybrid's mono requirement unmet) falls back to CELT here
176- /// exactly as `encode_toc_and_payload` does.
176+ /// falls back to CELT here exactly as `encode_toc_and_payload` does.
177177 pub fn look_ahead(&self, frame_size: usize) -> usize {
178178 let frame_48k = frame_size * self.upsample;
179179 if let Some(fs_khz) = self.silk_choice(frame_48k) {
@@ -244,26 +244,30 @@ impl Encoder {
244244 Some(Mode::Celt) | Some(Mode::Hybrid) => None,
245245 Some(Mode::Silk) => Some(forced()),
246246 None => {
247- if self.application == Application::Voip && self.bitrate < 20_000 {
248- Some(if matches!(self.bandwidth, Some(Bandwidth::Medium)) {
249- 12
250- } else if self.bitrate > 10_000 {
251- 16
252- } else {
253- 8
254- })
255- } else {
256- None
247+ if self.application == Application::Voip {
248+ let per_channel = self.bitrate / self.channels as u32;
249+ if per_channel < 20_000 {
250+ return Some(match self.bandwidth {
251+ Some(Bandwidth::Narrow) => 8,
252+ Some(Bandwidth::Medium) => 12,
253+ Some(_) => 16,
254+ None if per_channel <= 12_000 => 8,
255+ None if per_channel <= 16_000 => 12,
256+ None => 16,
257+ });
258+ }
257259 }
260+ None
258261 }
259262 }
260263 }
261264
262265 /// `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.
264268 fn silk_choice(&self, frame_48k: usize) -> Option<usize> {
265269 let fs_khz = self.wants_silk()?;
266- if !matches!(frame_48k, 480 | 960) {
270+ if !matches!(frame_48k, 480 | 960 | 1920 | 2880) {
267271 return None;
268272 }
269273 Some(fs_khz)
@@ -275,12 +279,13 @@ impl Encoder {
275279 /// is the better speech coder too), at the bitrate's own bandwidth
276280 /// (SWB/FB; narrower requests are CELT's). Mono and stereo, 10 or 20 ms.
277281 fn hybrid_choice(&self, frame_48k: usize) -> Option<Bandwidth> {
278- let lo = 20_000 * self.channels as u32;
279- let hi = 40_000 * self.channels as u32;
282+ let per_channel = self.bitrate / self.channels as u32;
280283 let wanted = match self.mode {
281284 Some(Mode::Hybrid) => true,
282285 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+ }
284289 };
285290 if !wanted || !matches!(frame_48k, 480 | 960) {
286291 return None;
@@ -360,6 +365,79 @@ impl Encoder {
360365 }
361366 }
362367
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+
363441 /// Picks SILK or CELT for one frame and encodes it, returning the TOC
364442 /// byte and the payload bytes (excluding TOC), borrowed from scratch
365443 /// space owned by `self` — no allocation on the steady-state path.
@@ -375,6 +453,9 @@ impl Encoder {
375453 if let Some(fs_khz) = self.silk_choice(frame_48k) {
376454 if self.channels == 2 {
377455 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+ }
378459 let enc = match fs_khz {
379460 8 => self
380461 .silk_stereo_nb
@@ -570,8 +651,7 @@ impl Encoder {
570651 let cap = cap.min(MAX_FRAME_BYTES);
571652 let frame_48k = frame_size * self.upsample;
572653 let frame_ms = frame_48k / 48;
573- let budget =
574- ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize;
654+ let budget = ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize;
575655 let budget = budget.saturating_sub(1).clamp(2, cap);
576656 if cap < HYBRID_CELT_MIN_BYTES + 2 {
577657 return Err(Error::corrupt(
@@ -713,7 +793,7 @@ mod tests {
713793 assert_eq!(e.look_ahead(960), 58, "20ms NB SILK");
714794
715795 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");
717797
718798 e.set_bitrate(32000);
719799 assert_eq!(e.look_ahead(960), 120, "20ms hybrid, CELT's overlap");
@@ -724,4 +804,27 @@ mod tests {
724804 e.set_bitrate(64_000);
725805 assert_eq!(e.look_ahead(960), 120, "stereo 20ms hybrid");
726806 }
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+ }
727830 }
crates/ec-opus/src/silk_enc_write.rsmodified+18 -8
@@ -181,6 +181,7 @@ impl SilkEncoder {
181181 None,
182182 conditional,
183183 prev_signal_type,
184+ frames_per_packet == 1,
184185 )?;
185186 prev_signal_type = trial.signal_type;
186187 frames.push(trial);
@@ -238,7 +239,7 @@ impl SilkEncoder {
238239 enc: &mut RangeEncoder,
239240 frame_ms: usize,
240241 ) -> 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)?;
242243 self.voiced_frames += usize::from(trial.voiced);
243244 Ok(())
244245 }
@@ -288,6 +289,7 @@ impl SilkEncoder {
288289 shared: Option<&mut RangeEncoder>,
289290 conditional: bool,
290291 prev_signal_type: i32,
292+ single_frame_packet: bool,
291293 ) -> Result<Trial> {
292294 assert!(
293295 matches!(frame_ms, 10 | 20),
@@ -485,9 +487,9 @@ impl SilkEncoder {
485487 // vector that best predicts the residual from the *reconstructed*
486488 // history, then quantise sample by sample with the shaped output error
487489 // fed back into the target, under the decoder's seed-driven sign flips.
488- let pulse_lambda = match (frame_ms, fs) {
489- (20, 8) => 1.25,
490- (10, 16) => 1.45,
490+ let pulse_lambda = match (single_frame_packet, frame_ms, fs) {
491+ (true, 20, 8) => 1.25,
492+ (_, 10, 16) => 1.45,
491493 _ => PULSE_LAMBDA,
492494 };
493495 let run = |per: usize, gains_q16: &[i32; MAX_NB_SUBFR]| -> Run {
@@ -786,8 +788,12 @@ impl SilkStereoEncoder {
786788 side.push(s);
787789 side_energy += s * s;
788790 }
789- let mid_trial = self.mid.encode_inner(&mid, frame_ms, None, false, 0)?;
790- let side_trial = self.side.encode_inner(&side, frame_ms, None, false, 0)?;
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)?;
791797 let mid_only = side_energy < 1.0e-10;
792798 write_stereo_packet_header(enc, &mid_trial, &side_trial, mid_only);
793799 write_stereo_zero_pred(enc);
@@ -842,8 +848,12 @@ impl SilkStereoEncoder {
842848 side.push(s);
843849 side_energy += s * s;
844850 }
845- let mid_trial = self.mid.encode_inner(&mid, frame_ms, None, false, 0)?;
846- let side_trial = self.side.encode_inner(&side, frame_ms, None, false, 0)?;
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)?;
847857 let mid_only = side_energy < 1.0e-10;
848858
849859 self.range.reset(1275);
crates/ec-opus/tests/conformance.rsmodified+387 -56
@@ -772,7 +772,7 @@ fn real_library_sweep() {
772772 // Encoder: self-consistency (range-exact against our own decoder)
773773 // ---------------------------------------------------------------------------
774774
775-use ec_opus::{Application, Bandwidth, Encoder, MultistreamEncoder};
775+use ec_opus::{Application, Bandwidth, Encoder, Mode, MultistreamEncoder, Packet};
776776
777777 /// A deterministic music-like test signal: several detuned partials plus a
778778 /// swept component per channel, loud enough to exercise every band.
@@ -875,52 +875,357 @@ fn encoder_roundtrips_at_every_rate() {
875875 }
876876 }
877877
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.
882878 #[test]
883-fn encoder_mode_follows_application_and_bitrate() {
884- // `None` for the two CELT rows: any CELT config is correct there, the
885- // exact one is `auto_bandwidth`'s call, not mode selection's.
879+fn encoder_mode_follows_application_bitrate_channels_and_frame_size() {
880+ #[derive(Clone, Copy, Debug)]
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+
886895 let cases = [
887- (Application::Voip, 8_000u32, Some(1u8)),
888- (Application::Voip, 16_000, Some(9)),
889- (Application::Audio, 64_000, None),
890- (Application::Voip, 32_000, Some(15)),
891- (Application::Voip, 48_000, None),
896+ Case {
897+ app: Application::Voip,
898+ channels: 1,
899+ bps: 8_000,
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+ },
8921208 ];
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- }
9151209
916- let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap();
917- enc.set_mode(Some(ec_opus::Mode::Silk));
918- enc.set_bandwidth(Some(Bandwidth::Medium));
919- let pcm = vec![0.0f32; 480];
920- let mut out = vec![0u8; 1500];
921- let n = enc.encode_float(&pcm, 480, &mut out).unwrap();
922- assert_eq!(ec_opus::Toc::new(out[0]).config, 4, "forced 10 ms MB SILK");
923- assert!(n > 1, "forced 10 ms MB SILK empty packet");
1210+ for case in cases {
1211+ let mut enc = Encoder::new(48000, case.channels, case.app).unwrap();
1212+ enc.set_bitrate(case.bps);
1213+ enc.set_mode(case.mode_request);
1214+ enc.set_bandwidth(case.bandwidth_request);
1215+ let pcm = vec![0.0f32; case.frame * case.channels];
1216+ let mut out = vec![0u8; 4096];
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+ }
9241229 }
9251230
9261231 /// All four CELT frame sizes survive the loop, and constrained VBR both
@@ -1751,7 +2056,7 @@ fn silk_mediumband_and_10ms_roundtrip() {
17512056 fn silk_multiframe_packets_roundtrip() {
17522057 let full = speech_like();
17532058 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 [
17552060 (
17562061 "NB40",
17572062 SilkEncoder::new(false),
@@ -1759,10 +2064,19 @@ fn silk_multiframe_packets_roundtrip() {
17592064 2u8,
17602065 3500.0,
17612066 16_000u32,
2067+ 0.9329f64,
17622068 ),
1763- ("MB40", SilkEncoder::new_mediumband(), 40, 6, 5500.0, 20_000),
1764- ("WB40", SilkEncoder::new(true), 40, 10, 7000.0, 24_000),
1765- ("WB60", SilkEncoder::new(true), 60, 11, 7000.0, 24_000),
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),
17662080 ] {
17672081 let (decoded, packets, voiced) = silk_roundtrip_ms(enc, pcm, frame_ms, Some(bps));
17682082 let toc = ec_opus::Toc::new(packets[0][0]);
@@ -1776,7 +2090,7 @@ fn silk_multiframe_packets_roundtrip() {
17762090 "silk {tag}: corr {corr:.4} at lag {lag}, voiced {voiced}/{} frames, {kbps:.2} kbps",
17772091 packets.len()
17782092 );
1779- assert!(corr >= 0.70, "{tag}: corr {corr:.4}");
2093+ assert!(corr >= floor, "{tag}: corr {corr:.4} below {floor:.4}");
17802094 assert!(voiced > 0, "{tag}: no frame coded with LTP");
17812095 if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len()) {
17822096 let (c, _) = aligned_corr(&oracle, &decoded, 2500);
@@ -1827,13 +2141,25 @@ fn aligned_channel_corr(reference: &[f32], decoded: &[f32], channels: usize, ch:
18272141 fn silk_stereo_speech_roundtrip() {
18282142 let pcm = stereo_speech_pair();
18292143 let total = pcm.len() / 2;
1830- for (tag, bandwidth, per_channel_bps, cutoff, config) in [
1831- ("NB20", Bandwidth::Narrow, 16_000u32, 3500.0, 1u8),
1832- ("MB20", Bandwidth::Medium, 20_000, 5500.0, 5),
1833- ("WB20", Bandwidth::Wide, 24_000, 7000.0, 9),
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),
18342160 ] {
1835- let frame = if tag.ends_with("10") { 480 } else { 960 };
18362161 let frame_ms = frame / 48;
2162+ let mono_frame_ms = frame_ms.min(20);
18372163 let mut mono_floor = [0.0f64; 2];
18382164 for ch in 0..2 {
18392165 let mono: Vec<f32> = pcm.chunks_exact(2).map(|f| f[ch]).collect();
@@ -1843,7 +2169,8 @@ fn silk_stereo_speech_roundtrip() {
18432169 _ => SilkEncoder::new(true),
18442170 };
18452171 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));
18472174 mono_floor[ch] = aligned_corr(&reference, &decoded, 2000).0;
18482175 }
18492176 let mut enc = Encoder::new(48000, 2, Application::Voip).unwrap();
@@ -1851,7 +2178,7 @@ fn silk_stereo_speech_roundtrip() {
18512178 enc.set_bandwidth(Some(bandwidth));
18522179 enc.set_bitrate(per_channel_bps * 2);
18532180 let mut dec = Decoder::new(48000, 2).unwrap();
1854- let mut out = vec![0u8; 1500];
2181+ let mut out = vec![0u8; 4096];
18552182 let mut buf = vec![0.0f32; 5760 * 2];
18562183 let mut decoded = Vec::new();
18572184 let mut packets = Vec::new();
@@ -1859,8 +2186,12 @@ fn silk_stereo_speech_roundtrip() {
18592186 padded.resize(pcm.len().div_ceil(frame * 2) * frame * 2 + frame * 2, 0.0);
18602187 for block in padded.chunks(frame * 2) {
18612188 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;
18632191 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");
18642195 assert!(toc.stereo, "{tag}: SILK TOC is not stereo");
18652196 let n = dec.decode_float(&out[..len], &mut buf).expect("decode");
18662197 assert_eq!(n, frame, "{tag}: decoded frame size");