forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe12d32fTahinli6 days ago3982 commits

encoder.rs2182 lines, 78.9 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//! In-band FEC (SILK LBRR, [`Encoder::set_inband_fec`]) is mono SILK and
13//! hybrid 10/20 ms only.
14//!
15//! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and
16//! the coded bandwidth is capped at the input's own Nyquist, so the images
17//! the stuffing puts there are never coded and the decoder's decimation
18//! drops them. [`Encoder::look_ahead`] reports the delay in *input* samples.
19//!
20//! Rate control is CBR by default — every packet the same size, derived from
21//! the bitrate — or constrained VBR, the reference's reservoir scheme, when
22//! [`Encoder::set_vbr_constrained`] is on. A CBR SILK packet of 10 or 20 ms
23//! is held to the same byte budget as a CELT one: its rate loop coarsens
24//! until it fits (D2b), then padded up to the budget with code-3 packet
25//! padding like libopus's `opus_packet_pad`.
26
27use ec_core::{Error, Result};
28
29use crate::analysis::{AnalysisInfo, TonalityAnalysis};
30use crate::celt_flp::enc::{BITRATE_MAX, CeltEnc};
31use crate::celt_flp::tables::WINDOW120;
32use crate::packet::{Bandwidth, Mode};
33use crate::range::RangeEncoder;
34use crate::silk_flp::opus::{
35 InputFilter, SilkFrame, SilkLayer, bitrate_to_bits, bits_to_bitrate, hp_min_smth1_q15,
36 silk_rate_for_hybrid,
37};
38
39/// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`).
40const MAX_FRAME_BYTES: usize = 1275;
41
42enum Payload {
43 Range(usize),
44 Silk(usize),
45}
46const MAX_SILK_PACKET_BYTES: usize = 1 + 1 + 2 * 2 + 3 * MAX_FRAME_BYTES;
47const MAX_REDUNDANCY_BYTES: usize = 257;
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50enum Prefill {
51 Off,
52 Reset,
53 Keep,
54}
55
56/// One MDCT overlap: the CELT layer's delay without libopus's input
57/// alignment ([`Encoder::set_libopus_input_alignment`]), which adds
58/// `delay_compensation = Fs/250` (192 at 48 kHz) on top.
59const CELT_OVERLAP_48K: usize = 120;
60/// libopus `opus_encoder.c`'s `delay_compensation = Fs/250`.
61const CELT_DELAY_COMP_48K: usize = 192;
62/// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent.
63/// Was 8: at 16 kbps SILK takes 37 of the 40-byte budget, so 8 expanded
64/// 5133/6001 packets (+12.9% rate on the speech gate); libopus leaves CELT
65/// a few bytes there.
66const HYBRID_CELT_MIN_BYTES: usize = 3;
67/// libopus 1.6 bandwidth threshold tables (`opus_encoder.c:151`/`162`).
68/// Each pair is `(threshold, transition_width)` for one bandwidth boundary;
69/// voice and music, mono and stereo, are identical in 1.6.
70const MONO_VOICE_BW: [i32; 8] = [9000, 700, 9000, 700, 13500, 1000, 14000, 2000];
71const STEREO_VOICE_BW: [i32; 8] = [9000, 700, 9000, 700, 13500, 1000, 14000, 2000];
72const MONO_MUSIC_BW: [i32; 8] = [9000, 700, 9000, 700, 11000, 1000, 12000, 2000];
73const STEREO_MUSIC_BW: [i32; 8] = [9000, 700, 9000, 700, 11000, 1000, 12000, 2000];
74/// libopus `mode_thresholds` blended by `voice_est` (`opus_encoder.c:183`).
75/// With `stereo_width=0` (no analysis) the voice term is `[0][0]=64000` and
76/// the music base is `10000`; the gap (54000) is the ve² interpolation span.
77const MODE_THRESHOLD_VOICE: i32 = 64000;
78const MODE_THRESHOLD_MUSIC: i32 = 10000;
79const MODE_THRESHOLD_VOICE_STEREO: i32 = 44000;
80const STEREO_THRESHOLD_VOICE: i32 = 19000;
81const STEREO_THRESHOLD_MUSIC: i32 = 17000;
82const EPSILON: f32 = 1e-15;
83const BANDWIDTHS: [Bandwidth; 5] = [
84 Bandwidth::Narrow,
85 Bandwidth::Medium,
86 Bandwidth::Wide,
87 Bandwidth::SuperWide,
88 Bandwidth::Full,
89];
90
91#[derive(Clone, Copy, Debug)]
92#[allow(dead_code)]
93struct Decision {
94 mode: Mode,
95 bandwidth: Bandwidth,
96 stream_channels: usize,
97 equiv_rate: i32,
98 redundancy: bool,
99 redundancy_bytes: usize,
100 celt_to_silk: bool,
101 to_celt: bool,
102 prefill: Prefill,
103 to_mono: bool,
104 toc_only: Option<usize>,
105}
106
107#[derive(Clone, Copy, Debug, Default)]
108struct StereoWidth {
109 xx: f32,
110 xy: f32,
111 yy: f32,
112 smoothed: f32,
113 max_follower: f32,
114}
115
116fn bw_index(bw: Bandwidth) -> usize {
117 BANDWIDTHS.iter().position(|&x| x == bw).unwrap_or(0)
118}
119
120fn detected_bandwidth(analysis: i32) -> Bandwidth {
121 match analysis {
122 i32::MIN..=12 => Bandwidth::Narrow,
123 13..=14 => Bandwidth::Medium,
124 15..=16 => Bandwidth::Wide,
125 17..=18 => Bandwidth::SuperWide,
126 _ => Bandwidth::Full,
127 }
128}
129
130fn compute_redundancy_bytes(
131 max_data_bytes: i32,
132 bitrate_bps: i32,
133 frame_rate: i32,
134 channels: i32,
135) -> usize {
136 let base_bits = 40 * channels + 20;
137 let rate = 3 * (bitrate_bps + base_bits * (200 - frame_rate)) / 2;
138 let mut bytes = rate / 1600;
139 let available_bits = max_data_bytes * 8 - 2 * base_bits;
140 let cap = (available_bits * 240 / (240 + 48000 / frame_rate) + base_bits) / 8;
141 bytes = bytes.min(cap);
142 if bytes > 4 + 8 * channels {
143 bytes.min(MAX_REDUNDANCY_BYTES as i32) as usize
144 } else {
145 0
146 }
147}
148
149fn compute_equiv_rate(
150 bitrate: i32,
151 channels: i32,
152 frame_rate: i32,
153 vbr: bool,
154 mode: Option<Mode>,
155 loss: i32,
156) -> i32 {
157 let mut equiv = bitrate;
158 if frame_rate > 50 {
159 equiv -= (40 * channels + 20) * (frame_rate - 50);
160 }
161 if !vbr {
162 equiv -= equiv / 12;
163 }
164 equiv = equiv * (90 + DEFAULT_COMPLEXITY) / 100;
165 match mode {
166 Some(Mode::Silk) | Some(Mode::Hybrid) => equiv -= equiv * loss / (6 * loss + 10),
167 Some(Mode::Celt) => {}
168 None => equiv -= equiv * loss / (12 * loss + 20),
169 }
170 equiv
171}
172
173fn update_stereo_width(mem: &mut StereoWidth, pcm: &[f32], frame_size: usize, fs: u32) -> f32 {
174 let frame_rate = (fs as usize / frame_size) as i32;
175 let short_alpha = 25.0 / frame_rate.max(50) as f32;
176 let (mut xx, mut xy, mut yy) = (0.0f32, 0.0f32, 0.0f32);
177 for g in (0..(frame_size & !3)).step_by(4) {
178 let (mut pxx, mut pxy, mut pyy) = (0.0f32, 0.0f32, 0.0f32);
179 for i in g..g + 4 {
180 let (x, y) = (pcm[2 * i], pcm[2 * i + 1]);
181 pxx += x * x;
182 pxy += x * y;
183 pyy += y * y;
184 }
185 xx += pxx;
186 xy += pxy;
187 yy += pyy;
188 }
189 if xx.is_nan() || yy.is_nan() || xx >= 1e9 || yy >= 1e9 {
190 xx = 0.0;
191 xy = 0.0;
192 yy = 0.0;
193 }
194 mem.xx = (mem.xx + short_alpha * (xx - mem.xx)).max(0.0);
195 mem.xy = ((1.0 - short_alpha) * mem.xy + short_alpha * xy).max(0.0);
196 mem.yy = (mem.yy + short_alpha * (yy - mem.yy)).max(0.0);
197 if mem.xx.max(mem.yy) > 8e-4 {
198 let frame_rate = frame_rate as f32;
199 let sqrt_xx = mem.xx.sqrt();
200 let sqrt_yy = mem.yy.sqrt();
201 let qrrt_xx = sqrt_xx.sqrt();
202 let qrrt_yy = sqrt_yy.sqrt();
203 mem.xy = mem.xy.min(sqrt_xx * sqrt_yy);
204 let corr = mem.xy / (EPSILON + sqrt_xx * sqrt_yy);
205 let ldiff = (qrrt_xx - qrrt_yy).abs() / (EPSILON + qrrt_xx + qrrt_yy);
206 let width = (1.0 - corr * corr).sqrt().min(1.0) * ldiff;
207 mem.smoothed += (width - mem.smoothed) / frame_rate;
208 mem.max_follower = (mem.max_follower - 0.02 / frame_rate).max(mem.smoothed);
209 }
210 (20.0 * mem.max_follower).min(1.0)
211}
212/// Opus default encoder complexity (the `(90+complexity)/100` equiv-rate
213/// multiplier; loss=0 and complexity≥5 add no per-mode adjustment).
214const DEFAULT_COMPLEXITY: i32 = 9;
215
216/// What the caller is encoding.
217#[derive(Clone, Copy, Debug, PartialEq, Eq)]
218pub enum Application {
219 /// Speech: one step narrower at a given rate, where the top octave costs
220 /// most and carries least.
221 Voip,
222 /// Music and general audio, the default.
223 Audio,
224 /// Lowest delay.
225 LowDelay,
226}
227
228const DTX_START_Q1: i32 = 10 * 2 * 20;
229const DTX_END_Q1: i32 = (10 + 20) * 2 * 20;
230const DTX_ACTIVITY_THRESHOLD: f32 = 0.1;
231const DTX_PSEUDO_SNR_THRESHOLD: f32 = 316.23;
232
233/// The TOC-only packet libopus sends in DTX: code 0 is the TOC alone; code 3
234/// keeps its frame-count byte with no frames. Self-delimited framing adds a
235/// zero frame length after it.
236fn gen_toc(mode: Mode, frame_rate: usize, bw: Bandwidth, channels: usize) -> u8 {
237 let mut period = 0;
238 let mut rate = frame_rate;
239 while rate < 400 {
240 rate <<= 1;
241 period += 1;
242 }
243 let bw = bw_index(bw) as u8;
244 let toc = match mode {
245 Mode::Silk => (bw << 5) | ((period - 2) << 3),
246 Mode::Celt => 0x80 | (bw.saturating_sub(1) << 5) | (period << 3),
247 Mode::Hybrid => 0x60 | ((bw - 3) << 4) | ((period - 2) << 3),
248 };
249 toc | (u8::from(channels == 2) << 2)
250}
251
252fn dtx_packet(toc: u8, count: u8, self_delimited: bool) -> ([u8; 3], usize) {
253 let mut bytes = [0u8; 3];
254 let len = if toc & 3 == 3 {
255 bytes[0] = toc;
256 bytes[1] = count & 0x3F;
257 if self_delimited { 3 } else { 2 }
258 } else {
259 bytes[0] = toc & !3;
260 if self_delimited { 2 } else { 1 }
261 };
262 (bytes, len)
263}
264
265fn encoder_buffer(sample_rate: u32) -> usize {
266 sample_rate as usize / 100
267}
268
269/// One elementary Opus encoder: mono or stereo.
270#[derive(Clone, Debug)]
271pub struct Encoder {
272 celt: CeltEnc,
273 bitrate_bps: i32,
274 lsb_depth: i32,
275 range: RangeEncoder,
276 sample_rate: u32,
277 /// 48000 / `sample_rate`: the zero-stuffing factor into CELT.
278 upsample: usize,
279 channels: usize,
280 bitrate: u32,
281 vbr: bool,
282 application: Application,
283 bandwidth: Option<Bandwidth>,
284 final_range: u32,
285 /// [`None`] picks SILK, CELT or (once D4 lands) Hybrid from the
286 /// application and bitrate; `Some` forces one.
287 mode: Option<Mode>,
288 /// The SILK layer, created on first use (boxed: `crate::stack_budget`).
289 silk: Option<Box<SilkLayer>>,
290 /// Scratch space for the SILK packet payload, sized once so the steady-state
291 /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate.
292 ///
293 /// Boxed for the same reason as the slots above: `MAX_SILK_PACKET_BYTES` is
294 /// 4088 bytes, and an inline array that size is a third of the whole
295 /// budget on the `Encoder` that a caller holds by value.
296 silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>,
297 /// [`Encoder::set_libopus_input_alignment`].
298 align_input: bool,
299 filter: InputFilter,
300 /// Scratch space for the filter's output, sized once.
301 hp_buf: Vec<f32>,
302 delay_buffer: Vec<f32>,
303 pcm_buf: Vec<f32>,
304 history: Vec<f32>,
305 redundant: RangeEncoder,
306 /// libopus `st->analysis`: the tonality/music-probability estimator. It
307 /// lives here, not in the CELT layer, because `opus_encode_native` runs
308 /// `run_analysis()` on the API frame *before* the SILK/CELT mode and
309 /// bandwidth decisions, so its state advances on SILK frames too.
310 analysis: TonalityAnalysis,
311 /// The current frame's analysis output, handed to `celt.encode`.
312 info: AnalysisInfo,
313 analysis_on: bool,
314 inband_fec: bool,
315 packet_loss_perc: u8,
316 lbrr_coded: bool,
317 silk_bw_switch: bool,
318 use_dtx: bool,
319 nb_no_activity_ms_q1: i32,
320 peak_signal_energy: f32,
321 prev_mode: Option<Mode>,
322 first: bool,
323 auto_bandwidth: Bandwidth,
324 coded_bandwidth: Bandwidth,
325 stream_channels: usize,
326 prev_channels: usize,
327 force_mono: bool,
328 to_mono: bool,
329 hybrid_stereo_width_q14: i32,
330 stereo_width_q14: i32,
331 voice_ratio: i32,
332 width_mem: StereoWidth,
333 nonfinal: bool,
334 prev_hb_gain: f32,
335}
336
337/// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8,
338/// Medium → 12, Wide/SuperWide/Full → 16. SILK only runs at 8/12/16 kHz;
339/// for SuperWide/Full the top bands are CELT (Hybrid), so SILK itself is 16.
340fn silk_fs_khz(bw: Bandwidth) -> usize {
341 match bw {
342 Bandwidth::Narrow => 8,
343 Bandwidth::Medium => 12,
344 _ => 16,
345 }
346}
347
348fn gain_fade(
349 buf: &mut [f32],
350 g1: f32,
351 g2: f32,
352 window: &[f32],
353 frame_size: usize,
354 channels: usize,
355 fs: u32,
356) {
357 let inc = (48000 / fs as usize).max(1);
358 let overlap = CELT_OVERLAP_48K / inc;
359 for i in 0..overlap {
360 let w = window[i * inc];
361 let w = w * w;
362 let g = w * g2 + (1.0 - w) * g1;
363 for c in 0..channels {
364 buf[i * channels + c] *= g;
365 }
366 }
367 for i in overlap..frame_size {
368 for c in 0..channels {
369 buf[i * channels + c] *= g2;
370 }
371 }
372}
373
374fn stereo_fade(buf: &mut [f32], g1: f32, g2: f32, window: &[f32], frame_size: usize, fs: u32) {
375 let inc = (48000 / fs as usize).max(1);
376 let overlap = CELT_OVERLAP_48K / inc;
377 let (a, b) = (1.0 - g1, 1.0 - g2);
378 for i in 0..overlap {
379 let w = window[i * inc];
380 let w = w * w;
381 let g = w * b + (1.0 - w) * a;
382 let diff = 0.5 * (buf[2 * i] - buf[2 * i + 1]) * g;
383 buf[2 * i] -= diff;
384 buf[2 * i + 1] += diff;
385 }
386 for i in overlap..frame_size {
387 let diff = 0.5 * (buf[2 * i] - buf[2 * i + 1]) * b;
388 buf[2 * i] -= diff;
389 buf[2 * i + 1] += diff;
390 }
391}
392
393fn stereo_width_for_rate(equiv: i32) -> i32 {
394 if equiv > 32000 {
395 16384
396 } else if equiv < 16000 {
397 0
398 } else {
399 16384 - 2048 * (32000 - equiv) / (equiv - 14000)
400 }
401}
402
403impl Encoder {
404 /// An encoder for `channels` channels (1 or 2) at `sample_rate`, which
405 /// must be one of 8000, 12000, 16000, 24000 or 48000 Hz — the rates
406 /// RFC 6716 Section 2 admits. CELT itself runs at 48 kHz whatever the
407 /// input rate is (RFC 7845 Section 5.1).
408 pub fn new(sample_rate: u32, channels: usize, application: Application) -> Result<Encoder> {
409 let upsample = match sample_rate {
410 48000 => 1,
411 24000 => 2,
412 16000 => 3,
413 12000 => 4,
414 8000 => 6,
415 _ => {
416 return Err(Error::unsupported(
417 format!("opus encode at {sample_rate} Hz"),
418 "Opus encodes from 8, 12, 16, 24 or 48 kHz; resample first",
419 ));
420 }
421 };
422 if !(1..=2).contains(&channels) {
423 return Err(Error::unsupported(
424 format!("{channels}-channel Opus stream"),
425 "one stream carries at most two channels; use MultistreamEncoder",
426 ));
427 }
428 let mut enc = Encoder {
429 celt: CeltEnc::new(channels, upsample),
430 bitrate_bps: 0,
431 lsb_depth: 24,
432 range: RangeEncoder::new(),
433 sample_rate,
434 upsample,
435 channels,
436 bitrate: 64_000 * channels as u32,
437 vbr: false,
438 application,
439 bandwidth: None,
440 final_range: 0,
441 mode: None,
442 silk: None,
443 silk_buf: Box::new([0u8; MAX_SILK_PACKET_BYTES]),
444 align_input: application != Application::LowDelay,
445 filter: InputFilter::new(),
446 hp_buf: Vec::new(),
447 delay_buffer: vec![0.0; encoder_buffer(sample_rate) * channels],
448 pcm_buf: Vec::new(),
449 history: Vec::new(),
450 redundant: RangeEncoder::new(),
451 analysis: TonalityAnalysis::new(sample_rate),
452 info: AnalysisInfo::default(),
453 analysis_on: true,
454 inband_fec: false,
455 packet_loss_perc: 0,
456 lbrr_coded: false,
457 silk_bw_switch: false,
458 use_dtx: false,
459 nb_no_activity_ms_q1: 0,
460 peak_signal_energy: 0.0,
461 prev_mode: None,
462 first: true,
463 auto_bandwidth: Bandwidth::Full,
464 coded_bandwidth: Bandwidth::Full,
465 stream_channels: channels,
466 prev_channels: 0,
467 force_mono: false,
468 to_mono: false,
469 hybrid_stereo_width_q14: 1 << 14,
470 stereo_width_q14: 0,
471 voice_ratio: -1,
472 width_mem: StereoWidth::default(),
473 nonfinal: false,
474 prev_hb_gain: 1.0,
475 };
476 enc.celt.set_complexity(DEFAULT_COMPLEXITY);
477 Ok(enc)
478 }
479
480 /// Turns libopus's tonality analysis on (the default) or off. Off saves
481 /// about a quarter of the encoder's time but drops what it feeds: speech/music
482 /// detection, bandwidth detection, and CELT's tonality-driven allocation.
483 pub fn set_analysis(&mut self, on: bool) {
484 self.analysis_on = on;
485 }
486
487 /// Overrides the automatic SILK/Hybrid/CELT choice made from the application and bitrate; pass `None` to
488 /// restore the automatic pick. Requests this encoder cannot honour
489 /// (10 ms Hybrid) fall back to CELT.
490 pub fn set_mode(&mut self, mode: Option<Mode>) {
491 self.mode = mode;
492 }
493
494 /// Channels per frame of input.
495 pub fn channels(&self) -> usize {
496 self.channels
497 }
498
499 /// The rate the caller feeds.
500 pub fn sample_rate(&self) -> u32 {
501 self.sample_rate
502 }
503
504 /// Encoder delay in *input* samples for a `frame_size`-sample (per
505 /// channel, native rate) frame: the decoded stream lags the input by
506 /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate`
507 /// cancels it exactly. CELT: one MDCT overlap plus the 192-sample input
508 /// delay compensation, 312 samples at 48 kHz.
509 /// SILK and hybrid: 312 as well, the libopus SILK encoder's own delay,
510 /// which the CELT layer's input delay is there to match.
511 pub fn look_ahead(&self, _frame_size: usize) -> usize {
512 self.celt_look_ahead_48k() / self.upsample
513 }
514
515 /// The CELT layer's delay in 48 kHz samples: one MDCT overlap, plus
516 /// libopus's `delay_compensation` when the alignment is on.
517 fn celt_look_ahead_48k(&self) -> usize {
518 CELT_OVERLAP_48K
519 + if self.align_input {
520 CELT_DELAY_COMP_48K
521 } else {
522 0
523 }
524 }
525
526 /// On by default except for [`Application::LowDelay`], as in libopus: the
527 /// SILK layer's own delay is 312 samples, and only an aligned CELT layer
528 /// keeps CELT, SILK and hybrid frames of one stream at the same delay.
529 ///
530 /// Puts our CELT analysis window exactly where libopus's is: the layer is
531 /// fed the input delayed by `delay_compensation = Fs/250` (192 samples at
532 /// 48 kHz, `opus_encoder.c` ~:1955) and every frame first goes through
533 /// libopus's 3 Hz `dc_reject`. The alignment is *exact* — on the reell
534 /// attack frame (frame 2, 20 ms, LM=3, transient) our first eight band
535 /// log-energies become
536 /// 3.4386 4.0055 3.2603 4.5954 1.1790 4.2774 4.7584 3.7169 against
537 /// libopus's 3.439 4.005 3.260 4.595 1.179 4.277 4.758 3.717, all eight
538 /// within .0006 (the unaligned encoder is .06-.21 apart).
539 ///
540 /// It ships OFF because the 12-row library gate rejects it, and because
541 /// re-tuning the constants that were fitted on the misaligned spectrum
542 /// does not rescue it. Against the shipped rows
543 /// (`lanes/opus-opustr2-r1.sweep.txt`), err_ratio:
544 ///
545 /// | arm | better | worse (blocking) |
546 /// |---|---|---|
547 /// | 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 |
548 /// | delay + `dc_reject` (`opus-opusx2-r1`) | 5 | those, plus dl8a@64 .552→1.074, dl8a@96 .374→1.011 |
549 /// | + two-pass coarse energy (`-r2`) | 5 | same 7 rows (nik@96 1.809, dl8a@64 1.200) |
550 /// | + continuous 1.3 `alloc_trim` (`-r3`) | 5 | same 7, and corr worse by >.0005 on 9 rows |
551 /// | + tf boost k=1.25 (`-r4`) | 5 | same 7 |
552 /// | + tf boost k=1.5 (`-r5`) | 5 | same 7 |
553 /// | + 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 |
554 /// | + 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 |
555 ///
556 /// The best aligned arm on the KEEP rule is the delay alone without
557 /// `dc_reject` (5 rows worse); every arm that adds `dc_reject` puts dl8a
558 /// in the blocking set too.
559 ///
560 /// The last row is the one that was expected to rescue this: libopus's
561 /// actual operating point is the aligned spectrum *with* `analysis->valid`
562 /// true, and running the real analysis (`crates/ec-opus/src/analysis.rs`,
563 /// `music_prob` matching a patched-libopus trace to .001) moves reell@64
564 /// 2.697→1.865, reell@96 4.499→3.986, reelo@64 1.510→1.123 and her@64
565 /// 1.103→.952 — the largest movement any arm has produced on those rows —
566 /// and still leaves the same seven rows worse.
567 ///
568 /// The blocking set (nik, her@96, dl8a, hein) is the same in every arm and
569 /// no arm moves any of those rows back towards its shipped value, so the
570 /// misfit is not one of the swept constants. Turning this on also costs
571 /// 4 ms of algorithmic delay: [`Encoder::look_ahead`] for a CELT frame
572 /// becomes 312, not 120, and the Ogg pre-skip must follow it.
573 pub fn set_libopus_input_alignment(&mut self, on: bool) {
574 self.align_input = on;
575 self.filter = InputFilter::new();
576 }
577
578 /// Forces the coded bandwidth; [`None`] (the default) picks it from the
579 /// bitrate, the application and the input's Nyquist.
580 pub fn set_bandwidth(&mut self, bandwidth: Option<Bandwidth>) {
581 self.bandwidth = bandwidth;
582 }
583
584 /// Target bitrate in bits per second for the whole packet stream,
585 /// including the packet headers. Clamped to 500..=510000.
586 pub fn set_bitrate(&mut self, bps: u32) {
587 self.bitrate = bps.clamp(500, 510_000);
588 }
589
590 /// OPUS_SET_INBAND_FEC: code LBRR (in-band FEC) when the loss rate and bitrate justify it; prefers SILK/hybrid over CELT under loss.
591 pub fn set_inband_fec(&mut self, on: bool) {
592 self.inband_fec = on;
593 }
594
595 /// OPUS_SET_PACKET_LOSS_PERC: expected packet loss, 0..=100 (clamped).
596 pub fn set_packet_loss_perc(&mut self, perc: u8) {
597 self.packet_loss_perc = perc.min(100);
598 self.celt.set_loss_rate(i32::from(self.packet_loss_perc));
599 }
600
601 /// OPUS_SET_DTX: send TOC-only packets during silence/inactivity (after 200 ms), refreshing every 400 ms.
602 pub fn set_dtx(&mut self, on: bool) {
603 self.use_dtx = on;
604 }
605
606 /// libopus's peak signal energy tracker, run on every frame after the analysis.
607 fn track_peak(&mut self, pcm: &[f32], frame_size: usize) {
608 let n = frame_size * self.channels;
609 if pcm
610 .iter()
611 .take(n)
612 .all(|x| x.abs() <= self.silence_threshold())
613 {
614 return;
615 }
616 if !self.info.valid || self.info.activity_probability > DTX_ACTIVITY_THRESHOLD {
617 let energy = pcm.iter().take(n).map(|x| x * x).sum::<f32>() / n as f32;
618 self.peak_signal_energy = (0.999 * self.peak_signal_energy).max(energy);
619 }
620 }
621
622 /// The `activity` libopus hands `silk_Encode`: 0/1 from the analysis,
623 /// -1 (`VAD_NO_DECISION`) without it.
624 fn silk_activity(&self, pcm: &[f32], frame_size: usize) -> i32 {
625 let n = frame_size * self.channels;
626 if pcm
627 .iter()
628 .take(n)
629 .all(|x| x.abs() <= self.silence_threshold())
630 {
631 return 0;
632 }
633 if !self.info.valid {
634 return -1;
635 }
636 let energy = pcm.iter().take(n).map(|x| x * x).sum::<f32>() / n as f32;
637 i32::from(
638 self.info.activity_probability >= DTX_ACTIVITY_THRESHOLD
639 || self.peak_signal_energy < DTX_PSEUDO_SNR_THRESHOLD * energy,
640 )
641 }
642
643 /// libopus `decide_dtx_mode` plus the activity test of `opus_encode_native`
644 /// for one frame: true when this frame's packet is a DTX one.
645 fn dtx_frame(&mut self, pcm: &[f32], frame_size: usize) -> bool {
646 if !self.use_dtx {
647 return false;
648 }
649 let n = frame_size * self.channels;
650 let energy = pcm.iter().take(n).map(|x| x * x).sum::<f32>() / n as f32;
651 let is_silence = pcm.iter().all(|x| x.abs() <= self.silence_threshold());
652 let (valid, prob) = (self.info.valid, self.info.activity_probability);
653 let active = if is_silence {
654 false
655 } else if valid {
656 prob >= DTX_ACTIVITY_THRESHOLD
657 || self.peak_signal_energy < DTX_PSEUDO_SNR_THRESHOLD * energy
658 } else {
659 true
660 };
661 if active {
662 self.nb_no_activity_ms_q1 = 0;
663 return false;
664 }
665 self.nb_no_activity_ms_q1 += 2 * 1000 * frame_size as i32 / self.sample_rate as i32;
666 if self.nb_no_activity_ms_q1 > DTX_START_Q1 {
667 if self.nb_no_activity_ms_q1 <= DTX_END_Q1 {
668 return true;
669 }
670 self.nb_no_activity_ms_q1 = DTX_START_Q1;
671 }
672 false
673 }
674
675 /// Current target bitrate.
676 pub fn bitrate(&self) -> u32 {
677 self.bitrate
678 }
679
680 /// Switches between CBR (default, every packet the target size) and
681 /// constrained VBR (packets vary, a reservoir holds the average to the
682 /// target).
683 pub fn set_vbr_constrained(&mut self, vbr: bool) {
684 self.vbr = vbr;
685 }
686
687 /// The range coder state after the last packet — the same value RFC 6716
688 /// test vectors carry, and what a conformant decoder's `final_range`
689 /// must equal after decoding that packet.
690 pub fn final_range(&self) -> u32 {
691 self.final_range
692 }
693
694 /// Drops all inter-frame state; the next packet starts like the first.
695 pub fn reset(&mut self) {
696 self.celt.reset();
697 self.silk = None;
698 self.filter = InputFilter::new();
699 self.delay_buffer.fill(0.0);
700 self.final_range = 0;
701 self.analysis.reset();
702 self.info = AnalysisInfo::default();
703 self.lbrr_coded = false;
704 self.silk_bw_switch = false;
705 self.prev_mode = None;
706 self.first = true;
707 self.auto_bandwidth = Bandwidth::Full;
708 self.coded_bandwidth = Bandwidth::Full;
709 self.stream_channels = self.channels;
710 self.prev_channels = 0;
711 self.force_mono = false;
712 self.to_mono = false;
713 self.hybrid_stereo_width_q14 = 1 << 14;
714 self.stereo_width_q14 = 0;
715 self.voice_ratio = -1;
716 self.width_mem = StereoWidth::default();
717 self.nonfinal = false;
718 self.prev_hb_gain = 1.0;
719 self.nb_no_activity_ms_q1 = 0;
720 self.peak_signal_energy = 0.0;
721 }
722
723 fn write_frame_len(out: &mut [u8], pos: &mut usize, len: usize) -> Result<()> {
724 if len > MAX_FRAME_BYTES {
725 return Err(Error::corrupt(format!(
726 "opus encode: frame payload of {len} bytes exceeds {MAX_FRAME_BYTES}"
727 )));
728 }
729 if len < 252 {
730 out[*pos] = len as u8;
731 *pos += 1;
732 } else {
733 let b0 = 252 + ((len - 252) & 3);
734 out[*pos] = b0 as u8;
735 out[*pos + 1] = ((len - b0) / 4) as u8;
736 *pos += 2;
737 }
738 Ok(())
739 }
740
741 /// The CBR packet budget for a `frame_48k`-sample frame, in payload bytes,
742 /// by the figure the CELT path uses; `None` under constrained VBR (D2b).
743 fn packet_budget(&self, frame_48k: usize, cap: usize) -> Option<usize> {
744 if self.vbr {
745 return None;
746 }
747 let b = ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize;
748 Some(b.saturating_sub(1).max(2).min(cap))
749 }
750
751 /// The `silk_mode` fields libopus sets for one frame; `max_data_bytes`
752 /// counts the TOC byte.
753 fn silk_frame(
754 &self,
755 d: Decision,
756 max_data_bytes: usize,
757 internal_khz: usize,
758 hybrid: bool,
759 swb: bool,
760 ) -> SilkFrame {
761 let reserved = if d.redundancy {
762 d.redundancy_bytes as i32 * 8 + 1 + if hybrid { 20 } else { 0 }
763 } else {
764 0
765 };
766 SilkFrame {
767 bitrate: self.bitrate as i32,
768 max_data_bytes,
769 redundancy_bytes: if d.redundancy {
770 d.redundancy_bytes as i32
771 } else {
772 0
773 },
774 reserved_bits: reserved,
775 vbr: self.vbr,
776 hybrid,
777 swb,
778 internal_khz: internal_khz as i32,
779 stream_channels: d.stream_channels,
780 to_mono: d.to_mono,
781 fec: self.inband_fec,
782 lbrr_coded: self.lbrr_coded,
783 loss_perc: i32::from(self.packet_loss_perc),
784 complexity: DEFAULT_COMPLEXITY,
785 }
786 }
787
788 fn silk_layer(&mut self) -> &mut SilkLayer {
789 let (fs, ch, nonfinal) = (self.sample_rate, self.channels, self.nonfinal);
790 let silk = self
791 .silk
792 .get_or_insert_with(|| Box::new(SilkLayer::new(fs, ch)));
793 silk.set_nonfinal(nonfinal);
794 silk
795 }
796
797 /// Picks SILK or CELT for one frame and encodes it, returning the TOC
798 /// byte and the payload bytes (excluding TOC), borrowed from scratch
799 /// space owned by `self` — no allocation on the steady-state path.
800 /// `cap` bounds the packet; under CBR a SILK packet is held to the same budget
801 /// as a CELT one (D2b).
802 fn encode_toc_and_payload(
803 &mut self,
804 pcm: &[f32],
805 frame_size: usize,
806 cap: usize,
807 self_delimited: bool,
808 ) -> Result<(u8, &[u8])> {
809 let cursor = self.analysis.cursor();
810 self.info = if self.analysis_on {
811 self.analysis
812 .run(pcm, frame_size, self.channels, self.lsb_depth)
813 } else {
814 AnalysisInfo::default()
815 };
816 self.track_peak(pcm, frame_size);
817 let d = self.decide(pcm, frame_size, cap + 1);
818 if let Some(max_data) = d.toc_only {
819 let (toc, n) = self.toc_only_packet(d, frame_size, cap + 1, max_data)?;
820 return Ok((toc, &self.silk_buf[..n]));
821 }
822 if d.prefill == Prefill::Reset {
823 self.silk_layer().reset();
824 }
825 let encoded = if frame_size * self.upsample > 960 && d.mode != Mode::Silk {
826 self.encode_multiframe(pcm, frame_size, cap, d, cursor, self_delimited)
827 } else {
828 self.encode_frame_decided(pcm, frame_size, cap, d)
829 };
830 let (toc, payload) = encoded?;
831 self.first = false;
832 Ok((toc, self.payload_bytes(payload)))
833 }
834
835 fn toc_only_packet(
836 &mut self,
837 d: Decision,
838 frame_size: usize,
839 out_bytes: usize,
840 max_data: usize,
841 ) -> Result<(u8, usize)> {
842 let mut frame_rate = 48000 / (frame_size * self.upsample);
843 let mut mode = d.mode;
844 let mut bw = d.bandwidth;
845 let mut code = 0u8;
846 let mut count = 1;
847 if frame_rate > 100 {
848 mode = Mode::Celt;
849 }
850 if frame_rate == 25 && mode != Mode::Silk {
851 frame_rate = 50;
852 code = 1;
853 count = 2;
854 }
855 if frame_rate <= 16 {
856 if out_bytes == 1 || (mode == Mode::Silk && frame_rate != 10) {
857 mode = Mode::Silk;
858 code = u8::from(frame_rate <= 12);
859 count = if code == 1 { 2 } else { 1 };
860 frame_rate = if frame_rate == 12 { 25 } else { 16 };
861 } else {
862 count = 50 / frame_rate;
863 frame_rate = 50;
864 code = 3;
865 }
866 }
867 bw = match mode {
868 Mode::Silk if bw > Bandwidth::Wide => Bandwidth::Wide,
869 Mode::Celt if bw == Bandwidth::Medium => Bandwidth::Narrow,
870 Mode::Hybrid if bw <= Bandwidth::SuperWide => Bandwidth::SuperWide,
871 _ => bw,
872 };
873 let toc = gen_toc(mode, frame_rate, bw, d.stream_channels);
874 let frames = vec![Vec::new(); count];
875 if !self.vbr && max_data > 1 + usize::from(code >= 2) {
876 let (_, n) = self.pack_frames(&frames, max_data, true)?;
877 return Ok((toc | 3, n));
878 }
879 if code == 3 {
880 self.silk_buf[0] = count as u8;
881 return Ok((toc | 3, 1));
882 }
883 Ok((toc | code, 0))
884 }
885
886 fn encode_frame_decided(
887 &mut self,
888 pcm: &[f32],
889 frame_size: usize,
890 cap: usize,
891 mut d: Decision,
892 ) -> Result<(u8, Payload)> {
893 if std::mem::take(&mut self.silk_bw_switch) {
894 d.redundancy = true;
895 d.celt_to_silk = true;
896 d.prefill = Prefill::Keep;
897 }
898 if d.mode == Mode::Celt {
899 d.redundancy = false;
900 }
901 d.redundancy_bytes = 0;
902 if d.redundancy {
903 let max_data = self.frame_max_data(frame_size * self.upsample, cap);
904 d.redundancy_bytes = self.redundancy_bytes(max_data, frame_size, d.stream_channels);
905 d.redundancy = d.redundancy_bytes != 0;
906 }
907 let mut buf = std::mem::take(&mut self.hp_buf);
908 self.filter_input(pcm, frame_size, d.mode == Mode::Celt, &mut buf);
909 let mut delayed = std::mem::take(&mut self.pcm_buf);
910 self.delay_input(&buf, frame_size, &mut delayed);
911 if d.prefill != Prefill::Off && d.mode != Mode::Celt {
912 self.fade_prefill_history();
913 }
914 self.history.clear();
915 self.history.extend_from_slice(&self.delay_buffer);
916 self.update_delay(&delayed, frame_size);
917 let r = self.encode_mode(pcm, &buf, &mut delayed, frame_size, cap, d);
918 self.hp_buf = buf;
919 self.pcm_buf = delayed;
920 self.prev_mode = Some(if d.to_celt { Mode::Celt } else { d.mode });
921 self.prev_channels = d.stream_channels;
922 r
923 }
924
925 fn payload_bytes(&self, payload: Payload) -> &[u8] {
926 match payload {
927 Payload::Range(n) => &self.range.data()[..n],
928 Payload::Silk(n) => &self.silk_buf[..n],
929 }
930 }
931
932 /// libopus `opus_encode_frame_native`'s input filter: `hp_cutoff` for
933 /// VoIP, its cutoff following SILK's estimate unless the frame is
934 /// CELT-only; otherwise the 3 Hz `dc_reject` (only with the CELT input
935 /// alignment on, the libopus default).
936 fn filter_input(
937 &mut self,
938 pcm: &[f32],
939 frame_size: usize,
940 celt_only: bool,
941 out: &mut Vec<f32>,
942 ) {
943 let n = frame_size * self.channels;
944 out.clear();
945 out.resize(n, 0.0);
946 let fs = self.sample_rate as i32;
947 if self.application == Application::Voip {
948 let smth1 = match (&self.silk, celt_only) {
949 (Some(silk), false) => silk.hp_smth1_q15(),
950 _ => hp_min_smth1_q15(),
951 };
952 self.filter
953 .hp_cutoff(&pcm[..n], out, smth1, self.channels, fs);
954 } else {
955 self.filter.dc_reject(&pcm[..n], out, self.channels, fs);
956 }
957 }
958
959 fn delay_input(&self, frame: &[f32], frame_size: usize, out: &mut Vec<f32>) {
960 let ch = self.channels;
961 let start = (encoder_buffer(self.sample_rate) - self.total_buffer()) * ch;
962 out.clear();
963 out.extend_from_slice(&self.delay_buffer[start..]);
964 out.extend_from_slice(&frame[..frame_size * ch]);
965 }
966
967 fn update_delay(&mut self, delayed: &[f32], frame_size: usize) {
968 let ch = self.channels;
969 let eb = encoder_buffer(self.sample_rate) * ch;
970 let tb = self.total_buffer() * ch;
971 let fb = frame_size * ch;
972 if eb > fb + tb {
973 let keep = eb - fb - tb;
974 self.delay_buffer.copy_within(fb..fb + keep, 0);
975 self.delay_buffer[keep..].copy_from_slice(delayed);
976 } else {
977 self.delay_buffer.copy_from_slice(&delayed[fb + tb - eb..]);
978 }
979 }
980
981 fn stereo_fade_step(&mut self, delayed: &mut [f32], frame_size: usize, d: Decision) {
982 if d.mode != Mode::Hybrid || d.stream_channels == 1 {
983 self.stereo_width_q14 = stereo_width_for_rate(d.equiv_rate);
984 }
985 if self.channels == 2
986 && (self.hybrid_stereo_width_q14 < 16384 || self.stereo_width_q14 < 16384)
987 {
988 let g1 = self.hybrid_stereo_width_q14 as f32 / 16384.0;
989 let g2 = self.stereo_width_q14 as f32 / 16384.0;
990 stereo_fade(delayed, g1, g2, &WINDOW120, frame_size, self.sample_rate);
991 self.hybrid_stereo_width_q14 = self.stereo_width_q14;
992 }
993 }
994
995 fn fade_celt_input(&mut self, delayed: &mut [f32], frame_size: usize, hb_gain: f32) {
996 let prev = self.prev_hb_gain;
997 if prev < 1.0 || hb_gain < 1.0 {
998 gain_fade(
999 delayed,
1000 prev,
1001 hb_gain,
1002 &WINDOW120,
1003 frame_size,
1004 self.channels,
1005 self.sample_rate,
1006 );
1007 }
1008 self.prev_hb_gain = hb_gain;
1009 }
1010
1011 fn frame_max_data(&self, frame_48k: usize, cap: usize) -> usize {
1012 self.packet_budget(frame_48k, cap)
1013 .unwrap_or(cap)
1014 .min(MAX_FRAME_BYTES)
1015 + 1
1016 }
1017
1018 fn redundancy_bytes(&self, max_data: usize, frame_size: usize, channels: usize) -> usize {
1019 let fs = self.sample_rate as i32;
1020 let bitrate = if self.vbr {
1021 self.bitrate as i32
1022 } else {
1023 bits_to_bitrate(max_data as i32 * 8, fs, frame_size as i32)
1024 };
1025 compute_redundancy_bytes(
1026 max_data as i32,
1027 bitrate,
1028 fs / frame_size as i32,
1029 channels as i32,
1030 )
1031 }
1032
1033 fn switch_ready(&mut self, d: &mut Decision, max_data: usize, frame_size: usize) {
1034 d.redundancy_bytes = self.redundancy_bytes(max_data, frame_size, d.stream_channels);
1035 d.redundancy = d.redundancy_bytes != 0;
1036 d.celt_to_silk = false;
1037 self.silk_bw_switch = true;
1038 }
1039
1040 fn fade_prefill_history(&mut self) {
1041 let (fs, ch) = (self.sample_rate, self.channels);
1042 let n = fs as usize / 400;
1043 let off = (encoder_buffer(fs) - self.total_buffer() - n) * ch;
1044 gain_fade(
1045 &mut self.delay_buffer[off..],
1046 0.0,
1047 1.0,
1048 &WINDOW120,
1049 n,
1050 ch,
1051 fs,
1052 );
1053 self.delay_buffer[..off].fill(0.0);
1054 }
1055
1056 fn silk_prefill(&mut self, f: &SilkFrame, frame_size: usize, activity: i32, prefill: Prefill) {
1057 let flag = if prefill == Prefill::Keep { 2 } else { 1 };
1058 let history = std::mem::take(&mut self.history);
1059 let mut dummy = std::mem::take(&mut self.redundant);
1060 self.silk_layer()
1061 .prefill(&history, frame_size, f, activity, flag, &mut dummy);
1062 self.redundant = dummy;
1063 self.history = history;
1064 }
1065
1066 fn celt_setup(&mut self, mode: Mode, end: usize, stream_channels: usize) {
1067 self.celt.set_lsb_depth(self.lsb_depth);
1068 self.celt.set_end_band(end);
1069 self.celt.set_stream_channels(stream_channels);
1070 self.celt.set_bitrate(BITRATE_MAX);
1071 if mode != Mode::Silk {
1072 self.celt.set_prediction(2);
1073 }
1074 }
1075
1076 fn celt_own(&mut self, pcm: &[f32], frame_size: usize, bytes: usize) -> u32 {
1077 let mut enc = std::mem::take(&mut self.redundant);
1078 self.celt.encode(pcm, frame_size, bytes, &mut enc, true);
1079 self.redundant = enc;
1080 self.celt.final_range()
1081 }
1082
1083 fn celt_to_silk_redundancy(&mut self, delayed: &[f32], bytes: usize, out: &mut [u8]) -> u32 {
1084 let n2 = self.sample_rate as usize / 200;
1085 self.celt.set_start_band(0);
1086 self.celt.set_vbr(false);
1087 self.celt.set_bitrate(BITRATE_MAX);
1088 let rng = self.celt_own(&delayed[..self.channels * n2], n2, bytes);
1089 out[..bytes].copy_from_slice(&self.redundant.data()[..bytes]);
1090 self.celt.reset();
1091 rng
1092 }
1093
1094 fn celt_main(
1095 &mut self,
1096 mode: Mode,
1097 delayed: &[f32],
1098 frame_size: usize,
1099 nb_compr: usize,
1100 celt_rate: i32,
1101 ) -> usize {
1102 self.celt.set_vbr(self.vbr);
1103 if self.vbr {
1104 if mode == Mode::Hybrid {
1105 self.celt.set_bitrate(celt_rate.max(501));
1106 self.celt.set_vbr_constraint(false);
1107 } else {
1108 self.celt.set_vbr_constraint(true);
1109 self.celt.set_bitrate(self.bitrate_bps);
1110 }
1111 }
1112 if self.prev_mode.is_some_and(|p| p != mode) {
1113 let (fs, ch) = (self.sample_rate as usize, self.channels);
1114 let n = fs / 400;
1115 let off = (encoder_buffer(fs as u32) - self.total_buffer()) * ch - n * ch;
1116 let mut tmp = [0.0f32; 2 * 120];
1117 tmp[..n * ch].copy_from_slice(&self.history[off..off + n * ch]);
1118 self.celt.reset();
1119 self.celt_own(&tmp[..n * ch], n, 2);
1120 self.celt.set_prediction(0);
1121 }
1122 let mut ret = nb_compr;
1123 if self.range.tell() as usize <= 8 * nb_compr {
1124 let mut range = std::mem::take(&mut self.range);
1125 let r = self
1126 .celt
1127 .encode(delayed, frame_size, nb_compr, &mut range, false);
1128 self.range = range;
1129 ret = r.max(0) as usize;
1130 }
1131 self.final_range = self.celt.final_range();
1132 ret
1133 }
1134
1135 fn silk_to_celt_redundancy(
1136 &mut self,
1137 delayed: &[f32],
1138 frame_size: usize,
1139 bytes: usize,
1140 out: &mut [u8],
1141 ) -> u32 {
1142 let ch = self.channels;
1143 let n2 = self.sample_rate as usize / 200;
1144 let n4 = self.sample_rate as usize / 400;
1145 self.celt.reset();
1146 self.celt.set_start_band(0);
1147 self.celt.set_prediction(0);
1148 self.celt.set_vbr(false);
1149 self.celt.set_bitrate(BITRATE_MAX);
1150 let tail = &delayed[ch * (frame_size - n2 - n4)..ch * frame_size];
1151 self.celt_own(&tail[..ch * n4], n4, 2);
1152 let rng = self.celt_own(&tail[ch * n4..], n2, bytes);
1153 out[..bytes].copy_from_slice(&self.redundant.data()[..bytes]);
1154 rng
1155 }
1156
1157 fn code_redundancy_flags(&mut self, d: &mut Decision, max_data: usize, hybrid: bool) {
1158 let max_payload = max_data - 1;
1159 if self.range.tell() as usize + 17 + 20 * usize::from(hybrid) <= 8 * max_payload {
1160 if hybrid {
1161 self.range.enc_bit_logp(d.redundancy, 12);
1162 }
1163 if d.redundancy {
1164 self.range.enc_bit_logp(d.celt_to_silk, 1);
1165 let overhead = if hybrid { 8 + 3 + 7 } else { 7 };
1166 let used = (self.range.tell() as usize + overhead) >> 3;
1167 let max_red = max_payload as i64 - used as i64;
1168 let bytes = (d.redundancy_bytes as i64)
1169 .min(max_red)
1170 .clamp(2, MAX_REDUNDANCY_BYTES as i64);
1171 d.redundancy_bytes = bytes as usize;
1172 if hybrid {
1173 self.range.enc_uint((bytes - 2) as u32, 256);
1174 }
1175 }
1176 } else {
1177 d.redundancy = false;
1178 }
1179 if !d.redundancy {
1180 self.silk_bw_switch = false;
1181 d.redundancy_bytes = 0;
1182 }
1183 }
1184
1185 fn encode_mode(
1186 &mut self,
1187 raw: &[f32],
1188 pcm: &[f32],
1189 delayed: &mut [f32],
1190 frame_size: usize,
1191 cap: usize,
1192 d: Decision,
1193 ) -> Result<(u8, Payload)> {
1194 match d.mode {
1195 Mode::Silk => self.encode_silk(raw, pcm, delayed, frame_size, cap, d),
1196 Mode::Hybrid => {
1197 let frame_48k = frame_size * self.upsample;
1198 let payload = self.encode_hybrid(raw, pcm, delayed, frame_size, d, cap)?;
1199 let config =
1200 12 + if d.bandwidth == Bandwidth::Full {
1201 2u8
1202 } else {
1203 0
1204 } + if frame_48k == 960 { 1 } else { 0 };
1205 Ok((
1206 (config << 3) | (u8::from(d.stream_channels == 2) << 2),
1207 payload,
1208 ))
1209 }
1210 Mode::Celt => {
1211 let (toc, frame_48k, end) = self.toc(frame_size, d.bandwidth, d.stream_channels)?;
1212 self.fade_celt_input(delayed, frame_size, 1.0);
1213 self.stereo_fade_step(delayed, frame_size, d);
1214 let input = &*delayed;
1215 let _ = frame_48k;
1216 let n = self.encode_frame(input, frame_size, end, cap, d.stream_channels)?;
1217 Ok((toc, Payload::Range(n)))
1218 }
1219 }
1220 }
1221
1222 fn encode_silk(
1223 &mut self,
1224 raw: &[f32],
1225 pcm: &[f32],
1226 delayed: &mut [f32],
1227 frame_size: usize,
1228 cap: usize,
1229 mut d: Decision,
1230 ) -> Result<(u8, Payload)> {
1231 let frame_48k = frame_size * self.upsample;
1232 self.fade_celt_input(delayed, frame_size, 1.0);
1233 let max_data_bytes = self.frame_max_data(frame_48k, cap);
1234 let fs_khz = silk_fs_khz(d.bandwidth);
1235 let f = self.silk_frame(d, max_data_bytes, fs_khz, false, false);
1236 let activity = self.silk_activity(raw, frame_size);
1237 self.range.reset(max_data_bytes - 1);
1238 if d.prefill != Prefill::Off {
1239 self.silk_prefill(&f, frame_size, activity, d.prefill);
1240 }
1241 let mut range = std::mem::take(&mut self.range);
1242 let silk = self
1243 .silk_layer()
1244 .encode(pcm, frame_size, &f, activity, &mut range);
1245 self.range = range;
1246 self.stereo_width_q14 = silk.stereo_width_q14;
1247 self.stereo_fade_step(delayed, frame_size, d);
1248 if silk.opus_can_switch {
1249 self.switch_ready(&mut d, max_data_bytes, frame_size);
1250 }
1251 self.code_redundancy_flags(&mut d, max_data_bytes, false);
1252 let khz = silk.internal_khz;
1253 let end = if khz == 8 { 13 } else { 17 };
1254 self.celt_setup(Mode::Silk, end, d.stream_channels);
1255 if d.redundancy {
1256 self.celt.set_analysis(&self.info);
1257 }
1258 let mut red = [0u8; MAX_REDUNDANCY_BYTES];
1259 let mut red_rng = 0;
1260 if d.redundancy && d.celt_to_silk {
1261 red_rng = self.celt_to_silk_redundancy(delayed, d.redundancy_bytes, &mut red);
1262 }
1263 self.celt.set_start_band(17);
1264 let mut len = (self.range.tell() as usize).div_ceil(8);
1265 self.range.done();
1266 let bust = self.range.tell() as usize > (max_data_bytes - 1) * 8;
1267 if bust {
1268 self.range.reset(1);
1269 len = 1;
1270 } else if !d.redundancy {
1271 while len > 2 && self.range.data()[len - 1] == 0 {
1272 len -= 1;
1273 }
1274 }
1275 if d.redundancy && !d.celt_to_silk {
1276 red_rng =
1277 self.silk_to_celt_redundancy(delayed, frame_size, d.redundancy_bytes, &mut red);
1278 }
1279 let red_len = if d.redundancy { d.redundancy_bytes } else { 0 };
1280 self.final_range = if bust {
1281 0
1282 } else {
1283 self.range.range() ^ red_rng
1284 };
1285 let body = len + red_len;
1286 self.silk_buf[..len].copy_from_slice(&self.range.data()[..len]);
1287 self.silk_buf[len..body].copy_from_slice(&red[..red_len]);
1288 let base = match khz {
1289 8 => 0u8,
1290 12 => 4,
1291 _ => 8,
1292 };
1293 let duration = match frame_48k {
1294 480 => 0u8,
1295 960 => 1,
1296 1920 => 2,
1297 _ => 3,
1298 };
1299 let toc = ((base + duration) << 3) | (u8::from(d.stream_channels == 2) << 2);
1300 if !self.vbr && body + 1 < max_data_bytes {
1301 let pad_amount = max_data_bytes - (body + 2);
1302 let nb_255s = if pad_amount > 0 {
1303 (pad_amount - 1) / 255
1304 } else {
1305 0
1306 };
1307 let pos = if pad_amount > 0 { nb_255s + 2 } else { 1 };
1308 let buf = &mut self.silk_buf[..];
1309 buf.copy_within(0..body, pos);
1310 buf[0] = if pad_amount > 0 { 0x41 } else { 1 };
1311 if pad_amount > 0 {
1312 buf[1..1 + nb_255s].fill(255);
1313 buf[1 + nb_255s] = (pad_amount - 255 * nb_255s - 1) as u8;
1314 }
1315 buf[pos + body..max_data_bytes - 1].fill(0);
1316 return Ok((toc | 3, Payload::Silk(max_data_bytes - 1)));
1317 }
1318 Ok((toc, Payload::Silk(body)))
1319 }
1320
1321 fn encode_multiframe(
1322 &mut self,
1323 pcm: &[f32],
1324 frame_size: usize,
1325 cap: usize,
1326 d: Decision,
1327 cursor: (usize, i32),
1328 self_delimited: bool,
1329 ) -> Result<(u8, Payload)> {
1330 let count = frame_size * self.upsample / 960;
1331 if !matches!(count, 2 | 3) || frame_size * self.upsample != count * 960 {
1332 return Err(Error::unsupported(
1333 format!(
1334 "opus frame of {frame_size} samples at {} Hz",
1335 self.sample_rate
1336 ),
1337 "frames are 2.5, 5, 10, 20, 40 or 60 ms",
1338 ));
1339 }
1340 let sub = frame_size / count;
1341 let max_data = if self.vbr {
1342 cap + 1
1343 } else {
1344 let bits = bitrate_to_bits(
1345 self.bitrate as i32,
1346 self.sample_rate as i32,
1347 frame_size as i32,
1348 );
1349 (((bits + 4) / 8) as usize).max(1).min(cap + 1)
1350 };
1351 let max_data = max_data.min(MAX_SILK_PACKET_BYTES);
1352 let max_header = if count == 2 { 3 } else { 2 + (count - 1) * 2 };
1353 let max_len_sum = (count + max_data).saturating_sub(max_header);
1354 let mut frames: Vec<Vec<u8>> = Vec::with_capacity(count);
1355 let mut tot = 0usize;
1356 let mut toc = 0u8;
1357 let mut result: Result<()> = Ok(());
1358 if d.to_mono {
1359 self.force_mono = true;
1360 } else {
1361 self.prev_channels = d.stream_channels;
1362 }
1363 if self.analysis_on {
1364 self.analysis.seek(cursor);
1365 }
1366 for i in 0..count {
1367 let bits = bitrate_to_bits(self.bitrate as i32, self.sample_rate as i32, sub as i32);
1368 let mut curr_max = ((bits / 8) as usize).min(max_len_sum / count);
1369 curr_max = curr_max.min(max_len_sum.saturating_sub(tot));
1370 let mut sub_d = d;
1371 sub_d.to_celt = d.to_celt && i == count - 1;
1372 sub_d.redundancy = d.redundancy && (sub_d.to_celt || (!d.to_celt && i == 0));
1373 sub_d.to_mono = d.to_mono && i == 0;
1374 self.nonfinal = i < count - 1;
1375 if self.analysis_on {
1376 self.info = self.analysis.sub_info(sub);
1377 }
1378 let chunk = &pcm[i * sub * self.channels..(i + 1) * sub * self.channels];
1379 match self.encode_frame_decided(chunk, sub, curr_max.saturating_sub(1), sub_d) {
1380 Ok((t, payload)) => {
1381 let bytes = self.payload_bytes(payload).to_vec();
1382 tot += 1 + bytes.len();
1383 if i == 0 {
1384 toc = t;
1385 }
1386 frames.push(bytes);
1387 }
1388 Err(e) => {
1389 result = Err(e);
1390 break;
1391 }
1392 }
1393 }
1394 self.nonfinal = false;
1395 result?;
1396 let dtx = frames.iter().filter(|f| f.is_empty()).count();
1397 let pad = !self_delimited && !self.vbr && dtx != count;
1398 let (code, size) = self.pack_frames(&frames, max_data, pad)?;
1399 Ok(((toc & !3) | code, Payload::Silk(size)))
1400 }
1401
1402 fn pack_frames(
1403 &mut self,
1404 frames: &[Vec<u8>],
1405 max_data: usize,
1406 pad: bool,
1407 ) -> Result<(u8, usize)> {
1408 let count = frames.len();
1409 let len0 = frames[0].len();
1410 let limit = max_data - 1;
1411 let lens_differ = frames.iter().any(|f| f.len() != len0);
1412 let too_big = || Error::corrupt("opus encode: multi-frame packet exceeds its budget");
1413 if count == 2 {
1414 let size = if lens_differ {
1415 len0 + frames[1].len() + 1 + usize::from(len0 >= 252)
1416 } else {
1417 2 * len0
1418 };
1419 if !(pad && size < limit) {
1420 if size > limit {
1421 return Err(too_big());
1422 }
1423 let buf = &mut self.silk_buf[..];
1424 let mut pos = 0;
1425 if lens_differ {
1426 Self::write_frame_len(buf, &mut pos, len0)?;
1427 }
1428 for f in frames {
1429 buf[pos..pos + f.len()].copy_from_slice(f);
1430 pos += f.len();
1431 }
1432 return Ok((if lens_differ { 2 } else { 1 }, pos));
1433 }
1434 }
1435 let vbr = lens_differ;
1436 let size = if vbr {
1437 1 + frames[..count - 1]
1438 .iter()
1439 .map(|f| f.len() + 1 + usize::from(f.len() >= 252))
1440 .sum::<usize>()
1441 + frames[count - 1].len()
1442 } else {
1443 1 + count * len0
1444 };
1445 if size > limit {
1446 return Err(too_big());
1447 }
1448 let pad_amount = if pad { limit - size } else { 0 };
1449 let buf = &mut self.silk_buf[..];
1450 buf[0] = count as u8 | (u8::from(vbr) << 7) | (u8::from(pad_amount != 0) << 6);
1451 let mut pos = 1;
1452 if pad_amount != 0 {
1453 let nb255 = (pad_amount - 1) / 255;
1454 buf[pos..pos + nb255].fill(255);
1455 pos += nb255;
1456 buf[pos] = (pad_amount - 255 * nb255 - 1) as u8;
1457 pos += 1;
1458 }
1459 if vbr {
1460 for f in &frames[..count - 1] {
1461 Self::write_frame_len(buf, &mut pos, f.len())?;
1462 }
1463 }
1464 for f in frames {
1465 buf[pos..pos + f.len()].copy_from_slice(f);
1466 pos += f.len();
1467 }
1468 if pad_amount != 0 {
1469 buf[pos..limit].fill(0);
1470 pos = limit;
1471 }
1472 Ok((3, pos))
1473 }
1474
1475 fn frame_len_at(payload: &[u8], pos: usize) -> (usize, usize) {
1476 let b0 = usize::from(payload[pos]);
1477 if b0 < 252 {
1478 (b0, 1)
1479 } else {
1480 (b0 + 4 * usize::from(payload[pos + 1]), 2)
1481 }
1482 }
1483
1484 fn self_delimited_split(toc: u8, payload: &[u8]) -> (usize, usize) {
1485 match toc & 3 {
1486 0 => (0, payload.len()),
1487 1 => (0, payload.len() / 2),
1488 2 => {
1489 let (len0, used) = Self::frame_len_at(payload, 0);
1490 (used, payload.len() - used - len0)
1491 }
1492 _ => {
1493 let count = usize::from(payload[0] & 0x3F);
1494 let vbr = payload[0] & 0x80 != 0;
1495 let mut pos = 1;
1496 let mut pad = 0;
1497 if payload[0] & 0x40 != 0 {
1498 loop {
1499 let p = usize::from(payload[pos]);
1500 pos += 1;
1501 if p == 255 {
1502 pad += 254;
1503 } else {
1504 pad += p;
1505 break;
1506 }
1507 }
1508 }
1509 if vbr {
1510 let mut sum = 0;
1511 for _ in 1..count {
1512 let (len, used) = Self::frame_len_at(payload, pos);
1513 sum += len;
1514 pos += used;
1515 }
1516 (pos, payload.len() - pos - pad - sum)
1517 } else {
1518 (pos, (payload.len() - pos - pad) / count)
1519 }
1520 }
1521 }
1522 }
1523
1524 /// The TOC byte, the frame size in 48 kHz samples and the CELT end band
1525 /// for a frame of `frame_size` input samples per channel.
1526 fn toc(
1527 &self,
1528 frame_size: usize,
1529 bandwidth: Bandwidth,
1530 stream_channels: usize,
1531 ) -> Result<(u8, usize, usize)> {
1532 let frame_48k = frame_size * self.upsample;
1533 let fs_idx: u8 = match frame_48k {
1534 120 => 0,
1535 240 => 1,
1536 480 => 2,
1537 960 => 3,
1538 _ => {
1539 return Err(Error::unsupported(
1540 format!(
1541 "opus frame of {frame_size} samples at {} Hz",
1542 self.sample_rate
1543 ),
1544 "CELT frames are 2.5, 5, 10 or 20 ms",
1545 ));
1546 }
1547 };
1548 let bw_idx: u8 = match bandwidth {
1549 Bandwidth::Narrow => 0,
1550 Bandwidth::Medium | Bandwidth::Wide => 1,
1551 Bandwidth::SuperWide => 2,
1552 Bandwidth::Full => 3,
1553 };
1554 let config = 16 + 4 * bw_idx + fs_idx;
1555 Ok((
1556 (config << 3) | (u8::from(stream_channels == 2) << 2),
1557 frame_48k,
1558 bandwidth.celt_end_band(),
1559 ))
1560 }
1561
1562 fn decide_fec(&self, mode: Mode, bw: Bandwidth, rate: i32) -> (bool, Bandwidth) {
1563 const FEC_THRESHOLDS: [i32; 10] = [
1564 12000, 1000, 14000, 1000, 16000, 1000, 20000, 1000, 22000, 1000,
1565 ];
1566 let loss = self.packet_loss_perc as i32;
1567 if !self.inband_fec || loss == 0 || mode == Mode::Celt {
1568 return (false, bw);
1569 }
1570 let mut b = bw_index(bw);
1571 loop {
1572 let mut thres = FEC_THRESHOLDS[2 * b];
1573 let hyst = FEC_THRESHOLDS[2 * b + 1];
1574 if self.lbrr_coded {
1575 thres -= hyst;
1576 } else {
1577 thres += hyst;
1578 }
1579 thres = ((thres as i64 * (125 - loss.min(25)) as i64 * 655) >> 16) as i32;
1580 if rate > thres {
1581 return (true, BANDWIDTHS[b]);
1582 } else if loss <= 5 {
1583 return (false, bw);
1584 } else if b > 0 {
1585 b -= 1;
1586 } else {
1587 return (false, bw);
1588 }
1589 }
1590 }
1591
1592 fn voice_est(&self) -> i32 {
1593 if self.voice_ratio >= 0 {
1594 let v = (self.voice_ratio * 327) >> 8;
1595 if self.application == Application::Audio {
1596 v.min(115)
1597 } else {
1598 v
1599 }
1600 } else if self.application == Application::Voip {
1601 115
1602 } else {
1603 48
1604 }
1605 }
1606
1607 fn decide(&mut self, pcm: &[f32], frame_size: usize, max_data_bytes: usize) -> Decision {
1608 let fs = self.sample_rate as i32;
1609 let fsz = frame_size as i32;
1610 let frame_rate = fs / fsz;
1611 let channels = self.channels as i32;
1612 let loss = i32::from(self.packet_loss_perc);
1613 let is_silence = pcm
1614 .iter()
1615 .take(frame_size * self.channels)
1616 .all(|x| x.abs() <= self.silence_threshold());
1617 let stereo_width = if self.channels == 2 && !self.force_mono {
1618 update_stereo_width(&mut self.width_mem, pcm, frame_size, self.sample_rate)
1619 } else {
1620 0.0
1621 };
1622 if !is_silence {
1623 self.voice_ratio = -1;
1624 }
1625 if self.info.valid {
1626 let prob = match self.prev_mode {
1627 None => self.info.music_prob,
1628 Some(Mode::Celt) => self.info.music_prob_max,
1629 Some(_) => self.info.music_prob_min,
1630 };
1631 self.voice_ratio = (0.5 + 100.0 * (1.0 - prob)).floor() as i32;
1632 }
1633 let detected = self
1634 .info
1635 .valid
1636 .then(|| detected_bandwidth(self.info.bandwidth));
1637
1638 let mut bitrate =
1639 (self.bitrate as i32).min(bits_to_bitrate(max_data_bytes as i32 * 8, fs, fsz));
1640 let mut max_data = max_data_bytes as i32;
1641 if !self.vbr {
1642 let cbr_bytes = ((bitrate_to_bits(bitrate, fs, fsz) + 4) / 8).min(max_data);
1643 bitrate = bits_to_bitrate(cbr_bytes * 8, fs, fsz);
1644 max_data = cbr_bytes.max(1);
1645 }
1646 self.bitrate_bps = bitrate;
1647 if max_data < 3
1648 || bitrate < 3 * frame_rate * 8
1649 || (frame_rate < 50 && (max_data * frame_rate < 300 || bitrate < 2400))
1650 {
1651 return Decision {
1652 mode: self.prev_mode.unwrap_or(Mode::Hybrid),
1653 bandwidth: self.coded_bandwidth,
1654 stream_channels: self.stream_channels,
1655 equiv_rate: 0,
1656 redundancy: false,
1657 redundancy_bytes: 0,
1658 celt_to_silk: false,
1659 to_celt: false,
1660 prefill: Prefill::Off,
1661 to_mono: false,
1662 toc_only: Some(max_data as usize),
1663 };
1664 }
1665 let max_rate = bits_to_bitrate(max_data * 8, fs, fsz);
1666 let ve = self.voice_est();
1667 let mut equiv = compute_equiv_rate(bitrate, channels, frame_rate, self.vbr, None, loss);
1668
1669 let mut stream_channels = self.channels;
1670 if self.channels == 2 && self.force_mono {
1671 stream_channels = 1;
1672 } else if self.channels == 2 {
1673 let mut threshold = STEREO_THRESHOLD_MUSIC
1674 + ((ve * ve * (STEREO_THRESHOLD_VOICE - STEREO_THRESHOLD_MUSIC)) >> 14);
1675 threshold += if self.stream_channels == 2 {
1676 -1000
1677 } else {
1678 1000
1679 };
1680 stream_channels = if equiv > threshold { 2 } else { 1 };
1681 }
1682 let sc = stream_channels as i32;
1683 equiv = compute_equiv_rate(bitrate, sc, frame_rate, self.vbr, None, loss);
1684
1685 let silk_dtx = self.use_dtx && !(self.info.valid || is_silence);
1686 let mut mode = if self.application == Application::LowDelay {
1687 Mode::Celt
1688 } else if let Some(forced) = self.mode {
1689 forced
1690 } else {
1691 let mode_voice = ((1.0 - stereo_width) * MODE_THRESHOLD_VOICE as f32
1692 + stereo_width * MODE_THRESHOLD_VOICE_STEREO as f32)
1693 as i32;
1694 let mut threshold =
1695 MODE_THRESHOLD_MUSIC + ((ve * ve * (mode_voice - MODE_THRESHOLD_MUSIC)) >> 14);
1696 if self.application == Application::Voip {
1697 threshold += 8000;
1698 }
1699 match self.prev_mode {
1700 Some(Mode::Celt) => threshold -= 4000,
1701 Some(_) => threshold += 4000,
1702 None => {}
1703 }
1704 let mut auto = if equiv >= threshold {
1705 Mode::Celt
1706 } else {
1707 Mode::Silk
1708 };
1709 if self.inband_fec && loss > (128 - ve) >> 4 {
1710 auto = Mode::Silk;
1711 }
1712 if silk_dtx && ve > 100 {
1713 auto = Mode::Silk;
1714 }
1715 let min_bits = bitrate_to_bits(if frame_rate > 50 { 9000 } else { 6000 }, fs, fsz);
1716 if max_data < min_bits / 8 {
1717 auto = Mode::Celt;
1718 }
1719 auto
1720 };
1721 if mode != Mode::Celt && frame_size < self.sample_rate as usize / 100 {
1722 mode = Mode::Celt;
1723 }
1724
1725 let prev = self.prev_mode;
1726 let (mut redundancy, mut celt_to_silk, mut to_celt) = (false, false, false);
1727 if let Some(p) = prev
1728 && (mode == Mode::Celt) != (p == Mode::Celt)
1729 {
1730 redundancy = true;
1731 celt_to_silk = mode != Mode::Celt;
1732 if !celt_to_silk {
1733 if frame_size >= self.sample_rate as usize / 100 {
1734 mode = p;
1735 to_celt = true;
1736 } else {
1737 redundancy = false;
1738 }
1739 }
1740 }
1741
1742 let mut to_mono = false;
1743 if stream_channels == 1
1744 && self.prev_channels == 2
1745 && !self.to_mono
1746 && mode != Mode::Celt
1747 && prev != Some(Mode::Celt)
1748 {
1749 to_mono = true;
1750 stream_channels = 2;
1751 }
1752 let sc = stream_channels as i32;
1753 equiv = compute_equiv_rate(bitrate, sc, frame_rate, self.vbr, Some(mode), loss);
1754 let prefill = if mode != Mode::Celt && prev == Some(Mode::Celt) {
1755 Prefill::Reset
1756 } else {
1757 Prefill::Off
1758 };
1759
1760 let mut auto_bandwidth = self.auto_bandwidth;
1761 let mut bandwidth = self.coded_bandwidth;
1762 if mode == Mode::Celt
1763 || self.first
1764 || self
1765 .silk
1766 .as_ref()
1767 .is_some_and(|s| s.allow_bandwidth_switch())
1768 {
1769 let (voice, music) = if self.channels == 2 && !self.force_mono {
1770 (&STEREO_VOICE_BW, &STEREO_MUSIC_BW)
1771 } else {
1772 (&MONO_VOICE_BW, &MONO_MUSIC_BW)
1773 };
1774 let th: [i32; 8] =
1775 std::array::from_fn(|i| music[i] + ((ve * ve * (voice[i] - music[i])) >> 14));
1776 let mut idx = 4;
1777 loop {
1778 let mut threshold = th[2 * (idx - 1)];
1779 let hysteresis = th[2 * (idx - 1) + 1];
1780 if !self.first {
1781 if bw_index(self.auto_bandwidth) >= idx {
1782 threshold -= hysteresis;
1783 } else {
1784 threshold += hysteresis;
1785 }
1786 }
1787 if equiv >= threshold {
1788 break;
1789 }
1790 idx -= 1;
1791 if idx == 0 {
1792 break;
1793 }
1794 }
1795 if idx == 1 {
1796 idx = 2;
1797 }
1798 auto_bandwidth = BANDWIDTHS[idx];
1799 bandwidth = auto_bandwidth;
1800 let in_wb = self
1801 .silk
1802 .as_ref()
1803 .is_some_and(|s| s.in_wb_mode_without_variable_lp());
1804 if !self.first && mode != Mode::Celt && !in_wb && bandwidth > Bandwidth::Wide {
1805 bandwidth = Bandwidth::Wide;
1806 }
1807 }
1808 if let Some(user) = self.bandwidth {
1809 bandwidth = user;
1810 }
1811 if mode != Mode::Celt && max_rate < 15000 {
1812 bandwidth = bandwidth.min(Bandwidth::Wide);
1813 }
1814 let ceiling = match self.sample_rate {
1815 48000 => Bandwidth::Full,
1816 24000 => Bandwidth::SuperWide,
1817 16000 => Bandwidth::Wide,
1818 12000 => Bandwidth::Medium,
1819 _ => Bandwidth::Narrow,
1820 };
1821 bandwidth = bandwidth.min(ceiling);
1822 if let Some(det) = detected.filter(|_| self.bandwidth.is_none()) {
1823 let floor = if equiv <= 18000 * sc && mode == Mode::Celt {
1824 Bandwidth::Narrow
1825 } else if equiv <= 24000 * sc && mode == Mode::Celt {
1826 Bandwidth::Medium
1827 } else if equiv <= 30000 * sc {
1828 Bandwidth::Wide
1829 } else if equiv <= 44000 * sc {
1830 Bandwidth::SuperWide
1831 } else {
1832 Bandwidth::Full
1833 };
1834 bandwidth = bandwidth.min(det.max(floor));
1835 }
1836 let (fec, mut bandwidth) = self.decide_fec(mode, bandwidth, equiv);
1837 if mode == Mode::Celt && bandwidth == Bandwidth::Medium {
1838 bandwidth = Bandwidth::Wide;
1839 }
1840
1841 if mode == Mode::Silk && bandwidth > Bandwidth::Wide {
1842 mode = Mode::Hybrid;
1843 }
1844 if mode == Mode::Hybrid && bandwidth <= Bandwidth::Wide {
1845 mode = Mode::Silk;
1846 }
1847 if mode == Mode::Hybrid {
1848 let silk_rate = silk_rate_for_hybrid(
1849 bitrate,
1850 bandwidth == Bandwidth::SuperWide,
1851 fs == 50 * fsz,
1852 self.vbr,
1853 fec,
1854 sc,
1855 );
1856 if bitrate - silk_rate <= 500 {
1857 mode = Mode::Silk;
1858 bandwidth = Bandwidth::Wide;
1859 }
1860 }
1861
1862 self.stream_channels = stream_channels;
1863 self.to_mono = to_mono;
1864 self.auto_bandwidth = auto_bandwidth;
1865 self.coded_bandwidth = bandwidth;
1866 self.lbrr_coded = fec;
1867 Decision {
1868 mode,
1869 bandwidth,
1870 stream_channels,
1871 equiv_rate: equiv,
1872 redundancy,
1873 redundancy_bytes: 0,
1874 celt_to_silk,
1875 to_celt,
1876 prefill,
1877 to_mono,
1878 toc_only: None,
1879 }
1880 }
1881
1882 /// Encodes one frame — `frame_size` samples per channel of interleaved
1883 /// `f32` at the input rate, 2.5, 5, 10 or 20 ms of it — as a code-0 Opus
1884 /// packet in `out`, returning the packet length.
1885 pub fn encode_float(
1886 &mut self,
1887 pcm: &[f32],
1888 frame_size: usize,
1889 out: &mut [u8],
1890 ) -> Result<usize> {
1891 match self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1), false) {
1892 Err(e) => Err(e),
1893 Ok((toc, payload)) => {
1894 let n = payload.len();
1895 let count = payload.first().copied().unwrap_or(0);
1896 if out.len() < 1 + n {
1897 Err(Error::corrupt(format!(
1898 "opus encode: packet needs {} bytes, buffer holds {}",
1899 1 + n,
1900 out.len()
1901 )))
1902 } else {
1903 out[0] = toc;
1904 out[1..1 + n].copy_from_slice(payload);
1905 if self.dtx_frame(pcm, frame_size) {
1906 self.final_range = 0;
1907 let (bytes, len) = dtx_packet(toc, count, false);
1908 if out.len() < len {
1909 Err(Error::corrupt("opus encode: DTX packet buffer too small"))
1910 } else {
1911 out[..len].copy_from_slice(&bytes[..len]);
1912 Ok(len)
1913 }
1914 } else {
1915 Ok(1 + n)
1916 }
1917 }
1918 }
1919 }
1920 }
1921
1922 /// [`Encoder::encode_float`] from 16-bit samples.
1923 pub fn encode(&mut self, pcm: &[i16], frame_size: usize, out: &mut [u8]) -> Result<usize> {
1924 let float: Vec<f32> = pcm.iter().map(|&v| v as f32 * (1.0 / 32768.0)).collect();
1925 self.lsb_depth = 16;
1926 let r = self.encode_float(&float, frame_size, out);
1927 self.lsb_depth = 24;
1928 r
1929 }
1930
1931 fn total_buffer(&self) -> usize {
1932 if self.align_input {
1933 self.sample_rate as usize / 250
1934 } else {
1935 0
1936 }
1937 }
1938
1939 fn silence_threshold(&self) -> f32 {
1940 1.0 / (1u32 << self.lsb_depth) as f32
1941 }
1942
1943 /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716
1944 /// Appendix B: TOC, an explicit frame length, then the frame. This is
1945 /// what every stream but the last uses inside a multistream packet.
1946 pub fn encode_self_delimited(
1947 &mut self,
1948 pcm: &[f32],
1949 frame_size: usize,
1950 out: &mut [u8],
1951 ) -> Result<usize> {
1952 match self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3), true) {
1953 Err(e) => Err(e),
1954 Ok((toc, payload)) => {
1955 let count = payload.first().copied().unwrap_or(0);
1956 let (head, last) = Self::self_delimited_split(toc, payload);
1957 let mut len = [0u8; 2];
1958 let mut len_bytes = 0;
1959 let r = Self::write_frame_len(&mut len, &mut len_bytes, last);
1960 let total = 1 + len_bytes + payload.len();
1961 match r {
1962 Err(e) => Err(e),
1963 Ok(()) if out.len() < total => Err(Error::corrupt(format!(
1964 "opus encode: self-delimited packet needs {total} bytes, buffer holds {}",
1965 out.len()
1966 ))),
1967 Ok(()) => {
1968 out[0] = toc;
1969 out[1..1 + head].copy_from_slice(&payload[..head]);
1970 out[1 + head..1 + head + len_bytes].copy_from_slice(&len[..len_bytes]);
1971 out[1 + head + len_bytes..total].copy_from_slice(&payload[head..]);
1972 if self.dtx_frame(pcm, frame_size) {
1973 self.final_range = 0;
1974 let (bytes, len) = dtx_packet(toc, count, true);
1975 if out.len() < len {
1976 Err(Error::corrupt("opus encode: DTX packet buffer too small"))
1977 } else {
1978 out[..len].copy_from_slice(&bytes[..len]);
1979 Ok(len)
1980 }
1981 } else {
1982 Ok(total)
1983 }
1984 }
1985 }
1986 }
1987 }
1988 }
1989
1990 /// One hybrid frame (10 or 20 ms, mono or stereo, `bandwidth` SWB or FB)
1991 /// into the internal range coder, returning its payload: the SILK
1992 /// layer's symbols (WB, 16 kHz internal), the redundancy flag under the
1993 /// decoder's exact presence rule, then the CELT layer from band 17 in the
1994 /// same coder, followed by any redundant frame. CBR: the packet is the
1995 /// bitrate's size unless SILK alone needs more, in which case CELT keeps
1996 /// [`HYBRID_CELT_MIN_BYTES`] on top.
1997 fn encode_hybrid(
1998 &mut self,
1999 raw: &[f32],
2000 pcm: &[f32],
2001 delayed: &mut [f32],
2002 frame_size: usize,
2003 mut d: Decision,
2004 cap: usize,
2005 ) -> Result<Payload> {
2006 let bandwidth = d.bandwidth;
2007 let cap = cap.min(MAX_FRAME_BYTES);
2008 let frame_48k = frame_size * self.upsample;
2009 if cap < HYBRID_CELT_MIN_BYTES + 2 {
2010 return Err(Error::corrupt(
2011 "opus encode: output buffer smaller than the minimum hybrid packet",
2012 ));
2013 }
2014 let max_data_bytes = self.frame_max_data(frame_48k, cap);
2015 let budget = max_data_bytes - 1;
2016 self.range.reset(budget);
2017 let f = self.silk_frame(
2018 d,
2019 max_data_bytes,
2020 16,
2021 true,
2022 bandwidth == Bandwidth::SuperWide,
2023 );
2024 let activity = self.silk_activity(raw, frame_size);
2025 if d.prefill != Prefill::Off {
2026 self.silk_prefill(&f, frame_size, activity, d.prefill);
2027 }
2028 let mut range = std::mem::take(&mut self.range);
2029 let silk = self
2030 .silk_layer()
2031 .encode(pcm, frame_size, &f, activity, &mut range);
2032 self.range = range;
2033 self.stereo_width_q14 = silk.stereo_width_q14;
2034 if silk.opus_can_switch {
2035 self.switch_ready(&mut d, max_data_bytes, frame_size);
2036 }
2037 let celt_rate = silk.total_bit_rate - silk.bit_rate;
2038 let hb_gain = 1.0 - crate::celt_flp::celt_exp2(-(celt_rate as f32) * (1.0 / 1024.0));
2039 self.fade_celt_input(delayed, frame_size, hb_gain);
2040 self.stereo_fade_step(delayed, frame_size, d);
2041 self.code_redundancy_flags(&mut d, max_data_bytes, true);
2042 let end = bandwidth.celt_end_band();
2043 let red_len = if d.redundancy { d.redundancy_bytes } else { 0 };
2044 let nb_compr = budget - red_len;
2045 self.range.shrink(nb_compr);
2046 self.celt_setup(Mode::Hybrid, end, d.stream_channels);
2047 self.celt.set_analysis(&self.info);
2048 self.celt.set_silk_info(silk.signal_type, silk.offset);
2049 let mut red = [0u8; MAX_REDUNDANCY_BYTES];
2050 let mut red_rng = 0;
2051 if d.redundancy && d.celt_to_silk {
2052 red_rng = self.celt_to_silk_redundancy(delayed, red_len, &mut red);
2053 }
2054 self.celt.set_start_band(17);
2055 let celt_rate = self.bitrate_bps - silk.bit_rate;
2056 let n = self.celt_main(Mode::Hybrid, delayed, frame_size, nb_compr, celt_rate);
2057 if d.redundancy && !d.celt_to_silk {
2058 self.range.shrink(n);
2059 red_rng = self.silk_to_celt_redundancy(delayed, frame_size, red_len, &mut red);
2060 }
2061 let final_range = self.final_range ^ red_rng;
2062 self.final_range = final_range;
2063 self.silk_buf[..n].copy_from_slice(&self.range.data()[..n]);
2064 self.silk_buf[n..n + red_len].copy_from_slice(&red[..red_len]);
2065 Ok(Payload::Silk(n + red_len))
2066 }
2067
2068 fn encode_frame(
2069 &mut self,
2070 delayed: &[f32],
2071 frame_size: usize,
2072 end: usize,
2073 cap: usize,
2074 stream_channels: usize,
2075 ) -> Result<usize> {
2076 let max_data_bytes = self.frame_max_data(frame_size * self.upsample, cap);
2077 if max_data_bytes < 3 {
2078 return Err(Error::corrupt(
2079 "opus encode: output buffer smaller than the minimum packet",
2080 ));
2081 }
2082 self.range.reset(max_data_bytes - 1);
2083 self.celt_setup(Mode::Celt, end, stream_channels);
2084 self.celt.set_analysis(&self.info);
2085 self.celt.set_start_band(0);
2086 let n = self.celt_main(Mode::Celt, delayed, frame_size, max_data_bytes - 1, 0);
2087 Ok(n)
2088 }
2089}
2090
2091#[cfg(test)]
2092mod tests {
2093 use super::*;
2094
2095 fn decided_bandwidth(e: &mut Encoder) -> Bandwidth {
2096 let pcm = vec![0.0f32; 960 * e.channels];
2097 e.decide(&pcm, 960, 1276).bandwidth
2098 }
2099
2100 #[test]
2101 fn detected_bandwidth_lowers_the_coded_bandwidth_but_not_below_its_floor() {
2102 let mut e = Encoder::new(48000, 2, Application::Audio).unwrap();
2103 e.set_vbr_constrained(true);
2104 e.set_bitrate(64_000);
2105 e.info.valid = true;
2106 e.info.bandwidth = 15;
2107 assert_eq!(decided_bandwidth(&mut e), Bandwidth::SuperWide);
2108 e.info.bandwidth = 20;
2109 assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full);
2110 e.info.bandwidth = 15;
2111 e.set_bitrate(96_000);
2112 assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full);
2113 e.set_bitrate(64_000);
2114 e.info.valid = false;
2115 assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full);
2116 }
2117
2118 #[test]
2119 fn bandwidth_follows_the_bitrate_the_application_and_the_input_rate() {
2120 let mut e = Encoder::new(48000, 1, Application::Audio).unwrap();
2121 e.set_bitrate(64000);
2122 assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full);
2123 e.set_bitrate(16000);
2124 assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full);
2125 e.set_bitrate(10000);
2126 assert_eq!(decided_bandwidth(&mut e), Bandwidth::Wide);
2127 e.set_bitrate(8000);
2128 assert_eq!(decided_bandwidth(&mut e), Bandwidth::Narrow);
2129 let mut v = Encoder::new(48000, 1, Application::Voip).unwrap();
2130 v.set_bitrate(16000);
2131 assert_eq!(decided_bandwidth(&mut v), Bandwidth::Full);
2132 let mut e = Encoder::new(24000, 2, Application::Audio).unwrap();
2133 e.set_bitrate(256_000);
2134 let pcm = vec![0.0f32; 480 * 2];
2135 assert_eq!(e.decide(&pcm, 480, 1276).bandwidth, Bandwidth::SuperWide);
2136 assert_eq!(
2137 e.look_ahead(960),
2138 (CELT_OVERLAP_48K + CELT_DELAY_COMP_48K) / 2
2139 );
2140 }
2141
2142 #[test]
2143 fn look_ahead_is_libopus_delay_in_every_mode() {
2144 let full = CELT_OVERLAP_48K + CELT_DELAY_COMP_48K;
2145 let mut e = Encoder::new(48000, 1, Application::Voip).unwrap();
2146 for bps in [8000, 16000, 32000, 64000] {
2147 e.set_bitrate(bps);
2148 for fs in [240, 480, 960] {
2149 assert_eq!(e.look_ahead(fs), full, "{bps} {fs}");
2150 }
2151 }
2152 let e = Encoder::new(48000, 1, Application::LowDelay).unwrap();
2153 assert_eq!(e.look_ahead(960), CELT_OVERLAP_48K);
2154 }
2155
2156 #[test]
2157 fn voip_auto_mode_is_monotonic_per_channel() {
2158 for channels in [1usize, 2] {
2159 let mut e = Encoder::new(48000, channels, Application::Voip).unwrap();
2160 e.set_vbr_constrained(true);
2161 let pcm = vec![0.0f32; 960 * channels];
2162 let mut last = 0u8;
2163 for per_channel in 500..=45_000u32 {
2164 e.set_bitrate(per_channel * channels as u32);
2165 let d = e.decide(&pcm, 960, 1276);
2166 if d.toc_only.is_some() {
2167 continue;
2168 }
2169 let class = match d.mode {
2170 Mode::Silk => 0,
2171 Mode::Hybrid => 1,
2172 Mode::Celt => 2,
2173 };
2174 assert!(
2175 class >= last,
2176 "{channels}ch {per_channel} bps/channel regressed from {last} to {class}"
2177 );
2178 last = class;
2179 }
2180 }
2181 }
2182}