forge
Explore
Log in

Don't you dare go Hollow

Add stereo silk packets

Browse files at this commit

4c0ea0aa2f88b62b51082306b011c70e53565049Ahmet Kaan GümüşParent: d8fab20
  • feat
    • add stereo silk packets
Show full message
feat(ec-opus): add stereo silk packets
crates/ec-opus/src/encoder.rsmodified+53 -12
@@ -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/1/4/5/8/9, mono or stereo NB/MB/WB 10 or 20 ms; mono also
8-//! stereo SILK and SILK at other frame sizes fall back to CELT, documented8+//! 40/60 ms through [`SilkEncoder`]), or Hybrid (TOC configs 13/15, mono
9-//! at the fallback site) or Hybrid (TOC configs 13/15, mono SWB/FB 20 ms:9+//! SWB/FB 20 ms: SILK at 16 kHz under CELT from band 17 up, one range-coded
10-//! SILK at 16 kHz under CELT from band 17 up, one range-coded stream;10+//! stream; stereo and other frame sizes fall back to CELT).
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,7 +24,7 @@ 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;
@@ -82,6 +81,9 @@ pub struct Encoder {
82 silk_nb: Option<SilkEncoder>,81 silk_nb: Option<SilkEncoder>,
83 silk_mb: Option<SilkEncoder>,82 silk_mb: Option<SilkEncoder>,
84 silk_wb: Option<SilkEncoder>,83 silk_wb: Option<SilkEncoder>,
84+ silk_stereo_nb: Option<SilkStereoEncoder>,
85+ silk_stereo_mb: Option<SilkStereoEncoder>,
86+ silk_stereo_wb: Option<SilkStereoEncoder>,
85 /// Scratch space for the SILK payload, sized once so the steady-state87 /// Scratch space for the SILK payload, sized once so the steady-state
86 /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate.88 /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate.
87 silk_buf: [u8; MAX_FRAME_BYTES + 1],89 silk_buf: [u8; MAX_FRAME_BYTES + 1],
@@ -132,6 +134,9 @@ impl Encoder {
132 silk_nb: None,134 silk_nb: None,
133 silk_mb: None,135 silk_mb: None,
134 silk_wb: None,136 silk_wb: None,
137+ silk_stereo_nb: None,
138+ silk_stereo_mb: None,
139+ silk_stereo_wb: None,
135 silk_buf: [0u8; MAX_FRAME_BYTES + 1],140 silk_buf: [0u8; MAX_FRAME_BYTES + 1],
136 silk_delay: Vec::new(),141 silk_delay: Vec::new(),
137 silk_stuff: Vec::new(),142 silk_stuff: Vec::new(),
@@ -141,7 +146,7 @@ impl Encoder {
141 /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and146 /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and
142 /// `hybrid_choice` make from the application and bitrate; pass `None` to147 /// `hybrid_choice` make from the application and bitrate; pass `None` to
143 /// restore the automatic pick. Requests this encoder cannot honour148 /// 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.149+ /// (SILK longer than 20 ms through this wrapper or 10 ms Hybrid) fall back to CELT.
145 pub fn set_mode(&mut self, mode: Option<Mode>) {150 pub fn set_mode(&mut self, mode: Option<Mode>) {
146 self.mode = mode;151 self.mode = mode;
147 }152 }
@@ -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 }
@@ -252,11 +260,10 @@ impl Encoder {
252 }260 }
253 261
254 /// `wants_silk` narrowed to what this encoder can actually code as SILK:262 /// `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. Stereo263+ /// mono or stereo, 10 or 20 ms (480 or 960 samples at 48 kHz) frames.
256- /// SILK and longer SILK packets are future work; both fall back to CELT.
257 fn silk_choice(&self, frame_48k: usize) -> Option<usize> {264 fn silk_choice(&self, frame_48k: usize) -> Option<usize> {
258 let fs_khz = self.wants_silk()?;265 let fs_khz = self.wants_silk()?;
259- if self.channels != 1 || !matches!(frame_48k, 480 | 960) {266+ if !matches!(frame_48k, 480 | 960) {
260 return None;267 return None;
261 }268 }
262 Some(fs_khz)269 Some(fs_khz)
@@ -339,6 +346,21 @@ impl Encoder {
339 }346 }
340 }347 }
341 348
349+ fn zero_stuff_stereo(pcm: &[f32], frame_size: usize, upsample: usize, out: &mut Vec<f32>) {
350+ if upsample == 1 {
351+ out.clear();
352+ out.extend_from_slice(&pcm[..2 * frame_size]);
353+ return;
354+ }
355+ out.resize(2 * frame_size * upsample, 0.0);
356+ out.fill(0.0);
357+ for i in 0..frame_size {
358+ let dst = 2 * i * upsample;
359+ out[dst] = pcm[2 * i] * upsample as f32;
360+ out[dst + 1] = pcm[2 * i + 1] * upsample as f32;
361+ }
362+ }
363+
342 /// Picks SILK or CELT for one frame and encodes it, returning the TOC364 /// Picks SILK or CELT for one frame and encodes it, returning the TOC
343 /// byte and the payload bytes (excluding TOC), borrowed from scratch365 /// byte and the payload bytes (excluding TOC), borrowed from scratch
344 /// space owned by `self` — no allocation on the steady-state path.366 /// space owned by `self` — no allocation on the steady-state path.
@@ -352,6 +374,25 @@ impl Encoder {
352 ) -> Result<(u8, &[u8])> {374 ) -> Result<(u8, &[u8])> {
353 let frame_48k = frame_size * self.upsample;375 let frame_48k = frame_size * self.upsample;
354 if let Some(fs_khz) = self.silk_choice(frame_48k) {376 if let Some(fs_khz) = self.silk_choice(frame_48k) {
377+ if self.channels == 2 {
378+ Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);
379+ let enc = match fs_khz {
380+ 8 => self
381+ .silk_stereo_nb
382+ .get_or_insert_with(|| SilkStereoEncoder::new(false)),
383+ 12 => self
384+ .silk_stereo_mb
385+ .get_or_insert_with(SilkStereoEncoder::new_mediumband),
386+ _ => self
387+ .silk_stereo_wb
388+ .get_or_insert_with(|| SilkStereoEncoder::new(true)),
389+ };
390+ enc.set_bitrate(self.bitrate);
391+ let n =
392+ enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf, frame_48k / 48)?;
393+ self.final_range = enc.final_range();
394+ return Ok((self.silk_buf[0], &self.silk_buf[1..n]));
395+ }
355 Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);396 Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);
356 let enc = match fs_khz {397 let enc = match fs_khz {
357 8 => self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)),398 8 => self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)),
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+194 -6
@@ -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,7 +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`]. Stereo is not written yet.15+//! [`SilkEncoder::set_bitrate`].
16 16
17 // 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.
18 #![allow(clippy::needless_range_loop)]18 #![allow(clippy::needless_range_loop)]
@@ -38,7 +38,7 @@ const LEVEL_ADJUST: f32 = 80.0 / 1024.0;
38 /// with 16 such pulses in one block.38 /// with 16 such pulses in one block.
39 const MAX_PULSE: i32 = 1023;39 const MAX_PULSE: i32 = 1023;
40 40
41-/// A mono, 10 or 20 ms, NB/MB/WB SILK encoder.41+/// A mono, 10/20/40/60 ms, NB/MB/WB SILK encoder.
42 #[derive(Clone, Debug)]42 #[derive(Clone, Debug)]
43 pub struct SilkEncoder {43 pub struct SilkEncoder {
44 fs_khz: usize,44 fs_khz: usize,
@@ -127,6 +127,10 @@ impl SilkEncoder {
127 self.target_bps = Some(bps);127 self.target_bps = Some(bps);
128 }128 }
129 129
130+ fn reset_state(&mut self) {
131+ *self = Self::with_fs_khz(self.fs_khz);
132+ }
133+
130 /// Algorithmic delay in 48 kHz samples: the analysis resampler only134 /// Algorithmic delay in 48 kHz samples: the analysis resampler only
131 /// (the decoder adds its own resampler delay on the way back up).135 /// (the decoder adds its own resampler delay on the way back up).
132 pub fn delay_samples(&self) -> usize {136 pub fn delay_samples(&self) -> usize {
@@ -180,6 +184,9 @@ impl SilkEncoder {
180 prev_signal_type = trial.signal_type;184 prev_signal_type = trial.signal_type;
181 frames.push(trial);185 frames.push(trial);
182 }186 }
187+ if frames.iter().any(|frame| frame.voiced) {
188+ self.voiced_frames += 1;
189+ }
183 self.range.reset(1275);190 self.range.reset(1275);
184 let refs: Vec<&Trial> = frames.iter().collect();191 let refs: Vec<&Trial> = frames.iter().collect();
185 write_packet_header(&mut self.range, &refs);192 write_packet_header(&mut self.range, &refs);
@@ -225,8 +232,9 @@ impl SilkEncoder {
225 /// must [`SilkEncoder::replay`] the finished payload so this encoder's232 /// must [`SilkEncoder::replay`] the finished payload so this encoder's
226 /// decoder mirror advances.233 /// decoder mirror advances.
227 pub fn encode_hybrid(&mut self, pcm48: &[f32], enc: &mut RangeEncoder) -> Result<()> {234 pub fn encode_hybrid(&mut self, pcm48: &[f32], enc: &mut RangeEncoder) -> Result<()> {
228- self.encode_inner(pcm48, 20, Some(enc), false, 0)235+ let trial = self.encode_inner(pcm48, 20, Some(enc), false, 0)?;
229- .map(|_| ())236+ self.voiced_frames += usize::from(trial.voiced);
237+ Ok(())
230 }238 }
231 239
232 /// Decodes `payload` (TOC stripped) through the mirror decoder so the next240 /// Decodes `payload` (TOC stripped) through the mirror decoder so the next
@@ -662,7 +670,6 @@ impl SilkEncoder {
662 write_frame_data(enc, trial_ref, conditional, prev_signal_type);670 write_frame_data(enc, trial_ref, conditional, prev_signal_type);
663 }671 }
664 self.prev_gain_index = best.prev_gain_index;672 self.prev_gain_index = best.prev_gain_index;
665- self.voiced_frames += usize::from(voiced);
666 self.shape_d.copy_from_slice(&best.run.d[n..]);673 self.shape_d.copy_from_slice(&best.run.d[n..]);
667 self.shape_u.copy_from_slice(&best.run.u[n..]);674 self.shape_u.copy_from_slice(&best.run.u[n..]);
668 self.shape_gq.copy_from_slice(&best.run.gq[n..]);675 self.shape_gq.copy_from_slice(&best.run.gq[n..]);
@@ -670,6 +677,187 @@ impl SilkEncoder {
670 }677 }
671 }678 }
672 679
680+/// A stereo, 10 or 20 ms, NB/MB/WB SILK encoder.
681+#[derive(Clone, Debug)]
682+pub struct SilkStereoEncoder {
683+ fs_khz: usize,
684+ mid: SilkEncoder,
685+ side: SilkEncoder,
686+ range: RangeEncoder,
687+ mirror: SilkDecoder,
688+ final_range: u32,
689+ mirror_range: u32,
690+ mirror_out: Vec<i16>,
691+ target_bps: Option<u32>,
692+ prev_mid_only: bool,
693+ voiced_frames: usize,
694+}
695+
696+impl SilkStereoEncoder {
697+ /// Narrowband or wideband stereo encoder.
698+ pub fn new(wideband: bool) -> SilkStereoEncoder {
699+ Self::with_fs_khz(if wideband { 16 } else { 8 })
700+ }
701+
702+ /// Mediumband stereo encoder.
703+ pub fn new_mediumband() -> SilkStereoEncoder {
704+ Self::with_fs_khz(12)
705+ }
706+
707+ fn with_fs_khz(fs_khz: usize) -> SilkStereoEncoder {
708+ SilkStereoEncoder {
709+ fs_khz,
710+ mid: SilkEncoder::with_fs_khz(fs_khz),
711+ side: SilkEncoder::with_fs_khz(fs_khz),
712+ range: RangeEncoder::new(),
713+ mirror: SilkDecoder::new(fs_khz as u32 * 1000, 2),
714+ final_range: 0,
715+ mirror_range: 0,
716+ mirror_out: vec![0; 2 * 20 * fs_khz],
717+ target_bps: None,
718+ prev_mid_only: false,
719+ voiced_frames: 0,
720+ }
721+ }
722+
723+ /// The range coder state after the last packet.
724+ pub fn final_range(&self) -> u32 {
725+ self.final_range
726+ }
727+
728+ /// Packets so far coded with a long-term predictor in either channel.
729+ pub fn voiced_frames(&self) -> usize {
730+ self.voiced_frames
731+ }
732+
733+ /// Target bit rate in bits per second for the whole stereo packet.
734+ pub fn set_bitrate(&mut self, bps: u32) {
735+ self.target_bps = Some(bps);
736+ let per_channel = (bps / 2).max(500);
737+ self.mid.set_bitrate(per_channel);
738+ self.side.set_bitrate(per_channel);
739+ }
740+
741+ /// Algorithmic delay in 48 kHz samples.
742+ pub fn delay_samples(&self) -> usize {
743+ self.mid.delay_samples()
744+ }
745+
746+ /// Encodes one 10 or 20 ms interleaved stereo frame at 48 kHz.
747+ pub fn encode_frame_ms(
748+ &mut self,
749+ pcm48: &[f32],
750+ out: &mut [u8],
751+ frame_ms: usize,
752+ ) -> Result<usize> {
753+ assert!(
754+ matches!(frame_ms, 10 | 20),
755+ "SilkStereoEncoder codes 10 or 20 ms stereo frames"
756+ );
757+ assert_eq!(
758+ pcm48.len(),
759+ 2 * 48 * frame_ms,
760+ "SilkStereoEncoder input is 48 kHz stereo"
761+ );
762+ if self.prev_mid_only {
763+ self.side.reset_state();
764+ if let Some(bps) = self.target_bps {
765+ self.side.set_bitrate((bps / 2).max(500));
766+ }
767+ }
768+ let samples = 48 * frame_ms;
769+ let mut mid = Vec::with_capacity(samples);
770+ let mut side = Vec::with_capacity(samples);
771+ let mut side_energy = 0.0f32;
772+ for lr in pcm48.chunks_exact(2) {
773+ let m = 0.5 * (lr[0] + lr[1]);
774+ let s = 0.5 * (lr[0] - lr[1]);
775+ mid.push(m);
776+ side.push(s);
777+ side_energy += s * s;
778+ }
779+ let mid_trial = self.mid.encode_inner(&mid, frame_ms, None, false, 0)?;
780+ let side_trial = self.side.encode_inner(&side, frame_ms, None, false, 0)?;
781+ let mid_only = side_energy < 1.0e-10;
782+
783+ self.range.reset(1275);
784+ write_stereo_packet_header(&mut self.range, &mid_trial, &side_trial, mid_only);
785+ write_stereo_zero_pred(&mut self.range);
786+ if !side_trial.vad_flag {
787+ self.range
788+ .enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8);
789+ }
790+ write_frame_data(&mut self.range, &mid_trial, false, 0);
791+ if !mid_only {
792+ write_frame_data(&mut self.range, &side_trial, false, 0);
793+ }
794+ self.range.done();
795+ debug_assert!(!self.range.error());
796+ let len = self.range.range_bytes();
797+ self.final_range = self.range.range();
798+ let duration = if frame_ms == 10 { 0u8 } else { 1 };
799+ let base = match self.fs_khz {
800+ 8 => 0u8,
801+ 12 => 4,
802+ _ => 8,
803+ };
804+ if out.len() < 1 + len {
805+ return Err(ec_core::Error::corrupt(format!(
806+ "silk stereo encode: packet needs {} bytes, buffer holds {}",
807+ 1 + len,
808+ out.len()
809+ )));
810+ }
811+ out[0] = ((base + duration) << 3) | 0x04;
812+ out[1..1 + len].copy_from_slice(&self.range.data()[..len]);
813+ self.replay_ms(&out[1..1 + len], frame_ms)?;
814+ self.mid.replay_ms(&mid_trial.bytes, frame_ms)?;
815+ if mid_only {
816+ self.side.reset_state();
817+ } else {
818+ self.side.replay_ms(&side_trial.bytes, frame_ms)?;
819+ }
820+ self.prev_mid_only = mid_only;
821+ self.voiced_frames += usize::from(mid_trial.voiced || side_trial.voiced);
822+ debug_assert_eq!(self.mirror_range, self.final_range);
823+ Ok(1 + len)
824+ }
825+
826+ fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
827+ let fs = self.fs_khz;
828+ let mut dec = RangeDecoder::new(payload);
829+ let total = 2 * frame_ms * fs;
830+ if self.mirror_out.len() < total {
831+ self.mirror_out.resize(total, 0);
832+ }
833+ let n = self.mirror.decode(
834+ &mut dec,
835+ &mut self.mirror_out[..total],
836+ frame_ms,
837+ fs as u32 * 1000,
838+ 2,
839+ true,
840+ )?;
841+ debug_assert_eq!(n, frame_ms * fs);
842+ self.mirror_range = dec.range();
843+ Ok(())
844+ }
845+}
846+
847+fn write_stereo_packet_header(enc: &mut RangeEncoder, mid: &Trial, side: &Trial, mid_only: bool) {
848+ enc.enc_bit_logp(mid.vad_flag, 1);
849+ enc.enc_bit_logp(false, 1);
850+ enc.enc_bit_logp(if mid_only { false } else { side.vad_flag }, 1);
851+ enc.enc_bit_logp(false, 1);
852+}
853+
854+fn write_stereo_zero_pred(enc: &mut RangeEncoder) {
855+ enc.enc_icdf(12, &STEREO_PRED_JOINT_ICDF, 8);
856+ enc.enc_icdf(1, &UNIFORM3_ICDF, 8);
857+ enc.enc_icdf(2, &UNIFORM5_ICDF, 8);
858+ enc.enc_icdf(1, &UNIFORM3_ICDF, 8);
859+ enc.enc_icdf(2, &UNIFORM5_ICDF, 8);
860+}
673 /// One closed-loop quantisation of a frame.861 /// One closed-loop quantisation of a frame.
674 struct Run {862 struct Run {
675 ltp_index: [usize; MAX_NB_SUBFR],863 ltp_index: [usize; MAX_NB_SUBFR],
crates/ec-opus/tests/conformance.rsmodified+125 -1
@@ -1037,7 +1037,14 @@ fn encode_packets(enc: &mut Encoder, pcm: &[f32], channels: usize) -> Vec<Vec<u8
1037 }1037 }
1038 1038
1039 fn temp_path(name: &str) -> PathBuf {1039 fn temp_path(name: &str) -> PathBuf {
1040- std::env::temp_dir().join(format!("ec-opus-enc-{}-{name}", std::process::id()))1040+ let root = std::env::var_os("EC_OPUS_SCRATCH")
1041+ .map(PathBuf::from)
1042+ .unwrap_or_else(|| {
1043+ let home = std::env::var_os("HOME").expect("HOME set for encoder scratch");
1044+ PathBuf::from(home).join(".cache/silk2")
1045+ });
1046+ fs::create_dir_all(&root).unwrap();
1047+ root.join(format!("ec-opus-enc-{}-{name}", std::process::id()))
1041 }1048 }
1042 1049
1043 /// The full product rate table, mono and stereo, decoded by libopus: the1050 /// The full product rate table, mono and stereo, decoded by libopus: the
@@ -1799,6 +1806,123 @@ fn silk_multiframe_packets_roundtrip() {
1799 }1806 }
1800 }1807 }
1801 1808
1809+fn stereo_speech_pair() -> Vec<f32> {
1810+ let left = speech_like();
1811+ let mut out = Vec::with_capacity(left.len() * 2);
1812+ for (i, &l) in left.iter().enumerate() {
1813+ let t = i as f64 / 48000.0;
1814+ let r = 0.78 * l + 0.12 * (std::f64::consts::TAU * 310.0 * t).sin() as f32;
1815+ out.push(l);
1816+ out.push(r);
1817+ }
1818+ out
1819+}
1820+
1821+fn aligned_channel_corr(reference: &[f32], decoded: &[f32], channels: usize, ch: usize) -> f64 {
1822+ let b: Vec<f32> = decoded.chunks_exact(channels).map(|f| f[ch]).collect();
1823+ aligned_corr(reference, &b, 2000).0
1824+}
1825+
1826+#[test]
1827+fn silk_stereo_speech_roundtrip() {
1828+ let pcm = stereo_speech_pair();
1829+ 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),
1834+ ] {
1835+ let frame = if tag.ends_with("10") { 480 } else { 960 };
1836+ let frame_ms = frame / 48;
1837+ let mut mono_floor = [0.0f64; 2];
1838+ for ch in 0..2 {
1839+ let mono: Vec<f32> = pcm.chunks_exact(2).map(|f| f[ch]).collect();
1840+ let silk = match bandwidth {
1841+ Bandwidth::Narrow => SilkEncoder::new(false),
1842+ Bandwidth::Medium => SilkEncoder::new_mediumband(),
1843+ _ => SilkEncoder::new(true),
1844+ };
1845+ let reference = lowpass(&mono, cutoff);
1846+ let (decoded, _, _) = silk_roundtrip_ms(silk, &mono, frame_ms, Some(per_channel_bps));
1847+ mono_floor[ch] = aligned_corr(&reference, &decoded, 2000).0;
1848+ }
1849+
1850+ let mut enc = Encoder::new(48000, 2, Application::Voip).unwrap();
1851+ enc.set_mode(Some(ec_opus::Mode::Silk));
1852+ enc.set_bandwidth(Some(bandwidth));
1853+ enc.set_bitrate(per_channel_bps * 2);
1854+ let mut dec = Decoder::new(48000, 2).unwrap();
1855+ let mut out = vec![0u8; 1500];
1856+ let mut buf = vec![0.0f32; 5760 * 2];
1857+ let mut decoded = Vec::new();
1858+ let mut packets = Vec::new();
1859+ let mut padded = pcm.clone();
1860+ padded.resize(pcm.len().div_ceil(frame * 2) * frame * 2 + frame * 2, 0.0);
1861+ for block in padded.chunks(frame * 2) {
1862+ let len = enc.encode_float(block, frame, &mut out).expect("encode");
1863+ let toc = ec_opus::Toc::new(out[0]);
1864+ assert_eq!(toc.config, config, "{tag}: wrong TOC config");
1865+ assert!(toc.stereo, "{tag}: SILK TOC is not stereo");
1866+ let n = dec.decode_float(&out[..len], &mut buf).expect("decode");
1867+ assert_eq!(n, frame, "{tag}: decoded frame size");
1868+ assert_eq!(dec.final_range(), enc.final_range(), "{tag}: range state");
1869+ decoded.extend_from_slice(&buf[..n * 2]);
1870+ packets.push(out[..len].to_vec());
1871+ }
1872+ let bytes: usize = packets.iter().map(Vec::len).sum();
1873+ let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64);
1874+ for ch in 0..2 {
1875+ let source: Vec<f32> = pcm.chunks_exact(2).map(|f| f[ch]).collect();
1876+ let reference = lowpass(&source, cutoff);
1877+ let corr = aligned_channel_corr(&reference, &decoded, 2, ch);
1878+ eprintln!(
1879+ "silk stereo {tag} ch{ch}: corr {corr:.4}, mono {:.4}, {kbps:.2} kbps",
1880+ mono_floor[ch]
1881+ );
1882+ assert!(
1883+ corr + 0.01 >= mono_floor[ch],
1884+ "{tag} ch{ch}: stereo corr {corr:.4} trails mono {:.4}",
1885+ mono_floor[ch]
1886+ );
1887+ }
1888+ if Command::new("ffmpeg").arg("-version").output().is_ok() {
1889+ let path = temp_path(&format!("silk-stereo-{tag}.opus"));
1890+ write_ogg_opus(
1891+ &path,
1892+ &packets,
1893+ opus_head(2, enc.look_ahead(frame) as u16, None),
1894+ 2,
1895+ total,
1896+ enc.look_ahead(frame) as i64,
1897+ );
1898+ let out = Command::new("ffmpeg")
1899+ .args(["-v", "warning", "-c:a", "libopus", "-i"])
1900+ .arg(&path)
1901+ .args(["-f", "null", "-"])
1902+ .output()
1903+ .unwrap();
1904+ let stderr = String::from_utf8_lossy(&out.stderr);
1905+ assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}");
1906+ if Command::new("gst-launch-1.0")
1907+ .arg("--version")
1908+ .output()
1909+ .is_ok()
1910+ {
1911+ let location = format!("location={}", path.display());
1912+ let out = Command::new("gst-launch-1.0")
1913+ .args([
1914+ "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!",
1915+ "fakesink",
1916+ ])
1917+ .output()
1918+ .unwrap();
1919+ let stderr = String::from_utf8_lossy(&out.stderr);
1920+ assert!(out.status.success(), "{tag}: gst decode: {stderr}");
1921+ }
1922+ let _ = fs::remove_file(&path);
1923+ }
1924+ }
1925+}
1802 #[test]1926 #[test]
1803 fn silk_compares_to_celt_on_speech_at_speech_rates() {1927 fn silk_compares_to_celt_on_speech_at_speech_rates() {
1804 let pcm = speech_like();1928 let pcm = speech_like();