From 7f710e5bcb9798e0b80f61a9ede9ac7ce97157b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 21 Aug 2026 01:21:07 +0300 Subject: [PATCH] feat(opus): SILK mode selection in Encoder Encoder dispatches SILK per frame (mono, 960-sample frames, Voip application under 20 kbps) via set_mode/wants_silk/silk_choice, with a click-measured look_ahead split per bandwidth (NB 58, WB 50 samples at 48 kHz) and a zero-alloc scratch buffer for the SILK payload so the steady-state encode loop stays allocation-free. --- crates/ec-opus/src/encoder.rs | 159 ++++++++++++++++++++++++--- crates/ec-opus/src/silk_enc_write.rs | 1 + crates/ec-opus/tests/conformance.rs | 94 ++++++++++++++-- 3 files changed, 225 insertions(+), 29 deletions(-) diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index abddaf4c..f397387a 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -1,30 +1,43 @@ -//! The Opus packet encoder: CELT-only, 8 to 48 kHz in. +//! The Opus packet encoder: CELT and mono SILK, 8 to 48 kHz in. //! //! One [`Encoder`] produces ordinary code-0 Opus packets (RFC 6716 Section 3) //! or the self-delimited variant of Appendix B that the multistream framing -//! needs. Every configuration this encoder emits is a CELT one (TOC configs -//! 16..31), which is what music encoding uses at every rate the product asks -//! for; there is no SILK and no hybrid path — a speech-optimised mode below -//! 16 kbps is out of scope, not silently approximated. +//! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s +//! default) picks CELT (TOC configs 16..31, every rate and frame size) or +//! SILK (TOC configs 1/9, mono NB/WB 20 ms only — stereo SILK and SILK at +//! other frame sizes fall back to CELT, documented at the fallback site). +//! Hybrid is not implemented yet and also falls back to CELT. //! -//! Input below 48 kHz is zero-stuffed to CELT's native rate and the coded -//! bandwidth is capped at the input's own Nyquist, so the images the stuffing -//! puts there are never coded and the decoder's decimation drops them. -//! [`Encoder::look_ahead`] reports the delay in *input* samples. +//! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and +//! the coded bandwidth is capped at the input's own Nyquist, so the images +//! the stuffing puts there are never coded and the decoder's decimation +//! drops them. [`Encoder::look_ahead`] reports the delay in *input* samples. //! //! Rate control is CBR by default — every packet the same size, derived from //! the bitrate — or constrained VBR, the reference's reservoir scheme, when -//! [`Encoder::set_vbr_constrained`] is on. +//! [`Encoder::set_vbr_constrained`] is on. SILK packets are not yet budgeted +//! against the target rate (D2b). use ec_core::{Error, Result}; use crate::celt_enc::CeltEncoder; -use crate::packet::Bandwidth; +use crate::packet::{Bandwidth, Mode}; use crate::range::RangeEncoder; +use crate::silk_enc_write::SilkEncoder; /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`). const MAX_FRAME_BYTES: usize = 1275; +/// SILK's round-trip algorithmic delay in 48 kHz samples: the analysis +/// resampler (`SilkEncoder::delay_samples`) on the way in plus the decoder's +/// own synthesis resampler on the way out. Click-measured, one impulse +/// through `Encoder`/`Decoder` at each bandwidth, not derived from a +/// formula — `Resampler`'s (decode-side) and `Resampler48`'s (encode-side) +/// FIR lengths differ per bandwidth, so narrowband and wideband delays +/// don't have to and don't match. +const SILK_LOOK_AHEAD_48K_NB: usize = 58; +const SILK_LOOK_AHEAD_48K_WB: usize = 50; + /// What the caller is encoding. This encoder is CELT-only, so the setting /// biases the coded bandwidth rather than selecting a different layer. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -52,6 +65,16 @@ pub struct Encoder { application: Application, bandwidth: Option, final_range: u32, + /// [`None`] picks SILK, CELT or (once D4 lands) Hybrid from the + /// application and bitrate; `Some` forces one. + mode: Option, + /// Lazily created on first use so the mode can flip between packets + /// without paying for the unused layer's state. + silk_nb: Option, + silk_wb: Option, + /// Scratch space for the SILK payload, sized once so the steady-state + /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. + silk_buf: [u8; MAX_FRAME_BYTES + 1], } impl Encoder { @@ -90,9 +113,21 @@ impl Encoder { application, bandwidth: None, final_range: 0, + mode: None, + silk_nb: None, + silk_wb: None, + silk_buf: [0u8; MAX_FRAME_BYTES + 1], }) } + /// Overrides the automatic SILK/CELT choice `wants_silk` would make from + /// the application and bitrate. [`Mode::Hybrid`] is unimplemented and + /// falls back to CELT (documented at the fallback site in + /// [`Encoder::silk_choice`]); pass `None` to restore the automatic pick. + pub fn set_mode(&mut self, mode: Option) { + self.mode = mode; + } + /// Channels per frame of input. pub fn channels(&self) -> usize { self.channels @@ -105,8 +140,22 @@ impl Encoder { /// Encoder delay in *input* samples: the decoded stream lags the input by /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate` - /// cancels it exactly. One MDCT overlap, 120 samples at 48 kHz. + /// cancels it exactly. CELT: one MDCT overlap, 120 samples at 48 kHz. + /// SILK (mono, when the application/bitrate or an explicit + /// [`Encoder::set_mode`] select it): [`SILK_LOOK_AHEAD_48K_NB`] or + /// [`SILK_LOOK_AHEAD_48K_WB`], the analysis-plus-synthesis resampler + /// round trip, click-measured per bandwidth. pub fn look_ahead(&self) -> usize { + if self.channels == 1 { + if let Some(wideband) = self.wants_silk() { + let delay = if wideband { + SILK_LOOK_AHEAD_48K_WB + } else { + SILK_LOOK_AHEAD_48K_NB + }; + return delay / self.upsample; + } + } 120 / self.upsample } @@ -144,9 +193,83 @@ impl Encoder { /// Drops all inter-frame state; the next packet starts like the first. pub fn reset(&mut self) { self.celt.reset(); + self.silk_nb = None; + self.silk_wb = None; self.final_range = 0; } + /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) + /// call for SILK, and if so, wideband (else narrowband). `None` means + /// CELT (or Hybrid, unimplemented and mapped to CELT). + fn wants_silk(&self) -> Option { + match self.mode { + Some(Mode::Celt) | Some(Mode::Hybrid) => None, + Some(Mode::Silk) => Some(self.bitrate > 10_000), + None => { + if self.application == Application::Voip && self.bitrate < 20_000 { + Some(self.bitrate > 10_000) + } else { + None + } + } + } + } + + /// `wants_silk` narrowed to what this encoder can actually code as SILK: + /// mono, 20 ms (960 samples at 48 kHz) frames only. Stereo SILK and SILK + /// at other frame sizes are D2b's work; both fall back to CELT here. + fn silk_choice(&self, frame_48k: usize) -> Option { + let wideband = self.wants_silk()?; + if self.channels != 1 || frame_48k != 960 { + return None; + } + Some(wideband) + } + + /// Zero-stuffs a mono, `frame_size`-sample native-rate frame up to + /// `frame_size * upsample` samples at 48 kHz, the rate [`SilkEncoder`] + /// takes — the same technique [`CeltEncoder::encode`] uses, scaled by + /// `upsample` so the passband gain survives the stuffing. + fn zero_stuff_mono(&self, pcm: &[f32], frame_size: usize) -> Vec { + let up = self.upsample; + if up == 1 { + return pcm[..frame_size].to_vec(); + } + let mut out = vec![0f32; frame_size * up]; + for i in 0..frame_size { + out[i * up] = pcm[i] * up as f32; + } + out + } + + /// Picks SILK or CELT for one frame and encodes it, returning the TOC + /// byte and the payload bytes (excluding TOC), borrowed from scratch + /// space owned by `self` — no allocation on the steady-state path. + /// `cap` bounds the CELT path only — SILK isn't budgeted against a byte + /// cap yet (D2b). + fn encode_toc_and_payload( + &mut self, + pcm: &[f32], + frame_size: usize, + cap: usize, + ) -> Result<(u8, &[u8])> { + let frame_48k = frame_size * self.upsample; + if let Some(wideband) = self.silk_choice(frame_48k) { + let stuffed = self.zero_stuff_mono(pcm, frame_size); + let enc = if wideband { + self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)) + } else { + self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)) + }; + let n = enc.encode_frame(&stuffed, &mut self.silk_buf)?; + self.final_range = enc.final_range(); + return Ok((self.silk_buf[0], &self.silk_buf[1..n])); + } + let (toc, frame_48k, end) = self.toc(frame_size)?; + let n = self.encode_frame(pcm, frame_48k, end, cap)?; + Ok((toc, &self.range.data()[..n])) + } + /// The TOC byte, the frame size in 48 kHz samples and the CELT end band /// for a frame of `frame_size` input samples per channel. fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> { @@ -226,8 +349,8 @@ impl Encoder { frame_size: usize, out: &mut [u8], ) -> Result { - let (toc, frame_48k, end) = self.toc(frame_size)?; - let n = self.encode_frame(pcm, frame_48k, end, out.len().saturating_sub(1))?; + let (toc, payload) = self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1))?; + let n = payload.len(); if out.len() < 1 + n { return Err(Error::corrupt(format!( "opus encode: packet needs {} bytes, buffer holds {}", @@ -236,7 +359,7 @@ impl Encoder { ))); } out[0] = toc; - out[1..1 + n].copy_from_slice(&self.range.data()[..n]); + out[1..1 + n].copy_from_slice(payload); Ok(1 + n) } @@ -255,8 +378,8 @@ impl Encoder { frame_size: usize, out: &mut [u8], ) -> Result { - let (toc, frame_48k, end) = self.toc(frame_size)?; - let n = self.encode_frame(pcm, frame_48k, end, out.len().saturating_sub(3))?; + let (toc, payload) = self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3))?; + let n = payload.len(); let len_bytes = if n < 252 { 1 } else { 2 }; if out.len() < 1 + len_bytes + n { return Err(Error::corrupt(format!( @@ -273,7 +396,7 @@ impl Encoder { out[1] = b0 as u8; out[2] = ((n - b0) / 4) as u8; } - out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(&self.range.data()[..n]); + out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(payload); Ok(1 + len_bytes + n) } diff --git a/crates/ec-opus/src/silk_enc_write.rs b/crates/ec-opus/src/silk_enc_write.rs index b240b92c..5fa959b6 100644 --- a/crates/ec-opus/src/silk_enc_write.rs +++ b/crates/ec-opus/src/silk_enc_write.rs @@ -37,6 +37,7 @@ const LEVEL_ADJUST: f32 = 80.0 / 1024.0; const MAX_PULSE: i32 = 1023; /// A mono, 20 ms, NB or WB SILK encoder. +#[derive(Clone, Debug)] pub struct SilkEncoder { fs_khz: usize, resampler: Resampler48, diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index e0b99470..ef2ad787 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -875,6 +875,44 @@ fn encoder_roundtrips_at_every_rate() { } } +/// The mode `Encoder` actually picks, read back from the packet's own TOC +/// byte: Voip below 20 kbps mono selects SILK (NB at/under 10 kbps, WB +/// above), Voip 20-40 kbps and Audio at any rate stay on CELT (Hybrid is +/// unimplemented and Mode 20-40 kbps needs it, D4). +#[test] +fn encoder_mode_follows_application_and_bitrate() { + // `None` for the two CELT rows: any CELT config is correct there, the + // exact one is `auto_bandwidth`'s call, not mode selection's. + let cases = [ + (Application::Voip, 8_000u32, Some(1u8)), + (Application::Voip, 16_000, Some(9)), + (Application::Audio, 64_000, None), + (Application::Voip, 32_000, None), + ]; + for (app, bps, want_config) in cases { + let mut enc = Encoder::new(48000, 1, app).unwrap(); + enc.set_bitrate(bps); + let pcm = vec![0.0f32; 960]; + let mut out = vec![0u8; 1500]; + let n = enc.encode_float(&pcm, 960, &mut out).unwrap(); + let toc = ec_opus::Toc::new(out[0]); + match want_config { + Some(want) => assert_eq!( + toc.config, want, + "{app:?} at {bps} bps: TOC config {} (wanted {want})", + toc.config + ), + None => assert_eq!( + toc.mode(), + ec_opus::Mode::Celt, + "{app:?} at {bps} bps: TOC config {} is not CELT", + toc.config + ), + } + assert!(n > 1, "{app:?} at {bps} bps: empty packet"); + } +} + /// All four CELT frame sizes survive the loop, and constrained VBR both /// stays decodable and lands near its target. #[test] @@ -915,12 +953,13 @@ use ec_core::{ChannelLayout, Packet as CorePacket, TimeBase}; use ec_ogg::OggMuxer; /// The RFC 7845 identification header for this encoder — built by the crate's -/// own [`ec_opus::ogg`] helper, so a muxer and the encoder cannot disagree — -/// with pre-skip 120, the CELT overlap delay. -fn opus_head(channels: usize, layout: Option<(usize, usize, &[u8])>) -> Vec { +/// own [`ec_opus::ogg`] helper, so a muxer and the encoder cannot disagree. +/// `pre_skip` is the encoder's [`Encoder::look_ahead`]: 120, the CELT overlap +/// delay, for every CELT call site; SILK's own (larger) delay for SILK. +fn opus_head(channels: usize, pre_skip: u16, layout: Option<(usize, usize, &[u8])>) -> Vec { let mapping = layout.map(|(streams, coupled, table)| (1u8, streams as u8, coupled as u8, table)); - ec_opus::ogg::opus_head(channels as u8, 120, 48000, 0, mapping) + ec_opus::ogg::opus_head(channels as u8, pre_skip, 48000, 0, mapping) } /// Muxes 20 ms packets into an Ogg-Opus file whose final granule trims the @@ -932,6 +971,7 @@ fn write_ogg_opus( head: Vec, channels: usize, total_samples: usize, + pre_skip: i64, ) { let file = std::io::BufWriter::new(fs::File::create(path).unwrap()); let mut mux = OggMuxer::new(file); @@ -947,7 +987,7 @@ fn write_ogg_opus( for (idx, p) in packets.iter().enumerate() { let last = idx == packets.len() - 1; let dur = if last { - total_samples as i64 + 120 - pts + total_samples as i64 + pre_skip - pts } else { 960 }; @@ -994,7 +1034,7 @@ fn temp_path(name: &str) -> PathBuf { /// incumbent fails this file's 256 kbps row at correlation 0.06; the MUST /// bars here are correlation >= 0.9 at 96/165/256 kbps. #[test] -fn libopus_decodes_our_packets_across_the_rate_table() { +fn oracle_decodes_our_packets_across_the_rate_table() { for channels in [1usize, 2] { let pcm = test_signal(channels, 2.0); let total = pcm.len() / channels; @@ -1004,7 +1044,7 @@ fn libopus_decodes_our_packets_across_the_rate_table() { enc.set_bitrate(kbps * 1000); let packets = encode_packets(&mut enc, &pcm, channels); let path = temp_path(&format!("{channels}ch-{kbps}k.opus")); - write_ogg_opus(&path, &packets, opus_head(channels, None), channels, total); + write_ogg_opus(&path, &packets, opus_head(channels, 120, None), channels, total, 120); let Some(reference) = ffmpeg_decode(&path, channels) else { eprintln!("ffmpeg unavailable, skipped"); let _ = fs::remove_file(&path); @@ -1059,6 +1099,38 @@ fn libopus_decodes_our_packets_across_the_rate_table() { println!("{line}"); } } + + // SILK, mono, the speech-rate corner: Voip application picks it + // automatically below 20 kbps (`Encoder::wants_silk`). 0.95 rather than + // the CELT floors above — SILK is a speech codec, this is a tone signal, + // not the pulse-coded content it's tuned for. + let pcm = test_signal(1, 2.0); + let total = pcm.len(); + for kbps in [8u32, 12, 16] { + let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); + enc.set_bitrate(kbps * 1000); + let pre_skip = enc.look_ahead() as u16; + let packets = encode_packets(&mut enc, &pcm, 1); + let path = temp_path(&format!("silk-1ch-{kbps}k.opus")); + write_ogg_opus( + &path, + &packets, + opus_head(1, pre_skip, None), + 1, + total, + pre_skip as i64, + ); + let Some(reference) = ffmpeg_decode(&path, 1) else { + eprintln!("ffmpeg unavailable, skipped"); + let _ = fs::remove_file(&path); + return; + }; + let _ = fs::remove_file(&path); + let n = (reference.len()).min(total); + let corr = correlation(&pcm[..n], &reference[..n]); + println!("silk 1 ch {kbps:>3} kbps: corr {corr:.4}"); + assert!(corr >= 0.95, "silk {kbps} kbps: correlation {corr:.4}"); + } } /// 5.1 multistream: one distinct tone per channel, encoded with the @@ -1092,9 +1164,9 @@ fn five_one_encode_end_to_end() { let len = enc.encode_float(&silence, 960, &mut out).expect("encode"); packets.push(out[..len].to_vec()); let (streams, coupled, mapping) = enc.layout(); - let head = opus_head(6, Some((streams, coupled, mapping))); + let head = opus_head(6, 120, Some((streams, coupled, mapping))); let path = temp_path("5.1.opus"); - write_ogg_opus(&path, &packets, head, 6, total); + write_ogg_opus(&path, &packets, head, 6, total, 120); let Some(reference) = ffmpeg_decode(&path, 6) else { eprintln!("ffmpeg unavailable, skipped"); let _ = fs::remove_file(&path); @@ -1126,7 +1198,7 @@ fn ogg_opus_round_trip_duration_is_exact() { enc.set_bitrate(128_000); let packets = encode_packets(&mut enc, &pcm, 2); let path = temp_path("duration.opus"); - write_ogg_opus(&path, &packets, opus_head(2, None), 2, total); + write_ogg_opus(&path, &packets, opus_head(2, 120, None), 2, total, 120); let probe = Command::new("ffprobe") .args([ "-v", @@ -1535,7 +1607,7 @@ fn silk_mono_nb_wb_roundtrip() { // Reference oracle: the packets in an Ogg-Opus file decode cleanly. if Command::new("ffmpeg").arg("-version").output().is_ok() { let path = temp_path(&format!("silk-{name}-{tag}.opus")); - write_ogg_opus(&path, &packets, opus_head(1, None), 1, pcm.len()); + write_ogg_opus(&path, &packets, opus_head(1, 120, None), 1, pcm.len(), 120); let out = Command::new("ffmpeg") .args(["-v", "warning", "-c:a", "libopus", "-i"]) .arg(&path)