edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·3d2e08f·Tahinli·7 days ago·3929 commits
| 1 | //! The Opus packet encoder: CELT, SILK and hybrid, 8 to 48 kHz in. |
| 2 | //! |
| 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 |
| 5 | //! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s |
| 6 | //! default) picks CELT (TOC configs 16..31, every rate and frame size), SILK |
| 7 | //! (TOC configs 0..11, mono NB/MB/WB 10/20/40/60 ms; stereo NB/MB/WB 10/20 ms, |
| 8 | //! with 40/60 ms carried as code-3 packets of 20 ms SILK frames), or Hybrid |
| 9 | //! (TOC configs 13/15, mono or stereo SWB/FB 10 or 20 ms: SILK at 16 kHz under |
| 10 | //! CELT from band 17 up, one range-coded stream). |
| 11 | //! |
| 12 | //! In-band FEC (SILK LBRR, [`Encoder::set_inband_fec`]) is mono SILK and |
| 13 | //! hybrid 10/20 ms only. |
| 14 | //! |
| 15 | //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and |
| 16 | //! the coded bandwidth is capped at the input's own Nyquist, so the images |
| 17 | //! the stuffing puts there are never coded and the decoder's decimation |
| 18 | //! drops them. [`Encoder::look_ahead`] reports the delay in *input* samples. |
| 19 | //! |
| 20 | //! Rate control is CBR by default — every packet the same size, derived from |
| 21 | //! the bitrate — or constrained VBR, the reference's reservoir scheme, when |
| 22 | //! [`Encoder::set_vbr_constrained`] is on. A CBR SILK packet of 10 or 20 ms |
| 23 | //! is held to the same byte budget as a CELT one: its rate loop coarsens |
| 24 | //! until it fits (D2b), then padded up to the budget with code-3 packet |
| 25 | //! padding like libopus's `opus_packet_pad`. |
| 26 | |
| 27 | use ec_core::{Error, Result}; |
| 28 | |
| 29 | use crate::analysis::{AnalysisInfo, TonalityAnalysis}; |
| 30 | use crate::celt_enc::CeltEncoder; |
| 31 | use crate::packet::{Bandwidth, Mode}; |
| 32 | use crate::range::RangeEncoder; |
| 33 | use crate::silk_flp::opus::{InputFilter, SilkFrame, SilkLayer, hp_min_smth1_q15}; |
| 34 | |
| 35 | /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`). |
| 36 | const MAX_FRAME_BYTES: usize = 1275; |
| 37 | |
| 38 | enum Payload { |
| 39 | Range(usize), |
| 40 | Silk(usize), |
| 41 | } |
| 42 | const MAX_SILK_PACKET_BYTES: usize = 1 + 1 + 2 * 2 + 3 * MAX_FRAME_BYTES; |
| 43 | |
| 44 | /// One MDCT overlap: the CELT layer's delay without libopus's input |
| 45 | /// alignment ([`Encoder::set_libopus_input_alignment`]), which adds |
| 46 | /// `delay_compensation = Fs/250` (192 at 48 kHz) on top. |
| 47 | const CELT_OVERLAP_48K: usize = 120; |
| 48 | /// libopus `opus_encoder.c`'s `delay_compensation = Fs/250`. |
| 49 | const CELT_DELAY_COMP_48K: usize = 192; |
| 50 | /// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent. |
| 51 | /// Was 8: at 16 kbps SILK takes 37 of the 40-byte budget, so 8 expanded |
| 52 | /// 5133/6001 packets (+12.9% rate on the speech gate); libopus leaves CELT |
| 53 | /// a few bytes there. |
| 54 | const HYBRID_CELT_MIN_BYTES: usize = 3; |
| 55 | /// libopus 1.6 bandwidth threshold tables (`opus_encoder.c:151`/`162`). |
| 56 | /// Each pair is `(threshold, transition_width)` for one bandwidth boundary; |
| 57 | /// voice and music, mono and stereo, are identical in 1.6. |
| 58 | const MONO_VOICE_BW: [i32; 8] = [9000, 700, 9000, 700, 13500, 1000, 14000, 2000]; |
| 59 | const STEREO_VOICE_BW: [i32; 8] = [9000, 700, 9000, 700, 13500, 1000, 14000, 2000]; |
| 60 | const MONO_MUSIC_BW: [i32; 8] = [9000, 700, 9000, 700, 11000, 1000, 12000, 2000]; |
| 61 | const STEREO_MUSIC_BW: [i32; 8] = [9000, 700, 9000, 700, 11000, 1000, 12000, 2000]; |
| 62 | /// libopus `mode_thresholds` blended by `voice_est` (`opus_encoder.c:183`). |
| 63 | /// With `stereo_width=0` (no analysis) the voice term is `[0][0]=64000` and |
| 64 | /// the music base is `10000`; the gap (54000) is the ve² interpolation span. |
| 65 | const MODE_THRESHOLD_VOICE: i32 = 64000; |
| 66 | const MODE_THRESHOLD_MUSIC: i32 = 10000; |
| 67 | /// Opus default encoder complexity (the `(90+complexity)/100` equiv-rate |
| 68 | /// multiplier; loss=0 and complexity≥5 add no per-mode adjustment). |
| 69 | const DEFAULT_COMPLEXITY: i32 = 9; |
| 70 | |
| 71 | /// What the caller is encoding. |
| 72 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 73 | pub enum Application { |
| 74 | /// Speech: one step narrower at a given rate, where the top octave costs |
| 75 | /// most and carries least. |
| 76 | Voip, |
| 77 | /// Music and general audio, the default. |
| 78 | Audio, |
| 79 | /// Lowest delay. |
| 80 | LowDelay, |
| 81 | } |
| 82 | |
| 83 | const DTX_START_Q1: i32 = 10 * 2 * 20; |
| 84 | const DTX_END_Q1: i32 = (10 + 20) * 2 * 20; |
| 85 | const DTX_ACTIVITY_THRESHOLD: f32 = 0.1; |
| 86 | const DTX_PSEUDO_SNR_THRESHOLD: f32 = 316.23; |
| 87 | const DTX_SILENCE: f32 = 1.0 / 16_777_216.0; |
| 88 | |
| 89 | /// The TOC-only packet libopus sends in DTX: code 0 is the TOC alone; code 3 |
| 90 | /// keeps its frame-count byte with no frames. Self-delimited framing adds a |
| 91 | /// zero frame length after it. |
| 92 | fn dtx_packet(toc: u8, count: u8, self_delimited: bool) -> ([u8; 3], usize) { |
| 93 | let mut bytes = [0u8; 3]; |
| 94 | let len = if toc & 3 == 3 { |
| 95 | bytes[0] = toc; |
| 96 | bytes[1] = count & 0x3F; |
| 97 | if self_delimited { 3 } else { 2 } |
| 98 | } else { |
| 99 | bytes[0] = toc & !3; |
| 100 | if self_delimited { 2 } else { 1 } |
| 101 | }; |
| 102 | (bytes, len) |
| 103 | } |
| 104 | |
| 105 | /// One elementary Opus encoder: mono or stereo. |
| 106 | #[derive(Clone, Debug)] |
| 107 | pub struct Encoder { |
| 108 | celt: CeltEncoder, |
| 109 | range: RangeEncoder, |
| 110 | sample_rate: u32, |
| 111 | /// 48000 / `sample_rate`: the zero-stuffing factor into CELT. |
| 112 | upsample: usize, |
| 113 | channels: usize, |
| 114 | bitrate: u32, |
| 115 | vbr: bool, |
| 116 | application: Application, |
| 117 | bandwidth: Option<Bandwidth>, |
| 118 | final_range: u32, |
| 119 | /// [`None`] picks SILK, CELT or (once D4 lands) Hybrid from the |
| 120 | /// application and bitrate; `Some` forces one. |
| 121 | mode: Option<Mode>, |
| 122 | /// The SILK layer, created on first use (boxed: `crate::stack_budget`). |
| 123 | silk: Option<Box<SilkLayer>>, |
| 124 | /// Scratch space for the SILK packet payload, sized once so the steady-state |
| 125 | /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. |
| 126 | /// |
| 127 | /// Boxed for the same reason as the slots above: `MAX_SILK_PACKET_BYTES` is |
| 128 | /// 4088 bytes, and an inline array that size is a third of the whole |
| 129 | /// budget on the `Encoder` that a caller holds by value. |
| 130 | silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>, |
| 131 | /// [`Encoder::set_libopus_input_alignment`]. |
| 132 | align_input: bool, |
| 133 | filter: InputFilter, |
| 134 | /// Scratch space for the filter's output, sized once. |
| 135 | hp_buf: Vec<f32>, |
| 136 | /// libopus `st->analysis`: the tonality/music-probability estimator. It |
| 137 | /// lives here, not in the CELT layer, because `opus_encode_native` runs |
| 138 | /// `run_analysis()` on the API frame *before* the SILK/CELT mode and |
| 139 | /// bandwidth decisions, so its state advances on SILK frames too. |
| 140 | analysis: TonalityAnalysis, |
| 141 | /// The current frame's analysis output, handed to `celt.encode`. |
| 142 | info: AnalysisInfo, |
| 143 | /// Whether the analysis runs at all — see `celt_enc::analysis_params`. |
| 144 | analysis_on: bool, |
| 145 | /// Whether the detected bandwidth may lower the coded one (`EC_OPUS_BW_DETECT`). |
| 146 | bw_detect: bool, |
| 147 | inband_fec: bool, |
| 148 | packet_loss_perc: u8, |
| 149 | lbrr_coded: bool, |
| 150 | fec_bandwidth: Option<Bandwidth>, |
| 151 | last_silk: Option<u8>, |
| 152 | use_dtx: bool, |
| 153 | nb_no_activity_ms_q1: i32, |
| 154 | peak_signal_energy: f32, |
| 155 | } |
| 156 | |
| 157 | fn toc_bandwidth(toc: u8) -> Bandwidth { |
| 158 | const BW: [Bandwidth; 5] = [ |
| 159 | Bandwidth::Narrow, |
| 160 | Bandwidth::Medium, |
| 161 | Bandwidth::Wide, |
| 162 | Bandwidth::SuperWide, |
| 163 | Bandwidth::Full, |
| 164 | ]; |
| 165 | let config = usize::from(toc >> 3); |
| 166 | match config { |
| 167 | 0..=11 => BW[config / 4], |
| 168 | 12 | 13 => Bandwidth::SuperWide, |
| 169 | 14 | 15 => Bandwidth::Full, |
| 170 | _ => [BW[0], BW[2], BW[3], BW[4]][(config - 16) / 4], |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8, |
| 175 | /// Medium → 12, Wide/SuperWide/Full → 16. SILK only runs at 8/12/16 kHz; |
| 176 | /// for SuperWide/Full the top bands are CELT (Hybrid), so SILK itself is 16. |
| 177 | fn silk_fs_khz(bw: Bandwidth) -> usize { |
| 178 | match bw { |
| 179 | Bandwidth::Narrow => 8, |
| 180 | Bandwidth::Medium => 12, |
| 181 | _ => 16, |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | impl Encoder { |
| 186 | /// An encoder for `channels` channels (1 or 2) at `sample_rate`, which |
| 187 | /// must be one of 8000, 12000, 16000, 24000 or 48000 Hz — the rates |
| 188 | /// RFC 6716 Section 2 admits. CELT itself runs at 48 kHz whatever the |
| 189 | /// input rate is (RFC 7845 Section 5.1). |
| 190 | pub fn new(sample_rate: u32, channels: usize, application: Application) -> Result<Encoder> { |
| 191 | let upsample = match sample_rate { |
| 192 | 48000 => 1, |
| 193 | 24000 => 2, |
| 194 | 16000 => 3, |
| 195 | 12000 => 4, |
| 196 | 8000 => 6, |
| 197 | _ => { |
| 198 | return Err(Error::unsupported( |
| 199 | format!("opus encode at {sample_rate} Hz"), |
| 200 | "Opus encodes from 8, 12, 16, 24 or 48 kHz; resample first", |
| 201 | )); |
| 202 | } |
| 203 | }; |
| 204 | if !(1..=2).contains(&channels) { |
| 205 | return Err(Error::unsupported( |
| 206 | format!("{channels}-channel Opus stream"), |
| 207 | "one stream carries at most two channels; use MultistreamEncoder", |
| 208 | )); |
| 209 | } |
| 210 | let mut enc = Encoder { |
| 211 | celt: CeltEncoder::new(channels, upsample), |
| 212 | range: RangeEncoder::new(), |
| 213 | sample_rate, |
| 214 | upsample, |
| 215 | channels, |
| 216 | bitrate: 64_000 * channels as u32, |
| 217 | vbr: false, |
| 218 | application, |
| 219 | bandwidth: None, |
| 220 | final_range: 0, |
| 221 | mode: None, |
| 222 | silk: None, |
| 223 | silk_buf: Box::new([0u8; MAX_SILK_PACKET_BYTES]), |
| 224 | align_input: application != Application::LowDelay, |
| 225 | filter: InputFilter::new(), |
| 226 | hp_buf: Vec::new(), |
| 227 | analysis: TonalityAnalysis::new(sample_rate), |
| 228 | info: AnalysisInfo::default(), |
| 229 | analysis_on: crate::celt_enc::analysis_params().0, |
| 230 | bw_detect: crate::celt_enc::analysis_params().5, |
| 231 | inband_fec: false, |
| 232 | packet_loss_perc: 0, |
| 233 | lbrr_coded: false, |
| 234 | fec_bandwidth: None, |
| 235 | last_silk: None, |
| 236 | use_dtx: false, |
| 237 | nb_no_activity_ms_q1: 0, |
| 238 | peak_signal_energy: 0.0, |
| 239 | }; |
| 240 | enc.celt.set_align_input(enc.align_input); |
| 241 | Ok(enc) |
| 242 | } |
| 243 | |
| 244 | /// Turns the tonality analysis on or off for this encoder. It is off |
| 245 | /// unless one of its consumers is switched on (see |
| 246 | /// `celt_enc::analysis_params`), because it costs ~25% of the encoder; |
| 247 | /// turn it on to read `music_prob`/`tonality` back through |
| 248 | /// [`Encoder::last_celt_diag`]. |
| 249 | pub fn set_analysis(&mut self, on: bool) { |
| 250 | self.analysis_on = on; |
| 251 | } |
| 252 | |
| 253 | /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and |
| 254 | /// `hybrid_choice` make from the application and bitrate; pass `None` to |
| 255 | /// restore the automatic pick. Requests this encoder cannot honour |
| 256 | /// (10 ms Hybrid) fall back to CELT. |
| 257 | pub fn set_mode(&mut self, mode: Option<Mode>) { |
| 258 | self.mode = mode; |
| 259 | } |
| 260 | |
| 261 | /// Channels per frame of input. |
| 262 | pub fn channels(&self) -> usize { |
| 263 | self.channels |
| 264 | } |
| 265 | |
| 266 | /// The rate the caller feeds. |
| 267 | pub fn sample_rate(&self) -> u32 { |
| 268 | self.sample_rate |
| 269 | } |
| 270 | |
| 271 | /// Encoder delay in *input* samples for a `frame_size`-sample (per |
| 272 | /// channel, native rate) frame: the decoded stream lags the input by |
| 273 | /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate` |
| 274 | /// cancels it exactly. CELT: one MDCT overlap plus the 192-sample input |
| 275 | /// delay compensation, 312 samples at 48 kHz. |
| 276 | /// SILK and hybrid: 312 as well, the libopus SILK encoder's own delay, |
| 277 | /// which the CELT layer's input delay is there to match. |
| 278 | pub fn look_ahead(&self, frame_size: usize) -> usize { |
| 279 | let frame_48k = frame_size * self.upsample; |
| 280 | if self.silk_choice(frame_48k).is_some() { |
| 281 | return (CELT_OVERLAP_48K + CELT_DELAY_COMP_48K) / self.upsample; |
| 282 | } |
| 283 | self.celt_look_ahead_48k() / self.upsample |
| 284 | } |
| 285 | |
| 286 | /// The CELT layer's delay in 48 kHz samples: one MDCT overlap, plus |
| 287 | /// libopus's `delay_compensation` when the alignment is on. |
| 288 | fn celt_look_ahead_48k(&self) -> usize { |
| 289 | CELT_OVERLAP_48K |
| 290 | + if self.align_input { |
| 291 | CELT_DELAY_COMP_48K |
| 292 | } else { |
| 293 | 0 |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | /// On by default except for [`Application::LowDelay`], as in libopus: the |
| 298 | /// SILK layer's own delay is 312 samples, and only an aligned CELT layer |
| 299 | /// keeps CELT, SILK and hybrid frames of one stream at the same delay. |
| 300 | /// |
| 301 | /// Puts our CELT analysis window exactly where libopus's is: the layer is |
| 302 | /// fed the input delayed by `delay_compensation = Fs/250` (192 samples at |
| 303 | /// 48 kHz, `opus_encoder.c` ~:1955) and every frame first goes through |
| 304 | /// libopus's 3 Hz `dc_reject`. The alignment is *exact* — on the reell |
| 305 | /// attack frame (frame 2, 20 ms, LM=3, transient) our first eight band |
| 306 | /// log-energies become |
| 307 | /// 3.4386 4.0055 3.2603 4.5954 1.1790 4.2774 4.7584 3.7169 against |
| 308 | /// libopus's 3.439 4.005 3.260 4.595 1.179 4.277 4.758 3.717, all eight |
| 309 | /// within .0006 (the unaligned encoder is .06-.21 apart). |
| 310 | /// |
| 311 | /// It ships OFF because the 12-row library gate rejects it, and because |
| 312 | /// re-tuning the constants that were fitted on the misaligned spectrum |
| 313 | /// does not rescue it. Against the shipped rows |
| 314 | /// (`lanes/opus-opustr2-r1.sweep.txt`), err_ratio: |
| 315 | /// |
| 316 | /// | arm | better | worse (blocking) | |
| 317 | /// |---|---|---| |
| 318 | /// | delay only (`opus-opusx-r1`) | 7 | nik@64 .708→.800, nik@96 .985→1.763, her@96 1.051→1.292, hein@64 .853→.980, hein@96 .528→1.602 | |
| 319 | /// | delay + `dc_reject` (`opus-opusx2-r1`) | 5 | those, plus dl8a@64 .552→1.074, dl8a@96 .374→1.011 | |
| 320 | /// | + two-pass coarse energy (`-r2`) | 5 | same 7 rows (nik@96 1.809, dl8a@64 1.200) | |
| 321 | /// | + continuous 1.3 `alloc_trim` (`-r3`) | 5 | same 7, and corr worse by >.0005 on 9 rows | |
| 322 | /// | + tf boost k=1.25 (`-r4`) | 5 | same 7 | |
| 323 | /// | + tf boost k=1.5 (`-r5`) | 5 | same 7 | |
| 324 | /// | + two-pass *and* k=1.25, the combined best (`-r7`) | 5 | same 7: nik@64 .773, nik@96 1.801, her@96 1.114, dl8a@64 1.181, dl8a@96 1.014, hein@64 .977, hein@96 1.398 | |
| 325 | /// | + the whole libopus tonality analysis and its `alloc_trim`/`compute_vbr` consumers (`opus-opustonal-r4`) | 5 | same 7: nik@64 1.014, nik@96 1.842, her@96 1.217, dl8a@64 1.162, dl8a@96 .988, hein@64 .971, hein@96 1.514 | |
| 326 | /// |
| 327 | /// The best aligned arm on the KEEP rule is the delay alone without |
| 328 | /// `dc_reject` (5 rows worse); every arm that adds `dc_reject` puts dl8a |
| 329 | /// in the blocking set too. |
| 330 | /// |
| 331 | /// The last row is the one that was expected to rescue this: libopus's |
| 332 | /// actual operating point is the aligned spectrum *with* `analysis->valid` |
| 333 | /// true, and running the real analysis (`crates/ec-opus/src/analysis.rs`, |
| 334 | /// `music_prob` matching a patched-libopus trace to .001) moves reell@64 |
| 335 | /// 2.697→1.865, reell@96 4.499→3.986, reelo@64 1.510→1.123 and her@64 |
| 336 | /// 1.103→.952 — the largest movement any arm has produced on those rows — |
| 337 | /// and still leaves the same seven rows worse. |
| 338 | /// |
| 339 | /// The blocking set (nik, her@96, dl8a, hein) is the same in every arm and |
| 340 | /// no arm moves any of those rows back towards its shipped value, so the |
| 341 | /// misfit is not one of the swept constants. Turning this on also costs |
| 342 | /// 4 ms of algorithmic delay: [`Encoder::look_ahead`] for a CELT frame |
| 343 | /// becomes 312, not 120, and the Ogg pre-skip must follow it. |
| 344 | pub fn set_libopus_input_alignment(&mut self, on: bool) { |
| 345 | self.align_input = on; |
| 346 | self.celt.set_align_input(on); |
| 347 | self.filter = InputFilter::new(); |
| 348 | } |
| 349 | |
| 350 | /// Forces the coded bandwidth; [`None`] (the default) picks it from the |
| 351 | /// bitrate, the application and the input's Nyquist. |
| 352 | pub fn set_bandwidth(&mut self, bandwidth: Option<Bandwidth>) { |
| 353 | self.bandwidth = bandwidth; |
| 354 | } |
| 355 | |
| 356 | /// Target bitrate in bits per second for the whole packet stream, |
| 357 | /// including the packet headers. Clamped to 500..=510000. |
| 358 | pub fn set_bitrate(&mut self, bps: u32) { |
| 359 | self.bitrate = bps.clamp(500, 510_000); |
| 360 | } |
| 361 | |
| 362 | /// OPUS_SET_INBAND_FEC: code LBRR (in-band FEC) when the loss rate and bitrate justify it; prefers SILK/hybrid over CELT under loss. |
| 363 | pub fn set_inband_fec(&mut self, on: bool) { |
| 364 | self.inband_fec = on; |
| 365 | } |
| 366 | |
| 367 | /// OPUS_SET_PACKET_LOSS_PERC: expected packet loss, 0..=100 (clamped). |
| 368 | pub fn set_packet_loss_perc(&mut self, perc: u8) { |
| 369 | self.packet_loss_perc = perc.min(100); |
| 370 | } |
| 371 | |
| 372 | /// OPUS_SET_DTX: send TOC-only packets during silence/inactivity (after 200 ms), refreshing every 400 ms. |
| 373 | pub fn set_dtx(&mut self, on: bool) { |
| 374 | self.use_dtx = on; |
| 375 | } |
| 376 | |
| 377 | /// libopus's peak signal energy tracker, run on every frame after the analysis. |
| 378 | fn track_peak(&mut self, pcm: &[f32], frame_size: usize) { |
| 379 | let n = frame_size * self.channels; |
| 380 | if pcm.iter().take(n).all(|x| x.abs() <= DTX_SILENCE) { |
| 381 | return; |
| 382 | } |
| 383 | if !self.info.valid || self.info.activity_probability > DTX_ACTIVITY_THRESHOLD { |
| 384 | let energy = pcm.iter().take(n).map(|x| x * x).sum::<f32>() / n as f32; |
| 385 | self.peak_signal_energy = (0.999 * self.peak_signal_energy).max(energy); |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | /// The `activity` libopus hands `silk_Encode`: 0/1 from the analysis, |
| 390 | /// -1 (`VAD_NO_DECISION`) without it. |
| 391 | fn silk_activity(&self, pcm: &[f32], frame_size: usize) -> i32 { |
| 392 | let n = frame_size * self.channels; |
| 393 | if pcm.iter().take(n).all(|x| x.abs() <= DTX_SILENCE) { |
| 394 | return 0; |
| 395 | } |
| 396 | if !self.info.valid { |
| 397 | return -1; |
| 398 | } |
| 399 | let energy = pcm.iter().take(n).map(|x| x * x).sum::<f32>() / n as f32; |
| 400 | i32::from( |
| 401 | self.info.activity_probability >= DTX_ACTIVITY_THRESHOLD |
| 402 | || self.peak_signal_energy < DTX_PSEUDO_SNR_THRESHOLD * energy, |
| 403 | ) |
| 404 | } |
| 405 | |
| 406 | /// libopus `decide_dtx_mode` plus the activity test of `opus_encode_native` |
| 407 | /// for one frame: true when this frame's packet is a DTX one. |
| 408 | fn dtx_frame(&mut self, pcm: &[f32], frame_size: usize) -> bool { |
| 409 | if !self.use_dtx { |
| 410 | return false; |
| 411 | } |
| 412 | let n = frame_size * self.channels; |
| 413 | let energy = pcm.iter().take(n).map(|x| x * x).sum::<f32>() / n as f32; |
| 414 | let is_silence = pcm.iter().all(|x| x.abs() <= DTX_SILENCE); |
| 415 | let (valid, prob) = (self.info.valid, self.info.activity_probability); |
| 416 | let active = if is_silence { |
| 417 | false |
| 418 | } else if valid { |
| 419 | prob >= DTX_ACTIVITY_THRESHOLD |
| 420 | || self.peak_signal_energy < DTX_PSEUDO_SNR_THRESHOLD * energy |
| 421 | } else { |
| 422 | true |
| 423 | }; |
| 424 | if active { |
| 425 | self.nb_no_activity_ms_q1 = 0; |
| 426 | return false; |
| 427 | } |
| 428 | self.nb_no_activity_ms_q1 += 2 * 1000 * frame_size as i32 / self.sample_rate as i32; |
| 429 | if self.nb_no_activity_ms_q1 > DTX_START_Q1 { |
| 430 | if self.nb_no_activity_ms_q1 <= DTX_END_Q1 { |
| 431 | return true; |
| 432 | } |
| 433 | self.nb_no_activity_ms_q1 = DTX_START_Q1; |
| 434 | } |
| 435 | false |
| 436 | } |
| 437 | |
| 438 | /// Current target bitrate. |
| 439 | pub fn bitrate(&self) -> u32 { |
| 440 | self.bitrate |
| 441 | } |
| 442 | |
| 443 | /// Switches between CBR (default, every packet the target size) and |
| 444 | /// constrained VBR (packets vary, a reservoir holds the average to the |
| 445 | /// target). |
| 446 | pub fn set_vbr_constrained(&mut self, vbr: bool) { |
| 447 | self.vbr = vbr; |
| 448 | } |
| 449 | |
| 450 | /// The range coder state after the last packet — the same value RFC 6716 |
| 451 | /// test vectors carry, and what a conformant decoder's `final_range` |
| 452 | /// must equal after decoding that packet. |
| 453 | pub fn final_range(&self) -> u32 { |
| 454 | self.final_range |
| 455 | } |
| 456 | |
| 457 | /// Per-frame CELT diagnostics from the most recent [`encode_float`] call. |
| 458 | /// Intended for the reelm@64k dropout investigation; the fields are only |
| 459 | /// meaningful when the last frame was coded as pure CELT (the path every |
| 460 | /// fullband Audio frame at 64 kbps stereo takes). |
| 461 | /// |
| 462 | /// [`encode_float`]: Encoder::encode_float |
| 463 | pub fn last_celt_diag(&self) -> &crate::celt_enc::CeltFrameDiag { |
| 464 | self.celt.last_diag() |
| 465 | } |
| 466 | |
| 467 | /// Drops all inter-frame state; the next packet starts like the first. |
| 468 | pub fn reset(&mut self) { |
| 469 | self.celt.reset(); |
| 470 | self.silk = None; |
| 471 | self.filter = InputFilter::new(); |
| 472 | self.final_range = 0; |
| 473 | self.analysis.reset(); |
| 474 | self.info = AnalysisInfo::default(); |
| 475 | self.lbrr_coded = false; |
| 476 | self.fec_bandwidth = None; |
| 477 | self.last_silk = None; |
| 478 | self.nb_no_activity_ms_q1 = 0; |
| 479 | self.peak_signal_energy = 0.0; |
| 480 | } |
| 481 | |
| 482 | /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) |
| 483 | /// calls for SILK, and if so, which SILK internal sample rate in kHz. |
| 484 | /// `None` means CELT or Hybrid (`hybrid_choice` tells those apart). |
| 485 | /// |
| 486 | /// Ports libopus's mode decision: SILK when `equiv_rate` is below the |
| 487 | /// voice/music-blended mode threshold (`opus_encoder.c` ~1900), with the |
| 488 | /// bandwidth from the threshold walk. SILK only codes up to Wide; a |
| 489 | /// SuperWide/Full result is Hybrid (10/20 ms) or, for 40/60 ms frames |
| 490 | /// that Hybrid cannot carry, SILK capped at Wide. |
| 491 | fn wants_silk(&self, frame_48k: usize) -> Option<usize> { |
| 492 | match self.mode { |
| 493 | Some(Mode::Celt) | Some(Mode::Hybrid) => None, |
| 494 | Some(Mode::Silk) => { |
| 495 | let bw = self |
| 496 | .fec_bandwidth |
| 497 | .or(self.bandwidth) |
| 498 | .unwrap_or_else(|| self.auto_bandwidth()); |
| 499 | Some(silk_fs_khz(bw)) |
| 500 | } |
| 501 | None => { |
| 502 | let equiv = self.equiv_rate(frame_48k); |
| 503 | let ve = self.voice_est(); |
| 504 | if !self.auto_silk(equiv, ve) { |
| 505 | return None; |
| 506 | } |
| 507 | let bw = self.auto_mode_bandwidth(equiv, ve); |
| 508 | // 40/60 ms frames are SILK-only (Hybrid supports 10/20 ms): |
| 509 | // cap at Wide so a high equiv rate does not fall through to |
| 510 | // an impossible CELT 40/60 ms packet. |
| 511 | let bw = if matches!(frame_48k, 1920 | 2880) { |
| 512 | bw.min(Bandwidth::Wide) |
| 513 | } else { |
| 514 | bw |
| 515 | }; |
| 516 | if bw > Bandwidth::Wide { |
| 517 | None // Hybrid territory — see hybrid_choice |
| 518 | } else { |
| 519 | Some(silk_fs_khz(bw)) |
| 520 | } |
| 521 | } |
| 522 | } |
| 523 | } |
| 524 | |
| 525 | /// The SILK/hybrid bandwidth in auto mode; libopus keeps CBR below |
| 526 | /// 15 kb/s out of hybrid by capping it at Wide. |
| 527 | fn auto_mode_bandwidth(&self, equiv: i32, ve: i32) -> Bandwidth { |
| 528 | let bw = self |
| 529 | .fec_bandwidth |
| 530 | .or(self.bandwidth) |
| 531 | .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)); |
| 532 | if !self.vbr && self.bitrate < 15000 { |
| 533 | bw.min(Bandwidth::Wide) |
| 534 | } else { |
| 535 | bw |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | /// `wants_silk` narrowed to what this encoder can actually code as SILK: |
| 540 | /// mono 10/20/40/60 ms, stereo 10/20 ms directly, or stereo 40/60 ms as |
| 541 | /// code-3 packets of 20 ms SILK frames. |
| 542 | fn silk_choice(&self, frame_48k: usize) -> Option<usize> { |
| 543 | let fs_khz = self.wants_silk(frame_48k)?; |
| 544 | if !matches!(frame_48k, 480 | 960 | 1920 | 2880) { |
| 545 | return None; |
| 546 | } |
| 547 | Some(fs_khz) |
| 548 | } |
| 549 | |
| 550 | /// Whether this frame goes out as a hybrid packet, and at which of the two |
| 551 | /// hybrid bandwidths. Automatic: Hybrid is SILK mode (equiv below the mode |
| 552 | /// threshold) whose bandwidth walk lands on SuperWide/Full — SILK alone |
| 553 | /// cannot code above Wide, so CELT carries the top bands. 10 or 20 ms |
| 554 | /// only (Hybrid has no 40/60 ms config). Forced Hybrid codes at least SWB. |
| 555 | fn hybrid_choice(&self, frame_48k: usize) -> Option<Bandwidth> { |
| 556 | if matches!(self.mode, Some(Mode::Silk) | Some(Mode::Celt)) { |
| 557 | return None; |
| 558 | } |
| 559 | if !matches!(frame_48k, 480 | 960) { |
| 560 | return None; |
| 561 | } |
| 562 | let equiv = self.equiv_rate(frame_48k); |
| 563 | let ve = self.voice_est(); |
| 564 | if self.mode.is_none() && !self.auto_silk(equiv, ve) { |
| 565 | return None; |
| 566 | } |
| 567 | let bw = if self.mode.is_none() { |
| 568 | self.auto_mode_bandwidth(equiv, ve) |
| 569 | } else { |
| 570 | self.fec_bandwidth |
| 571 | .or(self.bandwidth) |
| 572 | .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)) |
| 573 | }; |
| 574 | match bw { |
| 575 | Bandwidth::SuperWide | Bandwidth::Full => Some(bw), |
| 576 | // A forced Hybrid with a narrow/medium/wide bandwidth still codes |
| 577 | // at least SWB — Hybrid has no narrower configuration. |
| 578 | _ if self.mode == Some(Mode::Hybrid) => Some(Bandwidth::SuperWide), |
| 579 | _ => None, |
| 580 | } |
| 581 | } |
| 582 | |
| 583 | fn write_frame_len(out: &mut [u8], pos: &mut usize, len: usize) -> Result<()> { |
| 584 | if len > MAX_FRAME_BYTES { |
| 585 | return Err(Error::corrupt(format!( |
| 586 | "opus encode: frame payload of {len} bytes exceeds {MAX_FRAME_BYTES}" |
| 587 | ))); |
| 588 | } |
| 589 | if len < 252 { |
| 590 | out[*pos] = len as u8; |
| 591 | *pos += 1; |
| 592 | } else { |
| 593 | let b0 = 252 + ((len - 252) & 3); |
| 594 | out[*pos] = b0 as u8; |
| 595 | out[*pos + 1] = ((len - b0) / 4) as u8; |
| 596 | *pos += 2; |
| 597 | } |
| 598 | Ok(()) |
| 599 | } |
| 600 | |
| 601 | /// The CBR packet budget for a `frame_48k`-sample frame, in payload bytes, |
| 602 | /// by the figure the CELT path uses; `None` under constrained VBR (D2b). |
| 603 | fn packet_budget(&self, frame_48k: usize, cap: usize) -> Option<usize> { |
| 604 | if self.vbr { |
| 605 | return None; |
| 606 | } |
| 607 | let b = ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize; |
| 608 | Some(b.saturating_sub(1).max(2).min(cap)) |
| 609 | } |
| 610 | |
| 611 | /// The `silk_mode` fields libopus sets for one frame; `max_data_bytes` |
| 612 | /// counts the TOC byte. |
| 613 | fn silk_frame( |
| 614 | &self, |
| 615 | max_data_bytes: usize, |
| 616 | internal_khz: usize, |
| 617 | hybrid: bool, |
| 618 | swb: bool, |
| 619 | ) -> SilkFrame { |
| 620 | SilkFrame { |
| 621 | bitrate: self.bitrate as i32, |
| 622 | max_data_bytes, |
| 623 | vbr: self.vbr, |
| 624 | hybrid, |
| 625 | swb, |
| 626 | internal_khz: internal_khz as i32, |
| 627 | stream_channels: self.channels, |
| 628 | fec: self.inband_fec, |
| 629 | lbrr_coded: self.lbrr_coded, |
| 630 | loss_perc: i32::from(self.packet_loss_perc), |
| 631 | complexity: DEFAULT_COMPLEXITY, |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | /// The SILK layer, reset when the previous frame was CELT-only (libopus |
| 636 | /// re-inits `silk_enc` on a CELT to SILK/hybrid transition). |
| 637 | fn silk_layer(&mut self) -> &mut SilkLayer { |
| 638 | let (fs, ch, fresh) = (self.sample_rate, self.channels, self.last_silk.is_none()); |
| 639 | let silk = self |
| 640 | .silk |
| 641 | .get_or_insert_with(|| Box::new(SilkLayer::new(fs, ch))); |
| 642 | if fresh { |
| 643 | silk.reset(); |
| 644 | } |
| 645 | silk |
| 646 | } |
| 647 | |
| 648 | /// Picks SILK or CELT for one frame and encodes it, returning the TOC |
| 649 | /// byte and the payload bytes (excluding TOC), borrowed from scratch |
| 650 | /// space owned by `self` — no allocation on the steady-state path. |
| 651 | /// `cap` bounds the packet; under CBR a SILK packet is held to the same budget |
| 652 | /// as a CELT one (D2b). |
| 653 | fn encode_toc_and_payload( |
| 654 | &mut self, |
| 655 | pcm: &[f32], |
| 656 | frame_size: usize, |
| 657 | cap: usize, |
| 658 | ) -> Result<(u8, &[u8])> { |
| 659 | let frame_48k = frame_size * self.upsample; |
| 660 | self.fec_bandwidth = None; |
| 661 | if frame_48k > 960 && self.silk_choice(frame_48k).is_none() { |
| 662 | return self.encode_multiframe(pcm, frame_size, cap); |
| 663 | } |
| 664 | // libopus `opus_encode_native`: `run_analysis()` runs on the API frame |
| 665 | // before the mode/bandwidth decisions, so the estimator state advances |
| 666 | // on every frame, SILK ones included. 24 is libopus's float-API |
| 667 | // `lsb_depth` default. |
| 668 | self.info = if self.analysis_on { |
| 669 | self.analysis.run(pcm, frame_size, self.channels, 24) |
| 670 | } else { |
| 671 | AnalysisInfo::default() |
| 672 | }; |
| 673 | self.track_peak(pcm, frame_size); |
| 674 | let (fec, fec_bw) = self.fec_for(frame_48k); |
| 675 | self.lbrr_coded = fec; |
| 676 | self.fec_bandwidth = fec_bw; |
| 677 | let silk_khz = self.silk_choice(frame_48k); |
| 678 | let hybrid_bw = if silk_khz.is_none() { |
| 679 | self.hybrid_choice(frame_48k) |
| 680 | } else { |
| 681 | None |
| 682 | }; |
| 683 | let mut buf = std::mem::take(&mut self.hp_buf); |
| 684 | self.filter_input( |
| 685 | pcm, |
| 686 | frame_size, |
| 687 | silk_khz.is_none() && hybrid_bw.is_none(), |
| 688 | &mut buf, |
| 689 | ); |
| 690 | let r = self.encode_mode(pcm, &buf, frame_size, cap, silk_khz, hybrid_bw); |
| 691 | self.hp_buf = buf; |
| 692 | let (toc, payload) = r?; |
| 693 | Ok(( |
| 694 | toc, |
| 695 | match payload { |
| 696 | Payload::Range(n) => &self.range.data()[..n], |
| 697 | Payload::Silk(n) => &self.silk_buf[..n], |
| 698 | }, |
| 699 | )) |
| 700 | } |
| 701 | |
| 702 | /// libopus `opus_encode_frame_native`'s input filter: `hp_cutoff` for |
| 703 | /// VoIP, its cutoff following SILK's estimate unless the frame is |
| 704 | /// CELT-only; otherwise the 3 Hz `dc_reject` (only with the CELT input |
| 705 | /// alignment on, the libopus default). |
| 706 | fn filter_input( |
| 707 | &mut self, |
| 708 | pcm: &[f32], |
| 709 | frame_size: usize, |
| 710 | celt_only: bool, |
| 711 | out: &mut Vec<f32>, |
| 712 | ) { |
| 713 | let n = frame_size * self.channels; |
| 714 | out.clear(); |
| 715 | out.resize(n, 0.0); |
| 716 | let fs = self.sample_rate as i32; |
| 717 | if self.application == Application::Voip { |
| 718 | let smth1 = match (&self.silk, celt_only) { |
| 719 | (Some(silk), false) => silk.hp_smth1_q15(), |
| 720 | _ => hp_min_smth1_q15(), |
| 721 | }; |
| 722 | self.filter |
| 723 | .hp_cutoff(&pcm[..n], out, smth1, self.channels, fs); |
| 724 | } else if self.align_input { |
| 725 | self.filter.dc_reject(&pcm[..n], out, self.channels, fs); |
| 726 | } else { |
| 727 | out.copy_from_slice(&pcm[..n]); |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | fn encode_mode( |
| 732 | &mut self, |
| 733 | raw: &[f32], |
| 734 | pcm: &[f32], |
| 735 | frame_size: usize, |
| 736 | cap: usize, |
| 737 | silk_khz: Option<usize>, |
| 738 | hybrid_bw: Option<Bandwidth>, |
| 739 | ) -> Result<(u8, Payload)> { |
| 740 | let frame_48k = frame_size * self.upsample; |
| 741 | if let Some(fs_khz) = silk_khz { |
| 742 | let max_data_bytes = self |
| 743 | .packet_budget(frame_48k, cap) |
| 744 | .unwrap_or(cap) |
| 745 | .min(MAX_FRAME_BYTES) |
| 746 | + 1; |
| 747 | let f = self.silk_frame(max_data_bytes, fs_khz, false, false); |
| 748 | let activity = self.silk_activity(raw, frame_size); |
| 749 | self.range.reset(max_data_bytes - 1); |
| 750 | let mut range = std::mem::take(&mut self.range); |
| 751 | let (_, khz) = self |
| 752 | .silk_layer() |
| 753 | .encode(pcm, frame_size, &f, activity, &mut range); |
| 754 | self.range = range; |
| 755 | let mut len = (self.range.tell() as usize).div_ceil(8); |
| 756 | self.range.done(); |
| 757 | while len > 2 && self.range.data()[len - 1] == 0 { |
| 758 | len -= 1; |
| 759 | } |
| 760 | self.final_range = self.range.range(); |
| 761 | self.last_silk = Some(khz as u8); |
| 762 | let base = match khz { |
| 763 | 8 => 0u8, |
| 764 | 12 => 4, |
| 765 | _ => 8, |
| 766 | }; |
| 767 | let duration = match frame_48k { |
| 768 | 480 => 0u8, |
| 769 | 960 => 1, |
| 770 | 1920 => 2, |
| 771 | _ => 3, |
| 772 | }; |
| 773 | let toc = ((base + duration) << 3) | (u8::from(self.channels == 2) << 2); |
| 774 | if !self.vbr && len + 1 < max_data_bytes { |
| 775 | let pad_amount = max_data_bytes - (len + 2); |
| 776 | let buf = &mut self.silk_buf[..]; |
| 777 | buf[0] = 1; |
| 778 | let mut pos = 1; |
| 779 | if pad_amount > 0 { |
| 780 | buf[0] |= 0x40; |
| 781 | let nb_255s = (pad_amount - 1) / 255; |
| 782 | buf[1..1 + nb_255s].fill(255); |
| 783 | buf[1 + nb_255s] = (pad_amount - 255 * nb_255s - 1) as u8; |
| 784 | pos += nb_255s + 1; |
| 785 | } |
| 786 | buf[pos..pos + len].copy_from_slice(&self.range.data()[..len]); |
| 787 | buf[pos + len..max_data_bytes - 1].fill(0); |
| 788 | return Ok((toc | 3, Payload::Silk(max_data_bytes - 1))); |
| 789 | } |
| 790 | return Ok((toc, Payload::Range(len))); |
| 791 | } |
| 792 | if let Some(bandwidth) = hybrid_bw { |
| 793 | let n = self.encode_hybrid(raw, pcm, frame_size, bandwidth, cap)?; |
| 794 | let config = 12 |
| 795 | + if bandwidth == Bandwidth::Full { 2u8 } else { 0 } |
| 796 | + if frame_48k == 960 { 1 } else { 0 }; |
| 797 | return Ok(( |
| 798 | (config << 3) | (u8::from(self.channels == 2) << 2), |
| 799 | Payload::Range(n), |
| 800 | )); |
| 801 | } |
| 802 | self.last_silk = None; |
| 803 | let (toc, frame_48k, end) = self.toc(frame_size)?; |
| 804 | let n = self.encode_frame(pcm, frame_48k, end, cap)?; |
| 805 | Ok((toc, Payload::Range(n))) |
| 806 | } |
| 807 | |
| 808 | fn encode_multiframe( |
| 809 | &mut self, |
| 810 | pcm: &[f32], |
| 811 | frame_size: usize, |
| 812 | cap: usize, |
| 813 | ) -> Result<(u8, &[u8])> { |
| 814 | let count = frame_size * self.upsample / 960; |
| 815 | if !matches!(count, 2 | 3) || frame_size * self.upsample != count * 960 { |
| 816 | return Err(Error::unsupported( |
| 817 | format!( |
| 818 | "opus frame of {frame_size} samples at {} Hz", |
| 819 | self.sample_rate |
| 820 | ), |
| 821 | "frames are 2.5, 5, 10, 20, 40 or 60 ms", |
| 822 | )); |
| 823 | } |
| 824 | let sub = frame_size / count; |
| 825 | let (mode, bandwidth) = (self.mode, self.bandwidth); |
| 826 | self.mode = Some(if self.hybrid_choice(960).is_some() { |
| 827 | Mode::Hybrid |
| 828 | } else { |
| 829 | Mode::Celt |
| 830 | }); |
| 831 | let per = cap.saturating_sub(1 + 2 * (count - 1)) / count; |
| 832 | let mut frames: Vec<Vec<u8>> = Vec::with_capacity(count); |
| 833 | let mut toc = 0u8; |
| 834 | let mut result = Ok(()); |
| 835 | for i in 0..count { |
| 836 | let chunk = &pcm[i * sub * self.channels..(i + 1) * sub * self.channels]; |
| 837 | match self.encode_toc_and_payload(chunk, sub, per) { |
| 838 | Ok((t, payload)) => { |
| 839 | frames.push(payload.to_vec()); |
| 840 | if i == 0 { |
| 841 | toc = t; |
| 842 | self.bandwidth = Some(toc_bandwidth(t)); |
| 843 | } |
| 844 | } |
| 845 | Err(e) => { |
| 846 | result = Err(e); |
| 847 | break; |
| 848 | } |
| 849 | } |
| 850 | } |
| 851 | self.mode = mode; |
| 852 | self.bandwidth = bandwidth; |
| 853 | result?; |
| 854 | let mut pos = 0usize; |
| 855 | self.silk_buf[pos] = 0x80 | count as u8; |
| 856 | pos += 1; |
| 857 | for frame in &frames[..count - 1] { |
| 858 | Self::write_frame_len(&mut self.silk_buf[..], &mut pos, frame.len())?; |
| 859 | } |
| 860 | for frame in &frames { |
| 861 | if pos + frame.len() > self.silk_buf.len() { |
| 862 | return Err(Error::corrupt( |
| 863 | "opus encode: multi-frame packet overflows its buffer", |
| 864 | )); |
| 865 | } |
| 866 | self.silk_buf[pos..pos + frame.len()].copy_from_slice(frame); |
| 867 | pos += frame.len(); |
| 868 | } |
| 869 | Ok(((toc & !3) | 3, &self.silk_buf[..pos])) |
| 870 | } |
| 871 | |
| 872 | /// The TOC byte, the frame size in 48 kHz samples and the CELT end band |
| 873 | /// for a frame of `frame_size` input samples per channel. |
| 874 | fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> { |
| 875 | let frame_48k = frame_size * self.upsample; |
| 876 | let fs_idx: u8 = match frame_48k { |
| 877 | 120 => 0, |
| 878 | 240 => 1, |
| 879 | 480 => 2, |
| 880 | 960 => 3, |
| 881 | _ => { |
| 882 | return Err(Error::unsupported( |
| 883 | format!( |
| 884 | "opus frame of {frame_size} samples at {} Hz", |
| 885 | self.sample_rate |
| 886 | ), |
| 887 | "CELT frames are 2.5, 5, 10 or 20 ms", |
| 888 | )); |
| 889 | } |
| 890 | }; |
| 891 | let bandwidth = self.bandwidth.unwrap_or_else(|| { |
| 892 | self.auto_bandwidth_at( |
| 893 | self.equiv_rate_for(frame_48k, Some(Mode::Celt)), |
| 894 | self.voice_est(), |
| 895 | ) |
| 896 | }); |
| 897 | let bw_idx: u8 = match bandwidth { |
| 898 | Bandwidth::Narrow => 0, |
| 899 | // CELT has no mediumband configuration; the next one up covers it. |
| 900 | Bandwidth::Medium | Bandwidth::Wide => 1, |
| 901 | Bandwidth::SuperWide => 2, |
| 902 | Bandwidth::Full => 3, |
| 903 | }; |
| 904 | let config = 16 + 4 * bw_idx + fs_idx; |
| 905 | Ok(( |
| 906 | (config << 3) | (u8::from(self.channels == 2) << 2), |
| 907 | frame_48k, |
| 908 | bandwidth.celt_end_band(), |
| 909 | )) |
| 910 | } |
| 911 | |
| 912 | /// Bandwidth from the bitrate — libopus's threshold walk, 20 ms default. |
| 913 | /// Kept for the forced-mode paths and unit tests; the dispatch functions |
| 914 | /// pass the actual frame's equiv rate to [`auto_bandwidth_at`]. |
| 915 | fn auto_bandwidth(&self) -> Bandwidth { |
| 916 | self.auto_bandwidth_at(self.equiv_rate(960), self.voice_est()) |
| 917 | } |
| 918 | |
| 919 | /// The equivalent rate a frame is coded at, porting libopus |
| 920 | /// `compute_equiv_rate` (`opus_encoder.c:1021`): the bitrate, minus the |
| 921 | /// per-frame overhead for sub-20 ms frames, minus the CBR headroom, times |
| 922 | /// the complexity multiplier. Loss is 0 and complexity ≥ 5, so the |
| 923 | /// are both no-ops. |
| 924 | fn equiv_rate(&self, frame_48k: usize) -> i32 { |
| 925 | self.equiv_rate_for(frame_48k, None) |
| 926 | } |
| 927 | |
| 928 | fn equiv_rate_for(&self, frame_48k: usize, mode: Option<Mode>) -> i32 { |
| 929 | let frame_rate = 48000 / frame_48k as i32; |
| 930 | let mut equiv = self.bitrate as i32; |
| 931 | if frame_rate > 50 { |
| 932 | equiv -= (40 * self.channels as i32 + 20) * (frame_rate - 50); |
| 933 | } |
| 934 | if !self.vbr { |
| 935 | equiv -= equiv / 12; |
| 936 | } |
| 937 | equiv = equiv * (90 + DEFAULT_COMPLEXITY) / 100; |
| 938 | let loss = self.packet_loss_perc as i32; |
| 939 | match mode { |
| 940 | Some(Mode::Silk) | Some(Mode::Hybrid) => equiv -= equiv * loss / (6 * loss + 10), |
| 941 | Some(Mode::Celt) => {} |
| 942 | None => equiv -= equiv * loss / (12 * loss + 20), |
| 943 | } |
| 944 | equiv |
| 945 | } |
| 946 | |
| 947 | fn fec_for(&self, frame_48k: usize) -> (bool, Option<Bandwidth>) { |
| 948 | if !self.inband_fec || self.mode == Some(Mode::Celt) { |
| 949 | return (false, None); |
| 950 | } |
| 951 | if self.mode.is_none() && !self.auto_silk(self.equiv_rate(frame_48k), self.voice_est()) { |
| 952 | return (false, None); |
| 953 | } |
| 954 | let silk_equiv = self.equiv_rate_for(frame_48k, Some(Mode::Silk)); |
| 955 | let ve = self.voice_est(); |
| 956 | let bw = self |
| 957 | .bandwidth |
| 958 | .unwrap_or_else(|| self.auto_bandwidth_at(silk_equiv, ve)); |
| 959 | let (fec, b) = self.decide_fec(bw, silk_equiv); |
| 960 | (fec, (fec && b != bw).then_some(b)) |
| 961 | } |
| 962 | |
| 963 | fn decide_fec(&self, bw: Bandwidth, rate: i32) -> (bool, Bandwidth) { |
| 964 | const FEC_THRESHOLDS: [i32; 10] = [ |
| 965 | 12000, 1000, 14000, 1000, 16000, 1000, 20000, 1000, 22000, 1000, |
| 966 | ]; |
| 967 | const BANDWIDTHS: [Bandwidth; 5] = [ |
| 968 | Bandwidth::Narrow, |
| 969 | Bandwidth::Medium, |
| 970 | Bandwidth::Wide, |
| 971 | Bandwidth::SuperWide, |
| 972 | Bandwidth::Full, |
| 973 | ]; |
| 974 | let loss = self.packet_loss_perc as i32; |
| 975 | if !self.inband_fec || loss == 0 { |
| 976 | return (false, bw); |
| 977 | } |
| 978 | let mut b = BANDWIDTHS.iter().position(|&x| x == bw).unwrap_or(0); |
| 979 | loop { |
| 980 | let mut thres = FEC_THRESHOLDS[2 * b]; |
| 981 | let hyst = FEC_THRESHOLDS[2 * b + 1]; |
| 982 | if self.lbrr_coded { |
| 983 | thres -= hyst; |
| 984 | } else { |
| 985 | thres += hyst; |
| 986 | } |
| 987 | thres = ((thres as i64 * (125 - loss.min(25)) as i64 * 655) >> 16) as i32; |
| 988 | if rate > thres { |
| 989 | return (true, BANDWIDTHS[b]); |
| 990 | } else if loss <= 5 { |
| 991 | return (false, bw); |
| 992 | } else if b > 0 { |
| 993 | b -= 1; |
| 994 | } else { |
| 995 | return (false, bw); |
| 996 | } |
| 997 | } |
| 998 | } |
| 999 | |
| 1000 | /// Voice activity estimate: VoIP → 115, Audio and LowDelay → 48 |
| 1001 | /// (`opus_encoder.c` `tonality_analysis` proxy — no analysis is modelled, |
| 1002 | /// so the application alone decides). |
| 1003 | fn voice_est(&self) -> i32 { |
| 1004 | match self.application { |
| 1005 | Application::Voip => 115, |
| 1006 | _ => 48, |
| 1007 | } |
| 1008 | } |
| 1009 | |
| 1010 | /// Whether the auto mode is SILK: `equiv` below the voice/music-blended |
| 1011 | /// mode threshold (`opus_encoder.c` ~1900). LowDelay is always CELT. |
| 1012 | /// VoIP gets the `+8000` hysteresis/voice bonus libopus applies. |
| 1013 | fn auto_silk(&self, equiv: i32, ve: i32) -> bool { |
| 1014 | if self.application == Application::LowDelay { |
| 1015 | return false; |
| 1016 | } |
| 1017 | if self.inband_fec && self.packet_loss_perc as i32 > (128 - ve) >> 4 { |
| 1018 | return true; |
| 1019 | } |
| 1020 | let threshold = MODE_THRESHOLD_MUSIC |
| 1021 | + ((ve * ve * (MODE_THRESHOLD_VOICE - MODE_THRESHOLD_MUSIC)) >> 14); |
| 1022 | let threshold = if self.application == Application::Voip { |
| 1023 | threshold + 8000 |
| 1024 | } else { |
| 1025 | threshold |
| 1026 | }; |
| 1027 | equiv < threshold |
| 1028 | } |
| 1029 | |
| 1030 | /// Bandwidth from the equivalent rate, porting libopus's `decide_bandwidth` |
| 1031 | /// walk (`opus_encoder.c` ~1660). The voice and music threshold tables are |
| 1032 | /// blended by `ve²`; the walk starts at Full and steps down until the equiv |
| 1033 | /// rate sustains the current bandwidth. The input's own Nyquist clamps the |
| 1034 | /// result — coding above it would code the images the zero-stuffing put |
| 1035 | /// there. |
| 1036 | fn auto_bandwidth_at(&self, equiv: i32, ve: i32) -> Bandwidth { |
| 1037 | let (voice, music) = if self.channels == 2 { |
| 1038 | (&STEREO_VOICE_BW, &STEREO_MUSIC_BW) |
| 1039 | } else { |
| 1040 | (&MONO_VOICE_BW, &MONO_MUSIC_BW) |
| 1041 | }; |
| 1042 | let ve2 = ve * ve; |
| 1043 | // Pair i is the boundary between bandwidth i and i+1: |
| 1044 | // 0: NB↔MB, 1: MB↔WB, 2: WB↔SWB, 3: SWB↔FB. |
| 1045 | let thresh = |i: usize| music[2 * i] + ((ve2 * (voice[2 * i] - music[2 * i])) >> 14); |
| 1046 | const BWS: [Bandwidth; 5] = [ |
| 1047 | Bandwidth::Narrow, |
| 1048 | Bandwidth::Medium, |
| 1049 | Bandwidth::Wide, |
| 1050 | Bandwidth::SuperWide, |
| 1051 | Bandwidth::Full, |
| 1052 | ]; |
| 1053 | let mut idx = 4; // Full |
| 1054 | while idx > 0 && equiv < thresh(idx - 1) { |
| 1055 | idx -= 1; |
| 1056 | } |
| 1057 | let ceiling = match self.sample_rate { |
| 1058 | 48000 => Bandwidth::Full, |
| 1059 | 24000 => Bandwidth::SuperWide, |
| 1060 | 16000 => Bandwidth::Wide, |
| 1061 | 12000 => Bandwidth::Medium, |
| 1062 | _ => Bandwidth::Narrow, |
| 1063 | }; |
| 1064 | let bw = BWS[idx].min(ceiling); |
| 1065 | match self.detected_bandwidth(equiv, !self.auto_silk(equiv, ve)) { |
| 1066 | Some(d) => bw.min(d), |
| 1067 | None => bw, |
| 1068 | } |
| 1069 | } |
| 1070 | |
| 1071 | /// libopus `opus_encoder.c:1278-1305`: the tonality analysis's own |
| 1072 | /// bandwidth estimate as an Opus bandwidth, raised by the conservative |
| 1073 | /// floor of `opus_encoder.c:1652-1674` (which depends on `equiv_rate` per |
| 1074 | /// channel and on whether the frame is CELT-only) before it is allowed to |
| 1075 | /// lower the coded bandwidth. `None` when the analysis did not run, which |
| 1076 | /// is libopus's `st->detected_bandwidth == 0`. |
| 1077 | /// |
| 1078 | /// Only the caller's automatic path consults this — libopus guards the |
| 1079 | /// clamp with `st->user_bandwidth == OPUS_AUTO`, which is exactly the |
| 1080 | /// `self.bandwidth.is_none()` branch that reaches `auto_bandwidth_at`. |
| 1081 | fn detected_bandwidth(&self, equiv: i32, celt_only: bool) -> Option<Bandwidth> { |
| 1082 | if !self.bw_detect || !self.info.valid { |
| 1083 | return None; |
| 1084 | } |
| 1085 | let detected = match self.info.bandwidth { |
| 1086 | i32::MIN..=12 => Bandwidth::Narrow, |
| 1087 | 13..=14 => Bandwidth::Medium, |
| 1088 | 15..=16 => Bandwidth::Wide, |
| 1089 | 17..=18 => Bandwidth::SuperWide, |
| 1090 | _ => Bandwidth::Full, |
| 1091 | }; |
| 1092 | let ch = self.channels as i32; |
| 1093 | let floor = if celt_only && equiv <= 18000 * ch { |
| 1094 | Bandwidth::Narrow |
| 1095 | } else if celt_only && equiv <= 24000 * ch { |
| 1096 | Bandwidth::Medium |
| 1097 | } else if equiv <= 30000 * ch { |
| 1098 | Bandwidth::Wide |
| 1099 | } else if equiv <= 44000 * ch { |
| 1100 | Bandwidth::SuperWide |
| 1101 | } else { |
| 1102 | Bandwidth::Full |
| 1103 | }; |
| 1104 | Some(detected.max(floor)) |
| 1105 | } |
| 1106 | |
| 1107 | /// Encodes one frame — `frame_size` samples per channel of interleaved |
| 1108 | /// `f32` at the input rate, 2.5, 5, 10 or 20 ms of it — as a code-0 Opus |
| 1109 | /// packet in `out`, returning the packet length. |
| 1110 | pub fn encode_float( |
| 1111 | &mut self, |
| 1112 | pcm: &[f32], |
| 1113 | frame_size: usize, |
| 1114 | out: &mut [u8], |
| 1115 | ) -> Result<usize> { |
| 1116 | match self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1)) { |
| 1117 | Err(e) => Err(e), |
| 1118 | Ok((toc, payload)) => { |
| 1119 | let n = payload.len(); |
| 1120 | let count = payload.first().copied().unwrap_or(0); |
| 1121 | if out.len() < 1 + n { |
| 1122 | Err(Error::corrupt(format!( |
| 1123 | "opus encode: packet needs {} bytes, buffer holds {}", |
| 1124 | 1 + n, |
| 1125 | out.len() |
| 1126 | ))) |
| 1127 | } else { |
| 1128 | out[0] = toc; |
| 1129 | out[1..1 + n].copy_from_slice(payload); |
| 1130 | if self.dtx_frame(pcm, frame_size) { |
| 1131 | self.final_range = 0; |
| 1132 | let (bytes, len) = dtx_packet(toc, count, false); |
| 1133 | if out.len() < len { |
| 1134 | Err(Error::corrupt("opus encode: DTX packet buffer too small")) |
| 1135 | } else { |
| 1136 | out[..len].copy_from_slice(&bytes[..len]); |
| 1137 | Ok(len) |
| 1138 | } |
| 1139 | } else { |
| 1140 | Ok(1 + n) |
| 1141 | } |
| 1142 | } |
| 1143 | } |
| 1144 | } |
| 1145 | } |
| 1146 | |
| 1147 | /// [`Encoder::encode_float`] from 16-bit samples. |
| 1148 | pub fn encode(&mut self, pcm: &[i16], frame_size: usize, out: &mut [u8]) -> Result<usize> { |
| 1149 | let float: Vec<f32> = pcm.iter().map(|&v| v as f32 * (1.0 / 32768.0)).collect(); |
| 1150 | self.encode_float(&float, frame_size, out) |
| 1151 | } |
| 1152 | |
| 1153 | /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716 |
| 1154 | /// Appendix B: TOC, an explicit frame length, then the frame. This is |
| 1155 | /// what every stream but the last uses inside a multistream packet. |
| 1156 | pub fn encode_self_delimited( |
| 1157 | &mut self, |
| 1158 | pcm: &[f32], |
| 1159 | frame_size: usize, |
| 1160 | out: &mut [u8], |
| 1161 | ) -> Result<usize> { |
| 1162 | match self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3)) { |
| 1163 | Err(e) => Err(e), |
| 1164 | Ok((toc, payload)) => { |
| 1165 | let count = payload.first().copied().unwrap_or(0); |
| 1166 | let (head, last) = if toc & 3 == 3 { |
| 1167 | let count = usize::from(payload[0] & 0x3F); |
| 1168 | let mut pos = 1; |
| 1169 | let mut sum = 0; |
| 1170 | for _ in 1..count { |
| 1171 | let b0 = usize::from(payload[pos]); |
| 1172 | let (len, used) = if b0 < 252 { |
| 1173 | (b0, 1) |
| 1174 | } else { |
| 1175 | (b0 + 4 * usize::from(payload[pos + 1]), 2) |
| 1176 | }; |
| 1177 | sum += len; |
| 1178 | pos += used; |
| 1179 | } |
| 1180 | (pos, payload.len() - pos - sum) |
| 1181 | } else { |
| 1182 | (0, payload.len()) |
| 1183 | }; |
| 1184 | let mut len = [0u8; 2]; |
| 1185 | let mut len_bytes = 0; |
| 1186 | let r = Self::write_frame_len(&mut len, &mut len_bytes, last); |
| 1187 | let total = 1 + len_bytes + payload.len(); |
| 1188 | match r { |
| 1189 | Err(e) => Err(e), |
| 1190 | Ok(()) if out.len() < total => Err(Error::corrupt(format!( |
| 1191 | "opus encode: self-delimited packet needs {total} bytes, buffer holds {}", |
| 1192 | out.len() |
| 1193 | ))), |
| 1194 | Ok(()) => { |
| 1195 | out[0] = toc; |
| 1196 | out[1..1 + head].copy_from_slice(&payload[..head]); |
| 1197 | out[1 + head..1 + head + len_bytes].copy_from_slice(&len[..len_bytes]); |
| 1198 | out[1 + head + len_bytes..total].copy_from_slice(&payload[head..]); |
| 1199 | if self.dtx_frame(pcm, frame_size) { |
| 1200 | self.final_range = 0; |
| 1201 | let (bytes, len) = dtx_packet(toc, count, true); |
| 1202 | if out.len() < len { |
| 1203 | Err(Error::corrupt("opus encode: DTX packet buffer too small")) |
| 1204 | } else { |
| 1205 | out[..len].copy_from_slice(&bytes[..len]); |
| 1206 | Ok(len) |
| 1207 | } |
| 1208 | } else { |
| 1209 | Ok(total) |
| 1210 | } |
| 1211 | } |
| 1212 | } |
| 1213 | } |
| 1214 | } |
| 1215 | } |
| 1216 | |
| 1217 | /// One hybrid frame (10 or 20 ms, mono or stereo, `bandwidth` SWB or FB) |
| 1218 | /// into the internal range coder, returning its byte length: the SILK |
| 1219 | /// layer's symbols (WB, 16 kHz internal), the no-redundancy flag under the decoder's |
| 1220 | /// exact presence rule, then the CELT layer from band 17 in the same |
| 1221 | /// coder. CBR: the packet is the bitrate's size unless SILK alone needs |
| 1222 | /// more, in which case CELT keeps [`HYBRID_CELT_MIN_BYTES`] on top. |
| 1223 | fn encode_hybrid( |
| 1224 | &mut self, |
| 1225 | raw: &[f32], |
| 1226 | pcm: &[f32], |
| 1227 | frame_size: usize, |
| 1228 | bandwidth: Bandwidth, |
| 1229 | cap: usize, |
| 1230 | ) -> Result<usize> { |
| 1231 | let cap = cap.min(MAX_FRAME_BYTES); |
| 1232 | let frame_48k = frame_size * self.upsample; |
| 1233 | let budget = ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize; |
| 1234 | let budget = budget.saturating_sub(1).clamp(2, cap); |
| 1235 | // D2b: under CBR the SILK layer leaves CELT its minimum, plus two bytes |
| 1236 | // for the range coder's conservative `tell()` the hybrid split reads. |
| 1237 | if cap < HYBRID_CELT_MIN_BYTES + 2 { |
| 1238 | return Err(Error::corrupt( |
| 1239 | "opus encode: output buffer smaller than the minimum hybrid packet", |
| 1240 | )); |
| 1241 | } |
| 1242 | self.range.reset(cap); |
| 1243 | let max_data_bytes = if self.vbr { cap } else { budget } + 1; |
| 1244 | let f = self.silk_frame(max_data_bytes, 16, true, bandwidth == Bandwidth::SuperWide); |
| 1245 | let activity = self.silk_activity(raw, frame_size); |
| 1246 | let mut range = std::mem::take(&mut self.range); |
| 1247 | self.silk_layer() |
| 1248 | .encode(pcm, frame_size, &f, activity, &mut range); |
| 1249 | self.range = range; |
| 1250 | self.last_silk = Some(16); |
| 1251 | let silk_bytes = (self.range.tell() as usize).div_ceil(8); |
| 1252 | let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap); |
| 1253 | self.range.shrink(budget); |
| 1254 | // Redundancy flag: present under exactly the decoder's condition. |
| 1255 | if self.range.tell() as usize + 17 + 20 <= 8 * budget { |
| 1256 | self.range.enc_bit_logp(false, 12); |
| 1257 | } |
| 1258 | self.celt.set_align_input(true); |
| 1259 | let n = self.celt.encode( |
| 1260 | &mut self.range, |
| 1261 | pcm, |
| 1262 | frame_48k, |
| 1263 | 17, |
| 1264 | bandwidth.celt_end_band(), |
| 1265 | 0, |
| 1266 | &self.info, |
| 1267 | )?; |
| 1268 | self.celt.set_align_input(self.align_input); |
| 1269 | self.final_range = self.range.range(); |
| 1270 | Ok(n) |
| 1271 | } |
| 1272 | |
| 1273 | /// Encodes the CELT frame into the internal range coder and returns its |
| 1274 | /// byte length. `frame_size` is in 48 kHz samples, `end` is the last coded |
| 1275 | /// band, and `cap` bounds the frame (the caller's buffer minus headers). |
| 1276 | fn encode_frame( |
| 1277 | &mut self, |
| 1278 | pcm: &[f32], |
| 1279 | frame_size: usize, |
| 1280 | end: usize, |
| 1281 | cap: usize, |
| 1282 | ) -> Result<usize> { |
| 1283 | let cap = cap.min(MAX_FRAME_BYTES); |
| 1284 | if cap < 2 { |
| 1285 | return Err(Error::corrupt( |
| 1286 | "opus encode: output buffer smaller than the minimum packet", |
| 1287 | )); |
| 1288 | } |
| 1289 | // One byte per packet goes to the TOC; the CELT layer sees the rest. |
| 1290 | let toc_bps = 8 * 48000 / frame_size as u32; |
| 1291 | let (budget, vbr_rate) = if self.vbr { |
| 1292 | (cap, self.bitrate.saturating_sub(toc_bps).max(500)) |
| 1293 | } else { |
| 1294 | let b = ((self.bitrate as u64 * frame_size as u64 + 4 * 48000) / (8 * 48000)) as usize; |
| 1295 | (b.saturating_sub(1).clamp(2, cap), 0) |
| 1296 | }; |
| 1297 | self.range.reset(budget); |
| 1298 | let n = self.celt.encode( |
| 1299 | &mut self.range, |
| 1300 | pcm, |
| 1301 | frame_size, |
| 1302 | 0, |
| 1303 | end, |
| 1304 | vbr_rate, |
| 1305 | &self.info, |
| 1306 | )?; |
| 1307 | self.final_range = self.range.range(); |
| 1308 | Ok(n) |
| 1309 | } |
| 1310 | } |
| 1311 | |
| 1312 | #[cfg(test)] |
| 1313 | mod tests { |
| 1314 | use super::*; |
| 1315 | |
| 1316 | /// The detected-bandwidth clamp (`opus_encoder.c:1652-1674`): a band-limited |
| 1317 | /// analysis result lowers the coded bandwidth, but never below the |
| 1318 | /// rate-dependent floor, and never when the analysis did not run. |
| 1319 | #[test] |
| 1320 | fn detected_bandwidth_lowers_the_coded_bandwidth_but_not_below_its_floor() { |
| 1321 | let mut e = Encoder::new(48000, 2, Application::Audio).unwrap(); |
| 1322 | e.set_vbr_constrained(true); // the library gate's setting |
| 1323 | e.set_bitrate(64_000); |
| 1324 | // Analysis off (the default): fullband, whatever the estimate says. |
| 1325 | e.info.valid = true; |
| 1326 | e.info.bandwidth = 15; // wideband |
| 1327 | assert_eq!(e.auto_bandwidth(), Bandwidth::Full); |
| 1328 | // On: 64 kbps stereo is under 44000*2, so the floor is superwide — |
| 1329 | // a wideband estimate is raised to it, not honoured as wideband. |
| 1330 | e.bw_detect = true; |
| 1331 | assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide); |
| 1332 | // Above the floor the estimate passes through unchanged. |
| 1333 | e.info.bandwidth = 20; |
| 1334 | assert_eq!(e.auto_bandwidth(), Bandwidth::Full); |
| 1335 | // 96 kbps stereo is above 44000*2: the floor is fullband, so the |
| 1336 | // clamp is inert there — which is why it cannot move the @96 rows. |
| 1337 | e.info.bandwidth = 15; |
| 1338 | e.set_bitrate(96_000); |
| 1339 | assert_eq!(e.auto_bandwidth(), Bandwidth::Full); |
| 1340 | // An invalid analysis is libopus's `detected_bandwidth == 0`. |
| 1341 | e.set_bitrate(64_000); |
| 1342 | e.info.valid = false; |
| 1343 | assert_eq!(e.auto_bandwidth(), Bandwidth::Full); |
| 1344 | } |
| 1345 | |
| 1346 | /// The private half of the bandwidth decision: the thresholds themselves, |
| 1347 | /// which the TOC config only reports. |
| 1348 | #[test] |
| 1349 | fn bandwidth_follows_the_bitrate_the_application_and_the_input_rate() { |
| 1350 | let mut e = Encoder::new(48000, 1, Application::Audio).unwrap(); |
| 1351 | e.set_bitrate(64000); |
| 1352 | assert_eq!(e.auto_bandwidth(), Bandwidth::Full); |
| 1353 | // libopus MONO_MUSIC_BW blended at voice_est=48 (analysis off): |
| 1354 | // SWB<->FB boundary 12281, equiv(16k) = 14520 -> Full. |
| 1355 | e.set_bitrate(16000); |
| 1356 | assert_eq!(e.auto_bandwidth(), Bandwidth::Full); |
| 1357 | e.set_bitrate(10000); |
| 1358 | assert_eq!(e.auto_bandwidth(), Bandwidth::Wide); |
| 1359 | // equiv(8k) = 7260 < 9000 (NB<->MB boundary) -> Narrow. |
| 1360 | e.set_bitrate(8000); |
| 1361 | assert_eq!(e.auto_bandwidth(), Bandwidth::Narrow); |
| 1362 | // VoIP (voice_est=127): SWB<->FB boundary 13616, so 16k speech is |
| 1363 | // Full -> hybrid, matching libopus 1.6 on real speech |
| 1364 | // (lanes/opus-silk-r2.sweep.txt: 16k-NB row, ref_mode=Hybrid-FB). |
| 1365 | let mut v = Encoder::new(48000, 1, Application::Voip).unwrap(); |
| 1366 | v.set_bitrate(16000); |
| 1367 | assert_eq!(v.auto_bandwidth(), Bandwidth::Full); |
| 1368 | // The input's own Nyquist bounds it whatever the rate says. |
| 1369 | let mut e = Encoder::new(24000, 2, Application::Audio).unwrap(); |
| 1370 | e.set_bitrate(256_000); |
| 1371 | assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide); |
| 1372 | assert_eq!( |
| 1373 | e.look_ahead(960), |
| 1374 | (CELT_OVERLAP_48K + CELT_DELAY_COMP_48K) / 2 |
| 1375 | ); |
| 1376 | } |
| 1377 | |
| 1378 | #[test] |
| 1379 | fn look_ahead_is_libopus_delay_in_every_mode() { |
| 1380 | let full = CELT_OVERLAP_48K + CELT_DELAY_COMP_48K; |
| 1381 | let mut e = Encoder::new(48000, 1, Application::Voip).unwrap(); |
| 1382 | for bps in [8000, 16000, 32000, 64000] { |
| 1383 | e.set_bitrate(bps); |
| 1384 | for fs in [240, 480, 960] { |
| 1385 | assert_eq!(e.look_ahead(fs), full, "{bps} {fs}"); |
| 1386 | } |
| 1387 | } |
| 1388 | let e = Encoder::new(48000, 1, Application::LowDelay).unwrap(); |
| 1389 | assert_eq!(e.look_ahead(960), CELT_OVERLAP_48K); |
| 1390 | } |
| 1391 | |
| 1392 | #[test] |
| 1393 | fn voip_auto_mode_is_monotonic_per_channel() { |
| 1394 | for channels in [1usize, 2] { |
| 1395 | let mut e = Encoder::new(48000, channels, Application::Voip).unwrap(); |
| 1396 | let mut last = 0u8; |
| 1397 | for per_channel in 500..=45_000u32 { |
| 1398 | e.set_bitrate(per_channel * channels as u32); |
| 1399 | let class = if e.silk_choice(960).is_some() { |
| 1400 | 0 |
| 1401 | } else if e.hybrid_choice(960).is_some() { |
| 1402 | 1 |
| 1403 | } else { |
| 1404 | 2 |
| 1405 | }; |
| 1406 | assert!( |
| 1407 | class >= last, |
| 1408 | "{channels}ch {per_channel} bps/channel regressed from {last} to {class}" |
| 1409 | ); |
| 1410 | last = class; |
| 1411 | } |
| 1412 | } |
| 1413 | } |
| 1414 | } |