forge
Explore
Log in

Don't you dare go Hollow

Run the tonality analysis once per API frame, and only when read

Browse files at this commit

54d95807b1b34b502475e7710dcdf5d3771bc380Ahmet Kaan GümüşParent: bb5c616
  • perf
    • run the tonality analysis once per API frame, and only when read
Show full message
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.rsmodified+20 -25
@@ -32,7 +32,7 @@
32 32
33 use ec_core::{Error, Result};33 use ec_core::{Error, Result};
34 34
35-use crate::analysis::{AnalysisInfo, TonalityAnalysis};35+use crate::analysis::AnalysisInfo;
36 use crate::celt::{36 use crate::celt::{
37 self, BETA_COEF, BETA_INTRA, BITRES, CACHE_CAPS, E_BANDS, E_MEANS, E_PROB_MODEL, LOG_N,37 self, BETA_COEF, BETA_INTRA, BITRES, CACHE_CAPS, E_BANDS, E_MEANS, E_PROB_MODEL, LOG_N,
38 MAX_FINE_BITS, NB_BANDS, OVERLAP, PRED_COEF, PREEMPH, QTHETA_OFFSET, QTHETA_OFFSET_TWOPHASE,38 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) {
94 /// tf boost. Aligned, the analysis moves reell/reelo/her@64 a long way but leaves94 /// tf boost. Aligned, the analysis moves reell/reelo/her@64 a long way but leaves
95 /// the aligned blocking set (nik, her@96, dl8a, hein) exactly where the95 /// the aligned blocking set (nik, her@96, dl8a, hein) exactly where the
96 /// analysis-free aligned arms left it, so the alignment default stays off.96 /// analysis-free aligned arms left it, so the alignment default stays off.
97-fn analysis_params() -> (bool, bool, bool, bool) {97+pub(crate) fn analysis_params() -> (bool, bool, bool, bool) {
98 static P: std::sync::OnceLock<(bool, bool, bool, bool)> = std::sync::OnceLock::new();98 static P: std::sync::OnceLock<(bool, bool, bool, bool)> = std::sync::OnceLock::new();
99 *P.get_or_init(|| {99 *P.get_or_init(|| {
100 let b = |name: &str, dflt: bool| {100 let b = |name: &str, dflt: bool| {
101 std::env::var(name).map(|v| v != "0").unwrap_or(dflt)101 std::env::var(name).map(|v| v != "0").unwrap_or(dflt)
102 };102 };
103- (103+ let trim = b("EC_OPUS_TRIM_TONAL", false);
104- b("EC_OPUS_ANALYSIS", true),104+ let vbr_tonal = b("EC_OPUS_VBR_TONAL", false);
105- b("EC_OPUS_TRIM_TONAL", false),105+ let vbr_act = b("EC_OPUS_VBR_ACT", false);
106- b("EC_OPUS_VBR_TONAL", false),106+ // The analysis costs ~25% of the encoder (5.1 384k: 126x -> 100x
107- b("EC_OPUS_VBR_ACT", false),107+ // realtime), so it only runs when something reads it: any consumer
108- )108+ // switch, an explicit `EC_OPUS_ANALYSIS=1`, or
109+ // `Encoder::set_analysis(true)` for the diagnostics.
110+ let any = trim || vbr_tonal || vbr_act;
111+ (b("EC_OPUS_ANALYSIS", any), trim, vbr_tonal, vbr_act)
109 })112 })
110 }113 }
111 114
@@ -516,12 +519,10 @@ pub struct CeltEncoder {
516 urow: Vec<u32>,519 urow: Vec<u32>,
517 /// Per-frame diagnostics captured at the end of the last `encode` call.520 /// Per-frame diagnostics captured at the end of the last `encode` call.
518 last_diag: CeltFrameDiag,521 last_diag: CeltFrameDiag,
519- /// libopus `st->analysis`: the tonality/music-probability estimator, run522+ /// libopus `st->analysis`'s per-frame output, handed in by
520- /// on the *undelayed* API input at the top of every `encode` call exactly523+ /// [`crate::Encoder`] (which owns the estimator and runs it once per API
521- /// where `opus_encode()` runs `run_analysis()`.524+ /// frame, libopus's order); the `valid == false` default when the
522- analysis: TonalityAnalysis,525+ /// analysis is off.
523- /// The window that covers the frame being coded, or the default
524- /// (`valid == false`) state when the analysis is off.
525 info: AnalysisInfo,526 info: AnalysisInfo,
526 }527 }
527 528
@@ -580,7 +581,6 @@ impl CeltEncoder {
580 pvq_sign: vec![0; max_n],581 pvq_sign: vec![0; max_n],
581 urow: vec![0; 1280],582 urow: vec![0; 1280],
582 last_diag: CeltFrameDiag::default(),583 last_diag: CeltFrameDiag::default(),
583- analysis: TonalityAnalysis::new((48000 / upsample) as u32),
584 info: AnalysisInfo::default(),584 info: AnalysisInfo::default(),
585 }585 }
586 }586 }
@@ -624,7 +624,6 @@ impl CeltEncoder {
624 self.vbr_count = 0;624 self.vbr_count = 0;
625 self.stereo_saving = 0.0;625 self.stereo_saving = 0.0;
626 self.spec_avg = 0.0;626 self.spec_avg = 0.0;
627- self.analysis.reset();
628 self.info = AnalysisInfo::default();627 self.info = AnalysisInfo::default();
629 }628 }
630 629
@@ -638,7 +637,7 @@ impl CeltEncoder {
638 /// postfilter bit, allocation over the coded span only. With637 /// postfilter bit, allocation over the coded span only. With
639 /// `vbr_rate_bps` set, the frame may be shrunk below that budget638 /// `vbr_rate_bps` set, the frame may be shrunk below that budget
640 /// (constrained VBR); the return value is the final frame size in bytes.639 /// (constrained VBR); the return value is the final frame size in bytes.
641- pub fn encode(640+ pub(crate) fn encode(
642 &mut self,641 &mut self,
643 enc: &mut RangeEncoder,642 enc: &mut RangeEncoder,
644 pcm: &[f32],643 pcm: &[f32],
@@ -646,6 +645,7 @@ impl CeltEncoder {
646 start: usize,645 start: usize,
647 end: usize,646 end: usize,
648 vbr_rate_bps: u32,647 vbr_rate_bps: u32,
648+ info: &AnalysisInfo,
649 ) -> Result<usize> {649 ) -> Result<usize> {
650 let lm: usize = match frame_size {650 let lm: usize = match frame_size {
651 120 => 0,651 120 => 0,
@@ -672,14 +672,9 @@ impl CeltEncoder {
672 let end = end.clamp(start + 1, NB_BANDS);672 let end = end.clamp(start + 1, NB_BANDS);
673 673
674 // libopus `opus_encode_native` runs the tonality analysis on the raw674 // libopus `opus_encode_native` runs the tonality analysis on the raw
675- // API frame before anything else; the CELT layer's own delay does not675+ // API frame before the mode decision, so the estimator lives in
676- // apply to it, so this reads `pcm` and not the delayed buffer. 24 is676+ // `Encoder` and its result is handed down here.
677- // libopus's `lsb_depth` default for the float API.677+ self.info = *info;
678- self.info = if analysis_params().0 {
679- self.analysis.run(pcm, in_n, c, 24)
680- } else {
681- AnalysisInfo::default()
682- };
683 678
684 let mut nb_compressed = enc.storage();679 let mut nb_compressed = enc.storage();
685 let mut nb_available = nb_compressed as i32;680 let mut nb_available = nb_compressed as i32;
crates/ec-opus/src/encoder.rsmodified+37 -3
@@ -21,6 +21,7 @@
21 21
22 use ec_core::{Error, Result};22 use ec_core::{Error, Result};
23 23
24+use crate::analysis::{AnalysisInfo, TonalityAnalysis};
24 use crate::celt_enc::CeltEncoder;25 use crate::celt_enc::CeltEncoder;
25 use crate::packet::{Bandwidth, Mode};26 use crate::packet::{Bandwidth, Mode};
26 use crate::range::RangeEncoder;27 use crate::range::RangeEncoder;
@@ -120,6 +121,15 @@ pub struct Encoder {
120 hp_mem: [f32; 2],121 hp_mem: [f32; 2],
121 /// Scratch space for that filter's output, sized once.122 /// Scratch space for that filter's output, sized once.
122 hp_buf: Vec<f32>,123 hp_buf: Vec<f32>,
124+ /// libopus `st->analysis`: the tonality/music-probability estimator. It
125+ /// lives here, not in the CELT layer, because `opus_encode_native` runs
126+ /// `run_analysis()` on the API frame *before* the SILK/CELT mode and
127+ /// bandwidth decisions, so its state advances on SILK frames too.
128+ analysis: TonalityAnalysis,
129+ /// The current frame's analysis output, handed to `celt.encode`.
130+ info: AnalysisInfo,
131+ /// Whether the analysis runs at all — see `celt_enc::analysis_params`.
132+ analysis_on: bool,
123 }133 }
124 134
125 /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8,135 /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8,
@@ -182,6 +192,9 @@ impl Encoder {
182 align_input: false,192 align_input: false,
183 hp_mem: [0.0; 2],193 hp_mem: [0.0; 2],
184 hp_buf: Vec::new(),194 hp_buf: Vec::new(),
195+ analysis: TonalityAnalysis::new(sample_rate),
196+ info: AnalysisInfo::default(),
197+ analysis_on: crate::celt_enc::analysis_params().0,
185 };198 };
186 // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how199 // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how
187 // the gate rows at `set_libopus_input_alignment` were produced.200 // the gate rows at `set_libopus_input_alignment` were produced.
@@ -191,6 +204,15 @@ impl Encoder {
191 Ok(enc)204 Ok(enc)
192 }205 }
193 206
207+ /// Turns the tonality analysis on or off for this encoder. It is off
208+ /// unless one of its consumers is switched on (see
209+ /// `celt_enc::analysis_params`), because it costs ~25% of the encoder;
210+ /// turn it on to read `music_prob`/`tonality` back through
211+ /// [`Encoder::last_celt_diag`].
212+ pub fn set_analysis(&mut self, on: bool) {
213+ self.analysis_on = on;
214+ }
215+
194 /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and216 /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and
195 /// `hybrid_choice` make from the application and bitrate; pass `None` to217 /// `hybrid_choice` make from the application and bitrate; pass `None` to
196 /// restore the automatic pick. Requests this encoder cannot honour218 /// restore the automatic pick. Requests this encoder cannot honour
@@ -361,6 +383,8 @@ impl Encoder {
361 self.silk_delay.clear();383 self.silk_delay.clear();
362 self.hp_mem = [0.0; 2];384 self.hp_mem = [0.0; 2];
363 self.final_range = 0;385 self.final_range = 0;
386+ self.analysis.reset();
387+ self.info = AnalysisInfo::default();
364 }388 }
365 389
366 /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`])390 /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`])
@@ -591,6 +615,15 @@ impl Encoder {
591 cap: usize,615 cap: usize,
592 ) -> Result<(u8, &[u8])> {616 ) -> Result<(u8, &[u8])> {
593 let frame_48k = frame_size * self.upsample;617 let frame_48k = frame_size * self.upsample;
618+ // libopus `opus_encode_native`: `run_analysis()` runs on the API frame
619+ // before the mode/bandwidth decisions, so the estimator state advances
620+ // on every frame, SILK ones included. 24 is libopus's float-API
621+ // `lsb_depth` default.
622+ self.info = if self.analysis_on {
623+ self.analysis.run(pcm, frame_size, self.channels, 24)
624+ } else {
625+ AnalysisInfo::default()
626+ };
594 if let Some(fs_khz) = self.silk_choice(frame_48k) {627 if let Some(fs_khz) = self.silk_choice(frame_48k) {
595 if self.channels == 2 {628 if self.channels == 2 {
596 Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);629 Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff);
@@ -947,6 +980,7 @@ impl Encoder {
947 17,980 17,
948 bandwidth.celt_end_band(),981 bandwidth.celt_end_band(),
949 0,982 0,
983+ &self.info,
950 )?;984 )?;
951 self.final_range = self.range.range();985 self.final_range = self.range.range();
952 let payload = &self.range.data()[..n];986 let payload = &self.range.data()[..n];
@@ -989,9 +1023,9 @@ impl Encoder {
989 (b.saturating_sub(1).clamp(2, cap), 0)1023 (b.saturating_sub(1).clamp(2, cap), 0)
990 };1024 };
991 self.range.reset(budget);1025 self.range.reset(budget);
992- let n = self1026+ let n =
993- .celt1027+ self.celt
994- .encode(&mut self.range, pcm, frame_size, 0, end, vbr_rate)?;1028+ .encode(&mut self.range, pcm, frame_size, 0, end, vbr_rate, &self.info)?;
995 self.final_range = self.range.range();1029 self.final_range = self.range.range();
996 Ok(n)1030 Ok(n)
997 }1031 }
crates/ec-opus/tests/conformance.rsmodified+4 -0
@@ -5757,6 +5757,10 @@ fn analysis_music_prob_separates_speech_from_music() {
5757 let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder");5757 let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder");
5758 enc.set_bitrate(96_000);5758 enc.set_bitrate(96_000);
5759 enc.set_vbr_constrained(true);5759 enc.set_vbr_constrained(true);
5760+ // The analysis is off unless a consumer needs it (it costs ~25% of the
5761+ // encoder); the diagnostics are exactly the "explicitly asked for it"
5762+ // case.
5763+ enc.set_analysis(true);
5760 let mut out = vec![0u8; 4000];5764 let mut out = vec![0u8; 4000];
5761 let mut sum = [0.0f64; 4];5765 let mut sum = [0.0f64; 4];
5762 let mut n = 0usize;5766 let mut n = 0usize;