From a6d027812141f4b0e8355b1e2b9a9d89126a4bcc 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 01:42:35 +0300 Subject: [PATCH] feat(opus-hybrid): mono 20 ms SWB/FB hybrid packets (SILK 16 kHz + CELT from band 17) CeltEncoder::encode takes a start band and mirrors the decoder's start_band paths (no silence flag mid-stream, no postfilter bit, zeroed x below start, cleared energy history outside the coded span). SilkEncoder::encode_hybrid writes the chosen frame into a shared range coder and replay() advances the mirror from the finished payload. Encoder: Voip 20-40 kbps mono 20 ms -> config 13/15, reference's SILK rate share, no-redundancy flag under the decoder's exact presence rule, SILK input delayed 70 samples so both layers land at CELT's 120 (click-measured LB +121 / HB +120). Decoder gains a doc(hidden) per-layer mute for the tests. --- crates/ec-opus/src/celt_enc.rs | 33 +++++-- crates/ec-opus/src/encoder.rs | 142 +++++++++++++++++++++++++-- crates/ec-opus/src/lib.rs | 16 ++- crates/ec-opus/src/silk_enc_write.rs | 130 +++++++++++++++--------- crates/ec-opus/tests/conformance.rs | 101 ++++++++++++++++++- 5 files changed, 357 insertions(+), 65 deletions(-) diff --git a/crates/ec-opus/src/celt_enc.rs b/crates/ec-opus/src/celt_enc.rs index fd31e2c4..4be9d48c 100644 --- a/crates/ec-opus/src/celt_enc.rs +++ b/crates/ec-opus/src/celt_enc.rs @@ -388,8 +388,11 @@ impl CeltEncoder { /// Encodes one frame of interleaved `f32` (`frame_size` samples per /// channel at 48 kHz, one of 120/240/480/960 — of which /// `frame_size/upsample` are read from `pcm`) into `enc`, which must have - /// been `reset` to the frame's byte budget. `end` bounds the coded bands, - /// which is how the caller limits the coded bandwidth. With + /// been `reset` to the frame's byte budget. `start..end` bounds the coded + /// bands — `end` is how the caller limits the coded bandwidth, `start` + /// (0, or 17 under a hybrid packet's SILK layer) skips the low bands + /// exactly as the decoder's `start_band` does: no energy, no shapes, no + /// postfilter bit, allocation over the coded span only. With /// `vbr_rate_bps` set, the frame may be shrunk below that budget /// (constrained VBR); the return value is the final frame size in bytes. pub fn encode( @@ -397,6 +400,7 @@ impl CeltEncoder { enc: &mut RangeEncoder, pcm: &[f32], frame_size: usize, + start: usize, end: usize, vbr_rate_bps: u32, ) -> Result { @@ -422,7 +426,7 @@ impl CeltEncoder { pcm.len() ))); } - let (start, end) = (0usize, end.clamp(1, NB_BANDS)); + let end = end.clamp(start + 1, NB_BANDS); let mut nb_compressed = enc.storage(); let mut nb_available = nb_compressed as i32; @@ -485,7 +489,13 @@ impl CeltEncoder { } // --- Silence flag (first symbol of the frame) ----------------------- - enc.enc_bit_logp(silence, 15); + // Only exists when CELT opens the stream (decoder: `tell == 1`); under + // a hybrid packet's SILK layer the frame is never flagged silent. + if enc.tell() == 1 { + enc.enc_bit_logp(silence, 15); + } else { + silence = false; + } if silence { if vbr_rate > 0 { nb_compressed = nb_compressed.min(2); @@ -497,7 +507,8 @@ impl CeltEncoder { } // --- Postfilter: always off (throughput-first, = complexity < 5) ---- - if enc.tell() as i32 + 16 <= total_bits { + // The flag exists only when band 0 is coded (decoder: `start == 0`). + if start == 0 && enc.tell() as i32 + 16 <= total_bits { enc.enc_bit_logp(false, 1); } @@ -515,7 +526,8 @@ impl CeltEncoder { // --- Forward MDCTs, energies, normalisation ------------------------- self.compute_mdcts(short_blocks, lm, n, c); for ch in 0..c { - for i in 0..end { + self.x[ch * n..ch * n + m * E_BANDS[start]].fill(0.0); + for i in start..end { let mut sum = 1e-27f32; for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { let v = self.freq[ch * n + j]; @@ -525,7 +537,7 @@ impl CeltEncoder { self.band_log_e[i + ch * NB_BANDS] = (self.band_e[i + ch * NB_BANDS] as f64).log2() as f32 - E_MEANS[i]; } - for i in 0..end { + for i in start..end { let g = 1.0 / (1e-27 + self.band_e[i + ch * NB_BANDS]); for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { self.x[ch * n + j] = self.freq[ch * n + j] * g; @@ -811,6 +823,13 @@ impl CeltEncoder { self.old_band_e[NB_BANDS + i] = self.old_band_e[i]; } } + // Uncoded bands hold no energy history (the decoder clears them the + // same way), so a later start/end change predicts from the same state. + for ch in 0..2 { + for i in (0..start).chain(end..NB_BANDS) { + self.old_band_e[ch * NB_BANDS + i] = 0.0; + } + } if is_transient { self.consec_transient += 1; } else { diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index 9828267a..2fbb8ebd 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -5,8 +5,10 @@ //! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s //! default) picks CELT (TOC configs 16..31, every rate and frame size) or //! SILK (TOC configs 1/9, mono NB/WB 20 ms only — stereo SILK and SILK at -//! other frame sizes fall back to CELT, documented at the fallback site). -//! Hybrid is not implemented yet and also falls back to CELT. +//! other frame sizes fall back to CELT, documented at the fallback site) or +//! Hybrid (TOC configs 13/15, mono SWB/FB 20 ms: SILK at 16 kHz under CELT +//! from band 17 up, one range-coded stream; stereo and other frame sizes +//! fall back to CELT). //! //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and //! the coded bandwidth is capped at the input's own Nyquist, so the images @@ -37,6 +39,13 @@ const MAX_FRAME_BYTES: usize = 1275; /// don't have to and don't match. const SILK_LOOK_AHEAD_48K_NB: usize = 58; const SILK_LOOK_AHEAD_48K_WB: usize = 50; +/// How far the hybrid path delays the SILK layer's input so its output lines +/// up with the CELT layer's at the decoder (which sums them as-is): CELT's +/// overlap (120) minus SILK's WB round trip, click-measured through the +/// decoder with one layer muted (`hybrid_layers_align` in conformance.rs). +const HYBRID_SILK_DELAY_48K: usize = 120 - SILK_LOOK_AHEAD_48K_WB; +/// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent. +const HYBRID_CELT_MIN_BYTES: usize = 8; /// What the caller is encoding. This encoder is CELT-only, so the setting /// biases the coded bandwidth rather than selecting a different layer. @@ -75,6 +84,8 @@ pub struct Encoder { /// Scratch space for the SILK payload, sized once so the steady-state /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. silk_buf: [u8; MAX_FRAME_BYTES + 1], + /// Hybrid: the last [`HYBRID_SILK_DELAY_48K`] samples of SILK-layer input. + silk_delay: Vec, } impl Encoder { @@ -117,13 +128,14 @@ impl Encoder { silk_nb: None, silk_wb: None, silk_buf: [0u8; MAX_FRAME_BYTES + 1], + silk_delay: Vec::new(), }) } - /// Overrides the automatic SILK/CELT choice `wants_silk` would make from - /// the application and bitrate. [`Mode::Hybrid`] is unimplemented and - /// falls back to CELT (documented at the fallback site in - /// [`Encoder::silk_choice`]); pass `None` to restore the automatic pick. + /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and + /// `hybrid_choice` make from the application and bitrate; pass `None` to + /// restore the automatic pick. Requests this encoder cannot honour + /// (stereo SILK/Hybrid, frames other than 20 ms) fall back to CELT. pub fn set_mode(&mut self, mode: Option) { self.mode = mode; } @@ -144,7 +156,8 @@ impl Encoder { /// SILK (mono, when the application/bitrate or an explicit /// [`Encoder::set_mode`] select it): [`SILK_LOOK_AHEAD_48K_NB`] or /// [`SILK_LOOK_AHEAD_48K_WB`], the analysis-plus-synthesis resampler - /// round trip, click-measured per bandwidth. + /// round trip, click-measured per bandwidth. Hybrid: CELT's 120, the + /// SILK layer being delayed to meet it ([`HYBRID_SILK_DELAY_48K`]). pub fn look_ahead(&self) -> usize { if self.channels == 1 { if let Some(wideband) = self.wants_silk() { @@ -195,12 +208,13 @@ impl Encoder { self.celt.reset(); self.silk_nb = None; self.silk_wb = None; + self.silk_delay.clear(); self.final_range = 0; } /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) /// call for SILK, and if so, wideband (else narrowband). `None` means - /// CELT (or Hybrid, unimplemented and mapped to CELT). + /// CELT or Hybrid (`hybrid_choice` tells those apart). fn wants_silk(&self) -> Option { match self.mode { Some(Mode::Celt) | Some(Mode::Hybrid) => None, @@ -226,6 +240,53 @@ impl Encoder { Some(wideband) } + /// 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. + fn hybrid_choice(&self, frame_48k: usize) -> Option { + let wanted = match self.mode { + Some(Mode::Hybrid) => true, + Some(_) => false, + None => { + self.application == Application::Voip + && (20_000..40_000).contains(&self.bitrate) + } + }; + if !wanted || self.channels != 1 || frame_48k != 960 { + return None; + } + let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth()); + match bandwidth { + Bandwidth::SuperWide | Bandwidth::Full => Some(bandwidth), + // A forced Hybrid codes at least SWB; an automatic one that the + // bitrate would cap narrower is CELT's. + _ if self.mode == Some(Mode::Hybrid) => Some(Bandwidth::SuperWide), + _ => None, + } + } + + /// The SILK layer's share of a mono hybrid packet's bitrate, the + /// reference's 20 ms table interpolated: the rest is CELT's. + fn hybrid_silk_rate(total: u32, bandwidth: Bandwidth) -> u32 { + const TABLE: [(u32, u32, u32); 7] = [ + (0, 0, 0), + (12000, 10000, 11000), + (16000, 13500, 14500), + (20000, 16000, 17000), + (24000, 18000, 19000), + (32000, 22000, 24000), + (64000, 38000, 42000), + ]; + let pick = |row: &(u32, u32, u32)| if bandwidth == Bandwidth::Full { row.2 } else { row.1 }; + let total = total.min(64000); + let i = TABLE.iter().rposition(|r| r.0 <= total).unwrap().min(TABLE.len() - 2); + let (lo, hi) = (&TABLE[i], &TABLE[i + 1]); + pick(lo) + (pick(hi) - pick(lo)) * (total - lo.0) / (hi.0 - lo.0) + } + /// Zero-stuffs a mono, `frame_size`-sample native-rate frame up to /// `frame_size * upsample` samples at 48 kHz, the rate [`SilkEncoder`] /// takes — the same technique [`CeltEncoder::encode`] uses, scaled by @@ -269,6 +330,11 @@ impl Encoder { self.final_range = enc.final_range(); return Ok((self.silk_buf[0], &self.silk_buf[1..n])); } + 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 (toc, frame_48k, end) = self.toc(frame_size)?; let n = self.encode_frame(pcm, frame_48k, end, cap)?; Ok((toc, &self.range.data()[..n])) @@ -404,6 +470,64 @@ 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 + /// [`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 + /// more, in which case CELT keeps [`HYBRID_CELT_MIN_BYTES`] on top. + fn encode_hybrid( + &mut self, + pcm: &[f32], + frame_size: usize, + bandwidth: Bandwidth, + cap: usize, + ) -> Result { + let cap = cap.min(MAX_FRAME_BYTES); + let budget = ((self.bitrate as u64 * 960 + 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", + )); + } + let stuffed = self.zero_stuff_mono(pcm, frame_size); + let d = HYBRID_SILK_DELAY_48K; + self.silk_delay.resize(d, 0.0); + let mut delayed = Vec::with_capacity(960); + delayed.extend_from_slice(&self.silk_delay); + delayed.extend_from_slice(&stuffed[..960 - d]); + self.silk_delay.copy_from_slice(&stuffed[960 - d..]); + + 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_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); + // Redundancy flag: present under exactly the decoder's condition. + 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, + )?; + self.final_range = self.range.range(); + let payload = &self.range.data()[..n]; + self.silk_wb.as_mut().unwrap().replay(payload)?; + Ok(n) + } + /// Encodes the CELT frame into the internal range coder and returns its /// byte length. `frame_size` is in 48 kHz samples, `end` is the last coded /// band, and `cap` bounds the frame (the caller's buffer minus headers). @@ -431,7 +555,7 @@ impl Encoder { self.range.reset(budget); let n = self .celt - .encode(&mut self.range, pcm, frame_size, end, vbr_rate)?; + .encode(&mut self.range, pcm, frame_size, 0, end, vbr_rate)?; self.final_range = self.range.range(); Ok(n) } diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index b32fad55..61910a7c 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -107,9 +107,19 @@ pub struct Decoder { prev_mode: Option, prev_redundancy: bool, range_final: u32, + /// Test hook: drop the (CELT, SILK) layer's output before the sum. + debug_mute: (bool, bool), } impl Decoder { + /// Test hook, not for production use: silences the CELT and/or SILK + /// layer's contribution to the output (the decoder state still advances) + /// so a hybrid packet's two layers can be measured one at a time. + #[doc(hidden)] + pub fn debug_mute_layers(&mut self, celt: bool, silk: bool) { + self.debug_mute = (celt, silk); + } + /// A decoder for `channels` channels at `sample_rate`, which must be one of /// 8000, 12000, 16000, 24000 or 48000 Hz. pub fn new(sample_rate: u32, channels: usize) -> Result { @@ -144,6 +154,7 @@ impl Decoder { prev_mode: None, prev_redundancy: false, range_final: 0, + debug_mute: (false, false), }) } @@ -364,7 +375,10 @@ impl Decoder { } // Sum the two layers. - if mode != Mode::Celt { + if self.debug_mute.0 { + out.fill(0.0); + } + if mode != Mode::Celt && !self.debug_mute.1 { for (o, s) in out.iter_mut().zip(silk_pcm.iter()) { *o += *s as f32 * (1.0 / 32768.0); } diff --git a/crates/ec-opus/src/silk_enc_write.rs b/crates/ec-opus/src/silk_enc_write.rs index cb22b9f5..97d057f4 100644 --- a/crates/ec-opus/src/silk_enc_write.rs +++ b/crates/ec-opus/src/silk_enc_write.rs @@ -49,6 +49,8 @@ pub struct SilkEncoder { range: RangeEncoder, prev_gain_index: i32, final_range: u32, + /// The mirror decoder's range state after the last replay. + mirror_range: u32, voiced_frames: usize, mirror_out: Vec, target_bps: Option, @@ -88,6 +90,7 @@ impl SilkEncoder { range: RangeEncoder::new(), prev_gain_index: 10, final_range: 0, + mirror_range: 0, voiced_frames: 0, mirror_out: vec![0; 20 * 16], target_bps: None, @@ -124,6 +127,51 @@ impl SilkEncoder { /// Encodes 960 mono 48 kHz samples as one code-0 packet in `out`, /// returning its length. pub fn encode_frame(&mut self, pcm48: &[f32], out: &mut [u8]) -> Result { + let Trial { bytes, range, .. } = self.encode_inner(pcm48, None)?; + let len = bytes.len(); + self.final_range = range; + let toc = if self.fs_khz == 16 { 9u8 << 3 } else { 1u8 << 3 }; + if out.len() < 1 + len { + return Err(ec_core::Error::corrupt(format!( + "silk encode: packet needs {} bytes, buffer holds {}", + 1 + len, + out.len() + ))); + } + out[0] = toc; + out[1..1 + len].copy_from_slice(&bytes); + self.replay(&out[1..1 + len])?; + debug_assert_eq!(self.mirror_range, self.final_range); + Ok(1 + len) + } + + /// The SILK layer of a hybrid packet: codes 960 mono 48 kHz samples 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<()> { + self.encode_inner(pcm48, Some(enc)).map(|_| ()) + } + + /// 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<()> { + let fs = self.fs_khz; + let mut dec = RangeDecoder::new(payload); + self.mirror + .decode(&mut dec, &mut self.mirror_out, 20, fs as u32 * 1000, 1, true)?; + self.mirror_range = dec.range(); + Ok(()) + } + + /// Analysis, closed-loop quantisation and rate control of one frame; the + /// returned trial's `bytes` are the standalone SILK payload (TOC + /// excluded). With `shared`, the chosen frame's symbols are also written + /// into that coder (the hybrid path). + fn encode_inner(&mut self, pcm48: &[f32], shared: Option<&mut RangeEncoder>) -> Result { assert_eq!(pcm48.len(), 960, "SilkEncoder codes 20 ms mono frames"); let fs = self.fs_khz; let order = if fs == 16 { MAX_LPC_ORDER } else { 10 }; @@ -345,26 +393,9 @@ impl SilkEncoder { Run { ltp_index, pulses, err, d, u, gq } }; - // One full trial at a common gain offset (in quantiser steps): returns - // the coded packet body so the rate loop can read its exact size. - let candidates: Vec = if voiced { vec![0, 1, 2] } else { vec![0] }; - let mut trial = |step: i32| -> Trial { - let scale = GAIN_STEP.powi(step); - let mut t = targets; - for v in t.iter_mut() { - *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32; - } - let mut prev_gain_index = self.prev_gain_index; - let (gain_idx, gains_q16) = quantize_gains(&t, &mut prev_gain_index, false, NB_SUBFR); - let (per_index, run) = candidates - .iter() - .map(|&per| (per, run(per, &gains_q16))) - .min_by(|a, b| a.1.err.partial_cmp(&b.1.err).unwrap()) - .unwrap(); - - // --- Bitstream, in decode()'s order. --- - let enc = &mut self.range; - enc.reset(1275); + // Bitstream writer, in decode()'s order; shared by the sizing trials + // and the hybrid path's shared coder. + let write = |enc: &mut RangeEncoder, gain_idx: &[i8], per_index: usize, run: &Run| { enc.enc_bit_logp(vad_flag, 1); // VAD flag enc.enc_bit_logp(false, 1); // LBRR flag // Frame type. @@ -421,10 +452,32 @@ impl SilkEncoder { } enc.enc_icdf(seed_index as usize, &UNIFORM4_ICDF, 8); encode_pulses(enc, &run.pulses, signal_type, quant_offset_type as i32); + }; + // One full trial at a common gain offset (in quantiser steps): returns + // the coded packet body so the rate loop can read its exact size. + let candidates: Vec = if voiced { vec![0, 1, 2] } else { vec![0] }; + let mut trial = |step: i32| -> Trial { + let scale = GAIN_STEP.powi(step); + let mut t = targets; + for v in t.iter_mut() { + *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32; + } + let mut prev_gain_index = self.prev_gain_index; + let (gain_idx, gains_q16) = quantize_gains(&t, &mut prev_gain_index, false, NB_SUBFR); + let (per_index, run) = candidates + .iter() + .map(|&per| (per, run(per, &gains_q16))) + .min_by(|a, b| a.1.err.partial_cmp(&b.1.err).unwrap()) + .unwrap(); + + // --- Bitstream, in decode()'s order. --- + let enc = &mut self.range; + enc.reset(1275); + write(enc, &gain_idx, per_index, &run); enc.done(); debug_assert!(!enc.error()); let len = enc.range_bytes(); - Trial { bytes: enc.data()[..len].to_vec(), range: enc.range(), prev_gain_index, run } + Trial { bytes: enc.data()[..len].to_vec(), range: enc.range(), prev_gain_index, gain_idx, per_index, run } }; // Rate control: a common gain offset moves every subframe's pulse @@ -458,32 +511,15 @@ impl SilkEncoder { } self.reservoir = (self.reservoir + frame_bits - b0).clamp(-RESERVOIR_FRAMES * frame_bits, RESERVOIR_FRAMES * frame_bits); } - let Trial { bytes, range, prev_gain_index, run } = best; - let len = bytes.len(); - self.prev_gain_index = prev_gain_index; - self.voiced_frames += usize::from(voiced); - self.final_range = range; - self.shape_d.copy_from_slice(&run.d[n..]); - self.shape_u.copy_from_slice(&run.u[n..]); - self.shape_gq.copy_from_slice(&run.gq[n..]); - - let toc = if wb { 9u8 << 3 } else { 1u8 << 3 }; - if out.len() < 1 + len { - return Err(ec_core::Error::corrupt(format!( - "silk encode: packet needs {} bytes, buffer holds {}", - 1 + len, - out.len() - ))); + if let Some(enc) = shared { + write(enc, &best.gain_idx, best.per_index, &best.run); } - out[0] = toc; - out[1..1 + len].copy_from_slice(&bytes); - - // Replay through the mirror so the next frame sees decoder state. - let mut dec = RangeDecoder::new(&out[1..1 + len]); - self.mirror - .decode(&mut dec, &mut self.mirror_out, 20, fs as u32 * 1000, 1, true)?; - debug_assert_eq!(dec.range(), self.final_range); - Ok(1 + len) + self.prev_gain_index = best.prev_gain_index; + self.voiced_frames += usize::from(voiced); + self.shape_d.copy_from_slice(&best.run.d[n..]); + self.shape_u.copy_from_slice(&best.run.u[n..]); + self.shape_gq.copy_from_slice(&best.run.gq[n..]); + Ok(best) } } @@ -502,6 +538,8 @@ struct Trial { bytes: Vec, range: u32, prev_gain_index: i32, + gain_idx: [i8; MAX_NB_SUBFR], + per_index: usize, run: Run, } diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index bcafd673..b5c9a374 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -772,7 +772,7 @@ fn real_library_sweep() { // Encoder: self-consistency (range-exact against our own decoder) // --------------------------------------------------------------------------- -use ec_opus::{Application, Encoder, MultistreamEncoder}; +use ec_opus::{Application, Bandwidth, Encoder, MultistreamEncoder}; /// A deterministic music-like test signal: several detuned partials plus a /// swept component per channel, loud enough to exercise every band. @@ -887,7 +887,8 @@ fn encoder_mode_follows_application_and_bitrate() { (Application::Voip, 8_000u32, Some(1u8)), (Application::Voip, 16_000, Some(9)), (Application::Audio, 64_000, None), - (Application::Voip, 32_000, None), + (Application::Voip, 32_000, Some(15)), + (Application::Voip, 48_000, None), ]; for (app, bps, want_config) in cases { let mut enc = Encoder::new(48000, 1, app).unwrap(); @@ -1721,3 +1722,99 @@ fn silk_packets_track_encoder_bitrate() { assert!((0.8..=1.2).contains(&ratio), "target {kbps_target}: got {kbps:.2} kbps"); } } + +// --------------------------------------------------------------------------- +// Hybrid (SILK 16 kHz + CELT from band 17, one range-coded stream). + +/// Encodes mono `pcm` as hybrid packets at `bps` and decodes them with our +/// decoder, `mute` = (celt, silk) layers dropped at the decoder; asserts +/// range-state parity packet for packet. Returns (decoded, packets). +fn hybrid_roundtrip(pcm: &[f32], bps: u32, bandwidth: Option, mute: (bool, bool)) -> (Vec, Vec>) { + let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); + enc.set_bitrate(bps); + enc.set_bandwidth(bandwidth); + let mut dec = Decoder::new(48000, 1).unwrap(); + dec.debug_mute_layers(mute.0, mute.1); + let mut out = vec![0u8; 1500]; + let mut buf = vec![0f32; 5760]; + let (mut decoded, mut packets) = (Vec::new(), Vec::new()); + let mut padded = pcm.to_vec(); + padded.resize(pcm.len().div_ceil(960) * 960 + 960, 0.0); + for block in padded.chunks(960) { + let len = enc.encode_float(block, 960, &mut out).expect("hybrid encode"); + let n = dec.decode_float(&out[..len], &mut buf).expect("hybrid decode"); + assert_eq!(n, 960); + assert_eq!(dec.final_range(), enc.final_range(), "range state diverged"); + decoded.extend_from_slice(&buf[..n]); + packets.push(out[..len].to_vec()); + } + (decoded, packets) +} + +/// The two layers of a hybrid packet reach the decoder's output at the same +/// delay: a click's low-band-only and high-band-only peaks coincide at the +/// encoder's documented look-ahead. +#[test] +fn hybrid_layers_align() { + let mut click = vec![0f32; 48000]; + // Well inside the stream so both layers' predictors are running. + let at = 960 * 10 + 300; + click[at] = 0.9; + let peak = |x: &[f32]| { + x.iter().enumerate().max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()).unwrap().0 + }; + let (lb, _) = hybrid_roundtrip(&click, 32_000, None, (true, false)); + let (hb, _) = hybrid_roundtrip(&click, 32_000, None, (false, true)); + let enc = Encoder::new(48000, 1, Application::Voip).unwrap(); + let (plb, phb) = (peak(&lb) as i64 - at as i64, peak(&hb) as i64 - at as i64); + eprintln!("hybrid click: LB peak +{plb}, HB peak +{phb}, look_ahead {}", { + let mut e = enc.clone(); + e.set_bitrate(32_000); + e.look_ahead() + }); + assert!((plb - phb).abs() <= 2, "layers misaligned: LB +{plb} vs HB +{phb}"); + assert!((phb - 120).abs() <= 2, "HB peak +{phb}, look_ahead 120"); +} + +/// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks +/// the input full-band and in the SILK layer's band alone, and the reference +/// oracle decodes the packets to the same signal. +#[test] +fn hybrid_fb_roundtrip() { + for (name, pcm) in silk_sources() { + let (decoded, packets) = hybrid_roundtrip(&pcm, 32_000, None, (false, false)); + let toc = ec_opus::Toc::new(packets[0][0]); + assert_eq!(toc.config, 15, "{name}: TOC config {}", toc.config); + let (corr, lag) = aligned_corr(&pcm, &decoded, 400); + let (lb_only, _) = hybrid_roundtrip(&pcm, 32_000, None, (true, false)); + let lb_ref = lowpass(&pcm, 7000.0); + let (lb_corr, lb_lag) = aligned_corr(&lb_ref, &lb_only, 400); + let bytes: usize = packets.iter().map(Vec::len).sum(); + let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); + eprintln!("hybrid FB {name}: corr {corr:.4} at lag {lag}, LB corr {lb_corr:.4} at lag {lb_lag}, {kbps:.1} kbps"); + assert!(corr >= 0.95, "{name}: full-band corr {corr:.4}"); + // +-3: the wav16 fixture is a pure tone, whose phase moves the peak. + assert!((117..=123).contains(&lag), "{name}: aligned at lag {lag}, not the documented 120"); + assert!(lb_corr >= 0.9, "{name}: low-band corr {lb_corr:.4}"); + assert!((28.0..=36.0).contains(&kbps), "{name}: {kbps:.1} kbps for a 32 kbps CBR target"); + if let Some(oracle) = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len()) { + let n = oracle.len().min(decoded.len() - 120); + let c = correlation(&oracle[..n], &decoded[120..120 + n]); + eprintln!("hybrid FB {name}: oracle vs ours corr {c:.4}"); + assert!(c >= 0.95, "{name}: oracle corr {c:.4}"); + } + } + // SWB when asked for it, and the rest of the automatic hybrid range + // (SILK's share leaves CELT least at the bottom of it). + let speech = speech_like(); + let (_, packets) = hybrid_roundtrip(&speech, 24_000, Some(Bandwidth::SuperWide), (false, false)); + assert_eq!(ec_opus::Toc::new(packets[0][0]).config, 13); + for bps in [20_000u32, 24_000, 39_000] { + let (decoded, packets) = hybrid_roundtrip(&speech, bps, None, (false, false)); + let (corr, _) = aligned_corr(&speech, &decoded, 400); + let kbps = packets.iter().map(Vec::len).sum::() as f64 * 8.0 / (packets.len() as f64 * 20.0); + eprintln!("hybrid {bps}: config {}, corr {corr:.4}, {kbps:.1} kbps", ec_opus::Toc::new(packets[0][0]).config); + assert!(corr >= 0.9, "hybrid at {bps}: corr {corr:.4}"); + assert!(kbps <= bps as f64 / 1000.0 + 3.0, "hybrid at {bps}: {kbps:.1} kbps"); + } +}