forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB7947774Tahinli1 month ago3899 commits

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