//! 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_flp::enc::{BITRATE_MAX, CeltEnc}; use crate::celt_flp::tables::WINDOW120; use crate::packet::{Bandwidth, Mode}; use crate::range::RangeEncoder; use crate::silk_flp::opus::{ InputFilter, SilkFrame, SilkLayer, bitrate_to_bits, bits_to_bitrate, hp_min_smth1_q15, silk_rate_for_hybrid, }; /// 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; const MAX_REDUNDANCY_BYTES: usize = 257; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Prefill { Off, Reset, Keep, } /// One MDCT overlap: the CELT layer's delay without libopus's 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; const MODE_THRESHOLD_VOICE_STEREO: i32 = 44000; const STEREO_THRESHOLD_VOICE: i32 = 19000; const STEREO_THRESHOLD_MUSIC: i32 = 17000; const EPSILON: f32 = 1e-15; const BANDWIDTHS: [Bandwidth; 5] = [ Bandwidth::Narrow, Bandwidth::Medium, Bandwidth::Wide, Bandwidth::SuperWide, Bandwidth::Full, ]; #[derive(Clone, Copy, Debug)] #[allow(dead_code)] struct Decision { mode: Mode, bandwidth: Bandwidth, stream_channels: usize, equiv_rate: i32, redundancy: bool, redundancy_bytes: usize, celt_to_silk: bool, to_celt: bool, prefill: Prefill, to_mono: bool, toc_only: Option, } #[derive(Clone, Copy, Debug, Default)] struct StereoWidth { xx: f32, xy: f32, yy: f32, smoothed: f32, max_follower: f32, } fn bw_index(bw: Bandwidth) -> usize { BANDWIDTHS.iter().position(|&x| x == bw).unwrap_or(0) } fn detected_bandwidth(analysis: i32) -> Bandwidth { match analysis { i32::MIN..=12 => Bandwidth::Narrow, 13..=14 => Bandwidth::Medium, 15..=16 => Bandwidth::Wide, 17..=18 => Bandwidth::SuperWide, _ => Bandwidth::Full, } } fn compute_redundancy_bytes( max_data_bytes: i32, bitrate_bps: i32, frame_rate: i32, channels: i32, ) -> usize { let base_bits = 40 * channels + 20; let rate = 3 * (bitrate_bps + base_bits * (200 - frame_rate)) / 2; let mut bytes = rate / 1600; let available_bits = max_data_bytes * 8 - 2 * base_bits; let cap = (available_bits * 240 / (240 + 48000 / frame_rate) + base_bits) / 8; bytes = bytes.min(cap); if bytes > 4 + 8 * channels { bytes.min(MAX_REDUNDANCY_BYTES as i32) as usize } else { 0 } } fn compute_equiv_rate( bitrate: i32, channels: i32, frame_rate: i32, vbr: bool, mode: Option, loss: i32, ) -> i32 { let mut equiv = bitrate; if frame_rate > 50 { equiv -= (40 * channels + 20) * (frame_rate - 50); } if !vbr { equiv -= equiv / 12; } equiv = equiv * (90 + DEFAULT_COMPLEXITY) / 100; 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 update_stereo_width(mem: &mut StereoWidth, pcm: &[f32], frame_size: usize, fs: u32) -> f32 { let frame_rate = (fs as usize / frame_size) as i32; let short_alpha = 25.0 / frame_rate.max(50) as f32; let (mut xx, mut xy, mut yy) = (0.0f32, 0.0f32, 0.0f32); for g in (0..(frame_size & !3)).step_by(4) { let (mut pxx, mut pxy, mut pyy) = (0.0f32, 0.0f32, 0.0f32); for i in g..g + 4 { let (x, y) = (pcm[2 * i], pcm[2 * i + 1]); pxx += x * x; pxy += x * y; pyy += y * y; } xx += pxx; xy += pxy; yy += pyy; } if xx.is_nan() || yy.is_nan() || xx >= 1e9 || yy >= 1e9 { xx = 0.0; xy = 0.0; yy = 0.0; } mem.xx = (mem.xx + short_alpha * (xx - mem.xx)).max(0.0); mem.xy = ((1.0 - short_alpha) * mem.xy + short_alpha * xy).max(0.0); mem.yy = (mem.yy + short_alpha * (yy - mem.yy)).max(0.0); if mem.xx.max(mem.yy) > 8e-4 { let frame_rate = frame_rate as f32; let sqrt_xx = mem.xx.sqrt(); let sqrt_yy = mem.yy.sqrt(); let qrrt_xx = sqrt_xx.sqrt(); let qrrt_yy = sqrt_yy.sqrt(); mem.xy = mem.xy.min(sqrt_xx * sqrt_yy); let corr = mem.xy / (EPSILON + sqrt_xx * sqrt_yy); let ldiff = (qrrt_xx - qrrt_yy).abs() / (EPSILON + qrrt_xx + qrrt_yy); let width = (1.0 - corr * corr).sqrt().min(1.0) * ldiff; mem.smoothed += (width - mem.smoothed) / frame_rate; mem.max_follower = (mem.max_follower - 0.02 / frame_rate).max(mem.smoothed); } (20.0 * mem.max_follower).min(1.0) } /// 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; /// 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 gen_toc(mode: Mode, frame_rate: usize, bw: Bandwidth, channels: usize) -> u8 { let mut period = 0; let mut rate = frame_rate; while rate < 400 { rate <<= 1; period += 1; } let bw = bw_index(bw) as u8; let toc = match mode { Mode::Silk => (bw << 5) | ((period - 2) << 3), Mode::Celt => 0x80 | (bw.saturating_sub(1) << 5) | (period << 3), Mode::Hybrid => 0x60 | ((bw - 3) << 4) | ((period - 2) << 3), }; toc | (u8::from(channels == 2) << 2) } 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) } fn encoder_buffer(sample_rate: u32) -> usize { sample_rate as usize / 100 } /// One elementary Opus encoder: mono or stereo. #[derive(Clone, Debug)] pub struct Encoder { celt: CeltEnc, bitrate_bps: i32, lsb_depth: i32, 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. silk: Option>, /// Scratch space for the SILK packet payload, sized once so the steady-state /// loop 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]>, filter: InputFilter, /// Scratch space for the filter's output, sized once. hp_buf: Vec, delay_buffer: Vec, pcm_buf: Vec, history: Vec, redundant: RangeEncoder, /// 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, analysis_on: bool, inband_fec: bool, packet_loss_perc: u8, lbrr_coded: bool, silk_bw_switch: bool, use_dtx: bool, nb_no_activity_ms_q1: i32, peak_signal_energy: f32, prev_mode: Option, first: bool, auto_bandwidth: Bandwidth, coded_bandwidth: Bandwidth, stream_channels: usize, prev_channels: usize, force_mono: bool, to_mono: bool, hybrid_stereo_width_q14: i32, stereo_width_q14: i32, voice_ratio: i32, width_mem: StereoWidth, nonfinal: bool, prev_hb_gain: f32, } /// 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, } } fn gain_fade( buf: &mut [f32], g1: f32, g2: f32, window: &[f32], frame_size: usize, channels: usize, fs: u32, ) { let inc = (48000 / fs as usize).max(1); let overlap = CELT_OVERLAP_48K / inc; for i in 0..overlap { let w = window[i * inc]; let w = w * w; let g = w * g2 + (1.0 - w) * g1; for c in 0..channels { buf[i * channels + c] *= g; } } for i in overlap..frame_size { for c in 0..channels { buf[i * channels + c] *= g2; } } } fn stereo_fade(buf: &mut [f32], g1: f32, g2: f32, window: &[f32], frame_size: usize, fs: u32) { let inc = (48000 / fs as usize).max(1); let overlap = CELT_OVERLAP_48K / inc; let (a, b) = (1.0 - g1, 1.0 - g2); for i in 0..overlap { let w = window[i * inc]; let w = w * w; let g = w * b + (1.0 - w) * a; let diff = 0.5 * (buf[2 * i] - buf[2 * i + 1]) * g; buf[2 * i] -= diff; buf[2 * i + 1] += diff; } for i in overlap..frame_size { let diff = 0.5 * (buf[2 * i] - buf[2 * i + 1]) * b; buf[2 * i] -= diff; buf[2 * i + 1] += diff; } } fn stereo_width_for_rate(equiv: i32) -> i32 { if equiv > 32000 { 16384 } else if equiv < 16000 { 0 } else { 16384 - 2048 * (32000 - equiv) / (equiv - 14000) } } 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: CeltEnc::new(channels, upsample), bitrate_bps: 0, lsb_depth: 24, 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]), filter: InputFilter::new(), hp_buf: Vec::new(), delay_buffer: vec![0.0; encoder_buffer(sample_rate) * channels], pcm_buf: Vec::new(), history: Vec::new(), redundant: RangeEncoder::new(), analysis: TonalityAnalysis::new(sample_rate), info: AnalysisInfo::default(), analysis_on: true, inband_fec: false, packet_loss_perc: 0, lbrr_coded: false, silk_bw_switch: false, use_dtx: false, nb_no_activity_ms_q1: 0, peak_signal_energy: 0.0, prev_mode: None, first: true, auto_bandwidth: Bandwidth::Full, coded_bandwidth: Bandwidth::Full, stream_channels: channels, prev_channels: 0, force_mono: false, to_mono: false, hybrid_stereo_width_q14: 1 << 14, stereo_width_q14: 0, voice_ratio: -1, width_mem: StereoWidth::default(), nonfinal: false, prev_hb_gain: 1.0, }; enc.celt.set_complexity(DEFAULT_COMPLEXITY); Ok(enc) } /// Turns libopus's tonality analysis on (the default) or off. Off saves /// about a quarter of the encoder's time but drops what it feeds: speech/music /// detection, bandwidth detection, and CELT's tonality-driven allocation. pub fn set_analysis(&mut self, on: bool) { self.analysis_on = on; } /// Overrides the automatic SILK/Hybrid/CELT choice made 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 { 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.application != Application::LowDelay { CELT_DELAY_COMP_48K } else { 0 } } /// 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); self.celt.set_loss_rate(i32::from(self.packet_loss_perc)); } /// 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() <= self.silence_threshold()) { 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() <= self.silence_threshold()) { 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() <= self.silence_threshold()); 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 } /// 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.delay_buffer.fill(0.0); self.final_range = 0; self.analysis.reset(); self.info = AnalysisInfo::default(); self.lbrr_coded = false; self.silk_bw_switch = false; self.prev_mode = None; self.first = true; self.auto_bandwidth = Bandwidth::Full; self.coded_bandwidth = Bandwidth::Full; self.stream_channels = self.channels; self.prev_channels = 0; self.force_mono = false; self.to_mono = false; self.hybrid_stereo_width_q14 = 1 << 14; self.stereo_width_q14 = 0; self.voice_ratio = -1; self.width_mem = StereoWidth::default(); self.nonfinal = false; self.prev_hb_gain = 1.0; self.nb_no_activity_ms_q1 = 0; self.peak_signal_energy = 0.0; } 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, d: Decision, max_data_bytes: usize, internal_khz: usize, hybrid: bool, swb: bool, ) -> SilkFrame { let reserved = if d.redundancy { d.redundancy_bytes as i32 * 8 + 1 + if hybrid { 20 } else { 0 } } else { 0 }; SilkFrame { bitrate: self.bitrate as i32, max_data_bytes, redundancy_bytes: if d.redundancy { d.redundancy_bytes as i32 } else { 0 }, reserved_bits: reserved, vbr: self.vbr, hybrid, swb, internal_khz: internal_khz as i32, stream_channels: d.stream_channels, to_mono: d.to_mono, fec: self.inband_fec, lbrr_coded: self.lbrr_coded, loss_perc: i32::from(self.packet_loss_perc), complexity: DEFAULT_COMPLEXITY, } } fn silk_layer(&mut self) -> &mut SilkLayer { let (fs, ch, nonfinal) = (self.sample_rate, self.channels, self.nonfinal); let silk = self .silk .get_or_insert_with(|| Box::new(SilkLayer::new(fs, ch))); silk.set_nonfinal(nonfinal); 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, self_delimited: bool, ) -> Result<(u8, &[u8])> { let cursor = self.analysis.cursor(); self.info = if self.analysis_on { self.analysis .run(pcm, frame_size, self.channels, self.lsb_depth) } else { AnalysisInfo::default() }; self.track_peak(pcm, frame_size); let d = self.decide(pcm, frame_size, cap + 1); if let Some(max_data) = d.toc_only { let (toc, n) = self.toc_only_packet(d, frame_size, cap + 1, max_data)?; return Ok((toc, &self.silk_buf[..n])); } if d.prefill == Prefill::Reset { self.silk_layer().reset(); } let encoded = if frame_size * self.upsample > 960 && d.mode != Mode::Silk { self.encode_multiframe(pcm, frame_size, cap, d, cursor, self_delimited) } else { self.encode_frame_decided(pcm, frame_size, cap, d) }; let (toc, payload) = encoded?; self.first = false; Ok((toc, self.payload_bytes(payload))) } fn toc_only_packet( &mut self, d: Decision, frame_size: usize, out_bytes: usize, max_data: usize, ) -> Result<(u8, usize)> { let mut frame_rate = 48000 / (frame_size * self.upsample); let mut mode = d.mode; let mut bw = d.bandwidth; let mut code = 0u8; let mut count = 1; if frame_rate > 100 { mode = Mode::Celt; } if frame_rate == 25 && mode != Mode::Silk { frame_rate = 50; code = 1; count = 2; } if frame_rate <= 16 { if out_bytes == 1 || (mode == Mode::Silk && frame_rate != 10) { mode = Mode::Silk; code = u8::from(frame_rate <= 12); count = if code == 1 { 2 } else { 1 }; frame_rate = if frame_rate == 12 { 25 } else { 16 }; } else { count = 50 / frame_rate; frame_rate = 50; code = 3; } } bw = match mode { Mode::Silk if bw > Bandwidth::Wide => Bandwidth::Wide, Mode::Celt if bw == Bandwidth::Medium => Bandwidth::Narrow, Mode::Hybrid if bw <= Bandwidth::SuperWide => Bandwidth::SuperWide, _ => bw, }; let toc = gen_toc(mode, frame_rate, bw, d.stream_channels); let frames = vec![Vec::new(); count]; if !self.vbr && max_data > 1 + usize::from(code >= 2) { let (_, n) = self.pack_frames(&frames, max_data, true)?; return Ok((toc | 3, n)); } if code == 3 { self.silk_buf[0] = count as u8; return Ok((toc | 3, 1)); } Ok((toc | code, 0)) } fn encode_frame_decided( &mut self, pcm: &[f32], frame_size: usize, cap: usize, mut d: Decision, ) -> Result<(u8, Payload)> { if std::mem::take(&mut self.silk_bw_switch) { d.redundancy = true; d.celt_to_silk = true; d.prefill = Prefill::Keep; } if d.mode == Mode::Celt { d.redundancy = false; } d.redundancy_bytes = 0; if d.redundancy { let max_data = self.frame_max_data(frame_size * self.upsample, cap); d.redundancy_bytes = self.redundancy_bytes(max_data, frame_size, d.stream_channels); d.redundancy = d.redundancy_bytes != 0; } let mut buf = std::mem::take(&mut self.hp_buf); self.filter_input(pcm, frame_size, d.mode == Mode::Celt, &mut buf); let mut delayed = std::mem::take(&mut self.pcm_buf); self.delay_input(&buf, frame_size, &mut delayed); if d.prefill != Prefill::Off && d.mode != Mode::Celt { self.fade_prefill_history(); } self.history.clear(); self.history.extend_from_slice(&self.delay_buffer); self.update_delay(&delayed, frame_size); let r = self.encode_mode(pcm, &buf, &mut delayed, frame_size, cap, d); self.hp_buf = buf; self.pcm_buf = delayed; self.prev_mode = Some(if d.to_celt { Mode::Celt } else { d.mode }); self.prev_channels = d.stream_channels; r } fn payload_bytes(&self, payload: Payload) -> &[u8] { 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 { self.filter.dc_reject(&pcm[..n], out, self.channels, fs); } } fn delay_input(&self, frame: &[f32], frame_size: usize, out: &mut Vec) { let ch = self.channels; let start = (encoder_buffer(self.sample_rate) - self.total_buffer()) * ch; out.clear(); out.extend_from_slice(&self.delay_buffer[start..]); out.extend_from_slice(&frame[..frame_size * ch]); } fn update_delay(&mut self, delayed: &[f32], frame_size: usize) { let ch = self.channels; let eb = encoder_buffer(self.sample_rate) * ch; let tb = self.total_buffer() * ch; let fb = frame_size * ch; if eb > fb + tb { let keep = eb - fb - tb; self.delay_buffer.copy_within(fb..fb + keep, 0); self.delay_buffer[keep..].copy_from_slice(delayed); } else { self.delay_buffer.copy_from_slice(&delayed[fb + tb - eb..]); } } fn stereo_fade_step(&mut self, delayed: &mut [f32], frame_size: usize, d: Decision) { if d.mode != Mode::Hybrid || d.stream_channels == 1 { self.stereo_width_q14 = stereo_width_for_rate(d.equiv_rate); } if self.channels == 2 && (self.hybrid_stereo_width_q14 < 16384 || self.stereo_width_q14 < 16384) { let g1 = self.hybrid_stereo_width_q14 as f32 / 16384.0; let g2 = self.stereo_width_q14 as f32 / 16384.0; stereo_fade(delayed, g1, g2, &WINDOW120, frame_size, self.sample_rate); self.hybrid_stereo_width_q14 = self.stereo_width_q14; } } fn fade_celt_input(&mut self, delayed: &mut [f32], frame_size: usize, hb_gain: f32) { let prev = self.prev_hb_gain; if prev < 1.0 || hb_gain < 1.0 { gain_fade( delayed, prev, hb_gain, &WINDOW120, frame_size, self.channels, self.sample_rate, ); } self.prev_hb_gain = hb_gain; } fn frame_max_data(&self, frame_48k: usize, cap: usize) -> usize { self.packet_budget(frame_48k, cap) .unwrap_or(cap) .min(MAX_FRAME_BYTES) + 1 } fn redundancy_bytes(&self, max_data: usize, frame_size: usize, channels: usize) -> usize { let fs = self.sample_rate as i32; let bitrate = if self.vbr { self.bitrate as i32 } else { bits_to_bitrate(max_data as i32 * 8, fs, frame_size as i32) }; compute_redundancy_bytes( max_data as i32, bitrate, fs / frame_size as i32, channels as i32, ) } fn switch_ready(&mut self, d: &mut Decision, max_data: usize, frame_size: usize) { d.redundancy_bytes = self.redundancy_bytes(max_data, frame_size, d.stream_channels); d.redundancy = d.redundancy_bytes != 0; d.celt_to_silk = false; self.silk_bw_switch = true; } fn fade_prefill_history(&mut self) { let (fs, ch) = (self.sample_rate, self.channels); let n = fs as usize / 400; let off = (encoder_buffer(fs) - self.total_buffer() - n) * ch; gain_fade( &mut self.delay_buffer[off..], 0.0, 1.0, &WINDOW120, n, ch, fs, ); self.delay_buffer[..off].fill(0.0); } fn silk_prefill(&mut self, f: &SilkFrame, frame_size: usize, activity: i32, prefill: Prefill) { let flag = if prefill == Prefill::Keep { 2 } else { 1 }; let history = std::mem::take(&mut self.history); let mut dummy = std::mem::take(&mut self.redundant); self.silk_layer() .prefill(&history, frame_size, f, activity, flag, &mut dummy); self.redundant = dummy; self.history = history; } fn celt_setup(&mut self, mode: Mode, end: usize, stream_channels: usize) { self.celt.set_lsb_depth(self.lsb_depth); self.celt.set_end_band(end); self.celt.set_stream_channels(stream_channels); self.celt.set_bitrate(BITRATE_MAX); if mode != Mode::Silk { self.celt.set_prediction(2); } } fn celt_own(&mut self, pcm: &[f32], frame_size: usize, bytes: usize) -> u32 { let mut enc = std::mem::take(&mut self.redundant); self.celt.encode(pcm, frame_size, bytes, &mut enc, true); self.redundant = enc; self.celt.final_range() } fn celt_to_silk_redundancy(&mut self, delayed: &[f32], bytes: usize, out: &mut [u8]) -> u32 { let n2 = self.sample_rate as usize / 200; self.celt.set_start_band(0); self.celt.set_vbr(false); self.celt.set_bitrate(BITRATE_MAX); let rng = self.celt_own(&delayed[..self.channels * n2], n2, bytes); out[..bytes].copy_from_slice(&self.redundant.data()[..bytes]); self.celt.reset(); rng } fn celt_main( &mut self, mode: Mode, delayed: &[f32], frame_size: usize, nb_compr: usize, celt_rate: i32, ) -> usize { self.celt.set_vbr(self.vbr); if self.vbr { if mode == Mode::Hybrid { self.celt.set_bitrate(celt_rate.max(501)); self.celt.set_vbr_constraint(false); } else { self.celt.set_vbr_constraint(true); self.celt.set_bitrate(self.bitrate_bps); } } if self.prev_mode.is_some_and(|p| p != mode) { let (fs, ch) = (self.sample_rate as usize, self.channels); let n = fs / 400; let off = (encoder_buffer(fs as u32) - self.total_buffer()) * ch - n * ch; let mut tmp = [0.0f32; 2 * 120]; tmp[..n * ch].copy_from_slice(&self.history[off..off + n * ch]); self.celt.reset(); self.celt_own(&tmp[..n * ch], n, 2); self.celt.set_prediction(0); } let mut ret = nb_compr; if self.range.tell() as usize <= 8 * nb_compr { let mut range = std::mem::take(&mut self.range); let r = self .celt .encode(delayed, frame_size, nb_compr, &mut range, false); self.range = range; ret = r.max(0) as usize; } self.final_range = self.celt.final_range(); ret } fn silk_to_celt_redundancy( &mut self, delayed: &[f32], frame_size: usize, bytes: usize, out: &mut [u8], ) -> u32 { let ch = self.channels; let n2 = self.sample_rate as usize / 200; let n4 = self.sample_rate as usize / 400; self.celt.reset(); self.celt.set_start_band(0); self.celt.set_prediction(0); self.celt.set_vbr(false); self.celt.set_bitrate(BITRATE_MAX); let tail = &delayed[ch * (frame_size - n2 - n4)..ch * frame_size]; self.celt_own(&tail[..ch * n4], n4, 2); let rng = self.celt_own(&tail[ch * n4..], n2, bytes); out[..bytes].copy_from_slice(&self.redundant.data()[..bytes]); rng } fn code_redundancy_flags(&mut self, d: &mut Decision, max_data: usize, hybrid: bool) { let max_payload = max_data - 1; if self.range.tell() as usize + 17 + 20 * usize::from(hybrid) <= 8 * max_payload { if hybrid { self.range.enc_bit_logp(d.redundancy, 12); } if d.redundancy { self.range.enc_bit_logp(d.celt_to_silk, 1); let overhead = if hybrid { 8 + 3 + 7 } else { 7 }; let used = (self.range.tell() as usize + overhead) >> 3; let max_red = max_payload as i64 - used as i64; let bytes = (d.redundancy_bytes as i64) .min(max_red) .clamp(2, MAX_REDUNDANCY_BYTES as i64); d.redundancy_bytes = bytes as usize; if hybrid { self.range.enc_uint((bytes - 2) as u32, 256); } } } else { d.redundancy = false; } if !d.redundancy { self.silk_bw_switch = false; d.redundancy_bytes = 0; } } fn encode_mode( &mut self, raw: &[f32], pcm: &[f32], delayed: &mut [f32], frame_size: usize, cap: usize, d: Decision, ) -> Result<(u8, Payload)> { match d.mode { Mode::Silk => self.encode_silk(raw, pcm, delayed, frame_size, cap, d), Mode::Hybrid => { let frame_48k = frame_size * self.upsample; let payload = self.encode_hybrid(raw, pcm, delayed, frame_size, d, cap)?; let config = 12 + if d.bandwidth == Bandwidth::Full { 2u8 } else { 0 } + if frame_48k == 960 { 1 } else { 0 }; Ok(( (config << 3) | (u8::from(d.stream_channels == 2) << 2), payload, )) } Mode::Celt => { let (toc, frame_48k, end) = self.toc(frame_size, d.bandwidth, d.stream_channels)?; self.fade_celt_input(delayed, frame_size, 1.0); self.stereo_fade_step(delayed, frame_size, d); let input = &*delayed; let _ = frame_48k; let n = self.encode_frame(input, frame_size, end, cap, d.stream_channels)?; Ok((toc, Payload::Range(n))) } } } fn encode_silk( &mut self, raw: &[f32], pcm: &[f32], delayed: &mut [f32], frame_size: usize, cap: usize, mut d: Decision, ) -> Result<(u8, Payload)> { let frame_48k = frame_size * self.upsample; self.fade_celt_input(delayed, frame_size, 1.0); let max_data_bytes = self.frame_max_data(frame_48k, cap); let fs_khz = silk_fs_khz(d.bandwidth); let f = self.silk_frame(d, max_data_bytes, fs_khz, false, false); let activity = self.silk_activity(raw, frame_size); self.range.reset(max_data_bytes - 1); if d.prefill != Prefill::Off { self.silk_prefill(&f, frame_size, activity, d.prefill); } let mut range = std::mem::take(&mut self.range); let silk = self .silk_layer() .encode(pcm, frame_size, &f, activity, &mut range); self.range = range; self.stereo_width_q14 = silk.stereo_width_q14; self.stereo_fade_step(delayed, frame_size, d); if silk.opus_can_switch { self.switch_ready(&mut d, max_data_bytes, frame_size); } self.code_redundancy_flags(&mut d, max_data_bytes, false); let khz = silk.internal_khz; let end = if khz == 8 { 13 } else { 17 }; self.celt_setup(Mode::Silk, end, d.stream_channels); if d.redundancy { self.celt.set_analysis(&self.info); } let mut red = [0u8; MAX_REDUNDANCY_BYTES]; let mut red_rng = 0; if d.redundancy && d.celt_to_silk { red_rng = self.celt_to_silk_redundancy(delayed, d.redundancy_bytes, &mut red); } self.celt.set_start_band(17); let mut len = (self.range.tell() as usize).div_ceil(8); self.range.done(); let bust = self.range.tell() as usize > (max_data_bytes - 1) * 8; if bust { self.range.reset(1); len = 1; } else if !d.redundancy { while len > 2 && self.range.data()[len - 1] == 0 { len -= 1; } } if d.redundancy && !d.celt_to_silk { red_rng = self.silk_to_celt_redundancy(delayed, frame_size, d.redundancy_bytes, &mut red); } let red_len = if d.redundancy { d.redundancy_bytes } else { 0 }; self.final_range = if bust { 0 } else { self.range.range() ^ red_rng }; let body = len + red_len; self.silk_buf[..len].copy_from_slice(&self.range.data()[..len]); self.silk_buf[len..body].copy_from_slice(&red[..red_len]); 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(d.stream_channels == 2) << 2); if !self.vbr && body + 1 < max_data_bytes { let pad_amount = max_data_bytes - (body + 2); let nb_255s = if pad_amount > 0 { (pad_amount - 1) / 255 } else { 0 }; let pos = if pad_amount > 0 { nb_255s + 2 } else { 1 }; let buf = &mut self.silk_buf[..]; buf.copy_within(0..body, pos); buf[0] = if pad_amount > 0 { 0x41 } else { 1 }; if pad_amount > 0 { buf[1..1 + nb_255s].fill(255); buf[1 + nb_255s] = (pad_amount - 255 * nb_255s - 1) as u8; } buf[pos + body..max_data_bytes - 1].fill(0); return Ok((toc | 3, Payload::Silk(max_data_bytes - 1))); } Ok((toc, Payload::Silk(body))) } fn encode_multiframe( &mut self, pcm: &[f32], frame_size: usize, cap: usize, d: Decision, cursor: (usize, i32), self_delimited: bool, ) -> Result<(u8, Payload)> { 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 max_data = if self.vbr { cap + 1 } else { let bits = bitrate_to_bits( self.bitrate as i32, self.sample_rate as i32, frame_size as i32, ); (((bits + 4) / 8) as usize).max(1).min(cap + 1) }; let max_data = max_data.min(MAX_SILK_PACKET_BYTES); let max_header = if count == 2 { 3 } else { 2 + (count - 1) * 2 }; let max_len_sum = (count + max_data).saturating_sub(max_header); let mut frames: Vec> = Vec::with_capacity(count); let mut tot = 0usize; let mut toc = 0u8; let mut result: Result<()> = Ok(()); if d.to_mono { self.force_mono = true; } else { self.prev_channels = d.stream_channels; } if self.analysis_on { self.analysis.seek(cursor); } for i in 0..count { let bits = bitrate_to_bits(self.bitrate as i32, self.sample_rate as i32, sub as i32); let mut curr_max = ((bits / 8) as usize).min(max_len_sum / count); curr_max = curr_max.min(max_len_sum.saturating_sub(tot)); let mut sub_d = d; sub_d.to_celt = d.to_celt && i == count - 1; sub_d.redundancy = d.redundancy && (sub_d.to_celt || (!d.to_celt && i == 0)); sub_d.to_mono = d.to_mono && i == 0; self.nonfinal = i < count - 1; if self.analysis_on { self.info = self.analysis.sub_info(sub); } let chunk = &pcm[i * sub * self.channels..(i + 1) * sub * self.channels]; match self.encode_frame_decided(chunk, sub, curr_max.saturating_sub(1), sub_d) { Ok((t, payload)) => { let bytes = self.payload_bytes(payload).to_vec(); tot += 1 + bytes.len(); if i == 0 { toc = t; } frames.push(bytes); } Err(e) => { result = Err(e); break; } } } self.nonfinal = false; result?; let dtx = frames.iter().filter(|f| f.is_empty()).count(); let pad = !self_delimited && !self.vbr && dtx != count; let (code, size) = self.pack_frames(&frames, max_data, pad)?; Ok(((toc & !3) | code, Payload::Silk(size))) } fn pack_frames( &mut self, frames: &[Vec], max_data: usize, pad: bool, ) -> Result<(u8, usize)> { let count = frames.len(); let len0 = frames[0].len(); let limit = max_data - 1; let lens_differ = frames.iter().any(|f| f.len() != len0); let too_big = || Error::corrupt("opus encode: multi-frame packet exceeds its budget"); if count == 2 { let size = if lens_differ { len0 + frames[1].len() + 1 + usize::from(len0 >= 252) } else { 2 * len0 }; if !(pad && size < limit) { if size > limit { return Err(too_big()); } let buf = &mut self.silk_buf[..]; let mut pos = 0; if lens_differ { Self::write_frame_len(buf, &mut pos, len0)?; } for f in frames { buf[pos..pos + f.len()].copy_from_slice(f); pos += f.len(); } return Ok((if lens_differ { 2 } else { 1 }, pos)); } } let vbr = lens_differ; let size = if vbr { 1 + frames[..count - 1] .iter() .map(|f| f.len() + 1 + usize::from(f.len() >= 252)) .sum::() + frames[count - 1].len() } else { 1 + count * len0 }; if size > limit { return Err(too_big()); } let pad_amount = if pad { limit - size } else { 0 }; let buf = &mut self.silk_buf[..]; buf[0] = count as u8 | (u8::from(vbr) << 7) | (u8::from(pad_amount != 0) << 6); let mut pos = 1; if pad_amount != 0 { let nb255 = (pad_amount - 1) / 255; buf[pos..pos + nb255].fill(255); pos += nb255; buf[pos] = (pad_amount - 255 * nb255 - 1) as u8; pos += 1; } if vbr { for f in &frames[..count - 1] { Self::write_frame_len(buf, &mut pos, f.len())?; } } for f in frames { buf[pos..pos + f.len()].copy_from_slice(f); pos += f.len(); } if pad_amount != 0 { buf[pos..limit].fill(0); pos = limit; } Ok((3, pos)) } fn frame_len_at(payload: &[u8], pos: usize) -> (usize, usize) { let b0 = usize::from(payload[pos]); if b0 < 252 { (b0, 1) } else { (b0 + 4 * usize::from(payload[pos + 1]), 2) } } fn self_delimited_split(toc: u8, payload: &[u8]) -> (usize, usize) { match toc & 3 { 0 => (0, payload.len()), 1 => (0, payload.len() / 2), 2 => { let (len0, used) = Self::frame_len_at(payload, 0); (used, payload.len() - used - len0) } _ => { let count = usize::from(payload[0] & 0x3F); let vbr = payload[0] & 0x80 != 0; let mut pos = 1; let mut pad = 0; if payload[0] & 0x40 != 0 { loop { let p = usize::from(payload[pos]); pos += 1; if p == 255 { pad += 254; } else { pad += p; break; } } } if vbr { let mut sum = 0; for _ in 1..count { let (len, used) = Self::frame_len_at(payload, pos); sum += len; pos += used; } (pos, payload.len() - pos - pad - sum) } else { (pos, (payload.len() - pos - pad) / count) } } } } /// 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, bandwidth: Bandwidth, stream_channels: 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 bw_idx: u8 = match bandwidth { Bandwidth::Narrow => 0, Bandwidth::Medium | Bandwidth::Wide => 1, Bandwidth::SuperWide => 2, Bandwidth::Full => 3, }; let config = 16 + 4 * bw_idx + fs_idx; Ok(( (config << 3) | (u8::from(stream_channels == 2) << 2), frame_48k, bandwidth.celt_end_band(), )) } fn decide_fec(&self, mode: Mode, bw: Bandwidth, rate: i32) -> (bool, Bandwidth) { const FEC_THRESHOLDS: [i32; 10] = [ 12000, 1000, 14000, 1000, 16000, 1000, 20000, 1000, 22000, 1000, ]; let loss = self.packet_loss_perc as i32; if !self.inband_fec || loss == 0 || mode == Mode::Celt { return (false, bw); } let mut b = bw_index(bw); 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); } } } fn voice_est(&self) -> i32 { if self.voice_ratio >= 0 { let v = (self.voice_ratio * 327) >> 8; if self.application == Application::Audio { v.min(115) } else { v } } else if self.application == Application::Voip { 115 } else { 48 } } fn decide(&mut self, pcm: &[f32], frame_size: usize, max_data_bytes: usize) -> Decision { let fs = self.sample_rate as i32; let fsz = frame_size as i32; let frame_rate = fs / fsz; let channels = self.channels as i32; let loss = i32::from(self.packet_loss_perc); let is_silence = pcm .iter() .take(frame_size * self.channels) .all(|x| x.abs() <= self.silence_threshold()); let stereo_width = if self.channels == 2 && !self.force_mono { update_stereo_width(&mut self.width_mem, pcm, frame_size, self.sample_rate) } else { 0.0 }; if !is_silence { self.voice_ratio = -1; } if self.info.valid { let prob = match self.prev_mode { None => self.info.music_prob, Some(Mode::Celt) => self.info.music_prob_max, Some(_) => self.info.music_prob_min, }; self.voice_ratio = (0.5 + 100.0 * (1.0 - prob)).floor() as i32; } let detected = self .info .valid .then(|| detected_bandwidth(self.info.bandwidth)); let mut bitrate = (self.bitrate as i32).min(bits_to_bitrate(max_data_bytes as i32 * 8, fs, fsz)); let mut max_data = max_data_bytes as i32; if !self.vbr { let cbr_bytes = ((bitrate_to_bits(bitrate, fs, fsz) + 4) / 8).min(max_data); bitrate = bits_to_bitrate(cbr_bytes * 8, fs, fsz); max_data = cbr_bytes.max(1); } self.bitrate_bps = bitrate; if max_data < 3 || bitrate < 3 * frame_rate * 8 || (frame_rate < 50 && (max_data * frame_rate < 300 || bitrate < 2400)) { return Decision { mode: self.prev_mode.unwrap_or(Mode::Hybrid), bandwidth: self.coded_bandwidth, stream_channels: self.stream_channels, equiv_rate: 0, redundancy: false, redundancy_bytes: 0, celt_to_silk: false, to_celt: false, prefill: Prefill::Off, to_mono: false, toc_only: Some(max_data as usize), }; } let max_rate = bits_to_bitrate(max_data * 8, fs, fsz); let ve = self.voice_est(); let mut equiv = compute_equiv_rate(bitrate, channels, frame_rate, self.vbr, None, loss); let mut stream_channels = self.channels; if self.channels == 2 && self.force_mono { stream_channels = 1; } else if self.channels == 2 { let mut threshold = STEREO_THRESHOLD_MUSIC + ((ve * ve * (STEREO_THRESHOLD_VOICE - STEREO_THRESHOLD_MUSIC)) >> 14); threshold += if self.stream_channels == 2 { -1000 } else { 1000 }; stream_channels = if equiv > threshold { 2 } else { 1 }; } let sc = stream_channels as i32; equiv = compute_equiv_rate(bitrate, sc, frame_rate, self.vbr, None, loss); let silk_dtx = self.use_dtx && !(self.info.valid || is_silence); let mut mode = if self.application == Application::LowDelay { Mode::Celt } else if let Some(forced) = self.mode { forced } else { let mode_voice = ((1.0 - stereo_width) * MODE_THRESHOLD_VOICE as f32 + stereo_width * MODE_THRESHOLD_VOICE_STEREO as f32) as i32; let mut threshold = MODE_THRESHOLD_MUSIC + ((ve * ve * (mode_voice - MODE_THRESHOLD_MUSIC)) >> 14); if self.application == Application::Voip { threshold += 8000; } match self.prev_mode { Some(Mode::Celt) => threshold -= 4000, Some(_) => threshold += 4000, None => {} } let mut auto = if equiv >= threshold { Mode::Celt } else { Mode::Silk }; if self.inband_fec && loss > (128 - ve) >> 4 { auto = Mode::Silk; } if silk_dtx && ve > 100 { auto = Mode::Silk; } let min_bits = bitrate_to_bits(if frame_rate > 50 { 9000 } else { 6000 }, fs, fsz); if max_data < min_bits / 8 { auto = Mode::Celt; } auto }; if mode != Mode::Celt && frame_size < self.sample_rate as usize / 100 { mode = Mode::Celt; } let prev = self.prev_mode; let (mut redundancy, mut celt_to_silk, mut to_celt) = (false, false, false); if let Some(p) = prev && (mode == Mode::Celt) != (p == Mode::Celt) { redundancy = true; celt_to_silk = mode != Mode::Celt; if !celt_to_silk { if frame_size >= self.sample_rate as usize / 100 { mode = p; to_celt = true; } else { redundancy = false; } } } let mut to_mono = false; if stream_channels == 1 && self.prev_channels == 2 && !self.to_mono && mode != Mode::Celt && prev != Some(Mode::Celt) { to_mono = true; stream_channels = 2; } let sc = stream_channels as i32; equiv = compute_equiv_rate(bitrate, sc, frame_rate, self.vbr, Some(mode), loss); let prefill = if mode != Mode::Celt && prev == Some(Mode::Celt) { Prefill::Reset } else { Prefill::Off }; let mut auto_bandwidth = self.auto_bandwidth; let mut bandwidth = self.coded_bandwidth; if mode == Mode::Celt || self.first || self .silk .as_ref() .is_some_and(|s| s.allow_bandwidth_switch()) { let (voice, music) = if self.channels == 2 && !self.force_mono { (&STEREO_VOICE_BW, &STEREO_MUSIC_BW) } else { (&MONO_VOICE_BW, &MONO_MUSIC_BW) }; let th: [i32; 8] = std::array::from_fn(|i| music[i] + ((ve * ve * (voice[i] - music[i])) >> 14)); let mut idx = 4; loop { let mut threshold = th[2 * (idx - 1)]; let hysteresis = th[2 * (idx - 1) + 1]; if !self.first { if bw_index(self.auto_bandwidth) >= idx { threshold -= hysteresis; } else { threshold += hysteresis; } } if equiv >= threshold { break; } idx -= 1; if idx == 0 { break; } } if idx == 1 { idx = 2; } auto_bandwidth = BANDWIDTHS[idx]; bandwidth = auto_bandwidth; let in_wb = self .silk .as_ref() .is_some_and(|s| s.in_wb_mode_without_variable_lp()); if !self.first && mode != Mode::Celt && !in_wb && bandwidth > Bandwidth::Wide { bandwidth = Bandwidth::Wide; } } if let Some(user) = self.bandwidth { bandwidth = user; } if mode != Mode::Celt && max_rate < 15000 { bandwidth = bandwidth.min(Bandwidth::Wide); } let ceiling = match self.sample_rate { 48000 => Bandwidth::Full, 24000 => Bandwidth::SuperWide, 16000 => Bandwidth::Wide, 12000 => Bandwidth::Medium, _ => Bandwidth::Narrow, }; bandwidth = bandwidth.min(ceiling); if let Some(det) = detected.filter(|_| self.bandwidth.is_none()) { let floor = if equiv <= 18000 * sc && mode == Mode::Celt { Bandwidth::Narrow } else if equiv <= 24000 * sc && mode == Mode::Celt { Bandwidth::Medium } else if equiv <= 30000 * sc { Bandwidth::Wide } else if equiv <= 44000 * sc { Bandwidth::SuperWide } else { Bandwidth::Full }; bandwidth = bandwidth.min(det.max(floor)); } let (fec, mut bandwidth) = self.decide_fec(mode, bandwidth, equiv); if mode == Mode::Celt && bandwidth == Bandwidth::Medium { bandwidth = Bandwidth::Wide; } if mode == Mode::Silk && bandwidth > Bandwidth::Wide { mode = Mode::Hybrid; } if mode == Mode::Hybrid && bandwidth <= Bandwidth::Wide { mode = Mode::Silk; } if mode == Mode::Hybrid { let silk_rate = silk_rate_for_hybrid( bitrate, bandwidth == Bandwidth::SuperWide, fs == 50 * fsz, self.vbr, fec, sc, ); if bitrate - silk_rate <= 500 { mode = Mode::Silk; bandwidth = Bandwidth::Wide; } } self.stream_channels = stream_channels; self.to_mono = to_mono; self.auto_bandwidth = auto_bandwidth; self.coded_bandwidth = bandwidth; self.lbrr_coded = fec; Decision { mode, bandwidth, stream_channels, equiv_rate: equiv, redundancy, redundancy_bytes: 0, celt_to_silk, to_celt, prefill, to_mono, toc_only: None, } } /// 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), false) { 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.lsb_depth = 16; let r = self.encode_float(&float, frame_size, out); self.lsb_depth = 24; r } fn total_buffer(&self) -> usize { if self.application != Application::LowDelay { self.sample_rate as usize / 250 } else { 0 } } fn silence_threshold(&self) -> f32 { 1.0 / (1u32 << self.lsb_depth) as f32 } /// [`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), true) { Err(e) => Err(e), Ok((toc, payload)) => { let count = payload.first().copied().unwrap_or(0); let (head, last) = Self::self_delimited_split(toc, payload); 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 payload: the SILK /// layer's symbols (WB, 16 kHz internal), the redundancy flag under the /// decoder's exact presence rule, then the CELT layer from band 17 in the /// same coder, followed by any redundant frame. 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], delayed: &mut [f32], frame_size: usize, mut d: Decision, cap: usize, ) -> Result { let bandwidth = d.bandwidth; let cap = cap.min(MAX_FRAME_BYTES); let frame_48k = frame_size * self.upsample; if cap < HYBRID_CELT_MIN_BYTES + 2 { return Err(Error::corrupt( "opus encode: output buffer smaller than the minimum hybrid packet", )); } let max_data_bytes = self.frame_max_data(frame_48k, cap); let budget = max_data_bytes - 1; self.range.reset(budget); let f = self.silk_frame( d, max_data_bytes, 16, true, bandwidth == Bandwidth::SuperWide, ); let activity = self.silk_activity(raw, frame_size); if d.prefill != Prefill::Off { self.silk_prefill(&f, frame_size, activity, d.prefill); } let mut range = std::mem::take(&mut self.range); let silk = self .silk_layer() .encode(pcm, frame_size, &f, activity, &mut range); self.range = range; self.stereo_width_q14 = silk.stereo_width_q14; if silk.opus_can_switch { self.switch_ready(&mut d, max_data_bytes, frame_size); } let celt_rate = silk.total_bit_rate - silk.bit_rate; let hb_gain = 1.0 - crate::celt_flp::celt_exp2(-(celt_rate as f32) * (1.0 / 1024.0)); self.fade_celt_input(delayed, frame_size, hb_gain); self.stereo_fade_step(delayed, frame_size, d); self.code_redundancy_flags(&mut d, max_data_bytes, true); let end = bandwidth.celt_end_band(); let red_len = if d.redundancy { d.redundancy_bytes } else { 0 }; let nb_compr = budget - red_len; self.range.shrink(nb_compr); self.celt_setup(Mode::Hybrid, end, d.stream_channels); self.celt.set_analysis(&self.info); self.celt.set_silk_info(silk.signal_type, silk.offset); let mut red = [0u8; MAX_REDUNDANCY_BYTES]; let mut red_rng = 0; if d.redundancy && d.celt_to_silk { red_rng = self.celt_to_silk_redundancy(delayed, red_len, &mut red); } self.celt.set_start_band(17); let celt_rate = self.bitrate_bps - silk.bit_rate; let n = self.celt_main(Mode::Hybrid, delayed, frame_size, nb_compr, celt_rate); if d.redundancy && !d.celt_to_silk { self.range.shrink(n); red_rng = self.silk_to_celt_redundancy(delayed, frame_size, red_len, &mut red); } let final_range = self.final_range ^ red_rng; self.final_range = final_range; self.silk_buf[..n].copy_from_slice(&self.range.data()[..n]); self.silk_buf[n..n + red_len].copy_from_slice(&red[..red_len]); Ok(Payload::Silk(n + red_len)) } fn encode_frame( &mut self, delayed: &[f32], frame_size: usize, end: usize, cap: usize, stream_channels: usize, ) -> Result { let max_data_bytes = self.frame_max_data(frame_size * self.upsample, cap); if max_data_bytes < 3 { return Err(Error::corrupt( "opus encode: output buffer smaller than the minimum packet", )); } self.range.reset(max_data_bytes - 1); self.celt_setup(Mode::Celt, end, stream_channels); self.celt.set_analysis(&self.info); self.celt.set_start_band(0); let n = self.celt_main(Mode::Celt, delayed, frame_size, max_data_bytes - 1, 0); Ok(n) } } #[cfg(test)] mod tests { use super::*; fn decided_bandwidth(e: &mut Encoder) -> Bandwidth { let pcm = vec![0.0f32; 960 * e.channels]; e.decide(&pcm, 960, 1276).bandwidth } #[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); e.set_bitrate(64_000); e.info.valid = true; e.info.bandwidth = 15; assert_eq!(decided_bandwidth(&mut e), Bandwidth::SuperWide); e.info.bandwidth = 20; assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full); e.info.bandwidth = 15; e.set_bitrate(96_000); assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full); e.set_bitrate(64_000); e.info.valid = false; assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full); } #[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!(decided_bandwidth(&mut e), Bandwidth::Full); e.set_bitrate(16000); assert_eq!(decided_bandwidth(&mut e), Bandwidth::Full); e.set_bitrate(10000); assert_eq!(decided_bandwidth(&mut e), Bandwidth::Wide); e.set_bitrate(8000); assert_eq!(decided_bandwidth(&mut e), Bandwidth::Narrow); let mut v = Encoder::new(48000, 1, Application::Voip).unwrap(); v.set_bitrate(16000); assert_eq!(decided_bandwidth(&mut v), Bandwidth::Full); let mut e = Encoder::new(24000, 2, Application::Audio).unwrap(); e.set_bitrate(256_000); let pcm = vec![0.0f32; 480 * 2]; assert_eq!(e.decide(&pcm, 480, 1276).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(); e.set_vbr_constrained(true); let pcm = vec![0.0f32; 960 * channels]; let mut last = 0u8; for per_channel in 500..=45_000u32 { e.set_bitrate(per_channel * channels as u32); let d = e.decide(&pcm, 960, 1276); if d.toc_only.is_some() { continue; } let class = match d.mode { Mode::Silk => 0, Mode::Hybrid => 1, Mode::Celt => 2, }; assert!( class >= last, "{channels}ch {per_channel} bps/channel regressed from {last} to {class}" ); last = class; } } } }