forge
Explore
Log in

Don't you dare go Hollow

Finish hybrid mode wiring

Browse files at this commit

38c15e3a7d8d6e68ced7d05cdc6d37c7827a90aaAhmet Kaan GümüşParent: 4c0ea0a
  • feat
    • finish hybrid mode wiring
Show full message
feat(ec-opus): finish hybrid mode wiring
crates/ec-opus/src/encoder.rsmodified+65 -32
@@ -270,20 +270,19 @@ impl Encoder {
270 }270 }
271 271
272 /// Whether this frame goes out as a hybrid packet, and at which of the two272 /// Whether this frame goes out as a hybrid packet, and at which of the two
273- /// hybrid bandwidths. Automatic: VoIP from 20 kbps (where SILK alone273+ /// hybrid bandwidths. Automatic: VoIP from 20 kbps per coded channel
274- /// stops) to 40 kbps (where CELT alone is the better speech coder too),274+ /// (where SILK alone stops) to 40 kbps per coded channel (where CELT alone
275- /// at the bitrate's own bandwidth (SWB/FB; narrower requests are CELT's).275+ /// is the better speech coder too), at the bitrate's own bandwidth
276- /// Mono 20 ms only — stereo Hybrid (which needs stereo SILK) and the276+ /// (SWB/FB; narrower requests are CELT's). Mono and stereo, 10 or 20 ms.
277- /// 10 ms hybrid configs are not implemented and fall back to CELT.
278 fn hybrid_choice(&self, frame_48k: usize) -> Option<Bandwidth> {277 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;
279 let wanted = match self.mode {280 let wanted = match self.mode {
280 Some(Mode::Hybrid) => true,281 Some(Mode::Hybrid) => true,
281 Some(_) => false,282 Some(_) => false,
282- None => {283+ None => self.application == Application::Voip && (lo..hi).contains(&self.bitrate),
283- self.application == Application::Voip && (20_000..40_000).contains(&self.bitrate)
284- }
285 };284 };
286- if !wanted || self.channels != 1 || frame_48k != 960 {285+ if !wanted || !matches!(frame_48k, 480 | 960) {
287 return None;286 return None;
288 }287 }
289 let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth());288 let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth());
@@ -409,12 +408,13 @@ impl Encoder {
409 }408 }
410 if let Some(bandwidth) = self.hybrid_choice(frame_48k) {409 if let Some(bandwidth) = self.hybrid_choice(frame_48k) {
411 let n = self.encode_hybrid(pcm, frame_size, bandwidth, cap)?;410 let n = self.encode_hybrid(pcm, frame_size, bandwidth, cap)?;
412- let config = if bandwidth == Bandwidth::Full {411+ let config = 12
413- 15u8412+ + if bandwidth == Bandwidth::Full { 2u8 } else { 0 }
414- } else {413+ + if frame_48k == 960 { 1 } else { 0 };
415- 13414+ return Ok((
416- };415+ (config << 3) | (u8::from(self.channels == 2) << 2),
417- return Ok((config << 3, &self.range.data()[..n]));416+ &self.range.data()[..n],
417+ ));
418 }418 }
419 let (toc, frame_48k, end) = self.toc(frame_size)?;419 let (toc, frame_48k, end) = self.toc(frame_size)?;
420 let n = self.encode_frame(pcm, frame_48k, end, cap)?;420 let n = self.encode_frame(pcm, frame_48k, end, cap)?;
@@ -553,9 +553,9 @@ impl Encoder {
553 Ok(1 + len_bytes + n)553 Ok(1 + len_bytes + n)
554 }554 }
555 555
556- /// One hybrid frame (mono, 20 ms, `bandwidth` SWB or FB) into the556+ /// One hybrid frame (10 or 20 ms, mono or stereo, `bandwidth` SWB or FB)
557- /// internal range coder, returning its byte length: the SILK layer's557+ /// into the internal range coder, returning its byte length: the SILK
558- /// symbols (WB, 16 kHz internal, fed the input delayed by558+ /// layer's symbols (WB, 16 kHz internal, fed the input delayed by
559 /// [`HYBRID_SILK_DELAY_48K`]), the no-redundancy flag under the decoder's559 /// [`HYBRID_SILK_DELAY_48K`]), the no-redundancy flag under the decoder's
560 /// exact presence rule, then the CELT layer from band 17 in the same560 /// exact presence rule, then the CELT layer from band 17 in the same
561 /// coder. CBR: the packet is the bitrate's size unless SILK alone needs561 /// coder. CBR: the packet is the bitrate's size unless SILK alone needs
@@ -568,25 +568,46 @@ impl Encoder {
568 cap: usize,568 cap: usize,
569 ) -> Result<usize> {569 ) -> Result<usize> {
570 let cap = cap.min(MAX_FRAME_BYTES);570 let cap = cap.min(MAX_FRAME_BYTES);
571- let budget = ((self.bitrate as u64 * 960 + 4 * 48000) / (8 * 48000)) as usize;571+ let frame_48k = frame_size * self.upsample;
572+ let frame_ms = frame_48k / 48;
573+ let budget =
574+ ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize;
572 let budget = budget.saturating_sub(1).clamp(2, cap);575 let budget = budget.saturating_sub(1).clamp(2, cap);
573 if cap < HYBRID_CELT_MIN_BYTES + 2 {576 if cap < HYBRID_CELT_MIN_BYTES + 2 {
574 return Err(Error::corrupt(577 return Err(Error::corrupt(
575 "opus encode: output buffer smaller than the minimum hybrid packet",578 "opus encode: output buffer smaller than the minimum hybrid packet",
576 ));579 ));
577 }580 }
581+ if self.channels == 2 {
582+ Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);
583+ } else {
578 Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);584 Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);
579- let d = HYBRID_SILK_DELAY_48K;585+ }
586+ let d = HYBRID_SILK_DELAY_48K * self.channels;
587+ if self.silk_delay.len() != d {
588+ self.silk_delay.clear();
580 self.silk_delay.resize(d, 0.0);589 self.silk_delay.resize(d, 0.0);
581- let mut delayed = Vec::with_capacity(960);590+ }
591+ let silk_len = frame_48k * self.channels;
592+ let mut delayed = Vec::with_capacity(silk_len);
582 delayed.extend_from_slice(&self.silk_delay);593 delayed.extend_from_slice(&self.silk_delay);
583- delayed.extend_from_slice(&self.silk_stuff[..960 - d]);594+ delayed.extend_from_slice(&self.silk_stuff[..silk_len - d]);
584- self.silk_delay.copy_from_slice(&self.silk_stuff[960 - d..]);595+ self.silk_delay
596+ .copy_from_slice(&self.silk_stuff[silk_len - d..silk_len]);
585 597
586 self.range.reset(cap);598 self.range.reset(cap);
599+ let silk_rate = Self::hybrid_silk_rate(self.bitrate, bandwidth);
600+ if self.channels == 2 {
601+ let silk = self
602+ .silk_stereo_wb
603+ .get_or_insert_with(|| SilkStereoEncoder::new(true));
604+ silk.set_bitrate(silk_rate);
605+ silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;
606+ } else {
587 let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true));607 let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true));
588- silk.set_bitrate(Self::hybrid_silk_rate(self.bitrate, bandwidth));608+ silk.set_bitrate(silk_rate);
589- silk.encode_hybrid(&delayed, &mut self.range)?;609+ silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;
610+ }
590 let silk_bytes = (self.range.tell() as usize).div_ceil(8);611 let silk_bytes = (self.range.tell() as usize).div_ceil(8);
591 let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap);612 let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap);
592 self.range.shrink(budget);613 self.range.shrink(budget);
@@ -594,15 +615,27 @@ impl Encoder {
594 if self.range.tell() as usize + 17 + 20 <= 8 * budget {615 if self.range.tell() as usize + 17 + 20 <= 8 * budget {
595 self.range.enc_bit_logp(false, 12);616 self.range.enc_bit_logp(false, 12);
596 }617 }
597- // CELT sees the same input as SILK: start band 17 alone keeps it off618+ let n = self.celt.encode(
598- // the low band (a one-pole ~6 kHz high-pass here measured identical619+ &mut self.range,
599- // full-band correlation, so there is none).620+ pcm,
600- let n = self621+ frame_48k,
601- .celt622+ 17,
602- .encode(&mut self.range, pcm, 960, 17, bandwidth.celt_end_band(), 0)?;623+ bandwidth.celt_end_band(),
624+ 0,
625+ )?;
603 self.final_range = self.range.range();626 self.final_range = self.range.range();
604 let payload = &self.range.data()[..n];627 let payload = &self.range.data()[..n];
605- self.silk_wb.as_mut().unwrap().replay(payload)?;628+ if self.channels == 2 {
629+ self.silk_stereo_wb
630+ .as_mut()
631+ .unwrap()
632+ .replay_hybrid(payload, frame_ms)?;
633+ } else {
634+ self.silk_wb
635+ .as_mut()
636+ .unwrap()
637+ .replay_hybrid(payload, frame_ms)?;
638+ }
606 Ok(n)639 Ok(n)
607 }640 }
608 641
crates/ec-opus/src/silk_enc_write.rsmodified+77 -11
@@ -226,23 +226,26 @@ impl SilkEncoder {
226 Ok(1 + len)226 Ok(1 + len)
227 }227 }
228 228
229- /// The SILK layer of a hybrid packet: codes 960 mono 48 kHz samples into229+ /// The SILK layer of a hybrid packet: codes one mono 48 kHz frame into
230 /// `enc`, the packet's shared range coder (SILK symbols first; the CELT230 /// `enc`, the packet's shared range coder (SILK symbols first; the CELT
231 /// layer continues in the same coder), without finishing it. The caller231 /// layer continues in the same coder), without finishing it. The caller
232- /// must [`SilkEncoder::replay`] the finished payload so this encoder's232+ /// must [`SilkEncoder::replay_hybrid`] the finished payload so this
233- /// decoder mirror advances.233+ /// encoder's decoder mirror advances.
234- pub fn encode_hybrid(&mut self, pcm48: &[f32], enc: &mut RangeEncoder) -> Result<()> {234+ pub fn encode_hybrid_ms(
235- let trial = self.encode_inner(pcm48, 20, Some(enc), false, 0)?;235+ &mut self,
236+ pcm48: &[f32],
237+ enc: &mut RangeEncoder,
238+ frame_ms: usize,
239+ ) -> Result<()> {
240+ let trial = self.encode_inner(pcm48, frame_ms, Some(enc), false, 0)?;
236 self.voiced_frames += usize::from(trial.voiced);241 self.voiced_frames += usize::from(trial.voiced);
237 Ok(())242 Ok(())
238 }243 }
239 244
240- /// Decodes `payload` (TOC stripped) through the mirror decoder so the next245+ /// Decodes a finished hybrid payload (TOC stripped) through the mirror
241- /// frame predicts from the decoder's state; [`SilkEncoder::encode_frame`]246+ /// decoder so the next frame predicts from the decoder's state.
242- /// does this itself, [`SilkEncoder::encode_hybrid`] callers do it once247+ pub fn replay_hybrid(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
243- /// the packet is complete.248+ self.replay_ms(payload, frame_ms)
244- pub fn replay(&mut self, payload: &[u8]) -> Result<()> {
245- self.replay_ms(payload, 20)
246 }249 }
247 250
248 fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {251 fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
@@ -743,6 +746,63 @@ impl SilkStereoEncoder {
743 self.mid.delay_samples()746 self.mid.delay_samples()
744 }747 }
745 748
749+ /// The SILK layer of a hybrid packet: codes one interleaved stereo 48 kHz
750+ /// frame into the packet's shared range coder without finishing it.
751+ pub fn encode_hybrid_ms(
752+ &mut self,
753+ pcm48: &[f32],
754+ enc: &mut RangeEncoder,
755+ frame_ms: usize,
756+ ) -> Result<()> {
757+ assert!(
758+ matches!(frame_ms, 10 | 20),
759+ "SilkStereoEncoder codes 10 or 20 ms stereo frames"
760+ );
761+ assert_eq!(
762+ pcm48.len(),
763+ 2 * 48 * frame_ms,
764+ "SilkStereoEncoder input is 48 kHz stereo"
765+ );
766+ if self.prev_mid_only {
767+ self.side.reset_state();
768+ if let Some(bps) = self.target_bps {
769+ self.side.set_bitrate((bps / 2).max(500));
770+ }
771+ }
772+ let samples = 48 * frame_ms;
773+ let mut mid = Vec::with_capacity(samples);
774+ let mut side = Vec::with_capacity(samples);
775+ let mut side_energy = 0.0f32;
776+ for lr in pcm48.chunks_exact(2) {
777+ let m = 0.5 * (lr[0] + lr[1]);
778+ let s = 0.5 * (lr[0] - lr[1]);
779+ mid.push(m);
780+ side.push(s);
781+ side_energy += s * s;
782+ }
783+ let mid_trial = self.mid.encode_inner(&mid, frame_ms, None, false, 0)?;
784+ let side_trial = self.side.encode_inner(&side, frame_ms, None, false, 0)?;
785+ let mid_only = side_energy < 1.0e-10;
786+ write_stereo_packet_header(enc, &mid_trial, &side_trial, mid_only);
787+ write_stereo_zero_pred(enc);
788+ if !side_trial.vad_flag {
789+ enc.enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8);
790+ }
791+ write_frame_data(enc, &mid_trial, false, 0);
792+ if !mid_only {
793+ write_frame_data(enc, &side_trial, false, 0);
794+ }
795+ self.mid.replay_ms(&mid_trial.bytes, frame_ms)?;
796+ if mid_only {
797+ self.side.reset_state();
798+ } else {
799+ self.side.replay_ms(&side_trial.bytes, frame_ms)?;
800+ }
801+ self.prev_mid_only = mid_only;
802+ self.voiced_frames += usize::from(mid_trial.voiced || side_trial.voiced);
803+ Ok(())
804+ }
805+
746 /// Encodes one 10 or 20 ms interleaved stereo frame at 48 kHz.806 /// Encodes one 10 or 20 ms interleaved stereo frame at 48 kHz.
747 pub fn encode_frame_ms(807 pub fn encode_frame_ms(
748 &mut self,808 &mut self,
@@ -823,6 +883,12 @@ impl SilkStereoEncoder {
823 Ok(1 + len)883 Ok(1 + len)
824 }884 }
825 885
886+ /// Decodes a finished hybrid payload (TOC stripped) through the stereo
887+ /// mirror so the range state can be checked against the packet encoder.
888+ pub fn replay_hybrid(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
889+ self.replay_ms(payload, frame_ms)
890+ }
891+
826 fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {892 fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> {
827 let fs = self.fs_khz;893 let fs = self.fs_khz;
828 let mut dec = RangeDecoder::new(payload);894 let mut dec = RangeDecoder::new(payload);
crates/ec-opus/tests/conformance.rsmodified+125 -2
@@ -877,8 +877,8 @@ fn encoder_roundtrips_at_every_rate() {
877 877
878 /// The mode `Encoder` actually picks, read back from the packet's own TOC878 /// 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, WB879 /// 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 is880+/// above), Voip 20-40 kbps mono selects Hybrid, and Audio at any rate stays
881-/// unimplemented and Mode 20-40 kbps needs it, D4).881+/// on CELT.
882 #[test]882 #[test]
883 fn encoder_mode_follows_application_and_bitrate() {883 fn encoder_mode_follows_application_and_bitrate() {
884 // `None` for the two CELT rows: any CELT config is correct there, the884 // `None` for the two CELT rows: any CELT config is correct there, the
@@ -2203,3 +2203,126 @@ fn hybrid_fb_roundtrip() {
2203 );2203 );
2204 }2204 }
2205 }2205 }
2206+
2207+fn hybrid_roundtrip_shape(
2208+ pcm: &[f32],
2209+ channels: usize,
2210+ frame: usize,
2211+ bps: u32,
2212+ bandwidth: Option<Bandwidth>,
2213+) -> (Vec<f32>, Vec<Vec<u8>>) {
2214+ let mut enc = Encoder::new(48000, channels, Application::Voip).unwrap();
2215+ enc.set_bitrate(bps);
2216+ enc.set_bandwidth(bandwidth);
2217+ let mut dec = Decoder::new(48000, channels).unwrap();
2218+ let mut out = vec![0u8; 1500];
2219+ let mut buf = vec![0f32; 5760 * channels];
2220+ let (mut decoded, mut packets) = (Vec::new(), Vec::new());
2221+ let mut padded = pcm.to_vec();
2222+ padded.resize(
2223+ pcm.len().div_ceil(frame * channels) * frame * channels + frame * channels,
2224+ 0.0,
2225+ );
2226+ for block in padded.chunks(frame * channels) {
2227+ let len = enc
2228+ .encode_float(block, frame, &mut out)
2229+ .expect("hybrid encode");
2230+ let n = dec
2231+ .decode_float(&out[..len], &mut buf)
2232+ .expect("hybrid decode");
2233+ assert_eq!(n, frame);
2234+ assert_eq!(dec.final_range(), enc.final_range(), "range state diverged");
2235+ decoded.extend_from_slice(&buf[..n * channels]);
2236+ packets.push(out[..len].to_vec());
2237+ }
2238+ (decoded, packets)
2239+}
2240+
2241+#[test]
2242+fn hybrid_shapes_roundtrip() {
2243+ for (tag, channels, frame, bps, bandwidth, config, floor) in [
2244+ (
2245+ "mono-swb10",
2246+ 1usize,
2247+ 480usize,
2248+ 24_000u32,
2249+ Bandwidth::SuperWide,
2250+ 12u8,
2251+ 0.75f64,
2252+ ),
2253+ ("mono-fb10", 1, 480, 32_000, Bandwidth::Full, 14, 0.75),
2254+ (
2255+ "stereo-swb20",
2256+ 2,
2257+ 960,
2258+ 48_000,
2259+ Bandwidth::SuperWide,
2260+ 13,
2261+ 0.75,
2262+ ),
2263+ ("stereo-fb20", 2, 960, 64_000, Bandwidth::Full, 15, 0.75),
2264+ ("stereo-fb10", 2, 480, 64_000, Bandwidth::Full, 14, 0.70),
2265+ ] {
2266+ let pcm = if channels == 1 {
2267+ speech_like()
2268+ } else {
2269+ stereo_speech_pair()
2270+ };
2271+ let (decoded, packets) =
2272+ hybrid_roundtrip_shape(&pcm, channels, frame, bps, Some(bandwidth));
2273+ let toc = ec_opus::Toc::new(packets[0][0]);
2274+ assert_eq!(toc.config, config, "{tag}: TOC config {}", toc.config);
2275+ assert_eq!(toc.stereo, channels == 2, "{tag}: TOC stereo flag");
2276+ let mut worst = 1.0f64;
2277+ for ch in 0..channels {
2278+ let source: Vec<f32> = pcm.chunks_exact(channels).map(|f| f[ch]).collect();
2279+ let got: Vec<f32> = decoded.chunks_exact(channels).map(|f| f[ch]).collect();
2280+ let (corr, lag) = aligned_corr(&source, &got, 400);
2281+ worst = worst.min(corr);
2282+ eprintln!("hybrid {tag} ch{ch}: corr {corr:.4} at lag {lag}");
2283+ }
2284+ assert!(worst >= floor, "{tag}: worst corr {worst:.4}");
2285+ let total = pcm.len() / channels;
2286+ let path = temp_path(&format!("hybrid-{tag}.opus"));
2287+ write_ogg_opus(
2288+ &path,
2289+ &packets,
2290+ opus_head(channels, 120, None),
2291+ channels,
2292+ total,
2293+ 120,
2294+ );
2295+ if Command::new("ffmpeg").arg("-version").output().is_ok() {
2296+ let out = Command::new("ffmpeg")
2297+ .args(["-v", "warning", "-c:a", "libopus", "-i"])
2298+ .arg(&path)
2299+ .args(["-f", "null", "-"])
2300+ .output()
2301+ .unwrap();
2302+ let stderr = String::from_utf8_lossy(&out.stderr);
2303+ assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}");
2304+ }
2305+ if Command::new("gst-launch-1.0")
2306+ .arg("--version")
2307+ .output()
2308+ .is_ok()
2309+ {
2310+ let location = format!("location={}", path.display());
2311+ let out = Command::new("gst-launch-1.0")
2312+ .args([
2313+ "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink",
2314+ ])
2315+ .output()
2316+ .unwrap();
2317+ let stderr = String::from_utf8_lossy(&out.stderr);
2318+ assert!(out.status.success(), "{tag}: gst decode: {stderr}");
2319+ }
2320+ let _ = fs::remove_file(&path);
2321+ }
2322+
2323+ let speech = stereo_speech_pair();
2324+ let (_, packets) = hybrid_roundtrip_shape(&speech, 2, 960, 64_000, None);
2325+ let toc = ec_opus::Toc::new(packets[0][0]);
2326+ assert_eq!(toc.mode(), ec_opus::Mode::Hybrid);
2327+ assert!(toc.stereo);
2328+}