forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust379.8 MiBfa65f3eTahinli3 months ago304 commits

encoder.rs628 lines, 25.7 KiBHistoryRawDownload
1//! The Opus packet encoder: CELT and mono SILK, 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) or
7//! SILK (TOC configs 1/9, mono NB/WB 20 ms only — stereo SILK and SILK at
8//! other frame sizes fall back to CELT, documented at the fallback site) or
9//! Hybrid (TOC configs 13/15, mono SWB/FB 20 ms: SILK at 16 kHz under CELT
10//! from band 17 up, one range-coded stream; stereo and other frame sizes
11//! fall back to CELT).
12//!
13//! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and
14//! the coded bandwidth is capped at the input's own Nyquist, so the images
15//! the stuffing puts there are never coded and the decoder's decimation
16//! drops them. [`Encoder::look_ahead`] reports the delay in *input* samples.
17//!
18//! Rate control is CBR by default — every packet the same size, derived from
19//! the bitrate — or constrained VBR, the reference's reservoir scheme, when
20//! [`Encoder::set_vbr_constrained`] is on. SILK packets are not yet budgeted
21//! against the target rate (D2b).
22
23use ec_core::{Error, Result};
24
25use crate::celt_enc::CeltEncoder;
26use crate::packet::{Bandwidth, Mode};
27use crate::range::RangeEncoder;
28use crate::silk_enc_write::SilkEncoder;
29
30/// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`).
31const MAX_FRAME_BYTES: usize = 1275;
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_WB: usize = 50;
42/// How far the hybrid path delays the SILK layer's input so its output lines
43/// up with the CELT layer's at the decoder (which sums them as-is): CELT's
44/// overlap (120) minus SILK's WB round trip, click-measured through the
45/// decoder with one layer muted (`hybrid_layers_align` in conformance.rs).
46const HYBRID_SILK_DELAY_48K: usize = 120 - SILK_LOOK_AHEAD_48K_WB;
47/// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent.
48const HYBRID_CELT_MIN_BYTES: usize = 8;
49
50/// What the caller is encoding. This encoder is CELT-only, so the setting
51/// biases the coded bandwidth rather than selecting a different layer.
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, CELT-only.
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_wb: Option<SilkEncoder>,
84 /// Scratch space for the SILK payload, sized once so the steady-state
85 /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate.
86 silk_buf: [u8; MAX_FRAME_BYTES + 1],
87 /// Hybrid: the last [`HYBRID_SILK_DELAY_48K`] samples of SILK-layer input.
88 silk_delay: Vec<f32>,
89 /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so
90 /// the steady-state loop doesn't allocate a `Vec` per frame.
91 silk_stuff: Vec<f32>,
92}
93
94impl Encoder {
95 /// An encoder for `channels` channels (1 or 2) at `sample_rate`, which
96 /// must be one of 8000, 12000, 16000, 24000 or 48000 Hz — the rates
97 /// RFC 6716 Section 2 admits. CELT itself runs at 48 kHz whatever the
98 /// input rate is (RFC 7845 Section 5.1).
99 pub fn new(sample_rate: u32, channels: usize, application: Application) -> Result<Encoder> {
100 let upsample = match sample_rate {
101 48000 => 1,
102 24000 => 2,
103 16000 => 3,
104 12000 => 4,
105 8000 => 6,
106 _ => {
107 return Err(Error::unsupported(
108 format!("opus encode at {sample_rate} Hz"),
109 "Opus encodes from 8, 12, 16, 24 or 48 kHz; resample first",
110 ));
111 }
112 };
113 if !(1..=2).contains(&channels) {
114 return Err(Error::unsupported(
115 format!("{channels}-channel Opus stream"),
116 "one stream carries at most two channels; use MultistreamEncoder",
117 ));
118 }
119 Ok(Encoder {
120 celt: CeltEncoder::new(channels, upsample),
121 range: RangeEncoder::new(),
122 sample_rate,
123 upsample,
124 channels,
125 bitrate: 64_000 * channels as u32,
126 vbr: false,
127 application,
128 bandwidth: None,
129 final_range: 0,
130 mode: None,
131 silk_nb: None,
132 silk_wb: None,
133 silk_buf: [0u8; MAX_FRAME_BYTES + 1],
134 silk_delay: Vec::new(),
135 silk_stuff: Vec::new(),
136 })
137 }
138
139 /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and
140 /// `hybrid_choice` make from the application and bitrate; pass `None` to
141 /// restore the automatic pick. Requests this encoder cannot honour
142 /// (stereo SILK/Hybrid, frames other than 20 ms) fall back to CELT.
143 pub fn set_mode(&mut self, mode: Option<Mode>) {
144 self.mode = mode;
145 }
146
147 /// Channels per frame of input.
148 pub fn channels(&self) -> usize {
149 self.channels
150 }
151
152 /// The rate the caller feeds.
153 pub fn sample_rate(&self) -> u32 {
154 self.sample_rate
155 }
156
157 /// Encoder delay in *input* samples for a `frame_size`-sample (per
158 /// channel, native rate) frame: the decoded stream lags the input by
159 /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate`
160 /// cancels it exactly. CELT: one MDCT overlap, 120 samples at 48 kHz.
161 /// SILK (mono, 20 ms/960-sample-at-48k frames only, when the
162 /// application/bitrate or an explicit [`Encoder::set_mode`] select it —
163 /// the same [`Encoder::silk_choice`] predicate `encode_toc_and_payload`
164 /// dispatches on, so this always matches which layer actually codes the
165 /// frame): [`SILK_LOOK_AHEAD_48K_NB`] or [`SILK_LOOK_AHEAD_48K_WB`], the
166 /// analysis-plus-synthesis resampler round trip, click-measured per
167 /// bandwidth. Hybrid: CELT's 120, the SILK layer being delayed to meet
168 /// it ([`HYBRID_SILK_DELAY_48K`]). Any other frame size (or SILK/Hybrid's
169 /// mono, 20 ms requirement unmet) falls back to CELT here exactly as
170 /// `encode_toc_and_payload` does.
171 pub fn look_ahead(&self, frame_size: usize) -> usize {
172 let frame_48k = frame_size * self.upsample;
173 if let Some(wideband) = self.silk_choice(frame_48k) {
174 let delay = if wideband {
175 SILK_LOOK_AHEAD_48K_WB
176 } else {
177 SILK_LOOK_AHEAD_48K_NB
178 };
179 return delay / self.upsample;
180 }
181 120 / self.upsample
182 }
183
184 /// Forces the coded bandwidth; [`None`] (the default) picks it from the
185 /// bitrate, the application and the input's Nyquist.
186 pub fn set_bandwidth(&mut self, bandwidth: Option<Bandwidth>) {
187 self.bandwidth = bandwidth;
188 }
189
190 /// Target bitrate in bits per second for the whole packet stream,
191 /// including the packet headers. Clamped to 500..=510000.
192 pub fn set_bitrate(&mut self, bps: u32) {
193 self.bitrate = bps.clamp(500, 510_000);
194 }
195
196 /// Current target bitrate.
197 pub fn bitrate(&self) -> u32 {
198 self.bitrate
199 }
200
201 /// Switches between CBR (default, every packet the target size) and
202 /// constrained VBR (packets vary, a reservoir holds the average to the
203 /// target).
204 pub fn set_vbr_constrained(&mut self, vbr: bool) {
205 self.vbr = vbr;
206 }
207
208 /// The range coder state after the last packet — the same value RFC 6716
209 /// test vectors carry, and what a conformant decoder's `final_range`
210 /// must equal after decoding that packet.
211 pub fn final_range(&self) -> u32 {
212 self.final_range
213 }
214
215 /// Drops all inter-frame state; the next packet starts like the first.
216 pub fn reset(&mut self) {
217 self.celt.reset();
218 self.silk_nb = None;
219 self.silk_wb = None;
220 self.silk_delay.clear();
221 self.final_range = 0;
222 }
223
224 /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`])
225 /// call for SILK, and if so, wideband (else narrowband). `None` means
226 /// CELT or Hybrid (`hybrid_choice` tells those apart).
227 fn wants_silk(&self) -> Option<bool> {
228 match self.mode {
229 Some(Mode::Celt) | Some(Mode::Hybrid) => None,
230 Some(Mode::Silk) => Some(self.bitrate > 10_000),
231 None => {
232 if self.application == Application::Voip && self.bitrate < 20_000 {
233 Some(self.bitrate > 10_000)
234 } else {
235 None
236 }
237 }
238 }
239 }
240
241 /// `wants_silk` narrowed to what this encoder can actually code as SILK:
242 /// mono, 20 ms (960 samples at 48 kHz) frames only. Stereo SILK and SILK
243 /// at other frame sizes are D2b's work; both fall back to CELT here.
244 fn silk_choice(&self, frame_48k: usize) -> Option<bool> {
245 let wideband = self.wants_silk()?;
246 if self.channels != 1 || frame_48k != 960 {
247 return None;
248 }
249 Some(wideband)
250 }
251
252 /// Whether this frame goes out as a hybrid packet, and at which of the two
253 /// hybrid bandwidths. Automatic: VoIP from 20 kbps (where SILK alone
254 /// stops) to 40 kbps (where CELT alone is the better speech coder too),
255 /// at the bitrate's own bandwidth (SWB/FB; narrower requests are CELT's).
256 /// Mono 20 ms only — stereo Hybrid (which needs stereo SILK) and the
257 /// 10 ms hybrid configs are not implemented and fall back to CELT.
258 fn hybrid_choice(&self, frame_48k: usize) -> Option<Bandwidth> {
259 let wanted = match self.mode {
260 Some(Mode::Hybrid) => true,
261 Some(_) => false,
262 None => {
263 self.application == Application::Voip
264 && (20_000..40_000).contains(&self.bitrate)
265 }
266 };
267 if !wanted || self.channels != 1 || frame_48k != 960 {
268 return None;
269 }
270 let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth());
271 match bandwidth {
272 Bandwidth::SuperWide | Bandwidth::Full => Some(bandwidth),
273 // A forced Hybrid codes at least SWB; an automatic one that the
274 // bitrate would cap narrower is CELT's.
275 _ if self.mode == Some(Mode::Hybrid) => Some(Bandwidth::SuperWide),
276 _ => None,
277 }
278 }
279
280 /// The SILK layer's share of a mono hybrid packet's bitrate, the
281 /// reference's 20 ms table interpolated: the rest is CELT's.
282 fn hybrid_silk_rate(total: u32, bandwidth: Bandwidth) -> u32 {
283 const TABLE: [(u32, u32, u32); 7] = [
284 (0, 0, 0),
285 (12000, 10000, 11000),
286 (16000, 13500, 14500),
287 (20000, 16000, 17000),
288 (24000, 18000, 19000),
289 (32000, 22000, 24000),
290 (64000, 38000, 42000),
291 ];
292 let pick = |row: &(u32, u32, u32)| if bandwidth == Bandwidth::Full { row.2 } else { row.1 };
293 let total = total.min(64000);
294 let i = TABLE.iter().rposition(|r| r.0 <= total).unwrap().min(TABLE.len() - 2);
295 let (lo, hi) = (&TABLE[i], &TABLE[i + 1]);
296 pick(lo) + (pick(hi) - pick(lo)) * (total - lo.0) / (hi.0 - lo.0)
297 }
298
299 /// Zero-stuffs a mono, `frame_size`-sample native-rate frame up to
300 /// `frame_size * upsample` samples at 48 kHz, the rate [`SilkEncoder`]
301 /// takes — the same technique [`CeltEncoder::encode`] uses, scaled by
302 /// `upsample` so the passband gain survives the stuffing. Writes into
303 /// `out` (an `Encoder` scratch field, not a fresh `Vec` per call) rather
304 /// than returning one, so the caller doesn't allocate every frame; the
305 /// slots between the `upsample`-strided samples stay zero from one call
306 /// to the next once `out` first grows to size, so only the strided
307 /// samples themselves need rewriting.
308 fn zero_stuff_mono(pcm: &[f32], frame_size: usize, upsample: usize, out: &mut Vec<f32>) {
309 if upsample == 1 {
310 out.clear();
311 out.extend_from_slice(&pcm[..frame_size]);
312 return;
313 }
314 out.resize(frame_size * upsample, 0.0);
315 for i in 0..frame_size {
316 out[i * upsample] = pcm[i] * upsample as f32;
317 }
318 }
319
320 /// Picks SILK or CELT for one frame and encodes it, returning the TOC
321 /// byte and the payload bytes (excluding TOC), borrowed from scratch
322 /// space owned by `self` — no allocation on the steady-state path.
323 /// `cap` bounds the CELT path only — SILK isn't budgeted against a byte
324 /// cap yet (D2b).
325 fn encode_toc_and_payload(
326 &mut self,
327 pcm: &[f32],
328 frame_size: usize,
329 cap: usize,
330 ) -> Result<(u8, &[u8])> {
331 let frame_48k = frame_size * self.upsample;
332 if let Some(wideband) = self.silk_choice(frame_48k) {
333 Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);
334 let enc = if wideband {
335 self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true))
336 } else {
337 self.silk_nb.get_or_insert_with(|| SilkEncoder::new(false))
338 };
339 // Keep SILK's own reservoir-based rate control tracking the
340 // Encoder's current target on every frame — cheap (an Option<u32>
341 // store) and catches set_bitrate calls made between frames.
342 enc.set_bitrate(self.bitrate);
343 let n = enc.encode_frame(&self.silk_stuff, &mut self.silk_buf)?;
344 self.final_range = enc.final_range();
345 return Ok((self.silk_buf[0], &self.silk_buf[1..n]));
346 }
347 if let Some(bandwidth) = self.hybrid_choice(frame_48k) {
348 let n = self.encode_hybrid(pcm, frame_size, bandwidth, cap)?;
349 let config = if bandwidth == Bandwidth::Full { 15u8 } else { 13 };
350 return Ok((config << 3, &self.range.data()[..n]));
351 }
352 let (toc, frame_48k, end) = self.toc(frame_size)?;
353 let n = self.encode_frame(pcm, frame_48k, end, cap)?;
354 Ok((toc, &self.range.data()[..n]))
355 }
356
357 /// The TOC byte, the frame size in 48 kHz samples and the CELT end band
358 /// for a frame of `frame_size` input samples per channel.
359 fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> {
360 let frame_48k = frame_size * self.upsample;
361 let fs_idx: u8 = match frame_48k {
362 120 => 0,
363 240 => 1,
364 480 => 2,
365 960 => 3,
366 _ => {
367 return Err(Error::unsupported(
368 format!(
369 "opus frame of {frame_size} samples at {} Hz",
370 self.sample_rate
371 ),
372 "CELT frames are 2.5, 5, 10 or 20 ms",
373 ));
374 }
375 };
376 let bandwidth = self.bandwidth.unwrap_or_else(|| self.auto_bandwidth());
377 let bw_idx: u8 = match bandwidth {
378 Bandwidth::Narrow => 0,
379 // CELT has no mediumband configuration; the next one up covers it.
380 Bandwidth::Medium | Bandwidth::Wide => 1,
381 Bandwidth::SuperWide => 2,
382 Bandwidth::Full => 3,
383 };
384 let config = 16 + 4 * bw_idx + fs_idx;
385 Ok((
386 (config << 3) | (u8::from(self.channels == 2) << 2),
387 frame_48k,
388 bandwidth.celt_end_band(),
389 ))
390 }
391
392 /// Bandwidth from the bitrate: coding 20 kHz at 24 kbps spends bits on air.
393 ///
394 /// The thresholds are on the mono-equivalent rate — a coupled stereo stream
395 /// needs about 1.6x a mono one for the same per-channel quality — and VoIP
396 /// asks for one step narrower. The input's own Nyquist bounds the result:
397 /// coding above it would code the images the zero-stuffing put there.
398 fn auto_bandwidth(&self) -> Bandwidth {
399 let equiv = if self.channels == 2 {
400 (self.bitrate as f32 * 0.62) as u32
401 } else {
402 self.bitrate
403 };
404 let equiv = if self.application == Application::Voip {
405 (equiv as f32 * 0.7) as u32
406 } else {
407 equiv
408 };
409 let ceiling = match self.sample_rate {
410 48000 => Bandwidth::Full,
411 24000 => Bandwidth::SuperWide,
412 16000 => Bandwidth::Wide,
413 _ => Bandwidth::Narrow,
414 };
415 let wanted = if equiv < 9000 {
416 Bandwidth::Narrow
417 } else if equiv < 13000 {
418 Bandwidth::Wide
419 } else if equiv < 20000 {
420 Bandwidth::SuperWide
421 } else {
422 Bandwidth::Full
423 };
424 wanted.min(ceiling)
425 }
426
427 /// Encodes one frame — `frame_size` samples per channel of interleaved
428 /// `f32` at the input rate, 2.5, 5, 10 or 20 ms of it — as a code-0 Opus
429 /// packet in `out`, returning the packet length.
430 pub fn encode_float(
431 &mut self,
432 pcm: &[f32],
433 frame_size: usize,
434 out: &mut [u8],
435 ) -> Result<usize> {
436 let (toc, payload) = self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1))?;
437 let n = payload.len();
438 if out.len() < 1 + n {
439 return Err(Error::corrupt(format!(
440 "opus encode: packet needs {} bytes, buffer holds {}",
441 1 + n,
442 out.len()
443 )));
444 }
445 out[0] = toc;
446 out[1..1 + n].copy_from_slice(payload);
447 Ok(1 + n)
448 }
449
450 /// [`Encoder::encode_float`] from 16-bit samples.
451 pub fn encode(&mut self, pcm: &[i16], frame_size: usize, out: &mut [u8]) -> Result<usize> {
452 let float: Vec<f32> = pcm.iter().map(|&v| v as f32 * (1.0 / 32768.0)).collect();
453 self.encode_float(&float, frame_size, out)
454 }
455
456 /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716
457 /// Appendix B: TOC, an explicit frame length, then the frame. This is
458 /// what every stream but the last uses inside a multistream packet.
459 pub fn encode_self_delimited(
460 &mut self,
461 pcm: &[f32],
462 frame_size: usize,
463 out: &mut [u8],
464 ) -> Result<usize> {
465 let (toc, payload) = self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3))?;
466 let n = payload.len();
467 let len_bytes = if n < 252 { 1 } else { 2 };
468 if out.len() < 1 + len_bytes + n {
469 return Err(Error::corrupt(format!(
470 "opus encode: self-delimited packet needs {} bytes, buffer holds {}",
471 1 + len_bytes + n,
472 out.len()
473 )));
474 }
475 out[0] = toc;
476 if n < 252 {
477 out[1] = n as u8;
478 } else {
479 let b0 = 252 + ((n - 252) & 3);
480 out[1] = b0 as u8;
481 out[2] = ((n - b0) / 4) as u8;
482 }
483 out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(payload);
484 Ok(1 + len_bytes + n)
485 }
486
487 /// One hybrid frame (mono, 20 ms, `bandwidth` SWB or FB) into the
488 /// internal range coder, returning its byte length: the SILK layer's
489 /// symbols (WB, 16 kHz internal, fed the input delayed by
490 /// [`HYBRID_SILK_DELAY_48K`]), the no-redundancy flag under the decoder's
491 /// exact presence rule, then the CELT layer from band 17 in the same
492 /// coder. CBR: the packet is the bitrate's size unless SILK alone needs
493 /// more, in which case CELT keeps [`HYBRID_CELT_MIN_BYTES`] on top.
494 fn encode_hybrid(
495 &mut self,
496 pcm: &[f32],
497 frame_size: usize,
498 bandwidth: Bandwidth,
499 cap: usize,
500 ) -> Result<usize> {
501 let cap = cap.min(MAX_FRAME_BYTES);
502 let budget = ((self.bitrate as u64 * 960 + 4 * 48000) / (8 * 48000)) as usize;
503 let budget = budget.saturating_sub(1).clamp(2, cap);
504 if cap < HYBRID_CELT_MIN_BYTES + 2 {
505 return Err(Error::corrupt(
506 "opus encode: output buffer smaller than the minimum hybrid packet",
507 ));
508 }
509 Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);
510 let d = HYBRID_SILK_DELAY_48K;
511 self.silk_delay.resize(d, 0.0);
512 let mut delayed = Vec::with_capacity(960);
513 delayed.extend_from_slice(&self.silk_delay);
514 delayed.extend_from_slice(&self.silk_stuff[..960 - d]);
515 self.silk_delay.copy_from_slice(&self.silk_stuff[960 - d..]);
516
517 self.range.reset(cap);
518 let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true));
519 silk.set_bitrate(Self::hybrid_silk_rate(self.bitrate, bandwidth));
520 silk.encode_hybrid(&delayed, &mut self.range)?;
521 let silk_bytes = (self.range.tell() as usize).div_ceil(8);
522 let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap);
523 self.range.shrink(budget);
524 // Redundancy flag: present under exactly the decoder's condition.
525 if self.range.tell() as usize + 17 + 20 <= 8 * budget {
526 self.range.enc_bit_logp(false, 12);
527 }
528 // CELT sees the same input as SILK: start band 17 alone keeps it off
529 // the low band (a one-pole ~6 kHz high-pass here measured identical
530 // full-band correlation, so there is none).
531 let n = self.celt.encode(
532 &mut self.range,
533 pcm,
534 960,
535 17,
536 bandwidth.celt_end_band(),
537 0,
538 )?;
539 self.final_range = self.range.range();
540 let payload = &self.range.data()[..n];
541 self.silk_wb.as_mut().unwrap().replay(payload)?;
542 Ok(n)
543 }
544
545 /// Encodes the CELT frame into the internal range coder and returns its
546 /// byte length. `frame_size` is in 48 kHz samples, `end` is the last coded
547 /// band, and `cap` bounds the frame (the caller's buffer minus headers).
548 fn encode_frame(
549 &mut self,
550 pcm: &[f32],
551 frame_size: usize,
552 end: usize,
553 cap: usize,
554 ) -> Result<usize> {
555 let cap = cap.min(MAX_FRAME_BYTES);
556 if cap < 2 {
557 return Err(Error::corrupt(
558 "opus encode: output buffer smaller than the minimum packet",
559 ));
560 }
561 // One byte per packet goes to the TOC; the CELT layer sees the rest.
562 let toc_bps = 8 * 48000 / frame_size as u32;
563 let (budget, vbr_rate) = if self.vbr {
564 (cap, self.bitrate.saturating_sub(toc_bps).max(500))
565 } else {
566 let b = ((self.bitrate as u64 * frame_size as u64 + 4 * 48000) / (8 * 48000)) as usize;
567 (b.saturating_sub(1).clamp(2, cap), 0)
568 };
569 self.range.reset(budget);
570 let n = self
571 .celt
572 .encode(&mut self.range, pcm, frame_size, 0, end, vbr_rate)?;
573 self.final_range = self.range.range();
574 Ok(n)
575 }
576}
577
578#[cfg(test)]
579mod tests {
580 use super::*;
581
582 /// The private half of the bandwidth decision: the thresholds themselves,
583 /// which the TOC config only reports.
584 #[test]
585 fn bandwidth_follows_the_bitrate_the_application_and_the_input_rate() {
586 let mut e = Encoder::new(48000, 1, Application::Audio).unwrap();
587 e.set_bitrate(64000);
588 assert_eq!(e.auto_bandwidth(), Bandwidth::Full);
589 e.set_bitrate(16000);
590 assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide);
591 e.set_bitrate(10000);
592 assert_eq!(e.auto_bandwidth(), Bandwidth::Wide);
593 e.set_bitrate(8000);
594 assert_eq!(e.auto_bandwidth(), Bandwidth::Narrow);
595 // Speech asks for one step narrower at the same rate.
596 let mut v = Encoder::new(48000, 1, Application::Voip).unwrap();
597 v.set_bitrate(16000);
598 assert_eq!(v.auto_bandwidth(), Bandwidth::Wide);
599 // The input's own Nyquist bounds it whatever the rate says.
600 let mut e = Encoder::new(24000, 2, Application::Audio).unwrap();
601 e.set_bitrate(256_000);
602 assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide);
603 assert_eq!(e.look_ahead(960), 60);
604 }
605
606 /// `look_ahead` must use the same mono/20 ms-frame predicate dispatch
607 /// does (`silk_choice`/`hybrid_choice`), not just `wants_silk` — a
608 /// non-20 ms frame (or stereo) codes as CELT regardless of the
609 /// bitrate/application, so its look-ahead is CELT's 120, not SILK's.
610 #[test]
611 fn look_ahead_matches_the_frame_size_dispatch_actually_uses() {
612 let mut e = Encoder::new(48000, 1, Application::Voip).unwrap();
613 e.set_bitrate(8000);
614 assert_eq!(e.look_ahead(480), 120, "sub-20ms frame falls back to CELT");
615 assert_eq!(e.look_ahead(240), 120, "sub-20ms frame falls back to CELT");
616 assert_eq!(e.look_ahead(960), 58, "20ms NB SILK");
617
618 e.set_bitrate(16000);
619 assert_eq!(e.look_ahead(960), 50, "20ms WB SILK");
620
621 e.set_bitrate(32000);
622 assert_eq!(e.look_ahead(960), 120, "20ms hybrid, CELT's overlap");
623
624 let mut e = Encoder::new(48000, 2, Application::Voip).unwrap();
625 e.set_bitrate(8000);
626 assert_eq!(e.look_ahead(960), 120, "stereo never codes as SILK/Hybrid");
627 }
628}