Multi-rate input, application-driven bandwidth, whole shim surface
Browse files at this commit339a2eab7791b2b8b0e261b1de52fe2c187e33e8Parent: f935367- feat
- multi-rate input, application-driven bandwidth, whole shim surface
7 changed files +667 -80
- crates/ec-opus/src/celt_enc.rs +29 -12
- crates/ec-opus/src/encoder.rs +176 -29
- crates/ec-opus/src/lib.rs +2 -1
- crates/ec-opus/src/multistream_enc.rs +29 -3
- crates/ec-opus/src/ogg.rs +102 -0
- crates/ec-opus/tests/conformance.rs +15 -27
- shims/opus-rs/src/lib.rs +314 -8
crates/ec-opus/src/celt_enc.rsmodified+29 -12
| @@ -278,11 +278,13 @@ struct EncBand { | |||
| 278 | lm: i32, | 278 | lm: i32, |
| 279 | } | 279 | } |
| 280 | 280 | ||
| 281 | -/// A CELT-layer encoder for one elementary Opus stream (mono or stereo), | 281 | +/// A CELT-layer encoder for one elementary Opus stream (mono or stereo). |
| 282 | -/// fullband at 48 kHz. | 282 | +/// CELT itself always runs at 48 kHz; slower input is zero-stuffed up to it. |
| 283 | #[derive(Clone, Debug)] | 283 | #[derive(Clone, Debug)] |
| 284 | pub struct CeltEncoder { | 284 | pub struct CeltEncoder { |
| 285 | channels: usize, | 285 | channels: usize, |
| 286 | + /// 48000 / input rate, 1 for native 48 kHz input. | ||
| 287 | + upsample: usize, | ||
| 286 | window: Vec<f32>, | 288 | window: Vec<f32>, |
| 287 | plans: Vec<MdctPlan>, | 289 | plans: Vec<MdctPlan>, |
| 288 | /// Preemphasised history, `channels * OVERLAP`. | 290 | /// Preemphasised history, `channels * OVERLAP`. |
| @@ -321,12 +323,14 @@ pub struct CeltEncoder { | |||
| 321 | } | 323 | } |
| 322 | 324 | ||
| 323 | impl CeltEncoder { | 325 | impl CeltEncoder { |
| 324 | - /// An encoder for `channels` channels (1 or 2) at 48 kHz. | 326 | + /// An encoder for `channels` channels (1 or 2) fed at `48000/upsample` Hz. |
| 325 | - pub fn new(channels: usize) -> CeltEncoder { | 327 | + pub fn new(channels: usize, upsample: usize) -> CeltEncoder { |
| 326 | assert!((1..=2).contains(&channels)); | 328 | assert!((1..=2).contains(&channels)); |
| 329 | + assert!(upsample >= 1); | ||
| 327 | let max_n = SHORT_MDCT * 8; | 330 | let max_n = SHORT_MDCT * 8; |
| 328 | CeltEncoder { | 331 | CeltEncoder { |
| 329 | channels, | 332 | channels, |
| 333 | + upsample, | ||
| 330 | window: celt::overlap_window(), | 334 | window: celt::overlap_window(), |
| 331 | plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(), | 335 | plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(), |
| 332 | in_mem: vec![0.0; channels * OVERLAP], | 336 | in_mem: vec![0.0; channels * OVERLAP], |
| @@ -382,8 +386,10 @@ impl CeltEncoder { | |||
| 382 | } | 386 | } |
| 383 | 387 | ||
| 384 | /// Encodes one frame of interleaved `f32` (`frame_size` samples per | 388 | /// Encodes one frame of interleaved `f32` (`frame_size` samples per |
| 385 | - /// channel at 48 kHz, `frame_size` one of 120/240/480/960) into `enc`, | 389 | + /// channel at 48 kHz, one of 120/240/480/960 — of which |
| 386 | - /// which must have been `reset` to the frame's byte budget. With | 390 | + /// `frame_size/upsample` are read from `pcm`) into `enc`, which must have |
| 391 | + /// been `reset` to the frame's byte budget. `end` bounds the coded bands, | ||
| 392 | + /// which is how the caller limits the coded bandwidth. With | ||
| 387 | /// `vbr_rate_bps` set, the frame may be shrunk below that budget | 393 | /// `vbr_rate_bps` set, the frame may be shrunk below that budget |
| 388 | /// (constrained VBR); the return value is the final frame size in bytes. | 394 | /// (constrained VBR); the return value is the final frame size in bytes. |
| 389 | pub fn encode( | 395 | pub fn encode( |
| @@ -391,6 +397,7 @@ impl CeltEncoder { | |||
| 391 | enc: &mut RangeEncoder, | 397 | enc: &mut RangeEncoder, |
| 392 | pcm: &[f32], | 398 | pcm: &[f32], |
| 393 | frame_size: usize, | 399 | frame_size: usize, |
| 400 | + end: usize, | ||
| 394 | vbr_rate_bps: u32, | 401 | vbr_rate_bps: u32, |
| 395 | ) -> Result<usize> { | 402 | ) -> Result<usize> { |
| 396 | let lm: usize = match frame_size { | 403 | let lm: usize = match frame_size { |
| @@ -408,14 +415,14 @@ impl CeltEncoder { | |||
| 408 | let m = 1usize << lm; | 415 | let m = 1usize << lm; |
| 409 | let n = frame_size; | 416 | let n = frame_size; |
| 410 | let c = self.channels; | 417 | let c = self.channels; |
| 411 | - if pcm.len() < n * c { | 418 | + let in_n = n / self.upsample; |
| 419 | + if pcm.len() < in_n * c { | ||
| 412 | return Err(Error::corrupt(format!( | 420 | return Err(Error::corrupt(format!( |
| 413 | - "celt encode: {} samples for a {}-channel {frame_size}-sample frame", | 421 | + "celt encode: {} samples for a {c}-channel {in_n}-sample frame", |
| 414 | - pcm.len(), | 422 | + pcm.len() |
| 415 | - c | ||
| 416 | ))); | 423 | ))); |
| 417 | } | 424 | } |
| 418 | - let (start, end) = (0usize, NB_BANDS); | 425 | + let (start, end) = (0usize, end.clamp(1, NB_BANDS)); |
| 419 | 426 | ||
| 420 | let mut nb_compressed = enc.storage(); | 427 | let mut nb_compressed = enc.storage(); |
| 421 | let mut nb_available = nb_compressed as i32; | 428 | let mut nb_available = nb_compressed as i32; |
| @@ -451,8 +458,18 @@ impl CeltEncoder { | |||
| 451 | self.in_buf[base..base + OVERLAP] | 458 | self.in_buf[base..base + OVERLAP] |
| 452 | .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]); | 459 | .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]); |
| 453 | let mut mem = self.preemph_mem[ch]; | 460 | let mut mem = self.preemph_mem[ch]; |
| 461 | + let up = self.upsample; | ||
| 454 | for i in 0..n { | 462 | for i in 0..n { |
| 455 | - let mut x = pcm[i * c + ch] * SIG_SCALE; | 463 | + // Zero-stuffing to 48 kHz: the images above the input's own |
| 464 | + // Nyquist are never coded (the caller caps `end`) and the | ||
| 465 | + // decoder's decimation drops them. | ||
| 466 | + let mut x = if up == 1 { | ||
| 467 | + pcm[i * c + ch] * SIG_SCALE | ||
| 468 | + } else if i.is_multiple_of(up) { | ||
| 469 | + pcm[(i / up) * c + ch] * SIG_SCALE * up as f32 | ||
| 470 | + } else { | ||
| 471 | + 0.0 | ||
| 472 | + }; | ||
| 456 | if !x.is_finite() { | 473 | if !x.is_finite() { |
| 457 | x = 0.0; | 474 | x = 0.0; |
| 458 | } | 475 | } |
crates/ec-opus/src/encoder.rsmodified+176 -29
| @@ -1,11 +1,16 @@ | |||
| 1 | -//! The Opus packet encoder: CELT-only, fullband, 48 kHz. | 1 | +//! The Opus packet encoder: CELT-only, 8 to 48 kHz in. |
| 2 | //! | 2 | //! |
| 3 | //! One [`Encoder`] produces ordinary code-0 Opus packets (RFC 6716 Section 3) | 3 | //! One [`Encoder`] produces ordinary code-0 Opus packets (RFC 6716 Section 3) |
| 4 | //! or the self-delimited variant of Appendix B that the multistream framing | 4 | //! or the self-delimited variant of Appendix B that the multistream framing |
| 5 | -//! needs. Every configuration this encoder emits is a fullband CELT one | 5 | +//! needs. Every configuration this encoder emits is a CELT one (TOC configs |
| 6 | -//! (TOC configs 28..31), which is what music encoding uses at every rate the | 6 | +//! 16..31), which is what music encoding uses at every rate the product asks |
| 7 | -//! product asks for; there is no SILK and no hybrid path — a speech-optimised | 7 | +//! for; there is no SILK and no hybrid path — a speech-optimised mode below |
| 8 | -//! mode below 16 kbps is out of scope, not silently approximated. | 8 | +//! 16 kbps is out of scope, not silently approximated. |
| 9 | +//! | ||
| 10 | +//! Input below 48 kHz is zero-stuffed to CELT's native rate and the coded | ||
| 11 | +//! bandwidth is capped at the input's own Nyquist, so the images the stuffing | ||
| 12 | +//! puts there are never coded and the decoder's decimation drops them. | ||
| 13 | +//! [`Encoder::look_ahead`] reports the delay in *input* samples. | ||
| 9 | //! | 14 | //! |
| 10 | //! Rate control is CBR by default — every packet the same size, derived from | 15 | //! Rate control is CBR by default — every packet the same size, derived from |
| 11 | //! the bitrate — or constrained VBR, the reference's reservoir scheme, when | 16 | //! the bitrate — or constrained VBR, the reference's reservoir scheme, when |
| @@ -14,34 +19,60 @@ | |||
| 14 | use ec_core::{Error, Result}; | 19 | use ec_core::{Error, Result}; |
| 15 | 20 | ||
| 16 | use crate::celt_enc::CeltEncoder; | 21 | use crate::celt_enc::CeltEncoder; |
| 22 | +use crate::packet::Bandwidth; | ||
| 17 | use crate::range::RangeEncoder; | 23 | use crate::range::RangeEncoder; |
| 18 | 24 | ||
| 19 | /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`). | 25 | /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`). |
| 20 | const MAX_FRAME_BYTES: usize = 1275; | 26 | const MAX_FRAME_BYTES: usize = 1275; |
| 21 | 27 | ||
| 22 | -/// One elementary Opus encoder: mono or stereo, CELT-only, 48 kHz in. | 28 | +/// What the caller is encoding. This encoder is CELT-only, so the setting |
| 29 | +/// biases the coded bandwidth rather than selecting a different layer. | ||
| 30 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 31 | +pub enum Application { | ||
| 32 | + /// Speech: one step narrower at a given rate, where the top octave costs | ||
| 33 | + /// most and carries least. | ||
| 34 | + Voip, | ||
| 35 | + /// Music and general audio, the default. | ||
| 36 | + Audio, | ||
| 37 | + /// Lowest delay. | ||
| 38 | + LowDelay, | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/// One elementary Opus encoder: mono or stereo, CELT-only. | ||
| 23 | #[derive(Clone, Debug)] | 42 | #[derive(Clone, Debug)] |
| 24 | pub struct Encoder { | 43 | pub struct Encoder { |
| 25 | celt: CeltEncoder, | 44 | celt: CeltEncoder, |
| 26 | range: RangeEncoder, | 45 | range: RangeEncoder, |
| 46 | + sample_rate: u32, | ||
| 47 | + /// 48000 / `sample_rate`: the zero-stuffing factor into CELT. | ||
| 48 | + upsample: usize, | ||
| 27 | channels: usize, | 49 | channels: usize, |
| 28 | bitrate: u32, | 50 | bitrate: u32, |
| 29 | vbr: bool, | 51 | vbr: bool, |
| 52 | + application: Application, | ||
| 53 | + bandwidth: Option<Bandwidth>, | ||
| 30 | final_range: u32, | 54 | final_range: u32, |
| 31 | } | 55 | } |
| 32 | 56 | ||
| 33 | impl Encoder { | 57 | impl Encoder { |
| 34 | /// An encoder for `channels` channels (1 or 2) at `sample_rate`, which | 58 | /// An encoder for `channels` channels (1 or 2) at `sample_rate`, which |
| 35 | - /// must be 48000 — CELT's native rate, and the only rate the product | 59 | + /// must be one of 8000, 12000, 16000, 24000 or 48000 Hz — the rates |
| 36 | - /// feeds it (RFC 7845 Section 5.1: every Opus decoder runs at 48 kHz | 60 | + /// RFC 6716 Section 2 admits. CELT itself runs at 48 kHz whatever the |
| 37 | - /// regardless of what the container claims). | 61 | + /// input rate is (RFC 7845 Section 5.1). |
| 38 | - pub fn new(sample_rate: u32, channels: usize) -> Result<Encoder> { | 62 | + pub fn new(sample_rate: u32, channels: usize, application: Application) -> Result<Encoder> { |
| 39 | - if sample_rate != 48000 { | 63 | + let upsample = match sample_rate { |
| 64 | + 48000 => 1, | ||
| 65 | + 24000 => 2, | ||
| 66 | + 16000 => 3, | ||
| 67 | + 12000 => 4, | ||
| 68 | + 8000 => 6, | ||
| 69 | + _ => { | ||
| 40 | return Err(Error::unsupported( | 70 | return Err(Error::unsupported( |
| 41 | format!("opus encode at {sample_rate} Hz"), | 71 | format!("opus encode at {sample_rate} Hz"), |
| 42 | - "this CELT-only encoder takes 48 kHz input; resample first", | 72 | + "Opus encodes from 8, 12, 16, 24 or 48 kHz; resample first", |
| 43 | )); | 73 | )); |
| 44 | } | 74 | } |
| 75 | + }; | ||
| 45 | if !(1..=2).contains(&channels) { | 76 | if !(1..=2).contains(&channels) { |
| 46 | return Err(Error::unsupported( | 77 | return Err(Error::unsupported( |
| 47 | format!("{channels}-channel Opus stream"), | 78 | format!("{channels}-channel Opus stream"), |
| @@ -49,11 +80,15 @@ impl Encoder { | |||
| 49 | )); | 80 | )); |
| 50 | } | 81 | } |
| 51 | Ok(Encoder { | 82 | Ok(Encoder { |
| 52 | - celt: CeltEncoder::new(channels), | 83 | + celt: CeltEncoder::new(channels, upsample), |
| 53 | range: RangeEncoder::new(), | 84 | range: RangeEncoder::new(), |
| 85 | + sample_rate, | ||
| 86 | + upsample, | ||
| 54 | channels, | 87 | channels, |
| 55 | bitrate: 64_000 * channels as u32, | 88 | bitrate: 64_000 * channels as u32, |
| 56 | vbr: false, | 89 | vbr: false, |
| 90 | + application, | ||
| 91 | + bandwidth: None, | ||
| 57 | final_range: 0, | 92 | final_range: 0, |
| 58 | }) | 93 | }) |
| 59 | } | 94 | } |
| @@ -63,6 +98,24 @@ impl Encoder { | |||
| 63 | self.channels | 98 | self.channels |
| 64 | } | 99 | } |
| 65 | 100 | ||
| 101 | + /// The rate the caller feeds. | ||
| 102 | + pub fn sample_rate(&self) -> u32 { | ||
| 103 | + self.sample_rate | ||
| 104 | + } | ||
| 105 | + | ||
| 106 | + /// Encoder delay in *input* samples: the decoded stream lags the input by | ||
| 107 | + /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate` | ||
| 108 | + /// cancels it exactly. One MDCT overlap, 120 samples at 48 kHz. | ||
| 109 | + pub fn look_ahead(&self) -> usize { | ||
| 110 | + 120 / self.upsample | ||
| 111 | + } | ||
| 112 | + | ||
| 113 | + /// Forces the coded bandwidth; [`None`] (the default) picks it from the | ||
| 114 | + /// bitrate, the application and the input's Nyquist. | ||
| 115 | + pub fn set_bandwidth(&mut self, bandwidth: Option<Bandwidth>) { | ||
| 116 | + self.bandwidth = bandwidth; | ||
| 117 | + } | ||
| 118 | + | ||
| 66 | /// Target bitrate in bits per second for the whole packet stream, | 119 | /// Target bitrate in bits per second for the whole packet stream, |
| 67 | /// including the packet headers. Clamped to 500..=510000. | 120 | /// including the packet headers. Clamped to 500..=510000. |
| 68 | pub fn set_bitrate(&mut self, bps: u32) { | 121 | pub fn set_bitrate(&mut self, bps: u32) { |
| @@ -94,34 +147,87 @@ impl Encoder { | |||
| 94 | self.final_range = 0; | 147 | self.final_range = 0; |
| 95 | } | 148 | } |
| 96 | 149 | ||
| 97 | - fn toc(&self, frame_size: usize) -> Result<u8> { | 150 | + /// The TOC byte, the frame size in 48 kHz samples and the CELT end band |
| 98 | - let fs_idx: u8 = match frame_size { | 151 | + /// for a frame of `frame_size` input samples per channel. |
| 152 | + fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> { | ||
| 153 | + let frame_48k = frame_size * self.upsample; | ||
| 154 | + let fs_idx: u8 = match frame_48k { | ||
| 99 | 120 => 0, | 155 | 120 => 0, |
| 100 | 240 => 1, | 156 | 240 => 1, |
| 101 | 480 => 2, | 157 | 480 => 2, |
| 102 | 960 => 3, | 158 | 960 => 3, |
| 103 | _ => { | 159 | _ => { |
| 104 | return Err(Error::unsupported( | 160 | return Err(Error::unsupported( |
| 105 | - format!("opus frame of {frame_size} samples"), | 161 | + format!( |
| 106 | - "CELT frames are 120, 240, 480 or 960 samples at 48 kHz", | 162 | + "opus frame of {frame_size} samples at {} Hz", |
| 163 | + self.sample_rate | ||
| 164 | + ), | ||
| 165 | + "CELT frames are 2.5, 5, 10 or 20 ms", | ||
| 107 | )); | 166 | )); |
| 108 | } | 167 | } |
| 109 | }; | 168 | }; |
| 110 | - let config = 28 + fs_idx; // fullband CELT | 169 | + let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth()); |
| 111 | - Ok((config << 3) | (u8::from(self.channels == 2) << 2)) | 170 | + let bw_idx: u8 = match bandwidth { |
| 171 | + Bandwidth::Narrow => 0, | ||
| 172 | + // CELT has no mediumband configuration; the next one up covers it. | ||
| 173 | + Bandwidth::Medium | Bandwidth::Wide => 1, | ||
| 174 | + Bandwidth::SuperWide => 2, | ||
| 175 | + Bandwidth::Full => 3, | ||
| 176 | + }; | ||
| 177 | + let config = 16 + 4 * bw_idx + fs_idx; | ||
| 178 | + Ok(( | ||
| 179 | + (config << 3) | (u8::from(self.channels == 2) << 2), | ||
| 180 | + frame_48k, | ||
| 181 | + bandwidth.celt_end_band(), | ||
| 182 | + )) | ||
| 183 | + } | ||
| 184 | + | ||
| 185 | + /// Bandwidth from the bitrate: coding 20 kHz at 24 kbps spends bits on air. | ||
| 186 | + /// | ||
| 187 | + /// The thresholds are on the mono-equivalent rate — a coupled stereo stream | ||
| 188 | + /// needs about 1.6x a mono one for the same per-channel quality — and VoIP | ||
| 189 | + /// asks for one step narrower. The input's own Nyquist bounds the result: | ||
| 190 | + /// coding above it would code the images the zero-stuffing put there. | ||
| 191 | + fn auto_bandwidth(&self) -> Bandwidth { | ||
| 192 | + let equiv = if self.channels == 2 { | ||
| 193 | + (self.bitrate as f32 * 0.62) as u32 | ||
| 194 | + } else { | ||
| 195 | + self.bitrate | ||
| 196 | + }; | ||
| 197 | + let equiv = if self.application == Application::Voip { | ||
| 198 | + (equiv as f32 * 0.7) as u32 | ||
| 199 | + } else { | ||
| 200 | + equiv | ||
| 201 | + }; | ||
| 202 | + let ceiling = match self.sample_rate { | ||
| 203 | + 48000 => Bandwidth::Full, | ||
| 204 | + 24000 => Bandwidth::SuperWide, | ||
| 205 | + 16000 => Bandwidth::Wide, | ||
| 206 | + _ => Bandwidth::Narrow, | ||
| 207 | + }; | ||
| 208 | + let wanted = if equiv < 9000 { | ||
| 209 | + Bandwidth::Narrow | ||
| 210 | + } else if equiv < 13000 { | ||
| 211 | + Bandwidth::Wide | ||
| 212 | + } else if equiv < 20000 { | ||
| 213 | + Bandwidth::SuperWide | ||
| 214 | + } else { | ||
| 215 | + Bandwidth::Full | ||
| 216 | + }; | ||
| 217 | + wanted.min(ceiling) | ||
| 112 | } | 218 | } |
| 113 | 219 | ||
| 114 | /// Encodes one frame — `frame_size` samples per channel of interleaved | 220 | /// Encodes one frame — `frame_size` samples per channel of interleaved |
| 115 | - /// `f32` at 48 kHz, `frame_size` one of 120/240/480/960 — as a code-0 | 221 | + /// `f32` at the input rate, 2.5, 5, 10 or 20 ms of it — as a code-0 Opus |
| 116 | - /// Opus packet in `out`, returning the packet length. | 222 | + /// packet in `out`, returning the packet length. |
| 117 | pub fn encode_float( | 223 | pub fn encode_float( |
| 118 | &mut self, | 224 | &mut self, |
| 119 | pcm: &[f32], | 225 | pcm: &[f32], |
| 120 | frame_size: usize, | 226 | frame_size: usize, |
| 121 | out: &mut [u8], | 227 | out: &mut [u8], |
| 122 | ) -> Result<usize> { | 228 | ) -> Result<usize> { |
| 123 | - let toc = self.toc(frame_size)?; | 229 | + let (toc, frame_48k, end) = self.toc(frame_size)?; |
| 124 | - let n = self.encode_frame(pcm, frame_size, out.len().saturating_sub(1))?; | 230 | + let n = self.encode_frame(pcm, frame_48k, end, out.len().saturating_sub(1))?; |
| 125 | if out.len() < 1 + n { | 231 | if out.len() < 1 + n { |
| 126 | return Err(Error::corrupt(format!( | 232 | return Err(Error::corrupt(format!( |
| 127 | "opus encode: packet needs {} bytes, buffer holds {}", | 233 | "opus encode: packet needs {} bytes, buffer holds {}", |
| @@ -134,6 +240,12 @@ impl Encoder { | |||
| 134 | Ok(1 + n) | 240 | Ok(1 + n) |
| 135 | } | 241 | } |
| 136 | 242 | ||
| 243 | + /// [`Encoder::encode_float`] from 16-bit samples. | ||
| 244 | + pub fn encode(&mut self, pcm: &[i16], frame_size: usize, out: &mut [u8]) -> Result<usize> { | ||
| 245 | + let float: Vec<f32> = pcm.iter().map(|&v| v as f32 * (1.0 / 32768.0)).collect(); | ||
| 246 | + self.encode_float(&float, frame_size, out) | ||
| 247 | + } | ||
| 248 | + | ||
| 137 | /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716 | 249 | /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716 |
| 138 | /// Appendix B: TOC, an explicit frame length, then the frame. This is | 250 | /// Appendix B: TOC, an explicit frame length, then the frame. This is |
| 139 | /// what every stream but the last uses inside a multistream packet. | 251 | /// what every stream but the last uses inside a multistream packet. |
| @@ -143,8 +255,8 @@ impl Encoder { | |||
| 143 | frame_size: usize, | 255 | frame_size: usize, |
| 144 | out: &mut [u8], | 256 | out: &mut [u8], |
| 145 | ) -> Result<usize> { | 257 | ) -> Result<usize> { |
| 146 | - let toc = self.toc(frame_size)?; | 258 | + let (toc, frame_48k, end) = self.toc(frame_size)?; |
| 147 | - let n = self.encode_frame(pcm, frame_size, out.len().saturating_sub(3))?; | 259 | + let n = self.encode_frame(pcm, frame_48k, end, out.len().saturating_sub(3))?; |
| 148 | let len_bytes = if n < 252 { 1 } else { 2 }; | 260 | let len_bytes = if n < 252 { 1 } else { 2 }; |
| 149 | if out.len() < 1 + len_bytes + n { | 261 | if out.len() < 1 + len_bytes + n { |
| 150 | return Err(Error::corrupt(format!( | 262 | return Err(Error::corrupt(format!( |
| @@ -166,9 +278,15 @@ impl Encoder { | |||
| 166 | } | 278 | } |
| 167 | 279 | ||
| 168 | /// Encodes the CELT frame into the internal range coder and returns its | 280 | /// Encodes the CELT frame into the internal range coder and returns its |
| 169 | - /// byte length. `cap` bounds the frame (the caller's buffer minus | 281 | + /// byte length. `frame_size` is in 48 kHz samples, `end` is the last coded |
| 170 | - /// headers). | 282 | + /// band, and `cap` bounds the frame (the caller's buffer minus headers). |
| 171 | - fn encode_frame(&mut self, pcm: &[f32], frame_size: usize, cap: usize) -> Result<usize> { | 283 | + fn encode_frame( |
| 284 | + &mut self, | ||
| 285 | + pcm: &[f32], | ||
| 286 | + frame_size: usize, | ||
| 287 | + end: usize, | ||
| 288 | + cap: usize, | ||
| 289 | + ) -> Result<usize> { | ||
| 172 | let cap = cap.min(MAX_FRAME_BYTES); | 290 | let cap = cap.min(MAX_FRAME_BYTES); |
| 173 | if cap < 2 { | 291 | if cap < 2 { |
| 174 | return Err(Error::corrupt( | 292 | return Err(Error::corrupt( |
| @@ -186,8 +304,37 @@ impl Encoder { | |||
| 186 | self.range.reset(budget); | 304 | self.range.reset(budget); |
| 187 | let n = self | 305 | let n = self |
| 188 | .celt | 306 | .celt |
| 189 | - .encode(&mut self.range, pcm, frame_size, vbr_rate)?; | 307 | + .encode(&mut self.range, pcm, frame_size, end, vbr_rate)?; |
| 190 | self.final_range = self.range.range(); | 308 | self.final_range = self.range.range(); |
| 191 | Ok(n) | 309 | Ok(n) |
| 192 | } | 310 | } |
| 193 | } | 311 | } |
| 312 | + | ||
| 313 | +#[cfg(test)] | ||
| 314 | +mod tests { | ||
| 315 | + use super::*; | ||
| 316 | + | ||
| 317 | + /// The private half of the bandwidth decision: the thresholds themselves, | ||
| 318 | + /// which the TOC config only reports. | ||
| 319 | + #[test] | ||
| 320 | + fn bandwidth_follows_the_bitrate_the_application_and_the_input_rate() { | ||
| 321 | + let mut e = Encoder::new(48000, 1, Application::Audio).unwrap(); | ||
| 322 | + e.set_bitrate(64000); | ||
| 323 | + assert_eq!(e.auto_bandwidth(), Bandwidth::Full); | ||
| 324 | + e.set_bitrate(16000); | ||
| 325 | + assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide); | ||
| 326 | + e.set_bitrate(10000); | ||
| 327 | + assert_eq!(e.auto_bandwidth(), Bandwidth::Wide); | ||
| 328 | + e.set_bitrate(8000); | ||
| 329 | + assert_eq!(e.auto_bandwidth(), Bandwidth::Narrow); | ||
| 330 | + // Speech asks for one step narrower at the same rate. | ||
| 331 | + let mut v = Encoder::new(48000, 1, Application::Voip).unwrap(); | ||
| 332 | + v.set_bitrate(16000); | ||
| 333 | + assert_eq!(v.auto_bandwidth(), Bandwidth::Wide); | ||
| 334 | + // The input's own Nyquist bounds it whatever the rate says. | ||
| 335 | + let mut e = Encoder::new(24000, 2, Application::Audio).unwrap(); | ||
| 336 | + e.set_bitrate(256_000); | ||
| 337 | + assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide); | ||
| 338 | + assert_eq!(e.look_ahead(), 60); | ||
| 339 | + } | ||
| 340 | +} | ||
crates/ec-opus/src/lib.rsmodified+2 -1
| @@ -66,13 +66,14 @@ pub mod celt_enc; | |||
| 66 | pub mod encoder; | 66 | pub mod encoder; |
| 67 | pub mod multistream; | 67 | pub mod multistream; |
| 68 | pub mod multistream_enc; | 68 | pub mod multistream_enc; |
| 69 | +pub mod ogg; | ||
| 69 | pub mod packet; | 70 | pub mod packet; |
| 70 | pub mod range; | 71 | pub mod range; |
| 71 | pub mod silk; | 72 | pub mod silk; |
| 72 | 73 | ||
| 73 | pub use celt::CeltDecoder; | 74 | pub use celt::CeltDecoder; |
| 74 | pub use celt_enc::CeltEncoder; | 75 | pub use celt_enc::CeltEncoder; |
| 75 | -pub use encoder::Encoder; | 76 | +pub use encoder::{Application, Encoder}; |
| 76 | pub use multistream::MultistreamDecoder; | 77 | pub use multistream::MultistreamDecoder; |
| 77 | pub use multistream_enc::MultistreamEncoder; | 78 | pub use multistream_enc::MultistreamEncoder; |
| 78 | pub use packet::{Bandwidth, Mode, Packet, Toc}; | 79 | pub use packet::{Bandwidth, Mode, Packet, Toc}; |
crates/ec-opus/src/multistream_enc.rsmodified+29 -3
| @@ -13,7 +13,7 @@ | |||
| 13 | 13 | ||
| 14 | use ec_core::{Error, Result}; | 14 | use ec_core::{Error, Result}; |
| 15 | 15 | ||
| 16 | -use crate::encoder::Encoder; | 16 | +use crate::encoder::{Application, Encoder}; |
| 17 | 17 | ||
| 18 | /// A multichannel Opus encoder, mono through 255 channels. | 18 | /// A multichannel Opus encoder, mono through 255 channels. |
| 19 | #[derive(Debug)] | 19 | #[derive(Debug)] |
| @@ -36,6 +36,7 @@ impl MultistreamEncoder { | |||
| 36 | streams: usize, | 36 | streams: usize, |
| 37 | coupled: usize, | 37 | coupled: usize, |
| 38 | mapping: &[u8], | 38 | mapping: &[u8], |
| 39 | + application: Application, | ||
| 39 | ) -> Result<MultistreamEncoder> { | 40 | ) -> Result<MultistreamEncoder> { |
| 40 | if streams == 0 || streams > 255 || coupled > streams { | 41 | if streams == 0 || streams > 255 || coupled > streams { |
| 41 | return Err(Error::corrupt(format!( | 42 | return Err(Error::corrupt(format!( |
| @@ -57,7 +58,7 @@ impl MultistreamEncoder { | |||
| 57 | let mut encoders = Vec::with_capacity(streams); | 58 | let mut encoders = Vec::with_capacity(streams); |
| 58 | for s in 0..streams { | 59 | for s in 0..streams { |
| 59 | let ch = if s < coupled { 2 } else { 1 }; | 60 | let ch = if s < coupled { 2 } else { 1 }; |
| 60 | - encoders.push(Encoder::new(sample_rate, ch)?); | 61 | + encoders.push(Encoder::new(sample_rate, ch, application)?); |
| 61 | } | 62 | } |
| 62 | Ok(MultistreamEncoder { | 63 | Ok(MultistreamEncoder { |
| 63 | streams: encoders, | 64 | streams: encoders, |
| @@ -68,10 +69,35 @@ impl MultistreamEncoder { | |||
| 68 | }) | 69 | }) |
| 69 | } | 70 | } |
| 70 | 71 | ||
| 72 | + /// The RFC 7845 Section 5.1.1.2 default layout for `channels` channels | ||
| 73 | + /// (1 to 8), which for 5.1 is four streams, two coupled, in Vorbis channel | ||
| 74 | + /// order (FL, FC, FR, BL, BR, LFE) — see [`crate::ogg::default_mapping`] | ||
| 75 | + /// for the permutation a film-order caller applies on the way in. | ||
| 76 | + pub fn surround( | ||
| 77 | + sample_rate: u32, | ||
| 78 | + channels: usize, | ||
| 79 | + application: Application, | ||
| 80 | + ) -> Result<MultistreamEncoder> { | ||
| 81 | + let (_family, streams, coupled, table) = | ||
| 82 | + crate::ogg::default_mapping(channels).ok_or_else(|| { | ||
| 83 | + Error::unsupported( | ||
| 84 | + format!("{channels}-channel Opus stream"), | ||
| 85 | + "RFC 7845 maps 1 to 8 channels", | ||
| 86 | + ) | ||
| 87 | + })?; | ||
| 88 | + MultistreamEncoder::new( | ||
| 89 | + sample_rate, | ||
| 90 | + streams as usize, | ||
| 91 | + coupled as usize, | ||
| 92 | + &table, | ||
| 93 | + application, | ||
| 94 | + ) | ||
| 95 | + } | ||
| 96 | + | ||
| 71 | /// The RFC 7845 mapping-family-1 layout for 5.1: four streams, two | 97 | /// The RFC 7845 mapping-family-1 layout for 5.1: four streams, two |
| 72 | /// coupled, Vorbis channel order (FL, FC, FR, BL, BR, LFE). | 98 | /// coupled, Vorbis channel order (FL, FC, FR, BL, BR, LFE). |
| 73 | pub fn surround_5_1(sample_rate: u32) -> Result<MultistreamEncoder> { | 99 | pub fn surround_5_1(sample_rate: u32) -> Result<MultistreamEncoder> { |
| 74 | - MultistreamEncoder::new(sample_rate, 4, 2, &[0, 4, 1, 2, 3, 5]) | 100 | + MultistreamEncoder::surround(sample_rate, 6, Application::Audio) |
| 75 | } | 101 | } |
| 76 | 102 | ||
| 77 | /// Input channels per frame. | 103 | /// Input channels per frame. |
crates/ec-opus/src/ogg.rsadded+102 -0
| @@ -0,0 +1,102 @@ | |||
| 1 | +//! The Ogg-Opus header packets, RFC 7845. | ||
| 2 | +//! | ||
| 3 | +//! Only the two headers and the channel-mapping table live here; the pages | ||
| 4 | +//! themselves are `ec-ogg`'s job. Keeping the mapping in this crate is what | ||
| 5 | +//! lets an encoder and a muxer agree without either depending on the other. | ||
| 6 | +//! | ||
| 7 | +//! Two numbers a caller must not invent: | ||
| 8 | +//! | ||
| 9 | +//! - **pre-skip** is the encoder's delay in 48 kHz samples | ||
| 10 | +//! ([`crate::Encoder::look_ahead`] scaled to 48 kHz — 120 for this encoder). | ||
| 11 | +//! A player discards that many samples, which is exactly what cancels the | ||
| 12 | +//! delay; getting it wrong shifts the whole stream. | ||
| 13 | +//! - **granule position** counts 48 kHz samples *including* the pre-skip, so | ||
| 14 | +//! the first page's granule is `samples_encoded` and the file's duration is | ||
| 15 | +//! `last_granule - pre_skip`. | ||
| 16 | + | ||
| 17 | +/// Builds an `OpusHead` packet (RFC 7845, Section 5.1). | ||
| 18 | +/// | ||
| 19 | +/// `input_rate` is the rate the samples arrived at, informational only — | ||
| 20 | +/// the granule clock is always 48 kHz. `mapping` is `(family, streams, | ||
| 21 | +/// coupled, table)`; [`None`] writes family 0, which is mono or stereo. | ||
| 22 | +pub fn opus_head( | ||
| 23 | + channels: u8, | ||
| 24 | + pre_skip: u16, | ||
| 25 | + input_rate: u32, | ||
| 26 | + output_gain_q8: i16, | ||
| 27 | + mapping: Option<(u8, u8, u8, &[u8])>, | ||
| 28 | +) -> Vec<u8> { | ||
| 29 | + let mut v = Vec::with_capacity(21 + channels as usize); | ||
| 30 | + v.extend_from_slice(b"OpusHead"); | ||
| 31 | + v.push(1); | ||
| 32 | + v.push(channels); | ||
| 33 | + v.extend_from_slice(&pre_skip.to_le_bytes()); | ||
| 34 | + v.extend_from_slice(&input_rate.to_le_bytes()); | ||
| 35 | + v.extend_from_slice(&output_gain_q8.to_le_bytes()); | ||
| 36 | + match mapping { | ||
| 37 | + None => v.push(0), | ||
| 38 | + Some((family, streams, coupled, table)) => { | ||
| 39 | + v.push(family); | ||
| 40 | + v.push(streams); | ||
| 41 | + v.push(coupled); | ||
| 42 | + v.extend_from_slice(table); | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | + v | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// Builds an `OpusTags` packet with a vendor string and no comments. | ||
| 49 | +pub fn opus_tags(vendor: &str) -> Vec<u8> { | ||
| 50 | + let mut v = Vec::with_capacity(16 + vendor.len()); | ||
| 51 | + v.extend_from_slice(b"OpusTags"); | ||
| 52 | + v.extend_from_slice(&(vendor.len() as u32).to_le_bytes()); | ||
| 53 | + v.extend_from_slice(vendor.as_bytes()); | ||
| 54 | + v.extend_from_slice(&0u32.to_le_bytes()); | ||
| 55 | + v | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +/// The default channel mapping of RFC 7845 Section 5.1.1.2: `(family, streams, | ||
| 59 | +/// coupled, table)` for 1 to 8 channels. | ||
| 60 | +/// | ||
| 61 | +/// Families 0 and 1 differ in more than the table: family 1 puts the channels | ||
| 62 | +/// in *Vorbis* order (for 5.1: left, centre, right, back left, back right, | ||
| 63 | +/// LFE), so a caller whose buffers are in the usual film order | ||
| 64 | +/// (FL, FR, FC, LFE, BL, BR) permutes by `[0, 2, 1, 4, 5, 3]` on the way in and | ||
| 65 | +/// by the same permutation on the way out. | ||
| 66 | +pub fn default_mapping(channels: usize) -> Option<(u8, u8, u8, Vec<u8>)> { | ||
| 67 | + let m: (u8, u8, u8, &[u8]) = match channels { | ||
| 68 | + 1 => (0, 1, 0, &[0]), | ||
| 69 | + 2 => (0, 1, 1, &[0, 1]), | ||
| 70 | + 3 => (1, 2, 1, &[0, 2, 1]), | ||
| 71 | + 4 => (1, 2, 2, &[0, 1, 2, 3]), | ||
| 72 | + 5 => (1, 3, 2, &[0, 4, 1, 2, 3]), | ||
| 73 | + 6 => (1, 4, 2, &[0, 4, 1, 2, 3, 5]), | ||
| 74 | + 7 => (1, 4, 3, &[0, 4, 1, 2, 3, 5, 6]), | ||
| 75 | + 8 => (1, 5, 4, &[0, 6, 1, 2, 3, 4, 5, 7]), | ||
| 76 | + _ => return None, | ||
| 77 | + }; | ||
| 78 | + Some((m.0, m.1, m.2, m.3.to_vec())) | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +#[cfg(test)] | ||
| 82 | +mod tests { | ||
| 83 | + use super::*; | ||
| 84 | + | ||
| 85 | + #[test] | ||
| 86 | + fn the_head_is_what_the_rfc_describes() { | ||
| 87 | + let h = opus_head(2, 120, 48000, 0, None); | ||
| 88 | + assert_eq!(&h[..8], b"OpusHead"); | ||
| 89 | + assert_eq!(h[8], 1, "version"); | ||
| 90 | + assert_eq!(h[9], 2, "channels"); | ||
| 91 | + assert_eq!(u16::from_le_bytes([h[10], h[11]]), 120, "pre-skip"); | ||
| 92 | + assert_eq!(u32::from_le_bytes([h[12], h[13], h[14], h[15]]), 48000); | ||
| 93 | + assert_eq!(h[18], 0, "mapping family"); | ||
| 94 | + assert_eq!(h.len(), 19); | ||
| 95 | + | ||
| 96 | + let (family, streams, coupled, table) = default_mapping(6).unwrap(); | ||
| 97 | + let h = opus_head(6, 120, 48000, 0, Some((family, streams, coupled, &table))); | ||
| 98 | + assert_eq!(h.len(), 21 + 6); | ||
| 99 | + assert_eq!(&h[18..21], &[1, 4, 2]); | ||
| 100 | + assert_eq!(&h[21..], &[0, 4, 1, 2, 3, 5]); | ||
| 101 | + } | ||
| 102 | +} | ||
crates/ec-opus/tests/conformance.rsmodified+15 -27
| @@ -772,7 +772,7 @@ fn real_library_sweep() { | |||
| 772 | // Encoder: self-consistency (range-exact against our own decoder) | 772 | // Encoder: self-consistency (range-exact against our own decoder) |
| 773 | // --------------------------------------------------------------------------- | 773 | // --------------------------------------------------------------------------- |
| 774 | 774 | ||
| 775 | -use ec_opus::{Encoder, MultistreamEncoder}; | 775 | +use ec_opus::{Application, Encoder, MultistreamEncoder}; |
| 776 | 776 | ||
| 777 | /// A deterministic music-like test signal: several detuned partials plus a | 777 | /// A deterministic music-like test signal: several detuned partials plus a |
| 778 | /// swept component per channel, loud enough to exercise every band. | 778 | /// swept component per channel, loud enough to exercise every band. |
| @@ -860,7 +860,7 @@ fn encoder_roundtrips_at_every_rate() { | |||
| 860 | for channels in [1usize, 2] { | 860 | for channels in [1usize, 2] { |
| 861 | let pcm = test_signal(channels, 2.0); | 861 | let pcm = test_signal(channels, 2.0); |
| 862 | for kbps in [32u32, 64, 96, 128, 160, 165, 192, 256, 320, 510] { | 862 | for kbps in [32u32, 64, 96, 128, 160, 165, 192, 256, 320, 510] { |
| 863 | - let mut enc = Encoder::new(48000, channels).unwrap(); | 863 | + let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap(); |
| 864 | enc.set_bitrate(kbps * 1000); | 864 | enc.set_bitrate(kbps * 1000); |
| 865 | let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, channels, 960); | 865 | let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, channels, 960); |
| 866 | let corr = delayed_corr(&pcm, &decoded, channels); | 866 | let corr = delayed_corr(&pcm, &decoded, channels); |
| @@ -881,14 +881,14 @@ fn encoder_roundtrips_at_every_rate() { | |||
| 881 | fn encoder_frame_sizes_and_vbr() { | 881 | fn encoder_frame_sizes_and_vbr() { |
| 882 | let pcm = test_signal(2, 1.0); | 882 | let pcm = test_signal(2, 1.0); |
| 883 | for frame in [120usize, 240, 480, 960] { | 883 | for frame in [120usize, 240, 480, 960] { |
| 884 | - let mut enc = Encoder::new(48000, 2).unwrap(); | 884 | + let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); |
| 885 | enc.set_bitrate(128_000); | 885 | enc.set_bitrate(128_000); |
| 886 | let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, frame); | 886 | let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, frame); |
| 887 | let corr = delayed_corr(&pcm, &decoded, 2); | 887 | let corr = delayed_corr(&pcm, &decoded, 2); |
| 888 | println!("frame {frame}: corr {corr:.4}"); | 888 | println!("frame {frame}: corr {corr:.4}"); |
| 889 | assert!(corr >= 0.85, "frame {frame}: correlation {corr:.4}"); | 889 | assert!(corr >= 0.85, "frame {frame}: correlation {corr:.4}"); |
| 890 | } | 890 | } |
| 891 | - let mut enc = Encoder::new(48000, 2).unwrap(); | 891 | + let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); |
| 892 | enc.set_bitrate(128_000); | 892 | enc.set_bitrate(128_000); |
| 893 | enc.set_vbr_constrained(true); | 893 | enc.set_vbr_constrained(true); |
| 894 | let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, 2, 960); | 894 | let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, 2, 960); |
| @@ -914,25 +914,13 @@ use ec_core::registry::{CodecId, CodecParameters, MediaParameters, Muxer, Stream | |||
| 914 | use ec_core::{ChannelLayout, Packet as CorePacket, TimeBase}; | 914 | use ec_core::{ChannelLayout, Packet as CorePacket, TimeBase}; |
| 915 | use ec_ogg::OggMuxer; | 915 | use ec_ogg::OggMuxer; |
| 916 | 916 | ||
| 917 | -/// The RFC 7845 identification header for this encoder: pre-skip 120, the | 917 | +/// The RFC 7845 identification header for this encoder — built by the crate's |
| 918 | -/// CELT overlap delay. | 918 | +/// own [`ec_opus::ogg`] helper, so a muxer and the encoder cannot disagree — |
| 919 | +/// with pre-skip 120, the CELT overlap delay. | ||
| 919 | fn opus_head(channels: usize, layout: Option<(usize, usize, &[u8])>) -> Vec<u8> { | 920 | fn opus_head(channels: usize, layout: Option<(usize, usize, &[u8])>) -> Vec<u8> { |
| 920 | - let mut h = Vec::from(*b"OpusHead"); | 921 | + let mapping = |
| 921 | - h.push(1); | 922 | + layout.map(|(streams, coupled, table)| (1u8, streams as u8, coupled as u8, table)); |
| 922 | - h.push(channels as u8); | 923 | + ec_opus::ogg::opus_head(channels as u8, 120, 48000, 0, mapping) |
| 923 | - h.extend_from_slice(&120u16.to_le_bytes()); | ||
| 924 | - h.extend_from_slice(&48000u32.to_le_bytes()); | ||
| 925 | - h.extend_from_slice(&0i16.to_le_bytes()); | ||
| 926 | - match layout { | ||
| 927 | - None => h.push(0), | ||
| 928 | - Some((streams, coupled, mapping)) => { | ||
| 929 | - h.push(1); | ||
| 930 | - h.push(streams as u8); | ||
| 931 | - h.push(coupled as u8); | ||
| 932 | - h.extend_from_slice(mapping); | ||
| 933 | - } | ||
| 934 | - } | ||
| 935 | - h | ||
| 936 | } | 924 | } |
| 937 | 925 | ||
| 938 | /// Muxes 20 ms packets into an Ogg-Opus file whose final granule trims the | 926 | /// 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() { | |||
| 1012 | let total = pcm.len() / channels; | 1000 | let total = pcm.len() / channels; |
| 1013 | let mut table = Vec::new(); | 1001 | let mut table = Vec::new(); |
| 1014 | for kbps in [16u32, 32, 64, 96, 128, 160, 165, 192, 256, 320, 510] { | 1002 | for kbps in [16u32, 32, 64, 96, 128, 160, 165, 192, 256, 320, 510] { |
| 1015 | - let mut enc = Encoder::new(48000, channels).unwrap(); | 1003 | + let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap(); |
| 1016 | enc.set_bitrate(kbps * 1000); | 1004 | enc.set_bitrate(kbps * 1000); |
| 1017 | let packets = encode_packets(&mut enc, &pcm, channels); | 1005 | let packets = encode_packets(&mut enc, &pcm, channels); |
| 1018 | let path = temp_path(&format!("{channels}ch-{kbps}k.opus")); | 1006 | let path = temp_path(&format!("{channels}ch-{kbps}k.opus")); |
| @@ -1134,7 +1122,7 @@ fn five_one_encode_end_to_end() { | |||
| 1134 | fn ogg_opus_round_trip_duration_is_exact() { | 1122 | fn ogg_opus_round_trip_duration_is_exact() { |
| 1135 | let pcm = test_signal(2, 2.0); | 1123 | let pcm = test_signal(2, 2.0); |
| 1136 | let total = pcm.len() / 2; | 1124 | let total = pcm.len() / 2; |
| 1137 | - let mut enc = Encoder::new(48000, 2).unwrap(); | 1125 | + let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); |
| 1138 | enc.set_bitrate(128_000); | 1126 | enc.set_bitrate(128_000); |
| 1139 | let packets = encode_packets(&mut enc, &pcm, 2); | 1127 | let packets = encode_packets(&mut enc, &pcm, 2); |
| 1140 | let path = temp_path("duration.opus"); | 1128 | let path = temp_path("duration.opus"); |
| @@ -1191,7 +1179,7 @@ fn opus_demo_decodes_our_bit_stream() { | |||
| 1191 | return; | 1179 | return; |
| 1192 | }; | 1180 | }; |
| 1193 | let pcm = test_signal(2, 2.0); | 1181 | let pcm = test_signal(2, 2.0); |
| 1194 | - let mut enc = Encoder::new(48000, 2).unwrap(); | 1182 | + let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); |
| 1195 | enc.set_bitrate(256_000); | 1183 | enc.set_bitrate(256_000); |
| 1196 | let mut out = vec![0u8; 1500]; | 1184 | let mut out = vec![0u8; 1500]; |
| 1197 | let mut bit = Vec::new(); | 1185 | let mut bit = Vec::new(); |
| @@ -1252,7 +1240,7 @@ fn steady_state_encode_loop_zero_alloc() { | |||
| 1252 | v | 1240 | v |
| 1253 | }; | 1241 | }; |
| 1254 | // Stereo elementary encoder. | 1242 | // Stereo elementary encoder. |
| 1255 | - let mut enc = Encoder::new(48000, 2).unwrap(); | 1243 | + let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); |
| 1256 | enc.set_bitrate(256_000); | 1244 | enc.set_bitrate(256_000); |
| 1257 | let mut out = vec![0u8; 1500]; | 1245 | let mut out = vec![0u8; 1500]; |
| 1258 | for block in pcm.chunks_exact(960 * 2) { | 1246 | for block in pcm.chunks_exact(960 * 2) { |
| @@ -1302,7 +1290,7 @@ fn encode_speed() { | |||
| 1302 | ("stereo 510k", 2, 510, 50.0), | 1290 | ("stereo 510k", 2, 510, 50.0), |
| 1303 | ] { | 1291 | ] { |
| 1304 | let pcm = test_signal(channels, secs); | 1292 | let pcm = test_signal(channels, secs); |
| 1305 | - let mut enc = Encoder::new(48000, channels).unwrap(); | 1293 | + let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap(); |
| 1306 | enc.set_bitrate(kbps * 1000); | 1294 | enc.set_bitrate(kbps * 1000); |
| 1307 | let mut out = vec![0u8; 1500]; | 1295 | let mut out = vec![0u8; 1500]; |
| 1308 | // Warm up one pass, then measure. | 1296 | // Warm up one pass, then measure. |
shims/opus-rs/src/lib.rsmodified+314 -8
| @@ -14,15 +14,19 @@ | |||
| 14 | //! | 14 | //! |
| 15 | //! `complexity` is accepted for drop-in compatibility and ignored: this | 15 | //! `complexity` is accepted for drop-in compatibility and ignored: this |
| 16 | //! encoder has one (fast) analysis path, not a ladder. | 16 | //! encoder has one (fast) analysis path, not a ladder. |
| 17 | +//! | ||
| 18 | +//! One behaviour is genuinely narrower and is stated rather than hidden: this | ||
| 19 | +//! encoder is **CELT-only**, so [`Application::Voip`] selects a narrower | ||
| 20 | +//! bandwidth at a given rate but not the SILK layer the name implies. Speech | ||
| 21 | +//! below about 32 kbps is where that costs the most. | ||
| 17 | 22 | ||
| 18 | #![forbid(unsafe_code)] | 23 | #![forbid(unsafe_code)] |
| 19 | #![warn(missing_docs)] | 24 | #![warn(missing_docs)] |
| 20 | 25 | ||
| 21 | use std::fmt; | 26 | use std::fmt; |
| 22 | 27 | ||
| 23 | -/// What the encoded stream is optimised for. This CELT-only encoder treats | 28 | +/// What the encoded stream is optimised for. This CELT-only encoder spends the |
| 24 | -/// every application as [`Application::Audio`]; the variants exist for call | 29 | +/// setting on the coded bandwidth, not on a different coding layer. |
| 25 | -/// compatibility. | ||
| 26 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 30 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 27 | pub enum Application { | 31 | pub enum Application { |
| 28 | /// Speech-optimised (SILK in libopus; served by CELT here). | 32 | /// Speech-optimised (SILK in libopus; served by CELT here). |
| @@ -33,6 +37,33 @@ pub enum Application { | |||
| 33 | RestrictedLowdelay, | 37 | RestrictedLowdelay, |
| 34 | } | 38 | } |
| 35 | 39 | ||
| 40 | +impl From<Application> for ec_opus::Application { | ||
| 41 | + fn from(a: Application) -> ec_opus::Application { | ||
| 42 | + match a { | ||
| 43 | + Application::Voip => ec_opus::Application::Voip, | ||
| 44 | + Application::Audio => ec_opus::Application::Audio, | ||
| 45 | + Application::RestrictedLowdelay => ec_opus::Application::LowDelay, | ||
| 46 | + } | ||
| 47 | + } | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// Coded audio bandwidth, with the C API's discriminants. | ||
| 51 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 52 | +pub enum Bandwidth { | ||
| 53 | + /// Chosen from the bitrate, the application and the input rate. | ||
| 54 | + Auto = -1000, | ||
| 55 | + /// 4 kHz. | ||
| 56 | + Narrowband = 1101, | ||
| 57 | + /// 6 kHz. CELT has no mediumband configuration; this codes as wideband. | ||
| 58 | + Mediumband = 1102, | ||
| 59 | + /// 8 kHz. | ||
| 60 | + Wideband = 1103, | ||
| 61 | + /// 12 kHz. | ||
| 62 | + SuperWideband = 1104, | ||
| 63 | + /// 20 kHz. | ||
| 64 | + Fullband = 1105, | ||
| 65 | +} | ||
| 66 | + | ||
| 36 | /// The error type of this shim: a message, as the incumbent's was. | 67 | /// The error type of this shim: a message, as the incumbent's was. |
| 37 | #[derive(Debug, Clone)] | 68 | #[derive(Debug, Clone)] |
| 38 | pub struct OpusError(String); | 69 | pub struct OpusError(String); |
| @@ -53,33 +84,57 @@ pub struct OpusEncoder { | |||
| 53 | pub bitrate_bps: i32, | 84 | pub bitrate_bps: i32, |
| 54 | /// Accepted for compatibility; this encoder has a single analysis path. | 85 | /// Accepted for compatibility; this encoder has a single analysis path. |
| 55 | pub complexity: i32, | 86 | pub complexity: i32, |
| 87 | + /// Coded bandwidth; [`Bandwidth::Auto`] follows the bitrate. | ||
| 88 | + pub bandwidth: Bandwidth, | ||
| 89 | + /// Constrained VBR. Off by default, as the incumbent's was. | ||
| 90 | + pub vbr: bool, | ||
| 56 | inner: ec_opus::Encoder, | 91 | inner: ec_opus::Encoder, |
| 57 | channels: usize, | 92 | channels: usize, |
| 93 | + applied_bandwidth: Bandwidth, | ||
| 94 | + applied_vbr: bool, | ||
| 58 | } | 95 | } |
| 59 | 96 | ||
| 60 | impl OpusEncoder { | 97 | impl OpusEncoder { |
| 61 | - /// An encoder at `sample_rate` (48000 only — the rate the product feeds) | 98 | + /// An encoder at `sample_rate` (8000, 12000, 16000, 24000 or 48000) for |
| 62 | - /// for `channels` channels (1 or 2). | 99 | + /// `channels` channels (1 or 2). |
| 63 | pub fn new( | 100 | pub fn new( |
| 64 | sample_rate: i32, | 101 | sample_rate: i32, |
| 65 | channels: i32, | 102 | channels: i32, |
| 66 | - _application: Application, | 103 | + application: Application, |
| 67 | ) -> Result<OpusEncoder, OpusError> { | 104 | ) -> Result<OpusEncoder, OpusError> { |
| 68 | if sample_rate < 0 || channels < 0 { | 105 | if sample_rate < 0 || channels < 0 { |
| 69 | return Err(OpusError(format!( | 106 | return Err(OpusError(format!( |
| 70 | "invalid encoder arguments: {sample_rate} Hz, {channels} channels" | 107 | "invalid encoder arguments: {sample_rate} Hz, {channels} channels" |
| 71 | ))); | 108 | ))); |
| 72 | } | 109 | } |
| 73 | - let inner = ec_opus::Encoder::new(sample_rate as u32, channels as usize) | 110 | + let inner = |
| 111 | + ec_opus::Encoder::new(sample_rate as u32, channels as usize, application.into()) | ||
| 74 | .map_err(|e| OpusError(e.to_string()))?; | 112 | .map_err(|e| OpusError(e.to_string()))?; |
| 75 | Ok(OpusEncoder { | 113 | Ok(OpusEncoder { |
| 76 | bitrate_bps: 64_000 * channels, | 114 | bitrate_bps: 64_000 * channels, |
| 77 | complexity: 10, | 115 | complexity: 10, |
| 116 | + bandwidth: Bandwidth::Auto, | ||
| 117 | + vbr: false, | ||
| 78 | inner, | 118 | inner, |
| 79 | channels: channels as usize, | 119 | channels: channels as usize, |
| 120 | + applied_bandwidth: Bandwidth::Auto, | ||
| 121 | + applied_vbr: false, | ||
| 80 | }) | 122 | }) |
| 81 | } | 123 | } |
| 82 | 124 | ||
| 125 | + /// Samples of encoder delay, at the input rate: the decoded stream lags | ||
| 126 | + /// the input by this much, and an Ogg-Opus pre-skip of it (scaled to | ||
| 127 | + /// 48 kHz) cancels the lag exactly. | ||
| 128 | + pub fn look_ahead(&self) -> usize { | ||
| 129 | + self.inner.look_ahead() | ||
| 130 | + } | ||
| 131 | + | ||
| 132 | + /// The range coder state after the last packet — the RFC 6716 Section 6 | ||
| 133 | + /// conformance hook, which a conformant decoder reproduces exactly. | ||
| 134 | + pub fn final_range(&self) -> u32 { | ||
| 135 | + self.inner.final_range() | ||
| 136 | + } | ||
| 137 | + | ||
| 83 | /// Encodes `frame_size` samples per channel of interleaved `f32` into | 138 | /// Encodes `frame_size` samples per channel of interleaved `f32` into |
| 84 | /// `out`, returning the packet length in bytes. | 139 | /// `out`, returning the packet length in bytes. |
| 85 | pub fn encode( | 140 | pub fn encode( |
| @@ -95,16 +150,159 @@ impl OpusEncoder { | |||
| 95 | self.channels | 150 | self.channels |
| 96 | ))); | 151 | ))); |
| 97 | } | 152 | } |
| 98 | - self.inner.set_bitrate(self.bitrate_bps.max(0) as u32); | 153 | + self.sync_settings(); |
| 99 | self.inner | 154 | self.inner |
| 100 | .encode_float(pcm, frame_size, out) | 155 | .encode_float(pcm, frame_size, out) |
| 101 | .map_err(|e| OpusError(e.to_string())) | 156 | .map_err(|e| OpusError(e.to_string())) |
| 102 | } | 157 | } |
| 103 | 158 | ||
| 159 | + /// [`OpusEncoder::encode`] from 16-bit samples. | ||
| 160 | + pub fn encode_i16( | ||
| 161 | + &mut self, | ||
| 162 | + pcm: &[i16], | ||
| 163 | + frame_size: usize, | ||
| 164 | + out: &mut [u8], | ||
| 165 | + ) -> Result<usize, OpusError> { | ||
| 166 | + if pcm.len() < frame_size * self.channels { | ||
| 167 | + return Err(OpusError(format!( | ||
| 168 | + "{} samples is short of {} channels x {frame_size}", | ||
| 169 | + pcm.len(), | ||
| 170 | + self.channels | ||
| 171 | + ))); | ||
| 172 | + } | ||
| 173 | + self.sync_settings(); | ||
| 174 | + self.inner | ||
| 175 | + .encode(pcm, frame_size, out) | ||
| 176 | + .map_err(|e| OpusError(e.to_string())) | ||
| 177 | + } | ||
| 178 | + | ||
| 104 | /// Drops all inter-frame state; the next packet starts a fresh stream. | 179 | /// Drops all inter-frame state; the next packet starts a fresh stream. |
| 105 | pub fn reset(&mut self) { | 180 | pub fn reset(&mut self) { |
| 106 | self.inner.reset(); | 181 | self.inner.reset(); |
| 107 | } | 182 | } |
| 183 | + | ||
| 184 | + /// Pushes the public fields into the encoder before a frame. | ||
| 185 | + fn sync_settings(&mut self) { | ||
| 186 | + self.inner.set_bitrate(self.bitrate_bps.max(0) as u32); | ||
| 187 | + if self.bandwidth != self.applied_bandwidth { | ||
| 188 | + self.inner.set_bandwidth(match self.bandwidth { | ||
| 189 | + Bandwidth::Auto => None, | ||
| 190 | + Bandwidth::Narrowband => Some(ec_opus::Bandwidth::Narrow), | ||
| 191 | + Bandwidth::Mediumband | Bandwidth::Wideband => Some(ec_opus::Bandwidth::Wide), | ||
| 192 | + Bandwidth::SuperWideband => Some(ec_opus::Bandwidth::SuperWide), | ||
| 193 | + Bandwidth::Fullband => Some(ec_opus::Bandwidth::Full), | ||
| 194 | + }); | ||
| 195 | + self.applied_bandwidth = self.bandwidth; | ||
| 196 | + } | ||
| 197 | + if self.vbr != self.applied_vbr { | ||
| 198 | + self.inner.set_vbr_constrained(self.vbr); | ||
| 199 | + self.applied_vbr = self.vbr; | ||
| 200 | + } | ||
| 201 | + } | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +/// An Opus decoder, mono or stereo. | ||
| 205 | +#[derive(Debug)] | ||
| 206 | +pub struct OpusDecoder { | ||
| 207 | + inner: ec_opus::Decoder, | ||
| 208 | +} | ||
| 209 | + | ||
| 210 | +impl OpusDecoder { | ||
| 211 | + /// A decoder for `channels` channels at `sample_rate` Hz. | ||
| 212 | + pub fn new(sample_rate: i32, channels: i32) -> Result<OpusDecoder, OpusError> { | ||
| 213 | + if sample_rate < 0 || channels < 0 { | ||
| 214 | + return Err(OpusError(format!( | ||
| 215 | + "invalid decoder arguments: {sample_rate} Hz, {channels} channels" | ||
| 216 | + ))); | ||
| 217 | + } | ||
| 218 | + Ok(OpusDecoder { | ||
| 219 | + inner: ec_opus::Decoder::new(sample_rate as u32, channels as usize) | ||
| 220 | + .map_err(|e| OpusError(e.to_string()))?, | ||
| 221 | + }) | ||
| 222 | + } | ||
| 223 | + | ||
| 224 | + /// Decodes one packet into interleaved `f32`, returning samples per | ||
| 225 | + /// channel. `frame_size` bounds the output, as the incumbent's did. | ||
| 226 | + pub fn decode( | ||
| 227 | + &mut self, | ||
| 228 | + packet: &[u8], | ||
| 229 | + frame_size: usize, | ||
| 230 | + out: &mut [f32], | ||
| 231 | + ) -> Result<usize, OpusError> { | ||
| 232 | + let _ = frame_size; | ||
| 233 | + self.inner | ||
| 234 | + .decode_float(packet, out) | ||
| 235 | + .map_err(|e| OpusError(e.to_string())) | ||
| 236 | + } | ||
| 237 | + | ||
| 238 | + /// The range coder state after the last packet. | ||
| 239 | + pub fn final_range(&self) -> u32 { | ||
| 240 | + self.inner.final_range() | ||
| 241 | + } | ||
| 242 | +} | ||
| 243 | + | ||
| 244 | +/// A multichannel encoder, for the 5.1 and 7.1 exports the incumbent could not | ||
| 245 | +/// do at all — the replica's surround Opus path today is stereo only. | ||
| 246 | +#[derive(Debug)] | ||
| 247 | +pub struct MultistreamEncoder { | ||
| 248 | + /// Target bitrate in bits per second, across all streams. | ||
| 249 | + pub bitrate_bps: i32, | ||
| 250 | + inner: ec_opus::MultistreamEncoder, | ||
| 251 | + channels: usize, | ||
| 252 | +} | ||
| 253 | + | ||
| 254 | +impl MultistreamEncoder { | ||
| 255 | + /// An encoder for the RFC 7845 family-1 layout of `channels` channels (1 | ||
| 256 | + /// to 8). Input is in the mapping's channel order, which for 5.1 is Vorbis | ||
| 257 | + /// order: left, centre, right, back left, back right, LFE. | ||
| 258 | + pub fn surround( | ||
| 259 | + sample_rate: i32, | ||
| 260 | + channels: usize, | ||
| 261 | + application: Application, | ||
| 262 | + ) -> Result<MultistreamEncoder, OpusError> { | ||
| 263 | + if sample_rate < 0 { | ||
| 264 | + return Err(OpusError(format!("invalid sample rate {sample_rate}"))); | ||
| 265 | + } | ||
| 266 | + let inner = | ||
| 267 | + ec_opus::MultistreamEncoder::surround(sample_rate as u32, channels, application.into()) | ||
| 268 | + .map_err(|e| OpusError(e.to_string()))?; | ||
| 269 | + Ok(MultistreamEncoder { | ||
| 270 | + bitrate_bps: 96_000 * channels as i32 / 2, | ||
| 271 | + inner, | ||
| 272 | + channels, | ||
| 273 | + }) | ||
| 274 | + } | ||
| 275 | + | ||
| 276 | + /// The channel mapping table the `OpusHead` for this encoder needs. | ||
| 277 | + pub fn mapping(&self) -> &[u8] { | ||
| 278 | + self.inner.layout().2 | ||
| 279 | + } | ||
| 280 | + | ||
| 281 | + /// Elementary streams, and how many of them are coupled. | ||
| 282 | + pub fn stream_counts(&self) -> (usize, usize) { | ||
| 283 | + let (streams, coupled, _) = self.inner.layout(); | ||
| 284 | + (streams, coupled) | ||
| 285 | + } | ||
| 286 | + | ||
| 287 | + /// Encodes one frame of interleaved `f32`, returning the packet length. | ||
| 288 | + pub fn encode( | ||
| 289 | + &mut self, | ||
| 290 | + pcm: &[f32], | ||
| 291 | + frame_size: usize, | ||
| 292 | + out: &mut [u8], | ||
| 293 | + ) -> Result<usize, OpusError> { | ||
| 294 | + if pcm.len() < frame_size * self.channels { | ||
| 295 | + return Err(OpusError(format!( | ||
| 296 | + "{} samples is short of {} channels x {frame_size}", | ||
| 297 | + pcm.len(), | ||
| 298 | + self.channels | ||
| 299 | + ))); | ||
| 300 | + } | ||
| 301 | + self.inner.set_bitrate(self.bitrate_bps.max(0) as u32); | ||
| 302 | + self.inner | ||
| 303 | + .encode_float(pcm, frame_size, out) | ||
| 304 | + .map_err(|e| OpusError(e.to_string())) | ||
| 305 | + } | ||
| 108 | } | 306 | } |
| 109 | 307 | ||
| 110 | #[cfg(test)] | 308 | #[cfg(test)] |
| @@ -133,4 +331,112 @@ mod tests { | |||
| 133 | let len = mono.encode(&frame, 960, &mut out).unwrap(); | 331 | let len = mono.encode(&frame, 960, &mut out).unwrap(); |
| 134 | assert!(len > 2); | 332 | assert!(len > 2); |
| 135 | } | 333 | } |
| 334 | + | ||
| 335 | + fn tone(n: usize, channels: usize) -> Vec<f32> { | ||
| 336 | + (0..n * channels) | ||
| 337 | + .map(|i| { | ||
| 338 | + let t = (i / channels) as f32; | ||
| 339 | + 0.5 * (t * 0.07).sin() + 0.25 * (t * 0.23).sin() | ||
| 340 | + }) | ||
| 341 | + .collect() | ||
| 342 | + } | ||
| 343 | + | ||
| 344 | + /// The decoder half of the surface, and the conformance hook that says the | ||
| 345 | + /// two agree: the decoder's range state must equal the encoder's after | ||
| 346 | + /// every packet. | ||
| 347 | + #[test] | ||
| 348 | + fn the_shim_decodes_what_it_encodes_and_the_ranges_agree() { | ||
| 349 | + const FRAME: usize = 960; | ||
| 350 | + let mut enc = OpusEncoder::new(48_000, 2, Application::Audio).unwrap(); | ||
| 351 | + enc.bitrate_bps = 256_000; | ||
| 352 | + let mut dec = OpusDecoder::new(48_000, 2).unwrap(); | ||
| 353 | + let pcm = tone(FRAME * 8, 2); | ||
| 354 | + let mut out = vec![0u8; 1500]; | ||
| 355 | + let mut back = vec![0.0f32; FRAME * 2]; | ||
| 356 | + let mut total = 0; | ||
| 357 | + for block in pcm.chunks_exact(FRAME * 2) { | ||
| 358 | + let len = enc.encode(block, FRAME, &mut out).unwrap(); | ||
| 359 | + assert!(len > 1 && len <= 1276, "packet of {len} bytes"); | ||
| 360 | + total += len; | ||
| 361 | + assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME); | ||
| 362 | + assert_eq!(dec.final_range(), enc.final_range()); | ||
| 363 | + } | ||
| 364 | + // 256 kbps over 8 frames of 20 ms: the incumbent's 165 kbps ceiling is | ||
| 365 | + // what this number exists to refute. | ||
| 366 | + let want = 256_000 / 8 / 50 * 8; | ||
| 367 | + assert!( | ||
| 368 | + (total as f64 - want as f64).abs() < 0.2 * want as f64, | ||
| 369 | + "{total} bytes vs {want} at 256 kbps" | ||
| 370 | + ); | ||
| 371 | + } | ||
| 372 | + | ||
| 373 | + /// Input below 48 kHz, which the shim used to refuse outright, and the | ||
| 374 | + /// `look_ahead` that goes with it (120 samples at 48 kHz, scaled). | ||
| 375 | + #[test] | ||
| 376 | + fn slower_input_rates_encode_and_report_their_own_delay() { | ||
| 377 | + for &(rate, frame, look) in &[ | ||
| 378 | + (48_000i32, 960usize, 120usize), | ||
| 379 | + (24_000, 480, 60), | ||
| 380 | + (16_000, 320, 40), | ||
| 381 | + (12_000, 240, 30), | ||
| 382 | + (8_000, 160, 20), | ||
| 383 | + ] { | ||
| 384 | + let mut enc = OpusEncoder::new(rate, 1, Application::Voip).unwrap(); | ||
| 385 | + enc.bitrate_bps = 32_000; | ||
| 386 | + assert_eq!(enc.look_ahead(), look, "{rate} Hz look-ahead"); | ||
| 387 | + let pcm = tone(frame * 4, 1); | ||
| 388 | + let mut out = vec![0u8; 1500]; | ||
| 389 | + // Everything a 48 kHz decoder gets back is 48 kHz, whatever went in. | ||
| 390 | + let mut dec = OpusDecoder::new(48_000, 1).unwrap(); | ||
| 391 | + let mut back = vec![0.0f32; 960]; | ||
| 392 | + for block in pcm.chunks_exact(frame) { | ||
| 393 | + let len = enc.encode(block, frame, &mut out).unwrap(); | ||
| 394 | + assert!(len > 2, "{rate} Hz packet of {len} bytes"); | ||
| 395 | + assert_eq!(dec.decode(&out[..len], 960, &mut back).unwrap(), 960); | ||
| 396 | + assert_eq!(dec.final_range(), enc.final_range(), "{rate} Hz range"); | ||
| 397 | + } | ||
| 398 | + } | ||
| 399 | + assert!(OpusEncoder::new(44_100, 2, Application::Audio).is_err()); | ||
| 400 | + } | ||
| 401 | + | ||
| 402 | + /// A narrower band is a smaller top-band cost, not a refusal: forcing the | ||
| 403 | + /// bandwidth must still produce packets a decoder reads. | ||
| 404 | + #[test] | ||
| 405 | + fn forced_bandwidth_and_i16_input_round_trip() { | ||
| 406 | + const FRAME: usize = 960; | ||
| 407 | + let mut enc = OpusEncoder::new(48_000, 1, Application::Audio).unwrap(); | ||
| 408 | + enc.bitrate_bps = 64_000; | ||
| 409 | + enc.bandwidth = Bandwidth::Wideband; | ||
| 410 | + enc.vbr = true; | ||
| 411 | + let pcm: Vec<i16> = tone(FRAME * 4, 1) | ||
| 412 | + .iter() | ||
| 413 | + .map(|v| (v * 16_000.0) as i16) | ||
| 414 | + .collect(); | ||
| 415 | + let mut out = vec![0u8; 1500]; | ||
| 416 | + let mut dec = OpusDecoder::new(48_000, 1).unwrap(); | ||
| 417 | + let mut back = vec![0.0f32; FRAME]; | ||
| 418 | + for block in pcm.chunks_exact(FRAME) { | ||
| 419 | + let len = enc.encode_i16(block, FRAME, &mut out).unwrap(); | ||
| 420 | + // TOC config 20..23 is wideband CELT (RFC 6716 Table 2). | ||
| 421 | + assert_eq!(out[0] >> 3, 23, "wideband CELT config"); | ||
| 422 | + assert_eq!(dec.decode(&out[..len], FRAME, &mut back).unwrap(), FRAME); | ||
| 423 | + assert_eq!(dec.final_range(), enc.final_range()); | ||
| 424 | + } | ||
| 425 | + } | ||
| 426 | + | ||
| 427 | + /// 5.1, which the incumbent could not encode at all. | ||
| 428 | + #[test] | ||
| 429 | + fn surround_encodes_five_one() { | ||
| 430 | + const FRAME: usize = 960; | ||
| 431 | + let mut e = MultistreamEncoder::surround(48_000, 6, Application::Audio).unwrap(); | ||
| 432 | + e.bitrate_bps = 384_000; | ||
| 433 | + assert_eq!(e.stream_counts(), (4, 2)); | ||
| 434 | + assert_eq!(e.mapping(), &[0, 4, 1, 2, 3, 5]); | ||
| 435 | + let pcm = tone(FRAME * 3, 6); | ||
| 436 | + let mut out = vec![0u8; 8 * 1500]; | ||
| 437 | + for block in pcm.chunks_exact(FRAME * 6) { | ||
| 438 | + assert!(e.encode(block, FRAME, &mut out).unwrap() > 8); | ||
| 439 | + } | ||
| 440 | + assert!(MultistreamEncoder::surround(48_000, 9, Application::Audio).is_err()); | ||
| 441 | + } | ||
| 136 | } | 442 | } |