forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB35bdf35Tahinli2 months ago3757 commits

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