forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB06bf080Tahinli2 months ago2200 commits

encoder.rs950 lines, 38.5 KiBHistoryRawDownload
1//! The Opus packet encoder: CELT, SILK and hybrid, 8 to 48 kHz in.
2//!
3//! One [`Encoder`] produces ordinary code-0 Opus packets (RFC 6716 Section 3)
4//! or the self-delimited variant of Appendix B that the multistream framing
5//! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s
6//! default) picks CELT (TOC configs 16..31, every rate and frame size), SILK
7//! (TOC configs 0..11, mono NB/MB/WB 10/20/40/60 ms; stereo NB/MB/WB 10/20 ms,
8//! with 40/60 ms carried as code-3 packets of 20 ms SILK frames), or Hybrid
9//! (TOC configs 13/15, mono or stereo SWB/FB 10 or 20 ms: SILK at 16 kHz under
10//! CELT from band 17 up, one range-coded stream).
11//!
12//! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and
13//! the coded bandwidth is capped at the input's own Nyquist, so the images
14//! the stuffing puts there are never coded and the decoder's decimation
15//! drops them. [`Encoder::look_ahead`] reports the delay in *input* samples.
16//!
17//! Rate control is CBR by default — every packet the same size, derived from
18//! the bitrate — or constrained VBR, the reference's reservoir scheme, when
19//! [`Encoder::set_vbr_constrained`] is on. SILK packets are not yet budgeted
20//! against the target rate (D2b).
21
22use ec_core::{Error, Result};
23
24use crate::celt_enc::CeltEncoder;
25use crate::packet::{Bandwidth, Mode};
26use crate::range::RangeEncoder;
27use crate::silk_enc_write::{SilkEncoder, SilkStereoEncoder};
28
29/// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`).
30const MAX_FRAME_BYTES: usize = 1275;
31const MAX_SILK_PACKET_BYTES: usize = 1 + 1 + 2 * 2 + 3 * MAX_FRAME_BYTES;
32
33/// SILK's round-trip algorithmic delay in 48 kHz samples: the analysis
34/// resampler (`SilkEncoder::delay_samples`) on the way in plus the decoder's
35/// own synthesis resampler on the way out. Click-measured, one impulse
36/// through `Encoder`/`Decoder` at each bandwidth, not derived from a
37/// formula — `Resampler`'s (decode-side) and `Resampler48`'s (encode-side)
38/// FIR lengths differ per bandwidth, so narrowband and wideband delays
39/// don't have to and don't match.
40const SILK_LOOK_AHEAD_48K_NB: usize = 58;
41const SILK_LOOK_AHEAD_48K_MB: usize = 54;
42const SILK_LOOK_AHEAD_48K_WB: usize = 50;
43/// How far the hybrid path delays the SILK layer's input so its output lines
44/// up with the CELT layer's at the decoder (which sums them as-is): CELT's
45/// overlap (120) minus SILK's WB round trip, click-measured through the
46/// decoder with one layer muted (`hybrid_layers_align` in conformance.rs).
47const HYBRID_SILK_DELAY_48K: usize = 120 - SILK_LOOK_AHEAD_48K_WB;
48/// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent.
49/// Was 8: at 16 kbps SILK takes 37 of the 40-byte budget, so 8 expanded
50/// 5133/6001 packets (+12.9% rate on the speech gate); libopus leaves CELT
51/// a few bytes there.
52const HYBRID_CELT_MIN_BYTES: usize = 3;
53/// libopus 1.6 bandwidth threshold tables (`opus_encoder.c:151`/`162`).
54/// Each pair is `(threshold, transition_width)` for one bandwidth boundary;
55/// voice and music, mono and stereo, are identical in 1.6.
56const MONO_VOICE_BW: [i32; 8] = [9000, 700, 9000, 700, 13500, 1000, 14000, 2000];
57const STEREO_VOICE_BW: [i32; 8] = [9000, 700, 9000, 700, 13500, 1000, 14000, 2000];
58const MONO_MUSIC_BW: [i32; 8] = [9000, 700, 9000, 700, 11000, 1000, 12000, 2000];
59const STEREO_MUSIC_BW: [i32; 8] = [9000, 700, 9000, 700, 11000, 1000, 12000, 2000];
60/// libopus `mode_thresholds` blended by `voice_est` (`opus_encoder.c:183`).
61/// With `stereo_width=0` (no analysis) the voice term is `[0][0]=64000` and
62/// the music base is `10000`; the gap (54000) is the ve² interpolation span.
63const MODE_THRESHOLD_VOICE: i32 = 64000;
64const MODE_THRESHOLD_MUSIC: i32 = 10000;
65/// Opus default encoder complexity (the `(90+complexity)/100` equiv-rate
66/// multiplier; loss=0 and complexity≥5 add no per-mode adjustment).
67const DEFAULT_COMPLEXITY: i32 = 9;
68
69/// What the caller is encoding.
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub enum Application {
72 /// Speech: one step narrower at a given rate, where the top octave costs
73 /// most and carries least.
74 Voip,
75 /// Music and general audio, the default.
76 Audio,
77 /// Lowest delay.
78 LowDelay,
79}
80
81/// One elementary Opus encoder: mono or stereo.
82#[derive(Clone, Debug)]
83pub struct Encoder {
84 celt: CeltEncoder,
85 range: RangeEncoder,
86 sample_rate: u32,
87 /// 48000 / `sample_rate`: the zero-stuffing factor into CELT.
88 upsample: usize,
89 channels: usize,
90 bitrate: u32,
91 vbr: bool,
92 application: Application,
93 bandwidth: Option<Bandwidth>,
94 final_range: u32,
95 /// [`None`] picks SILK, CELT or (once D4 lands) Hybrid from the
96 /// application and bitrate; `Some` forces one.
97 mode: Option<Mode>,
98 /// Lazily created on first use so the mode can flip between packets
99 /// without paying for the unused layer's state.
100 silk_nb: Option<SilkEncoder>,
101 silk_mb: Option<SilkEncoder>,
102 silk_wb: Option<SilkEncoder>,
103 silk_stereo_nb: Option<SilkStereoEncoder>,
104 silk_stereo_mb: Option<SilkStereoEncoder>,
105 silk_stereo_wb: Option<SilkStereoEncoder>,
106 /// Scratch space for the SILK packet payload, sized once so the steady-state
107 /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate.
108 silk_buf: [u8; MAX_SILK_PACKET_BYTES],
109 /// Hybrid: the last [`HYBRID_SILK_DELAY_48K`] samples of SILK-layer input.
110 silk_delay: Vec<f32>,
111 /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so
112 /// the steady-state loop doesn't allocate a `Vec` per frame.
113 silk_stuff: Vec<f32>,
114}
115
116/// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8,
117/// Medium → 12, Wide/SuperWide/Full → 16. SILK only runs at 8/12/16 kHz;
118/// for SuperWide/Full the top bands are CELT (Hybrid), so SILK itself is 16.
119fn silk_fs_khz(bw: Bandwidth) -> usize {
120 match bw {
121 Bandwidth::Narrow => 8,
122 Bandwidth::Medium => 12,
123 _ => 16,
124 }
125}
126
127impl Encoder {
128 /// An encoder for `channels` channels (1 or 2) at `sample_rate`, which
129 /// must be one of 8000, 12000, 16000, 24000 or 48000 Hz — the rates
130 /// RFC 6716 Section 2 admits. CELT itself runs at 48 kHz whatever the
131 /// input rate is (RFC 7845 Section 5.1).
132 pub fn new(sample_rate: u32, channels: usize, application: Application) -> Result<Encoder> {
133 let upsample = match sample_rate {
134 48000 => 1,
135 24000 => 2,
136 16000 => 3,
137 12000 => 4,
138 8000 => 6,
139 _ => {
140 return Err(Error::unsupported(
141 format!("opus encode at {sample_rate} Hz"),
142 "Opus encodes from 8, 12, 16, 24 or 48 kHz; resample first",
143 ));
144 }
145 };
146 if !(1..=2).contains(&channels) {
147 return Err(Error::unsupported(
148 format!("{channels}-channel Opus stream"),
149 "one stream carries at most two channels; use MultistreamEncoder",
150 ));
151 }
152 Ok(Encoder {
153 celt: CeltEncoder::new(channels, upsample),
154 range: RangeEncoder::new(),
155 sample_rate,
156 upsample,
157 channels,
158 bitrate: 64_000 * channels as u32,
159 vbr: false,
160 application,
161 bandwidth: None,
162 final_range: 0,
163 mode: None,
164 silk_nb: None,
165 silk_mb: None,
166 silk_wb: None,
167 silk_stereo_nb: None,
168 silk_stereo_mb: None,
169 silk_stereo_wb: None,
170 silk_buf: [0u8; MAX_SILK_PACKET_BYTES],
171 silk_delay: Vec::new(),
172 silk_stuff: Vec::new(),
173 })
174 }
175
176 /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and
177 /// `hybrid_choice` make from the application and bitrate; pass `None` to
178 /// restore the automatic pick. Requests this encoder cannot honour
179 /// (10 ms Hybrid) fall back to CELT.
180 pub fn set_mode(&mut self, mode: Option<Mode>) {
181 self.mode = mode;
182 }
183
184 /// Channels per frame of input.
185 pub fn channels(&self) -> usize {
186 self.channels
187 }
188
189 /// The rate the caller feeds.
190 pub fn sample_rate(&self) -> u32 {
191 self.sample_rate
192 }
193
194 /// Encoder delay in *input* samples for a `frame_size`-sample (per
195 /// channel, native rate) frame: the decoded stream lags the input by
196 /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate`
197 /// cancels it exactly. CELT: one MDCT overlap, 120 samples at 48 kHz.
198 /// SILK (10, 20, 40 or 60 ms frames, when the application/bitrate or an
199 /// explicit [`Encoder::set_mode`] select it — the same
200 /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches
201 /// on, so this always matches which layer actually codes the frame):
202 /// [`SILK_LOOK_AHEAD_48K_NB`], [`SILK_LOOK_AHEAD_48K_MB`] or
203 /// [`SILK_LOOK_AHEAD_48K_WB`]. Hybrid: CELT's 120, the SILK layer being
204 /// delayed to meet it ([`HYBRID_SILK_DELAY_48K`]). Any other frame size
205 /// falls back to CELT here exactly as `encode_toc_and_payload` does.
206 pub fn look_ahead(&self, frame_size: usize) -> usize {
207 let frame_48k = frame_size * self.upsample;
208 if let Some(fs_khz) = self.silk_choice(frame_48k) {
209 let delay = match fs_khz {
210 8 => SILK_LOOK_AHEAD_48K_NB,
211 12 => SILK_LOOK_AHEAD_48K_MB,
212 _ => SILK_LOOK_AHEAD_48K_WB,
213 };
214 return delay / self.upsample;
215 }
216 120 / self.upsample
217 }
218
219 /// Forces the coded bandwidth; [`None`] (the default) picks it from the
220 /// bitrate, the application and the input's Nyquist.
221 pub fn set_bandwidth(&mut self, bandwidth: Option<Bandwidth>) {
222 self.bandwidth = bandwidth;
223 }
224
225 /// Target bitrate in bits per second for the whole packet stream,
226 /// including the packet headers. Clamped to 500..=510000.
227 pub fn set_bitrate(&mut self, bps: u32) {
228 self.bitrate = bps.clamp(500, 510_000);
229 }
230
231 /// Current target bitrate.
232 pub fn bitrate(&self) -> u32 {
233 self.bitrate
234 }
235
236 /// Switches between CBR (default, every packet the target size) and
237 /// constrained VBR (packets vary, a reservoir holds the average to the
238 /// target).
239 pub fn set_vbr_constrained(&mut self, vbr: bool) {
240 self.vbr = vbr;
241 }
242
243 /// The range coder state after the last packet — the same value RFC 6716
244 /// test vectors carry, and what a conformant decoder's `final_range`
245 /// must equal after decoding that packet.
246 pub fn final_range(&self) -> u32 {
247 self.final_range
248 }
249
250 /// Per-frame CELT diagnostics from the most recent [`encode_float`] call.
251 /// Intended for the reelm@64k dropout investigation; the fields are only
252 /// meaningful when the last frame was coded as pure CELT (the path every
253 /// fullband Audio frame at 64 kbps stereo takes).
254 ///
255 /// [`encode_float`]: Encoder::encode_float
256 pub fn last_celt_diag(&self) -> &crate::celt_enc::CeltFrameDiag {
257 self.celt.last_diag()
258 }
259
260 /// Per-frame SILK diagnostics from the last SILK-encoded frame (mono).
261 /// Returns `None` if no mono SILK encoder has been initialised.
262 pub fn last_silk_diag(&self) -> Option<&crate::silk_enc_write::SilkFrameDiag> {
263 self.silk_mb
264 .as_ref()
265 .or(self.silk_wb.as_ref())
266 .or(self.silk_nb.as_ref())
267 .map(|s| s.last_diag())
268 }
269
270 /// Drops all inter-frame state; the next packet starts like the first.
271 pub fn reset(&mut self) {
272 self.celt.reset();
273 self.silk_nb = None;
274 self.silk_mb = None;
275 self.silk_wb = None;
276 self.silk_stereo_nb = None;
277 self.silk_stereo_mb = None;
278 self.silk_stereo_wb = None;
279 self.silk_delay.clear();
280 self.final_range = 0;
281 }
282
283 /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`])
284 /// calls for SILK, and if so, which SILK internal sample rate in kHz.
285 /// `None` means CELT or Hybrid (`hybrid_choice` tells those apart).
286 ///
287 /// Ports libopus's mode decision: SILK when `equiv_rate` is below the
288 /// voice/music-blended mode threshold (`opus_encoder.c` ~1900), with the
289 /// bandwidth from the threshold walk. SILK only codes up to Wide; a
290 /// SuperWide/Full result is Hybrid (10/20 ms) or, for 40/60 ms frames
291 /// that Hybrid cannot carry, SILK capped at Wide.
292 fn wants_silk(&self, frame_48k: usize) -> Option<usize> {
293 match self.mode {
294 Some(Mode::Celt) | Some(Mode::Hybrid) => None,
295 Some(Mode::Silk) => {
296 let bw = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth());
297 Some(silk_fs_khz(bw))
298 }
299 None => {
300 let equiv = self.equiv_rate(frame_48k);
301 let ve = self.voice_est();
302 if !self.auto_silk(equiv, ve) {
303 return None;
304 }
305 let bw = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve));
306 // 40/60 ms frames are SILK-only (Hybrid supports 10/20 ms):
307 // cap at Wide so a high equiv rate does not fall through to
308 // an impossible CELT 40/60 ms packet.
309 let bw = if matches!(frame_48k, 1920 | 2880) {
310 bw.min(Bandwidth::Wide)
311 } else {
312 bw
313 };
314 if bw > Bandwidth::Wide {
315 None // Hybrid territory — see hybrid_choice
316 } else {
317 Some(silk_fs_khz(bw))
318 }
319 }
320 }
321 }
322
323 /// `wants_silk` narrowed to what this encoder can actually code as SILK:
324 /// mono 10/20/40/60 ms, stereo 10/20 ms directly, or stereo 40/60 ms as
325 /// code-3 packets of 20 ms SILK frames.
326 fn silk_choice(&self, frame_48k: usize) -> Option<usize> {
327 let fs_khz = self.wants_silk(frame_48k)?;
328 if !matches!(frame_48k, 480 | 960 | 1920 | 2880) {
329 return None;
330 }
331 Some(fs_khz)
332 }
333
334 /// Whether this frame goes out as a hybrid packet, and at which of the two
335 /// hybrid bandwidths. Automatic: Hybrid is SILK mode (equiv below the mode
336 /// threshold) whose bandwidth walk lands on SuperWide/Full — SILK alone
337 /// cannot code above Wide, so CELT carries the top bands. 10 or 20 ms
338 /// only (Hybrid has no 40/60 ms config). Forced Hybrid codes at least SWB.
339 fn hybrid_choice(&self, frame_48k: usize) -> Option<Bandwidth> {
340 if matches!(self.mode, Some(Mode::Silk) | Some(Mode::Celt)) {
341 return None;
342 }
343 if !matches!(frame_48k, 480 | 960) {
344 return None;
345 }
346 let equiv = self.equiv_rate(frame_48k);
347 let ve = self.voice_est();
348 if self.mode.is_none() && !self.auto_silk(equiv, ve) {
349 return None;
350 }
351 let bw = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve));
352 match bw {
353 Bandwidth::SuperWide | Bandwidth::Full => Some(bw),
354 // A forced Hybrid with a narrow/medium/wide bandwidth still codes
355 // at least SWB — Hybrid has no narrower configuration.
356 _ if self.mode == Some(Mode::Hybrid) => Some(Bandwidth::SuperWide),
357 _ => None,
358 }
359 }
360
361 /// The SILK layer's share of a mono hybrid packet's bitrate, the
362 /// reference's 20 ms table interpolated: the rest is CELT's.
363 fn hybrid_silk_rate(total: u32, bandwidth: Bandwidth) -> u32 {
364 const TABLE: [(u32, u32, u32); 7] = [
365 (0, 0, 0),
366 (12000, 10000, 11000),
367 (16000, 13500, 14500),
368 (20000, 16000, 17000),
369 (24000, 18000, 19000),
370 (32000, 22000, 24000),
371 (64000, 38000, 42000),
372 ];
373 let pick = |row: &(u32, u32, u32)| {
374 if bandwidth == Bandwidth::Full {
375 row.2
376 } else {
377 row.1
378 }
379 };
380 let total = total.min(64000);
381 let i = TABLE
382 .iter()
383 .rposition(|r| r.0 <= total)
384 .unwrap()
385 .min(TABLE.len() - 2);
386 let (lo, hi) = (&TABLE[i], &TABLE[i + 1]);
387 pick(lo) + (pick(hi) - pick(lo)) * (total - lo.0) / (hi.0 - lo.0)
388 }
389
390 /// Zero-stuffs a mono, `frame_size`-sample native-rate frame up to
391 /// `frame_size * upsample` samples at 48 kHz, the rate [`SilkEncoder`]
392 /// takes — the same technique [`CeltEncoder::encode`] uses, scaled by
393 /// `upsample` so the passband gain survives the stuffing. Writes into
394 /// `out` (an `Encoder` scratch field, not a fresh `Vec` per call) rather
395 /// than returning one, so the caller doesn't allocate every frame; the
396 /// slots between the `upsample`-strided samples stay zero from one call
397 /// to the next once `out` first grows to size, so only the strided
398 /// samples themselves need rewriting.
399 fn zero_stuff_mono(pcm: &[f32], frame_size: usize, upsample: usize, out: &mut Vec<f32>) {
400 if upsample == 1 {
401 out.clear();
402 out.extend_from_slice(&pcm[..frame_size]);
403 return;
404 }
405 out.resize(frame_size * upsample, 0.0);
406 for i in 0..frame_size {
407 out[i * upsample] = pcm[i] * upsample as f32;
408 }
409 }
410
411 fn zero_stuff_stereo(pcm: &[f32], frame_size: usize, upsample: usize, out: &mut Vec<f32>) {
412 if upsample == 1 {
413 out.clear();
414 out.extend_from_slice(&pcm[..2 * frame_size]);
415 return;
416 }
417 out.resize(2 * frame_size * upsample, 0.0);
418 out.fill(0.0);
419 for i in 0..frame_size {
420 let dst = 2 * i * upsample;
421 out[dst] = pcm[2 * i] * upsample as f32;
422 out[dst + 1] = pcm[2 * i + 1] * upsample as f32;
423 }
424 }
425
426 fn write_frame_len(out: &mut [u8], pos: &mut usize, len: usize) -> Result<()> {
427 if len > MAX_FRAME_BYTES {
428 return Err(Error::corrupt(format!(
429 "opus encode: frame payload of {len} bytes exceeds {MAX_FRAME_BYTES}"
430 )));
431 }
432 if len < 252 {
433 out[*pos] = len as u8;
434 *pos += 1;
435 } else {
436 let b0 = 252 + ((len - 252) & 3);
437 out[*pos] = b0 as u8;
438 out[*pos + 1] = ((len - b0) / 4) as u8;
439 *pos += 2;
440 }
441 Ok(())
442 }
443
444 fn encode_stereo_silk_multiframe(
445 &mut self,
446 fs_khz: usize,
447 frame_48k: usize,
448 ) -> Result<(u8, &[u8])> {
449 let frame_count = frame_48k / 960;
450 debug_assert!(matches!(frame_count, 2 | 3));
451 let mut frames = [[0u8; MAX_FRAME_BYTES + 1]; 3];
452 let mut lens = [0usize; 3];
453 let toc = {
454 let enc = match fs_khz {
455 8 => self
456 .silk_stereo_nb
457 .get_or_insert_with(|| SilkStereoEncoder::new(false)),
458 12 => self
459 .silk_stereo_mb
460 .get_or_insert_with(SilkStereoEncoder::new_mediumband),
461 _ => self
462 .silk_stereo_wb
463 .get_or_insert_with(|| SilkStereoEncoder::new(true)),
464 };
465 enc.set_bitrate(self.bitrate);
466 for i in 0..frame_count {
467 let from = i * 2 * 960;
468 lens[i] = enc.encode_frame_ms(
469 &self.silk_stuff[from..from + 2 * 960],
470 &mut frames[i],
471 20,
472 )?;
473 debug_assert!(i == 0 || frames[i][0] == frames[0][0]);
474 }
475 self.final_range = enc.final_range();
476 frames[0][0] | 0x03
477 };
478 let mut pos = 0usize;
479 self.silk_buf[pos] = 0x80 | frame_count as u8;
480 pos += 1;
481 for &len in &lens[..frame_count - 1] {
482 Self::write_frame_len(&mut self.silk_buf, &mut pos, len - 1)?;
483 }
484 for i in 0..frame_count {
485 let len = lens[i] - 1;
486 if pos + len > self.silk_buf.len() {
487 return Err(Error::corrupt(format!(
488 "opus encode: SILK packet needs {} bytes, buffer holds {}",
489 pos + len,
490 self.silk_buf.len()
491 )));
492 }
493 self.silk_buf[pos..pos + len].copy_from_slice(&frames[i][1..lens[i]]);
494 pos += len;
495 }
496 Ok((toc, &self.silk_buf[..pos]))
497 }
498
499 /// Picks SILK or CELT for one frame and encodes it, returning the TOC
500 /// byte and the payload bytes (excluding TOC), borrowed from scratch
501 /// space owned by `self` — no allocation on the steady-state path.
502 /// `cap` bounds the CELT path only — SILK isn't budgeted against a byte
503 /// cap yet (D2b).
504 fn encode_toc_and_payload(
505 &mut self,
506 pcm: &[f32],
507 frame_size: usize,
508 cap: usize,
509 ) -> Result<(u8, &[u8])> {
510 let frame_48k = frame_size * self.upsample;
511 if let Some(fs_khz) = self.silk_choice(frame_48k) {
512 if self.channels == 2 {
513 Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);
514 if frame_48k > 960 {
515 return self.encode_stereo_silk_multiframe(fs_khz, frame_48k);
516 }
517 let enc = match fs_khz {
518 8 => self
519 .silk_stereo_nb
520 .get_or_insert_with(|| SilkStereoEncoder::new(false)),
521 12 => self
522 .silk_stereo_mb
523 .get_or_insert_with(SilkStereoEncoder::new_mediumband),
524 _ => self
525 .silk_stereo_wb
526 .get_or_insert_with(|| SilkStereoEncoder::new(true)),
527 };
528 enc.set_bitrate(self.bitrate);
529 let n =
530 enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf, frame_48k / 48)?;
531 self.final_range = enc.final_range();
532 return Ok((self.silk_buf[0], &self.silk_buf[1..n]));
533 }
534 Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);
535 let enc = match fs_khz {
536 8 => self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)),
537 12 => self.silk_mb.get_or_insert_with(SilkEncoder::new_mediumband),
538 _ => self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)),
539 };
540 // Keep SILK's own reservoir-based rate control tracking the
541 // Encoder's current target on every frame — cheap (an Option<u32>
542 // store) and catches set_bitrate calls made between frames.
543 enc.set_bitrate(self.bitrate);
544 let n = enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf, frame_48k / 48)?;
545 self.final_range = enc.final_range();
546 return Ok((self.silk_buf[0], &self.silk_buf[1..n]));
547 }
548 if let Some(bandwidth) = self.hybrid_choice(frame_48k) {
549 let n = self.encode_hybrid(pcm, frame_size, bandwidth, cap)?;
550 let config = 12
551 + if bandwidth == Bandwidth::Full { 2u8 } else { 0 }
552 + if frame_48k == 960 { 1 } else { 0 };
553 return Ok((
554 (config << 3) | (u8::from(self.channels == 2) << 2),
555 &self.range.data()[..n],
556 ));
557 }
558 let (toc, frame_48k, end) = self.toc(frame_size)?;
559 let n = self.encode_frame(pcm, frame_48k, end, cap)?;
560 Ok((toc, &self.range.data()[..n]))
561 }
562
563 /// The TOC byte, the frame size in 48 kHz samples and the CELT end band
564 /// for a frame of `frame_size` input samples per channel.
565 fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> {
566 let frame_48k = frame_size * self.upsample;
567 let fs_idx: u8 = match frame_48k {
568 120 => 0,
569 240 => 1,
570 480 => 2,
571 960 => 3,
572 _ => {
573 return Err(Error::unsupported(
574 format!(
575 "opus frame of {frame_size} samples at {} Hz",
576 self.sample_rate
577 ),
578 "CELT frames are 2.5, 5, 10 or 20 ms",
579 ));
580 }
581 };
582 let bandwidth = self
583 .bandwidth
584 .unwrap_or_else(|| self.auto_bandwidth_at(self.equiv_rate(frame_48k), self.voice_est()));
585 let bw_idx: u8 = match bandwidth {
586 Bandwidth::Narrow => 0,
587 // CELT has no mediumband configuration; the next one up covers it.
588 Bandwidth::Medium | Bandwidth::Wide => 1,
589 Bandwidth::SuperWide => 2,
590 Bandwidth::Full => 3,
591 };
592 let config = 16 + 4 * bw_idx + fs_idx;
593 Ok((
594 (config << 3) | (u8::from(self.channels == 2) << 2),
595 frame_48k,
596 bandwidth.celt_end_band(),
597 ))
598 }
599
600 /// Bandwidth from the bitrate — libopus's threshold walk, 20 ms default.
601 /// Kept for the forced-mode paths and unit tests; the dispatch functions
602 /// pass the actual frame's equiv rate to [`auto_bandwidth_at`].
603 fn auto_bandwidth(&self) -> Bandwidth {
604 self.auto_bandwidth_at(self.equiv_rate(960), self.voice_est())
605 }
606
607 /// The equivalent rate a frame is coded at, porting libopus
608 /// `compute_equiv_rate` (`opus_encoder.c:1021`): the bitrate, minus the
609 /// per-frame overhead for sub-20 ms frames, minus the CBR headroom, times
610 /// the complexity multiplier. Loss is 0 and complexity ≥ 5, so the
611 /// are both no-ops.
612 fn equiv_rate(&self, frame_48k: usize) -> i32 {
613 let frame_rate = 48000 / frame_48k as i32;
614 let mut equiv = self.bitrate as i32;
615 if frame_rate > 50 {
616 equiv -= (40 * self.channels as i32 + 20) * (frame_rate - 50);
617 }
618 if !self.vbr {
619 equiv -= equiv / 12;
620 }
621 equiv = equiv * (90 + DEFAULT_COMPLEXITY) / 100;
622 equiv
623 }
624
625 /// Voice activity estimate: VoIP → 115, Audio and LowDelay → 48
626 /// (`opus_encoder.c` `tonality_analysis` proxy — no analysis is modelled,
627 /// so the application alone decides).
628 fn voice_est(&self) -> i32 {
629 match self.application {
630 Application::Voip => 115,
631 _ => 48,
632 }
633 }
634
635 /// Whether the auto mode is SILK: `equiv` below the voice/music-blended
636 /// mode threshold (`opus_encoder.c` ~1900). LowDelay is always CELT.
637 /// VoIP gets the `+8000` hysteresis/voice bonus libopus applies.
638 fn auto_silk(&self, equiv: i32, ve: i32) -> bool {
639 if self.application == Application::LowDelay {
640 return false;
641 }
642 let threshold = MODE_THRESHOLD_MUSIC
643 + ((ve * ve * (MODE_THRESHOLD_VOICE - MODE_THRESHOLD_MUSIC)) >> 14);
644 let threshold = if self.application == Application::Voip {
645 threshold + 8000
646 } else {
647 threshold
648 };
649 equiv < threshold
650 }
651
652 /// Bandwidth from the equivalent rate, porting libopus's `decide_bandwidth`
653 /// walk (`opus_encoder.c` ~1660). The voice and music threshold tables are
654 /// blended by `ve²`; the walk starts at Full and steps down until the equiv
655 /// rate sustains the current bandwidth. The input's own Nyquist clamps the
656 /// result — coding above it would code the images the zero-stuffing put
657 /// there.
658 fn auto_bandwidth_at(&self, equiv: i32, ve: i32) -> Bandwidth {
659 let (voice, music) = if self.channels == 2 {
660 (&STEREO_VOICE_BW, &STEREO_MUSIC_BW)
661 } else {
662 (&MONO_VOICE_BW, &MONO_MUSIC_BW)
663 };
664 let ve2 = ve * ve;
665 // Pair i is the boundary between bandwidth i and i+1:
666 // 0: NB↔MB, 1: MB↔WB, 2: WB↔SWB, 3: SWB↔FB.
667 let thresh = |i: usize| music[2 * i] + ((ve2 * (voice[2 * i] - music[2 * i])) >> 14);
668 const BWS: [Bandwidth; 5] = [
669 Bandwidth::Narrow,
670 Bandwidth::Medium,
671 Bandwidth::Wide,
672 Bandwidth::SuperWide,
673 Bandwidth::Full,
674 ];
675 let mut idx = 4; // Full
676 while idx > 0 && equiv < thresh(idx - 1) {
677 idx -= 1;
678 }
679 let ceiling = match self.sample_rate {
680 48000 => Bandwidth::Full,
681 24000 => Bandwidth::SuperWide,
682 16000 => Bandwidth::Wide,
683 12000 => Bandwidth::Medium,
684 _ => Bandwidth::Narrow,
685 };
686 BWS[idx].min(ceiling)
687 }
688
689 /// Encodes one frame — `frame_size` samples per channel of interleaved
690 /// `f32` at the input rate, 2.5, 5, 10 or 20 ms of it — as a code-0 Opus
691 /// packet in `out`, returning the packet length.
692 pub fn encode_float(
693 &mut self,
694 pcm: &[f32],
695 frame_size: usize,
696 out: &mut [u8],
697 ) -> Result<usize> {
698 let (toc, payload) =
699 self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1))?;
700 let n = payload.len();
701 if out.len() < 1 + n {
702 return Err(Error::corrupt(format!(
703 "opus encode: packet needs {} bytes, buffer holds {}",
704 1 + n,
705 out.len()
706 )));
707 }
708 out[0] = toc;
709 out[1..1 + n].copy_from_slice(payload);
710 Ok(1 + n)
711 }
712
713 /// [`Encoder::encode_float`] from 16-bit samples.
714 pub fn encode(&mut self, pcm: &[i16], frame_size: usize, out: &mut [u8]) -> Result<usize> {
715 let float: Vec<f32> = pcm.iter().map(|&v| v as f32 * (1.0 / 32768.0)).collect();
716 self.encode_float(&float, frame_size, out)
717 }
718
719 /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716
720 /// Appendix B: TOC, an explicit frame length, then the frame. This is
721 /// what every stream but the last uses inside a multistream packet.
722 pub fn encode_self_delimited(
723 &mut self,
724 pcm: &[f32],
725 frame_size: usize,
726 out: &mut [u8],
727 ) -> Result<usize> {
728 let (toc, payload) =
729 self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3))?;
730 let n = payload.len();
731 let len_bytes = if n < 252 { 1 } else { 2 };
732 if out.len() < 1 + len_bytes + n {
733 return Err(Error::corrupt(format!(
734 "opus encode: self-delimited packet needs {} bytes, buffer holds {}",
735 1 + len_bytes + n,
736 out.len()
737 )));
738 }
739 out[0] = toc;
740 if n < 252 {
741 out[1] = n as u8;
742 } else {
743 let b0 = 252 + ((n - 252) & 3);
744 out[1] = b0 as u8;
745 out[2] = ((n - b0) / 4) as u8;
746 }
747 out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(payload);
748 Ok(1 + len_bytes + n)
749 }
750
751 /// One hybrid frame (10 or 20 ms, mono or stereo, `bandwidth` SWB or FB)
752 /// into the internal range coder, returning its byte length: the SILK
753 /// layer's symbols (WB, 16 kHz internal, fed the input delayed by
754 /// [`HYBRID_SILK_DELAY_48K`]), the no-redundancy flag under the decoder's
755 /// exact presence rule, then the CELT layer from band 17 in the same
756 /// coder. CBR: the packet is the bitrate's size unless SILK alone needs
757 /// more, in which case CELT keeps [`HYBRID_CELT_MIN_BYTES`] on top.
758 fn encode_hybrid(
759 &mut self,
760 pcm: &[f32],
761 frame_size: usize,
762 bandwidth: Bandwidth,
763 cap: usize,
764 ) -> Result<usize> {
765 let cap = cap.min(MAX_FRAME_BYTES);
766 let frame_48k = frame_size * self.upsample;
767 let frame_ms = frame_48k / 48;
768 let budget = ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize;
769 let budget = budget.saturating_sub(1).clamp(2, cap);
770 if cap < HYBRID_CELT_MIN_BYTES + 2 {
771 return Err(Error::corrupt(
772 "opus encode: output buffer smaller than the minimum hybrid packet",
773 ));
774 }
775 if self.channels == 2 {
776 Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);
777 } else {
778 Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);
779 }
780 let d = HYBRID_SILK_DELAY_48K * self.channels;
781 if self.silk_delay.len() != d {
782 self.silk_delay.clear();
783 self.silk_delay.resize(d, 0.0);
784 }
785 let silk_len = frame_48k * self.channels;
786 let mut delayed = Vec::with_capacity(silk_len);
787 delayed.extend_from_slice(&self.silk_delay);
788 delayed.extend_from_slice(&self.silk_stuff[..silk_len - d]);
789 self.silk_delay
790 .copy_from_slice(&self.silk_stuff[silk_len - d..silk_len]);
791
792 self.range.reset(cap);
793 let silk_rate = Self::hybrid_silk_rate(self.bitrate, bandwidth);
794 if self.channels == 2 {
795 let silk = self
796 .silk_stereo_wb
797 .get_or_insert_with(|| SilkStereoEncoder::new(true));
798 silk.set_bitrate(silk_rate);
799 silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;
800 } else {
801 let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true));
802 silk.set_bitrate(silk_rate);
803 silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;
804 }
805 let silk_bytes = (self.range.tell() as usize).div_ceil(8);
806 let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap);
807 self.range.shrink(budget);
808 // Redundancy flag: present under exactly the decoder's condition.
809 if self.range.tell() as usize + 17 + 20 <= 8 * budget {
810 self.range.enc_bit_logp(false, 12);
811 }
812 let n = self.celt.encode(
813 &mut self.range,
814 pcm,
815 frame_48k,
816 17,
817 bandwidth.celt_end_band(),
818 0,
819 )?;
820 self.final_range = self.range.range();
821 let payload = &self.range.data()[..n];
822 if self.channels == 2 {
823 self.silk_stereo_wb
824 .as_mut()
825 .unwrap()
826 .replay_hybrid(payload, frame_ms)?;
827 } else {
828 self.silk_wb
829 .as_mut()
830 .unwrap()
831 .replay_hybrid(payload, frame_ms)?;
832 }
833 Ok(n)
834 }
835
836 /// Encodes the CELT frame into the internal range coder and returns its
837 /// byte length. `frame_size` is in 48 kHz samples, `end` is the last coded
838 /// band, and `cap` bounds the frame (the caller's buffer minus headers).
839 fn encode_frame(
840 &mut self,
841 pcm: &[f32],
842 frame_size: usize,
843 end: usize,
844 cap: usize,
845 ) -> Result<usize> {
846 let cap = cap.min(MAX_FRAME_BYTES);
847 if cap < 2 {
848 return Err(Error::corrupt(
849 "opus encode: output buffer smaller than the minimum packet",
850 ));
851 }
852 // One byte per packet goes to the TOC; the CELT layer sees the rest.
853 let toc_bps = 8 * 48000 / frame_size as u32;
854 let (budget, vbr_rate) = if self.vbr {
855 (cap, self.bitrate.saturating_sub(toc_bps).max(500))
856 } else {
857 let b = ((self.bitrate as u64 * frame_size as u64 + 4 * 48000) / (8 * 48000)) as usize;
858 (b.saturating_sub(1).clamp(2, cap), 0)
859 };
860 self.range.reset(budget);
861 let n = self
862 .celt
863 .encode(&mut self.range, pcm, frame_size, 0, end, vbr_rate)?;
864 self.final_range = self.range.range();
865 Ok(n)
866 }
867}
868
869#[cfg(test)]
870mod tests {
871 use super::*;
872
873 /// The private half of the bandwidth decision: the thresholds themselves,
874 /// which the TOC config only reports.
875 #[test]
876 fn bandwidth_follows_the_bitrate_the_application_and_the_input_rate() {
877 let mut e = Encoder::new(48000, 1, Application::Audio).unwrap();
878 e.set_bitrate(64000);
879 assert_eq!(e.auto_bandwidth(), Bandwidth::Full);
880 // libopus MONO_MUSIC_BW blended at voice_est=48 (analysis off):
881 // SWB<->FB boundary 12281, equiv(16k) = 14520 -> Full.
882 e.set_bitrate(16000);
883 assert_eq!(e.auto_bandwidth(), Bandwidth::Full);
884 e.set_bitrate(10000);
885 assert_eq!(e.auto_bandwidth(), Bandwidth::Wide);
886 // equiv(8k) = 7260 < 9000 (NB<->MB boundary) -> Narrow.
887 e.set_bitrate(8000);
888 assert_eq!(e.auto_bandwidth(), Bandwidth::Narrow);
889 // VoIP (voice_est=127): SWB<->FB boundary 13616, so 16k speech is
890 // Full -> hybrid, matching libopus 1.6 on real speech
891 // (lanes/opus-silk-r2.sweep.txt: 16k-NB row, ref_mode=Hybrid-FB).
892 let mut v = Encoder::new(48000, 1, Application::Voip).unwrap();
893 v.set_bitrate(16000);
894 assert_eq!(v.auto_bandwidth(), Bandwidth::Full);
895 // The input's own Nyquist bounds it whatever the rate says.
896 let mut e = Encoder::new(24000, 2, Application::Audio).unwrap();
897 e.set_bitrate(256_000);
898 assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide);
899 assert_eq!(e.look_ahead(960), 60);
900 }
901
902 /// `look_ahead` must use the same 10-or-20 ms-frame predicate dispatch
903 /// does (`silk_choice`/`hybrid_choice`), not just `wants_silk`: 2.5/5 ms
904 /// frames still code as CELT, while 10/20 ms speech follows SILK and
905 /// hybrid follows CELT's overlap.
906 #[test]
907 fn look_ahead_matches_the_frame_size_dispatch_actually_uses() {
908 let mut e = Encoder::new(48000, 1, Application::Voip).unwrap();
909 e.set_bitrate(8000);
910 assert_eq!(e.look_ahead(480), 58, "10ms NB SILK");
911 assert_eq!(e.look_ahead(240), 120, "5ms frame falls back to CELT");
912 assert_eq!(e.look_ahead(960), 58, "20ms NB SILK");
913
914 // 16k VoIP is hybrid-FB since the libopus threshold port (CELT overlap).
915 e.set_bitrate(16000);
916 assert_eq!(e.look_ahead(960), 120, "20ms hybrid FB");
917
918 e.set_bitrate(32000);
919 assert_eq!(e.look_ahead(960), 120, "20ms hybrid, CELT's overlap");
920
921 let mut e = Encoder::new(48000, 2, Application::Voip).unwrap();
922 e.set_bitrate(8000);
923 assert_eq!(e.look_ahead(960), 58, "stereo 20ms NB SILK");
924 e.set_bitrate(64_000);
925 assert_eq!(e.look_ahead(960), 120, "stereo 20ms hybrid");
926 }
927
928 #[test]
929 fn voip_auto_mode_is_monotonic_per_channel() {
930 for channels in [1usize, 2] {
931 let mut e = Encoder::new(48000, channels, Application::Voip).unwrap();
932 let mut last = 0u8;
933 for per_channel in 500..=45_000u32 {
934 e.set_bitrate(per_channel * channels as u32);
935 let class = if e.silk_choice(960).is_some() {
936 0
937 } else if e.hybrid_choice(960).is_some() {
938 1
939 } else {
940 2
941 };
942 assert!(
943 class >= last,
944 "{channels}ch {per_channel} bps/channel regressed from {last} to {class}"
945 );
946 last = class;
947 }
948 }
949 }
950}