diff --git a/crates/ec-opus/src/celt_enc.rs b/crates/ec-opus/src/celt_enc.rs index c71bf616..e5422d80 100644 --- a/crates/ec-opus/src/celt_enc.rs +++ b/crates/ec-opus/src/celt_enc.rs @@ -68,7 +68,9 @@ fn tf_boost_params() -> (f32, f32, bool, f32) { /// `EC_OPUS_TRIM_TONAL` (`alloc_trim`'s `tonality_slope` term), /// `EC_OPUS_TRIM13` (the continuous 1.3 trim the term belongs to), /// `EC_OPUS_VBR_TONAL` (`compute_vbr`'s tonality boost) and -/// `EC_OPUS_VBR_ACT` (`compute_vbr`'s low-activity cut). +/// `EC_OPUS_VBR_ACT` (`compute_vbr`'s low-activity cut), +/// `EC_OPUS_LEAK` (`dynalloc_analysis`'s per-band leakage boost) and +/// `EC_OPUS_BW_DETECT` (the detected bandwidth lowering the coded one). /// /// MEASURED (lane opustonal, four detached 12-row library-gate runs against /// 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) { /// 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. -pub(crate) fn analysis_params() -> (bool, bool, bool, bool) { - static P: std::sync::OnceLock<(bool, bool, bool, bool)> = std::sync::OnceLock::new(); +pub(crate) fn analysis_params() -> (bool, bool, bool, bool, bool, bool) { + static P: std::sync::OnceLock<(bool, bool, 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) @@ -107,8 +109,10 @@ pub(crate) fn analysis_params() -> (bool, bool, bool, bool) { // 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) + let leak = b("EC_OPUS_LEAK", false); + let bw = b("EC_OPUS_BW_DETECT", false); + let any = trim || vbr_tonal || vbr_act || leak || bw; + (b("EC_OPUS_ANALYSIS", any), trim, vbr_tonal, vbr_act, leak, bw) }) } @@ -1026,7 +1030,7 @@ impl CeltEncoder { let base_target = vbr_rate + (self.vbr_offset >> lm_diff) - ((40 * c as i32 + 20) << BITRES); let mut target = base_target; - let (_, _, vbr_tonal, vbr_act) = analysis_params(); + let (_, _, vbr_tonal, vbr_act, _, _) = analysis_params(); // compute_vbr (libopus celt_encoder.c:1605-1716), float-mode. // Skipped: activity, tonality, surround_mask (analysis->valid= // false, has_surround_mask=0, pitch_change=0, lfe=0). The qext @@ -1548,6 +1552,13 @@ impl CeltEncoder { follower[i] *= 0.5; } } + // libopus `celt_encoder.c:1226-1230`: the analysis's per-band + // leakage boost, in 1/64 dB units, on top of the follower. + if analysis_params().4 && self.info.valid { + for i in start..crate::analysis::LEAK_BANDS.min(end) { + follower[i] += f32::from(self.info.leak_boost[i]) / 64.0; + } + } let mut tot_boost = 0i32; for i in start..end { let f = follower[i].min(4.0); diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index 594d0afb..e6a9193b 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -130,6 +130,8 @@ pub struct Encoder { 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, } /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8, @@ -195,6 +197,7 @@ impl Encoder { analysis: TonalityAnalysis::new(sample_rate), info: AnalysisInfo::default(), analysis_on: crate::celt_enc::analysis_params().0, + bw_detect: crate::celt_enc::analysis_params().5, }; // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how // the gate rows at `set_libopus_input_alignment` were produced. @@ -799,7 +802,47 @@ impl Encoder { 12000 => Bandwidth::Medium, _ => Bandwidth::Narrow, }; - BWS[idx].min(ceiling) + 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)) } /// libopus `opus_encoder.c`'s `dc_reject(pcm, 3, ...)`: a 3 Hz one-pole @@ -1035,6 +1078,36 @@ impl Encoder { 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]