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