forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiBf70e8e6Tahinli3 months ago314 commits

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