forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBbb2f32fTahinli3 months ago423 commits

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