forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB6828b15Tahinli3 months ago393 commits

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