forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.2 MiBe18142dTahinli4 hours ago4543 commits

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