From 54d95807b1b34b502475e7710dcdf5d3771bc380 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 22:32:59 +0300 Subject: [PATCH] perf(opus): run the tonality analysis once per API frame, and only when read libopus's opus_encode_native runs run_analysis() on the API frame before the SILK/CELT mode decision, so the estimator belongs to Encoder, not to the CELT layer: hoisted, its result threaded into celt.encode at both call sites, state now advancing on SILK frames too. It also cost ~25% of the encoder while every one of its bitstream consumers ships off, so it now runs only when something reads it -- any consumer switch, EC_OPUS_ANALYSIS=1, or the new Encoder::set_analysis. 5.1 384k goes 100x -> 123x realtime, mono 96k 433x -> 557x; the music_prob oracle test is unchanged against libopus (hein .161/.155/ -.0875/.568, reell .991/.362/-.1680/.701, reelo .976/.312/-.1332/.735). --- crates/ec-opus/src/celt_enc.rs | 45 +++++++++++++---------------- crates/ec-opus/src/encoder.rs | 40 +++++++++++++++++++++++-- crates/ec-opus/tests/conformance.rs | 4 +++ 3 files changed, 61 insertions(+), 28 deletions(-) diff --git a/crates/ec-opus/src/celt_enc.rs b/crates/ec-opus/src/celt_enc.rs index db36d63f..c71bf616 100644 --- a/crates/ec-opus/src/celt_enc.rs +++ b/crates/ec-opus/src/celt_enc.rs @@ -32,7 +32,7 @@ use ec_core::{Error, Result}; -use crate::analysis::{AnalysisInfo, TonalityAnalysis}; +use crate::analysis::AnalysisInfo; use crate::celt::{ self, BETA_COEF, BETA_INTRA, BITRES, CACHE_CAPS, E_BANDS, E_MEANS, E_PROB_MODEL, LOG_N, MAX_FINE_BITS, NB_BANDS, OVERLAP, PRED_COEF, PREEMPH, QTHETA_OFFSET, QTHETA_OFFSET_TWOPHASE, @@ -94,18 +94,21 @@ fn tf_boost_params() -> (f32, f32, bool, f32) { /// tf boost. Aligned, the analysis moves reell/reelo/her@64 a long way but leaves /// the aligned blocking set (nik, her@96, dl8a, hein) exactly where the /// analysis-free aligned arms left it, so the alignment default stays off. -fn analysis_params() -> (bool, bool, bool, bool) { +pub(crate) fn analysis_params() -> (bool, bool, bool, bool) { static P: std::sync::OnceLock<(bool, bool, bool, bool)> = std::sync::OnceLock::new(); *P.get_or_init(|| { let b = |name: &str, dflt: bool| { std::env::var(name).map(|v| v != "0").unwrap_or(dflt) }; - ( - b("EC_OPUS_ANALYSIS", true), - b("EC_OPUS_TRIM_TONAL", false), - b("EC_OPUS_VBR_TONAL", false), - b("EC_OPUS_VBR_ACT", false), - ) + let trim = b("EC_OPUS_TRIM_TONAL", false); + let vbr_tonal = b("EC_OPUS_VBR_TONAL", false); + let vbr_act = b("EC_OPUS_VBR_ACT", false); + // The analysis costs ~25% of the encoder (5.1 384k: 126x -> 100x + // realtime), so it only runs when something reads it: any consumer + // switch, an explicit `EC_OPUS_ANALYSIS=1`, or + // `Encoder::set_analysis(true)` for the diagnostics. + let any = trim || vbr_tonal || vbr_act; + (b("EC_OPUS_ANALYSIS", any), trim, vbr_tonal, vbr_act) }) } @@ -516,12 +519,10 @@ pub struct CeltEncoder { urow: Vec, /// Per-frame diagnostics captured at the end of the last `encode` call. last_diag: CeltFrameDiag, - /// libopus `st->analysis`: the tonality/music-probability estimator, run - /// on the *undelayed* API input at the top of every `encode` call exactly - /// where `opus_encode()` runs `run_analysis()`. - analysis: TonalityAnalysis, - /// The window that covers the frame being coded, or the default - /// (`valid == false`) state when the analysis is off. + /// libopus `st->analysis`'s per-frame output, handed in by + /// [`crate::Encoder`] (which owns the estimator and runs it once per API + /// frame, libopus's order); the `valid == false` default when the + /// analysis is off. info: AnalysisInfo, } @@ -580,7 +581,6 @@ impl CeltEncoder { pvq_sign: vec![0; max_n], urow: vec![0; 1280], last_diag: CeltFrameDiag::default(), - analysis: TonalityAnalysis::new((48000 / upsample) as u32), info: AnalysisInfo::default(), } } @@ -624,7 +624,6 @@ impl CeltEncoder { self.vbr_count = 0; self.stereo_saving = 0.0; self.spec_avg = 0.0; - self.analysis.reset(); self.info = AnalysisInfo::default(); } @@ -638,7 +637,7 @@ impl CeltEncoder { /// postfilter bit, allocation over the coded span only. With /// `vbr_rate_bps` set, the frame may be shrunk below that budget /// (constrained VBR); the return value is the final frame size in bytes. - pub fn encode( + pub(crate) fn encode( &mut self, enc: &mut RangeEncoder, pcm: &[f32], @@ -646,6 +645,7 @@ impl CeltEncoder { start: usize, end: usize, vbr_rate_bps: u32, + info: &AnalysisInfo, ) -> Result { let lm: usize = match frame_size { 120 => 0, @@ -672,14 +672,9 @@ impl CeltEncoder { let end = end.clamp(start + 1, NB_BANDS); // libopus `opus_encode_native` runs the tonality analysis on the raw - // API frame before anything else; the CELT layer's own delay does not - // apply to it, so this reads `pcm` and not the delayed buffer. 24 is - // libopus's `lsb_depth` default for the float API. - self.info = if analysis_params().0 { - self.analysis.run(pcm, in_n, c, 24) - } else { - AnalysisInfo::default() - }; + // API frame before the mode decision, so the estimator lives in + // `Encoder` and its result is handed down here. + self.info = *info; let mut nb_compressed = enc.storage(); let mut nb_available = nb_compressed as i32; diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index 3530f5d7..594d0afb 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -21,6 +21,7 @@ use ec_core::{Error, Result}; +use crate::analysis::{AnalysisInfo, TonalityAnalysis}; use crate::celt_enc::CeltEncoder; use crate::packet::{Bandwidth, Mode}; use crate::range::RangeEncoder; @@ -120,6 +121,15 @@ pub struct Encoder { hp_mem: [f32; 2], /// Scratch space for that 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, } /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8, @@ -182,6 +192,9 @@ impl Encoder { align_input: false, hp_mem: [0.0; 2], hp_buf: Vec::new(), + analysis: TonalityAnalysis::new(sample_rate), + info: AnalysisInfo::default(), + analysis_on: crate::celt_enc::analysis_params().0, }; // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how // the gate rows at `set_libopus_input_alignment` were produced. @@ -191,6 +204,15 @@ impl Encoder { 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 @@ -361,6 +383,8 @@ impl Encoder { self.silk_delay.clear(); self.hp_mem = [0.0; 2]; self.final_range = 0; + self.analysis.reset(); + self.info = AnalysisInfo::default(); } /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) @@ -591,6 +615,15 @@ impl Encoder { cap: usize, ) -> Result<(u8, &[u8])> { let frame_48k = frame_size * self.upsample; + // 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() + }; if let Some(fs_khz) = self.silk_choice(frame_48k) { if self.channels == 2 { Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff); @@ -947,6 +980,7 @@ impl Encoder { 17, bandwidth.celt_end_band(), 0, + &self.info, )?; self.final_range = self.range.range(); let payload = &self.range.data()[..n]; @@ -989,9 +1023,9 @@ impl Encoder { (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)?; + 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) } diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 87c804eb..257de1f8 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -5757,6 +5757,10 @@ fn analysis_music_prob_separates_speech_from_music() { let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder"); enc.set_bitrate(96_000); enc.set_vbr_constrained(true); + // The analysis is off unless a consumer needs it (it costs ~25% of the + // encoder); the diagnostics are exactly the "explicitly asked for it" + // case. + enc.set_analysis(true); let mut out = vec![0u8; 4000]; let mut sum = [0.0f64; 4]; let mut n = 0usize;