SILK mode selection in Encoder
Browse files at this commit7f710e5bcb9798e0b80f61a9ede9ac7ce97157b5Parent: 68c7064- feat
- SILK mode selection in Encoder
3 changed files +225 -29
- crates/ec-opus/src/encoder.rs +141 -18
- crates/ec-opus/src/silk_enc_write.rs +1 -0
- crates/ec-opus/tests/conformance.rs +83 -11
crates/ec-opus/src/encoder.rsmodified+141 -18
| @@ -1,30 +1,43 @@ | |||
| 1 | -//! The Opus packet encoder: CELT-only, 8 to 48 kHz in. | 1 | +//! The Opus packet encoder: CELT and mono SILK, 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 CELT one (TOC configs | 5 | +//! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s |
| 6 | -//! 16..31), which is what music encoding uses at every rate the product asks | 6 | +//! default) picks CELT (TOC configs 16..31, every rate and frame size) or |
| 7 | -//! for; there is no SILK and no hybrid path — a speech-optimised mode below | 7 | +//! SILK (TOC configs 1/9, mono NB/WB 20 ms only — stereo SILK and SILK at |
| 8 | -//! 16 kbps is out of scope, not silently approximated. | 8 | +//! other frame sizes fall back to CELT, documented at the fallback site). |
| 9 | +//! Hybrid is not implemented yet and also falls back to CELT. | ||
| 9 | //! | 10 | //! |
| 10 | -//! Input below 48 kHz is zero-stuffed to CELT's native rate and the coded | 11 | +//! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and |
| 11 | -//! bandwidth is capped at the input's own Nyquist, so the images the stuffing | 12 | +//! the coded bandwidth is capped at the input's own Nyquist, so the images |
| 12 | -//! puts there are never coded and the decoder's decimation drops them. | 13 | +//! the stuffing puts there are never coded and the decoder's decimation |
| 13 | -//! [`Encoder::look_ahead`] reports the delay in *input* samples. | 14 | +//! drops them. [`Encoder::look_ahead`] reports the delay in *input* samples. |
| 14 | //! | 15 | //! |
| 15 | //! Rate control is CBR by default — every packet the same size, derived from | 16 | //! Rate control is CBR by default — every packet the same size, derived from |
| 16 | //! the bitrate — or constrained VBR, the reference's reservoir scheme, when | 17 | //! the bitrate — or constrained VBR, the reference's reservoir scheme, when |
| 17 | -//! [`Encoder::set_vbr_constrained`] is on. | 18 | +//! [`Encoder::set_vbr_constrained`] is on. SILK packets are not yet budgeted |
| 19 | +//! against the target rate (D2b). | ||
| 18 | 20 | ||
| 19 | use ec_core::{Error, Result}; | 21 | use ec_core::{Error, Result}; |
| 20 | 22 | ||
| 21 | use crate::celt_enc::CeltEncoder; | 23 | use crate::celt_enc::CeltEncoder; |
| 22 | -use crate::packet::Bandwidth; | 24 | +use crate::packet::{Bandwidth, Mode}; |
| 23 | use crate::range::RangeEncoder; | 25 | use crate::range::RangeEncoder; |
| 26 | +use crate::silk_enc_write::SilkEncoder; | ||
| 24 | 27 | ||
| 25 | /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`). | 28 | /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`). |
| 26 | const MAX_FRAME_BYTES: usize = 1275; | 29 | const MAX_FRAME_BYTES: usize = 1275; |
| 27 | 30 | ||
| 31 | +/// SILK's round-trip algorithmic delay in 48 kHz samples: the analysis | ||
| 32 | +/// resampler (`SilkEncoder::delay_samples`) on the way in plus the decoder's | ||
| 33 | +/// own synthesis resampler on the way out. Click-measured, one impulse | ||
| 34 | +/// through `Encoder`/`Decoder` at each bandwidth, not derived from a | ||
| 35 | +/// formula — `Resampler`'s (decode-side) and `Resampler48`'s (encode-side) | ||
| 36 | +/// FIR lengths differ per bandwidth, so narrowband and wideband delays | ||
| 37 | +/// don't have to and don't match. | ||
| 38 | +const SILK_LOOK_AHEAD_48K_NB: usize = 58; | ||
| 39 | +const SILK_LOOK_AHEAD_48K_WB: usize = 50; | ||
| 40 | + | ||
| 28 | /// What the caller is encoding. This encoder is CELT-only, so the setting | 41 | /// What the caller is encoding. This encoder is CELT-only, so the setting |
| 29 | /// biases the coded bandwidth rather than selecting a different layer. | 42 | /// biases the coded bandwidth rather than selecting a different layer. |
| 30 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | 43 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| @@ -52,6 +65,16 @@ pub struct Encoder { | |||
| 52 | application: Application, | 65 | application: Application, |
| 53 | bandwidth: Option<Bandwidth>, | 66 | bandwidth: Option<Bandwidth>, |
| 54 | final_range: u32, | 67 | final_range: u32, |
| 68 | + /// [`None`] picks SILK, CELT or (once D4 lands) Hybrid from the | ||
| 69 | + /// application and bitrate; `Some` forces one. | ||
| 70 | + mode: Option<Mode>, | ||
| 71 | + /// Lazily created on first use so the mode can flip between packets | ||
| 72 | + /// without paying for the unused layer's state. | ||
| 73 | + silk_nb: Option<SilkEncoder>, | ||
| 74 | + silk_wb: Option<SilkEncoder>, | ||
| 75 | + /// Scratch space for the SILK payload, sized once so the steady-state | ||
| 76 | + /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. | ||
| 77 | + silk_buf: [u8; MAX_FRAME_BYTES + 1], | ||
| 55 | } | 78 | } |
| 56 | 79 | ||
| 57 | impl Encoder { | 80 | impl Encoder { |
| @@ -90,9 +113,21 @@ impl Encoder { | |||
| 90 | application, | 113 | application, |
| 91 | bandwidth: None, | 114 | bandwidth: None, |
| 92 | final_range: 0, | 115 | final_range: 0, |
| 116 | + mode: None, | ||
| 117 | + silk_nb: None, | ||
| 118 | + silk_wb: None, | ||
| 119 | + silk_buf: [0u8; MAX_FRAME_BYTES + 1], | ||
| 93 | }) | 120 | }) |
| 94 | } | 121 | } |
| 95 | 122 | ||
| 123 | + /// Overrides the automatic SILK/CELT choice `wants_silk` would make from | ||
| 124 | + /// the application and bitrate. [`Mode::Hybrid`] is unimplemented and | ||
| 125 | + /// falls back to CELT (documented at the fallback site in | ||
| 126 | + /// [`Encoder::silk_choice`]); pass `None` to restore the automatic pick. | ||
| 127 | + pub fn set_mode(&mut self, mode: Option<Mode>) { | ||
| 128 | + self.mode = mode; | ||
| 129 | + } | ||
| 130 | + | ||
| 96 | /// Channels per frame of input. | 131 | /// Channels per frame of input. |
| 97 | pub fn channels(&self) -> usize { | 132 | pub fn channels(&self) -> usize { |
| 98 | self.channels | 133 | self.channels |
| @@ -105,8 +140,22 @@ impl Encoder { | |||
| 105 | 140 | ||
| 106 | /// Encoder delay in *input* samples: the decoded stream lags the input by | 141 | /// 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` | 142 | /// 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. | 143 | + /// cancels it exactly. CELT: one MDCT overlap, 120 samples at 48 kHz. |
| 144 | + /// SILK (mono, when the application/bitrate or an explicit | ||
| 145 | + /// [`Encoder::set_mode`] select it): [`SILK_LOOK_AHEAD_48K_NB`] or | ||
| 146 | + /// [`SILK_LOOK_AHEAD_48K_WB`], the analysis-plus-synthesis resampler | ||
| 147 | + /// round trip, click-measured per bandwidth. | ||
| 109 | pub fn look_ahead(&self) -> usize { | 148 | pub fn look_ahead(&self) -> usize { |
| 149 | + if self.channels == 1 { | ||
| 150 | + if let Some(wideband) = self.wants_silk() { | ||
| 151 | + let delay = if wideband { | ||
| 152 | + SILK_LOOK_AHEAD_48K_WB | ||
| 153 | + } else { | ||
| 154 | + SILK_LOOK_AHEAD_48K_NB | ||
| 155 | + }; | ||
| 156 | + return delay / self.upsample; | ||
| 157 | + } | ||
| 158 | + } | ||
| 110 | 120 / self.upsample | 159 | 120 / self.upsample |
| 111 | } | 160 | } |
| 112 | 161 | ||
| @@ -144,9 +193,83 @@ impl Encoder { | |||
| 144 | /// Drops all inter-frame state; the next packet starts like the first. | 193 | /// Drops all inter-frame state; the next packet starts like the first. |
| 145 | pub fn reset(&mut self) { | 194 | pub fn reset(&mut self) { |
| 146 | self.celt.reset(); | 195 | self.celt.reset(); |
| 196 | + self.silk_nb = None; | ||
| 197 | + self.silk_wb = None; | ||
| 147 | self.final_range = 0; | 198 | self.final_range = 0; |
| 148 | } | 199 | } |
| 149 | 200 | ||
| 201 | + /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) | ||
| 202 | + /// call for SILK, and if so, wideband (else narrowband). `None` means | ||
| 203 | + /// CELT (or Hybrid, unimplemented and mapped to CELT). | ||
| 204 | + fn wants_silk(&self) -> Option<bool> { | ||
| 205 | + match self.mode { | ||
| 206 | + Some(Mode::Celt) | Some(Mode::Hybrid) => None, | ||
| 207 | + Some(Mode::Silk) => Some(self.bitrate > 10_000), | ||
| 208 | + None => { | ||
| 209 | + if self.application == Application::Voip && self.bitrate < 20_000 { | ||
| 210 | + Some(self.bitrate > 10_000) | ||
| 211 | + } else { | ||
| 212 | + None | ||
| 213 | + } | ||
| 214 | + } | ||
| 215 | + } | ||
| 216 | + } | ||
| 217 | + | ||
| 218 | + /// `wants_silk` narrowed to what this encoder can actually code as SILK: | ||
| 219 | + /// mono, 20 ms (960 samples at 48 kHz) frames only. Stereo SILK and SILK | ||
| 220 | + /// at other frame sizes are D2b's work; both fall back to CELT here. | ||
| 221 | + fn silk_choice(&self, frame_48k: usize) -> Option<bool> { | ||
| 222 | + let wideband = self.wants_silk()?; | ||
| 223 | + if self.channels != 1 || frame_48k != 960 { | ||
| 224 | + return None; | ||
| 225 | + } | ||
| 226 | + Some(wideband) | ||
| 227 | + } | ||
| 228 | + | ||
| 229 | + /// Zero-stuffs a mono, `frame_size`-sample native-rate frame up to | ||
| 230 | + /// `frame_size * upsample` samples at 48 kHz, the rate [`SilkEncoder`] | ||
| 231 | + /// takes — the same technique [`CeltEncoder::encode`] uses, scaled by | ||
| 232 | + /// `upsample` so the passband gain survives the stuffing. | ||
| 233 | + fn zero_stuff_mono(&self, pcm: &[f32], frame_size: usize) -> Vec<f32> { | ||
| 234 | + let up = self.upsample; | ||
| 235 | + if up == 1 { | ||
| 236 | + return pcm[..frame_size].to_vec(); | ||
| 237 | + } | ||
| 238 | + let mut out = vec![0f32; frame_size * up]; | ||
| 239 | + for i in 0..frame_size { | ||
| 240 | + out[i * up] = pcm[i] * up as f32; | ||
| 241 | + } | ||
| 242 | + out | ||
| 243 | + } | ||
| 244 | + | ||
| 245 | + /// Picks SILK or CELT for one frame and encodes it, returning the TOC | ||
| 246 | + /// byte and the payload bytes (excluding TOC), borrowed from scratch | ||
| 247 | + /// space owned by `self` — no allocation on the steady-state path. | ||
| 248 | + /// `cap` bounds the CELT path only — SILK isn't budgeted against a byte | ||
| 249 | + /// cap yet (D2b). | ||
| 250 | + fn encode_toc_and_payload( | ||
| 251 | + &mut self, | ||
| 252 | + pcm: &[f32], | ||
| 253 | + frame_size: usize, | ||
| 254 | + cap: usize, | ||
| 255 | + ) -> Result<(u8, &[u8])> { | ||
| 256 | + let frame_48k = frame_size * self.upsample; | ||
| 257 | + if let Some(wideband) = self.silk_choice(frame_48k) { | ||
| 258 | + let stuffed = self.zero_stuff_mono(pcm, frame_size); | ||
| 259 | + let enc = if wideband { | ||
| 260 | + self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)) | ||
| 261 | + } else { | ||
| 262 | + self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)) | ||
| 263 | + }; | ||
| 264 | + let n = enc.encode_frame(&stuffed, &mut self.silk_buf)?; | ||
| 265 | + self.final_range = enc.final_range(); | ||
| 266 | + return Ok((self.silk_buf[0], &self.silk_buf[1..n])); | ||
| 267 | + } | ||
| 268 | + let (toc, frame_48k, end) = self.toc(frame_size)?; | ||
| 269 | + let n = self.encode_frame(pcm, frame_48k, end, cap)?; | ||
| 270 | + Ok((toc, &self.range.data()[..n])) | ||
| 271 | + } | ||
| 272 | + | ||
| 150 | /// The TOC byte, the frame size in 48 kHz samples and the CELT end band | 273 | /// The TOC byte, the frame size in 48 kHz samples and the CELT end band |
| 151 | /// for a frame of `frame_size` input samples per channel. | 274 | /// for a frame of `frame_size` input samples per channel. |
| 152 | fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> { | 275 | fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> { |
| @@ -226,8 +349,8 @@ impl Encoder { | |||
| 226 | frame_size: usize, | 349 | frame_size: usize, |
| 227 | out: &mut [u8], | 350 | out: &mut [u8], |
| 228 | ) -> Result<usize> { | 351 | ) -> Result<usize> { |
| 229 | - let (toc, frame_48k, end) = self.toc(frame_size)?; | 352 | + let (toc, payload) = self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1))?; |
| 230 | - let n = self.encode_frame(pcm, frame_48k, end, out.len().saturating_sub(1))?; | 353 | + let n = payload.len(); |
| 231 | if out.len() < 1 + n { | 354 | if out.len() < 1 + n { |
| 232 | return Err(Error::corrupt(format!( | 355 | return Err(Error::corrupt(format!( |
| 233 | "opus encode: packet needs {} bytes, buffer holds {}", | 356 | "opus encode: packet needs {} bytes, buffer holds {}", |
| @@ -236,7 +359,7 @@ impl Encoder { | |||
| 236 | ))); | 359 | ))); |
| 237 | } | 360 | } |
| 238 | out[0] = toc; | 361 | out[0] = toc; |
| 239 | - out[1..1 + n].copy_from_slice(&self.range.data()[..n]); | 362 | + out[1..1 + n].copy_from_slice(payload); |
| 240 | Ok(1 + n) | 363 | Ok(1 + n) |
| 241 | } | 364 | } |
| 242 | 365 | ||
| @@ -255,8 +378,8 @@ impl Encoder { | |||
| 255 | frame_size: usize, | 378 | frame_size: usize, |
| 256 | out: &mut [u8], | 379 | out: &mut [u8], |
| 257 | ) -> Result<usize> { | 380 | ) -> Result<usize> { |
| 258 | - let (toc, frame_48k, end) = self.toc(frame_size)?; | 381 | + let (toc, payload) = self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3))?; |
| 259 | - let n = self.encode_frame(pcm, frame_48k, end, out.len().saturating_sub(3))?; | 382 | + let n = payload.len(); |
| 260 | let len_bytes = if n < 252 { 1 } else { 2 }; | 383 | let len_bytes = if n < 252 { 1 } else { 2 }; |
| 261 | if out.len() < 1 + len_bytes + n { | 384 | if out.len() < 1 + len_bytes + n { |
| 262 | return Err(Error::corrupt(format!( | 385 | return Err(Error::corrupt(format!( |
| @@ -273,7 +396,7 @@ impl Encoder { | |||
| 273 | out[1] = b0 as u8; | 396 | out[1] = b0 as u8; |
| 274 | out[2] = ((n - b0) / 4) as u8; | 397 | out[2] = ((n - b0) / 4) as u8; |
| 275 | } | 398 | } |
| 276 | - out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(&self.range.data()[..n]); | 399 | + out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(payload); |
| 277 | Ok(1 + len_bytes + n) | 400 | Ok(1 + len_bytes + n) |
| 278 | } | 401 | } |
| 279 | 402 | ||
crates/ec-opus/src/silk_enc_write.rsmodified+1 -0
| @@ -37,6 +37,7 @@ const LEVEL_ADJUST: f32 = 80.0 / 1024.0; | |||
| 37 | const MAX_PULSE: i32 = 1023; | 37 | const MAX_PULSE: i32 = 1023; |
| 38 | 38 | ||
| 39 | /// A mono, 20 ms, NB or WB SILK encoder. | 39 | /// A mono, 20 ms, NB or WB SILK encoder. |
| 40 | +#[derive(Clone, Debug)] | ||
| 40 | pub struct SilkEncoder { | 41 | pub struct SilkEncoder { |
| 41 | fs_khz: usize, | 42 | fs_khz: usize, |
| 42 | resampler: Resampler48, | 43 | resampler: Resampler48, |
crates/ec-opus/tests/conformance.rsmodified+83 -11
| @@ -875,6 +875,44 @@ fn encoder_roundtrips_at_every_rate() { | |||
| 875 | } | 875 | } |
| 876 | } | 876 | } |
| 877 | 877 | ||
| 878 | +/// The mode `Encoder` actually picks, read back from the packet's own TOC | ||
| 879 | +/// byte: Voip below 20 kbps mono selects SILK (NB at/under 10 kbps, WB | ||
| 880 | +/// above), Voip 20-40 kbps and Audio at any rate stay on CELT (Hybrid is | ||
| 881 | +/// unimplemented and Mode 20-40 kbps needs it, D4). | ||
| 882 | +#[test] | ||
| 883 | +fn encoder_mode_follows_application_and_bitrate() { | ||
| 884 | + // `None` for the two CELT rows: any CELT config is correct there, the | ||
| 885 | + // exact one is `auto_bandwidth`'s call, not mode selection's. | ||
| 886 | + let cases = [ | ||
| 887 | + (Application::Voip, 8_000u32, Some(1u8)), | ||
| 888 | + (Application::Voip, 16_000, Some(9)), | ||
| 889 | + (Application::Audio, 64_000, None), | ||
| 890 | + (Application::Voip, 32_000, None), | ||
| 891 | + ]; | ||
| 892 | + for (app, bps, want_config) in cases { | ||
| 893 | + let mut enc = Encoder::new(48000, 1, app).unwrap(); | ||
| 894 | + enc.set_bitrate(bps); | ||
| 895 | + let pcm = vec![0.0f32; 960]; | ||
| 896 | + let mut out = vec![0u8; 1500]; | ||
| 897 | + let n = enc.encode_float(&pcm, 960, &mut out).unwrap(); | ||
| 898 | + let toc = ec_opus::Toc::new(out[0]); | ||
| 899 | + match want_config { | ||
| 900 | + Some(want) => assert_eq!( | ||
| 901 | + toc.config, want, | ||
| 902 | + "{app:?} at {bps} bps: TOC config {} (wanted {want})", | ||
| 903 | + toc.config | ||
| 904 | + ), | ||
| 905 | + None => assert_eq!( | ||
| 906 | + toc.mode(), | ||
| 907 | + ec_opus::Mode::Celt, | ||
| 908 | + "{app:?} at {bps} bps: TOC config {} is not CELT", | ||
| 909 | + toc.config | ||
| 910 | + ), | ||
| 911 | + } | ||
| 912 | + assert!(n > 1, "{app:?} at {bps} bps: empty packet"); | ||
| 913 | + } | ||
| 914 | +} | ||
| 915 | + | ||
| 878 | /// All four CELT frame sizes survive the loop, and constrained VBR both | 916 | /// All four CELT frame sizes survive the loop, and constrained VBR both |
| 879 | /// stays decodable and lands near its target. | 917 | /// stays decodable and lands near its target. |
| 880 | #[test] | 918 | #[test] |
| @@ -915,12 +953,13 @@ use ec_core::{ChannelLayout, Packet as CorePacket, TimeBase}; | |||
| 915 | use ec_ogg::OggMuxer; | 953 | use ec_ogg::OggMuxer; |
| 916 | 954 | ||
| 917 | /// The RFC 7845 identification header for this encoder — built by the crate's | 955 | /// The RFC 7845 identification header for this encoder — built by the crate's |
| 918 | -/// own [`ec_opus::ogg`] helper, so a muxer and the encoder cannot disagree — | 956 | +/// own [`ec_opus::ogg`] helper, so a muxer and the encoder cannot disagree. |
| 919 | -/// with pre-skip 120, the CELT overlap delay. | 957 | +/// `pre_skip` is the encoder's [`Encoder::look_ahead`]: 120, the CELT overlap |
| 920 | -fn opus_head(channels: usize, layout: Option<(usize, usize, &[u8])>) -> Vec<u8> { | 958 | +/// delay, for every CELT call site; SILK's own (larger) delay for SILK. |
| 959 | +fn opus_head(channels: usize, pre_skip: u16, layout: Option<(usize, usize, &[u8])>) -> Vec<u8> { | ||
| 921 | let mapping = | 960 | let mapping = |
| 922 | layout.map(|(streams, coupled, table)| (1u8, streams as u8, coupled as u8, table)); | 961 | layout.map(|(streams, coupled, table)| (1u8, streams as u8, coupled as u8, table)); |
| 923 | - ec_opus::ogg::opus_head(channels as u8, 120, 48000, 0, mapping) | 962 | + ec_opus::ogg::opus_head(channels as u8, pre_skip, 48000, 0, mapping) |
| 924 | } | 963 | } |
| 925 | 964 | ||
| 926 | /// Muxes 20 ms packets into an Ogg-Opus file whose final granule trims the | 965 | /// Muxes 20 ms packets into an Ogg-Opus file whose final granule trims the |
| @@ -932,6 +971,7 @@ fn write_ogg_opus( | |||
| 932 | head: Vec<u8>, | 971 | head: Vec<u8>, |
| 933 | channels: usize, | 972 | channels: usize, |
| 934 | total_samples: usize, | 973 | total_samples: usize, |
| 974 | + pre_skip: i64, | ||
| 935 | ) { | 975 | ) { |
| 936 | let file = std::io::BufWriter::new(fs::File::create(path).unwrap()); | 976 | let file = std::io::BufWriter::new(fs::File::create(path).unwrap()); |
| 937 | let mut mux = OggMuxer::new(file); | 977 | let mut mux = OggMuxer::new(file); |
| @@ -947,7 +987,7 @@ fn write_ogg_opus( | |||
| 947 | for (idx, p) in packets.iter().enumerate() { | 987 | for (idx, p) in packets.iter().enumerate() { |
| 948 | let last = idx == packets.len() - 1; | 988 | let last = idx == packets.len() - 1; |
| 949 | let dur = if last { | 989 | let dur = if last { |
| 950 | - total_samples as i64 + 120 - pts | 990 | + total_samples as i64 + pre_skip - pts |
| 951 | } else { | 991 | } else { |
| 952 | 960 | 992 | 960 |
| 953 | }; | 993 | }; |
| @@ -994,7 +1034,7 @@ fn temp_path(name: &str) -> PathBuf { | |||
| 994 | /// incumbent fails this file's 256 kbps row at correlation 0.06; the MUST | 1034 | /// incumbent fails this file's 256 kbps row at correlation 0.06; the MUST |
| 995 | /// bars here are correlation >= 0.9 at 96/165/256 kbps. | 1035 | /// bars here are correlation >= 0.9 at 96/165/256 kbps. |
| 996 | #[test] | 1036 | #[test] |
| 997 | -fn libopus_decodes_our_packets_across_the_rate_table() { | 1037 | +fn oracle_decodes_our_packets_across_the_rate_table() { |
| 998 | for channels in [1usize, 2] { | 1038 | for channels in [1usize, 2] { |
| 999 | let pcm = test_signal(channels, 2.0); | 1039 | let pcm = test_signal(channels, 2.0); |
| 1000 | let total = pcm.len() / channels; | 1040 | let total = pcm.len() / channels; |
| @@ -1004,7 +1044,7 @@ fn libopus_decodes_our_packets_across_the_rate_table() { | |||
| 1004 | enc.set_bitrate(kbps * 1000); | 1044 | enc.set_bitrate(kbps * 1000); |
| 1005 | let packets = encode_packets(&mut enc, &pcm, channels); | 1045 | let packets = encode_packets(&mut enc, &pcm, channels); |
| 1006 | let path = temp_path(&format!("{channels}ch-{kbps}k.opus")); | 1046 | let path = temp_path(&format!("{channels}ch-{kbps}k.opus")); |
| 1007 | - write_ogg_opus(&path, &packets, opus_head(channels, None), channels, total); | 1047 | + write_ogg_opus(&path, &packets, opus_head(channels, 120, None), channels, total, 120); |
| 1008 | let Some(reference) = ffmpeg_decode(&path, channels) else { | 1048 | let Some(reference) = ffmpeg_decode(&path, channels) else { |
| 1009 | eprintln!("ffmpeg unavailable, skipped"); | 1049 | eprintln!("ffmpeg unavailable, skipped"); |
| 1010 | let _ = fs::remove_file(&path); | 1050 | let _ = fs::remove_file(&path); |
| @@ -1059,6 +1099,38 @@ fn libopus_decodes_our_packets_across_the_rate_table() { | |||
| 1059 | println!("{line}"); | 1099 | println!("{line}"); |
| 1060 | } | 1100 | } |
| 1061 | } | 1101 | } |
| 1102 | + | ||
| 1103 | + // SILK, mono, the speech-rate corner: Voip application picks it | ||
| 1104 | + // automatically below 20 kbps (`Encoder::wants_silk`). 0.95 rather than | ||
| 1105 | + // the CELT floors above — SILK is a speech codec, this is a tone signal, | ||
| 1106 | + // not the pulse-coded content it's tuned for. | ||
| 1107 | + let pcm = test_signal(1, 2.0); | ||
| 1108 | + let total = pcm.len(); | ||
| 1109 | + for kbps in [8u32, 12, 16] { | ||
| 1110 | + let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); | ||
| 1111 | + enc.set_bitrate(kbps * 1000); | ||
| 1112 | + let pre_skip = enc.look_ahead() as u16; | ||
| 1113 | + let packets = encode_packets(&mut enc, &pcm, 1); | ||
| 1114 | + let path = temp_path(&format!("silk-1ch-{kbps}k.opus")); | ||
| 1115 | + write_ogg_opus( | ||
| 1116 | + &path, | ||
| 1117 | + &packets, | ||
| 1118 | + opus_head(1, pre_skip, None), | ||
| 1119 | + 1, | ||
| 1120 | + total, | ||
| 1121 | + pre_skip as i64, | ||
| 1122 | + ); | ||
| 1123 | + let Some(reference) = ffmpeg_decode(&path, 1) else { | ||
| 1124 | + eprintln!("ffmpeg unavailable, skipped"); | ||
| 1125 | + let _ = fs::remove_file(&path); | ||
| 1126 | + return; | ||
| 1127 | + }; | ||
| 1128 | + let _ = fs::remove_file(&path); | ||
| 1129 | + let n = (reference.len()).min(total); | ||
| 1130 | + let corr = correlation(&pcm[..n], &reference[..n]); | ||
| 1131 | + println!("silk 1 ch {kbps:>3} kbps: corr {corr:.4}"); | ||
| 1132 | + assert!(corr >= 0.95, "silk {kbps} kbps: correlation {corr:.4}"); | ||
| 1133 | + } | ||
| 1062 | } | 1134 | } |
| 1063 | 1135 | ||
| 1064 | /// 5.1 multistream: one distinct tone per channel, encoded with the | 1136 | /// 5.1 multistream: one distinct tone per channel, encoded with the |
| @@ -1092,9 +1164,9 @@ fn five_one_encode_end_to_end() { | |||
| 1092 | let len = enc.encode_float(&silence, 960, &mut out).expect("encode"); | 1164 | let len = enc.encode_float(&silence, 960, &mut out).expect("encode"); |
| 1093 | packets.push(out[..len].to_vec()); | 1165 | packets.push(out[..len].to_vec()); |
| 1094 | let (streams, coupled, mapping) = enc.layout(); | 1166 | let (streams, coupled, mapping) = enc.layout(); |
| 1095 | - let head = opus_head(6, Some((streams, coupled, mapping))); | 1167 | + let head = opus_head(6, 120, Some((streams, coupled, mapping))); |
| 1096 | let path = temp_path("5.1.opus"); | 1168 | let path = temp_path("5.1.opus"); |
| 1097 | - write_ogg_opus(&path, &packets, head, 6, total); | 1169 | + write_ogg_opus(&path, &packets, head, 6, total, 120); |
| 1098 | let Some(reference) = ffmpeg_decode(&path, 6) else { | 1170 | let Some(reference) = ffmpeg_decode(&path, 6) else { |
| 1099 | eprintln!("ffmpeg unavailable, skipped"); | 1171 | eprintln!("ffmpeg unavailable, skipped"); |
| 1100 | let _ = fs::remove_file(&path); | 1172 | let _ = fs::remove_file(&path); |
| @@ -1126,7 +1198,7 @@ fn ogg_opus_round_trip_duration_is_exact() { | |||
| 1126 | enc.set_bitrate(128_000); | 1198 | enc.set_bitrate(128_000); |
| 1127 | let packets = encode_packets(&mut enc, &pcm, 2); | 1199 | let packets = encode_packets(&mut enc, &pcm, 2); |
| 1128 | let path = temp_path("duration.opus"); | 1200 | let path = temp_path("duration.opus"); |
| 1129 | - write_ogg_opus(&path, &packets, opus_head(2, None), 2, total); | 1201 | + write_ogg_opus(&path, &packets, opus_head(2, 120, None), 2, total, 120); |
| 1130 | let probe = Command::new("ffprobe") | 1202 | let probe = Command::new("ffprobe") |
| 1131 | .args([ | 1203 | .args([ |
| 1132 | "-v", | 1204 | "-v", |
| @@ -1535,7 +1607,7 @@ fn silk_mono_nb_wb_roundtrip() { | |||
| 1535 | // Reference oracle: the packets in an Ogg-Opus file decode cleanly. | 1607 | // Reference oracle: the packets in an Ogg-Opus file decode cleanly. |
| 1536 | if Command::new("ffmpeg").arg("-version").output().is_ok() { | 1608 | if Command::new("ffmpeg").arg("-version").output().is_ok() { |
| 1537 | let path = temp_path(&format!("silk-{name}-{tag}.opus")); | 1609 | let path = temp_path(&format!("silk-{name}-{tag}.opus")); |
| 1538 | - write_ogg_opus(&path, &packets, opus_head(1, None), 1, pcm.len()); | 1610 | + write_ogg_opus(&path, &packets, opus_head(1, 120, None), 1, pcm.len(), 120); |
| 1539 | let out = Command::new("ffmpeg") | 1611 | let out = Command::new("ffmpeg") |
| 1540 | .args(["-v", "warning", "-c:a", "libopus", "-i"]) | 1612 | .args(["-v", "warning", "-c:a", "libopus", "-i"]) |
| 1541 | .arg(&path) | 1613 | .arg(&path) |