//! The Opus packet encoder: CELT, SILK and hybrid, 8 to 48 kHz in. //! //! One [`Encoder`] produces ordinary code-0 Opus packets (RFC 6716 Section 3) //! or the self-delimited variant of Appendix B that the multistream framing //! needs. [`Encoder::set_mode`] (or the automatic choice in [`Mode`]'s //! default) picks CELT (TOC configs 16..31, every rate and frame size), SILK //! (TOC configs 0..11, mono NB/MB/WB 10/20/40/60 ms; stereo NB/MB/WB 10/20 ms, //! with 40/60 ms carried as code-3 packets of 20 ms SILK frames), or Hybrid //! (TOC configs 13/15, mono or stereo SWB/FB 10 or 20 ms: SILK at 16 kHz under //! CELT from band 17 up, one range-coded stream). //! //! In-band FEC (SILK LBRR, [`Encoder::set_inband_fec`]) is mono SILK and //! hybrid 10/20 ms only. //! //! Input below 48 kHz is zero-stuffed to CELT's or SILK's native rate and //! the coded bandwidth is capped at the input's own Nyquist, so the images //! the stuffing puts there are never coded and the decoder's decimation //! drops them. [`Encoder::look_ahead`] reports the delay in *input* samples. //! //! Rate control is CBR by default — every packet the same size, derived from //! the bitrate — or constrained VBR, the reference's reservoir scheme, when //! [`Encoder::set_vbr_constrained`] is on. A CBR SILK packet of 10 or 20 ms //! is held to the same byte budget as a CELT one: its rate loop coarsens //! until it fits (D2b), then padded up to the budget with code-3 packet //! padding like libopus's `opus_packet_pad`. use ec_core::{Error, Result}; use crate::analysis::{AnalysisInfo, TonalityAnalysis}; use crate::celt_enc::CeltEncoder; use crate::packet::{Bandwidth, Mode}; use crate::range::RangeEncoder; use crate::silk_flp::opus::{InputFilter, SilkFrame, SilkLayer, hp_min_smth1_q15}; /// Most bytes one Opus frame may occupy (RFC 6716 `[R2]`). const MAX_FRAME_BYTES: usize = 1275; enum Payload { Range(usize), Silk(usize), } const MAX_SILK_PACKET_BYTES: usize = 1 + 1 + 2 * 2 + 3 * MAX_FRAME_BYTES; /// One MDCT overlap: the CELT layer's delay without libopus's input /// alignment ([`Encoder::set_libopus_input_alignment`]), which adds /// `delay_compensation = Fs/250` (192 at 48 kHz) on top. const CELT_OVERLAP_48K: usize = 120; /// libopus `opus_encoder.c`'s `delay_compensation = Fs/250`. const CELT_DELAY_COMP_48K: usize = 192; /// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent. /// Was 8: at 16 kbps SILK takes 37 of the 40-byte budget, so 8 expanded /// 5133/6001 packets (+12.9% rate on the speech gate); libopus leaves CELT /// a few bytes there. const HYBRID_CELT_MIN_BYTES: usize = 3; /// libopus 1.6 bandwidth threshold tables (`opus_encoder.c:151`/`162`). /// Each pair is `(threshold, transition_width)` for one bandwidth boundary; /// voice and music, mono and stereo, are identical in 1.6. const MONO_VOICE_BW: [i32; 8] = [9000, 700, 9000, 700, 13500, 1000, 14000, 2000]; const STEREO_VOICE_BW: [i32; 8] = [9000, 700, 9000, 700, 13500, 1000, 14000, 2000]; const MONO_MUSIC_BW: [i32; 8] = [9000, 700, 9000, 700, 11000, 1000, 12000, 2000]; const STEREO_MUSIC_BW: [i32; 8] = [9000, 700, 9000, 700, 11000, 1000, 12000, 2000]; /// libopus `mode_thresholds` blended by `voice_est` (`opus_encoder.c:183`). /// With `stereo_width=0` (no analysis) the voice term is `[0][0]=64000` and /// the music base is `10000`; the gap (54000) is the ve² interpolation span. const MODE_THRESHOLD_VOICE: i32 = 64000; const MODE_THRESHOLD_MUSIC: i32 = 10000; /// Opus default encoder complexity (the `(90+complexity)/100` equiv-rate /// multiplier; loss=0 and complexity≥5 add no per-mode adjustment). const DEFAULT_COMPLEXITY: i32 = 9; /// What the caller is encoding. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Application { /// Speech: one step narrower at a given rate, where the top octave costs /// most and carries least. Voip, /// Music and general audio, the default. Audio, /// Lowest delay. LowDelay, } const DTX_START_Q1: i32 = 10 * 2 * 20; const DTX_END_Q1: i32 = (10 + 20) * 2 * 20; const DTX_ACTIVITY_THRESHOLD: f32 = 0.1; const DTX_PSEUDO_SNR_THRESHOLD: f32 = 316.23; const DTX_SILENCE: f32 = 1.0 / 16_777_216.0; /// The TOC-only packet libopus sends in DTX: code 0 is the TOC alone; code 3 /// keeps its frame-count byte with no frames. Self-delimited framing adds a /// zero frame length after it. fn dtx_packet(toc: u8, count: u8, self_delimited: bool) -> ([u8; 3], usize) { let mut bytes = [0u8; 3]; let len = if toc & 3 == 3 { bytes[0] = toc; bytes[1] = count & 0x3F; if self_delimited { 3 } else { 2 } } else { bytes[0] = toc & !3; if self_delimited { 2 } else { 1 } }; (bytes, len) } /// One elementary Opus encoder: mono or stereo. #[derive(Clone, Debug)] pub struct Encoder { celt: CeltEncoder, range: RangeEncoder, sample_rate: u32, /// 48000 / `sample_rate`: the zero-stuffing factor into CELT. upsample: usize, channels: usize, bitrate: u32, vbr: bool, application: Application, bandwidth: Option, final_range: u32, /// [`None`] picks SILK, CELT or (once D4 lands) Hybrid from the /// application and bitrate; `Some` forces one. mode: Option, /// The SILK layer, created on first use (boxed: `crate::stack_budget`). silk: Option>, /// Scratch space for the SILK packet payload, sized once so the steady-state /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. /// /// Boxed for the same reason as the slots above: `MAX_SILK_PACKET_BYTES` is /// 4088 bytes, and an inline array that size is a third of the whole /// budget on the `Encoder` that a caller holds by value. silk_buf: Box<[u8; MAX_SILK_PACKET_BYTES]>, /// [`Encoder::set_libopus_input_alignment`]. align_input: bool, filter: InputFilter, /// Scratch space for the filter's output, sized once. hp_buf: Vec, /// libopus `st->analysis`: the tonality/music-probability estimator. It /// lives here, not in the CELT layer, because `opus_encode_native` runs /// `run_analysis()` on the API frame *before* the SILK/CELT mode and /// bandwidth decisions, so its state advances on SILK frames too. analysis: TonalityAnalysis, /// The current frame's analysis output, handed to `celt.encode`. info: AnalysisInfo, /// Whether the analysis runs at all — see `celt_enc::analysis_params`. analysis_on: bool, /// Whether the detected bandwidth may lower the coded one (`EC_OPUS_BW_DETECT`). bw_detect: bool, inband_fec: bool, packet_loss_perc: u8, lbrr_coded: bool, fec_bandwidth: Option, last_silk: Option, use_dtx: bool, nb_no_activity_ms_q1: i32, peak_signal_energy: f32, } fn toc_bandwidth(toc: u8) -> Bandwidth { const BW: [Bandwidth; 5] = [ Bandwidth::Narrow, Bandwidth::Medium, Bandwidth::Wide, Bandwidth::SuperWide, Bandwidth::Full, ]; let config = usize::from(toc >> 3); match config { 0..=11 => BW[config / 4], 12 | 13 => Bandwidth::SuperWide, 14 | 15 => Bandwidth::Full, _ => [BW[0], BW[2], BW[3], BW[4]][(config - 16) / 4], } } /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8, /// Medium → 12, Wide/SuperWide/Full → 16. SILK only runs at 8/12/16 kHz; /// for SuperWide/Full the top bands are CELT (Hybrid), so SILK itself is 16. fn silk_fs_khz(bw: Bandwidth) -> usize { match bw { Bandwidth::Narrow => 8, Bandwidth::Medium => 12, _ => 16, } } impl Encoder { /// An encoder for `channels` channels (1 or 2) at `sample_rate`, which /// must be one of 8000, 12000, 16000, 24000 or 48000 Hz — the rates /// RFC 6716 Section 2 admits. CELT itself runs at 48 kHz whatever the /// input rate is (RFC 7845 Section 5.1). pub fn new(sample_rate: u32, channels: usize, application: Application) -> Result { let upsample = match sample_rate { 48000 => 1, 24000 => 2, 16000 => 3, 12000 => 4, 8000 => 6, _ => { return Err(Error::unsupported( format!("opus encode at {sample_rate} Hz"), "Opus encodes from 8, 12, 16, 24 or 48 kHz; resample first", )); } }; if !(1..=2).contains(&channels) { return Err(Error::unsupported( format!("{channels}-channel Opus stream"), "one stream carries at most two channels; use MultistreamEncoder", )); } let mut enc = Encoder { celt: CeltEncoder::new(channels, upsample), range: RangeEncoder::new(), sample_rate, upsample, channels, bitrate: 64_000 * channels as u32, vbr: false, application, bandwidth: None, final_range: 0, mode: None, silk: None, silk_buf: Box::new([0u8; MAX_SILK_PACKET_BYTES]), align_input: application != Application::LowDelay, filter: InputFilter::new(), hp_buf: Vec::new(), analysis: TonalityAnalysis::new(sample_rate), info: AnalysisInfo::default(), analysis_on: crate::celt_enc::analysis_params().0, bw_detect: crate::celt_enc::analysis_params().5, inband_fec: false, packet_loss_perc: 0, lbrr_coded: false, fec_bandwidth: None, last_silk: None, use_dtx: false, nb_no_activity_ms_q1: 0, peak_signal_energy: 0.0, }; enc.celt.set_align_input(enc.align_input); Ok(enc) } /// Turns the tonality analysis on or off for this encoder. It is off /// unless one of its consumers is switched on (see /// `celt_enc::analysis_params`), because it costs ~25% of the encoder; /// turn it on to read `music_prob`/`tonality` back through /// [`Encoder::last_celt_diag`]. pub fn set_analysis(&mut self, on: bool) { self.analysis_on = on; } /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and /// `hybrid_choice` make from the application and bitrate; pass `None` to /// restore the automatic pick. Requests this encoder cannot honour /// (10 ms Hybrid) fall back to CELT. pub fn set_mode(&mut self, mode: Option) { self.mode = mode; } /// Channels per frame of input. pub fn channels(&self) -> usize { self.channels } /// The rate the caller feeds. pub fn sample_rate(&self) -> u32 { self.sample_rate } /// Encoder delay in *input* samples for a `frame_size`-sample (per /// channel, native rate) frame: the decoded stream lags the input by /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate` /// cancels it exactly. CELT: one MDCT overlap plus the 192-sample input /// delay compensation, 312 samples at 48 kHz. /// SILK and hybrid: 312 as well, the libopus SILK encoder's own delay, /// which the CELT layer's input delay is there to match. pub fn look_ahead(&self, frame_size: usize) -> usize { let frame_48k = frame_size * self.upsample; if self.silk_choice(frame_48k).is_some() { return (CELT_OVERLAP_48K + CELT_DELAY_COMP_48K) / self.upsample; } self.celt_look_ahead_48k() / self.upsample } /// The CELT layer's delay in 48 kHz samples: one MDCT overlap, plus /// libopus's `delay_compensation` when the alignment is on. fn celt_look_ahead_48k(&self) -> usize { CELT_OVERLAP_48K + if self.align_input { CELT_DELAY_COMP_48K } else { 0 } } /// On by default except for [`Application::LowDelay`], as in libopus: the /// SILK layer's own delay is 312 samples, and only an aligned CELT layer /// keeps CELT, SILK and hybrid frames of one stream at the same delay. /// /// Puts our CELT analysis window exactly where libopus's is: the layer is /// fed the input delayed by `delay_compensation = Fs/250` (192 samples at /// 48 kHz, `opus_encoder.c` ~:1955) and every frame first goes through /// libopus's 3 Hz `dc_reject`. The alignment is *exact* — on the reell /// attack frame (frame 2, 20 ms, LM=3, transient) our first eight band /// log-energies become /// 3.4386 4.0055 3.2603 4.5954 1.1790 4.2774 4.7584 3.7169 against /// libopus's 3.439 4.005 3.260 4.595 1.179 4.277 4.758 3.717, all eight /// within .0006 (the unaligned encoder is .06-.21 apart). /// /// It ships OFF because the 12-row library gate rejects it, and because /// re-tuning the constants that were fitted on the misaligned spectrum /// does not rescue it. Against the shipped rows /// (`lanes/opus-opustr2-r1.sweep.txt`), err_ratio: /// /// | arm | better | worse (blocking) | /// |---|---|---| /// | delay only (`opus-opusx-r1`) | 7 | nik@64 .708→.800, nik@96 .985→1.763, her@96 1.051→1.292, hein@64 .853→.980, hein@96 .528→1.602 | /// | delay + `dc_reject` (`opus-opusx2-r1`) | 5 | those, plus dl8a@64 .552→1.074, dl8a@96 .374→1.011 | /// | + two-pass coarse energy (`-r2`) | 5 | same 7 rows (nik@96 1.809, dl8a@64 1.200) | /// | + continuous 1.3 `alloc_trim` (`-r3`) | 5 | same 7, and corr worse by >.0005 on 9 rows | /// | + tf boost k=1.25 (`-r4`) | 5 | same 7 | /// | + tf boost k=1.5 (`-r5`) | 5 | same 7 | /// | + two-pass *and* k=1.25, the combined best (`-r7`) | 5 | same 7: nik@64 .773, nik@96 1.801, her@96 1.114, dl8a@64 1.181, dl8a@96 1.014, hein@64 .977, hein@96 1.398 | /// | + the whole libopus tonality analysis and its `alloc_trim`/`compute_vbr` consumers (`opus-opustonal-r4`) | 5 | same 7: nik@64 1.014, nik@96 1.842, her@96 1.217, dl8a@64 1.162, dl8a@96 .988, hein@64 .971, hein@96 1.514 | /// /// The best aligned arm on the KEEP rule is the delay alone without /// `dc_reject` (5 rows worse); every arm that adds `dc_reject` puts dl8a /// in the blocking set too. /// /// The last row is the one that was expected to rescue this: libopus's /// actual operating point is the aligned spectrum *with* `analysis->valid` /// true, and running the real analysis (`crates/ec-opus/src/analysis.rs`, /// `music_prob` matching a patched-libopus trace to .001) moves reell@64 /// 2.697→1.865, reell@96 4.499→3.986, reelo@64 1.510→1.123 and her@64 /// 1.103→.952 — the largest movement any arm has produced on those rows — /// and still leaves the same seven rows worse. /// /// The blocking set (nik, her@96, dl8a, hein) is the same in every arm and /// no arm moves any of those rows back towards its shipped value, so the /// misfit is not one of the swept constants. Turning this on also costs /// 4 ms of algorithmic delay: [`Encoder::look_ahead`] for a CELT frame /// becomes 312, not 120, and the Ogg pre-skip must follow it. pub fn set_libopus_input_alignment(&mut self, on: bool) { self.align_input = on; self.celt.set_align_input(on); self.filter = InputFilter::new(); } /// Forces the coded bandwidth; [`None`] (the default) picks it from the /// bitrate, the application and the input's Nyquist. pub fn set_bandwidth(&mut self, bandwidth: Option) { self.bandwidth = bandwidth; } /// Target bitrate in bits per second for the whole packet stream, /// including the packet headers. Clamped to 500..=510000. pub fn set_bitrate(&mut self, bps: u32) { self.bitrate = bps.clamp(500, 510_000); } /// OPUS_SET_INBAND_FEC: code LBRR (in-band FEC) when the loss rate and bitrate justify it; prefers SILK/hybrid over CELT under loss. pub fn set_inband_fec(&mut self, on: bool) { self.inband_fec = on; } /// OPUS_SET_PACKET_LOSS_PERC: expected packet loss, 0..=100 (clamped). pub fn set_packet_loss_perc(&mut self, perc: u8) { self.packet_loss_perc = perc.min(100); } /// OPUS_SET_DTX: send TOC-only packets during silence/inactivity (after 200 ms), refreshing every 400 ms. pub fn set_dtx(&mut self, on: bool) { self.use_dtx = on; } /// libopus's peak signal energy tracker, run on every frame after the analysis. fn track_peak(&mut self, pcm: &[f32], frame_size: usize) { let n = frame_size * self.channels; if pcm.iter().take(n).all(|x| x.abs() <= DTX_SILENCE) { return; } if !self.info.valid || self.info.activity_probability > DTX_ACTIVITY_THRESHOLD { let energy = pcm.iter().take(n).map(|x| x * x).sum::() / n as f32; self.peak_signal_energy = (0.999 * self.peak_signal_energy).max(energy); } } /// The `activity` libopus hands `silk_Encode`: 0/1 from the analysis, /// -1 (`VAD_NO_DECISION`) without it. fn silk_activity(&self, pcm: &[f32], frame_size: usize) -> i32 { let n = frame_size * self.channels; if pcm.iter().take(n).all(|x| x.abs() <= DTX_SILENCE) { return 0; } if !self.info.valid { return -1; } let energy = pcm.iter().take(n).map(|x| x * x).sum::() / n as f32; i32::from( self.info.activity_probability >= DTX_ACTIVITY_THRESHOLD || self.peak_signal_energy < DTX_PSEUDO_SNR_THRESHOLD * energy, ) } /// libopus `decide_dtx_mode` plus the activity test of `opus_encode_native` /// for one frame: true when this frame's packet is a DTX one. fn dtx_frame(&mut self, pcm: &[f32], frame_size: usize) -> bool { if !self.use_dtx { return false; } let n = frame_size * self.channels; let energy = pcm.iter().take(n).map(|x| x * x).sum::() / n as f32; let is_silence = pcm.iter().all(|x| x.abs() <= DTX_SILENCE); let (valid, prob) = (self.info.valid, self.info.activity_probability); let active = if is_silence { false } else if valid { prob >= DTX_ACTIVITY_THRESHOLD || self.peak_signal_energy < DTX_PSEUDO_SNR_THRESHOLD * energy } else { true }; if active { self.nb_no_activity_ms_q1 = 0; return false; } self.nb_no_activity_ms_q1 += 2 * 1000 * frame_size as i32 / self.sample_rate as i32; if self.nb_no_activity_ms_q1 > DTX_START_Q1 { if self.nb_no_activity_ms_q1 <= DTX_END_Q1 { return true; } self.nb_no_activity_ms_q1 = DTX_START_Q1; } false } /// Current target bitrate. pub fn bitrate(&self) -> u32 { self.bitrate } /// Switches between CBR (default, every packet the target size) and /// constrained VBR (packets vary, a reservoir holds the average to the /// target). pub fn set_vbr_constrained(&mut self, vbr: bool) { self.vbr = vbr; } /// The range coder state after the last packet — the same value RFC 6716 /// test vectors carry, and what a conformant decoder's `final_range` /// must equal after decoding that packet. pub fn final_range(&self) -> u32 { self.final_range } /// Per-frame CELT diagnostics from the most recent [`encode_float`] call. /// Intended for the reelm@64k dropout investigation; the fields are only /// meaningful when the last frame was coded as pure CELT (the path every /// fullband Audio frame at 64 kbps stereo takes). /// /// [`encode_float`]: Encoder::encode_float pub fn last_celt_diag(&self) -> &crate::celt_enc::CeltFrameDiag { self.celt.last_diag() } /// Drops all inter-frame state; the next packet starts like the first. pub fn reset(&mut self) { self.celt.reset(); self.silk = None; self.filter = InputFilter::new(); self.final_range = 0; self.analysis.reset(); self.info = AnalysisInfo::default(); self.lbrr_coded = false; self.fec_bandwidth = None; self.last_silk = None; self.nb_no_activity_ms_q1 = 0; self.peak_signal_energy = 0.0; } /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) /// calls for SILK, and if so, which SILK internal sample rate in kHz. /// `None` means CELT or Hybrid (`hybrid_choice` tells those apart). /// /// Ports libopus's mode decision: SILK when `equiv_rate` is below the /// voice/music-blended mode threshold (`opus_encoder.c` ~1900), with the /// bandwidth from the threshold walk. SILK only codes up to Wide; a /// SuperWide/Full result is Hybrid (10/20 ms) or, for 40/60 ms frames /// that Hybrid cannot carry, SILK capped at Wide. fn wants_silk(&self, frame_48k: usize) -> Option { match self.mode { Some(Mode::Celt) | Some(Mode::Hybrid) => None, Some(Mode::Silk) => { let bw = self .fec_bandwidth .or(self.bandwidth) .unwrap_or_else(|| self.auto_bandwidth()); Some(silk_fs_khz(bw)) } None => { let equiv = self.equiv_rate(frame_48k); let ve = self.voice_est(); if !self.auto_silk(equiv, ve) { return None; } let bw = self.auto_mode_bandwidth(equiv, ve); // 40/60 ms frames are SILK-only (Hybrid supports 10/20 ms): // cap at Wide so a high equiv rate does not fall through to // an impossible CELT 40/60 ms packet. let bw = if matches!(frame_48k, 1920 | 2880) { bw.min(Bandwidth::Wide) } else { bw }; if bw > Bandwidth::Wide { None // Hybrid territory — see hybrid_choice } else { Some(silk_fs_khz(bw)) } } } } /// The SILK/hybrid bandwidth in auto mode; libopus keeps CBR below /// 15 kb/s out of hybrid by capping it at Wide. fn auto_mode_bandwidth(&self, equiv: i32, ve: i32) -> Bandwidth { let bw = self .fec_bandwidth .or(self.bandwidth) .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)); if !self.vbr && self.bitrate < 15000 { bw.min(Bandwidth::Wide) } else { bw } } /// `wants_silk` narrowed to what this encoder can actually code as SILK: /// mono 10/20/40/60 ms, stereo 10/20 ms directly, or stereo 40/60 ms as /// code-3 packets of 20 ms SILK frames. fn silk_choice(&self, frame_48k: usize) -> Option { let fs_khz = self.wants_silk(frame_48k)?; if !matches!(frame_48k, 480 | 960 | 1920 | 2880) { return None; } Some(fs_khz) } /// Whether this frame goes out as a hybrid packet, and at which of the two /// hybrid bandwidths. Automatic: Hybrid is SILK mode (equiv below the mode /// threshold) whose bandwidth walk lands on SuperWide/Full — SILK alone /// cannot code above Wide, so CELT carries the top bands. 10 or 20 ms /// only (Hybrid has no 40/60 ms config). Forced Hybrid codes at least SWB. fn hybrid_choice(&self, frame_48k: usize) -> Option { if matches!(self.mode, Some(Mode::Silk) | Some(Mode::Celt)) { return None; } if !matches!(frame_48k, 480 | 960) { return None; } let equiv = self.equiv_rate(frame_48k); let ve = self.voice_est(); if self.mode.is_none() && !self.auto_silk(equiv, ve) { return None; } let bw = if self.mode.is_none() { self.auto_mode_bandwidth(equiv, ve) } else { self.fec_bandwidth .or(self.bandwidth) .unwrap_or_else(|| self.auto_bandwidth_at(equiv, ve)) }; match bw { Bandwidth::SuperWide | Bandwidth::Full => Some(bw), // A forced Hybrid with a narrow/medium/wide bandwidth still codes // at least SWB — Hybrid has no narrower configuration. _ if self.mode == Some(Mode::Hybrid) => Some(Bandwidth::SuperWide), _ => None, } } fn write_frame_len(out: &mut [u8], pos: &mut usize, len: usize) -> Result<()> { if len > MAX_FRAME_BYTES { return Err(Error::corrupt(format!( "opus encode: frame payload of {len} bytes exceeds {MAX_FRAME_BYTES}" ))); } if len < 252 { out[*pos] = len as u8; *pos += 1; } else { let b0 = 252 + ((len - 252) & 3); out[*pos] = b0 as u8; out[*pos + 1] = ((len - b0) / 4) as u8; *pos += 2; } Ok(()) } /// The CBR packet budget for a `frame_48k`-sample frame, in payload bytes, /// by the figure the CELT path uses; `None` under constrained VBR (D2b). fn packet_budget(&self, frame_48k: usize, cap: usize) -> Option { if self.vbr { return None; } let b = ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize; Some(b.saturating_sub(1).max(2).min(cap)) } /// The `silk_mode` fields libopus sets for one frame; `max_data_bytes` /// counts the TOC byte. fn silk_frame( &self, max_data_bytes: usize, internal_khz: usize, hybrid: bool, swb: bool, ) -> SilkFrame { SilkFrame { bitrate: self.bitrate as i32, max_data_bytes, vbr: self.vbr, hybrid, swb, internal_khz: internal_khz as i32, stream_channels: self.channels, fec: self.inband_fec, lbrr_coded: self.lbrr_coded, loss_perc: i32::from(self.packet_loss_perc), complexity: DEFAULT_COMPLEXITY, } } /// The SILK layer, reset when the previous frame was CELT-only (libopus /// re-inits `silk_enc` on a CELT to SILK/hybrid transition). fn silk_layer(&mut self) -> &mut SilkLayer { let (fs, ch, fresh) = (self.sample_rate, self.channels, self.last_silk.is_none()); let silk = self .silk .get_or_insert_with(|| Box::new(SilkLayer::new(fs, ch))); if fresh { silk.reset(); } silk } /// Picks SILK or CELT for one frame and encodes it, returning the TOC /// byte and the payload bytes (excluding TOC), borrowed from scratch /// space owned by `self` — no allocation on the steady-state path. /// `cap` bounds the packet; under CBR a SILK packet is held to the same budget /// as a CELT one (D2b). fn encode_toc_and_payload( &mut self, pcm: &[f32], frame_size: usize, cap: usize, ) -> Result<(u8, &[u8])> { let frame_48k = frame_size * self.upsample; self.fec_bandwidth = None; if frame_48k > 960 && self.silk_choice(frame_48k).is_none() { return self.encode_multiframe(pcm, frame_size, cap); } // libopus `opus_encode_native`: `run_analysis()` runs on the API frame // before the mode/bandwidth decisions, so the estimator state advances // on every frame, SILK ones included. 24 is libopus's float-API // `lsb_depth` default. self.info = if self.analysis_on { self.analysis.run(pcm, frame_size, self.channels, 24) } else { AnalysisInfo::default() }; self.track_peak(pcm, frame_size); let (fec, fec_bw) = self.fec_for(frame_48k); self.lbrr_coded = fec; self.fec_bandwidth = fec_bw; let silk_khz = self.silk_choice(frame_48k); let hybrid_bw = if silk_khz.is_none() { self.hybrid_choice(frame_48k) } else { None }; let mut buf = std::mem::take(&mut self.hp_buf); self.filter_input( pcm, frame_size, silk_khz.is_none() && hybrid_bw.is_none(), &mut buf, ); let r = self.encode_mode(pcm, &buf, frame_size, cap, silk_khz, hybrid_bw); self.hp_buf = buf; let (toc, payload) = r?; Ok(( toc, match payload { Payload::Range(n) => &self.range.data()[..n], Payload::Silk(n) => &self.silk_buf[..n], }, )) } /// libopus `opus_encode_frame_native`'s input filter: `hp_cutoff` for /// VoIP, its cutoff following SILK's estimate unless the frame is /// CELT-only; otherwise the 3 Hz `dc_reject` (only with the CELT input /// alignment on, the libopus default). fn filter_input( &mut self, pcm: &[f32], frame_size: usize, celt_only: bool, out: &mut Vec, ) { let n = frame_size * self.channels; out.clear(); out.resize(n, 0.0); let fs = self.sample_rate as i32; if self.application == Application::Voip { let smth1 = match (&self.silk, celt_only) { (Some(silk), false) => silk.hp_smth1_q15(), _ => hp_min_smth1_q15(), }; self.filter .hp_cutoff(&pcm[..n], out, smth1, self.channels, fs); } else if self.align_input { self.filter.dc_reject(&pcm[..n], out, self.channels, fs); } else { out.copy_from_slice(&pcm[..n]); } } fn encode_mode( &mut self, raw: &[f32], pcm: &[f32], frame_size: usize, cap: usize, silk_khz: Option, hybrid_bw: Option, ) -> Result<(u8, Payload)> { let frame_48k = frame_size * self.upsample; if let Some(fs_khz) = silk_khz { let max_data_bytes = self .packet_budget(frame_48k, cap) .unwrap_or(cap) .min(MAX_FRAME_BYTES) + 1; let f = self.silk_frame(max_data_bytes, fs_khz, false, false); let activity = self.silk_activity(raw, frame_size); self.range.reset(max_data_bytes - 1); let mut range = std::mem::take(&mut self.range); let (_, khz) = self .silk_layer() .encode(pcm, frame_size, &f, activity, &mut range); self.range = range; let mut len = (self.range.tell() as usize).div_ceil(8); self.range.done(); while len > 2 && self.range.data()[len - 1] == 0 { len -= 1; } self.final_range = self.range.range(); self.last_silk = Some(khz as u8); let base = match khz { 8 => 0u8, 12 => 4, _ => 8, }; let duration = match frame_48k { 480 => 0u8, 960 => 1, 1920 => 2, _ => 3, }; let toc = ((base + duration) << 3) | (u8::from(self.channels == 2) << 2); if !self.vbr && len + 1 < max_data_bytes { let pad_amount = max_data_bytes - (len + 2); let buf = &mut self.silk_buf[..]; buf[0] = 1; let mut pos = 1; if pad_amount > 0 { buf[0] |= 0x40; let nb_255s = (pad_amount - 1) / 255; buf[1..1 + nb_255s].fill(255); buf[1 + nb_255s] = (pad_amount - 255 * nb_255s - 1) as u8; pos += nb_255s + 1; } buf[pos..pos + len].copy_from_slice(&self.range.data()[..len]); buf[pos + len..max_data_bytes - 1].fill(0); return Ok((toc | 3, Payload::Silk(max_data_bytes - 1))); } return Ok((toc, Payload::Range(len))); } if let Some(bandwidth) = hybrid_bw { let n = self.encode_hybrid(raw, pcm, frame_size, bandwidth, cap)?; let config = 12 + if bandwidth == Bandwidth::Full { 2u8 } else { 0 } + if frame_48k == 960 { 1 } else { 0 }; return Ok(( (config << 3) | (u8::from(self.channels == 2) << 2), Payload::Range(n), )); } self.last_silk = None; let (toc, frame_48k, end) = self.toc(frame_size)?; let n = self.encode_frame(pcm, frame_48k, end, cap)?; Ok((toc, Payload::Range(n))) } fn encode_multiframe( &mut self, pcm: &[f32], frame_size: usize, cap: usize, ) -> Result<(u8, &[u8])> { let count = frame_size * self.upsample / 960; if !matches!(count, 2 | 3) || frame_size * self.upsample != count * 960 { return Err(Error::unsupported( format!( "opus frame of {frame_size} samples at {} Hz", self.sample_rate ), "frames are 2.5, 5, 10, 20, 40 or 60 ms", )); } let sub = frame_size / count; let (mode, bandwidth) = (self.mode, self.bandwidth); self.mode = Some(if self.hybrid_choice(960).is_some() { Mode::Hybrid } else { Mode::Celt }); let per = cap.saturating_sub(1 + 2 * (count - 1)) / count; let mut frames: Vec> = Vec::with_capacity(count); let mut toc = 0u8; let mut result = Ok(()); for i in 0..count { let chunk = &pcm[i * sub * self.channels..(i + 1) * sub * self.channels]; match self.encode_toc_and_payload(chunk, sub, per) { Ok((t, payload)) => { frames.push(payload.to_vec()); if i == 0 { toc = t; self.bandwidth = Some(toc_bandwidth(t)); } } Err(e) => { result = Err(e); break; } } } self.mode = mode; self.bandwidth = bandwidth; result?; let mut pos = 0usize; self.silk_buf[pos] = 0x80 | count as u8; pos += 1; for frame in &frames[..count - 1] { Self::write_frame_len(&mut self.silk_buf[..], &mut pos, frame.len())?; } for frame in &frames { if pos + frame.len() > self.silk_buf.len() { return Err(Error::corrupt( "opus encode: multi-frame packet overflows its buffer", )); } self.silk_buf[pos..pos + frame.len()].copy_from_slice(frame); pos += frame.len(); } Ok(((toc & !3) | 3, &self.silk_buf[..pos])) } /// The TOC byte, the frame size in 48 kHz samples and the CELT end band /// for a frame of `frame_size` input samples per channel. fn toc(&self, frame_size: usize) -> Result<(u8, usize, usize)> { let frame_48k = frame_size * self.upsample; let fs_idx: u8 = match frame_48k { 120 => 0, 240 => 1, 480 => 2, 960 => 3, _ => { return Err(Error::unsupported( format!( "opus frame of {frame_size} samples at {} Hz", self.sample_rate ), "CELT frames are 2.5, 5, 10 or 20 ms", )); } }; let bandwidth = self.bandwidth.unwrap_or_else(|| { self.auto_bandwidth_at( self.equiv_rate_for(frame_48k, Some(Mode::Celt)), self.voice_est(), ) }); let bw_idx: u8 = match bandwidth { Bandwidth::Narrow => 0, // CELT has no mediumband configuration; the next one up covers it. Bandwidth::Medium | Bandwidth::Wide => 1, Bandwidth::SuperWide => 2, Bandwidth::Full => 3, }; let config = 16 + 4 * bw_idx + fs_idx; Ok(( (config << 3) | (u8::from(self.channels == 2) << 2), frame_48k, bandwidth.celt_end_band(), )) } /// Bandwidth from the bitrate — libopus's threshold walk, 20 ms default. /// Kept for the forced-mode paths and unit tests; the dispatch functions /// pass the actual frame's equiv rate to [`auto_bandwidth_at`]. fn auto_bandwidth(&self) -> Bandwidth { self.auto_bandwidth_at(self.equiv_rate(960), self.voice_est()) } /// The equivalent rate a frame is coded at, porting libopus /// `compute_equiv_rate` (`opus_encoder.c:1021`): the bitrate, minus the /// per-frame overhead for sub-20 ms frames, minus the CBR headroom, times /// the complexity multiplier. Loss is 0 and complexity ≥ 5, so the /// are both no-ops. fn equiv_rate(&self, frame_48k: usize) -> i32 { self.equiv_rate_for(frame_48k, None) } fn equiv_rate_for(&self, frame_48k: usize, mode: Option) -> i32 { let frame_rate = 48000 / frame_48k as i32; let mut equiv = self.bitrate as i32; if frame_rate > 50 { equiv -= (40 * self.channels as i32 + 20) * (frame_rate - 50); } if !self.vbr { equiv -= equiv / 12; } equiv = equiv * (90 + DEFAULT_COMPLEXITY) / 100; let loss = self.packet_loss_perc as i32; match mode { Some(Mode::Silk) | Some(Mode::Hybrid) => equiv -= equiv * loss / (6 * loss + 10), Some(Mode::Celt) => {} None => equiv -= equiv * loss / (12 * loss + 20), } equiv } fn fec_for(&self, frame_48k: usize) -> (bool, Option) { if !self.inband_fec || self.mode == Some(Mode::Celt) { return (false, None); } if self.mode.is_none() && !self.auto_silk(self.equiv_rate(frame_48k), self.voice_est()) { return (false, None); } let silk_equiv = self.equiv_rate_for(frame_48k, Some(Mode::Silk)); let ve = self.voice_est(); let bw = self .bandwidth .unwrap_or_else(|| self.auto_bandwidth_at(silk_equiv, ve)); let (fec, b) = self.decide_fec(bw, silk_equiv); (fec, (fec && b != bw).then_some(b)) } fn decide_fec(&self, bw: Bandwidth, rate: i32) -> (bool, Bandwidth) { const FEC_THRESHOLDS: [i32; 10] = [ 12000, 1000, 14000, 1000, 16000, 1000, 20000, 1000, 22000, 1000, ]; const BANDWIDTHS: [Bandwidth; 5] = [ Bandwidth::Narrow, Bandwidth::Medium, Bandwidth::Wide, Bandwidth::SuperWide, Bandwidth::Full, ]; let loss = self.packet_loss_perc as i32; if !self.inband_fec || loss == 0 { return (false, bw); } let mut b = BANDWIDTHS.iter().position(|&x| x == bw).unwrap_or(0); loop { let mut thres = FEC_THRESHOLDS[2 * b]; let hyst = FEC_THRESHOLDS[2 * b + 1]; if self.lbrr_coded { thres -= hyst; } else { thres += hyst; } thres = ((thres as i64 * (125 - loss.min(25)) as i64 * 655) >> 16) as i32; if rate > thres { return (true, BANDWIDTHS[b]); } else if loss <= 5 { return (false, bw); } else if b > 0 { b -= 1; } else { return (false, bw); } } } /// Voice activity estimate: VoIP → 115, Audio and LowDelay → 48 /// (`opus_encoder.c` `tonality_analysis` proxy — no analysis is modelled, /// so the application alone decides). fn voice_est(&self) -> i32 { match self.application { Application::Voip => 115, _ => 48, } } /// Whether the auto mode is SILK: `equiv` below the voice/music-blended /// mode threshold (`opus_encoder.c` ~1900). LowDelay is always CELT. /// VoIP gets the `+8000` hysteresis/voice bonus libopus applies. fn auto_silk(&self, equiv: i32, ve: i32) -> bool { if self.application == Application::LowDelay { return false; } if self.inband_fec && self.packet_loss_perc as i32 > (128 - ve) >> 4 { return true; } let threshold = MODE_THRESHOLD_MUSIC + ((ve * ve * (MODE_THRESHOLD_VOICE - MODE_THRESHOLD_MUSIC)) >> 14); let threshold = if self.application == Application::Voip { threshold + 8000 } else { threshold }; equiv < threshold } /// Bandwidth from the equivalent rate, porting libopus's `decide_bandwidth` /// walk (`opus_encoder.c` ~1660). The voice and music threshold tables are /// blended by `ve²`; the walk starts at Full and steps down until the equiv /// rate sustains the current bandwidth. The input's own Nyquist clamps the /// result — coding above it would code the images the zero-stuffing put /// there. fn auto_bandwidth_at(&self, equiv: i32, ve: i32) -> Bandwidth { let (voice, music) = if self.channels == 2 { (&STEREO_VOICE_BW, &STEREO_MUSIC_BW) } else { (&MONO_VOICE_BW, &MONO_MUSIC_BW) }; let ve2 = ve * ve; // Pair i is the boundary between bandwidth i and i+1: // 0: NB↔MB, 1: MB↔WB, 2: WB↔SWB, 3: SWB↔FB. let thresh = |i: usize| music[2 * i] + ((ve2 * (voice[2 * i] - music[2 * i])) >> 14); const BWS: [Bandwidth; 5] = [ Bandwidth::Narrow, Bandwidth::Medium, Bandwidth::Wide, Bandwidth::SuperWide, Bandwidth::Full, ]; let mut idx = 4; // Full while idx > 0 && equiv < thresh(idx - 1) { idx -= 1; } let ceiling = match self.sample_rate { 48000 => Bandwidth::Full, 24000 => Bandwidth::SuperWide, 16000 => Bandwidth::Wide, 12000 => Bandwidth::Medium, _ => Bandwidth::Narrow, }; let bw = BWS[idx].min(ceiling); match self.detected_bandwidth(equiv, !self.auto_silk(equiv, ve)) { Some(d) => bw.min(d), None => bw, } } /// libopus `opus_encoder.c:1278-1305`: the tonality analysis's own /// bandwidth estimate as an Opus bandwidth, raised by the conservative /// floor of `opus_encoder.c:1652-1674` (which depends on `equiv_rate` per /// channel and on whether the frame is CELT-only) before it is allowed to /// lower the coded bandwidth. `None` when the analysis did not run, which /// is libopus's `st->detected_bandwidth == 0`. /// /// Only the caller's automatic path consults this — libopus guards the /// clamp with `st->user_bandwidth == OPUS_AUTO`, which is exactly the /// `self.bandwidth.is_none()` branch that reaches `auto_bandwidth_at`. fn detected_bandwidth(&self, equiv: i32, celt_only: bool) -> Option { if !self.bw_detect || !self.info.valid { return None; } let detected = match self.info.bandwidth { i32::MIN..=12 => Bandwidth::Narrow, 13..=14 => Bandwidth::Medium, 15..=16 => Bandwidth::Wide, 17..=18 => Bandwidth::SuperWide, _ => Bandwidth::Full, }; let ch = self.channels as i32; let floor = if celt_only && equiv <= 18000 * ch { Bandwidth::Narrow } else if celt_only && equiv <= 24000 * ch { Bandwidth::Medium } else if equiv <= 30000 * ch { Bandwidth::Wide } else if equiv <= 44000 * ch { Bandwidth::SuperWide } else { Bandwidth::Full }; Some(detected.max(floor)) } /// Encodes one frame — `frame_size` samples per channel of interleaved /// `f32` at the input rate, 2.5, 5, 10 or 20 ms of it — as a code-0 Opus /// packet in `out`, returning the packet length. pub fn encode_float( &mut self, pcm: &[f32], frame_size: usize, out: &mut [u8], ) -> Result { match self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1)) { Err(e) => Err(e), Ok((toc, payload)) => { let n = payload.len(); let count = payload.first().copied().unwrap_or(0); if out.len() < 1 + n { Err(Error::corrupt(format!( "opus encode: packet needs {} bytes, buffer holds {}", 1 + n, out.len() ))) } else { out[0] = toc; out[1..1 + n].copy_from_slice(payload); if self.dtx_frame(pcm, frame_size) { self.final_range = 0; let (bytes, len) = dtx_packet(toc, count, false); if out.len() < len { Err(Error::corrupt("opus encode: DTX packet buffer too small")) } else { out[..len].copy_from_slice(&bytes[..len]); Ok(len) } } else { Ok(1 + n) } } } } } /// [`Encoder::encode_float`] from 16-bit samples. pub fn encode(&mut self, pcm: &[i16], frame_size: usize, out: &mut [u8]) -> Result { let float: Vec = pcm.iter().map(|&v| v as f32 * (1.0 / 32768.0)).collect(); self.encode_float(&float, frame_size, out) } /// [`Encoder::encode_float`] in the self-delimited framing of RFC 6716 /// Appendix B: TOC, an explicit frame length, then the frame. This is /// what every stream but the last uses inside a multistream packet. pub fn encode_self_delimited( &mut self, pcm: &[f32], frame_size: usize, out: &mut [u8], ) -> Result { match self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3)) { Err(e) => Err(e), Ok((toc, payload)) => { let count = payload.first().copied().unwrap_or(0); let (head, last) = if toc & 3 == 3 { let count = usize::from(payload[0] & 0x3F); let mut pos = 1; let mut sum = 0; for _ in 1..count { let b0 = usize::from(payload[pos]); let (len, used) = if b0 < 252 { (b0, 1) } else { (b0 + 4 * usize::from(payload[pos + 1]), 2) }; sum += len; pos += used; } (pos, payload.len() - pos - sum) } else { (0, payload.len()) }; let mut len = [0u8; 2]; let mut len_bytes = 0; let r = Self::write_frame_len(&mut len, &mut len_bytes, last); let total = 1 + len_bytes + payload.len(); match r { Err(e) => Err(e), Ok(()) if out.len() < total => Err(Error::corrupt(format!( "opus encode: self-delimited packet needs {total} bytes, buffer holds {}", out.len() ))), Ok(()) => { out[0] = toc; out[1..1 + head].copy_from_slice(&payload[..head]); out[1 + head..1 + head + len_bytes].copy_from_slice(&len[..len_bytes]); out[1 + head + len_bytes..total].copy_from_slice(&payload[head..]); if self.dtx_frame(pcm, frame_size) { self.final_range = 0; let (bytes, len) = dtx_packet(toc, count, true); if out.len() < len { Err(Error::corrupt("opus encode: DTX packet buffer too small")) } else { out[..len].copy_from_slice(&bytes[..len]); Ok(len) } } else { Ok(total) } } } } } } /// One hybrid frame (10 or 20 ms, mono or stereo, `bandwidth` SWB or FB) /// into the internal range coder, returning its byte length: the SILK /// layer's symbols (WB, 16 kHz internal), the no-redundancy flag under the decoder's /// exact presence rule, then the CELT layer from band 17 in the same /// coder. CBR: the packet is the bitrate's size unless SILK alone needs /// more, in which case CELT keeps [`HYBRID_CELT_MIN_BYTES`] on top. fn encode_hybrid( &mut self, raw: &[f32], pcm: &[f32], frame_size: usize, bandwidth: Bandwidth, cap: usize, ) -> Result { let cap = cap.min(MAX_FRAME_BYTES); let frame_48k = frame_size * self.upsample; let budget = ((self.bitrate as u64 * frame_48k as u64 + 4 * 48000) / (8 * 48000)) as usize; let budget = budget.saturating_sub(1).clamp(2, cap); // D2b: under CBR the SILK layer leaves CELT its minimum, plus two bytes // for the range coder's conservative `tell()` the hybrid split reads. if cap < HYBRID_CELT_MIN_BYTES + 2 { return Err(Error::corrupt( "opus encode: output buffer smaller than the minimum hybrid packet", )); } self.range.reset(cap); let max_data_bytes = if self.vbr { cap } else { budget } + 1; let f = self.silk_frame(max_data_bytes, 16, true, bandwidth == Bandwidth::SuperWide); let activity = self.silk_activity(raw, frame_size); let mut range = std::mem::take(&mut self.range); self.silk_layer() .encode(pcm, frame_size, &f, activity, &mut range); self.range = range; self.last_silk = Some(16); let silk_bytes = (self.range.tell() as usize).div_ceil(8); let budget = budget.max(silk_bytes + HYBRID_CELT_MIN_BYTES).min(cap); self.range.shrink(budget); // Redundancy flag: present under exactly the decoder's condition. if self.range.tell() as usize + 17 + 20 <= 8 * budget { self.range.enc_bit_logp(false, 12); } self.celt.set_align_input(true); let n = self.celt.encode( &mut self.range, pcm, frame_48k, 17, bandwidth.celt_end_band(), 0, &self.info, )?; self.celt.set_align_input(self.align_input); self.final_range = self.range.range(); Ok(n) } /// Encodes the CELT frame into the internal range coder and returns its /// byte length. `frame_size` is in 48 kHz samples, `end` is the last coded /// band, and `cap` bounds the frame (the caller's buffer minus headers). fn encode_frame( &mut self, pcm: &[f32], frame_size: usize, end: usize, cap: usize, ) -> Result { let cap = cap.min(MAX_FRAME_BYTES); if cap < 2 { return Err(Error::corrupt( "opus encode: output buffer smaller than the minimum packet", )); } // One byte per packet goes to the TOC; the CELT layer sees the rest. let toc_bps = 8 * 48000 / frame_size as u32; let (budget, vbr_rate) = if self.vbr { (cap, self.bitrate.saturating_sub(toc_bps).max(500)) } else { let b = ((self.bitrate as u64 * frame_size as u64 + 4 * 48000) / (8 * 48000)) as usize; (b.saturating_sub(1).clamp(2, cap), 0) }; self.range.reset(budget); let n = self.celt.encode( &mut self.range, pcm, frame_size, 0, end, vbr_rate, &self.info, )?; self.final_range = self.range.range(); Ok(n) } } #[cfg(test)] mod tests { use super::*; /// The detected-bandwidth clamp (`opus_encoder.c:1652-1674`): a band-limited /// analysis result lowers the coded bandwidth, but never below the /// rate-dependent floor, and never when the analysis did not run. #[test] fn detected_bandwidth_lowers_the_coded_bandwidth_but_not_below_its_floor() { let mut e = Encoder::new(48000, 2, Application::Audio).unwrap(); e.set_vbr_constrained(true); // the library gate's setting e.set_bitrate(64_000); // Analysis off (the default): fullband, whatever the estimate says. e.info.valid = true; e.info.bandwidth = 15; // wideband assert_eq!(e.auto_bandwidth(), Bandwidth::Full); // On: 64 kbps stereo is under 44000*2, so the floor is superwide — // a wideband estimate is raised to it, not honoured as wideband. e.bw_detect = true; assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide); // Above the floor the estimate passes through unchanged. e.info.bandwidth = 20; assert_eq!(e.auto_bandwidth(), Bandwidth::Full); // 96 kbps stereo is above 44000*2: the floor is fullband, so the // clamp is inert there — which is why it cannot move the @96 rows. e.info.bandwidth = 15; e.set_bitrate(96_000); assert_eq!(e.auto_bandwidth(), Bandwidth::Full); // An invalid analysis is libopus's `detected_bandwidth == 0`. e.set_bitrate(64_000); e.info.valid = false; assert_eq!(e.auto_bandwidth(), Bandwidth::Full); } /// The private half of the bandwidth decision: the thresholds themselves, /// which the TOC config only reports. #[test] fn bandwidth_follows_the_bitrate_the_application_and_the_input_rate() { let mut e = Encoder::new(48000, 1, Application::Audio).unwrap(); e.set_bitrate(64000); assert_eq!(e.auto_bandwidth(), Bandwidth::Full); // libopus MONO_MUSIC_BW blended at voice_est=48 (analysis off): // SWB<->FB boundary 12281, equiv(16k) = 14520 -> Full. e.set_bitrate(16000); assert_eq!(e.auto_bandwidth(), Bandwidth::Full); e.set_bitrate(10000); assert_eq!(e.auto_bandwidth(), Bandwidth::Wide); // equiv(8k) = 7260 < 9000 (NB<->MB boundary) -> Narrow. e.set_bitrate(8000); assert_eq!(e.auto_bandwidth(), Bandwidth::Narrow); // VoIP (voice_est=127): SWB<->FB boundary 13616, so 16k speech is // Full -> hybrid, matching libopus 1.6 on real speech // (lanes/opus-silk-r2.sweep.txt: 16k-NB row, ref_mode=Hybrid-FB). let mut v = Encoder::new(48000, 1, Application::Voip).unwrap(); v.set_bitrate(16000); assert_eq!(v.auto_bandwidth(), Bandwidth::Full); // The input's own Nyquist bounds it whatever the rate says. let mut e = Encoder::new(24000, 2, Application::Audio).unwrap(); e.set_bitrate(256_000); assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide); assert_eq!( e.look_ahead(960), (CELT_OVERLAP_48K + CELT_DELAY_COMP_48K) / 2 ); } #[test] fn look_ahead_is_libopus_delay_in_every_mode() { let full = CELT_OVERLAP_48K + CELT_DELAY_COMP_48K; let mut e = Encoder::new(48000, 1, Application::Voip).unwrap(); for bps in [8000, 16000, 32000, 64000] { e.set_bitrate(bps); for fs in [240, 480, 960] { assert_eq!(e.look_ahead(fs), full, "{bps} {fs}"); } } let e = Encoder::new(48000, 1, Application::LowDelay).unwrap(); assert_eq!(e.look_ahead(960), CELT_OVERLAP_48K); } #[test] fn voip_auto_mode_is_monotonic_per_channel() { for channels in [1usize, 2] { let mut e = Encoder::new(48000, channels, Application::Voip).unwrap(); let mut last = 0u8; for per_channel in 500..=45_000u32 { e.set_bitrate(per_channel * channels as u32); let class = if e.silk_choice(960).is_some() { 0 } else if e.hybrid_choice(960).is_some() { 1 } else { 2 }; assert!( class >= last, "{channels}ch {per_channel} bps/channel regressed from {last} to {class}" ); last = class; } } } }