Mono 20 ms SWB/FB hybrid packets (SILK 16 kHz + CELT from band 17)
Browse files at this commita6d027812141f4b0e8355b1e2b9a9d89126a4bccParent: c54a10c- feat
- mono 20 ms SWB/FB hybrid packets (SILK 16 kHz + CELT from band 17)
5 changed files +357 -65
- crates/ec-opus/src/celt_enc.rs +26 -7
- crates/ec-opus/src/encoder.rs +133 -9
- crates/ec-opus/src/lib.rs +15 -1
- crates/ec-opus/src/silk_enc_write.rs +84 -46
- crates/ec-opus/tests/conformance.rs +99 -2
crates/ec-opus/src/celt_enc.rsmodified+26 -7
| @@ -388,8 +388,11 @@ impl CeltEncoder { | |||
| 388 | /// Encodes one frame of interleaved `f32` (`frame_size` samples per | 388 | /// Encodes one frame of interleaved `f32` (`frame_size` samples per |
| 389 | /// channel at 48 kHz, one of 120/240/480/960 — of which | 389 | /// channel at 48 kHz, one of 120/240/480/960 — of which |
| 390 | /// `frame_size/upsample` are read from `pcm`) into `enc`, which must have | 390 | /// `frame_size/upsample` are read from `pcm`) into `enc`, which must have |
| 391 | - /// been `reset` to the frame's byte budget. `end` bounds the coded bands, | 391 | + /// been `reset` to the frame's byte budget. `start..end` bounds the coded |
| 392 | - /// which is how the caller limits the coded bandwidth. With | 392 | + /// bands — `end` is how the caller limits the coded bandwidth, `start` |
| 393 | + /// (0, or 17 under a hybrid packet's SILK layer) skips the low bands | ||
| 394 | + /// exactly as the decoder's `start_band` does: no energy, no shapes, no | ||
| 395 | + /// postfilter bit, allocation over the coded span only. With | ||
| 393 | /// `vbr_rate_bps` set, the frame may be shrunk below that budget | 396 | /// `vbr_rate_bps` set, the frame may be shrunk below that budget |
| 394 | /// (constrained VBR); the return value is the final frame size in bytes. | 397 | /// (constrained VBR); the return value is the final frame size in bytes. |
| 395 | pub fn encode( | 398 | pub fn encode( |
| @@ -397,6 +400,7 @@ impl CeltEncoder { | |||
| 397 | enc: &mut RangeEncoder, | 400 | enc: &mut RangeEncoder, |
| 398 | pcm: &[f32], | 401 | pcm: &[f32], |
| 399 | frame_size: usize, | 402 | frame_size: usize, |
| 403 | + start: usize, | ||
| 400 | end: usize, | 404 | end: usize, |
| 401 | vbr_rate_bps: u32, | 405 | vbr_rate_bps: u32, |
| 402 | ) -> Result<usize> { | 406 | ) -> Result<usize> { |
| @@ -422,7 +426,7 @@ impl CeltEncoder { | |||
| 422 | pcm.len() | 426 | pcm.len() |
| 423 | ))); | 427 | ))); |
| 424 | } | 428 | } |
| 425 | - let (start, end) = (0usize, end.clamp(1, NB_BANDS)); | 429 | + let end = end.clamp(start + 1, NB_BANDS); |
| 426 | 430 | ||
| 427 | let mut nb_compressed = enc.storage(); | 431 | let mut nb_compressed = enc.storage(); |
| 428 | let mut nb_available = nb_compressed as i32; | 432 | let mut nb_available = nb_compressed as i32; |
| @@ -485,7 +489,13 @@ impl CeltEncoder { | |||
| 485 | } | 489 | } |
| 486 | 490 | ||
| 487 | // --- Silence flag (first symbol of the frame) ----------------------- | 491 | // --- Silence flag (first symbol of the frame) ----------------------- |
| 488 | - enc.enc_bit_logp(silence, 15); | 492 | + // Only exists when CELT opens the stream (decoder: `tell == 1`); under |
| 493 | + // a hybrid packet's SILK layer the frame is never flagged silent. | ||
| 494 | + if enc.tell() == 1 { | ||
| 495 | + enc.enc_bit_logp(silence, 15); | ||
| 496 | + } else { | ||
| 497 | + silence = false; | ||
| 498 | + } | ||
| 489 | if silence { | 499 | if silence { |
| 490 | if vbr_rate > 0 { | 500 | if vbr_rate > 0 { |
| 491 | nb_compressed = nb_compressed.min(2); | 501 | nb_compressed = nb_compressed.min(2); |
| @@ -497,7 +507,8 @@ impl CeltEncoder { | |||
| 497 | } | 507 | } |
| 498 | 508 | ||
| 499 | // --- Postfilter: always off (throughput-first, = complexity < 5) ---- | 509 | // --- Postfilter: always off (throughput-first, = complexity < 5) ---- |
| 500 | - if enc.tell() as i32 + 16 <= total_bits { | 510 | + // The flag exists only when band 0 is coded (decoder: `start == 0`). |
| 511 | + if start == 0 && enc.tell() as i32 + 16 <= total_bits { | ||
| 501 | enc.enc_bit_logp(false, 1); | 512 | enc.enc_bit_logp(false, 1); |
| 502 | } | 513 | } |
| 503 | 514 | ||
| @@ -515,7 +526,8 @@ impl CeltEncoder { | |||
| 515 | // --- Forward MDCTs, energies, normalisation ------------------------- | 526 | // --- Forward MDCTs, energies, normalisation ------------------------- |
| 516 | self.compute_mdcts(short_blocks, lm, n, c); | 527 | self.compute_mdcts(short_blocks, lm, n, c); |
| 517 | for ch in 0..c { | 528 | for ch in 0..c { |
| 518 | - for i in 0..end { | 529 | + self.x[ch * n..ch * n + m * E_BANDS[start]].fill(0.0); |
| 530 | + for i in start..end { | ||
| 519 | let mut sum = 1e-27f32; | 531 | let mut sum = 1e-27f32; |
| 520 | for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { | 532 | for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { |
| 521 | let v = self.freq[ch * n + j]; | 533 | let v = self.freq[ch * n + j]; |
| @@ -525,7 +537,7 @@ impl CeltEncoder { | |||
| 525 | self.band_log_e[i + ch * NB_BANDS] = | 537 | self.band_log_e[i + ch * NB_BANDS] = |
| 526 | (self.band_e[i + ch * NB_BANDS] as f64).log2() as f32 - E_MEANS[i]; | 538 | (self.band_e[i + ch * NB_BANDS] as f64).log2() as f32 - E_MEANS[i]; |
| 527 | } | 539 | } |
| 528 | - for i in 0..end { | 540 | + for i in start..end { |
| 529 | let g = 1.0 / (1e-27 + self.band_e[i + ch * NB_BANDS]); | 541 | let g = 1.0 / (1e-27 + self.band_e[i + ch * NB_BANDS]); |
| 530 | for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { | 542 | for j in m * E_BANDS[i]..m * E_BANDS[i + 1] { |
| 531 | self.x[ch * n + j] = self.freq[ch * n + j] * g; | 543 | self.x[ch * n + j] = self.freq[ch * n + j] * g; |
| @@ -811,6 +823,13 @@ impl CeltEncoder { | |||
| 811 | self.old_band_e[NB_BANDS + i] = self.old_band_e[i]; | 823 | self.old_band_e[NB_BANDS + i] = self.old_band_e[i]; |
| 812 | } | 824 | } |
| 813 | } | 825 | } |
| 826 | + // Uncoded bands hold no energy history (the decoder clears them the | ||
| 827 | + // same way), so a later start/end change predicts from the same state. | ||
| 828 | + for ch in 0..2 { | ||
| 829 | + for i in (0..start).chain(end..NB_BANDS) { | ||
| 830 | + self.old_band_e[ch * NB_BANDS + i] = 0.0; | ||
| 831 | + } | ||
| 832 | + } | ||
| 814 | if is_transient { | 833 | if is_transient { |
| 815 | self.consec_transient += 1; | 834 | self.consec_transient += 1; |
| 816 | } else { | 835 | } else { |
crates/ec-opus/src/encoder.rsmodified+133 -9
| @@ -5,8 +5,10 @@ | |||
| 5 | //! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s | 5 | //! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s |
| 6 | //! default) picks CELT (TOC configs 16..31, every rate and frame size) or | 6 | //! default) picks CELT (TOC configs 16..31, every rate and frame size) or |
| 7 | //! SILK (TOC configs 1/9, mono NB/WB 20 ms only — stereo SILK and SILK at | 7 | //! SILK (TOC configs 1/9, mono NB/WB 20 ms only — stereo SILK and SILK at |
| 8 | -//! other frame sizes fall back to CELT, documented at the fallback site). | 8 | +//! other frame sizes fall back to CELT, documented at the fallback site) or |
| 9 | -//! Hybrid is not implemented yet and also falls back to CELT. | 9 | +//! Hybrid (TOC configs 13/15, mono SWB/FB 20 ms: SILK at 16 kHz under CELT |
| 10 | +//! from band 17 up, one range-coded stream; stereo and other frame sizes | ||
| 11 | +//! fall back to CELT). | ||
| 10 | //! | 12 | //! |
| 11 | //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and | 13 | //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and |
| 12 | //! the coded bandwidth is capped at the input's own Nyquist, so the images | 14 | //! the coded bandwidth is capped at the input's own Nyquist, so the images |
| @@ -37,6 +39,13 @@ const MAX_FRAME_BYTES: usize = 1275; | |||
| 37 | /// don't have to and don't match. | 39 | /// don't have to and don't match. |
| 38 | const SILK_LOOK_AHEAD_48K_NB: usize = 58; | 40 | const SILK_LOOK_AHEAD_48K_NB: usize = 58; |
| 39 | const SILK_LOOK_AHEAD_48K_WB: usize = 50; | 41 | const SILK_LOOK_AHEAD_48K_WB: usize = 50; |
| 42 | +/// How far the hybrid path delays the SILK layer's input so its output lines | ||
| 43 | +/// up with the CELT layer's at the decoder (which sums them as-is): CELT's | ||
| 44 | +/// overlap (120) minus SILK's WB round trip, click-measured through the | ||
| 45 | +/// decoder with one layer muted (`hybrid_layers_align` in conformance.rs). | ||
| 46 | +const HYBRID_SILK_DELAY_48K: usize = 120 - SILK_LOOK_AHEAD_48K_WB; | ||
| 47 | +/// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent. | ||
| 48 | +const HYBRID_CELT_MIN_BYTES: usize = 8; | ||
| 40 | 49 | ||
| 41 | /// What the caller is encoding. This encoder is CELT-only, so the setting | 50 | /// What the caller is encoding. This encoder is CELT-only, so the setting |
| 42 | /// biases the coded bandwidth rather than selecting a different layer. | 51 | /// biases the coded bandwidth rather than selecting a different layer. |
| @@ -75,6 +84,8 @@ pub struct Encoder { | |||
| 75 | /// Scratch space for the SILK payload, sized once so the steady-state | 84 | /// Scratch space for the SILK payload, sized once so the steady-state |
| 76 | /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. | 85 | /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. |
| 77 | silk_buf: [u8; MAX_FRAME_BYTES + 1], | 86 | silk_buf: [u8; MAX_FRAME_BYTES + 1], |
| 87 | + /// Hybrid: the last [`HYBRID_SILK_DELAY_48K`] samples of SILK-layer input. | ||
| 88 | + silk_delay: Vec<f32>, | ||
| 78 | } | 89 | } |
| 79 | 90 | ||
| 80 | impl Encoder { | 91 | impl Encoder { |
| @@ -117,13 +128,14 @@ impl Encoder { | |||
| 117 | silk_nb: None, | 128 | silk_nb: None, |
| 118 | silk_wb: None, | 129 | silk_wb: None, |
| 119 | silk_buf: [0u8; MAX_FRAME_BYTES + 1], | 130 | silk_buf: [0u8; MAX_FRAME_BYTES + 1], |
| 131 | + silk_delay: Vec::new(), | ||
| 120 | }) | 132 | }) |
| 121 | } | 133 | } |
| 122 | 134 | ||
| 123 | - /// Overrides the automatic SILK/CELT choice `wants_silk` would make from | 135 | + /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and |
| 124 | - /// the application and bitrate. [`Mode::Hybrid`] is unimplemented and | 136 | + /// `hybrid_choice` make from the application and bitrate; pass `None` to |
| 125 | - /// falls back to CELT (documented at the fallback site in | 137 | + /// restore the automatic pick. Requests this encoder cannot honour |
| 126 | - /// [`Encoder::silk_choice`]); pass `None` to restore the automatic pick. | 138 | + /// (stereo SILK/Hybrid, frames other than 20 ms) fall back to CELT. |
| 127 | pub fn set_mode(&mut self, mode: Option<Mode>) { | 139 | pub fn set_mode(&mut self, mode: Option<Mode>) { |
| 128 | self.mode = mode; | 140 | self.mode = mode; |
| 129 | } | 141 | } |
| @@ -144,7 +156,8 @@ impl Encoder { | |||
| 144 | /// SILK (mono, when the application/bitrate or an explicit | 156 | /// SILK (mono, when the application/bitrate or an explicit |
| 145 | /// [`Encoder::set_mode`] select it): [`SILK_LOOK_AHEAD_48K_NB`] or | 157 | /// [`Encoder::set_mode`] select it): [`SILK_LOOK_AHEAD_48K_NB`] or |
| 146 | /// [`SILK_LOOK_AHEAD_48K_WB`], the analysis-plus-synthesis resampler | 158 | /// [`SILK_LOOK_AHEAD_48K_WB`], the analysis-plus-synthesis resampler |
| 147 | - /// round trip, click-measured per bandwidth. | 159 | + /// round trip, click-measured per bandwidth. Hybrid: CELT's 120, the |
| 160 | + /// SILK layer being delayed to meet it ([`HYBRID_SILK_DELAY_48K`]). | ||
| 148 | pub fn look_ahead(&self) -> usize { | 161 | pub fn look_ahead(&self) -> usize { |
| 149 | if self.channels == 1 { | 162 | if self.channels == 1 { |
| 150 | if let Some(wideband) = self.wants_silk() { | 163 | if let Some(wideband) = self.wants_silk() { |
| @@ -195,12 +208,13 @@ impl Encoder { | |||
| 195 | self.celt.reset(); | 208 | self.celt.reset(); |
| 196 | self.silk_nb = None; | 209 | self.silk_nb = None; |
| 197 | self.silk_wb = None; | 210 | self.silk_wb = None; |
| 211 | + self.silk_delay.clear(); | ||
| 198 | self.final_range = 0; | 212 | self.final_range = 0; |
| 199 | } | 213 | } |
| 200 | 214 | ||
| 201 | /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) | 215 | /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) |
| 202 | /// call for SILK, and if so, wideband (else narrowband). `None` means | 216 | /// call for SILK, and if so, wideband (else narrowband). `None` means |
| 203 | - /// CELT (or Hybrid, unimplemented and mapped to CELT). | 217 | + /// CELT or Hybrid (`hybrid_choice` tells those apart). |
| 204 | fn wants_silk(&self) -> Option<bool> { | 218 | fn wants_silk(&self) -> Option<bool> { |
| 205 | match self.mode { | 219 | match self.mode { |
| 206 | Some(Mode::Celt) | Some(Mode::Hybrid) => None, | 220 | Some(Mode::Celt) | Some(Mode::Hybrid) => None, |
| @@ -226,6 +240,53 @@ impl Encoder { | |||
| 226 | Some(wideband) | 240 | Some(wideband) |
| 227 | } | 241 | } |
| 228 | 242 | ||
| 243 | + /// Whether this frame goes out as a hybrid packet, and at which of the two | ||
| 244 | + /// hybrid bandwidths. Automatic: VoIP from 20 kbps (where SILK alone | ||
| 245 | + /// stops) to 40 kbps (where CELT alone is the better speech coder too), | ||
| 246 | + /// at the bitrate's own bandwidth (SWB/FB; narrower requests are CELT's). | ||
| 247 | + /// Mono 20 ms only — stereo Hybrid (which needs stereo SILK) and the | ||
| 248 | + /// 10 ms hybrid configs are not implemented and fall back to CELT. | ||
| 249 | + fn hybrid_choice(&self, frame_48k: usize) -> Option<Bandwidth> { | ||
| 250 | + let wanted = match self.mode { | ||
| 251 | + Some(Mode::Hybrid) => true, | ||
| 252 | + Some(_) => false, | ||
| 253 | + None => { | ||
| 254 | + self.application == Application::Voip | ||
| 255 | + && (20_000..40_000).contains(&self.bitrate) | ||
| 256 | + } | ||
| 257 | + }; | ||
| 258 | + if !wanted || self.channels != 1 || frame_48k != 960 { | ||
| 259 | + return None; | ||
| 260 | + } | ||
| 261 | + let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth()); | ||
| 262 | + match bandwidth { | ||
| 263 | + Bandwidth::SuperWide | Bandwidth::Full => Some(bandwidth), | ||
| 264 | + // A forced Hybrid codes at least SWB; an automatic one that the | ||
| 265 | + // bitrate would cap narrower is CELT's. | ||
| 266 | + _ if self.mode == Some(Mode::Hybrid) => Some(Bandwidth::SuperWide), | ||
| 267 | + _ => None, | ||
| 268 | + } | ||
| 269 | + } | ||
| 270 | + | ||
| 271 | + /// The SILK layer's share of a mono hybrid packet's bitrate, the | ||
| 272 | + /// reference's 20 ms table interpolated: the rest is CELT's. | ||
| 273 | + fn hybrid_silk_rate(total: u32, bandwidth: Bandwidth) -> u32 { | ||
| 274 | + const TABLE: [(u32, u32, u32); 7] = [ | ||
| 275 | + (0, 0, 0), | ||
| 276 | + (12000, 10000, 11000), | ||
| 277 | + (16000, 13500, 14500), | ||
| 278 | + (20000, 16000, 17000), | ||
| 279 | + (24000, 18000, 19000), | ||
| 280 | + (32000, 22000, 24000), | ||
| 281 | + (64000, 38000, 42000), | ||
| 282 | + ]; | ||
| 283 | + let pick = |row: &(u32, u32, u32)| if bandwidth == Bandwidth::Full { row.2 } else { row.1 }; | ||
| 284 | + let total = total.min(64000); | ||
| 285 | + let i = TABLE.iter().rposition(|r| r.0 <= total).unwrap().min(TABLE.len() - 2); | ||
| 286 | + let (lo, hi) = (&TABLE[i], &TABLE[i + 1]); | ||
| 287 | + pick(lo) + (pick(hi) - pick(lo)) * (total - lo.0) / (hi.0 - lo.0) | ||
| 288 | + } | ||
| 289 | + | ||
| 229 | /// Zero-stuffs a mono, `frame_size`-sample native-rate frame up to | 290 | /// Zero-stuffs a mono, `frame_size`-sample native-rate frame up to |
| 230 | /// `frame_size * upsample` samples at 48 kHz, the rate [`SilkEncoder`] | 291 | /// `frame_size * upsample` samples at 48 kHz, the rate [`SilkEncoder`] |
| 231 | /// takes — the same technique [`CeltEncoder::encode`] uses, scaled by | 292 | /// takes — the same technique [`CeltEncoder::encode`] uses, scaled by |
| @@ -269,6 +330,11 @@ impl Encoder { | |||
| 269 | self.final_range = enc.final_range(); | 330 | self.final_range = enc.final_range(); |
| 270 | return Ok((self.silk_buf[0], &self.silk_buf[1..n])); | 331 | return Ok((self.silk_buf[0], &self.silk_buf[1..n])); |
| 271 | } | 332 | } |
| 333 | + if let Some(bandwidth) = self.hybrid_choice(frame_48k) { | ||
| 334 | + let n = self.encode_hybrid(pcm, frame_size, bandwidth, cap)?; | ||
| 335 | + let config = if bandwidth == Bandwidth::Full { 15u8 } else { 13 }; | ||
| 336 | + return Ok((config << 3, &self.range.data()[..n])); | ||
| 337 | + } | ||
| 272 | let (toc, frame_48k, end) = self.toc(frame_size)?; | 338 | let (toc, frame_48k, end) = self.toc(frame_size)?; |
| 273 | let n = self.encode_frame(pcm, frame_48k, end, cap)?; | 339 | let n = self.encode_frame(pcm, frame_48k, end, cap)?; |
| 274 | Ok((toc, &self.range.data()[..n])) | 340 | Ok((toc, &self.range.data()[..n])) |
| @@ -404,6 +470,64 @@ impl Encoder { | |||
| 404 | Ok(1 + len_bytes + n) | 470 | Ok(1 + len_bytes + n) |
| 405 | } | 471 | } |
| 406 | 472 | ||
| 473 | + /// One hybrid frame (mono, 20 ms, `bandwidth` SWB or FB) into the | ||
| 474 | + /// internal range coder, returning its byte length: the SILK layer's | ||
| 475 | + /// symbols (WB, 16 kHz internal, fed the input delayed by | ||
| 476 | + /// [`HYBRID_SILK_DELAY_48K`]), the no-redundancy flag under the decoder's | ||
| 477 | + /// exact presence rule, then the CELT layer from band 17 in the same | ||
| 478 | + /// coder. CBR: the packet is the bitrate's size unless SILK alone needs | ||
| 479 | + /// more, in which case CELT keeps [`HYBRID_CELT_MIN_BYTES`] on top. | ||
| 480 | + fn encode_hybrid( | ||
| 481 | + &mut self, | ||
| 482 | + pcm: &[f32], | ||
| 483 | + frame_size: usize, | ||
| 484 | + bandwidth: Bandwidth, | ||
| 485 | + cap: usize, | ||
| 486 | + ) -> Result<usize> { | ||
| 487 | + let cap = cap.min(MAX_FRAME_BYTES); | ||
| 488 | + let budget = ((self.bitrate as u64 * 960 + 4 * 48000) / (8 * 48000)) as usize; | ||
| 489 | + let budget = budget.saturating_sub(1).clamp(2, cap); | ||
| 490 | + if cap < HYBRID_CELT_MIN_BYTES + 2 { | ||
| 491 | + return Err(Error::corrupt( | ||
| 492 | + "opus encode: output buffer smaller than the minimum hybrid packet", | ||
| 493 | + )); | ||
| 494 | + } | ||
| 495 | + let stuffed = self.zero_stuff_mono(pcm, frame_size); | ||
| 496 | + let d = HYBRID_SILK_DELAY_48K; | ||
| 497 | + self.silk_delay.resize(d, 0.0); | ||
| 498 | + let mut delayed = Vec::with_capacity(960); | ||
| 499 | + delayed.extend_from_slice(&self.silk_delay); | ||
| 500 | + delayed.extend_from_slice(&stuffed[..960 - d]); | ||
| 501 | + self.silk_delay.copy_from_slice(&stuffed[960 - d..]); | ||
| 502 | + | ||
| 503 | + self.range.reset(cap); | ||
| 504 | + let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)); | ||
| 505 | + silk.set_bitrate(Self::hybrid_silk_rate(self.bitrate, bandwidth)); | ||
| 506 | + silk.encode_hybrid(&delayed, &mut self.range)?; | ||
| 507 | + let silk_bytes = (self.range.tell() as usize).div_ceil(8); | ||
| 508 | + let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap); | ||
| 509 | + self.range.shrink(budget); | ||
| 510 | + // Redundancy flag: present under exactly the decoder's condition. | ||
| 511 | + if self.range.tell() as usize + 17 + 20 <= 8 * budget { | ||
| 512 | + self.range.enc_bit_logp(false, 12); | ||
| 513 | + } | ||
| 514 | + // CELT sees the same input as SILK: start band 17 alone keeps it off | ||
| 515 | + // the low band (a one-pole ~6 kHz high-pass here measured identical | ||
| 516 | + // full-band correlation, so there is none). | ||
| 517 | + let n = self.celt.encode( | ||
| 518 | + &mut self.range, | ||
| 519 | + pcm, | ||
| 520 | + 960, | ||
| 521 | + 17, | ||
| 522 | + bandwidth.celt_end_band(), | ||
| 523 | + 0, | ||
| 524 | + )?; | ||
| 525 | + self.final_range = self.range.range(); | ||
| 526 | + let payload = &self.range.data()[..n]; | ||
| 527 | + self.silk_wb.as_mut().unwrap().replay(payload)?; | ||
| 528 | + Ok(n) | ||
| 529 | + } | ||
| 530 | + | ||
| 407 | /// Encodes the CELT frame into the internal range coder and returns its | 531 | /// Encodes the CELT frame into the internal range coder and returns its |
| 408 | /// byte length. `frame_size` is in 48 kHz samples, `end` is the last coded | 532 | /// byte length. `frame_size` is in 48 kHz samples, `end` is the last coded |
| 409 | /// band, and `cap` bounds the frame (the caller's buffer minus headers). | 533 | /// band, and `cap` bounds the frame (the caller's buffer minus headers). |
| @@ -431,7 +555,7 @@ impl Encoder { | |||
| 431 | self.range.reset(budget); | 555 | self.range.reset(budget); |
| 432 | let n = self | 556 | let n = self |
| 433 | .celt | 557 | .celt |
| 434 | - .encode(&mut self.range, pcm, frame_size, end, vbr_rate)?; | 558 | + .encode(&mut self.range, pcm, frame_size, 0, end, vbr_rate)?; |
| 435 | self.final_range = self.range.range(); | 559 | self.final_range = self.range.range(); |
| 436 | Ok(n) | 560 | Ok(n) |
| 437 | } | 561 | } |
crates/ec-opus/src/lib.rsmodified+15 -1
| @@ -107,9 +107,19 @@ pub struct Decoder { | |||
| 107 | prev_mode: Option<Mode>, | 107 | prev_mode: Option<Mode>, |
| 108 | prev_redundancy: bool, | 108 | prev_redundancy: bool, |
| 109 | range_final: u32, | 109 | range_final: u32, |
| 110 | + /// Test hook: drop the (CELT, SILK) layer's output before the sum. | ||
| 111 | + debug_mute: (bool, bool), | ||
| 110 | } | 112 | } |
| 111 | 113 | ||
| 112 | impl Decoder { | 114 | impl Decoder { |
| 115 | + /// Test hook, not for production use: silences the CELT and/or SILK | ||
| 116 | + /// layer's contribution to the output (the decoder state still advances) | ||
| 117 | + /// so a hybrid packet's two layers can be measured one at a time. | ||
| 118 | + #[doc(hidden)] | ||
| 119 | + pub fn debug_mute_layers(&mut self, celt: bool, silk: bool) { | ||
| 120 | + self.debug_mute = (celt, silk); | ||
| 121 | + } | ||
| 122 | + | ||
| 113 | /// A decoder for `channels` channels at `sample_rate`, which must be one of | 123 | /// A decoder for `channels` channels at `sample_rate`, which must be one of |
| 114 | /// 8000, 12000, 16000, 24000 or 48000 Hz. | 124 | /// 8000, 12000, 16000, 24000 or 48000 Hz. |
| 115 | pub fn new(sample_rate: u32, channels: usize) -> Result<Decoder> { | 125 | pub fn new(sample_rate: u32, channels: usize) -> Result<Decoder> { |
| @@ -144,6 +154,7 @@ impl Decoder { | |||
| 144 | prev_mode: None, | 154 | prev_mode: None, |
| 145 | prev_redundancy: false, | 155 | prev_redundancy: false, |
| 146 | range_final: 0, | 156 | range_final: 0, |
| 157 | + debug_mute: (false, false), | ||
| 147 | }) | 158 | }) |
| 148 | } | 159 | } |
| 149 | 160 | ||
| @@ -364,7 +375,10 @@ impl Decoder { | |||
| 364 | } | 375 | } |
| 365 | 376 | ||
| 366 | // Sum the two layers. | 377 | // Sum the two layers. |
| 367 | - if mode != Mode::Celt { | 378 | + if self.debug_mute.0 { |
| 379 | + out.fill(0.0); | ||
| 380 | + } | ||
| 381 | + if mode != Mode::Celt && !self.debug_mute.1 { | ||
| 368 | for (o, s) in out.iter_mut().zip(silk_pcm.iter()) { | 382 | for (o, s) in out.iter_mut().zip(silk_pcm.iter()) { |
| 369 | *o += *s as f32 * (1.0 / 32768.0); | 383 | *o += *s as f32 * (1.0 / 32768.0); |
| 370 | } | 384 | } |
crates/ec-opus/src/silk_enc_write.rsmodified+84 -46
| @@ -49,6 +49,8 @@ pub struct SilkEncoder { | |||
| 49 | range: RangeEncoder, | 49 | range: RangeEncoder, |
| 50 | prev_gain_index: i32, | 50 | prev_gain_index: i32, |
| 51 | final_range: u32, | 51 | final_range: u32, |
| 52 | + /// The mirror decoder's range state after the last replay. | ||
| 53 | + mirror_range: u32, | ||
| 52 | voiced_frames: usize, | 54 | voiced_frames: usize, |
| 53 | mirror_out: Vec<i16>, | 55 | mirror_out: Vec<i16>, |
| 54 | target_bps: Option<u32>, | 56 | target_bps: Option<u32>, |
| @@ -88,6 +90,7 @@ impl SilkEncoder { | |||
| 88 | range: RangeEncoder::new(), | 90 | range: RangeEncoder::new(), |
| 89 | prev_gain_index: 10, | 91 | prev_gain_index: 10, |
| 90 | final_range: 0, | 92 | final_range: 0, |
| 93 | + mirror_range: 0, | ||
| 91 | voiced_frames: 0, | 94 | voiced_frames: 0, |
| 92 | mirror_out: vec![0; 20 * 16], | 95 | mirror_out: vec![0; 20 * 16], |
| 93 | target_bps: None, | 96 | target_bps: None, |
| @@ -124,6 +127,51 @@ impl SilkEncoder { | |||
| 124 | /// Encodes 960 mono 48 kHz samples as one code-0 packet in `out`, | 127 | /// Encodes 960 mono 48 kHz samples as one code-0 packet in `out`, |
| 125 | /// returning its length. | 128 | /// returning its length. |
| 126 | pub fn encode_frame(&mut self, pcm48: &[f32], out: &mut [u8]) -> Result<usize> { | 129 | pub fn encode_frame(&mut self, pcm48: &[f32], out: &mut [u8]) -> Result<usize> { |
| 130 | + let Trial { bytes, range, .. } = self.encode_inner(pcm48, None)?; | ||
| 131 | + let len = bytes.len(); | ||
| 132 | + self.final_range = range; | ||
| 133 | + let toc = if self.fs_khz == 16 { 9u8 << 3 } else { 1u8 << 3 }; | ||
| 134 | + if out.len() < 1 + len { | ||
| 135 | + return Err(ec_core::Error::corrupt(format!( | ||
| 136 | + "silk encode: packet needs {} bytes, buffer holds {}", | ||
| 137 | + 1 + len, | ||
| 138 | + out.len() | ||
| 139 | + ))); | ||
| 140 | + } | ||
| 141 | + out[0] = toc; | ||
| 142 | + out[1..1 + len].copy_from_slice(&bytes); | ||
| 143 | + self.replay(&out[1..1 + len])?; | ||
| 144 | + debug_assert_eq!(self.mirror_range, self.final_range); | ||
| 145 | + Ok(1 + len) | ||
| 146 | + } | ||
| 147 | + | ||
| 148 | + /// The SILK layer of a hybrid packet: codes 960 mono 48 kHz samples into | ||
| 149 | + /// `enc`, the packet's shared range coder (SILK symbols first; the CELT | ||
| 150 | + /// layer continues in the same coder), without finishing it. The caller | ||
| 151 | + /// must [`SilkEncoder::replay`] the finished payload so this encoder's | ||
| 152 | + /// decoder mirror advances. | ||
| 153 | + pub fn encode_hybrid(&mut self, pcm48: &[f32], enc: &mut RangeEncoder) -> Result<()> { | ||
| 154 | + self.encode_inner(pcm48, Some(enc)).map(|_| ()) | ||
| 155 | + } | ||
| 156 | + | ||
| 157 | + /// Decodes `payload` (TOC stripped) through the mirror decoder so the next | ||
| 158 | + /// frame predicts from the decoder's state; [`SilkEncoder::encode_frame`] | ||
| 159 | + /// does this itself, [`SilkEncoder::encode_hybrid`] callers do it once | ||
| 160 | + /// the packet is complete. | ||
| 161 | + pub fn replay(&mut self, payload: &[u8]) -> Result<()> { | ||
| 162 | + let fs = self.fs_khz; | ||
| 163 | + let mut dec = RangeDecoder::new(payload); | ||
| 164 | + self.mirror | ||
| 165 | + .decode(&mut dec, &mut self.mirror_out, 20, fs as u32 * 1000, 1, true)?; | ||
| 166 | + self.mirror_range = dec.range(); | ||
| 167 | + Ok(()) | ||
| 168 | + } | ||
| 169 | + | ||
| 170 | + /// Analysis, closed-loop quantisation and rate control of one frame; the | ||
| 171 | + /// returned trial's `bytes` are the standalone SILK payload (TOC | ||
| 172 | + /// excluded). With `shared`, the chosen frame's symbols are also written | ||
| 173 | + /// into that coder (the hybrid path). | ||
| 174 | + fn encode_inner(&mut self, pcm48: &[f32], shared: Option<&mut RangeEncoder>) -> Result<Trial> { | ||
| 127 | assert_eq!(pcm48.len(), 960, "SilkEncoder codes 20 ms mono frames"); | 175 | assert_eq!(pcm48.len(), 960, "SilkEncoder codes 20 ms mono frames"); |
| 128 | let fs = self.fs_khz; | 176 | let fs = self.fs_khz; |
| 129 | let order = if fs == 16 { MAX_LPC_ORDER } else { 10 }; | 177 | let order = if fs == 16 { MAX_LPC_ORDER } else { 10 }; |
| @@ -345,26 +393,9 @@ impl SilkEncoder { | |||
| 345 | Run { ltp_index, pulses, err, d, u, gq } | 393 | Run { ltp_index, pulses, err, d, u, gq } |
| 346 | }; | 394 | }; |
| 347 | 395 | ||
| 348 | - // One full trial at a common gain offset (in quantiser steps): returns | 396 | + // Bitstream writer, in decode()'s order; shared by the sizing trials |
| 349 | - // the coded packet body so the rate loop can read its exact size. | 397 | + // and the hybrid path's shared coder. |
| 350 | - let candidates: Vec<usize> = if voiced { vec![0, 1, 2] } else { vec![0] }; | 398 | + let write = |enc: &mut RangeEncoder, gain_idx: &[i8], per_index: usize, run: &Run| { |
| 351 | - let mut trial = |step: i32| -> Trial { | ||
| 352 | - let scale = GAIN_STEP.powi(step); | ||
| 353 | - let mut t = targets; | ||
| 354 | - for v in t.iter_mut() { | ||
| 355 | - *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32; | ||
| 356 | - } | ||
| 357 | - let mut prev_gain_index = self.prev_gain_index; | ||
| 358 | - let (gain_idx, gains_q16) = quantize_gains(&t, &mut prev_gain_index, false, NB_SUBFR); | ||
| 359 | - let (per_index, run) = candidates | ||
| 360 | - .iter() | ||
| 361 | - .map(|&per| (per, run(per, &gains_q16))) | ||
| 362 | - .min_by(|a, b| a.1.err.partial_cmp(&b.1.err).unwrap()) | ||
| 363 | - .unwrap(); | ||
| 364 | - | ||
| 365 | - // --- Bitstream, in decode()'s order. --- | ||
| 366 | - let enc = &mut self.range; | ||
| 367 | - enc.reset(1275); | ||
| 368 | enc.enc_bit_logp(vad_flag, 1); // VAD flag | 399 | enc.enc_bit_logp(vad_flag, 1); // VAD flag |
| 369 | enc.enc_bit_logp(false, 1); // LBRR flag | 400 | enc.enc_bit_logp(false, 1); // LBRR flag |
| 370 | // Frame type. | 401 | // Frame type. |
| @@ -421,10 +452,32 @@ impl SilkEncoder { | |||
| 421 | } | 452 | } |
| 422 | enc.enc_icdf(seed_index as usize, &UNIFORM4_ICDF, 8); | 453 | enc.enc_icdf(seed_index as usize, &UNIFORM4_ICDF, 8); |
| 423 | encode_pulses(enc, &run.pulses, signal_type, quant_offset_type as i32); | 454 | encode_pulses(enc, &run.pulses, signal_type, quant_offset_type as i32); |
| 455 | + }; | ||
| 456 | + // One full trial at a common gain offset (in quantiser steps): returns | ||
| 457 | + // the coded packet body so the rate loop can read its exact size. | ||
| 458 | + let candidates: Vec<usize> = if voiced { vec![0, 1, 2] } else { vec![0] }; | ||
| 459 | + let mut trial = |step: i32| -> Trial { | ||
| 460 | + let scale = GAIN_STEP.powi(step); | ||
| 461 | + let mut t = targets; | ||
| 462 | + for v in t.iter_mut() { | ||
| 463 | + *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32; | ||
| 464 | + } | ||
| 465 | + let mut prev_gain_index = self.prev_gain_index; | ||
| 466 | + let (gain_idx, gains_q16) = quantize_gains(&t, &mut prev_gain_index, false, NB_SUBFR); | ||
| 467 | + let (per_index, run) = candidates | ||
| 468 | + .iter() | ||
| 469 | + .map(|&per| (per, run(per, &gains_q16))) | ||
| 470 | + .min_by(|a, b| a.1.err.partial_cmp(&b.1.err).unwrap()) | ||
| 471 | + .unwrap(); | ||
| 472 | + | ||
| 473 | + // --- Bitstream, in decode()'s order. --- | ||
| 474 | + let enc = &mut self.range; | ||
| 475 | + enc.reset(1275); | ||
| 476 | + write(enc, &gain_idx, per_index, &run); | ||
| 424 | enc.done(); | 477 | enc.done(); |
| 425 | debug_assert!(!enc.error()); | 478 | debug_assert!(!enc.error()); |
| 426 | let len = enc.range_bytes(); | 479 | let len = enc.range_bytes(); |
| 427 | - Trial { bytes: enc.data()[..len].to_vec(), range: enc.range(), prev_gain_index, run } | 480 | + Trial { bytes: enc.data()[..len].to_vec(), range: enc.range(), prev_gain_index, gain_idx, per_index, run } |
| 428 | }; | 481 | }; |
| 429 | 482 | ||
| 430 | // Rate control: a common gain offset moves every subframe's pulse | 483 | // Rate control: a common gain offset moves every subframe's pulse |
| @@ -458,32 +511,15 @@ impl SilkEncoder { | |||
| 458 | } | 511 | } |
| 459 | self.reservoir = (self.reservoir + frame_bits - b0).clamp(-RESERVOIR_FRAMES * frame_bits, RESERVOIR_FRAMES * frame_bits); | 512 | self.reservoir = (self.reservoir + frame_bits - b0).clamp(-RESERVOIR_FRAMES * frame_bits, RESERVOIR_FRAMES * frame_bits); |
| 460 | } | 513 | } |
| 461 | - let Trial { bytes, range, prev_gain_index, run } = best; | 514 | + if let Some(enc) = shared { |
| 462 | - let len = bytes.len(); | 515 | + write(enc, &best.gain_idx, best.per_index, &best.run); |
| 463 | - self.prev_gain_index = prev_gain_index; | ||
| 464 | - self.voiced_frames += usize::from(voiced); | ||
| 465 | - self.final_range = range; | ||
| 466 | - self.shape_d.copy_from_slice(&run.d[n..]); | ||
| 467 | - self.shape_u.copy_from_slice(&run.u[n..]); | ||
| 468 | - self.shape_gq.copy_from_slice(&run.gq[n..]); | ||
| 469 | - | ||
| 470 | - let toc = if wb { 9u8 << 3 } else { 1u8 << 3 }; | ||
| 471 | - if out.len() < 1 + len { | ||
| 472 | - return Err(ec_core::Error::corrupt(format!( | ||
| 473 | - "silk encode: packet needs {} bytes, buffer holds {}", | ||
| 474 | - 1 + len, | ||
| 475 | - out.len() | ||
| 476 | - ))); | ||
| 477 | } | 516 | } |
| 478 | - out[0] = toc; | 517 | + self.prev_gain_index = best.prev_gain_index; |
| 479 | - out[1..1 + len].copy_from_slice(&bytes); | 518 | + self.voiced_frames += usize::from(voiced); |
| 480 | - | 519 | + self.shape_d.copy_from_slice(&best.run.d[n..]); |
| 481 | - // Replay through the mirror so the next frame sees decoder state. | 520 | + self.shape_u.copy_from_slice(&best.run.u[n..]); |
| 482 | - let mut dec = RangeDecoder::new(&out[1..1 + len]); | 521 | + self.shape_gq.copy_from_slice(&best.run.gq[n..]); |
| 483 | - self.mirror | 522 | + Ok(best) |
| 484 | - .decode(&mut dec, &mut self.mirror_out, 20, fs as u32 * 1000, 1, true)?; | ||
| 485 | - debug_assert_eq!(dec.range(), self.final_range); | ||
| 486 | - Ok(1 + len) | ||
| 487 | } | 523 | } |
| 488 | } | 524 | } |
| 489 | 525 | ||
| @@ -502,6 +538,8 @@ struct Trial { | |||
| 502 | bytes: Vec<u8>, | 538 | bytes: Vec<u8>, |
| 503 | range: u32, | 539 | range: u32, |
| 504 | prev_gain_index: i32, | 540 | prev_gain_index: i32, |
| 541 | + gain_idx: [i8; MAX_NB_SUBFR], | ||
| 542 | + per_index: usize, | ||
| 505 | run: Run, | 543 | run: Run, |
| 506 | } | 544 | } |
| 507 | 545 | ||
crates/ec-opus/tests/conformance.rsmodified+99 -2
| @@ -772,7 +772,7 @@ fn real_library_sweep() { | |||
| 772 | // Encoder: self-consistency (range-exact against our own decoder) | 772 | // Encoder: self-consistency (range-exact against our own decoder) |
| 773 | // --------------------------------------------------------------------------- | 773 | // --------------------------------------------------------------------------- |
| 774 | 774 | ||
| 775 | -use ec_opus::{Application, Encoder, MultistreamEncoder}; | 775 | +use ec_opus::{Application, Bandwidth, Encoder, MultistreamEncoder}; |
| 776 | 776 | ||
| 777 | /// A deterministic music-like test signal: several detuned partials plus a | 777 | /// A deterministic music-like test signal: several detuned partials plus a |
| 778 | /// swept component per channel, loud enough to exercise every band. | 778 | /// swept component per channel, loud enough to exercise every band. |
| @@ -887,7 +887,8 @@ fn encoder_mode_follows_application_and_bitrate() { | |||
| 887 | (Application::Voip, 8_000u32, Some(1u8)), | 887 | (Application::Voip, 8_000u32, Some(1u8)), |
| 888 | (Application::Voip, 16_000, Some(9)), | 888 | (Application::Voip, 16_000, Some(9)), |
| 889 | (Application::Audio, 64_000, None), | 889 | (Application::Audio, 64_000, None), |
| 890 | - (Application::Voip, 32_000, None), | 890 | + (Application::Voip, 32_000, Some(15)), |
| 891 | + (Application::Voip, 48_000, None), | ||
| 891 | ]; | 892 | ]; |
| 892 | for (app, bps, want_config) in cases { | 893 | for (app, bps, want_config) in cases { |
| 893 | let mut enc = Encoder::new(48000, 1, app).unwrap(); | 894 | let mut enc = Encoder::new(48000, 1, app).unwrap(); |
| @@ -1721,3 +1722,99 @@ fn silk_packets_track_encoder_bitrate() { | |||
| 1721 | assert!((0.8..=1.2).contains(&ratio), "target {kbps_target}: got {kbps:.2} kbps"); | 1722 | assert!((0.8..=1.2).contains(&ratio), "target {kbps_target}: got {kbps:.2} kbps"); |
| 1722 | } | 1723 | } |
| 1723 | } | 1724 | } |
| 1725 | + | ||
| 1726 | +// --------------------------------------------------------------------------- | ||
| 1727 | +// Hybrid (SILK 16 kHz + CELT from band 17, one range-coded stream). | ||
| 1728 | + | ||
| 1729 | +/// Encodes mono `pcm` as hybrid packets at `bps` and decodes them with our | ||
| 1730 | +/// decoder, `mute` = (celt, silk) layers dropped at the decoder; asserts | ||
| 1731 | +/// range-state parity packet for packet. Returns (decoded, packets). | ||
| 1732 | +fn hybrid_roundtrip(pcm: &[f32], bps: u32, bandwidth: Option<Bandwidth>, mute: (bool, bool)) -> (Vec<f32>, Vec<Vec<u8>>) { | ||
| 1733 | + let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); | ||
| 1734 | + enc.set_bitrate(bps); | ||
| 1735 | + enc.set_bandwidth(bandwidth); | ||
| 1736 | + let mut dec = Decoder::new(48000, 1).unwrap(); | ||
| 1737 | + dec.debug_mute_layers(mute.0, mute.1); | ||
| 1738 | + let mut out = vec![0u8; 1500]; | ||
| 1739 | + let mut buf = vec![0f32; 5760]; | ||
| 1740 | + let (mut decoded, mut packets) = (Vec::new(), Vec::new()); | ||
| 1741 | + let mut padded = pcm.to_vec(); | ||
| 1742 | + padded.resize(pcm.len().div_ceil(960) * 960 + 960, 0.0); | ||
| 1743 | + for block in padded.chunks(960) { | ||
| 1744 | + let len = enc.encode_float(block, 960, &mut out).expect("hybrid encode"); | ||
| 1745 | + let n = dec.decode_float(&out[..len], &mut buf).expect("hybrid decode"); | ||
| 1746 | + assert_eq!(n, 960); | ||
| 1747 | + assert_eq!(dec.final_range(), enc.final_range(), "range state diverged"); | ||
| 1748 | + decoded.extend_from_slice(&buf[..n]); | ||
| 1749 | + packets.push(out[..len].to_vec()); | ||
| 1750 | + } | ||
| 1751 | + (decoded, packets) | ||
| 1752 | +} | ||
| 1753 | + | ||
| 1754 | +/// The two layers of a hybrid packet reach the decoder's output at the same | ||
| 1755 | +/// delay: a click's low-band-only and high-band-only peaks coincide at the | ||
| 1756 | +/// encoder's documented look-ahead. | ||
| 1757 | +#[test] | ||
| 1758 | +fn hybrid_layers_align() { | ||
| 1759 | + let mut click = vec![0f32; 48000]; | ||
| 1760 | + // Well inside the stream so both layers' predictors are running. | ||
| 1761 | + let at = 960 * 10 + 300; | ||
| 1762 | + click[at] = 0.9; | ||
| 1763 | + let peak = |x: &[f32]| { | ||
| 1764 | + x.iter().enumerate().max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()).unwrap().0 | ||
| 1765 | + }; | ||
| 1766 | + let (lb, _) = hybrid_roundtrip(&click, 32_000, None, (true, false)); | ||
| 1767 | + let (hb, _) = hybrid_roundtrip(&click, 32_000, None, (false, true)); | ||
| 1768 | + let enc = Encoder::new(48000, 1, Application::Voip).unwrap(); | ||
| 1769 | + let (plb, phb) = (peak(&lb) as i64 - at as i64, peak(&hb) as i64 - at as i64); | ||
| 1770 | + eprintln!("hybrid click: LB peak +{plb}, HB peak +{phb}, look_ahead {}", { | ||
| 1771 | + let mut e = enc.clone(); | ||
| 1772 | + e.set_bitrate(32_000); | ||
| 1773 | + e.look_ahead() | ||
| 1774 | + }); | ||
| 1775 | + assert!((plb - phb).abs() <= 2, "layers misaligned: LB +{plb} vs HB +{phb}"); | ||
| 1776 | + assert!((phb - 120).abs() <= 2, "HB peak +{phb}, look_ahead 120"); | ||
| 1777 | +} | ||
| 1778 | + | ||
| 1779 | +/// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks | ||
| 1780 | +/// the input full-band and in the SILK layer's band alone, and the reference | ||
| 1781 | +/// oracle decodes the packets to the same signal. | ||
| 1782 | +#[test] | ||
| 1783 | +fn hybrid_fb_roundtrip() { | ||
| 1784 | + for (name, pcm) in silk_sources() { | ||
| 1785 | + let (decoded, packets) = hybrid_roundtrip(&pcm, 32_000, None, (false, false)); | ||
| 1786 | + let toc = ec_opus::Toc::new(packets[0][0]); | ||
| 1787 | + assert_eq!(toc.config, 15, "{name}: TOC config {}", toc.config); | ||
| 1788 | + let (corr, lag) = aligned_corr(&pcm, &decoded, 400); | ||
| 1789 | + let (lb_only, _) = hybrid_roundtrip(&pcm, 32_000, None, (true, false)); | ||
| 1790 | + let lb_ref = lowpass(&pcm, 7000.0); | ||
| 1791 | + let (lb_corr, lb_lag) = aligned_corr(&lb_ref, &lb_only, 400); | ||
| 1792 | + let bytes: usize = packets.iter().map(Vec::len).sum(); | ||
| 1793 | + let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); | ||
| 1794 | + eprintln!("hybrid FB {name}: corr {corr:.4} at lag {lag}, LB corr {lb_corr:.4} at lag {lb_lag}, {kbps:.1} kbps"); | ||
| 1795 | + assert!(corr >= 0.95, "{name}: full-band corr {corr:.4}"); | ||
| 1796 | + // +-3: the wav16 fixture is a pure tone, whose phase moves the peak. | ||
| 1797 | + assert!((117..=123).contains(&lag), "{name}: aligned at lag {lag}, not the documented 120"); | ||
| 1798 | + assert!(lb_corr >= 0.9, "{name}: low-band corr {lb_corr:.4}"); | ||
| 1799 | + assert!((28.0..=36.0).contains(&kbps), "{name}: {kbps:.1} kbps for a 32 kbps CBR target"); | ||
| 1800 | + if let Some(oracle) = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len()) { | ||
| 1801 | + let n = oracle.len().min(decoded.len() - 120); | ||
| 1802 | + let c = correlation(&oracle[..n], &decoded[120..120 + n]); | ||
| 1803 | + eprintln!("hybrid FB {name}: oracle vs ours corr {c:.4}"); | ||
| 1804 | + assert!(c >= 0.95, "{name}: oracle corr {c:.4}"); | ||
| 1805 | + } | ||
| 1806 | + } | ||
| 1807 | + // SWB when asked for it, and the rest of the automatic hybrid range | ||
| 1808 | + // (SILK's share leaves CELT least at the bottom of it). | ||
| 1809 | + let speech = speech_like(); | ||
| 1810 | + let (_, packets) = hybrid_roundtrip(&speech, 24_000, Some(Bandwidth::SuperWide), (false, false)); | ||
| 1811 | + assert_eq!(ec_opus::Toc::new(packets[0][0]).config, 13); | ||
| 1812 | + for bps in [20_000u32, 24_000, 39_000] { | ||
| 1813 | + let (decoded, packets) = hybrid_roundtrip(&speech, bps, None, (false, false)); | ||
| 1814 | + let (corr, _) = aligned_corr(&speech, &decoded, 400); | ||
| 1815 | + let kbps = packets.iter().map(Vec::len).sum::<usize>() as f64 * 8.0 / (packets.len() as f64 * 20.0); | ||
| 1816 | + eprintln!("hybrid {bps}: config {}, corr {corr:.4}, {kbps:.1} kbps", ec_opus::Toc::new(packets[0][0]).config); | ||
| 1817 | + assert!(corr >= 0.9, "hybrid at {bps}: corr {corr:.4}"); | ||
| 1818 | + assert!(kbps <= bps as f64 / 1000.0 + 3.0, "hybrid at {bps}: {kbps:.1} kbps"); | ||
| 1819 | + } | ||
| 1820 | +} | ||