forge
Explore
Log in

Don't you dare go Hollow

Add 10ms mediumband silk

Browse files at this commit

35e743eab9a062ff077d477cd9d03a0bed212b51Ahmet Kaan GümüşParent: e44f0f4
  • feat
    • add 10ms mediumband silk
Show full message
feat(opus): add 10ms mediumband silk
crates/ec-opus/src/encoder.rsmodified+85 -62
@@ -4,11 +4,11 @@
44 //! or the self-delimited variant of Appendix B that the multistream framing
55 //! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s
66 //! 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).
1212 //!
1313 //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and
1414 //! the coded bandwidth is capped at the input's own Nyquist, so the images
@@ -38,6 +38,7 @@ const MAX_FRAME_BYTES: usize = 1275;
3838 /// FIR lengths differ per bandwidth, so narrowband and wideband delays
3939 /// don't have to and don't match.
4040 const SILK_LOOK_AHEAD_48K_NB: usize = 58;
41+const SILK_LOOK_AHEAD_48K_MB: usize = 54;
4142 const SILK_LOOK_AHEAD_48K_WB: usize = 50;
4243 /// How far the hybrid path delays the SILK layer's input so its output lines
4344 /// 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;
4748 /// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent.
4849 const HYBRID_CELT_MIN_BYTES: usize = 8;
4950
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.
5252 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
5353 pub enum Application {
5454 /// Speech: one step narrower at a given rate, where the top octave costs
@@ -60,7 +60,7 @@ pub enum Application {
6060 LowDelay,
6161 }
6262
63-/// One elementary Opus encoder: mono or stereo, CELT-only.
63+/// One elementary Opus encoder: mono or stereo.
6464 #[derive(Clone, Debug)]
6565 pub struct Encoder {
6666 celt: CeltEncoder,
@@ -80,6 +80,7 @@ pub struct Encoder {
8080 /// Lazily created on first use so the mode can flip between packets
8181 /// without paying for the unused layer's state.
8282 silk_nb: Option<SilkEncoder>,
83+ silk_mb: Option<SilkEncoder>,
8384 silk_wb: Option<SilkEncoder>,
8485 /// Scratch space for the SILK payload, sized once so the steady-state
8586 /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate.
@@ -129,6 +130,7 @@ impl Encoder {
129130 final_range: 0,
130131 mode: None,
131132 silk_nb: None,
133+ silk_mb: None,
132134 silk_wb: None,
133135 silk_buf: [0u8; MAX_FRAME_BYTES + 1],
134136 silk_delay: Vec::new(),
@@ -139,7 +141,7 @@ impl Encoder {
139141 /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and
140142 /// `hybrid_choice` make from the application and bitrate; pass `None` to
141143 /// 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.
143145 pub fn set_mode(&mut self, mode: Option<Mode>) {
144146 self.mode = mode;
145147 }
@@ -158,23 +160,22 @@ impl Encoder {
158160 /// channel, native rate) frame: the decoded stream lags the input by
159161 /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate`
160162 /// 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.
171172 pub fn look_ahead(&self, frame_size: usize) -> usize {
172173 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,
178179 };
179180 return delay / self.upsample;
180181 }
@@ -216,21 +217,33 @@ impl Encoder {
216217 pub fn reset(&mut self) {
217218 self.celt.reset();
218219 self.silk_nb = None;
220+ self.silk_mb = None;
219221 self.silk_wb = None;
220222 self.silk_delay.clear();
221223 self.final_range = 0;
222224 }
223225
224226 /// 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+ };
228235 match self.mode {
229236 Some(Mode::Celt) | Some(Mode::Hybrid) => None,
230- Some(Mode::Silk) => Some(self.bitrate > 10_000),
237+ Some(Mode::Silk) => Some(forced()),
231238 None => {
232239 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+ })
234247 } else {
235248 None
236249 }
@@ -239,14 +252,14 @@ impl Encoder {
239252 }
240253
241254 /// `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) {
247260 return None;
248261 }
249- Some(wideband)
262+ Some(fs_khz)
250263 }
251264
252265 /// Whether this frame goes out as a hybrid packet, and at which of the two
@@ -260,8 +273,7 @@ impl Encoder {
260273 Some(Mode::Hybrid) => true,
261274 Some(_) => false,
262275 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)
265277 }
266278 };
267279 if !wanted || self.channels != 1 || frame_48k != 960 {
@@ -289,9 +301,19 @@ impl Encoder {
289301 (32000, 22000, 24000),
290302 (64000, 38000, 42000),
291303 ];
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+ };
293311 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);
295317 let (lo, hi) = (&TABLE[i], &TABLE[i + 1]);
296318 pick(lo) + (pick(hi) - pick(lo)) * (total - lo.0) / (hi.0 - lo.0)
297319 }
@@ -329,24 +351,28 @@ impl Encoder {
329351 cap: usize,
330352 ) -> Result<(u8, &[u8])> {
331353 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) {
333355 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)),
338360 };
339361 // Keep SILK's own reservoir-based rate control tracking the
340362 // Encoder's current target on every frame — cheap (an Option<u32>
341363 // store) and catches set_bitrate calls made between frames.
342364 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)?;
344366 self.final_range = enc.final_range();
345367 return Ok((self.silk_buf[0], &self.silk_buf[1..n]));
346368 }
347369 if let Some(bandwidth) = self.hybrid_choice(frame_48k) {
348370 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+ };
350376 return Ok((config << 3, &self.range.data()[..n]));
351377 }
352378 let (toc, frame_48k, end) = self.toc(frame_size)?;
@@ -433,7 +459,8 @@ impl Encoder {
433459 frame_size: usize,
434460 out: &mut [u8],
435461 ) -> 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))?;
437464 let n = payload.len();
438465 if out.len() < 1 + n {
439466 return Err(Error::corrupt(format!(
@@ -462,7 +489,8 @@ impl Encoder {
462489 frame_size: usize,
463490 out: &mut [u8],
464491 ) -> 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))?;
466494 let n = payload.len();
467495 let len_bytes = if n < 252 { 1 } else { 2 };
468496 if out.len() < 1 + len_bytes + n {
@@ -528,14 +556,9 @@ impl Encoder {
528556 // CELT sees the same input as SILK: start band 17 alone keeps it off
529557 // the low band (a one-pole ~6 kHz high-pass here measured identical
530558 // 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)?;
539562 self.final_range = self.range.range();
540563 let payload = &self.range.data()[..n];
541564 self.silk_wb.as_mut().unwrap().replay(payload)?;
@@ -603,16 +626,16 @@ mod tests {
603626 assert_eq!(e.look_ahead(960), 60);
604627 }
605628
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.
610633 #[test]
611634 fn look_ahead_matches_the_frame_size_dispatch_actually_uses() {
612635 let mut e = Encoder::new(48000, 1, Application::Voip).unwrap();
613636 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");
616639 assert_eq!(e.look_ahead(960), 58, "20ms NB SILK");
617640
618641 e.set_bitrate(16000);
crates/ec-opus/src/silk_enc_write.rsmodified+224 -59
@@ -1,5 +1,5 @@
11 //! 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).
33 //!
44 //! Symbol order is exactly `silk::decode()`'s, and every decision is made
55 //! against the decoder's own tables and reconstruction functions. The
@@ -12,7 +12,7 @@
1212 //! output error is fed back through short-term (bandwidth-expanded LPC),
1313 //! harmonic and tilt shaping filters so the noise hides under the signal's
1414 //! 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
1616 //! written yet.
1717
1818 // Same idiom as silk.rs: index loops mirror the decoder's position arithmetic.
@@ -23,12 +23,13 @@ use ec_core::Result;
2323 use crate::range::{RangeDecoder, RangeEncoder};
2424 use crate::silk::tables::*;
2525 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,
2831 };
29-use crate::silk_enc::{estimate_pitch, lpc_analyze, quantize_gains, quantize_nlsf, Resampler48, Vad};
3032
31-const NB_SUBFR: usize = 4;
3233 const SHELL_LEN: usize = 16;
3334 const LTP_ORDER: usize = 5;
3435 /// `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;
3839 /// with 16 such pulses in one block.
3940 const MAX_PULSE: i32 = 1023;
4041
41-/// A mono, 20 ms, NB or WB SILK encoder.
42+/// A mono, 10 or 20 ms, NB/MB/WB SILK encoder.
4243 #[derive(Clone, Debug)]
4344 pub struct SilkEncoder {
4445 fs_khz: usize,
@@ -81,7 +82,16 @@ const PULSE_LAMBDA: f32 = 1.5;
8182 impl SilkEncoder {
8283 /// `wideband`: 16 kHz internal rate (TOC config 9), else 8 kHz (config 1).
8384 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));
8595 SilkEncoder {
8696 fs_khz,
8797 resampler: Resampler48::new(fs_khz as u32),
@@ -124,13 +134,39 @@ impl SilkEncoder {
124134 self.resampler.delay_samples()
125135 }
126136
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`,
128138 /// returning its length.
129139 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)?;
131152 let len = bytes.len();
132153 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;
134170 if out.len() < 1 + len {
135171 return Err(ec_core::Error::corrupt(format!(
136172 "silk encode: packet needs {} bytes, buffer holds {}",
@@ -140,7 +176,7 @@ impl SilkEncoder {
140176 }
141177 out[0] = toc;
142178 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)?;
144180 debug_assert_eq!(self.mirror_range, self.final_range);
145181 Ok(1 + len)
146182 }
@@ -151,7 +187,7 @@ impl SilkEncoder {
151187 /// must [`SilkEncoder::replay`] the finished payload so this encoder's
152188 /// decoder mirror advances.
153189 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(|_| ())
155191 }
156192
157193 /// Decodes `payload` (TOC stripped) through the mirror decoder so the next
@@ -159,10 +195,20 @@ impl SilkEncoder {
159195 /// does this itself, [`SilkEncoder::encode_hybrid`] callers do it once
160196 /// the packet is complete.
161197 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<()> {
162202 let fs = self.fs_khz;
163203 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+ )?;
166212 self.mirror_range = dec.range();
167213 Ok(())
168214 }
@@ -171,12 +217,31 @@ impl SilkEncoder {
171217 /// returned trial's `bytes` are the standalone SILK payload (TOC
172218 /// excluded). With `shared`, the chosen frame's symbols are also written
173219 /// 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+ );
176235 let fs = self.fs_khz;
177236 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;
179239 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+ }
180245 let x: Vec<f32> = self
181246 .resampler
182247 .process(pcm48)
@@ -186,13 +251,15 @@ impl SilkEncoder {
186251 let vad = self.vad.analyze(&x);
187252
188253 // 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+ });
196263 let wb = fs == 16;
197264 let nq = quantize_nlsf(&nlsf_target[..order], wb);
198265 let a_q12 = nlsf2a(&nq.nlsf_q15[..order], order);
@@ -224,14 +291,18 @@ impl SilkEncoder {
224291 let res: Vec<f32> = (0..n as isize).map(whiten).collect();
225292
226293 // 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);
228295 let voiced = pitch.is_some();
229296
230297 let (lag_index, contour_index, pitch_l) = match &pitch {
231298 Some(p) => {
232299 let max_index = (PE_MAX_LAG_MS - PE_MIN_LAG_MS) * fs as i32 - 1;
233300 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+ )
235306 }
236307 None => (0, 0, [0; MAX_NB_SUBFR]),
237308 };
@@ -259,7 +330,7 @@ impl SilkEncoder {
259330 {
260331 let mut r_ol: Vec<f32> = (-(n as isize)..0).map(whiten).collect();
261332 r_ol.extend_from_slice(&res);
262- for k in 0..NB_SUBFR {
333+ for k in 0..nb_subfr {
263334 let (e, gsum) = if voiced {
264335 LTP_GAIN_VQ_2
265336 .iter()
@@ -279,25 +350,51 @@ impl SilkEncoder {
279350 }
280351 }
281352 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+ };
283360 // Over-unity LTP gain: scale the previous frame's history down so
284361 // 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+ };
286371 let ltp_scale = LTPSCALES_TABLE_Q14[ltp_scale_index] as f32 / 16384.0;
287372 // Inactive or low-energy frames (and sparse voiced excitation) take the
288373 // 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;
290379 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;
293382
294383 // Noise shaping filters, from the bandwidth-expanded LPC: the output
295384 // error d follows A(z/g2)(1 - tilt z^-1) / (A(z/g1)(1 - h z^-L)), i.e.
296385 // the quantisation noise sits under the formants and, when voiced,
297386 // under the harmonics, instead of being white at the decoder output.
298387 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();
301398 // (1 - B2(z))(1 - tilt z^-1) = 1 - NB(z).
302399 let mut nb = vec![0f32; order + 1];
303400 for j in 0..order {
@@ -305,7 +402,11 @@ impl SilkEncoder {
305402 nb[j + 1] -= tilt * b2[j];
306403 }
307404 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+ };
309410
310411 // `r`: LTP history in absolute sample units, past frame first (scaled
311412 // by ltp_scale as the decoder scales its rebuilt history), then this
@@ -333,12 +434,13 @@ impl SilkEncoder {
333434 let mut pulses = vec![0i32; n];
334435 let mut seed = seed_index;
335436 let mut err = 0f32;
336- for k in 0..NB_SUBFR {
437+ for k in 0..nb_subfr {
337438 if voiced {
338439 // In-subframe taps (lag shorter than the subframe) see the
339440 // unquantised residual as a stand-in.
340441 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]);
342444 let mut best = f32::INFINITY;
343445 for (v, b) in cbk.iter().enumerate() {
344446 let e: f32 = (0..sub)
@@ -356,9 +458,17 @@ impl SilkEncoder {
356458 let idx = k * sub + i;
357459 let p = n + idx;
358460 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+ };
360466 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>();
362472 if harm > 0.0 {
363473 s += harm * u[p - lag];
364474 }
@@ -375,7 +485,9 @@ impl SilkEncoder {
375485 .into_iter()
376486 .filter(|p| p.abs() <= MAX_PULSE)
377487 .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+ };
379491 cost(a).partial_cmp(&cost(b)).unwrap()
380492 })
381493 .unwrap();
@@ -386,11 +498,22 @@ impl SilkEncoder {
386498 y[p] = r[p] + lpc;
387499 d[p] = y[p] - x[idx];
388500 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>();
390506 err += d[p] * d[p];
391507 }
392508 }
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+ }
394517 };
395518
396519 // Bitstream writer, in decode()'s order; shared by the sizing trials
@@ -400,14 +523,22 @@ impl SilkEncoder {
400523 enc.enc_bit_logp(false, 1); // LBRR flag
401524 // Frame type.
402525 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+ );
404531 } else {
405532 enc.enc_icdf(quant_offset_type, &TYPE_OFFSET_NO_VAD_ICDF, 8);
406533 }
407534 // 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+ );
409540 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 {
411542 enc.enc_icdf(gain_idx[k] as usize, &DELTA_GAIN_ICDF, 8);
412543 }
413544 // NLSFs.
@@ -428,16 +559,27 @@ impl SilkEncoder {
428559 enc.enc_icdf((q + 4) as usize, icdf, 8);
429560 }
430561 }
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+ }
432565 // Pitch + LTP. (One frame per packet: the decoder only takes the
433566 // lag-delta code path for the 2nd+ frame of a packet, so the
434567 // absolute lag is always coded here.)
435568 if voiced {
436569 let half = fs as i32 >> 1;
437570 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+ };
439576 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+ };
441583 enc.enc_icdf(contour_index as usize, contour_icdf, 8);
442584 enc.enc_icdf(per_index, &LTP_PER_INDEX_ICDF, 8);
443585 let gain_icdf: &[u8] = match per_index {
@@ -445,7 +587,7 @@ impl SilkEncoder {
445587 1 => &LTP_GAIN_ICDF_1,
446588 _ => &LTP_GAIN_ICDF_2,
447589 };
448- for k in 0..NB_SUBFR {
590+ for k in 0..nb_subfr {
449591 enc.enc_icdf(run.ltp_index[k], gain_icdf, 8);
450592 }
451593 enc.enc_icdf(ltp_scale_index, &LTPSCALE_ICDF, 8);
@@ -463,7 +605,7 @@ impl SilkEncoder {
463605 *v = ((*v as f64 * scale as f64).round() as i64).clamp(1, i32::MAX as i64) as i32;
464606 }
465607 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);
467609 let (per_index, run) = candidates
468610 .iter()
469611 .map(|&per| (per, run(per, &gains_q16)))
@@ -477,14 +619,21 @@ impl SilkEncoder {
477619 enc.done();
478620 debug_assert!(!enc.error());
479621 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+ }
481630 };
482631
483632 // Rate control: a common gain offset moves every subframe's pulse
484633 // magnitudes together; the reservoir carries each packet's miss.
485634 let mut best = trial(0);
486635 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;
488637 let target = frame_bits + self.reservoir.clamp(-frame_bits, frame_bits);
489638 let bits_of = |t: &Trial| t.bytes.len() as f32 * 8.0;
490639 let (mut s0, mut b0) = (0i32, bits_of(&best));
@@ -509,7 +658,10 @@ impl SilkEncoder {
509658 break;
510659 }
511660 }
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+ );
513665 }
514666 if let Some(enc) = shared {
515667 write(enc, &best.gain_idx, best.per_index, &best.run);
@@ -543,7 +695,6 @@ struct Trial {
543695 run: Run,
544696 }
545697
546-
547698 /// Bits an ICDF symbol costs, for choosing among equivalent codings.
548699 fn icdf_bits(k: usize, icdf: &[u8]) -> f32 {
549700 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
591742 enc.enc_icdf(first, &PULSES_PER_BLOCK_ICDF[rate_level], 8);
592743 for level in 1..=shifts[i] {
593744 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+ };
595750 enc.enc_icdf(sym, icdf, 8);
596751 }
597752 }
@@ -633,7 +788,11 @@ fn shell_encode(enc: &mut RangeEncoder, p: &[i32]) {
633788 fn join(enc: &mut RangeEncoder, a: i32, b: i32, table: &[u8]) -> i32 {
634789 let sum = a + b;
635790 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+ );
637796 }
638797 sum
639798 }
@@ -685,7 +844,14 @@ mod tests {
685844 let len = enc.encode_frame(&x, &mut out).unwrap();
686845 let mut rd = RangeDecoder::new(&out[1..len]);
687846 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+ )
689855 .unwrap();
690856 assert_eq!(n, if wb { 320 } else { 160 });
691857 assert_eq!(rd.range(), enc.final_range(), "frame {frame}");
@@ -694,4 +860,3 @@ mod tests {
694860 }
695861 }
696862 }
697-
crates/ec-opus/tests/conformance.rsmodified+225 -30
@@ -912,6 +912,15 @@ fn encoder_mode_follows_application_and_bitrate() {
912912 }
913913 assert!(n > 1, "{app:?} at {bps} bps: empty packet");
914914 }
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");
915924 }
916925
917926 /// 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() {
10451054 enc.set_bitrate(kbps * 1000);
10461055 let packets = encode_packets(&mut enc, &pcm, channels);
10471056 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+ );
10491065 let Some(reference) = ffmpeg_decode(&path, channels) else {
10501066 eprintln!("ffmpeg unavailable, skipped");
10511067 let _ = fs::remove_file(&path);
@@ -1530,7 +1546,11 @@ fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec<f32> {
15301546 let h: Vec<f64> = (0..taps)
15311547 .map(|i| {
15321548 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+ };
15341554 sinc * (0.54 - 0.46 * (2.0 * std::f64::consts::PI * i as f64 / (taps - 1) as f64).cos())
15351555 })
15361556 .collect();
@@ -1541,7 +1561,11 @@ fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec<f32> {
15411561 .enumerate()
15421562 .map(|(k, &hk)| {
15431563 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+ }
15451569 })
15461570 .sum::<f64>() as f32
15471571 })
@@ -1551,7 +1575,11 @@ fn lowpass(x: &[f32], cutoff_hz: f64) -> Vec<f32> {
15511575 /// Encodes `pcm` NB or WB, decodes each packet with our decoder asserting the
15521576 /// range-coder invariant, returns (decoded 48 kHz, packets, voiced frames,
15531577 /// 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) {
15551583 let mut enc = SilkEncoder::new(wideband);
15561584 if let Some(bps) = bitrate {
15571585 enc.set_bitrate(bps);
@@ -1565,7 +1593,9 @@ fn silk_roundtrip(pcm: &[f32], wideband: bool, bitrate: Option<u32>) -> (Vec<f32
15651593 padded.resize(pcm.len().div_ceil(960) * 960 + 960, 0.0);
15661594 for block in padded.chunks(960) {
15671595 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");
15691599 assert_eq!(n, 960);
15701600 assert_eq!(dec.final_range(), enc.final_range(), "range state diverged");
15711601 decoded.extend_from_slice(&buf[..n]);
@@ -1574,6 +1604,38 @@ fn silk_roundtrip(pcm: &[f32], wideband: bool, bitrate: Option<u32>) -> (Vec<f32
15741604 (decoded, packets, enc.voiced_frames(), enc.delay_samples())
15751605 }
15761606
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+
15771639 /// Correlation after aligning `decoded` to `reference` at the best lag in
15781640 /// `[0, max_lag)`; the peak must be interior (a peak at the search bound is
15791641 /// no measurement).
@@ -1612,7 +1674,10 @@ fn silk_mono_nb_wb_roundtrip() {
16121674 bytes * 8 / (packets.len() * 20)
16131675 );
16141676 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+ );
16161681 if *name == "synthetic" {
16171682 assert!(voiced > 0, "{name} {tag}: no frame coded with LTP");
16181683 }
@@ -1628,13 +1693,94 @@ fn silk_mono_nb_wb_roundtrip() {
16281693 .output()
16291694 .unwrap();
16301695 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+ );
16321700 let _ = fs::remove_file(&path);
16331701 }
16341702 }
16351703 }
16361704 }
16371705
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+
16381784 /// Reference oracle decode of `packets` as Ogg-Opus, or `None` without ffmpeg.
16391785 fn oracle_decode(name: &str, packets: &[Vec<u8>], samples: usize) -> Option<Vec<f32>> {
16401786 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<
16491795 .output()
16501796 .unwrap();
16511797 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+ );
16531802 let decoded = ffmpeg_decode(&path, 1);
16541803 let _ = fs::remove_file(&path);
16551804 decoded
@@ -1681,7 +1830,9 @@ fn silk_nsq_improves_quality_at_equal_rate() {
16811830 // at ~0.96 at this rate; its pulse-train part alone reaches 0.992.
16821831 let floor = if *name == "synthetic" { 0.96 } else { 0.99 };
16831832 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+ ));
16851836 }
16861837 if let Some(oracle) = oracle_decode(&format!("silk-nsq-{name}"), &packets, pcm.len()) {
16871838 let (c, _) = aligned_corr(&oracle, &decoded, 2000);
@@ -1697,15 +1848,21 @@ fn silk_rate_control_tracks_target() {
16971848 for (name, pcm) in &silk_sources() {
16981849 for wideband in [false, true] {
16991850 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));
17011853 let bytes: usize = packets.iter().map(Vec::len).sum();
17021854 let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0);
17031855 let reference = lowpass(pcm, if wideband { 7000.0 } else { 3500.0 });
17041856 let (corr, _) = aligned_corr(&reference, &decoded, 2000);
17051857 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+ );
17071861 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+ );
17091866 }
17101867 }
17111868 }
@@ -1725,7 +1882,10 @@ fn silk_packets_track_encoder_bitrate() {
17251882 let kbps = bytes as f64 * 8.0 / (packets.len() as f64 * 20.0);
17261883 eprintln!("encoder bitrate target {kbps_target}: {kbps:.2} kbps");
17271884 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+ );
17291889 }
17301890 }
17311891
@@ -1735,7 +1895,12 @@ fn silk_packets_track_encoder_bitrate() {
17351895 /// Encodes mono `pcm` as hybrid packets at `bps` and decodes them with our
17361896 /// decoder, `mute` = (celt, silk) layers dropped at the decoder; asserts
17371897 /// 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>>) {
17391904 let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap();
17401905 enc.set_bitrate(bps);
17411906 enc.set_bandwidth(bandwidth);
@@ -1747,8 +1912,12 @@ fn hybrid_roundtrip(pcm: &[f32], bps: u32, bandwidth: Option<Bandwidth>, mute: (
17471912 let mut padded = pcm.to_vec();
17481913 padded.resize(pcm.len().div_ceil(960) * 960 + 960, 0.0);
17491914 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");
17521921 assert_eq!(n, 960);
17531922 assert_eq!(dec.final_range(), enc.final_range(), "range state diverged");
17541923 decoded.extend_from_slice(&buf[..n]);
@@ -1767,18 +1936,28 @@ fn hybrid_layers_align() {
17671936 let at = 960 * 10 + 300;
17681937 click[at] = 0.9;
17691938 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
17711944 };
17721945 let (lb, _) = hybrid_roundtrip(&click, 32_000, None, (true, false));
17731946 let (hb, _) = hybrid_roundtrip(&click, 32_000, None, (false, true));
17741947 let enc = Encoder::new(48000, 1, Application::Voip).unwrap();
17751948 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+ );
17821961 assert!((phb - 120).abs() <= 2, "HB peak +{phb}, look_ahead 120");
17831962 }
17841963
@@ -1797,12 +1976,20 @@ fn hybrid_fb_roundtrip() {
17971976 let (lb_corr, lb_lag) = aligned_corr(&lb_ref, &lb_only, 400);
17981977 let bytes: usize = packets.iter().map(Vec::len).sum();
17991978 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+ );
18011982 assert!(corr >= 0.95, "{name}: full-band corr {corr:.4}");
18021983 // +-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+ );
18041988 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+ );
18061993 if let Some(oracle) = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len()) {
18071994 let n = oracle.len().min(decoded.len() - 120);
18081995 let c = correlation(&oracle[..n], &decoded[120..120 + n]);
@@ -1813,14 +2000,22 @@ fn hybrid_fb_roundtrip() {
18132000 // SWB when asked for it, and the rest of the automatic hybrid range
18142001 // (SILK's share leaves CELT least at the bottom of it).
18152002 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));
18172005 assert_eq!(ec_opus::Toc::new(packets[0][0]).config, 13);
18182006 for bps in [20_000u32, 24_000, 39_000] {
18192007 let (decoded, packets) = hybrid_roundtrip(&speech, bps, None, (false, false));
18202008 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+ );
18232015 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+ );
18252020 }
18262021 }