From 339a2eab7791b2b8b0e261b1de52fe2c187e33e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 13:26:27 +0300 Subject: [PATCH] feat(opus): multi-rate input, application-driven bandwidth, whole shim surface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Grafts onto the merged CELT encoder, all four bitstream-neutral at 48 kHz fullband (the four regression cells re-encode byte for byte): - encoder: input at 8, 12, 16, 24 or 48 kHz, zero-stuffed to CELT's native rate with the coded bandwidth capped at the input's own Nyquist, so the images the stuffing puts there are never coded; look_ahead() reports the delay in input samples (120 at 48 kHz, scaled). - encoder: Application reaches the encoder instead of being discarded at the shim boundary — it biases the coded bandwidth (Voip one step narrower), which is the only thing a CELT-only encoder can honestly do with it, and the TOC now spans configs 16..31 rather than fullband alone. - celt_enc: `end` is a parameter, so the caller bounds the coded bands. - ogg: the RFC 7845 header builders (opus_head, opus_tags, default_mapping) move into the crate, where the encoder, a muxer and the tests share one definition; the conformance test's hand-rolled OpusHead is now that call, and MultistreamEncoder::surround reads the mapping table from it. - shims/opus-rs: the rest of the incumbent's surface — OpusDecoder, MultistreamEncoder::surround, the Bandwidth enum, the vbr field, look_ahead(), final_range() and encode_i16() — so a caller needs no second crate for the decode half or for surround. Proof: the shim's own tests round-trip every input rate through the decoder with range-state parity per packet, hold the 8 kHz..48 kHz look-ahead, force a wideband TOC and read it back, and encode 5.1; the ec-opus suite (RFC vectors, libopus rate table, opus_demo, Ogg duration, zero-alloc) is unchanged and green. --- crates/ec-opus/src/celt_enc.rs | 41 +++- crates/ec-opus/src/encoder.rs | 213 ++++++++++++++--- crates/ec-opus/src/lib.rs | 3 +- crates/ec-opus/src/multistream_enc.rs | 32 ++- crates/ec-opus/src/ogg.rs | 102 ++++++++ crates/ec-opus/tests/conformance.rs | 42 ++-- shims/opus-rs/src/lib.rs | 324 +++++++++++++++++++++++++- 7 files changed, 672 insertions(+), 85 deletions(-) create mode 100644 crates/ec-opus/src/ogg.rs diff --git a/crates/ec-opus/src/celt_enc.rs b/crates/ec-opus/src/celt_enc.rs index 708a254a..fd31e2c4 100644 --- a/crates/ec-opus/src/celt_enc.rs +++ b/crates/ec-opus/src/celt_enc.rs @@ -278,11 +278,13 @@ struct EncBand { lm: i32, } -/// A CELT-layer encoder for one elementary Opus stream (mono or stereo), -/// fullband at 48 kHz. +/// A CELT-layer encoder for one elementary Opus stream (mono or stereo). +/// CELT itself always runs at 48 kHz; slower input is zero-stuffed up to it. #[derive(Clone, Debug)] pub struct CeltEncoder { channels: usize, + /// 48000 / input rate, 1 for native 48 kHz input. + upsample: usize, window: Vec, plans: Vec, /// Preemphasised history, `channels * OVERLAP`. @@ -321,12 +323,14 @@ pub struct CeltEncoder { } impl CeltEncoder { - /// An encoder for `channels` channels (1 or 2) at 48 kHz. - pub fn new(channels: usize) -> CeltEncoder { + /// An encoder for `channels` channels (1 or 2) fed at `48000/upsample` Hz. + pub fn new(channels: usize, upsample: usize) -> CeltEncoder { assert!((1..=2).contains(&channels)); + assert!(upsample >= 1); let max_n = SHORT_MDCT * 8; CeltEncoder { channels, + upsample, window: celt::overlap_window(), plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(), in_mem: vec![0.0; channels * OVERLAP], @@ -382,8 +386,10 @@ impl CeltEncoder { } /// Encodes one frame of interleaved `f32` (`frame_size` samples per - /// channel at 48 kHz, `frame_size` one of 120/240/480/960) into `enc`, - /// which must have been `reset` to the frame's byte budget. With + /// channel at 48 kHz, one of 120/240/480/960 — of which + /// `frame_size/upsample` are read from `pcm`) into `enc`, which must have + /// been `reset` to the frame's byte budget. `end` bounds the coded bands, + /// which is how the caller limits the coded bandwidth. With /// `vbr_rate_bps` set, the frame may be shrunk below that budget /// (constrained VBR); the return value is the final frame size in bytes. pub fn encode( @@ -391,6 +397,7 @@ impl CeltEncoder { enc: &mut RangeEncoder, pcm: &[f32], frame_size: usize, + end: usize, vbr_rate_bps: u32, ) -> Result { let lm: usize = match frame_size { @@ -408,14 +415,14 @@ impl CeltEncoder { let m = 1usize << lm; let n = frame_size; let c = self.channels; - if pcm.len() < n * c { + let in_n = n / self.upsample; + if pcm.len() < in_n * c { return Err(Error::corrupt(format!( - "celt encode: {} samples for a {}-channel {frame_size}-sample frame", - pcm.len(), - c + "celt encode: {} samples for a {c}-channel {in_n}-sample frame", + pcm.len() ))); } - let (start, end) = (0usize, NB_BANDS); + let (start, end) = (0usize, end.clamp(1, NB_BANDS)); let mut nb_compressed = enc.storage(); let mut nb_available = nb_compressed as i32; @@ -451,8 +458,18 @@ impl CeltEncoder { self.in_buf[base..base + OVERLAP] .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]); let mut mem = self.preemph_mem[ch]; + let up = self.upsample; for i in 0..n { - let mut x = pcm[i * c + ch] * SIG_SCALE; + // Zero-stuffing to 48 kHz: the images above the input's own + // Nyquist are never coded (the caller caps `end`) and the + // decoder's decimation drops them. + let mut x = if up == 1 { + pcm[i * c + ch] * SIG_SCALE + } else if i.is_multiple_of(up) { + pcm[(i / up) * c + ch] * SIG_SCALE * up as f32 + } else { + 0.0 + }; if !x.is_finite() { x = 0.0; } diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index 01ce7211..abddaf4c 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -1,11 +1,16 @@ -//! The Opus packet encoder: CELT-only, fullband, 48 kHz. +//! The Opus packet encoder: CELT-only, 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 fullband CELT one -//! (TOC configs 28..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. 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. +//! +//! 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. //! //! Rate control is CBR by default — every packet the same size, derived from //! the bitrate — or constrained VBR, the reference's reservoir scheme, when @@ -14,34 +19,60 @@ use ec_core::{Error, Result}; use crate::celt_enc::CeltEncoder; +use crate::packet::Bandwidth; use crate::range::RangeEncoder; /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`). const MAX_FRAME_BYTES: usize = 1275; -/// One elementary Opus encoder: mono or stereo, CELT-only, 48 kHz in. +/// 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)] +pub enum Application { + /// Speech: one step narrower at a given rate, where the top octave costs + /// most and carries least. + Voip, + /// Music and general audio, the default. + Audio, + /// Lowest delay. + LowDelay, +} + +/// One elementary Opus encoder: mono or stereo, CELT-only. #[derive(Clone, Debug)] pub struct Encoder { celt: CeltEncoder, range: RangeEncoder, + sample_rate: u32, + /// 48000 / `sample_rate`: the zero-stuffing factor into CELT. + upsample: usize, channels: usize, bitrate: u32, vbr: bool, + application: Application, + bandwidth: Option, final_range: u32, } impl Encoder { /// An encoder for `channels` channels (1 or 2) at `sample_rate`, which - /// must be 48000 — CELT's native rate, and the only rate the product - /// feeds it (RFC 7845 Section 5.1: every Opus decoder runs at 48 kHz - /// regardless of what the container claims). - pub fn new(sample_rate: u32, channels: usize) -> Result { - if sample_rate != 48000 { - return Err(Error::unsupported( - format!("opus encode at {sample_rate} Hz"), - "this CELT-only encoder takes 48 kHz input; resample first", - )); - } + /// must be one of 8000, 12000, 16000, 24000 or 48000 Hz — the rates + /// RFC 6716 Section 2 admits. CELT itself runs at 48 kHz whatever the + /// input rate is (RFC 7845 Section 5.1). + pub fn new(sample_rate: u32, channels: usize, application: Application) -> Result { + let upsample = match sample_rate { + 48000 => 1, + 24000 => 2, + 16000 => 3, + 12000 => 4, + 8000 => 6, + _ => { + return Err(Error::unsupported( + format!("opus encode at {sample_rate} Hz"), + "Opus encodes from 8, 12, 16, 24 or 48 kHz; resample first", + )); + } + }; if !(1..=2).contains(&channels) { return Err(Error::unsupported( format!("{channels}-channel Opus stream"), @@ -49,11 +80,15 @@ impl Encoder { )); } Ok(Encoder { - celt: CeltEncoder::new(channels), + celt: CeltEncoder::new(channels, upsample), range: RangeEncoder::new(), + sample_rate, + upsample, channels, bitrate: 64_000 * channels as u32, vbr: false, + application, + bandwidth: None, final_range: 0, }) } @@ -63,6 +98,24 @@ impl Encoder { self.channels } + /// The rate the caller feeds. + pub fn sample_rate(&self) -> u32 { + self.sample_rate + } + + /// 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. + pub fn look_ahead(&self) -> usize { + 120 / self.upsample + } + + /// Forces the coded bandwidth; [`None`] (the default) picks it from the + /// bitrate, the application and the input's Nyquist. + pub fn set_bandwidth(&mut self, bandwidth: Option) { + self.bandwidth = bandwidth; + } + /// Target bitrate in bits per second for the whole packet stream, /// including the packet headers. Clamped to 500..=510000. pub fn set_bitrate(&mut self, bps: u32) { @@ -94,34 +147,87 @@ impl Encoder { self.final_range = 0; } - fn toc(&self, frame_size: usize) -> Result { - let fs_idx: u8 = match frame_size { + /// 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)> { + let frame_48k = frame_size * self.upsample; + let fs_idx: u8 = match frame_48k { 120 => 0, 240 => 1, 480 => 2, 960 => 3, _ => { return Err(Error::unsupported( - format!("opus frame of {frame_size} samples"), - "CELT frames are 120, 240, 480 or 960 samples at 48 kHz", + format!( + "opus frame of {frame_size} samples at {} Hz", + self.sample_rate + ), + "CELT frames are 2.5, 5, 10 or 20 ms", )); } }; - let config = 28 + fs_idx; // fullband CELT - Ok((config << 3) | (u8::from(self.channels == 2) << 2)) + let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth()); + let bw_idx: u8 = match bandwidth { + Bandwidth::Narrow => 0, + // CELT has no mediumband configuration; the next one up covers it. + Bandwidth::Medium | Bandwidth::Wide => 1, + Bandwidth::SuperWide => 2, + Bandwidth::Full => 3, + }; + let config = 16 + 4 * bw_idx + fs_idx; + Ok(( + (config << 3) | (u8::from(self.channels == 2) << 2), + frame_48k, + bandwidth.celt_end_band(), + )) + } + + /// Bandwidth from the bitrate: coding 20 kHz at 24 kbps spends bits on air. + /// + /// The thresholds are on the mono-equivalent rate — a coupled stereo stream + /// needs about 1.6x a mono one for the same per-channel quality — and VoIP + /// asks for one step narrower. The input's own Nyquist bounds the result: + /// coding above it would code the images the zero-stuffing put there. + fn auto_bandwidth(&self) -> Bandwidth { + let equiv = if self.channels == 2 { + (self.bitrate as f32 * 0.62) as u32 + } else { + self.bitrate + }; + let equiv = if self.application == Application::Voip { + (equiv as f32 * 0.7) as u32 + } else { + equiv + }; + let ceiling = match self.sample_rate { + 48000 => Bandwidth::Full, + 24000 => Bandwidth::SuperWide, + 16000 => Bandwidth::Wide, + _ => Bandwidth::Narrow, + }; + let wanted = if equiv < 9000 { + Bandwidth::Narrow + } else if equiv < 13000 { + Bandwidth::Wide + } else if equiv < 20000 { + Bandwidth::SuperWide + } else { + Bandwidth::Full + }; + wanted.min(ceiling) } /// Encodes one frame — `frame_size` samples per channel of interleaved - /// `f32` at 48 kHz, `frame_size` one of 120/240/480/960 — as a code-0 - /// Opus packet in `out`, returning the packet length. + /// `f32` at the input rate, 2.5, 5, 10 or 20 ms of it — as a code-0 Opus + /// packet in `out`, returning the packet length. pub fn encode_float( &mut self, pcm: &[f32], frame_size: usize, out: &mut [u8], ) -> Result { - let toc = self.toc(frame_size)?; - let n = self.encode_frame(pcm, frame_size, out.len().saturating_sub(1))?; + let (toc, frame_48k, end) = self.toc(frame_size)?; + let n = self.encode_frame(pcm, frame_48k, end, out.len().saturating_sub(1))?; if out.len() < 1 + n { return Err(Error::corrupt(format!( "opus encode: packet needs {} bytes, buffer holds {}", @@ -134,6 +240,12 @@ impl Encoder { Ok(1 + n) } + /// [`Encoder::encode_float`] from 16-bit samples. + pub fn encode(&mut self, pcm: &[i16], frame_size: usize, out: &mut [u8]) -> Result { + let float: Vec = pcm.iter().map(|&v| v as f32 * (1.0 / 32768.0)).collect(); + self.encode_float(&float, frame_size, out) + } + /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716 /// Appendix B: TOC, an explicit frame length, then the frame. This is /// what every stream but the last uses inside a multistream packet. @@ -143,8 +255,8 @@ impl Encoder { frame_size: usize, out: &mut [u8], ) -> Result { - let toc = self.toc(frame_size)?; - let n = self.encode_frame(pcm, frame_size, out.len().saturating_sub(3))?; + let (toc, frame_48k, end) = self.toc(frame_size)?; + let n = self.encode_frame(pcm, frame_48k, end, out.len().saturating_sub(3))?; let len_bytes = if n < 252 { 1 } else { 2 }; if out.len() < 1 + len_bytes + n { return Err(Error::corrupt(format!( @@ -166,9 +278,15 @@ impl Encoder { } /// Encodes the CELT frame into the internal range coder and returns its - /// byte length. `cap` bounds the frame (the caller's buffer minus - /// headers). - fn encode_frame(&mut self, pcm: &[f32], frame_size: usize, cap: usize) -> Result { + /// byte length. `frame_size` is in 48 kHz samples, `end` is the last coded + /// band, and `cap` bounds the frame (the caller's buffer minus headers). + fn encode_frame( + &mut self, + pcm: &[f32], + frame_size: usize, + end: usize, + cap: usize, + ) -> Result { let cap = cap.min(MAX_FRAME_BYTES); if cap < 2 { return Err(Error::corrupt( @@ -186,8 +304,37 @@ impl Encoder { self.range.reset(budget); let n = self .celt - .encode(&mut self.range, pcm, frame_size, vbr_rate)?; + .encode(&mut self.range, pcm, frame_size, end, vbr_rate)?; self.final_range = self.range.range(); Ok(n) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The private half of the bandwidth decision: the thresholds themselves, + /// which the TOC config only reports. + #[test] + fn bandwidth_follows_the_bitrate_the_application_and_the_input_rate() { + let mut e = Encoder::new(48000, 1, Application::Audio).unwrap(); + e.set_bitrate(64000); + assert_eq!(e.auto_bandwidth(), Bandwidth::Full); + e.set_bitrate(16000); + assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide); + e.set_bitrate(10000); + assert_eq!(e.auto_bandwidth(), Bandwidth::Wide); + e.set_bitrate(8000); + assert_eq!(e.auto_bandwidth(), Bandwidth::Narrow); + // Speech asks for one step narrower at the same rate. + let mut v = Encoder::new(48000, 1, Application::Voip).unwrap(); + v.set_bitrate(16000); + assert_eq!(v.auto_bandwidth(), Bandwidth::Wide); + // The input's own Nyquist bounds it whatever the rate says. + let mut e = Encoder::new(24000, 2, Application::Audio).unwrap(); + e.set_bitrate(256_000); + assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide); + assert_eq!(e.look_ahead(), 60); + } +} diff --git a/crates/ec-opus/src/lib.rs b/crates/ec-opus/src/lib.rs index b482136c..d1d97d64 100644 --- a/crates/ec-opus/src/lib.rs +++ b/crates/ec-opus/src/lib.rs @@ -66,13 +66,14 @@ pub mod celt_enc; pub mod encoder; pub mod multistream; pub mod multistream_enc; +pub mod ogg; pub mod packet; pub mod range; pub mod silk; pub use celt::CeltDecoder; pub use celt_enc::CeltEncoder; -pub use encoder::Encoder; +pub use encoder::{Application, Encoder}; pub use multistream::MultistreamDecoder; pub use multistream_enc::MultistreamEncoder; pub use packet::{Bandwidth, Mode, Packet, Toc}; diff --git a/crates/ec-opus/src/multistream_enc.rs b/crates/ec-opus/src/multistream_enc.rs index 6e625642..99a3ee67 100644 --- a/crates/ec-opus/src/multistream_enc.rs +++ b/crates/ec-opus/src/multistream_enc.rs @@ -13,7 +13,7 @@ use ec_core::{Error, Result}; -use crate::encoder::Encoder; +use crate::encoder::{Application, Encoder}; /// A multichannel Opus encoder, mono through 255 channels. #[derive(Debug)] @@ -36,6 +36,7 @@ impl MultistreamEncoder { streams: usize, coupled: usize, mapping: &[u8], + application: Application, ) -> Result { if streams == 0 || streams > 255 || coupled > streams { return Err(Error::corrupt(format!( @@ -57,7 +58,7 @@ impl MultistreamEncoder { let mut encoders = Vec::with_capacity(streams); for s in 0..streams { let ch = if s < coupled { 2 } else { 1 }; - encoders.push(Encoder::new(sample_rate, ch)?); + encoders.push(Encoder::new(sample_rate, ch, application)?); } Ok(MultistreamEncoder { streams: encoders, @@ -68,10 +69,35 @@ impl MultistreamEncoder { }) } + /// The RFC 7845 Section 5.1.1.2 default layout for `channels` channels + /// (1 to 8), which for 5.1 is four streams, two coupled, in Vorbis channel + /// order (FL, FC, FR, BL, BR, LFE) — see [`crate::ogg::default_mapping`] + /// for the permutation a film-order caller applies on the way in. + pub fn surround( + sample_rate: u32, + channels: usize, + application: Application, + ) -> Result { + let (_family, streams, coupled, table) = + crate::ogg::default_mapping(channels).ok_or_else(|| { + Error::unsupported( + format!("{channels}-channel Opus stream"), + "RFC 7845 maps 1 to 8 channels", + ) + })?; + MultistreamEncoder::new( + sample_rate, + streams as usize, + coupled as usize, + &table, + application, + ) + } + /// The RFC 7845 mapping-family-1 layout for 5.1: four streams, two /// coupled, Vorbis channel order (FL, FC, FR, BL, BR, LFE). pub fn surround_5_1(sample_rate: u32) -> Result { - MultistreamEncoder::new(sample_rate, 4, 2, &[0, 4, 1, 2, 3, 5]) + MultistreamEncoder::surround(sample_rate, 6, Application::Audio) } /// Input channels per frame. diff --git a/crates/ec-opus/src/ogg.rs b/crates/ec-opus/src/ogg.rs new file mode 100644 index 00000000..503679a6 --- /dev/null +++ b/crates/ec-opus/src/ogg.rs @@ -0,0 +1,102 @@ +//! The Ogg-Opus header packets, RFC 7845. +//! +//! Only the two headers and the channel-mapping table live here; the pages +//! themselves are `ec-ogg`'s job. Keeping the mapping in this crate is what +//! lets an encoder and a muxer agree without either depending on the other. +//! +//! Two numbers a caller must not invent: +//! +//! - **pre-skip** is the encoder's delay in 48 kHz samples +//! ([`crate::Encoder::look_ahead`] scaled to 48 kHz — 120 for this encoder). +//! A player discards that many samples, which is exactly what cancels the +//! delay; getting it wrong shifts the whole stream. +//! - **granule position** counts 48 kHz samples *including* the pre-skip, so +//! the first page's granule is `samples_encoded` and the file's duration is +//! `last_granule - pre_skip`. + +/// Builds an `OpusHead` packet (RFC 7845, Section 5.1). +/// +/// `input_rate` is the rate the samples arrived at, informational only — +/// the granule clock is always 48 kHz. `mapping` is `(family, streams, +/// coupled, table)`; [`None`] writes family 0, which is mono or stereo. +pub fn opus_head( + channels: u8, + pre_skip: u16, + input_rate: u32, + output_gain_q8: i16, + mapping: Option<(u8, u8, u8, &[u8])>, +) -> Vec { + let mut v = Vec::with_capacity(21 + channels as usize); + v.extend_from_slice(b"OpusHead"); + v.push(1); + v.push(channels); + v.extend_from_slice(&pre_skip.to_le_bytes()); + v.extend_from_slice(&input_rate.to_le_bytes()); + v.extend_from_slice(&output_gain_q8.to_le_bytes()); + match mapping { + None => v.push(0), + Some((family, streams, coupled, table)) => { + v.push(family); + v.push(streams); + v.push(coupled); + v.extend_from_slice(table); + } + } + v +} + +/// Builds an `OpusTags` packet with a vendor string and no comments. +pub fn opus_tags(vendor: &str) -> Vec { + let mut v = Vec::with_capacity(16 + vendor.len()); + v.extend_from_slice(b"OpusTags"); + v.extend_from_slice(&(vendor.len() as u32).to_le_bytes()); + v.extend_from_slice(vendor.as_bytes()); + v.extend_from_slice(&0u32.to_le_bytes()); + v +} + +/// The default channel mapping of RFC 7845 Section 5.1.1.2: `(family, streams, +/// coupled, table)` for 1 to 8 channels. +/// +/// Families 0 and 1 differ in more than the table: family 1 puts the channels +/// in *Vorbis* order (for 5.1: left, centre, right, back left, back right, +/// LFE), so a caller whose buffers are in the usual film order +/// (FL, FR, FC, LFE, BL, BR) permutes by `[0, 2, 1, 4, 5, 3]` on the way in and +/// by the same permutation on the way out. +pub fn default_mapping(channels: usize) -> Option<(u8, u8, u8, Vec)> { + let m: (u8, u8, u8, &[u8]) = match channels { + 1 => (0, 1, 0, &[0]), + 2 => (0, 1, 1, &[0, 1]), + 3 => (1, 2, 1, &[0, 2, 1]), + 4 => (1, 2, 2, &[0, 1, 2, 3]), + 5 => (1, 3, 2, &[0, 4, 1, 2, 3]), + 6 => (1, 4, 2, &[0, 4, 1, 2, 3, 5]), + 7 => (1, 4, 3, &[0, 4, 1, 2, 3, 5, 6]), + 8 => (1, 5, 4, &[0, 6, 1, 2, 3, 4, 5, 7]), + _ => return None, + }; + Some((m.0, m.1, m.2, m.3.to_vec())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_head_is_what_the_rfc_describes() { + let h = opus_head(2, 120, 48000, 0, None); + assert_eq!(&h[..8], b"OpusHead"); + assert_eq!(h[8], 1, "version"); + assert_eq!(h[9], 2, "channels"); + assert_eq!(u16::from_le_bytes([h[10], h[11]]), 120, "pre-skip"); + assert_eq!(u32::from_le_bytes([h[12], h[13], h[14], h[15]]), 48000); + assert_eq!(h[18], 0, "mapping family"); + assert_eq!(h.len(), 19); + + let (family, streams, coupled, table) = default_mapping(6).unwrap(); + let h = opus_head(6, 120, 48000, 0, Some((family, streams, coupled, &table))); + assert_eq!(h.len(), 21 + 6); + assert_eq!(&h[18..21], &[1, 4, 2]); + assert_eq!(&h[21..], &[0, 4, 1, 2, 3, 5]); + } +} diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 5a434454..be64842f 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -772,7 +772,7 @@ fn real_library_sweep() { // Encoder: self-consistency (range-exact against our own decoder) // --------------------------------------------------------------------------- -use ec_opus::{Encoder, MultistreamEncoder}; +use ec_opus::{Application, Encoder, MultistreamEncoder}; /// A deterministic music-like test signal: several detuned partials plus a /// swept component per channel, loud enough to exercise every band. @@ -860,7 +860,7 @@ fn encoder_roundtrips_at_every_rate() { for channels in [1usize, 2] { let pcm = test_signal(channels, 2.0); for kbps in [32u32, 64, 96, 128, 160, 165, 192, 256, 320, 510] { - let mut enc = Encoder::new(48000, channels).unwrap(); + let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap(); enc.set_bitrate(kbps * 1000); let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, channels, 960); let corr = delayed_corr(&pcm, &decoded, channels); @@ -881,14 +881,14 @@ fn encoder_roundtrips_at_every_rate() { fn encoder_frame_sizes_and_vbr() { let pcm = test_signal(2, 1.0); for frame in [120usize, 240, 480, 960] { - let mut enc = Encoder::new(48000, 2).unwrap(); + let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); enc.set_bitrate(128_000); let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, frame); let corr = delayed_corr(&pcm, &decoded, 2); println!("frame {frame}: corr {corr:.4}"); assert!(corr >= 0.85, "frame {frame}: correlation {corr:.4}"); } - let mut enc = Encoder::new(48000, 2).unwrap(); + let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); enc.set_bitrate(128_000); enc.set_vbr_constrained(true); let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, 2, 960); @@ -914,25 +914,13 @@ use ec_core::registry::{CodecId, CodecParameters, MediaParameters, Muxer, Stream use ec_core::{ChannelLayout, Packet as CorePacket, TimeBase}; use ec_ogg::OggMuxer; -/// The RFC 7845 identification header for this encoder: pre-skip 120, the -/// CELT overlap delay. +/// 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 { - let mut h = Vec::from(*b"OpusHead"); - h.push(1); - h.push(channels as u8); - h.extend_from_slice(&120u16.to_le_bytes()); - h.extend_from_slice(&48000u32.to_le_bytes()); - h.extend_from_slice(&0i16.to_le_bytes()); - match layout { - None => h.push(0), - Some((streams, coupled, mapping)) => { - h.push(1); - h.push(streams as u8); - h.push(coupled as u8); - h.extend_from_slice(mapping); - } - } - h + 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) } /// Muxes 20 ms packets into an Ogg-Opus file whose final granule trims the @@ -1012,7 +1000,7 @@ fn libopus_decodes_our_packets_across_the_rate_table() { let total = pcm.len() / channels; let mut table = Vec::new(); for kbps in [16u32, 32, 64, 96, 128, 160, 165, 192, 256, 320, 510] { - let mut enc = Encoder::new(48000, channels).unwrap(); + let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap(); enc.set_bitrate(kbps * 1000); let packets = encode_packets(&mut enc, &pcm, channels); let path = temp_path(&format!("{channels}ch-{kbps}k.opus")); @@ -1134,7 +1122,7 @@ fn five_one_encode_end_to_end() { fn ogg_opus_round_trip_duration_is_exact() { let pcm = test_signal(2, 2.0); let total = pcm.len() / 2; - let mut enc = Encoder::new(48000, 2).unwrap(); + let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); enc.set_bitrate(128_000); let packets = encode_packets(&mut enc, &pcm, 2); let path = temp_path("duration.opus"); @@ -1191,7 +1179,7 @@ fn opus_demo_decodes_our_bit_stream() { return; }; let pcm = test_signal(2, 2.0); - let mut enc = Encoder::new(48000, 2).unwrap(); + let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); enc.set_bitrate(256_000); let mut out = vec![0u8; 1500]; let mut bit = Vec::new(); @@ -1252,7 +1240,7 @@ fn steady_state_encode_loop_zero_alloc() { v }; // Stereo elementary encoder. - let mut enc = Encoder::new(48000, 2).unwrap(); + let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); enc.set_bitrate(256_000); let mut out = vec![0u8; 1500]; for block in pcm.chunks_exact(960 * 2) { @@ -1302,7 +1290,7 @@ fn encode_speed() { ("stereo 510k", 2, 510, 50.0), ] { let pcm = test_signal(channels, secs); - let mut enc = Encoder::new(48000, channels).unwrap(); + let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap(); enc.set_bitrate(kbps * 1000); let mut out = vec![0u8; 1500]; // Warm up one pass, then measure. diff --git a/shims/opus-rs/src/lib.rs b/shims/opus-rs/src/lib.rs index 009be1e9..7ccae9bd 100644 --- a/shims/opus-rs/src/lib.rs +++ b/shims/opus-rs/src/lib.rs @@ -14,15 +14,19 @@ //! //! `complexity` is accepted for drop-in compatibility and ignored: this //! encoder has one (fast) analysis path, not a ladder. +//! +//! One behaviour is genuinely narrower and is stated rather than hidden: this +//! encoder is **CELT-only**, so [`Application::Voip`] selects a narrower +//! bandwidth at a given rate but not the SILK layer the name implies. Speech +//! below about 32 kbps is where that costs the most. #![forbid(unsafe_code)] #![warn(missing_docs)] use std::fmt; -/// What the encoded stream is optimised for. This CELT-only encoder treats -/// every application as [`Application::Audio`]; the variants exist for call -/// compatibility. +/// What the encoded stream is optimised for. This CELT-only encoder spends the +/// setting on the coded bandwidth, not on a different coding layer. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Application { /// Speech-optimised (SILK in libopus; served by CELT here). @@ -33,6 +37,33 @@ pub enum Application { RestrictedLowdelay, } +impl From for ec_opus::Application { + fn from(a: Application) -> ec_opus::Application { + match a { + Application::Voip => ec_opus::Application::Voip, + Application::Audio => ec_opus::Application::Audio, + Application::RestrictedLowdelay => ec_opus::Application::LowDelay, + } + } +} + +/// Coded audio bandwidth, with the C API's discriminants. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Bandwidth { + /// Chosen from the bitrate, the application and the input rate. + Auto = -1000, + /// 4 kHz. + Narrowband = 1101, + /// 6 kHz. CELT has no mediumband configuration; this codes as wideband. + Mediumband = 1102, + /// 8 kHz. + Wideband = 1103, + /// 12 kHz. + SuperWideband = 1104, + /// 20 kHz. + Fullband = 1105, +} + /// The error type of this shim: a message, as the incumbent's was. #[derive(Debug, Clone)] pub struct OpusError(String); @@ -53,33 +84,57 @@ pub struct OpusEncoder { pub bitrate_bps: i32, /// Accepted for compatibility; this encoder has a single analysis path. pub complexity: i32, + /// Coded bandwidth; [`Bandwidth::Auto`] follows the bitrate. + pub bandwidth: Bandwidth, + /// Constrained VBR. Off by default, as the incumbent's was. + pub vbr: bool, inner: ec_opus::Encoder, channels: usize, + applied_bandwidth: Bandwidth, + applied_vbr: bool, } impl OpusEncoder { - /// An encoder at `sample_rate` (48000 only — the rate the product feeds) - /// for `channels` channels (1 or 2). + /// An encoder at `sample_rate` (8000, 12000, 16000, 24000 or 48000) for + /// `channels` channels (1 or 2). pub fn new( sample_rate: i32, channels: i32, - _application: Application, + application: Application, ) -> Result { if sample_rate < 0 || channels < 0 { return Err(OpusError(format!( "invalid encoder arguments: {sample_rate} Hz, {channels} channels" ))); } - let inner = ec_opus::Encoder::new(sample_rate as u32, channels as usize) - .map_err(|e| OpusError(e.to_string()))?; + let inner = + ec_opus::Encoder::new(sample_rate as u32, channels as usize, application.into()) + .map_err(|e| OpusError(e.to_string()))?; Ok(OpusEncoder { bitrate_bps: 64_000 * channels, complexity: 10, + bandwidth: Bandwidth::Auto, + vbr: false, inner, channels: channels as usize, + applied_bandwidth: Bandwidth::Auto, + applied_vbr: false, }) } + /// Samples of encoder delay, at the input rate: the decoded stream lags + /// the input by this much, and an Ogg-Opus pre-skip of it (scaled to + /// 48 kHz) cancels the lag exactly. + pub fn look_ahead(&self) -> usize { + self.inner.look_ahead() + } + + /// The range coder state after the last packet — the RFC 6716 Section 6 + /// conformance hook, which a conformant decoder reproduces exactly. + pub fn final_range(&self) -> u32 { + self.inner.final_range() + } + /// Encodes `frame_size` samples per channel of interleaved `f32` into /// `out`, returning the packet length in bytes. pub fn encode( @@ -95,16 +150,159 @@ impl OpusEncoder { self.channels ))); } - self.inner.set_bitrate(self.bitrate_bps.max(0) as u32); + self.sync_settings(); self.inner .encode_float(pcm, frame_size, out) .map_err(|e| OpusError(e.to_string())) } + /// [`OpusEncoder::encode`] from 16-bit samples. + pub fn encode_i16( + &mut self, + pcm: &[i16], + frame_size: usize, + out: &mut [u8], + ) -> Result { + if pcm.len() < frame_size * self.channels { + return Err(OpusError(format!( + "{} samples is short of {} channels x {frame_size}", + pcm.len(), + self.channels + ))); + } + self.sync_settings(); + self.inner + .encode(pcm, frame_size, out) + .map_err(|e| OpusError(e.to_string())) + } + /// Drops all inter-frame state; the next packet starts a fresh stream. pub fn reset(&mut self) { self.inner.reset(); } + + /// Pushes the public fields into the encoder before a frame. + fn sync_settings(&mut self) { + self.inner.set_bitrate(self.bitrate_bps.max(0) as u32); + if self.bandwidth != self.applied_bandwidth { + self.inner.set_bandwidth(match self.bandwidth { + Bandwidth::Auto => None, + Bandwidth::Narrowband => Some(ec_opus::Bandwidth::Narrow), + Bandwidth::Mediumband | Bandwidth::Wideband => Some(ec_opus::Bandwidth::Wide), + Bandwidth::SuperWideband => Some(ec_opus::Bandwidth::SuperWide), + Bandwidth::Fullband => Some(ec_opus::Bandwidth::Full), + }); + self.applied_bandwidth = self.bandwidth; + } + if self.vbr != self.applied_vbr { + self.inner.set_vbr_constrained(self.vbr); + self.applied_vbr = self.vbr; + } + } +} + +/// An Opus decoder, mono or stereo. +#[derive(Debug)] +pub struct OpusDecoder { + inner: ec_opus::Decoder, +} + +impl OpusDecoder { + /// A decoder for `channels` channels at `sample_rate` Hz. + pub fn new(sample_rate: i32, channels: i32) -> Result { + if sample_rate < 0 || channels < 0 { + return Err(OpusError(format!( + "invalid decoder arguments: {sample_rate} Hz, {channels} channels" + ))); + } + Ok(OpusDecoder { + inner: ec_opus::Decoder::new(sample_rate as u32, channels as usize) + .map_err(|e| OpusError(e.to_string()))?, + }) + } + + /// Decodes one packet into interleaved `f32`, returning samples per + /// channel. `frame_size` bounds the output, as the incumbent's did. + pub fn decode( + &mut self, + packet: &[u8], + frame_size: usize, + out: &mut [f32], + ) -> Result { + let _ = frame_size; + self.inner + .decode_float(packet, out) + .map_err(|e| OpusError(e.to_string())) + } + + /// The range coder state after the last packet. + pub fn final_range(&self) -> u32 { + self.inner.final_range() + } +} + +/// A multichannel encoder, for the 5.1 and 7.1 exports the incumbent could not +/// do at all — the replica's surround Opus path today is stereo only. +#[derive(Debug)] +pub struct MultistreamEncoder { + /// Target bitrate in bits per second, across all streams. + pub bitrate_bps: i32, + inner: ec_opus::MultistreamEncoder, + channels: usize, +} + +impl MultistreamEncoder { + /// An encoder for the RFC 7845 family-1 layout of `channels` channels (1 + /// to 8). Input is in the mapping's channel order, which for 5.1 is Vorbis + /// order: left, centre, right, back left, back right, LFE. + pub fn surround( + sample_rate: i32, + channels: usize, + application: Application, + ) -> Result { + if sample_rate < 0 { + return Err(OpusError(format!("invalid sample rate {sample_rate}"))); + } + let inner = + ec_opus::MultistreamEncoder::surround(sample_rate as u32, channels, application.into()) + .map_err(|e| OpusError(e.to_string()))?; + Ok(MultistreamEncoder { + bitrate_bps: 96_000 * channels as i32 / 2, + inner, + channels, + }) + } + + /// The channel mapping table the `OpusHead` for this encoder needs. + pub fn mapping(&self) -> &[u8] { + self.inner.layout().2 + } + + /// Elementary streams, and how many of them are coupled. + pub fn stream_counts(&self) -> (usize, usize) { + let (streams, coupled, _) = self.inner.layout(); + (streams, coupled) + } + + /// Encodes one frame of interleaved `f32`, returning the packet length. + pub fn encode( + &mut self, + pcm: &[f32], + frame_size: usize, + out: &mut [u8], + ) -> Result { + if pcm.len() < frame_size * self.channels { + return Err(OpusError(format!( + "{} samples is short of {} channels x {frame_size}", + pcm.len(), + self.channels + ))); + } + self.inner.set_bitrate(self.bitrate_bps.max(0) as u32); + self.inner + .encode_float(pcm, frame_size, out) + .map_err(|e| OpusError(e.to_string())) + } } #[cfg(test)] @@ -133,4 +331,112 @@ mod tests { let len = mono.encode(&frame, 960, &mut out).unwrap(); assert!(len > 2); } + + fn tone(n: usize, channels: usize) -> Vec { + (0..n * channels) + .map(|i| { + let t = (i / channels) as f32; + 0.5 * (t * 0.07).sin() + 0.25 * (t * 0.23).sin() + }) + .collect() + } + + /// The decoder half of the surface, and the conformance hook that says the + /// two agree: the decoder's range state must equal the encoder's after + /// every packet. + #[test] + fn the_shim_decodes_what_it_encodes_and_the_ranges_agree() { + const FRAME: usize = 960; + let mut enc = OpusEncoder::new(48_000, 2, Application::Audio).unwrap(); + enc.bitrate_bps = 256_000; + let mut dec = OpusDecoder::new(48_000, 2).unwrap(); + let pcm = tone(FRAME * 8, 2); + let mut out = vec![0u8; 1500]; + let mut back = vec![0.0f32; FRAME * 2]; + let mut total = 0; + for block in pcm.chunks_exact(FRAME * 2) { + let len = enc.encode(block, FRAME, &mut out).unwrap(); + assert!(len > 1 && len <= 1276, "packet of {len} bytes"); + total += len; + assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME); + assert_eq!(dec.final_range(), enc.final_range()); + } + // 256 kbps over 8 frames of 20 ms: the incumbent's 165 kbps ceiling is + // what this number exists to refute. + let want = 256_000 / 8 / 50 * 8; + assert!( + (total as f64 - want as f64).abs() < 0.2 * want as f64, + "{total} bytes vs {want} at 256 kbps" + ); + } + + /// Input below 48 kHz, which the shim used to refuse outright, and the + /// `look_ahead` that goes with it (120 samples at 48 kHz, scaled). + #[test] + fn slower_input_rates_encode_and_report_their_own_delay() { + for &(rate, frame, look) in &[ + (48_000i32, 960usize, 120usize), + (24_000, 480, 60), + (16_000, 320, 40), + (12_000, 240, 30), + (8_000, 160, 20), + ] { + let mut enc = OpusEncoder::new(rate, 1, Application::Voip).unwrap(); + enc.bitrate_bps = 32_000; + assert_eq!(enc.look_ahead(), look, "{rate} Hz look-ahead"); + let pcm = tone(frame * 4, 1); + let mut out = vec![0u8; 1500]; + // Everything a 48 kHz decoder gets back is 48 kHz, whatever went in. + let mut dec = OpusDecoder::new(48_000, 1).unwrap(); + let mut back = vec![0.0f32; 960]; + for block in pcm.chunks_exact(frame) { + let len = enc.encode(block, frame, &mut out).unwrap(); + assert!(len > 2, "{rate} Hz packet of {len} bytes"); + assert_eq!(dec.decode(&out[..len], 960, &mut back).unwrap(), 960); + assert_eq!(dec.final_range(), enc.final_range(), "{rate} Hz range"); + } + } + assert!(OpusEncoder::new(44_100, 2, Application::Audio).is_err()); + } + + /// A narrower band is a smaller top-band cost, not a refusal: forcing the + /// bandwidth must still produce packets a decoder reads. + #[test] + fn forced_bandwidth_and_i16_input_round_trip() { + const FRAME: usize = 960; + let mut enc = OpusEncoder::new(48_000, 1, Application::Audio).unwrap(); + enc.bitrate_bps = 64_000; + enc.bandwidth = Bandwidth::Wideband; + enc.vbr = true; + let pcm: Vec = tone(FRAME * 4, 1) + .iter() + .map(|v| (v * 16_000.0) as i16) + .collect(); + let mut out = vec![0u8; 1500]; + let mut dec = OpusDecoder::new(48_000, 1).unwrap(); + let mut back = vec![0.0f32; FRAME]; + for block in pcm.chunks_exact(FRAME) { + let len = enc.encode_i16(block, FRAME, &mut out).unwrap(); + // TOC config 20..23 is wideband CELT (RFC 6716 Table 2). + assert_eq!(out[0] >> 3, 23, "wideband CELT config"); + assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME); + assert_eq!(dec.final_range(), enc.final_range()); + } + } + + /// 5.1, which the incumbent could not encode at all. + #[test] + fn surround_encodes_five_one() { + const FRAME: usize = 960; + let mut e = MultistreamEncoder::surround(48_000, 6, Application::Audio).unwrap(); + e.bitrate_bps = 384_000; + assert_eq!(e.stream_counts(), (4, 2)); + assert_eq!(e.mapping(), &[0, 4, 1, 2, 3, 5]); + let pcm = tone(FRAME * 3, 6); + let mut out = vec![0u8; 8 * 1500]; + for block in pcm.chunks_exact(FRAME * 6) { + assert!(e.encode(block, FRAME, &mut out).unwrap() > 8); + } + assert!(MultistreamEncoder::surround(48_000, 9, Application::Audio).is_err()); + } }