Merge branch 'lane-silk': SILK encoder covers NB/MB/WB at 10 and 20 ms, public Encoder routes 10/20 ms mono speech to SILK
Browse files at this commit3 changed files +534 -151
- crates/ec-opus/src/encoder.rs +85 -62
- crates/ec-opus/src/silk_enc_write.rs +224 -59
- crates/ec-opus/tests/conformance.rs +225 -30
crates/ec-opus/src/encoder.rsmodified+85 -62
| @@ -4,11 +4,11 @@ | ||
| 4 | 4 | //! or the self-delimited variant of Appendix B that the multistream framing |
| 5 | 5 | //! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s |
| 6 | 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 | |
| 8 | -//! other frame sizes fall back to CELT, documented at the fallback site) or | |
| 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). | |
| 7 | +//! SILK (TOC configs 0/1/4/5/8/9, mono NB/MB/WB 10 or 20 ms only — | |
| 8 | +//! stereo SILK and SILK at other frame sizes fall back to CELT, documented | |
| 9 | +//! at the fallback site) or Hybrid (TOC configs 13/15, mono SWB/FB 20 ms: | |
| 10 | +//! SILK at 16 kHz under CELT from band 17 up, one range-coded stream; | |
| 11 | +//! stereo and other frame sizes fall back to CELT). | |
| 12 | 12 | //! |
| 13 | 13 | //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and |
| 14 | 14 | //! the coded bandwidth is capped at the input's own Nyquist, so the images |
| @@ -38,6 +38,7 @@ const MAX_FRAME_BYTES: usize = 1275; | ||
| 38 | 38 | /// FIR lengths differ per bandwidth, so narrowband and wideband delays |
| 39 | 39 | /// don't have to and don't match. |
| 40 | 40 | const SILK_LOOK_AHEAD_48K_NB: usize = 58; |
| 41 | +const SILK_LOOK_AHEAD_48K_MB: usize = 54; | |
| 41 | 42 | const SILK_LOOK_AHEAD_48K_WB: usize = 50; |
| 42 | 43 | /// How far the hybrid path delays the SILK layer's input so its output lines |
| 43 | 44 | /// up with the CELT layer's at the decoder (which sums them as-is): CELT's |
| @@ -47,8 +48,7 @@ const HYBRID_SILK_DELAY_48K: usize = 120 - SILK_LOOK_AHEAD_48K_WB; | ||
| 47 | 48 | /// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent. |
| 48 | 49 | const HYBRID_CELT_MIN_BYTES: usize = 8; |
| 49 | 50 | |
| 50 | -/// What the caller is encoding. This encoder is CELT-only, so the setting | |
| 51 | -/// biases the coded bandwidth rather than selecting a different layer. | |
| 51 | +/// What the caller is encoding. | |
| 52 | 52 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 53 | 53 | pub enum Application { |
| 54 | 54 | /// Speech: one step narrower at a given rate, where the top octave costs |
| @@ -60,7 +60,7 @@ pub enum Application { | ||
| 60 | 60 | LowDelay, |
| 61 | 61 | } |
| 62 | 62 | |
| 63 | -/// One elementary Opus encoder: mono or stereo, CELT-only. | |
| 63 | +/// One elementary Opus encoder: mono or stereo. | |
| 64 | 64 | #[derive(Clone, Debug)] |
| 65 | 65 | pub struct Encoder { |
| 66 | 66 | celt: CeltEncoder, |
| @@ -80,6 +80,7 @@ pub struct Encoder { | ||
| 80 | 80 | /// Lazily created on first use so the mode can flip between packets |
| 81 | 81 | /// without paying for the unused layer's state. |
| 82 | 82 | silk_nb: Option<SilkEncoder>, |
| 83 | + silk_mb: Option<SilkEncoder>, | |
| 83 | 84 | silk_wb: Option<SilkEncoder>, |
| 84 | 85 | /// Scratch space for the SILK payload, sized once so the steady-state |
| 85 | 86 | /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. |
| @@ -129,6 +130,7 @@ impl Encoder { | ||
| 129 | 130 | final_range: 0, |
| 130 | 131 | mode: None, |
| 131 | 132 | silk_nb: None, |
| 133 | + silk_mb: None, | |
| 132 | 134 | silk_wb: None, |
| 133 | 135 | silk_buf: [0u8; MAX_FRAME_BYTES + 1], |
| 134 | 136 | silk_delay: Vec::new(), |
| @@ -139,7 +141,7 @@ impl Encoder { | ||
| 139 | 141 | /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and |
| 140 | 142 | /// `hybrid_choice` make from the application and bitrate; pass `None` to |
| 141 | 143 | /// restore the automatic pick. Requests this encoder cannot honour |
| 142 | - /// (stereo SILK/Hybrid, frames other than 20 ms) fall back to CELT. | |
| 144 | + /// (stereo SILK/Hybrid, SILK longer than 20 ms, or 10 ms Hybrid) fall back to CELT. | |
| 143 | 145 | pub fn set_mode(&mut self, mode: Option<Mode>) { |
| 144 | 146 | self.mode = mode; |
| 145 | 147 | } |
| @@ -158,23 +160,22 @@ impl Encoder { | ||
| 158 | 160 | /// channel, native rate) frame: the decoded stream lags the input by |
| 159 | 161 | /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate` |
| 160 | 162 | /// cancels it exactly. CELT: one MDCT overlap, 120 samples at 48 kHz. |
| 161 | - /// SILK (mono, 20 ms/960-sample-at-48k frames only, when the | |
| 162 | - /// application/bitrate or an explicit [`Encoder::set_mode`] select it — | |
| 163 | - /// the same [`Encoder::silk_choice`] predicate `encode_toc_and_payload` | |
| 164 | - /// dispatches on, so this always matches which layer actually codes the | |
| 165 | - /// frame): [`SILK_LOOK_AHEAD_48K_NB`] or [`SILK_LOOK_AHEAD_48K_WB`], the | |
| 166 | - /// analysis-plus-synthesis resampler round trip, click-measured per | |
| 167 | - /// bandwidth. Hybrid: CELT's 120, the SILK layer being delayed to meet | |
| 168 | - /// it ([`HYBRID_SILK_DELAY_48K`]). Any other frame size (or SILK/Hybrid's | |
| 169 | - /// mono, 20 ms requirement unmet) falls back to CELT here exactly as | |
| 170 | - /// `encode_toc_and_payload` does. | |
| 163 | + /// SILK (mono, 10 or 20 ms frames, when the application/bitrate or an | |
| 164 | + /// explicit [`Encoder::set_mode`] select it — the same | |
| 165 | + /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches | |
| 166 | + /// on, so this always matches which layer actually codes the frame): | |
| 167 | + /// [`SILK_LOOK_AHEAD_48K_NB`], [`SILK_LOOK_AHEAD_48K_MB`] or | |
| 168 | + /// [`SILK_LOOK_AHEAD_48K_WB`]. Hybrid: CELT's 120, the SILK layer being | |
| 169 | + /// delayed to meet it ([`HYBRID_SILK_DELAY_48K`]). Any other frame size | |
| 170 | + /// (or SILK/Hybrid's mono requirement unmet) falls back to CELT here | |
| 171 | + /// exactly as `encode_toc_and_payload` does. | |
| 171 | 172 | pub fn look_ahead(&self, frame_size: usize) -> usize { |
| 172 | 173 | let frame_48k = frame_size * self.upsample; |
| 173 | - if let Some(wideband) = self.silk_choice(frame_48k) { | |
| 174 | - let delay = if wideband { | |
| 175 | - SILK_LOOK_AHEAD_48K_WB | |
| 176 | - } else { | |
| 177 | - SILK_LOOK_AHEAD_48K_NB | |
| 174 | + if let Some(fs_khz) = self.silk_choice(frame_48k) { | |
| 175 | + let delay = match fs_khz { | |
| 176 | + 8 => SILK_LOOK_AHEAD_48K_NB, | |
| 177 | + 12 => SILK_LOOK_AHEAD_48K_MB, | |
| 178 | + _ => SILK_LOOK_AHEAD_48K_WB, | |
| 178 | 179 | }; |
| 179 | 180 | return delay / self.upsample; |
| 180 | 181 | } |
| @@ -216,21 +217,33 @@ impl Encoder { | ||
| 216 | 217 | pub fn reset(&mut self) { |
| 217 | 218 | self.celt.reset(); |
| 218 | 219 | self.silk_nb = None; |
| 220 | + self.silk_mb = None; | |
| 219 | 221 | self.silk_wb = None; |
| 220 | 222 | self.silk_delay.clear(); |
| 221 | 223 | self.final_range = 0; |
| 222 | 224 | } |
| 223 | 225 | |
| 224 | 226 | /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) |
| 225 | - /// call for SILK, and if so, wideband (else narrowband). `None` means | |
| 226 | - /// CELT or Hybrid (`hybrid_choice` tells those apart). | |
| 227 | - fn wants_silk(&self) -> Option<bool> { | |
| 227 | + /// call for SILK, and if so, which SILK internal sample rate in kHz. | |
| 228 | + /// `None` means CELT or Hybrid (`hybrid_choice` tells those apart). | |
| 229 | + fn wants_silk(&self) -> Option<usize> { | |
| 230 | + let forced = || match self.bandwidth.unwrap_or_else(|| self.auto_bandwidth()) { | |
| 231 | + Bandwidth::Narrow => 8, | |
| 232 | + Bandwidth::Medium => 12, | |
| 233 | + _ => 16, | |
| 234 | + }; | |
| 228 | 235 | match self.mode { |
| 229 | 236 | Some(Mode::Celt) | Some(Mode::Hybrid) => None, |
| 230 | - Some(Mode::Silk) => Some(self.bitrate > 10_000), | |
| 237 | + Some(Mode::Silk) => Some(forced()), | |
| 231 | 238 | None => { |
| 232 | 239 | if self.application == Application::Voip && self.bitrate < 20_000 { |
| 233 | - Some(self.bitrate > 10_000) | |
| 240 | + Some(if matches!(self.bandwidth, Some(Bandwidth::Medium)) { | |
| 241 | + 12 | |
| 242 | + } else if self.bitrate > 10_000 { | |
| 243 | + 16 | |
| 244 | + } else { | |
| 245 | + 8 | |
| 246 | + }) | |
| 234 | 247 | } else { |
| 235 | 248 | None |
| 236 | 249 | } |
| @@ -239,14 +252,14 @@ impl Encoder { | ||
| 239 | 252 | } |
| 240 | 253 | |
| 241 | 254 | /// `wants_silk` narrowed to what this encoder can actually code as SILK: |
| 242 | - /// mono, 20 ms (960 samples at 48 kHz) frames only. Stereo SILK and SILK | |
| 243 | - /// at other frame sizes are D2b's work; both fall back to CELT here. | |
| 244 | - fn silk_choice(&self, frame_48k: usize) -> Option<bool> { | |
| 245 | - let wideband = self.wants_silk()?; | |
| 246 | - if self.channels != 1 || frame_48k != 960 { | |
| 255 | + /// mono, 10 or 20 ms (480 or 960 samples at 48 kHz) frames only. Stereo | |
| 256 | + /// SILK and longer SILK packets are future work; both fall back to CELT. | |
| 257 | + fn silk_choice(&self, frame_48k: usize) -> Option<usize> { | |
| 258 | + let fs_khz = self.wants_silk()?; | |
| 259 | + if self.channels != 1 || !matches!(frame_48k, 480 | 960) { | |
| 247 | 260 | return None; |
| 248 | 261 | } |
| 249 | - Some(wideband) | |
| 262 | + Some(fs_khz) | |
| 250 | 263 | } |
| 251 | 264 | |
| 252 | 265 | /// Whether this frame goes out as a hybrid packet, and at which of the two |
| @@ -260,8 +273,7 @@ impl Encoder { | ||
| 260 | 273 | Some(Mode::Hybrid) => true, |
| 261 | 274 | Some(_) => false, |
| 262 | 275 | None => { |
| 263 | - self.application == Application::Voip | |
| 264 | - && (20_000..40_000).contains(&self.bitrate) | |
| 276 | + self.application == Application::Voip && (20_000..40_000).contains(&self.bitrate) | |
| 265 | 277 | } |
| 266 | 278 | }; |
| 267 | 279 | if !wanted || self.channels != 1 || frame_48k != 960 { |
| @@ -289,9 +301,19 @@ impl Encoder { | ||
| 289 | 301 | (32000, 22000, 24000), |
| 290 | 302 | (64000, 38000, 42000), |
| 291 | 303 | ]; |
| 292 | - let pick = |row: &(u32, u32, u32)| if bandwidth == Bandwidth::Full { row.2 } else { row.1 }; | |
| 304 | + let pick = |row: &(u32, u32, u32)| { | |
| 305 | + if bandwidth == Bandwidth::Full { | |
| 306 | + row.2 | |
| 307 | + } else { | |
| 308 | + row.1 | |
| 309 | + } | |
| 310 | + }; | |
| 293 | 311 | let total = total.min(64000); |
| 294 | - let i = TABLE.iter().rposition(|r| r.0 <= total).unwrap().min(TABLE.len() - 2); | |
| 312 | + let i = TABLE | |
| 313 | + .iter() | |
| 314 | + .rposition(|r| r.0 <= total) | |
| 315 | + .unwrap() | |
| 316 | + .min(TABLE.len() - 2); | |
| 295 | 317 | let (lo, hi) = (&TABLE[i], &TABLE[i + 1]); |
| 296 | 318 | pick(lo) + (pick(hi) - pick(lo)) * (total - lo.0) / (hi.0 - lo.0) |
| 297 | 319 | } |
| @@ -329,24 +351,28 @@ impl Encoder { | ||
| 329 | 351 | cap: usize, |
| 330 | 352 | ) -> Result<(u8, &[u8])> { |
| 331 | 353 | let frame_48k = frame_size * self.upsample; |
| 332 | - if let Some(wideband) = self.silk_choice(frame_48k) { | |
| 354 | + if let Some(fs_khz) = self.silk_choice(frame_48k) { | |
| 333 | 355 | Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); |
| 334 | - let enc = if wideband { | |
| 335 | - self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)) | |
| 336 | - } else { | |
| 337 | - self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)) | |
| 356 | + let enc = match fs_khz { | |
| 357 | + 8 => self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)), | |
| 358 | + 12 => self.silk_mb.get_or_insert_with(SilkEncoder::new_mediumband), | |
| 359 | + _ => self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)), | |
| 338 | 360 | }; |
| 339 | 361 | // Keep SILK's own reservoir-based rate control tracking the |
| 340 | 362 | // Encoder's current target on every frame — cheap (an Option<u32> |
| 341 | 363 | // store) and catches set_bitrate calls made between frames. |
| 342 | 364 | enc.set_bitrate(self.bitrate); |
| 343 | - let n = enc.encode_frame(&self.silk_stuff, &mut self.silk_buf)?; | |
| 365 | + let n = enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf, frame_48k / 48)?; | |
| 344 | 366 | self.final_range = enc.final_range(); |
| 345 | 367 | return Ok((self.silk_buf[0], &self.silk_buf[1..n])); |
| 346 | 368 | } |
| 347 | 369 | if let Some(bandwidth) = self.hybrid_choice(frame_48k) { |
| 348 | 370 | let n = self.encode_hybrid(pcm, frame_size, bandwidth, cap)?; |
| 349 | - let config = if bandwidth == Bandwidth::Full { 15u8 } else { 13 }; | |
| 371 | + let config = if bandwidth == Bandwidth::Full { | |
| 372 | + 15u8 | |
| 373 | + } else { | |
| 374 | + 13 | |
| 375 | + }; | |
| 350 | 376 | return Ok((config << 3, &self.range.data()[..n])); |
| 351 | 377 | } |
| 352 | 378 | let (toc, frame_48k, end) = self.toc(frame_size)?; |
| @@ -433,7 +459,8 @@ impl Encoder { | ||
| 433 | 459 | frame_size: usize, |
| 434 | 460 | out: &mut [u8], |
| 435 | 461 | ) -> Result<usize> { |
| 436 | - let (toc, payload) = self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1))?; | |
| 462 | + let (toc, payload) = | |
| 463 | + self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1))?; | |
| 437 | 464 | let n = payload.len(); |
| 438 | 465 | if out.len() < 1 + n { |
| 439 | 466 | return Err(Error::corrupt(format!( |
| @@ -462,7 +489,8 @@ impl Encoder { | ||
| 462 | 489 | frame_size: usize, |
| 463 | 490 | out: &mut [u8], |
| 464 | 491 | ) -> Result<usize> { |
| 465 | - let (toc, payload) = self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3))?; | |
| 492 | + let (toc, payload) = | |
| 493 | + self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3))?; | |
| 466 | 494 | let n = payload.len(); |
| 467 | 495 | let len_bytes = if n < 252 { 1 } else { 2 }; |
| 468 | 496 | if out.len() < 1 + len_bytes + n { |
| @@ -528,14 +556,9 @@ impl Encoder { | ||
| 528 | 556 | // CELT sees the same input as SILK: start band 17 alone keeps it off |
| 529 | 557 | // the low band (a one-pole ~6 kHz high-pass here measured identical |
| 530 | 558 | // full-band correlation, so there is none). |
| 531 | - let n = self.celt.encode( | |
| 532 | - &mut self.range, | |
| 533 | - pcm, | |
| 534 | - 960, | |
| 535 | - 17, | |
| 536 | - bandwidth.celt_end_band(), | |
| 537 | - 0, | |
| 538 | - )?; | |
| 559 | + let n = self | |
| 560 | + .celt | |
| 561 | + .encode(&mut self.range, pcm, 960, 17, bandwidth.celt_end_band(), 0)?; | |
| 539 | 562 | self.final_range = self.range.range(); |
| 540 | 563 | let payload = &self.range.data()[..n]; |
| 541 | 564 | self.silk_wb.as_mut().unwrap().replay(payload)?; |
| @@ -603,16 +626,16 @@ mod tests { | ||
| 603 | 626 | assert_eq!(e.look_ahead(960), 60); |
| 604 | 627 | } |
| 605 | 628 | |
| 606 | - /// `look_ahead` must use the same mono/20 ms-frame predicate dispatch | |
| 607 | - /// does (`silk_choice`/`hybrid_choice`), not just `wants_silk` — a | |
| 608 | - /// non-20 ms frame (or stereo) codes as CELT regardless of the | |
| 609 | - /// bitrate/application, so its look-ahead is CELT's 120, not SILK's. | |
| 629 | + /// `look_ahead` must use the same mono/10-or-20 ms-frame predicate | |
| 630 | + /// dispatch does (`silk_choice`/`hybrid_choice`), not just `wants_silk`: | |
| 631 | + /// 2.5/5 ms frames and stereo still code as CELT, while mono 10 ms | |
| 632 | + /// speech follows SILK. | |
| 610 | 633 | #[test] |
| 611 | 634 | fn look_ahead_matches_the_frame_size_dispatch_actually_uses() { |
| 612 | 635 | let mut e = Encoder::new(48000, 1, Application::Voip).unwrap(); |
| 613 | 636 | e.set_bitrate(8000); |
| 614 | - assert_eq!(e.look_ahead(480), 120, "sub-20ms frame falls back to CELT"); | |
| 615 | - assert_eq!(e.look_ahead(240), 120, "sub-20ms frame falls back to CELT"); | |
| 637 | + assert_eq!(e.look_ahead(480), 58, "10ms NB SILK"); | |
| 638 | + assert_eq!(e.look_ahead(240), 120, "5ms frame falls back to CELT"); | |
| 616 | 639 | assert_eq!(e.look_ahead(960), 58, "20ms NB SILK"); |
| 617 | 640 | |
| 618 | 641 | e.set_bitrate(16000); |
crates/ec-opus/src/silk_enc_write.rsmodified+224 -59
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | //! SILK payload writer (subtask D2a): turns the analysis in [`crate::silk_enc`] |
| 2 | -//! into a decodable mono 20 ms SILK packet, NB (8 kHz) or WB (16 kHz). | |
| 2 | +//! into a decodable mono SILK packet, NB (8 kHz), MB (12 kHz) or WB (16 kHz). | |
| 3 | 3 | //! |
| 4 | 4 | //! Symbol order is exactly `silk::decode()`'s, and every decision is made |
| 5 | 5 | //! against the decoder's own tables and reconstruction functions. The |
| @@ -12,7 +12,7 @@ | ||
| 12 | 12 | //! output error is fed back through short-term (bandwidth-expanded LPC), |
| 13 | 13 | //! harmonic and tilt shaping filters so the noise hides under the signal's |
| 14 | 14 | //! own spectrum, and a gain-offset rate loop sizes each packet against |
| 15 | -//! [`SilkEncoder::set_bitrate`]. 10/40/60 ms frames and stereo are not | |
| 15 | +//! [`SilkEncoder::set_bitrate`]. 40/60 ms packets and stereo are not | |
| 16 | 16 | //! written yet. |
| 17 | 17 | |
| 18 | 18 | // Same idiom as silk.rs: index loops mirror the decoder's position arithmetic. |
| @@ -23,12 +23,13 @@ use ec_core::Result; | ||
| 23 | 23 | use crate::range::{RangeDecoder, RangeEncoder}; |
| 24 | 24 | use crate::silk::tables::*; |
| 25 | 25 | use crate::silk::{ |
| 26 | - decode_pitch, nlsf2a, nlsf_cb, silk_rand, SilkDecoder, MAX_LPC_ORDER, MAX_NB_SUBFR, | |
| 27 | - PE_MAX_LAG_MS, PE_MIN_LAG_MS, | |
| 26 | + MAX_LPC_ORDER, MAX_NB_SUBFR, PE_MAX_LAG_MS, PE_MIN_LAG_MS, SilkDecoder, decode_pitch, nlsf_cb, | |
| 27 | + nlsf2a, silk_rand, | |
| 28 | +}; | |
| 29 | +use crate::silk_enc::{ | |
| 30 | + Resampler48, Vad, estimate_pitch, lpc_analyze, quantize_gains, quantize_nlsf, | |
| 28 | 31 | }; |
| 29 | -use crate::silk_enc::{estimate_pitch, lpc_analyze, quantize_gains, quantize_nlsf, Resampler48, Vad}; | |
| 30 | 32 | |
| 31 | -const NB_SUBFR: usize = 4; | |
| 32 | 33 | const SHELL_LEN: usize = 16; |
| 33 | 34 | const LTP_ORDER: usize = 5; |
| 34 | 35 | /// `QUANT_LEVEL_ADJUST_Q10` in `decode_core`: a non-zero pulse decodes 80/1024 |
| @@ -38,7 +39,7 @@ const LEVEL_ADJUST: f32 = 80.0 / 1024.0; | ||
| 38 | 39 | /// with 16 such pulses in one block. |
| 39 | 40 | const MAX_PULSE: i32 = 1023; |
| 40 | 41 | |
| 41 | -/// A mono, 20 ms, NB or WB SILK encoder. | |
| 42 | +/// A mono, 10 or 20 ms, NB/MB/WB SILK encoder. | |
| 42 | 43 | #[derive(Clone, Debug)] |
| 43 | 44 | pub struct SilkEncoder { |
| 44 | 45 | fs_khz: usize, |
| @@ -81,7 +82,16 @@ const PULSE_LAMBDA: f32 = 1.5; | ||
| 81 | 82 | impl SilkEncoder { |
| 82 | 83 | /// `wideband`: 16 kHz internal rate (TOC config 9), else 8 kHz (config 1). |
| 83 | 84 | pub fn new(wideband: bool) -> SilkEncoder { |
| 84 | - let fs_khz = if wideband { 16 } else { 8 }; | |
| 85 | + Self::with_fs_khz(if wideband { 16 } else { 8 }) | |
| 86 | + } | |
| 87 | + | |
| 88 | + /// Mediumband, 12 kHz internal rate (TOC config 5). | |
| 89 | + pub fn new_mediumband() -> SilkEncoder { | |
| 90 | + Self::with_fs_khz(12) | |
| 91 | + } | |
| 92 | + | |
| 93 | + fn with_fs_khz(fs_khz: usize) -> SilkEncoder { | |
| 94 | + debug_assert!(matches!(fs_khz, 8 | 12 | 16)); | |
| 85 | 95 | SilkEncoder { |
| 86 | 96 | fs_khz, |
| 87 | 97 | resampler: Resampler48::new(fs_khz as u32), |
| @@ -124,13 +134,39 @@ impl SilkEncoder { | ||
| 124 | 134 | self.resampler.delay_samples() |
| 125 | 135 | } |
| 126 | 136 | |
| 127 | - /// Encodes 960 mono 48 kHz samples as one code-0 packet in `out`, | |
| 137 | + /// Encodes 960 mono 48 kHz samples as one 20 ms code-0 packet in `out`, | |
| 128 | 138 | /// returning its length. |
| 129 | 139 | pub fn encode_frame(&mut self, pcm48: &[f32], out: &mut [u8]) -> Result<usize> { |
| 130 | - let Trial { bytes, range, .. } = self.encode_inner(pcm48, None)?; | |
| 140 | + self.encode_frame_ms(pcm48, out, 20) | |
| 141 | + } | |
| 142 | + | |
| 143 | + /// Encodes 10 or 20 ms of mono 48 kHz samples as one code-0 packet in | |
| 144 | + /// `out`, returning its length. | |
| 145 | + pub fn encode_frame_ms( | |
| 146 | + &mut self, | |
| 147 | + pcm48: &[f32], | |
| 148 | + out: &mut [u8], | |
| 149 | + frame_ms: usize, | |
| 150 | + ) -> Result<usize> { | |
| 151 | + let Trial { bytes, range, .. } = self.encode_inner(pcm48, frame_ms, None)?; | |
| 131 | 152 | let len = bytes.len(); |
| 132 | 153 | self.final_range = range; |
| 133 | - let toc = if self.fs_khz == 16 { 9u8 << 3 } else { 1u8 << 3 }; | |
| 154 | + let duration = match frame_ms { | |
| 155 | + 10 => 0u8, | |
| 156 | + 20 => 1, | |
| 157 | + _ => { | |
| 158 | + return Err(ec_core::Error::unsupported( | |
| 159 | + format!("silk encode frame of {frame_ms} ms"), | |
| 160 | + "SILK encoder writes 10 or 20 ms packets", | |
| 161 | + )); | |
| 162 | + } | |
| 163 | + }; | |
| 164 | + let base = match self.fs_khz { | |
| 165 | + 8 => 0u8, | |
| 166 | + 12 => 4, | |
| 167 | + _ => 8, | |
| 168 | + }; | |
| 169 | + let toc = (base + duration) << 3; | |
| 134 | 170 | if out.len() < 1 + len { |
| 135 | 171 | return Err(ec_core::Error::corrupt(format!( |
| 136 | 172 | "silk encode: packet needs {} bytes, buffer holds {}", |
| @@ -140,7 +176,7 @@ impl SilkEncoder { | ||
| 140 | 176 | } |
| 141 | 177 | out[0] = toc; |
| 142 | 178 | out[1..1 + len].copy_from_slice(&bytes); |
| 143 | - self.replay(&out[1..1 + len])?; | |
| 179 | + self.replay_ms(&out[1..1 + len], frame_ms)?; | |
| 144 | 180 | debug_assert_eq!(self.mirror_range, self.final_range); |
| 145 | 181 | Ok(1 + len) |
| 146 | 182 | } |
| @@ -151,7 +187,7 @@ impl SilkEncoder { | ||
| 151 | 187 | /// must [`SilkEncoder::replay`] the finished payload so this encoder's |
| 152 | 188 | /// decoder mirror advances. |
| 153 | 189 | pub fn encode_hybrid(&mut self, pcm48: &[f32], enc: &mut RangeEncoder) -> Result<()> { |
| 154 | - self.encode_inner(pcm48, Some(enc)).map(|_| ()) | |
| 190 | + self.encode_inner(pcm48, 20, Some(enc)).map(|_| ()) | |
| 155 | 191 | } |
| 156 | 192 | |
| 157 | 193 | /// Decodes `payload` (TOC stripped) through the mirror decoder so the next |
| @@ -159,10 +195,20 @@ impl SilkEncoder { | ||
| 159 | 195 | /// does this itself, [`SilkEncoder::encode_hybrid`] callers do it once |
| 160 | 196 | /// the packet is complete. |
| 161 | 197 | pub fn replay(&mut self, payload: &[u8]) -> Result<()> { |
| 198 | + self.replay_ms(payload, 20) | |
| 199 | + } | |
| 200 | + | |
| 201 | + fn replay_ms(&mut self, payload: &[u8], frame_ms: usize) -> Result<()> { | |
| 162 | 202 | let fs = self.fs_khz; |
| 163 | 203 | let mut dec = RangeDecoder::new(payload); |
| 164 | - self.mirror | |
| 165 | - .decode(&mut dec, &mut self.mirror_out, 20, fs as u32 * 1000, 1, true)?; | |
| 204 | + self.mirror.decode( | |
| 205 | + &mut dec, | |
| 206 | + &mut self.mirror_out, | |
| 207 | + frame_ms, | |
| 208 | + fs as u32 * 1000, | |
| 209 | + 1, | |
| 210 | + true, | |
| 211 | + )?; | |
| 166 | 212 | self.mirror_range = dec.range(); |
| 167 | 213 | Ok(()) |
| 168 | 214 | } |
| @@ -171,12 +217,31 @@ impl SilkEncoder { | ||
| 171 | 217 | /// returned trial's `bytes` are the standalone SILK payload (TOC |
| 172 | 218 | /// excluded). With `shared`, the chosen frame's symbols are also written |
| 173 | 219 | /// into that coder (the hybrid path). |
| 174 | - fn encode_inner(&mut self, pcm48: &[f32], shared: Option<&mut RangeEncoder>) -> Result<Trial> { | |
| 175 | - assert_eq!(pcm48.len(), 960, "SilkEncoder codes 20 ms mono frames"); | |
| 220 | + fn encode_inner( | |
| 221 | + &mut self, | |
| 222 | + pcm48: &[f32], | |
| 223 | + frame_ms: usize, | |
| 224 | + shared: Option<&mut RangeEncoder>, | |
| 225 | + ) -> Result<Trial> { | |
| 226 | + assert!( | |
| 227 | + matches!(frame_ms, 10 | 20), | |
| 228 | + "SilkEncoder codes 10 or 20 ms mono frames" | |
| 229 | + ); | |
| 230 | + assert_eq!( | |
| 231 | + pcm48.len(), | |
| 232 | + 48 * frame_ms, | |
| 233 | + "SilkEncoder input is 48 kHz mono" | |
| 234 | + ); | |
| 176 | 235 | let fs = self.fs_khz; |
| 177 | 236 | let order = if fs == 16 { MAX_LPC_ORDER } else { 10 }; |
| 178 | - let n = 20 * fs; | |
| 237 | + let nb_subfr = frame_ms / 5; | |
| 238 | + let n = frame_ms * fs; | |
| 179 | 239 | let sub = 5 * fs; |
| 240 | + if self.shape_d.len() != n { | |
| 241 | + self.shape_d.resize(n, 0.0); | |
| 242 | + self.shape_u.resize(n, 0.0); | |
| 243 | + self.shape_gq.resize(n, 0.0); | |
| 244 | + } | |
| 180 | 245 | let x: Vec<f32> = self |
| 181 | 246 | .resampler |
| 182 | 247 | .process(pcm48) |
| @@ -186,13 +251,15 @@ impl SilkEncoder { | ||
| 186 | 251 | let vad = self.vad.analyze(&x); |
| 187 | 252 | |
| 188 | 253 | // LPC -> NLSF indices -> the decoder's dequantised filter. |
| 189 | - let nlsf_target = lpc_analyze(&x, order).map(|a| a.nlsf_q15).unwrap_or_else(|| { | |
| 190 | - let mut flat = [0i16; MAX_LPC_ORDER]; | |
| 191 | - for (i, v) in flat.iter_mut().enumerate().take(order) { | |
| 192 | - *v = ((i + 1) * 32768 / (order + 1)) as i16; | |
| 193 | - } | |
| 194 | - flat | |
| 195 | - }); | |
| 254 | + let nlsf_target = lpc_analyze(&x, order) | |
| 255 | + .map(|a| a.nlsf_q15) | |
| 256 | + .unwrap_or_else(|| { | |
| 257 | + let mut flat = [0i16; MAX_LPC_ORDER]; | |
| 258 | + for (i, v) in flat.iter_mut().enumerate().take(order) { | |
| 259 | + *v = ((i + 1) * 32768 / (order + 1)) as i16; | |
| 260 | + } | |
| 261 | + flat | |
| 262 | + }); | |
| 196 | 263 | let wb = fs == 16; |
| 197 | 264 | let nq = quantize_nlsf(&nlsf_target[..order], wb); |
| 198 | 265 | let a_q12 = nlsf2a(&nq.nlsf_q15[..order], order); |
| @@ -224,14 +291,18 @@ impl SilkEncoder { | ||
| 224 | 291 | let res: Vec<f32> = (0..n as isize).map(whiten).collect(); |
| 225 | 292 | |
| 226 | 293 | // Pitch / LTP. |
| 227 | - let pitch = estimate_pitch(&x, fs as i32, NB_SUBFR).filter(|p| p.voiced); | |
| 294 | + let pitch = estimate_pitch(&x, fs as i32, nb_subfr).filter(|p| p.voiced); | |
| 228 | 295 | let voiced = pitch.is_some(); |
| 229 | 296 | |
| 230 | 297 | let (lag_index, contour_index, pitch_l) = match &pitch { |
| 231 | 298 | Some(p) => { |
| 232 | 299 | let max_index = (PE_MAX_LAG_MS - PE_MIN_LAG_MS) * fs as i32 - 1; |
| 233 | 300 | let li = p.lag_index.clamp(0, max_index); |
| 234 | - (li, p.contour_index, decode_pitch(li, p.contour_index, fs as i32, NB_SUBFR)) | |
| 301 | + ( | |
| 302 | + li, | |
| 303 | + p.contour_index, | |
| 304 | + decode_pitch(li, p.contour_index, fs as i32, nb_subfr), | |
| 305 | + ) | |
| 235 | 306 | } |
| 236 | 307 | None => (0, 0, [0; MAX_NB_SUBFR]), |
| 237 | 308 | }; |
| @@ -259,7 +330,7 @@ impl SilkEncoder { | ||
| 259 | 330 | { |
| 260 | 331 | let mut r_ol: Vec<f32> = (-(n as isize)..0).map(whiten).collect(); |
| 261 | 332 | r_ol.extend_from_slice(&res); |
| 262 | - for k in 0..NB_SUBFR { | |
| 333 | + for k in 0..nb_subfr { | |
| 263 | 334 | let (e, gsum) = if voiced { |
| 264 | 335 | LTP_GAIN_VQ_2 |
| 265 | 336 | .iter() |
| @@ -279,25 +350,51 @@ impl SilkEncoder { | ||
| 279 | 350 | } |
| 280 | 351 | } |
| 281 | 352 | let vad_flag = vad.active || voiced; |
| 282 | - let signal_type: i32 = if !vad_flag { 0 } else if voiced { 2 } else { 1 }; | |
| 353 | + let signal_type: i32 = if !vad_flag { | |
| 354 | + 0 | |
| 355 | + } else if voiced { | |
| 356 | + 2 | |
| 357 | + } else { | |
| 358 | + 1 | |
| 359 | + }; | |
| 283 | 360 | // Over-unity LTP gain: scale the previous frame's history down so |
| 284 | 361 | // quantisation error does not build up through the pitch loop. |
| 285 | - let ltp_scale_index = if !voiced { 0 } else if ltp_gain > 1.25 { 2 } else if ltp_gain > 1.0 { 1 } else { 0 }; | |
| 362 | + let ltp_scale_index = if !voiced { | |
| 363 | + 0 | |
| 364 | + } else if ltp_gain > 1.25 { | |
| 365 | + 2 | |
| 366 | + } else if ltp_gain > 1.0 { | |
| 367 | + 1 | |
| 368 | + } else { | |
| 369 | + 0 | |
| 370 | + }; | |
| 286 | 371 | let ltp_scale = LTPSCALES_TABLE_Q14[ltp_scale_index] as f32 / 16384.0; |
| 287 | 372 | // Inactive or low-energy frames (and sparse voiced excitation) take the |
| 288 | 373 | // small quantisation offset; dense unvoiced excitation the large one. |
| 289 | - let mean_rms = targets.iter().map(|&t| t as f32 / 65536.0).sum::<f32>() / NB_SUBFR as f32; | |
| 374 | + let mean_rms = targets[..nb_subfr] | |
| 375 | + .iter() | |
| 376 | + .map(|&t| t as f32 / 65536.0) | |
| 377 | + .sum::<f32>() | |
| 378 | + / nb_subfr as f32; | |
| 290 | 379 | let quant_offset_type = usize::from(signal_type == 1 && mean_rms > 64.0); |
| 291 | - let offset = QUANTIZATION_OFFSETS_Q10[signal_type as usize >> 1][quant_offset_type] as f32 | |
| 292 | - / 1024.0; | |
| 380 | + let offset = | |
| 381 | + QUANTIZATION_OFFSETS_Q10[signal_type as usize >> 1][quant_offset_type] as f32 / 1024.0; | |
| 293 | 382 | |
| 294 | 383 | // Noise shaping filters, from the bandwidth-expanded LPC: the output |
| 295 | 384 | // error d follows A(z/g2)(1 - tilt z^-1) / (A(z/g1)(1 - h z^-L)), i.e. |
| 296 | 385 | // the quantisation noise sits under the formants and, when voiced, |
| 297 | 386 | // under the harmonics, instead of being white at the decoder output. |
| 298 | 387 | let (g1, g2, tilt) = (SHAPE_AR, SHAPE_MA, if voiced { SHAPE_TILT } else { 0.0 }); |
| 299 | - let c: Vec<f32> = a.iter().enumerate().map(|(j, &aj)| aj * g1.powi(j as i32 + 1)).collect(); | |
| 300 | - let b2: Vec<f32> = a.iter().enumerate().map(|(j, &aj)| aj * g2.powi(j as i32 + 1)).collect(); | |
| 388 | + let c: Vec<f32> = a | |
| 389 | + .iter() | |
| 390 | + .enumerate() | |
| 391 | + .map(|(j, &aj)| aj * g1.powi(j as i32 + 1)) | |
| 392 | + .collect(); | |
| 393 | + let b2: Vec<f32> = a | |
| 394 | + .iter() | |
| 395 | + .enumerate() | |
| 396 | + .map(|(j, &aj)| aj * g2.powi(j as i32 + 1)) | |
| 397 | + .collect(); | |
| 301 | 398 | // (1 - B2(z))(1 - tilt z^-1) = 1 - NB(z). |
| 302 | 399 | let mut nb = vec![0f32; order + 1]; |
| 303 | 400 | for j in 0..order { |
| @@ -305,7 +402,11 @@ impl SilkEncoder { | ||
| 305 | 402 | nb[j + 1] -= tilt * b2[j]; |
| 306 | 403 | } |
| 307 | 404 | nb[0] += tilt; |
| 308 | - let harm = if voiced { SHAPE_HARMONIC * ltp_gain.clamp(0.0, 1.0) } else { 0.0 }; | |
| 405 | + let harm = if voiced { | |
| 406 | + SHAPE_HARMONIC * ltp_gain.clamp(0.0, 1.0) | |
| 407 | + } else { | |
| 408 | + 0.0 | |
| 409 | + }; | |
| 309 | 410 | |
| 310 | 411 | // `r`: LTP history in absolute sample units, past frame first (scaled |
| 311 | 412 | // by ltp_scale as the decoder scales its rebuilt history), then this |
| @@ -333,12 +434,13 @@ impl SilkEncoder { | ||
| 333 | 434 | let mut pulses = vec![0i32; n]; |
| 334 | 435 | let mut seed = seed_index; |
| 335 | 436 | let mut err = 0f32; |
| 336 | - for k in 0..NB_SUBFR { | |
| 437 | + for k in 0..nb_subfr { | |
| 337 | 438 | if voiced { |
| 338 | 439 | // In-subframe taps (lag shorter than the subframe) see the |
| 339 | 440 | // unquantised residual as a stand-in. |
| 340 | 441 | let mut r_ol = r.clone(); |
| 341 | - r_ol[n + k * sub..n + (k + 1) * sub].copy_from_slice(&res[k * sub..(k + 1) * sub]); | |
| 442 | + r_ol[n + k * sub..n + (k + 1) * sub] | |
| 443 | + .copy_from_slice(&res[k * sub..(k + 1) * sub]); | |
| 342 | 444 | let mut best = f32::INFINITY; |
| 343 | 445 | for (v, b) in cbk.iter().enumerate() { |
| 344 | 446 | let e: f32 = (0..sub) |
| @@ -356,9 +458,17 @@ impl SilkEncoder { | ||
| 356 | 458 | let idx = k * sub + i; |
| 357 | 459 | let p = n + idx; |
| 358 | 460 | let lpc: f32 = a.iter().enumerate().map(|(j, &aj)| aj * y[p - 1 - j]).sum(); |
| 359 | - let pred = if voiced { ltp_pred(&r, &cbk[ltp_index[k]], k, i) } else { 0.0 }; | |
| 461 | + let pred = if voiced { | |
| 462 | + ltp_pred(&r, &cbk[ltp_index[k]], k, i) | |
| 463 | + } else { | |
| 464 | + 0.0 | |
| 465 | + }; | |
| 360 | 466 | let mut s: f32 = c.iter().enumerate().map(|(j, &cj)| cj * d[p - 1 - j]).sum(); |
| 361 | - s -= nb.iter().enumerate().map(|(j, &bj)| bj * gq[p - 1 - j]).sum::<f32>(); | |
| 467 | + s -= nb | |
| 468 | + .iter() | |
| 469 | + .enumerate() | |
| 470 | + .map(|(j, &bj)| bj * gq[p - 1 - j]) | |
| 471 | + .sum::<f32>(); | |
| 362 | 472 | if harm > 0.0 { |
| 363 | 473 | s += harm * u[p - lag]; |
| 364 | 474 | } |
| @@ -375,7 +485,9 @@ impl SilkEncoder { | ||
| 375 | 485 | .into_iter() |
| 376 | 486 | .filter(|p| p.abs() <= MAX_PULSE) |
| 377 | 487 | .min_by(|&a, &b| { |
| 378 | - let cost = |p: i32| (recon(p) - target).powi(2) + PULSE_LAMBDA * p.abs() as f32; | |
| 488 | + let cost = |p: i32| { | |
| 489 | + (recon(p) - target).powi(2) + PULSE_LAMBDA * p.abs() as f32 | |
| 490 | + }; | |
| 379 | 491 | cost(a).partial_cmp(&cost(b)).unwrap() |
| 380 | 492 | }) |
| 381 | 493 | .unwrap(); |
| @@ -386,11 +498,22 @@ impl SilkEncoder { | ||
| 386 | 498 | y[p] = r[p] + lpc; |
| 387 | 499 | d[p] = y[p] - x[idx]; |
| 388 | 500 | gq[p] = d[p] - s; |
| 389 | - u[p] = d[p] - c.iter().enumerate().map(|(j, &cj)| cj * d[p - 1 - j]).sum::<f32>(); | |
| 501 | + u[p] = d[p] | |
| 502 | + - c.iter() | |
| 503 | + .enumerate() | |
| 504 | + .map(|(j, &cj)| cj * d[p - 1 - j]) | |
| 505 | + .sum::<f32>(); | |
| 390 | 506 | err += d[p] * d[p]; |
| 391 | 507 | } |
| 392 | 508 | } |
| 393 | - Run { ltp_index, pulses, err, d, u, gq } | |
| 509 | + Run { | |
| 510 | + ltp_index, | |
| 511 | + pulses, | |
| 512 | + err, | |
| 513 | + d, | |
| 514 | + u, | |
| 515 | + gq, | |
| 516 | + } | |
| 394 | 517 | }; |
| 395 | 518 | |
| 396 | 519 | // Bitstream writer, in decode()'s order; shared by the sizing trials |
| @@ -400,14 +523,22 @@ impl SilkEncoder { | ||
| 400 | 523 | enc.enc_bit_logp(false, 1); // LBRR flag |
| 401 | 524 | // Frame type. |
| 402 | 525 | if vad_flag { |
| 403 | - enc.enc_icdf(((signal_type << 1) | quant_offset_type as i32) as usize - 2, &TYPE_OFFSET_VAD_ICDF, 8); | |
| 526 | + enc.enc_icdf( | |
| 527 | + ((signal_type << 1) | quant_offset_type as i32) as usize - 2, | |
| 528 | + &TYPE_OFFSET_VAD_ICDF, | |
| 529 | + 8, | |
| 530 | + ); | |
| 404 | 531 | } else { |
| 405 | 532 | enc.enc_icdf(quant_offset_type, &TYPE_OFFSET_NO_VAD_ICDF, 8); |
| 406 | 533 | } |
| 407 | 534 | // Gains: one frame per packet, so always independently coded. |
| 408 | - enc.enc_icdf((gain_idx[0] as usize) >> 3, &GAIN_ICDF[signal_type as usize], 8); | |
| 535 | + enc.enc_icdf( | |
| 536 | + (gain_idx[0] as usize) >> 3, | |
| 537 | + &GAIN_ICDF[signal_type as usize], | |
| 538 | + 8, | |
| 539 | + ); | |
| 409 | 540 | enc.enc_icdf((gain_idx[0] as usize) & 7, &UNIFORM8_ICDF, 8); |
| 410 | - for k in 1..NB_SUBFR { | |
| 541 | + for k in 1..nb_subfr { | |
| 411 | 542 | enc.enc_icdf(gain_idx[k] as usize, &DELTA_GAIN_ICDF, 8); |
| 412 | 543 | } |
| 413 | 544 | // NLSFs. |
| @@ -428,16 +559,27 @@ impl SilkEncoder { | ||
| 428 | 559 | enc.enc_icdf((q + 4) as usize, icdf, 8); |
| 429 | 560 | } |
| 430 | 561 | } |
| 431 | - enc.enc_icdf(nq.interp_index as usize, &NLSF_INTERPOLATION_FACTOR_ICDF, 8); | |
| 562 | + if nb_subfr == MAX_NB_SUBFR { | |
| 563 | + enc.enc_icdf(nq.interp_index as usize, &NLSF_INTERPOLATION_FACTOR_ICDF, 8); | |
| 564 | + } | |
| 432 | 565 | // Pitch + LTP. (One frame per packet: the decoder only takes the |
| 433 | 566 | // lag-delta code path for the 2nd+ frame of a packet, so the |
| 434 | 567 | // absolute lag is always coded here.) |
| 435 | 568 | if voiced { |
| 436 | 569 | let half = fs as i32 >> 1; |
| 437 | 570 | enc.enc_icdf((lag_index / half) as usize, &PITCH_LAG_ICDF, 8); |
| 438 | - let low_icdf: &[u8] = if wb { &UNIFORM8_ICDF } else { &UNIFORM4_ICDF }; | |
| 571 | + let low_icdf: &[u8] = match fs { | |
| 572 | + 16 => &UNIFORM8_ICDF, | |
| 573 | + 12 => &UNIFORM6_ICDF, | |
| 574 | + _ => &UNIFORM4_ICDF, | |
| 575 | + }; | |
| 439 | 576 | enc.enc_icdf((lag_index % half) as usize, low_icdf, 8); |
| 440 | - let contour_icdf: &[u8] = if wb { &PITCH_CONTOUR_ICDF } else { &PITCH_CONTOUR_NB_ICDF }; | |
| 577 | + let contour_icdf: &[u8] = match (fs, nb_subfr) { | |
| 578 | + (8, 4) => &PITCH_CONTOUR_NB_ICDF, | |
| 579 | + (8, _) => &PITCH_CONTOUR_10_MS_NB_ICDF, | |
| 580 | + (_, 4) => &PITCH_CONTOUR_ICDF, | |
| 581 | + _ => &PITCH_CONTOUR_10_MS_ICDF, | |
| 582 | + }; | |
| 441 | 583 | enc.enc_icdf(contour_index as usize, contour_icdf, 8); |
| 442 | 584 | enc.enc_icdf(per_index, <P_PER_INDEX_ICDF, 8); |
| 443 | 585 | let gain_icdf: &[u8] = match per_index { |
| @@ -445,7 +587,7 @@ impl SilkEncoder { | ||
| 445 | 587 | 1 => <P_GAIN_ICDF_1, |
| 446 | 588 | _ => <P_GAIN_ICDF_2, |
| 447 | 589 | }; |
| 448 | - for k in 0..NB_SUBFR { | |
| 590 | + for k in 0..nb_subfr { | |
| 449 | 591 | enc.enc_icdf(run.ltp_index[k], gain_icdf, 8); |
| 450 | 592 | } |
| 451 | 593 | enc.enc_icdf(ltp_scale_index, <PSCALE_ICDF, 8); |
| @@ -463,7 +605,7 @@ impl SilkEncoder { | ||
| 463 | 605 | *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32; |
| 464 | 606 | } |
| 465 | 607 | 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); | |
| 608 | + let (gain_idx, gains_q16) = quantize_gains(&t, &mut prev_gain_index, false, nb_subfr); | |
| 467 | 609 | let (per_index, run) = candidates |
| 468 | 610 | .iter() |
| 469 | 611 | .map(|&per| (per, run(per, &gains_q16))) |
| @@ -477,14 +619,21 @@ impl SilkEncoder { | ||
| 477 | 619 | enc.done(); |
| 478 | 620 | debug_assert!(!enc.error()); |
| 479 | 621 | let len = enc.range_bytes(); |
| 480 | - Trial { bytes: enc.data()[..len].to_vec(), range: enc.range(), prev_gain_index, gain_idx, per_index, run } | |
| 622 | + Trial { | |
| 623 | + bytes: enc.data()[..len].to_vec(), | |
| 624 | + range: enc.range(), | |
| 625 | + prev_gain_index, | |
| 626 | + gain_idx, | |
| 627 | + per_index, | |
| 628 | + run, | |
| 629 | + } | |
| 481 | 630 | }; |
| 482 | 631 | |
| 483 | 632 | // Rate control: a common gain offset moves every subframe's pulse |
| 484 | 633 | // magnitudes together; the reservoir carries each packet's miss. |
| 485 | 634 | let mut best = trial(0); |
| 486 | 635 | if let Some(bps) = self.target_bps { |
| 487 | - let frame_bits = bps as f32 * 0.02; | |
| 636 | + let frame_bits = bps as f32 * frame_ms as f32 / 1000.0; | |
| 488 | 637 | let target = frame_bits + self.reservoir.clamp(-frame_bits, frame_bits); |
| 489 | 638 | let bits_of = |t: &Trial| t.bytes.len() as f32 * 8.0; |
| 490 | 639 | let (mut s0, mut b0) = (0i32, bits_of(&best)); |
| @@ -509,7 +658,10 @@ impl SilkEncoder { | ||
| 509 | 658 | break; |
| 510 | 659 | } |
| 511 | 660 | } |
| 512 | - self.reservoir = (self.reservoir + frame_bits - b0).clamp(-RESERVOIR_FRAMES * frame_bits, RESERVOIR_FRAMES * frame_bits); | |
| 661 | + self.reservoir = (self.reservoir + frame_bits - b0).clamp( | |
| 662 | + -RESERVOIR_FRAMES * frame_bits, | |
| 663 | + RESERVOIR_FRAMES * frame_bits, | |
| 664 | + ); | |
| 513 | 665 | } |
| 514 | 666 | if let Some(enc) = shared { |
| 515 | 667 | write(enc, &best.gain_idx, best.per_index, &best.run); |
| @@ -543,7 +695,6 @@ struct Trial { | ||
| 543 | 695 | run: Run, |
| 544 | 696 | } |
| 545 | 697 | |
| 546 | - | |
| 547 | 698 | /// Bits an ICDF symbol costs, for choosing among equivalent codings. |
| 548 | 699 | fn icdf_bits(k: usize, icdf: &[u8]) -> f32 { |
| 549 | 700 | let hi = if k == 0 { 256 } else { icdf[k - 1] as u32 }; |
| @@ -591,7 +742,11 @@ fn encode_pulses(enc: &mut RangeEncoder, pulses: &[i32], signal_type: i32, quant | ||
| 591 | 742 | enc.enc_icdf(first, &PULSES_PER_BLOCK_ICDF[rate_level], 8); |
| 592 | 743 | for level in 1..=shifts[i] { |
| 593 | 744 | let icdf = &PULSES_PER_BLOCK_ICDF[9][usize::from(level == 10)..]; |
| 594 | - let sym = if level < shifts[i] { 17 } else { sums[i] as usize }; | |
| 745 | + let sym = if level < shifts[i] { | |
| 746 | + 17 | |
| 747 | + } else { | |
| 748 | + sums[i] as usize | |
| 749 | + }; | |
| 595 | 750 | enc.enc_icdf(sym, icdf, 8); |
| 596 | 751 | } |
| 597 | 752 | } |
| @@ -633,7 +788,11 @@ fn shell_encode(enc: &mut RangeEncoder, p: &[i32]) { | ||
| 633 | 788 | fn join(enc: &mut RangeEncoder, a: i32, b: i32, table: &[u8]) -> i32 { |
| 634 | 789 | let sum = a + b; |
| 635 | 790 | if sum > 0 { |
| 636 | - enc.enc_icdf(a as usize, &table[SHELL_CODE_TABLE_OFFSETS[sum as usize] as usize..], 8); | |
| 791 | + enc.enc_icdf( | |
| 792 | + a as usize, | |
| 793 | + &table[SHELL_CODE_TABLE_OFFSETS[sum as usize] as usize..], | |
| 794 | + 8, | |
| 795 | + ); | |
| 637 | 796 | } |
| 638 | 797 | sum |
| 639 | 798 | } |
| @@ -685,7 +844,14 @@ mod tests { | ||
| 685 | 844 | let len = enc.encode_frame(&x, &mut out).unwrap(); |
| 686 | 845 | let mut rd = RangeDecoder::new(&out[1..len]); |
| 687 | 846 | let n = dec |
| 688 | - .decode(&mut rd, &mut pcm, 20, if wb { 16000 } else { 8000 }, 1, true) | |
| 847 | + .decode( | |
| 848 | + &mut rd, | |
| 849 | + &mut pcm, | |
| 850 | + 20, | |
| 851 | + if wb { 16000 } else { 8000 }, | |
| 852 | + 1, | |
| 853 | + true, | |
| 854 | + ) | |
| 689 | 855 | .unwrap(); |
| 690 | 856 | assert_eq!(n, if wb { 320 } else { 160 }); |
| 691 | 857 | assert_eq!(rd.range(), enc.final_range(), "frame {frame}"); |
| @@ -694,4 +860,3 @@ mod tests { | ||
| 694 | 860 | } |
| 695 | 861 | } |
| 696 | 862 | } |
| 697 | - |
crates/ec-opus/tests/conformance.rsmodified+225 -30
| @@ -912,6 +912,15 @@ fn encoder_mode_follows_application_and_bitrate() { | ||
| 912 | 912 | } |
| 913 | 913 | assert!(n > 1, "{app:?} at {bps} bps: empty packet"); |
| 914 | 914 | } |
| 915 | + | |
| 916 | + let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); | |
| 917 | + enc.set_mode(Some(ec_opus::Mode::Silk)); | |
| 918 | + enc.set_bandwidth(Some(Bandwidth::Medium)); | |
| 919 | + let pcm = vec![0.0f32; 480]; | |
| 920 | + let mut out = vec![0u8; 1500]; | |
| 921 | + let n = enc.encode_float(&pcm, 480, &mut out).unwrap(); | |
| 922 | + assert_eq!(ec_opus::Toc::new(out[0]).config, 4, "forced 10 ms MB SILK"); | |
| 923 | + assert!(n > 1, "forced 10 ms MB SILK empty packet"); | |
| 915 | 924 | } |
| 916 | 925 | |
| 917 | 926 | /// All four CELT frame sizes survive the loop, and constrained VBR both |
| @@ -1045,7 +1054,14 @@ fn oracle_decodes_our_packets_across_the_rate_table() { | ||
| 1045 | 1054 | enc.set_bitrate(kbps * 1000); |
| 1046 | 1055 | let packets = encode_packets(&mut enc, &pcm, channels); |
| 1047 | 1056 | let path = temp_path(&format!("{channels}ch-{kbps}k.opus")); |
| 1048 | - write_ogg_opus(&path, &packets, opus_head(channels, 120, None), channels, total, 120); | |
| 1057 | + write_ogg_opus( | |
| 1058 | + &path, | |
| 1059 | + &packets, | |
| 1060 | + opus_head(channels, 120, None), | |
| 1061 | + channels, | |
| 1062 | + total, | |
| 1063 | + 120, | |
| 1064 | + ); | |
| 1049 | 1065 | let Some(reference) = ffmpeg_decode(&path, channels) else { |
| 1050 | 1066 | eprintln!("ffmpeg unavailable, skipped"); |
| 1051 | 1067 | let _ = fs::remove_file(&path); |
| @@ -1530,7 +1546,11 @@ fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec<f32> { | ||
| 1530 | 1546 | let h: Vec<f64> = (0..taps) |
| 1531 | 1547 | .map(|i| { |
| 1532 | 1548 | let m = i as f64 - (taps - 1) as f64 / 2.0; |
| 1533 | - let sinc = if m == 0.0 { 2.0 * c } else { (2.0 * std::f64::consts::PI * c * m).sin() / (std::f64::consts::PI * m) }; | |
| 1549 | + let sinc = if m == 0.0 { | |
| 1550 | + 2.0 * c | |
| 1551 | + } else { | |
| 1552 | + (2.0 * std::f64::consts::PI * c * m).sin() / (std::f64::consts::PI * m) | |
| 1553 | + }; | |
| 1534 | 1554 | sinc * (0.54 - 0.46 * (2.0 * std::f64::consts::PI * i as f64 / (taps - 1) as f64).cos()) |
| 1535 | 1555 | }) |
| 1536 | 1556 | .collect(); |
| @@ -1541,7 +1561,11 @@ fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec<f32> { | ||
| 1541 | 1561 | .enumerate() |
| 1542 | 1562 | .map(|(k, &hk)| { |
| 1543 | 1563 | let idx = n as isize + half as isize - k as isize; |
| 1544 | - if idx >= 0 && (idx as usize) < x.len() { hk * x[idx as usize] as f64 } else { 0.0 } | |
| 1564 | + if idx >= 0 && (idx as usize) < x.len() { | |
| 1565 | + hk * x[idx as usize] as f64 | |
| 1566 | + } else { | |
| 1567 | + 0.0 | |
| 1568 | + } | |
| 1545 | 1569 | }) |
| 1546 | 1570 | .sum::<f64>() as f32 |
| 1547 | 1571 | }) |
| @@ -1551,7 +1575,11 @@ fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec<f32> { | ||
| 1551 | 1575 | /// Encodes `pcm` NB or WB, decodes each packet with our decoder asserting the |
| 1552 | 1576 | /// range-coder invariant, returns (decoded 48 kHz, packets, voiced frames, |
| 1553 | 1577 | /// encoder delay). |
| 1554 | -fn silk_roundtrip(pcm: &[f32], wideband: bool, bitrate: Option<u32>) -> (Vec<f32>, Vec<Vec<u8>>, usize, usize) { | |
| 1578 | +fn silk_roundtrip( | |
| 1579 | + pcm: &[f32], | |
| 1580 | + wideband: bool, | |
| 1581 | + bitrate: Option<u32>, | |
| 1582 | +) -> (Vec<f32>, Vec<Vec<u8>>, usize, usize) { | |
| 1555 | 1583 | let mut enc = SilkEncoder::new(wideband); |
| 1556 | 1584 | if let Some(bps) = bitrate { |
| 1557 | 1585 | enc.set_bitrate(bps); |
| @@ -1565,7 +1593,9 @@ fn silk_roundtrip(pcm: &[f32], wideband: bool, bitrate: Option<u32>) -> (Vec<f32 | ||
| 1565 | 1593 | padded.resize(pcm.len().div_ceil(960) * 960 + 960, 0.0); |
| 1566 | 1594 | for block in padded.chunks(960) { |
| 1567 | 1595 | let len = enc.encode_frame(block, &mut out).expect("silk encode"); |
| 1568 | - let n = dec.decode_float(&out[..len], &mut buf).expect("silk decode"); | |
| 1596 | + let n = dec | |
| 1597 | + .decode_float(&out[..len], &mut buf) | |
| 1598 | + .expect("silk decode"); | |
| 1569 | 1599 | assert_eq!(n, 960); |
| 1570 | 1600 | assert_eq!(dec.final_range(), enc.final_range(), "range state diverged"); |
| 1571 | 1601 | decoded.extend_from_slice(&buf[..n]); |
| @@ -1574,6 +1604,38 @@ fn silk_roundtrip(pcm: &[f32], wideband: bool, bitrate: Option<u32>) -> (Vec<f32 | ||
| 1574 | 1604 | (decoded, packets, enc.voiced_frames(), enc.delay_samples()) |
| 1575 | 1605 | } |
| 1576 | 1606 | |
| 1607 | +fn silk_roundtrip_ms( | |
| 1608 | + mut enc: SilkEncoder, | |
| 1609 | + pcm: &[f32], | |
| 1610 | + frame_ms: usize, | |
| 1611 | + bitrate: Option<u32>, | |
| 1612 | +) -> (Vec<f32>, Vec<Vec<u8>>, usize) { | |
| 1613 | + if let Some(bps) = bitrate { | |
| 1614 | + enc.set_bitrate(bps); | |
| 1615 | + } | |
| 1616 | + let frame = 48 * frame_ms; | |
| 1617 | + let mut dec = Decoder::new(48000, 1).unwrap(); | |
| 1618 | + let mut out = vec![0u8; 1500]; | |
| 1619 | + let mut buf = vec![0f32; 5760]; | |
| 1620 | + let mut decoded = Vec::new(); | |
| 1621 | + let mut packets = Vec::new(); | |
| 1622 | + let mut padded = pcm.to_vec(); | |
| 1623 | + padded.resize(pcm.len().div_ceil(frame) * frame + frame, 0.0); | |
| 1624 | + for block in padded.chunks(frame) { | |
| 1625 | + let len = enc | |
| 1626 | + .encode_frame_ms(block, &mut out, frame_ms) | |
| 1627 | + .expect("silk encode"); | |
| 1628 | + let n = dec | |
| 1629 | + .decode_float(&out[..len], &mut buf) | |
| 1630 | + .expect("silk decode"); | |
| 1631 | + assert_eq!(n, frame); | |
| 1632 | + assert_eq!(dec.final_range(), enc.final_range(), "range state diverged"); | |
| 1633 | + decoded.extend_from_slice(&buf[..n]); | |
| 1634 | + packets.push(out[..len].to_vec()); | |
| 1635 | + } | |
| 1636 | + (decoded, packets, enc.voiced_frames()) | |
| 1637 | +} | |
| 1638 | + | |
| 1577 | 1639 | /// Correlation after aligning `decoded` to `reference` at the best lag in |
| 1578 | 1640 | /// `[0, max_lag)`; the peak must be interior (a peak at the search bound is |
| 1579 | 1641 | /// no measurement). |
| @@ -1612,7 +1674,10 @@ fn silk_mono_nb_wb_roundtrip() { | ||
| 1612 | 1674 | bytes * 8 / (packets.len() * 20) |
| 1613 | 1675 | ); |
| 1614 | 1676 | assert!(corr >= 0.8, "{name} {tag}: corr {corr:.4}"); |
| 1615 | - assert!(lag >= delay, "{name} {tag}: aligned before the documented delay"); | |
| 1677 | + assert!( | |
| 1678 | + lag >= delay, | |
| 1679 | + "{name} {tag}: aligned before the documented delay" | |
| 1680 | + ); | |
| 1616 | 1681 | if *name == "synthetic" { |
| 1617 | 1682 | assert!(voiced > 0, "{name} {tag}: no frame coded with LTP"); |
| 1618 | 1683 | } |
| @@ -1628,13 +1693,94 @@ fn silk_mono_nb_wb_roundtrip() { | ||
| 1628 | 1693 | .output() |
| 1629 | 1694 | .unwrap(); |
| 1630 | 1695 | let stderr = String::from_utf8_lossy(&out.stderr); |
| 1631 | - assert!(out.status.success() && stderr.trim().is_empty(), "{name} {tag}: ffmpeg: {stderr}"); | |
| 1696 | + assert!( | |
| 1697 | + out.status.success() && stderr.trim().is_empty(), | |
| 1698 | + "{name} {tag}: ffmpeg: {stderr}" | |
| 1699 | + ); | |
| 1632 | 1700 | let _ = fs::remove_file(&path); |
| 1633 | 1701 | } |
| 1634 | 1702 | } |
| 1635 | 1703 | } |
| 1636 | 1704 | } |
| 1637 | 1705 | |
| 1706 | +#[test] | |
| 1707 | +fn silk_mediumband_and_10ms_roundtrip() { | |
| 1708 | + let pcm = speech_like(); | |
| 1709 | + for (tag, fs_khz, frame_ms, config, cutoff, bps) in [ | |
| 1710 | + ("NB10", 8usize, 10usize, 0u8, 3500.0, 12_000u32), | |
| 1711 | + ("MB10", 12, 10, 4, 5500.0, 16_000), | |
| 1712 | + ("WB10", 16, 10, 8, 7000.0, 20_000), | |
| 1713 | + ("MB20", 12, 20, 5, 5500.0, 16_000), | |
| 1714 | + ] { | |
| 1715 | + let enc = match fs_khz { | |
| 1716 | + 8 => SilkEncoder::new(false), | |
| 1717 | + 12 => SilkEncoder::new_mediumband(), | |
| 1718 | + _ => SilkEncoder::new(true), | |
| 1719 | + }; | |
| 1720 | + let (decoded, packets, voiced) = silk_roundtrip_ms(enc, &pcm, frame_ms, Some(bps)); | |
| 1721 | + assert_eq!(packets[0][0] >> 3, config, "{tag}: wrong TOC config"); | |
| 1722 | + let reference = lowpass(&pcm, cutoff); | |
| 1723 | + let (corr, lag) = aligned_corr(&reference, &decoded, 2000); | |
| 1724 | + let bytes: usize = packets.iter().map(Vec::len).sum(); | |
| 1725 | + let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * frame_ms as f64); | |
| 1726 | + eprintln!( | |
| 1727 | + "silk {tag}: corr {corr:.4} at lag {lag}, voiced {voiced}/{} frames, {kbps:.2} kbps", | |
| 1728 | + packets.len() | |
| 1729 | + ); | |
| 1730 | + assert!(corr >= 0.75, "{tag}: corr {corr:.4}"); | |
| 1731 | + assert!( | |
| 1732 | + frame_ms == 10 || voiced > 0, | |
| 1733 | + "{tag}: no frame coded with LTP" | |
| 1734 | + ); | |
| 1735 | + if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len()) { | |
| 1736 | + let (c, _) = aligned_corr(&oracle, &decoded, 2000); | |
| 1737 | + assert!(c >= 0.99, "{tag}: our decode vs oracle decode corr {c:.4}"); | |
| 1738 | + } | |
| 1739 | + } | |
| 1740 | +} | |
| 1741 | + | |
| 1742 | +#[test] | |
| 1743 | +fn silk_compares_to_celt_on_speech_at_speech_rates() { | |
| 1744 | + let pcm = speech_like(); | |
| 1745 | + for (tag, silk, bandwidth, bps, cutoff) in [ | |
| 1746 | + ( | |
| 1747 | + "NB16", | |
| 1748 | + SilkEncoder::new(false), | |
| 1749 | + Bandwidth::Narrow, | |
| 1750 | + 16_000u32, | |
| 1751 | + 3500.0, | |
| 1752 | + ), | |
| 1753 | + ( | |
| 1754 | + "WB24", | |
| 1755 | + SilkEncoder::new(true), | |
| 1756 | + Bandwidth::Wide, | |
| 1757 | + 24_000u32, | |
| 1758 | + 7000.0, | |
| 1759 | + ), | |
| 1760 | + ] { | |
| 1761 | + let reference = lowpass(&pcm, cutoff); | |
| 1762 | + let (silk_decoded, silk_packets, _) = silk_roundtrip_ms(silk, &pcm, 20, Some(bps)); | |
| 1763 | + let (silk_corr, silk_lag) = aligned_corr(&reference, &silk_decoded, 2000); | |
| 1764 | + let mut celt = Encoder::new(48000, 1, Application::Audio).unwrap(); | |
| 1765 | + celt.set_mode(Some(ec_opus::Mode::Celt)); | |
| 1766 | + celt.set_bandwidth(Some(bandwidth)); | |
| 1767 | + celt.set_bitrate(bps); | |
| 1768 | + let (celt_decoded, celt_bytes) = roundtrip_own(&mut celt, &pcm, 1, 960); | |
| 1769 | + let (celt_corr, celt_lag) = aligned_corr(&reference, &celt_decoded, 2000); | |
| 1770 | + let silk_bytes: usize = silk_packets.iter().map(Vec::len).sum(); | |
| 1771 | + let silk_kbps = silk_bytes as f64 * 8.0 / (silk_packets.len() as f64 * 20.0); | |
| 1772 | + let celt_kbps = celt_bytes as f64 * 8.0 / 1000.0; | |
| 1773 | + eprintln!( | |
| 1774 | + "speech {tag}: SILK corr {silk_corr:.4} lag {silk_lag} {silk_kbps:.2} kbps; CELT corr {celt_corr:.4} lag {celt_lag} {celt_kbps:.2} kbps" | |
| 1775 | + ); | |
| 1776 | + assert!(silk_corr >= 0.95, "{tag}: SILK corr {silk_corr:.4}"); | |
| 1777 | + assert!( | |
| 1778 | + silk_corr + 0.01 >= celt_corr, | |
| 1779 | + "{tag}: SILK {silk_corr:.4} trails CELT {celt_corr:.4} by >0.01" | |
| 1780 | + ); | |
| 1781 | + } | |
| 1782 | +} | |
| 1783 | + | |
| 1638 | 1784 | /// Reference oracle decode of `packets` as Ogg-Opus, or `None` without ffmpeg. |
| 1639 | 1785 | fn oracle_decode(name: &str, packets: &[Vec<u8>], samples: usize) -> Option<Vec<f32>> { |
| 1640 | 1786 | if Command::new("ffmpeg").arg("-version").output().is_err() { |
| @@ -1649,7 +1795,10 @@ fn oracle_decode(name: &str, packets: &[Vec<u8>], samples: usize) -> Option<Vec< | ||
| 1649 | 1795 | .output() |
| 1650 | 1796 | .unwrap(); |
| 1651 | 1797 | let stderr = String::from_utf8_lossy(&out.stderr); |
| 1652 | - assert!(out.status.success() && stderr.trim().is_empty(), "{name}: ffmpeg: {stderr}"); | |
| 1798 | + assert!( | |
| 1799 | + out.status.success() && stderr.trim().is_empty(), | |
| 1800 | + "{name}: ffmpeg: {stderr}" | |
| 1801 | + ); | |
| 1653 | 1802 | let decoded = ffmpeg_decode(&path, 1); |
| 1654 | 1803 | let _ = fs::remove_file(&path); |
| 1655 | 1804 | decoded |
| @@ -1681,7 +1830,9 @@ fn silk_nsq_improves_quality_at_equal_rate() { | ||
| 1681 | 1830 | // at ~0.96 at this rate; its pulse-train part alone reaches 0.992. |
| 1682 | 1831 | let floor = if *name == "synthetic" { 0.96 } else { 0.99 }; |
| 1683 | 1832 | if corr < floor || kbps > 16.0 * 1.2 { |
| 1684 | - failures.push(format!("{name}: corr {corr:.4} (floor {floor}) at {kbps:.1} kbps")); | |
| 1833 | + failures.push(format!( | |
| 1834 | + "{name}: corr {corr:.4} (floor {floor}) at {kbps:.1} kbps" | |
| 1835 | + )); | |
| 1685 | 1836 | } |
| 1686 | 1837 | if let Some(oracle) = oracle_decode(&format!("silk-nsq-{name}"), &packets, pcm.len()) { |
| 1687 | 1838 | let (c, _) = aligned_corr(&oracle, &decoded, 2000); |
| @@ -1697,15 +1848,21 @@ fn silk_rate_control_tracks_target() { | ||
| 1697 | 1848 | for (name, pcm) in &silk_sources() { |
| 1698 | 1849 | for wideband in [false, true] { |
| 1699 | 1850 | for kbps_target in [8u32, 12, 16, 24] { |
| 1700 | - let (decoded, packets, _, _) = silk_roundtrip(pcm, wideband, Some(kbps_target * 1000)); | |
| 1851 | + let (decoded, packets, _, _) = | |
| 1852 | + silk_roundtrip(pcm, wideband, Some(kbps_target * 1000)); | |
| 1701 | 1853 | let bytes: usize = packets.iter().map(Vec::len).sum(); |
| 1702 | 1854 | let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); |
| 1703 | 1855 | let reference = lowpass(pcm, if wideband { 7000.0 } else { 3500.0 }); |
| 1704 | 1856 | let (corr, _) = aligned_corr(&reference, &decoded, 2000); |
| 1705 | 1857 | let tag = if wideband { "WB" } else { "NB" }; |
| 1706 | - eprintln!("silk rate {name} {tag} target {kbps_target}: {kbps:.2} kbps, corr {corr:.4}"); | |
| 1858 | + eprintln!( | |
| 1859 | + "silk rate {name} {tag} target {kbps_target}: {kbps:.2} kbps, corr {corr:.4}" | |
| 1860 | + ); | |
| 1707 | 1861 | let ratio = kbps / kbps_target as f64; |
| 1708 | - assert!((0.8..=1.2).contains(&ratio), "{name} {tag} target {kbps_target}: got {kbps:.2} kbps"); | |
| 1862 | + assert!( | |
| 1863 | + (0.8..=1.2).contains(&ratio), | |
| 1864 | + "{name} {tag} target {kbps_target}: got {kbps:.2} kbps" | |
| 1865 | + ); | |
| 1709 | 1866 | } |
| 1710 | 1867 | } |
| 1711 | 1868 | } |
| @@ -1725,7 +1882,10 @@ fn silk_packets_track_encoder_bitrate() { | ||
| 1725 | 1882 | let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); |
| 1726 | 1883 | eprintln!("encoder bitrate target {kbps_target}: {kbps:.2} kbps"); |
| 1727 | 1884 | let ratio = kbps / kbps_target as f64; |
| 1728 | - assert!((0.8..=1.2).contains(&ratio), "target {kbps_target}: got {kbps:.2} kbps"); | |
| 1885 | + assert!( | |
| 1886 | + (0.8..=1.2).contains(&ratio), | |
| 1887 | + "target {kbps_target}: got {kbps:.2} kbps" | |
| 1888 | + ); | |
| 1729 | 1889 | } |
| 1730 | 1890 | } |
| 1731 | 1891 | |
| @@ -1735,7 +1895,12 @@ fn silk_packets_track_encoder_bitrate() { | ||
| 1735 | 1895 | /// Encodes mono `pcm` as hybrid packets at `bps` and decodes them with our |
| 1736 | 1896 | /// decoder, `mute` = (celt, silk) layers dropped at the decoder; asserts |
| 1737 | 1897 | /// range-state parity packet for packet. Returns (decoded, packets). |
| 1738 | -fn hybrid_roundtrip(pcm: &[f32], bps: u32, bandwidth: Option<Bandwidth>, mute: (bool, bool)) -> (Vec<f32>, Vec<Vec<u8>>) { | |
| 1898 | +fn hybrid_roundtrip( | |
| 1899 | + pcm: &[f32], | |
| 1900 | + bps: u32, | |
| 1901 | + bandwidth: Option<Bandwidth>, | |
| 1902 | + mute: (bool, bool), | |
| 1903 | +) -> (Vec<f32>, Vec<Vec<u8>>) { | |
| 1739 | 1904 | let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); |
| 1740 | 1905 | enc.set_bitrate(bps); |
| 1741 | 1906 | enc.set_bandwidth(bandwidth); |
| @@ -1747,8 +1912,12 @@ fn hybrid_roundtrip(pcm: &[f32], bps: u32, bandwidth: Option<Bandwidth>, mute: ( | ||
| 1747 | 1912 | let mut padded = pcm.to_vec(); |
| 1748 | 1913 | padded.resize(pcm.len().div_ceil(960) * 960 + 960, 0.0); |
| 1749 | 1914 | for block in padded.chunks(960) { |
| 1750 | - let len = enc.encode_float(block, 960, &mut out).expect("hybrid encode"); | |
| 1751 | - let n = dec.decode_float(&out[..len], &mut buf).expect("hybrid decode"); | |
| 1915 | + let len = enc | |
| 1916 | + .encode_float(block, 960, &mut out) | |
| 1917 | + .expect("hybrid encode"); | |
| 1918 | + let n = dec | |
| 1919 | + .decode_float(&out[..len], &mut buf) | |
| 1920 | + .expect("hybrid decode"); | |
| 1752 | 1921 | assert_eq!(n, 960); |
| 1753 | 1922 | assert_eq!(dec.final_range(), enc.final_range(), "range state diverged"); |
| 1754 | 1923 | decoded.extend_from_slice(&buf[..n]); |
| @@ -1767,18 +1936,28 @@ fn hybrid_layers_align() { | ||
| 1767 | 1936 | let at = 960 * 10 + 300; |
| 1768 | 1937 | click[at] = 0.9; |
| 1769 | 1938 | let peak = |x: &[f32]| { |
| 1770 | - x.iter().enumerate().max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()).unwrap().0 | |
| 1939 | + x.iter() | |
| 1940 | + .enumerate() | |
| 1941 | + .max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()) | |
| 1942 | + .unwrap() | |
| 1943 | + .0 | |
| 1771 | 1944 | }; |
| 1772 | 1945 | let (lb, _) = hybrid_roundtrip(&click, 32_000, None, (true, false)); |
| 1773 | 1946 | let (hb, _) = hybrid_roundtrip(&click, 32_000, None, (false, true)); |
| 1774 | 1947 | let enc = Encoder::new(48000, 1, Application::Voip).unwrap(); |
| 1775 | 1948 | let (plb, phb) = (peak(&lb) as i64 - at as i64, peak(&hb) as i64 - at as i64); |
| 1776 | - eprintln!("hybrid click: LB peak +{plb}, HB peak +{phb}, look_ahead {}", { | |
| 1777 | - let mut e = enc.clone(); | |
| 1778 | - e.set_bitrate(32_000); | |
| 1779 | - e.look_ahead(960) | |
| 1780 | - }); | |
| 1781 | - assert!((plb - phb).abs() <= 2, "layers misaligned: LB +{plb} vs HB +{phb}"); | |
| 1949 | + eprintln!( | |
| 1950 | + "hybrid click: LB peak +{plb}, HB peak +{phb}, look_ahead {}", | |
| 1951 | + { | |
| 1952 | + let mut e = enc.clone(); | |
| 1953 | + e.set_bitrate(32_000); | |
| 1954 | + e.look_ahead(960) | |
| 1955 | + } | |
| 1956 | + ); | |
| 1957 | + assert!( | |
| 1958 | + (plb - phb).abs() <= 2, | |
| 1959 | + "layers misaligned: LB +{plb} vs HB +{phb}" | |
| 1960 | + ); | |
| 1782 | 1961 | assert!((phb - 120).abs() <= 2, "HB peak +{phb}, look_ahead 120"); |
| 1783 | 1962 | } |
| 1784 | 1963 | |
| @@ -1797,12 +1976,20 @@ fn hybrid_fb_roundtrip() { | ||
| 1797 | 1976 | let (lb_corr, lb_lag) = aligned_corr(&lb_ref, &lb_only, 400); |
| 1798 | 1977 | let bytes: usize = packets.iter().map(Vec::len).sum(); |
| 1799 | 1978 | let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0); |
| 1800 | - eprintln!("hybrid FB {name}: corr {corr:.4} at lag {lag}, LB corr {lb_corr:.4} at lag {lb_lag}, {kbps:.1} kbps"); | |
| 1979 | + eprintln!( | |
| 1980 | + "hybrid FB {name}: corr {corr:.4} at lag {lag}, LB corr {lb_corr:.4} at lag {lb_lag}, {kbps:.1} kbps" | |
| 1981 | + ); | |
| 1801 | 1982 | assert!(corr >= 0.95, "{name}: full-band corr {corr:.4}"); |
| 1802 | 1983 | // +-3: the wav16 fixture is a pure tone, whose phase moves the peak. |
| 1803 | - assert!((117..=123).contains(&lag), "{name}: aligned at lag {lag}, not the documented 120"); | |
| 1984 | + assert!( | |
| 1985 | + (117..=123).contains(&lag), | |
| 1986 | + "{name}: aligned at lag {lag}, not the documented 120" | |
| 1987 | + ); | |
| 1804 | 1988 | assert!(lb_corr >= 0.9, "{name}: low-band corr {lb_corr:.4}"); |
| 1805 | - assert!((28.0..=36.0).contains(&kbps), "{name}: {kbps:.1} kbps for a 32 kbps CBR target"); | |
| 1989 | + assert!( | |
| 1990 | + (28.0..=36.0).contains(&kbps), | |
| 1991 | + "{name}: {kbps:.1} kbps for a 32 kbps CBR target" | |
| 1992 | + ); | |
| 1806 | 1993 | if let Some(oracle) = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len()) { |
| 1807 | 1994 | let n = oracle.len().min(decoded.len() - 120); |
| 1808 | 1995 | let c = correlation(&oracle[..n], &decoded[120..120 + n]); |
| @@ -1813,14 +2000,22 @@ fn hybrid_fb_roundtrip() { | ||
| 1813 | 2000 | // SWB when asked for it, and the rest of the automatic hybrid range |
| 1814 | 2001 | // (SILK's share leaves CELT least at the bottom of it). |
| 1815 | 2002 | let speech = speech_like(); |
| 1816 | - let (_, packets) = hybrid_roundtrip(&speech, 24_000, Some(Bandwidth::SuperWide), (false, false)); | |
| 2003 | + let (_, packets) = | |
| 2004 | + hybrid_roundtrip(&speech, 24_000, Some(Bandwidth::SuperWide), (false, false)); | |
| 1817 | 2005 | assert_eq!(ec_opus::Toc::new(packets[0][0]).config, 13); |
| 1818 | 2006 | for bps in [20_000u32, 24_000, 39_000] { |
| 1819 | 2007 | let (decoded, packets) = hybrid_roundtrip(&speech, bps, None, (false, false)); |
| 1820 | 2008 | let (corr, _) = aligned_corr(&speech, &decoded, 400); |
| 1821 | - let kbps = packets.iter().map(Vec::len).sum::<usize>() as f64 * 8.0 / (packets.len() as f64 * 20.0); | |
| 1822 | - eprintln!("hybrid {bps}: config {}, corr {corr:.4}, {kbps:.1} kbps", ec_opus::Toc::new(packets[0][0]).config); | |
| 2009 | + let kbps = packets.iter().map(Vec::len).sum::<usize>() as f64 * 8.0 | |
| 2010 | + / (packets.len() as f64 * 20.0); | |
| 2011 | + eprintln!( | |
| 2012 | + "hybrid {bps}: config {}, corr {corr:.4}, {kbps:.1} kbps", | |
| 2013 | + ec_opus::Toc::new(packets[0][0]).config | |
| 2014 | + ); | |
| 1823 | 2015 | assert!(corr >= 0.9, "hybrid at {bps}: corr {corr:.4}"); |
| 1824 | - assert!(kbps <= bps as f64 / 1000.0 + 3.0, "hybrid at {bps}: {kbps:.1} kbps"); | |
| 2016 | + assert!( | |
| 2017 | + kbps <= bps as f64 / 1000.0 + 3.0, | |
| 2018 | + "hybrid at {bps}: {kbps:.1} kbps" | |
| 2019 | + ); | |
| 1825 | 2020 | } |
| 1826 | 2021 | } |