forge
Explore
Log in

Don't you dare go Hollow

Wire the analysis's leakage boost and detected bandwidth, both off

Browse files at this commit

7e58adeb37910f10b68112bd3a749b459d1b1d4eAhmet Kaan GümüşParent: 54d9580
  • feat
    • wire the analysis's leakage boost and detected bandwidth, both off
Show full message
feat(opus): wire the analysis's leakage boost and detected bandwidth, both off

Two more consumers of the ported tonality analysis, each behind its own
switch and each defaulting off until the 12-row library gate keeps it:

- EC_OPUS_LEAK: celt_encoder.c:1226-1230, the per-band leak_boost added
  to the dynalloc follower in 1/64 dB units.
- EC_OPUS_BW_DETECT: opus_encoder.c:1278-1305 maps analysis.bandwidth to
  an Opus bandwidth, :1652-1674 raises it to a rate-dependent floor and
  lets it lower (never raise) the automatic bandwidth.

The prefilter's max_pitch_ratio (celt_encoder.c:1494) has no consumer --
this encoder has no pitch prefilter -- and the spread/tapset hysteresis
is inside an #if 0 in libopus, so neither is wired.
crates/ec-opus/src/celt_enc.rsmodified+17 -6
@@ -68,7 +68,9 @@ fn tf_boost_params() -> (f32, f32, bool, f32) {
6868 /// `EC_OPUS_TRIM_TONAL` (`alloc_trim`'s `tonality_slope` term),
6969 /// `EC_OPUS_TRIM13` (the continuous 1.3 trim the term belongs to),
7070 /// `EC_OPUS_VBR_TONAL` (`compute_vbr`'s tonality boost) and
71-/// `EC_OPUS_VBR_ACT` (`compute_vbr`'s low-activity cut).
71+/// `EC_OPUS_VBR_ACT` (`compute_vbr`'s low-activity cut),
72+/// `EC_OPUS_LEAK` (`dynalloc_analysis`'s per-band leakage boost) and
73+/// `EC_OPUS_BW_DETECT` (the detected bandwidth lowering the coded one).
7274 ///
7375 /// MEASURED (lane opustonal, four detached 12-row library-gate runs against
7476 /// the shipped rows `lanes/opus-opustr2-r1.sweep.txt`). The analysis itself is
@@ -94,8 +96,8 @@ fn tf_boost_params() -> (f32, f32, bool, f32) {
9496 /// tf boost. Aligned, the analysis moves reell/reelo/her@64 a long way but leaves
9597 /// the aligned blocking set (nik, her@96, dl8a, hein) exactly where the
9698 /// analysis-free aligned arms left it, so the alignment default stays off.
97-pub(crate) fn analysis_params() -> (bool, bool, bool, bool) {
98- static P: std::sync::OnceLock<(bool, bool, bool, bool)> = std::sync::OnceLock::new();
99+pub(crate) fn analysis_params() -> (bool, bool, bool, bool, bool, bool) {
100+ static P: std::sync::OnceLock<(bool, bool, bool, bool, bool, bool)> = std::sync::OnceLock::new();
99101 *P.get_or_init(|| {
100102 let b = |name: &str, dflt: bool| {
101103 std::env::var(name).map(|v| v != "0").unwrap_or(dflt)
@@ -107,8 +109,10 @@ pub(crate) fn analysis_params() -> (bool, bool, bool, bool) {
107109 // realtime), so it only runs when something reads it: any consumer
108110 // switch, an explicit `EC_OPUS_ANALYSIS=1`, or
109111 // `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)
112+ let leak = b("EC_OPUS_LEAK", false);
113+ let bw = b("EC_OPUS_BW_DETECT", false);
114+ let any = trim || vbr_tonal || vbr_act || leak || bw;
115+ (b("EC_OPUS_ANALYSIS", any), trim, vbr_tonal, vbr_act, leak, bw)
112116 })
113117 }
114118
@@ -1026,7 +1030,7 @@ impl CeltEncoder {
10261030 let base_target =
10271031 vbr_rate + (self.vbr_offset >> lm_diff) - ((40 * c as i32 + 20) << BITRES);
10281032 let mut target = base_target;
1029- let (_, _, vbr_tonal, vbr_act) = analysis_params();
1033+ let (_, _, vbr_tonal, vbr_act, _, _) = analysis_params();
10301034 // compute_vbr (libopus celt_encoder.c:1605-1716), float-mode.
10311035 // Skipped: activity, tonality, surround_mask (analysis->valid=
10321036 // false, has_surround_mask=0, pitch_change=0, lfe=0). The qext
@@ -1548,6 +1552,13 @@ impl CeltEncoder {
15481552 follower[i] *= 0.5;
15491553 }
15501554 }
1555+ // libopus `celt_encoder.c:1226-1230`: the analysis's per-band
1556+ // leakage boost, in 1/64 dB units, on top of the follower.
1557+ if analysis_params().4 && self.info.valid {
1558+ for i in start..crate::analysis::LEAK_BANDS.min(end) {
1559+ follower[i] += f32::from(self.info.leak_boost[i]) / 64.0;
1560+ }
1561+ }
15511562 let mut tot_boost = 0i32;
15521563 for i in start..end {
15531564 let f = follower[i].min(4.0);
crates/ec-opus/src/encoder.rsmodified+74 -1
@@ -130,6 +130,8 @@ pub struct Encoder {
130130 info: AnalysisInfo,
131131 /// Whether the analysis runs at all — see `celt_enc::analysis_params`.
132132 analysis_on: bool,
133+ /// Whether the detected bandwidth may lower the coded one (`EC_OPUS_BW_DETECT`).
134+ bw_detect: bool,
133135 }
134136
135137 /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8,
@@ -195,6 +197,7 @@ impl Encoder {
195197 analysis: TonalityAnalysis::new(sample_rate),
196198 info: AnalysisInfo::default(),
197199 analysis_on: crate::celt_enc::analysis_params().0,
200+ bw_detect: crate::celt_enc::analysis_params().5,
198201 };
199202 // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how
200203 // the gate rows at `set_libopus_input_alignment` were produced.
@@ -799,7 +802,47 @@ impl Encoder {
799802 12000 => Bandwidth::Medium,
800803 _ => Bandwidth::Narrow,
801804 };
802- BWS[idx].min(ceiling)
805+ let bw = BWS[idx].min(ceiling);
806+ match self.detected_bandwidth(equiv, !self.auto_silk(equiv, ve)) {
807+ Some(d) => bw.min(d),
808+ None => bw,
809+ }
810+ }
811+
812+ /// libopus `opus_encoder.c:1278-1305`: the tonality analysis's own
813+ /// bandwidth estimate as an Opus bandwidth, raised by the conservative
814+ /// floor of `opus_encoder.c:1652-1674` (which depends on `equiv_rate` per
815+ /// channel and on whether the frame is CELT-only) before it is allowed to
816+ /// lower the coded bandwidth. `None` when the analysis did not run, which
817+ /// is libopus's `st->detected_bandwidth == 0`.
818+ ///
819+ /// Only the caller's automatic path consults this — libopus guards the
820+ /// clamp with `st->user_bandwidth == OPUS_AUTO`, which is exactly the
821+ /// `self.bandwidth.is_none()` branch that reaches `auto_bandwidth_at`.
822+ fn detected_bandwidth(&self, equiv: i32, celt_only: bool) -> Option<Bandwidth> {
823+ if !self.bw_detect || !self.info.valid {
824+ return None;
825+ }
826+ let detected = match self.info.bandwidth {
827+ i32::MIN..=12 => Bandwidth::Narrow,
828+ 13..=14 => Bandwidth::Medium,
829+ 15..=16 => Bandwidth::Wide,
830+ 17..=18 => Bandwidth::SuperWide,
831+ _ => Bandwidth::Full,
832+ };
833+ let ch = self.channels as i32;
834+ let floor = if celt_only && equiv <= 18000 * ch {
835+ Bandwidth::Narrow
836+ } else if celt_only && equiv <= 24000 * ch {
837+ Bandwidth::Medium
838+ } else if equiv <= 30000 * ch {
839+ Bandwidth::Wide
840+ } else if equiv <= 44000 * ch {
841+ Bandwidth::SuperWide
842+ } else {
843+ Bandwidth::Full
844+ };
845+ Some(detected.max(floor))
803846 }
804847
805848 /// libopus `opus_encoder.c`'s `dc_reject(pcm, 3, ...)`: a 3 Hz one-pole
@@ -1035,6 +1078,36 @@ impl Encoder {
10351078 mod tests {
10361079 use super::*;
10371080
1081+ /// The detected-bandwidth clamp (`opus_encoder.c:1652-1674`): a band-limited
1082+ /// analysis result lowers the coded bandwidth, but never below the
1083+ /// rate-dependent floor, and never when the analysis did not run.
1084+ #[test]
1085+ fn detected_bandwidth_lowers_the_coded_bandwidth_but_not_below_its_floor() {
1086+ let mut e = Encoder::new(48000, 2, Application::Audio).unwrap();
1087+ e.set_vbr_constrained(true); // the library gate's setting
1088+ e.set_bitrate(64_000);
1089+ // Analysis off (the default): fullband, whatever the estimate says.
1090+ e.info.valid = true;
1091+ e.info.bandwidth = 15; // wideband
1092+ assert_eq!(e.auto_bandwidth(), Bandwidth::Full);
1093+ // On: 64 kbps stereo is under 44000*2, so the floor is superwide —
1094+ // a wideband estimate is raised to it, not honoured as wideband.
1095+ e.bw_detect = true;
1096+ assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide);
1097+ // Above the floor the estimate passes through unchanged.
1098+ e.info.bandwidth = 20;
1099+ assert_eq!(e.auto_bandwidth(), Bandwidth::Full);
1100+ // 96 kbps stereo is above 44000*2: the floor is fullband, so the
1101+ // clamp is inert there — which is why it cannot move the @96 rows.
1102+ e.info.bandwidth = 15;
1103+ e.set_bitrate(96_000);
1104+ assert_eq!(e.auto_bandwidth(), Bandwidth::Full);
1105+ // An invalid analysis is libopus's `detected_bandwidth == 0`.
1106+ e.set_bitrate(64_000);
1107+ e.info.valid = false;
1108+ assert_eq!(e.auto_bandwidth(), Bandwidth::Full);
1109+ }
1110+
10381111 /// The private half of the bandwidth decision: the thresholds themselves,
10391112 /// which the TOC config only reports.
10401113 #[test]