From 38c15e3a7d8d6e68ced7d05cdc6d37c7827a90aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 21 Aug 2026 13:53:25 +0300 Subject: [PATCH] feat(ec-opus): finish hybrid mode wiring --- crates/ec-opus/src/encoder.rs | 103 ++++++++++++++-------- crates/ec-opus/src/silk_enc_write.rs | 88 ++++++++++++++++--- crates/ec-opus/tests/conformance.rs | 127 ++++++++++++++++++++++++++- 3 files changed, 270 insertions(+), 48 deletions(-) diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index 553724b1..7cc90a9f 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -270,20 +270,19 @@ impl Encoder { } /// Whether this frame goes out as a hybrid packet, and at which of the two - /// hybrid bandwidths. Automatic: VoIP from 20 kbps (where SILK alone - /// stops) to 40 kbps (where CELT alone is the better speech coder too), - /// at the bitrate's own bandwidth (SWB/FB; narrower requests are CELT's). - /// Mono 20 ms only — stereo Hybrid (which needs stereo SILK) and the - /// 10 ms hybrid configs are not implemented and fall back to CELT. + /// hybrid bandwidths. Automatic: VoIP from 20 kbps per coded channel + /// (where SILK alone stops) to 40 kbps per coded channel (where CELT alone + /// is the better speech coder too), at the bitrate's own bandwidth + /// (SWB/FB; narrower requests are CELT's). Mono and stereo, 10 or 20 ms. fn hybrid_choice(&self, frame_48k: usize) -> Option { + let lo = 20_000 * self.channels as u32; + let hi = 40_000 * self.channels as u32; let wanted = match self.mode { Some(Mode::Hybrid) => true, Some(_) => false, - None => { - self.application == Application::Voip && (20_000..40_000).contains(&self.bitrate) - } + None => self.application == Application::Voip && (lo..hi).contains(&self.bitrate), }; - if !wanted || self.channels != 1 || frame_48k != 960 { + if !wanted || !matches!(frame_48k, 480 | 960) { return None; } let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth()); @@ -409,12 +408,13 @@ impl Encoder { } if let Some(bandwidth) = self.hybrid_choice(frame_48k) { let n = self.encode_hybrid(pcm, frame_size, bandwidth, cap)?; - let config = if bandwidth == Bandwidth::Full { - 15u8 - } else { - 13 - }; - return Ok((config << 3, &self.range.data()[..n])); + let config = 12 + + if bandwidth == Bandwidth::Full { 2u8 } else { 0 } + + if frame_48k == 960 { 1 } else { 0 }; + return Ok(( + (config << 3) | (u8::from(self.channels == 2) << 2), + &self.range.data()[..n], + )); } let (toc, frame_48k, end) = self.toc(frame_size)?; let n = self.encode_frame(pcm, frame_48k, end, cap)?; @@ -553,9 +553,9 @@ impl Encoder { Ok(1 + len_bytes + n) } - /// One hybrid frame (mono, 20 ms, `bandwidth` SWB or FB) into the - /// internal range coder, returning its byte length: the SILK layer's - /// symbols (WB, 16 kHz internal, fed the input delayed by + /// One hybrid frame (10 or 20 ms, mono or stereo, `bandwidth` SWB or FB) + /// into the internal range coder, returning its byte length: the SILK + /// layer's symbols (WB, 16 kHz internal, fed the input delayed by /// [`HYBRID_SILK_DELAY_48K`]), the no-redundancy flag under the decoder's /// exact presence rule, then the CELT layer from band 17 in the same /// coder. CBR: the packet is the bitrate's size unless SILK alone needs @@ -568,25 +568,46 @@ impl Encoder { cap: usize, ) -> Result { let cap = cap.min(MAX_FRAME_BYTES); - let budget = ((self.bitrate as u64 * 960 + 4 * 48000) / (8 * 48000)) as usize; + let frame_48k = frame_size * self.upsample; + let frame_ms = frame_48k / 48; + let budget = + ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize; let budget = budget.saturating_sub(1).clamp(2, cap); if cap < HYBRID_CELT_MIN_BYTES + 2 { return Err(Error::corrupt( "opus encode: output buffer smaller than the minimum hybrid packet", )); } - Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); - let d = HYBRID_SILK_DELAY_48K; - self.silk_delay.resize(d, 0.0); - let mut delayed = Vec::with_capacity(960); + if self.channels == 2 { + Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff); + } else { + Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); + } + let d = HYBRID_SILK_DELAY_48K * self.channels; + if self.silk_delay.len() != d { + self.silk_delay.clear(); + self.silk_delay.resize(d, 0.0); + } + let silk_len = frame_48k * self.channels; + let mut delayed = Vec::with_capacity(silk_len); delayed.extend_from_slice(&self.silk_delay); - delayed.extend_from_slice(&self.silk_stuff[..960 - d]); - self.silk_delay.copy_from_slice(&self.silk_stuff[960 - d..]); + delayed.extend_from_slice(&self.silk_stuff[..silk_len - d]); + self.silk_delay + .copy_from_slice(&self.silk_stuff[silk_len - d..silk_len]); self.range.reset(cap); - let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)); - silk.set_bitrate(Self::hybrid_silk_rate(self.bitrate, bandwidth)); - silk.encode_hybrid(&delayed, &mut self.range)?; + let silk_rate = Self::hybrid_silk_rate(self.bitrate, bandwidth); + if self.channels == 2 { + let silk = self + .silk_stereo_wb + .get_or_insert_with(|| SilkStereoEncoder::new(true)); + silk.set_bitrate(silk_rate); + silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?; + } else { + let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)); + silk.set_bitrate(silk_rate); + silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?; + } let silk_bytes = (self.range.tell() as usize).div_ceil(8); let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap); self.range.shrink(budget); @@ -594,15 +615,27 @@ impl Encoder { if self.range.tell() as usize + 17 + 20 <= 8 * budget { self.range.enc_bit_logp(false, 12); } - // CELT sees the same input as SILK: start band 17 alone keeps it off - // the low band (a one-pole ~6 kHz high-pass here measured identical - // full-band correlation, so there is none). - let n = self - .celt - .encode(&mut self.range, pcm, 960, 17, bandwidth.celt_end_band(), 0)?; + let n = self.celt.encode( + &mut self.range, + pcm, + frame_48k, + 17, + bandwidth.celt_end_band(), + 0, + )?; self.final_range = self.range.range(); let payload = &self.range.data()[..n]; - self.silk_wb.as_mut().unwrap().replay(payload)?; + if self.channels == 2 { + self.silk_stereo_wb + .as_mut() + .unwrap() + .replay_hybrid(payload, frame_ms)?; + } else { + self.silk_wb + .as_mut() + .unwrap() + .replay_hybrid(payload, frame_ms)?; + } Ok(n) } diff --git a/crates/ec-opus/src/silk_enc_write.rs b/crates/ec-opus/src/silk_enc_write.rs index 2136c0a0..4ae32b00 100644 --- a/crates/ec-opus/src/silk_enc_write.rs +++ b/crates/ec-opus/src/silk_enc_write.rs @@ -226,23 +226,26 @@ impl SilkEncoder { Ok(1 + len) } - /// The SILK layer of a hybrid packet: codes 960 mono 48 kHz samples into + /// The SILK layer of a hybrid packet: codes one mono 48 kHz frame into /// `enc`, the packet's shared range coder (SILK symbols first; the CELT /// layer continues in the same coder), without finishing it. The caller - /// must [`SilkEncoder::replay`] the finished payload so this encoder's - /// decoder mirror advances. - pub fn encode_hybrid(&mut self, pcm48: &[f32], enc: &mut RangeEncoder) -> Result<()> { - let trial = self.encode_inner(pcm48, 20, Some(enc), false, 0)?; + /// must [`SilkEncoder::replay_hybrid`] the finished payload so this + /// encoder's decoder mirror advances. + pub fn encode_hybrid_ms( + &mut self, + pcm48: &[f32], + enc: &mut RangeEncoder, + frame_ms: usize, + ) -> Result<()> { + let trial = self.encode_inner(pcm48, frame_ms, Some(enc), false, 0)?; self.voiced_frames += usize::from(trial.voiced); Ok(()) } - /// Decodes `payload` (TOC stripped) through the mirror decoder so the next - /// frame predicts from the decoder's state; [`SilkEncoder::encode_frame`] - /// does this itself, [`SilkEncoder::encode_hybrid`] callers do it once - /// the packet is complete. - pub fn replay(&mut self, payload: &[u8]) -> Result<()> { - self.replay_ms(payload, 20) + /// Decodes a finished hybrid payload (TOC stripped) through the mirror + /// decoder so the next frame predicts from the decoder's state. + pub fn replay_hybrid(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> { + self.replay_ms(payload, frame_ms) } fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> { @@ -743,6 +746,63 @@ impl SilkStereoEncoder { self.mid.delay_samples() } + /// The SILK layer of a hybrid packet: codes one interleaved stereo 48 kHz + /// frame into the packet's shared range coder without finishing it. + pub fn encode_hybrid_ms( + &mut self, + pcm48: &[f32], + enc: &mut RangeEncoder, + frame_ms: usize, + ) -> Result<()> { + assert!( + matches!(frame_ms, 10 | 20), + "SilkStereoEncoder codes 10 or 20 ms stereo frames" + ); + assert_eq!( + pcm48.len(), + 2 * 48 * frame_ms, + "SilkStereoEncoder input is 48 kHz stereo" + ); + if self.prev_mid_only { + self.side.reset_state(); + if let Some(bps) = self.target_bps { + self.side.set_bitrate((bps / 2).max(500)); + } + } + let samples = 48 * frame_ms; + let mut mid = Vec::with_capacity(samples); + let mut side = Vec::with_capacity(samples); + let mut side_energy = 0.0f32; + for lr in pcm48.chunks_exact(2) { + let m = 0.5 * (lr[0] + lr[1]); + let s = 0.5 * (lr[0] - lr[1]); + mid.push(m); + side.push(s); + side_energy += s * s; + } + let mid_trial = self.mid.encode_inner(&mid, frame_ms, None, false, 0)?; + let side_trial = self.side.encode_inner(&side, frame_ms, None, false, 0)?; + let mid_only = side_energy < 1.0e-10; + write_stereo_packet_header(enc, &mid_trial, &side_trial, mid_only); + write_stereo_zero_pred(enc); + if !side_trial.vad_flag { + enc.enc_icdf(usize::from(mid_only), &STEREO_ONLY_CODE_MID_ICDF, 8); + } + write_frame_data(enc, &mid_trial, false, 0); + if !mid_only { + write_frame_data(enc, &side_trial, false, 0); + } + self.mid.replay_ms(&mid_trial.bytes, frame_ms)?; + if mid_only { + self.side.reset_state(); + } else { + self.side.replay_ms(&side_trial.bytes, frame_ms)?; + } + self.prev_mid_only = mid_only; + self.voiced_frames += usize::from(mid_trial.voiced || side_trial.voiced); + Ok(()) + } + /// Encodes one 10 or 20 ms interleaved stereo frame at 48 kHz. pub fn encode_frame_ms( &mut self, @@ -823,6 +883,12 @@ impl SilkStereoEncoder { Ok(1 + len) } + /// Decodes a finished hybrid payload (TOC stripped) through the stereo + /// mirror so the range state can be checked against the packet encoder. + pub fn replay_hybrid(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> { + self.replay_ms(payload, frame_ms) + } + fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> { let fs = self.fs_khz; let mut dec = RangeDecoder::new(payload); diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 365adcb6..740089de 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -877,8 +877,8 @@ fn encoder_roundtrips_at_every_rate() { /// The mode `Encoder` actually picks, read back from the packet's own TOC /// byte: Voip below 20 kbps mono selects SILK (NB at/under 10 kbps, WB -/// above), Voip 20-40 kbps and Audio at any rate stay on CELT (Hybrid is -/// unimplemented and Mode 20-40 kbps needs it, D4). +/// above), Voip 20-40 kbps mono selects Hybrid, and Audio at any rate stays +/// on CELT. #[test] fn encoder_mode_follows_application_and_bitrate() { // `None` for the two CELT rows: any CELT config is correct there, the @@ -2203,3 +2203,126 @@ fn hybrid_fb_roundtrip() { ); } } + +fn hybrid_roundtrip_shape( + pcm: &[f32], + channels: usize, + frame: usize, + bps: u32, + bandwidth: Option, +) -> (Vec, Vec>) { + let mut enc = Encoder::new(48000, channels, Application::Voip).unwrap(); + enc.set_bitrate(bps); + enc.set_bandwidth(bandwidth); + let mut dec = Decoder::new(48000, channels).unwrap(); + let mut out = vec![0u8; 1500]; + let mut buf = vec![0f32; 5760 * channels]; + let (mut decoded, mut packets) = (Vec::new(), Vec::new()); + let mut padded = pcm.to_vec(); + padded.resize( + pcm.len().div_ceil(frame * channels) * frame * channels + frame * channels, + 0.0, + ); + for block in padded.chunks(frame * channels) { + let len = enc + .encode_float(block, frame, &mut out) + .expect("hybrid encode"); + let n = dec + .decode_float(&out[..len], &mut buf) + .expect("hybrid decode"); + assert_eq!(n, frame); + assert_eq!(dec.final_range(), enc.final_range(), "range state diverged"); + decoded.extend_from_slice(&buf[..n * channels]); + packets.push(out[..len].to_vec()); + } + (decoded, packets) +} + +#[test] +fn hybrid_shapes_roundtrip() { + for (tag, channels, frame, bps, bandwidth, config, floor) in [ + ( + "mono-swb10", + 1usize, + 480usize, + 24_000u32, + Bandwidth::SuperWide, + 12u8, + 0.75f64, + ), + ("mono-fb10", 1, 480, 32_000, Bandwidth::Full, 14, 0.75), + ( + "stereo-swb20", + 2, + 960, + 48_000, + Bandwidth::SuperWide, + 13, + 0.75, + ), + ("stereo-fb20", 2, 960, 64_000, Bandwidth::Full, 15, 0.75), + ("stereo-fb10", 2, 480, 64_000, Bandwidth::Full, 14, 0.70), + ] { + let pcm = if channels == 1 { + speech_like() + } else { + stereo_speech_pair() + }; + let (decoded, packets) = + hybrid_roundtrip_shape(&pcm, channels, frame, bps, Some(bandwidth)); + let toc = ec_opus::Toc::new(packets[0][0]); + assert_eq!(toc.config, config, "{tag}: TOC config {}", toc.config); + assert_eq!(toc.stereo, channels == 2, "{tag}: TOC stereo flag"); + let mut worst = 1.0f64; + for ch in 0..channels { + let source: Vec = pcm.chunks_exact(channels).map(|f| f[ch]).collect(); + let got: Vec = decoded.chunks_exact(channels).map(|f| f[ch]).collect(); + let (corr, lag) = aligned_corr(&source, &got, 400); + worst = worst.min(corr); + eprintln!("hybrid {tag} ch{ch}: corr {corr:.4} at lag {lag}"); + } + assert!(worst >= floor, "{tag}: worst corr {worst:.4}"); + let total = pcm.len() / channels; + let path = temp_path(&format!("hybrid-{tag}.opus")); + write_ogg_opus( + &path, + &packets, + opus_head(channels, 120, None), + channels, + total, + 120, + ); + if Command::new("ffmpeg").arg("-version").output().is_ok() { + let out = Command::new("ffmpeg") + .args(["-v", "warning", "-c:a", "libopus", "-i"]) + .arg(&path) + .args(["-f", "null", "-"]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}"); + } + if Command::new("gst-launch-1.0") + .arg("--version") + .output() + .is_ok() + { + let location = format!("location={}", path.display()); + let out = Command::new("gst-launch-1.0") + .args([ + "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink", + ]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{tag}: gst decode: {stderr}"); + } + let _ = fs::remove_file(&path); + } + + let speech = stereo_speech_pair(); + let (_, packets) = hybrid_roundtrip_shape(&speech, 2, 960, 64_000, None); + let toc = ec_opus::Toc::new(packets[0][0]); + assert_eq!(toc.mode(), ec_opus::Mode::Hybrid); + assert!(toc.stereo); +}