forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8a26b91Tahinli3 months ago348 commits

encoder.rs830 lines, 32.8 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 /// Drops all inter-frame state; the next packet starts like the first.
222 pub fn reset(&mut self) {
223 self.celt.reset();
224 self.silk_nb = None;
225 self.silk_mb = None;
226 self.silk_wb = None;
227 self.silk_stereo_nb = None;
228 self.silk_stereo_mb = None;
229 self.silk_stereo_wb = None;
230 self.silk_delay.clear();
231 self.final_range = 0;
232 }
233
234 /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`])
235 /// call for SILK, and if so, which SILK internal sample rate in kHz.
236 /// `None` means CELT or Hybrid (`hybrid_choice` tells those apart).
237 fn wants_silk(&self) -> Option<usize> {
238 let forced = || match self.bandwidth.unwrap_or_else(|| self.auto_bandwidth()) {
239 Bandwidth::Narrow => 8,
240 Bandwidth::Medium => 12,
241 _ => 16,
242 };
243 match self.mode {
244 Some(Mode::Celt) | Some(Mode::Hybrid) => None,
245 Some(Mode::Silk) => Some(forced()),
246 None => {
247 if self.application == Application::Voip {
248 let per_channel = self.bitrate / self.channels as u32;
249 if per_channel < 20_000 {
250 return Some(match self.bandwidth {
251 Some(Bandwidth::Narrow) => 8,
252 Some(Bandwidth::Medium) => 12,
253 Some(_) => 16,
254 None if per_channel <= 12_000 => 8,
255 None if per_channel <= 16_000 => 12,
256 None => 16,
257 });
258 }
259 }
260 None
261 }
262 }
263 }
264
265 /// `wants_silk` narrowed to what this encoder can actually code as SILK:
266 /// mono 10/20/40/60 ms, stereo 10/20 ms directly, or stereo 40/60 ms as
267 /// code-3 packets of 20 ms SILK frames.
268 fn silk_choice(&self, frame_48k: usize) -> Option<usize> {
269 let fs_khz = self.wants_silk()?;
270 if !matches!(frame_48k, 480 | 960 | 1920 | 2880) {
271 return None;
272 }
273 Some(fs_khz)
274 }
275
276 /// Whether this frame goes out as a hybrid packet, and at which of the two
277 /// hybrid bandwidths. Automatic: VoIP from 20 kbps per coded channel
278 /// (where SILK alone stops) to 40 kbps per coded channel (where CELT alone
279 /// is the better speech coder too), at the bitrate's own bandwidth
280 /// (SWB/FB; narrower requests are CELT's). Mono and stereo, 10 or 20 ms.
281 fn hybrid_choice(&self, frame_48k: usize) -> Option<Bandwidth> {
282 let per_channel = self.bitrate / self.channels as u32;
283 let wanted = match self.mode {
284 Some(Mode::Hybrid) => true,
285 Some(_) => false,
286 None => {
287 self.application == Application::Voip && (20_000..40_000).contains(&per_channel)
288 }
289 };
290 if !wanted || !matches!(frame_48k, 480 | 960) {
291 return None;
292 }
293 let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth());
294 match bandwidth {
295 Bandwidth::SuperWide | Bandwidth::Full => Some(bandwidth),
296 // A forced Hybrid codes at least SWB; an automatic one that the
297 // bitrate would cap narrower is CELT's.
298 _ if self.mode == Some(Mode::Hybrid) => Some(Bandwidth::SuperWide),
299 _ => None,
300 }
301 }
302
303 /// The SILK layer's share of a mono hybrid packet's bitrate, the
304 /// reference's 20 ms table interpolated: the rest is CELT's.
305 fn hybrid_silk_rate(total: u32, bandwidth: Bandwidth) -> u32 {
306 const TABLE: [(u32, u32, u32); 7] = [
307 (0, 0, 0),
308 (12000, 10000, 11000),
309 (16000, 13500, 14500),
310 (20000, 16000, 17000),
311 (24000, 18000, 19000),
312 (32000, 22000, 24000),
313 (64000, 38000, 42000),
314 ];
315 let pick = |row: &(u32, u32, u32)| {
316 if bandwidth == Bandwidth::Full {
317 row.2
318 } else {
319 row.1
320 }
321 };
322 let total = total.min(64000);
323 let i = TABLE
324 .iter()
325 .rposition(|r| r.0 <= total)
326 .unwrap()
327 .min(TABLE.len() - 2);
328 let (lo, hi) = (&TABLE[i], &TABLE[i + 1]);
329 pick(lo) + (pick(hi) - pick(lo)) * (total - lo.0) / (hi.0 - lo.0)
330 }
331
332 /// Zero-stuffs a mono, `frame_size`-sample native-rate frame up to
333 /// `frame_size * upsample` samples at 48 kHz, the rate [`SilkEncoder`]
334 /// takes — the same technique [`CeltEncoder::encode`] uses, scaled by
335 /// `upsample` so the passband gain survives the stuffing. Writes into
336 /// `out` (an `Encoder` scratch field, not a fresh `Vec` per call) rather
337 /// than returning one, so the caller doesn't allocate every frame; the
338 /// slots between the `upsample`-strided samples stay zero from one call
339 /// to the next once `out` first grows to size, so only the strided
340 /// samples themselves need rewriting.
341 fn zero_stuff_mono(pcm: &[f32], frame_size: usize, upsample: usize, out: &mut Vec<f32>) {
342 if upsample == 1 {
343 out.clear();
344 out.extend_from_slice(&pcm[..frame_size]);
345 return;
346 }
347 out.resize(frame_size * upsample, 0.0);
348 for i in 0..frame_size {
349 out[i * upsample] = pcm[i] * upsample as f32;
350 }
351 }
352
353 fn zero_stuff_stereo(pcm: &[f32], frame_size: usize, upsample: usize, out: &mut Vec<f32>) {
354 if upsample == 1 {
355 out.clear();
356 out.extend_from_slice(&pcm[..2 * frame_size]);
357 return;
358 }
359 out.resize(2 * frame_size * upsample, 0.0);
360 out.fill(0.0);
361 for i in 0..frame_size {
362 let dst = 2 * i * upsample;
363 out[dst] = pcm[2 * i] * upsample as f32;
364 out[dst + 1] = pcm[2 * i + 1] * upsample as f32;
365 }
366 }
367
368 fn write_frame_len(out: &mut [u8], pos: &mut usize, len: usize) -> Result<()> {
369 if len > MAX_FRAME_BYTES {
370 return Err(Error::corrupt(format!(
371 "opus encode: frame payload of {len} bytes exceeds {MAX_FRAME_BYTES}"
372 )));
373 }
374 if len < 252 {
375 out[*pos] = len as u8;
376 *pos += 1;
377 } else {
378 let b0 = 252 + ((len - 252) & 3);
379 out[*pos] = b0 as u8;
380 out[*pos + 1] = ((len - b0) / 4) as u8;
381 *pos += 2;
382 }
383 Ok(())
384 }
385
386 fn encode_stereo_silk_multiframe(
387 &mut self,
388 fs_khz: usize,
389 frame_48k: usize,
390 ) -> Result<(u8, &[u8])> {
391 let frame_count = frame_48k / 960;
392 debug_assert!(matches!(frame_count, 2 | 3));
393 let mut frames = [[0u8; MAX_FRAME_BYTES + 1]; 3];
394 let mut lens = [0usize; 3];
395 let toc = {
396 let enc = match fs_khz {
397 8 => self
398 .silk_stereo_nb
399 .get_or_insert_with(|| SilkStereoEncoder::new(false)),
400 12 => self
401 .silk_stereo_mb
402 .get_or_insert_with(SilkStereoEncoder::new_mediumband),
403 _ => self
404 .silk_stereo_wb
405 .get_or_insert_with(|| SilkStereoEncoder::new(true)),
406 };
407 enc.set_bitrate(self.bitrate);
408 for i in 0..frame_count {
409 let from = i * 2 * 960;
410 lens[i] = enc.encode_frame_ms(
411 &self.silk_stuff[from..from + 2 * 960],
412 &mut frames[i],
413 20,
414 )?;
415 debug_assert!(i == 0 || frames[i][0] == frames[0][0]);
416 }
417 self.final_range = enc.final_range();
418 frames[0][0] | 0x03
419 };
420 let mut pos = 0usize;
421 self.silk_buf[pos] = 0x80 | frame_count as u8;
422 pos += 1;
423 for &len in &lens[..frame_count - 1] {
424 Self::write_frame_len(&mut self.silk_buf, &mut pos, len - 1)?;
425 }
426 for i in 0..frame_count {
427 let len = lens[i] - 1;
428 if pos + len > self.silk_buf.len() {
429 return Err(Error::corrupt(format!(
430 "opus encode: SILK packet needs {} bytes, buffer holds {}",
431 pos + len,
432 self.silk_buf.len()
433 )));
434 }
435 self.silk_buf[pos..pos + len].copy_from_slice(&frames[i][1..lens[i]]);
436 pos += len;
437 }
438 Ok((toc, &self.silk_buf[..pos]))
439 }
440
441 /// Picks SILK or CELT for one frame and encodes it, returning the TOC
442 /// byte and the payload bytes (excluding TOC), borrowed from scratch
443 /// space owned by `self` — no allocation on the steady-state path.
444 /// `cap` bounds the CELT path only — SILK isn't budgeted against a byte
445 /// cap yet (D2b).
446 fn encode_toc_and_payload(
447 &mut self,
448 pcm: &[f32],
449 frame_size: usize,
450 cap: usize,
451 ) -> Result<(u8, &[u8])> {
452 let frame_48k = frame_size * self.upsample;
453 if let Some(fs_khz) = self.silk_choice(frame_48k) {
454 if self.channels == 2 {
455 Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);
456 if frame_48k > 960 {
457 return self.encode_stereo_silk_multiframe(fs_khz, frame_48k);
458 }
459 let enc = match fs_khz {
460 8 => self
461 .silk_stereo_nb
462 .get_or_insert_with(|| SilkStereoEncoder::new(false)),
463 12 => self
464 .silk_stereo_mb
465 .get_or_insert_with(SilkStereoEncoder::new_mediumband),
466 _ => self
467 .silk_stereo_wb
468 .get_or_insert_with(|| SilkStereoEncoder::new(true)),
469 };
470 enc.set_bitrate(self.bitrate);
471 let n =
472 enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf, frame_48k / 48)?;
473 self.final_range = enc.final_range();
474 return Ok((self.silk_buf[0], &self.silk_buf[1..n]));
475 }
476 Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);
477 let enc = match fs_khz {
478 8 => self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false)),
479 12 => self.silk_mb.get_or_insert_with(SilkEncoder::new_mediumband),
480 _ => self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true)),
481 };
482 // Keep SILK's own reservoir-based rate control tracking the
483 // Encoder's current target on every frame — cheap (an Option<u32>
484 // store) and catches set_bitrate calls made between frames.
485 enc.set_bitrate(self.bitrate);
486 let n = enc.encode_frame_ms(&self.silk_stuff, &mut self.silk_buf, frame_48k / 48)?;
487 self.final_range = enc.final_range();
488 return Ok((self.silk_buf[0], &self.silk_buf[1..n]));
489 }
490 if let Some(bandwidth) = self.hybrid_choice(frame_48k) {
491 let n = self.encode_hybrid(pcm, frame_size, bandwidth, cap)?;
492 let config = 12
493 + if bandwidth == Bandwidth::Full { 2u8 } else { 0 }
494 + if frame_48k == 960 { 1 } else { 0 };
495 return Ok((
496 (config << 3) | (u8::from(self.channels == 2) << 2),
497 &self.range.data()[..n],
498 ));
499 }
500 let (toc, frame_48k, end) = self.toc(frame_size)?;
501 let n = self.encode_frame(pcm, frame_48k, end, cap)?;
502 Ok((toc, &self.range.data()[..n]))
503 }
504
505 /// The TOC byte, the frame size in 48 kHz samples and the CELT end band
506 /// for a frame of `frame_size` input samples per channel.
507 fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> {
508 let frame_48k = frame_size * self.upsample;
509 let fs_idx: u8 = match frame_48k {
510 120 => 0,
511 240 => 1,
512 480 => 2,
513 960 => 3,
514 _ => {
515 return Err(Error::unsupported(
516 format!(
517 "opus frame of {frame_size} samples at {} Hz",
518 self.sample_rate
519 ),
520 "CELT frames are 2.5, 5, 10 or 20 ms",
521 ));
522 }
523 };
524 let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth());
525 let bw_idx: u8 = match bandwidth {
526 Bandwidth::Narrow => 0,
527 // CELT has no mediumband configuration; the next one up covers it.
528 Bandwidth::Medium | Bandwidth::Wide => 1,
529 Bandwidth::SuperWide => 2,
530 Bandwidth::Full => 3,
531 };
532 let config = 16 + 4 * bw_idx + fs_idx;
533 Ok((
534 (config << 3) | (u8::from(self.channels == 2) << 2),
535 frame_48k,
536 bandwidth.celt_end_band(),
537 ))
538 }
539
540 /// Bandwidth from the bitrate: coding 20 kHz at 24 kbps spends bits on air.
541 ///
542 /// The thresholds are on the mono-equivalent rate — a coupled stereo stream
543 /// needs about 1.6x a mono one for the same per-channel quality — and VoIP
544 /// asks for one step narrower. The input's own Nyquist bounds the result:
545 /// coding above it would code the images the zero-stuffing put there.
546 fn auto_bandwidth(&self) -> Bandwidth {
547 let equiv = if self.channels == 2 {
548 (self.bitrate as f32 * 0.62) as u32
549 } else {
550 self.bitrate
551 };
552 let equiv = if self.application == Application::Voip {
553 (equiv as f32 * 0.7) as u32
554 } else {
555 equiv
556 };
557 let ceiling = match self.sample_rate {
558 48000 => Bandwidth::Full,
559 24000 => Bandwidth::SuperWide,
560 16000 => Bandwidth::Wide,
561 _ => Bandwidth::Narrow,
562 };
563 let wanted = if equiv < 9000 {
564 Bandwidth::Narrow
565 } else if equiv < 13000 {
566 Bandwidth::Wide
567 } else if equiv < 20000 {
568 Bandwidth::SuperWide
569 } else {
570 Bandwidth::Full
571 };
572 wanted.min(ceiling)
573 }
574
575 /// Encodes one frame — `frame_size` samples per channel of interleaved
576 /// `f32` at the input rate, 2.5, 5, 10 or 20 ms of it — as a code-0 Opus
577 /// packet in `out`, returning the packet length.
578 pub fn encode_float(
579 &mut self,
580 pcm: &[f32],
581 frame_size: usize,
582 out: &mut [u8],
583 ) -> Result<usize> {
584 let (toc, payload) =
585 self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1))?;
586 let n = payload.len();
587 if out.len() < 1 + n {
588 return Err(Error::corrupt(format!(
589 "opus encode: packet needs {} bytes, buffer holds {}",
590 1 + n,
591 out.len()
592 )));
593 }
594 out[0] = toc;
595 out[1..1 + n].copy_from_slice(payload);
596 Ok(1 + n)
597 }
598
599 /// [`Encoder::encode_float`] from 16-bit samples.
600 pub fn encode(&mut self, pcm: &[i16], frame_size: usize, out: &mut [u8]) -> Result<usize> {
601 let float: Vec<f32> = pcm.iter().map(|&v| v as f32 * (1.0 / 32768.0)).collect();
602 self.encode_float(&float, frame_size, out)
603 }
604
605 /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716
606 /// Appendix B: TOC, an explicit frame length, then the frame. This is
607 /// what every stream but the last uses inside a multistream packet.
608 pub fn encode_self_delimited(
609 &mut self,
610 pcm: &[f32],
611 frame_size: usize,
612 out: &mut [u8],
613 ) -> Result<usize> {
614 let (toc, payload) =
615 self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3))?;
616 let n = payload.len();
617 let len_bytes = if n < 252 { 1 } else { 2 };
618 if out.len() < 1 + len_bytes + n {
619 return Err(Error::corrupt(format!(
620 "opus encode: self-delimited packet needs {} bytes, buffer holds {}",
621 1 + len_bytes + n,
622 out.len()
623 )));
624 }
625 out[0] = toc;
626 if n < 252 {
627 out[1] = n as u8;
628 } else {
629 let b0 = 252 + ((n - 252) & 3);
630 out[1] = b0 as u8;
631 out[2] = ((n - b0) / 4) as u8;
632 }
633 out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(payload);
634 Ok(1 + len_bytes + n)
635 }
636
637 /// One hybrid frame (10 or 20 ms, mono or stereo, `bandwidth` SWB or FB)
638 /// into the internal range coder, returning its byte length: the SILK
639 /// layer's symbols (WB, 16 kHz internal, fed the input delayed by
640 /// [`HYBRID_SILK_DELAY_48K`]), the no-redundancy flag under the decoder's
641 /// exact presence rule, then the CELT layer from band 17 in the same
642 /// coder. CBR: the packet is the bitrate's size unless SILK alone needs
643 /// more, in which case CELT keeps [`HYBRID_CELT_MIN_BYTES`] on top.
644 fn encode_hybrid(
645 &mut self,
646 pcm: &[f32],
647 frame_size: usize,
648 bandwidth: Bandwidth,
649 cap: usize,
650 ) -> Result<usize> {
651 let cap = cap.min(MAX_FRAME_BYTES);
652 let frame_48k = frame_size * self.upsample;
653 let frame_ms = frame_48k / 48;
654 let budget = ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize;
655 let budget = budget.saturating_sub(1).clamp(2, cap);
656 if cap < HYBRID_CELT_MIN_BYTES + 2 {
657 return Err(Error::corrupt(
658 "opus encode: output buffer smaller than the minimum hybrid packet",
659 ));
660 }
661 if self.channels == 2 {
662 Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);
663 } else {
664 Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);
665 }
666 let d = HYBRID_SILK_DELAY_48K * self.channels;
667 if self.silk_delay.len() != d {
668 self.silk_delay.clear();
669 self.silk_delay.resize(d, 0.0);
670 }
671 let silk_len = frame_48k * self.channels;
672 let mut delayed = Vec::with_capacity(silk_len);
673 delayed.extend_from_slice(&self.silk_delay);
674 delayed.extend_from_slice(&self.silk_stuff[..silk_len - d]);
675 self.silk_delay
676 .copy_from_slice(&self.silk_stuff[silk_len - d..silk_len]);
677
678 self.range.reset(cap);
679 let silk_rate = Self::hybrid_silk_rate(self.bitrate, bandwidth);
680 if self.channels == 2 {
681 let silk = self
682 .silk_stereo_wb
683 .get_or_insert_with(|| SilkStereoEncoder::new(true));
684 silk.set_bitrate(silk_rate);
685 silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;
686 } else {
687 let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true));
688 silk.set_bitrate(silk_rate);
689 silk.encode_hybrid_ms(&delayed, &mut self.range, frame_ms)?;
690 }
691 let silk_bytes = (self.range.tell() as usize).div_ceil(8);
692 let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap);
693 self.range.shrink(budget);
694 // Redundancy flag: present under exactly the decoder's condition.
695 if self.range.tell() as usize + 17 + 20 <= 8 * budget {
696 self.range.enc_bit_logp(false, 12);
697 }
698 let n = self.celt.encode(
699 &mut self.range,
700 pcm,
701 frame_48k,
702 17,
703 bandwidth.celt_end_band(),
704 0,
705 )?;
706 self.final_range = self.range.range();
707 let payload = &self.range.data()[..n];
708 if self.channels == 2 {
709 self.silk_stereo_wb
710 .as_mut()
711 .unwrap()
712 .replay_hybrid(payload, frame_ms)?;
713 } else {
714 self.silk_wb
715 .as_mut()
716 .unwrap()
717 .replay_hybrid(payload, frame_ms)?;
718 }
719 Ok(n)
720 }
721
722 /// Encodes the CELT frame into the internal range coder and returns its
723 /// byte length. `frame_size` is in 48 kHz samples, `end` is the last coded
724 /// band, and `cap` bounds the frame (the caller's buffer minus headers).
725 fn encode_frame(
726 &mut self,
727 pcm: &[f32],
728 frame_size: usize,
729 end: usize,
730 cap: usize,
731 ) -> Result<usize> {
732 let cap = cap.min(MAX_FRAME_BYTES);
733 if cap < 2 {
734 return Err(Error::corrupt(
735 "opus encode: output buffer smaller than the minimum packet",
736 ));
737 }
738 // One byte per packet goes to the TOC; the CELT layer sees the rest.
739 let toc_bps = 8 * 48000 / frame_size as u32;
740 let (budget, vbr_rate) = if self.vbr {
741 (cap, self.bitrate.saturating_sub(toc_bps).max(500))
742 } else {
743 let b = ((self.bitrate as u64 * frame_size as u64 + 4 * 48000) / (8 * 48000)) as usize;
744 (b.saturating_sub(1).clamp(2, cap), 0)
745 };
746 self.range.reset(budget);
747 let n = self
748 .celt
749 .encode(&mut self.range, pcm, frame_size, 0, end, vbr_rate)?;
750 self.final_range = self.range.range();
751 Ok(n)
752 }
753}
754
755#[cfg(test)]
756mod tests {
757 use super::*;
758
759 /// The private half of the bandwidth decision: the thresholds themselves,
760 /// which the TOC config only reports.
761 #[test]
762 fn bandwidth_follows_the_bitrate_the_application_and_the_input_rate() {
763 let mut e = Encoder::new(48000, 1, Application::Audio).unwrap();
764 e.set_bitrate(64000);
765 assert_eq!(e.auto_bandwidth(), Bandwidth::Full);
766 e.set_bitrate(16000);
767 assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide);
768 e.set_bitrate(10000);
769 assert_eq!(e.auto_bandwidth(), Bandwidth::Wide);
770 e.set_bitrate(8000);
771 assert_eq!(e.auto_bandwidth(), Bandwidth::Narrow);
772 // Speech asks for one step narrower at the same rate.
773 let mut v = Encoder::new(48000, 1, Application::Voip).unwrap();
774 v.set_bitrate(16000);
775 assert_eq!(v.auto_bandwidth(), Bandwidth::Wide);
776 // The input's own Nyquist bounds it whatever the rate says.
777 let mut e = Encoder::new(24000, 2, Application::Audio).unwrap();
778 e.set_bitrate(256_000);
779 assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide);
780 assert_eq!(e.look_ahead(960), 60);
781 }
782
783 /// `look_ahead` must use the same 10-or-20 ms-frame predicate dispatch
784 /// does (`silk_choice`/`hybrid_choice`), not just `wants_silk`: 2.5/5 ms
785 /// frames still code as CELT, while 10/20 ms speech follows SILK and
786 /// hybrid follows CELT's overlap.
787 #[test]
788 fn look_ahead_matches_the_frame_size_dispatch_actually_uses() {
789 let mut e = Encoder::new(48000, 1, Application::Voip).unwrap();
790 e.set_bitrate(8000);
791 assert_eq!(e.look_ahead(480), 58, "10ms NB SILK");
792 assert_eq!(e.look_ahead(240), 120, "5ms frame falls back to CELT");
793 assert_eq!(e.look_ahead(960), 58, "20ms NB SILK");
794
795 e.set_bitrate(16000);
796 assert_eq!(e.look_ahead(960), 54, "20ms MB SILK");
797
798 e.set_bitrate(32000);
799 assert_eq!(e.look_ahead(960), 120, "20ms hybrid, CELT's overlap");
800
801 let mut e = Encoder::new(48000, 2, Application::Voip).unwrap();
802 e.set_bitrate(8000);
803 assert_eq!(e.look_ahead(960), 58, "stereo 20ms NB SILK");
804 e.set_bitrate(64_000);
805 assert_eq!(e.look_ahead(960), 120, "stereo 20ms hybrid");
806 }
807
808 #[test]
809 fn voip_auto_mode_is_monotonic_per_channel() {
810 for channels in [1usize, 2] {
811 let mut e = Encoder::new(48000, channels, Application::Voip).unwrap();
812 let mut last = 0u8;
813 for per_channel in 500..=45_000u32 {
814 e.set_bitrate(per_channel * channels as u32);
815 let class = if e.silk_choice(960).is_some() {
816 0
817 } else if e.hybrid_choice(960).is_some() {
818 1
819 } else {
820 2
821 };
822 assert!(
823 class >= last,
824 "{channels}ch {per_channel} bps/channel regressed from {last} to {class}"
825 );
826 last = class;
827 }
828 }
829 }
830}