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