Merge branch 'lane-opusmode' (dda82f99): the tonality analysis runs once per API frame and only when read; detected-bandwidth clamp and leak boost wired, off
Browse files at this commit6 changed files +218 -33
- crates/ec-opus/src/celt_enc.rs +44 -29
- crates/ec-opus/src/encoder.rs +111 -4
- crates/ec-opus/tests/conformance.rs +15 -0
- lanes/opus-opusmode-r1.sweep.txt +16 -0
- lanes/opus-opusmode-r2.sweep.txt +16 -0
- lanes/opus-opusmode-r3.sweep.txt +16 -0
crates/ec-opus/src/celt_enc.rsmodified+44 -29
| @@ -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, |
| @@ -68,7 +68,9 @@ fn tf_boost_params() -> (f32, f32, bool, f32) { | |||
| 68 | /// `EC_OPUS_TRIM_TONAL` (`alloc_trim`'s `tonality_slope` term), | 68 | /// `EC_OPUS_TRIM_TONAL` (`alloc_trim`'s `tonality_slope` term), |
| 69 | /// `EC_OPUS_TRIM13` (the continuous 1.3 trim the term belongs to), | 69 | /// `EC_OPUS_TRIM13` (the continuous 1.3 trim the term belongs to), |
| 70 | /// `EC_OPUS_VBR_TONAL` (`compute_vbr`'s tonality boost) and | 70 | /// `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). | ||
| 72 | /// | 74 | /// |
| 73 | /// MEASURED (lane opustonal, four detached 12-row library-gate runs against | 75 | /// MEASURED (lane opustonal, four detached 12-row library-gate runs against |
| 74 | /// the shipped rows `lanes/opus-opustr2-r1.sweep.txt`). The analysis itself is | 76 | /// the shipped rows `lanes/opus-opustr2-r1.sweep.txt`). The analysis itself is |
| @@ -81,6 +83,9 @@ fn tf_boost_params() -> (f32, f32, bool, f32) { | |||
| 81 | /// | 1.3 trim + tonality term (`-r1`) | nik@64 .708→.647, reelo@64 1.510→1.071, reelo@96 .940→.898, reell@96 4.499→2.458, dl8a .552/.374→.512/.336 | nik@96 .985→1.006, her@64 1.103→1.109, her@96 1.051→1.085, reell@64 2.697→2.872 | | 83 | /// | 1.3 trim + tonality term (`-r1`) | nik@64 .708→.647, reelo@64 1.510→1.071, reelo@96 .940→.898, reell@96 4.499→2.458, dl8a .552/.374→.512/.336 | nik@96 .985→1.006, her@64 1.103→1.109, her@96 1.051→1.085, reell@64 2.697→2.872 | |
| 82 | /// | vbr tonality + activity (`-r2`) | hein@64 .853→.327, hein@96 .528→.426, nik@64 →.672, dl8a@64 →.541 | nik@96 →1.061, reelo@96 →1.165, her@64 →1.104, her@96 →1.060, dl8a@96 →.414 | | 84 | /// | vbr tonality + activity (`-r2`) | hein@64 .853→.327, hein@96 .528→.426, nik@64 →.672, dl8a@64 →.541 | nik@96 →1.061, reelo@96 →1.165, her@64 →1.104, her@96 →1.060, dl8a@96 →.414 | |
| 83 | /// | vbr activity alone (`-r3`) | hein@64 →.430, hein@96 →.408, nik@64 →.657, dl8a@64 →.511 | nik@96 →.990, her@64 →1.104, her@96 →1.071, dl8a@96 →.382 | | 85 | /// | vbr activity alone (`-r3`) | hein@64 →.430, hein@96 →.408, nik@64 →.657, dl8a@64 →.511 | nik@96 →.990, her@64 →1.104, her@96 →1.071, dl8a@96 →.382 | |
| 86 | +/// | `EC_OPUS_BW_DETECT` (`opusmode -r1`) | -- | -- (byte-identical: `analysis.bandwidth` is 20 on every valid frame of every gate source, so the clamp never fires) | | ||
| 87 | +/// | `EC_OPUS_LEAK` (`opusmode -r2`) | -- | nik@64 .708→.709, nik@96 .985→.986, her@96 1.051→1.052 (the rest identical) | | ||
| 88 | +/// | `EC_OPUS_BW_DETECT` + `EC_OPUS_VBR_ACT` + `EC_OPUS_TF_K=1.25` (`opusmode -r3`) | reell@96 4.499→2.516, reell@64 2.697→1.440, hein@64 .853→.470, hein@96 .528→.404, dl8a@96 .374→.315, dl8a@64 →.535, nik@64 →.651, **nik@96 .985→.957**, reelo@96 →.928, reelo@64 →1.509 | her@96 1.051→1.071, her@64 1.103→1.104 | | ||
| 84 | /// | all four + `EC_OPUS_ALIGN=1` (`-r4`) | reell@64 →1.865, reell@96 →3.986, reelo@64 →1.123, reelo@96 →.891, her@64 →.952 | nik@64 →1.014, nik@96 →1.842, her@96 →1.217, dl8a →1.162/.988, hein →.971/1.514 | | 89 | /// | all four + `EC_OPUS_ALIGN=1` (`-r4`) | reell@64 →1.865, reell@96 →3.986, reelo@64 →1.123, reelo@96 →.891, her@64 →.952 | nik@64 →1.014, nik@96 →1.842, her@96 →1.217, dl8a →1.162/.988, hein →.971/1.514 | |
| 85 | /// | 90 | /// |
| 86 | /// `corr_ours` is never worse by more than .0005 on any unaligned arm (it is | 91 | /// `corr_ours` is never worse by more than .0005 on any unaligned arm (it is |
| @@ -91,21 +96,32 @@ fn tf_boost_params() -> (f32, f32, bool, f32) { | |||
| 91 | /// discrete-ladder arm was run. The activity cut is the nearest miss ever | 96 | /// discrete-ladder arm was run. The activity cut is the nearest miss ever |
| 92 | /// measured on this gate for a speech source (hein halves) and is blocked by | 97 | /// measured on this gate for a speech source (hein halves) and is blocked by |
| 93 | /// her@96 +.020 and nik@96 +.005 -- the same two rows that have blocked the | 98 | /// her@96 +.020 and nik@96 +.005 -- the same two rows that have blocked the |
| 94 | -/// tf boost. Aligned, the analysis moves reell/reelo/her@64 a long way but leaves | 99 | +/// The combined arm (`opusmode -r3`) is the first arm ever measured on this |
| 100 | +/// gate that moves a blocking row the right way: nik@96 .985→.957. It is | ||
| 101 | +/// **rejected by the per-row KEEP rule** (her@96 +.020, her@64 +.001) and | ||
| 102 | +/// **passes the aggregate rule** (geometric-mean err_ratio 1.0218→0.8378, | ||
| 103 | +/// -18.0%; worst row her@96 +1.9%, under the 5% bound; `corr_ours` within | ||
| 104 | +/// .0001 on every row). Which rule ships is the user's call; the default is | ||
| 105 | +/// off either way. 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 the | 106 | /// 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. | 107 | /// analysis-free aligned arms left it, so the alignment default stays off. |
| 97 | -fn analysis_params() -> (bool, bool, bool, bool) { | 108 | +pub(crate) fn analysis_params() -> (bool, bool, bool, bool, bool, bool) { |
| 98 | - static P: std::sync::OnceLock<(bool, bool, bool, bool)> = std::sync::OnceLock::new(); | 109 | + static P: std::sync::OnceLock<(bool, bool, bool, bool, bool, bool)> = std::sync::OnceLock::new(); |
| 99 | *P.get_or_init(|| { | 110 | *P.get_or_init(|| { |
| 100 | let b = |name: &str, dflt: bool| { | 111 | let b = |name: &str, dflt: bool| { |
| 101 | std::env::var(name).map(|v| v != "0").unwrap_or(dflt) | 112 | std::env::var(name).map(|v| v != "0").unwrap_or(dflt) |
| 102 | }; | 113 | }; |
| 103 | - ( | 114 | + let trim = b("EC_OPUS_TRIM_TONAL", false); |
| 104 | - b("EC_OPUS_ANALYSIS", true), | 115 | + let vbr_tonal = b("EC_OPUS_VBR_TONAL", false); |
| 105 | - b("EC_OPUS_TRIM_TONAL", false), | 116 | + let vbr_act = b("EC_OPUS_VBR_ACT", false); |
| 106 | - b("EC_OPUS_VBR_TONAL", false), | 117 | + // The analysis costs ~25% of the encoder (5.1 384k: 126x -> 100x |
| 107 | - b("EC_OPUS_VBR_ACT", false), | 118 | + // realtime), so it only runs when something reads it: any consumer |
| 108 | - ) | 119 | + // switch, an explicit `EC_OPUS_ANALYSIS=1`, or |
| 120 | + // `Encoder::set_analysis(true)` for the diagnostics. | ||
| 121 | + let leak = b("EC_OPUS_LEAK", false); | ||
| 122 | + let bw = b("EC_OPUS_BW_DETECT", false); | ||
| 123 | + let any = trim || vbr_tonal || vbr_act || leak || bw; | ||
| 124 | + (b("EC_OPUS_ANALYSIS", any), trim, vbr_tonal, vbr_act, leak, bw) | ||
| 109 | }) | 125 | }) |
| 110 | } | 126 | } |
| 111 | 127 | ||
| @@ -516,12 +532,10 @@ pub struct CeltEncoder { | |||
| 516 | urow: Vec<u32>, | 532 | urow: Vec<u32>, |
| 517 | /// Per-frame diagnostics captured at the end of the last `encode` call. | 533 | /// Per-frame diagnostics captured at the end of the last `encode` call. |
| 518 | last_diag: CeltFrameDiag, | 534 | last_diag: CeltFrameDiag, |
| 519 | - /// libopus `st->analysis`: the tonality/music-probability estimator, run | 535 | + /// libopus `st->analysis`'s per-frame output, handed in by |
| 520 | - /// on the *undelayed* API input at the top of every `encode` call exactly | 536 | + /// [`crate::Encoder`] (which owns the estimator and runs it once per API |
| 521 | - /// where `opus_encode()` runs `run_analysis()`. | 537 | + /// frame, libopus's order); the `valid == false` default when the |
| 522 | - analysis: TonalityAnalysis, | 538 | + /// 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, | 539 | info: AnalysisInfo, |
| 526 | } | 540 | } |
| 527 | 541 | ||
| @@ -580,7 +594,6 @@ impl CeltEncoder { | |||
| 580 | pvq_sign: vec![0; max_n], | 594 | pvq_sign: vec![0; max_n], |
| 581 | urow: vec![0; 1280], | 595 | urow: vec![0; 1280], |
| 582 | last_diag: CeltFrameDiag::default(), | 596 | last_diag: CeltFrameDiag::default(), |
| 583 | - analysis: TonalityAnalysis::new((48000 / upsample) as u32), | ||
| 584 | info: AnalysisInfo::default(), | 597 | info: AnalysisInfo::default(), |
| 585 | } | 598 | } |
| 586 | } | 599 | } |
| @@ -624,7 +637,6 @@ impl CeltEncoder { | |||
| 624 | self.vbr_count = 0; | 637 | self.vbr_count = 0; |
| 625 | self.stereo_saving = 0.0; | 638 | self.stereo_saving = 0.0; |
| 626 | self.spec_avg = 0.0; | 639 | self.spec_avg = 0.0; |
| 627 | - self.analysis.reset(); | ||
| 628 | self.info = AnalysisInfo::default(); | 640 | self.info = AnalysisInfo::default(); |
| 629 | } | 641 | } |
| 630 | 642 | ||
| @@ -638,7 +650,7 @@ impl CeltEncoder { | |||
| 638 | /// postfilter bit, allocation over the coded span only. With | 650 | /// postfilter bit, allocation over the coded span only. With |
| 639 | /// `vbr_rate_bps` set, the frame may be shrunk below that budget | 651 | /// `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. | 652 | /// (constrained VBR); the return value is the final frame size in bytes. |
| 641 | - pub fn encode( | 653 | + pub(crate) fn encode( |
| 642 | &mut self, | 654 | &mut self, |
| 643 | enc: &mut RangeEncoder, | 655 | enc: &mut RangeEncoder, |
| 644 | pcm: &[f32], | 656 | pcm: &[f32], |
| @@ -646,6 +658,7 @@ impl CeltEncoder { | |||
| 646 | start: usize, | 658 | start: usize, |
| 647 | end: usize, | 659 | end: usize, |
| 648 | vbr_rate_bps: u32, | 660 | vbr_rate_bps: u32, |
| 661 | + info: &AnalysisInfo, | ||
| 649 | ) -> Result<usize> { | 662 | ) -> Result<usize> { |
| 650 | let lm: usize = match frame_size { | 663 | let lm: usize = match frame_size { |
| 651 | 120 => 0, | 664 | 120 => 0, |
| @@ -672,14 +685,9 @@ impl CeltEncoder { | |||
| 672 | let end = end.clamp(start + 1, NB_BANDS); | 685 | let end = end.clamp(start + 1, NB_BANDS); |
| 673 | 686 | ||
| 674 | // libopus `opus_encode_native` runs the tonality analysis on the raw | 687 | // libopus `opus_encode_native` runs the tonality analysis on the raw |
| 675 | - // API frame before anything else; the CELT layer's own delay does not | 688 | + // 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 is | 689 | + // `Encoder` and its result is handed down here. |
| 677 | - // libopus's `lsb_depth` default for the float API. | 690 | + 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 | 691 | ||
| 684 | let mut nb_compressed = enc.storage(); | 692 | let mut nb_compressed = enc.storage(); |
| 685 | let mut nb_available = nb_compressed as i32; | 693 | let mut nb_available = nb_compressed as i32; |
| @@ -1031,7 +1039,7 @@ impl CeltEncoder { | |||
| 1031 | let base_target = | 1039 | let base_target = |
| 1032 | vbr_rate + (self.vbr_offset >> lm_diff) - ((40 * c as i32 + 20) << BITRES); | 1040 | vbr_rate + (self.vbr_offset >> lm_diff) - ((40 * c as i32 + 20) << BITRES); |
| 1033 | let mut target = base_target; | 1041 | let mut target = base_target; |
| 1034 | - let (_, _, vbr_tonal, vbr_act) = analysis_params(); | 1042 | + let (_, _, vbr_tonal, vbr_act, _, _) = analysis_params(); |
| 1035 | // compute_vbr (libopus celt_encoder.c:1605-1716), float-mode. | 1043 | // compute_vbr (libopus celt_encoder.c:1605-1716), float-mode. |
| 1036 | // Skipped: activity, tonality, surround_mask (analysis->valid= | 1044 | // Skipped: activity, tonality, surround_mask (analysis->valid= |
| 1037 | // false, has_surround_mask=0, pitch_change=0, lfe=0). The qext | 1045 | // false, has_surround_mask=0, pitch_change=0, lfe=0). The qext |
| @@ -1553,6 +1561,13 @@ impl CeltEncoder { | |||
| 1553 | follower[i] *= 0.5; | 1561 | follower[i] *= 0.5; |
| 1554 | } | 1562 | } |
| 1555 | } | 1563 | } |
| 1564 | + // libopus `celt_encoder.c:1226-1230`: the analysis's per-band | ||
| 1565 | + // leakage boost, in 1/64 dB units, on top of the follower. | ||
| 1566 | + if analysis_params().4 && self.info.valid { | ||
| 1567 | + for i in start..crate::analysis::LEAK_BANDS.min(end) { | ||
| 1568 | + follower[i] += f32::from(self.info.leak_boost[i]) / 64.0; | ||
| 1569 | + } | ||
| 1570 | + } | ||
| 1556 | let mut tot_boost = 0i32; | 1571 | let mut tot_boost = 0i32; |
| 1557 | for i in start..end { | 1572 | for i in start..end { |
| 1558 | let f = follower[i].min(4.0); | 1573 | let f = follower[i].min(4.0); |
crates/ec-opus/src/encoder.rsmodified+111 -4
| @@ -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,17 @@ 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, | ||
| 133 | + /// Whether the detected bandwidth may lower the coded one (`EC_OPUS_BW_DETECT`). | ||
| 134 | + bw_detect: bool, | ||
| 123 | } | 135 | } |
| 124 | 136 | ||
| 125 | /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8, | 137 | /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8, |
| @@ -182,6 +194,10 @@ impl Encoder { | |||
| 182 | align_input: false, | 194 | align_input: false, |
| 183 | hp_mem: [0.0; 2], | 195 | hp_mem: [0.0; 2], |
| 184 | hp_buf: Vec::new(), | 196 | hp_buf: Vec::new(), |
| 197 | + analysis: TonalityAnalysis::new(sample_rate), | ||
| 198 | + info: AnalysisInfo::default(), | ||
| 199 | + analysis_on: crate::celt_enc::analysis_params().0, | ||
| 200 | + bw_detect: crate::celt_enc::analysis_params().5, | ||
| 185 | }; | 201 | }; |
| 186 | // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how | 202 | // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how |
| 187 | // the gate rows at `set_libopus_input_alignment` were produced. | 203 | // the gate rows at `set_libopus_input_alignment` were produced. |
| @@ -191,6 +207,15 @@ impl Encoder { | |||
| 191 | Ok(enc) | 207 | Ok(enc) |
| 192 | } | 208 | } |
| 193 | 209 | ||
| 210 | + /// Turns the tonality analysis on or off for this encoder. It is off | ||
| 211 | + /// unless one of its consumers is switched on (see | ||
| 212 | + /// `celt_enc::analysis_params`), because it costs ~25% of the encoder; | ||
| 213 | + /// turn it on to read `music_prob`/`tonality` back through | ||
| 214 | + /// [`Encoder::last_celt_diag`]. | ||
| 215 | + pub fn set_analysis(&mut self, on: bool) { | ||
| 216 | + self.analysis_on = on; | ||
| 217 | + } | ||
| 218 | + | ||
| 194 | /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and | 219 | /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and |
| 195 | /// `hybrid_choice` make from the application and bitrate; pass `None` to | 220 | /// `hybrid_choice` make from the application and bitrate; pass `None` to |
| 196 | /// restore the automatic pick. Requests this encoder cannot honour | 221 | /// restore the automatic pick. Requests this encoder cannot honour |
| @@ -361,6 +386,8 @@ impl Encoder { | |||
| 361 | self.silk_delay.clear(); | 386 | self.silk_delay.clear(); |
| 362 | self.hp_mem = [0.0; 2]; | 387 | self.hp_mem = [0.0; 2]; |
| 363 | self.final_range = 0; | 388 | self.final_range = 0; |
| 389 | + self.analysis.reset(); | ||
| 390 | + self.info = AnalysisInfo::default(); | ||
| 364 | } | 391 | } |
| 365 | 392 | ||
| 366 | /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) | 393 | /// Whether the application/bitrate (or an explicit [`Encoder::set_mode`]) |
| @@ -591,6 +618,15 @@ impl Encoder { | |||
| 591 | cap: usize, | 618 | cap: usize, |
| 592 | ) -> Result<(u8, &[u8])> { | 619 | ) -> Result<(u8, &[u8])> { |
| 593 | let frame_48k = frame_size * self.upsample; | 620 | let frame_48k = frame_size * self.upsample; |
| 621 | + // libopus `opus_encode_native`: `run_analysis()` runs on the API frame | ||
| 622 | + // before the mode/bandwidth decisions, so the estimator state advances | ||
| 623 | + // on every frame, SILK ones included. 24 is libopus's float-API | ||
| 624 | + // `lsb_depth` default. | ||
| 625 | + self.info = if self.analysis_on { | ||
| 626 | + self.analysis.run(pcm, frame_size, self.channels, 24) | ||
| 627 | + } else { | ||
| 628 | + AnalysisInfo::default() | ||
| 629 | + }; | ||
| 594 | if let Some(fs_khz) = self.silk_choice(frame_48k) { | 630 | if let Some(fs_khz) = self.silk_choice(frame_48k) { |
| 595 | if self.channels == 2 { | 631 | if self.channels == 2 { |
| 596 | Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff); | 632 | Self::zero_stuff_stereo(pcm, frame_size, self.upsample, &mut self.silk_stuff); |
| @@ -766,7 +802,47 @@ impl Encoder { | |||
| 766 | 12000 => Bandwidth::Medium, | 802 | 12000 => Bandwidth::Medium, |
| 767 | _ => Bandwidth::Narrow, | 803 | _ => Bandwidth::Narrow, |
| 768 | }; | 804 | }; |
| 769 | - 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)) | ||
| 770 | } | 846 | } |
| 771 | 847 | ||
| 772 | /// libopus `opus_encoder.c`'s `dc_reject(pcm, 3, ...)`: a 3 Hz one-pole | 848 | /// libopus `opus_encoder.c`'s `dc_reject(pcm, 3, ...)`: a 3 Hz one-pole |
| @@ -947,6 +1023,7 @@ impl Encoder { | |||
| 947 | 17, | 1023 | 17, |
| 948 | bandwidth.celt_end_band(), | 1024 | bandwidth.celt_end_band(), |
| 949 | 0, | 1025 | 0, |
| 1026 | + &self.info, | ||
| 950 | )?; | 1027 | )?; |
| 951 | self.final_range = self.range.range(); | 1028 | self.final_range = self.range.range(); |
| 952 | let payload = &self.range.data()[..n]; | 1029 | let payload = &self.range.data()[..n]; |
| @@ -989,9 +1066,9 @@ impl Encoder { | |||
| 989 | (b.saturating_sub(1).clamp(2, cap), 0) | 1066 | (b.saturating_sub(1).clamp(2, cap), 0) |
| 990 | }; | 1067 | }; |
| 991 | self.range.reset(budget); | 1068 | self.range.reset(budget); |
| 992 | - let n = self | 1069 | + let n = |
| 993 | - .celt | 1070 | + self.celt |
| 994 | - .encode(&mut self.range, pcm, frame_size, 0, end, vbr_rate)?; | 1071 | + .encode(&mut self.range, pcm, frame_size, 0, end, vbr_rate, &self.info)?; |
| 995 | self.final_range = self.range.range(); | 1072 | self.final_range = self.range.range(); |
| 996 | Ok(n) | 1073 | Ok(n) |
| 997 | } | 1074 | } |
| @@ -1001,6 +1078,36 @@ impl Encoder { | |||
| 1001 | mod tests { | 1078 | mod tests { |
| 1002 | use super::*; | 1079 | use super::*; |
| 1003 | 1080 | ||
| 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 | + | ||
| 1004 | /// The private half of the bandwidth decision: the thresholds themselves, | 1111 | /// The private half of the bandwidth decision: the thresholds themselves, |
| 1005 | /// which the TOC config only reports. | 1112 | /// which the TOC config only reports. |
| 1006 | #[test] | 1113 | #[test] |
crates/ec-opus/tests/conformance.rsmodified+15 -0
| @@ -5757,10 +5757,17 @@ 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; |
| 5763 | let mut valid = 0usize; | 5767 | let mut valid = 0usize; |
| 5768 | + // Histogram of the detected bandwidth index, which drives | ||
| 5769 | + // `opus_encoder.c`'s `detected_bandwidth` clamp. | ||
| 5770 | + let mut bw_hist = [0u32; 21]; | ||
| 5764 | for chunk in pcm.chunks_exact(FRAME * CHANNELS) { | 5771 | for chunk in pcm.chunks_exact(FRAME * CHANNELS) { |
| 5765 | enc.encode_float(chunk, FRAME, &mut out).expect("encode"); | 5772 | enc.encode_float(chunk, FRAME, &mut out).expect("encode"); |
| 5766 | let d = enc.last_celt_diag(); | 5773 | let d = enc.last_celt_diag(); |
| @@ -5771,9 +5778,17 @@ fn analysis_music_prob_separates_speech_from_music() { | |||
| 5771 | sum[1] += f64::from(d.tonality); | 5778 | sum[1] += f64::from(d.tonality); |
| 5772 | sum[2] += f64::from(d.tonality_slope); | 5779 | sum[2] += f64::from(d.tonality_slope); |
| 5773 | sum[3] += f64::from(d.activity); | 5780 | sum[3] += f64::from(d.activity); |
| 5781 | + bw_hist[(d.analysis_bandwidth.clamp(0, 20)) as usize] += 1; | ||
| 5774 | } | 5782 | } |
| 5775 | } | 5783 | } |
| 5776 | assert!(valid * 10 > n * 9, "{tag}: analysis valid on only {valid}/{n} frames"); | 5784 | assert!(valid * 10 > n * 9, "{tag}: analysis valid on only {valid}/{n} frames"); |
| 5785 | + let bw: Vec<String> = bw_hist | ||
| 5786 | + .iter() | ||
| 5787 | + .enumerate() | ||
| 5788 | + .filter(|&(_, &c)| c > 0) | ||
| 5789 | + .map(|(i, c)| format!("{i}:{c}")) | ||
| 5790 | + .collect(); | ||
| 5791 | + println!("analysis {tag}: bandwidth histogram {}", bw.join(" ")); | ||
| 5777 | let m = sum.map(|v| v / valid as f64); | 5792 | let m = sum.map(|v| v / valid as f64); |
| 5778 | println!( | 5793 | println!( |
| 5779 | "analysis {tag}: music {:.3} tonality {:.3} slope {:.4} activity {:.3} over {valid}/{n} frames (music={is_music})", | 5794 | "analysis {tag}: music {:.3} tonality {:.3} slope {:.4} activity {:.3} over {valid}/{n} frames (music={is_music})", |
lanes/opus-opusmode-r1.sweep.txtadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +# lane-opusmode r1: EC_OPUS_BW_DETECT=1 (detected-bandwidth clamp) -- byte-identical to shipped | ||
| 2 | +# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1) | ||
| 3 | +# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo | ||
| 4 | +# source kbps ours_kbps ref_kbps rate% corr_ours corr_ref gap Q_ours Q_ref err_ratio minsec_ours minsec_ref drop_ours drop_ref | ||
| 5 | +nik 64 69.1 69.2 -0.1 0.9887 0.9864 -0.0024 -95.23 -154.78 0.708 0.9766 0.9745 0 0 | ||
| 6 | +nik 96 100.9 101.0 -0.1 0.9947 0.9940 -0.0007 -29.86 -31.55 0.985 0.9889 0.9888 0 0 | ||
| 7 | +reelo 64 63.6 63.6 -0.0 0.9893 0.9866 -0.0027 -202.82 -123.36 1.510 0.9702 0.9686 0 0 | ||
| 8 | +reelo 96 93.4 93.9 -0.5 0.9947 0.9937 -0.0009 -114.74 -125.18 0.940 0.9862 0.9854 0 0 | ||
| 9 | +her 64 67.7 67.9 -0.4 0.9834 0.9794 -0.0040 -365.72 -339.00 1.103 0.9477 0.9406 0 0 | ||
| 10 | +her 96 101.0 101.5 -0.5 0.9914 0.9902 -0.0012 -202.07 -191.50 1.051 0.9728 0.9728 0 0 | ||
| 11 | +reell 64 71.3 71.3 -0.0 0.9908 0.9880 -0.0029 -351.70 -128.39 2.697 0.9721 0.9644 0 0 | ||
| 12 | +reell 96 105.3 105.4 -0.0 0.9956 0.9948 -0.0008 -301.83 -29.16 4.499 0.9856 0.9804 0 0 | ||
| 13 | +dl8a 64 65.7 65.8 -0.1 0.9889 0.9865 -0.0025 -227.54 -378.84 0.552 0.9787 0.9723 0 0 | ||
| 14 | +dl8a 96 96.5 96.8 -0.3 0.9942 0.9934 -0.0009 -177.70 -423.47 0.374 0.9881 0.9864 0 0 | ||
| 15 | +hein 64 64.8 64.9 -0.2 0.9888 0.9874 -0.0014 -344.06 -388.31 0.853 0.9318 0.9148 0 0 | ||
| 16 | +hein 96 86.8 86.9 -0.2 0.9946 0.9930 -0.0016 -117.91 -246.46 0.528 0.9689 0.9499 0 0 | ||
lanes/opus-opusmode-r2.sweep.txtadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +# lane-opusmode r2: EC_OPUS_LEAK=1 (dynalloc leak_boost) | ||
| 2 | +# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1) | ||
| 3 | +# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo | ||
| 4 | +# source kbps ours_kbps ref_kbps rate% corr_ours corr_ref gap Q_ours Q_ref err_ratio minsec_ours minsec_ref drop_ours drop_ref | ||
| 5 | +nik 64 69.1 69.2 -0.1 0.9888 0.9864 -0.0024 -95.46 -154.78 0.709 0.9767 0.9745 0 0 | ||
| 6 | +nik 96 100.9 101.0 -0.1 0.9947 0.9940 -0.0007 -29.96 -31.55 0.986 0.9888 0.9888 0 0 | ||
| 7 | +reelo 64 63.6 63.6 -0.0 0.9893 0.9866 -0.0027 -202.82 -123.36 1.510 0.9702 0.9686 0 0 | ||
| 8 | +reelo 96 93.4 93.9 -0.5 0.9947 0.9937 -0.0009 -114.74 -125.18 0.940 0.9862 0.9854 0 0 | ||
| 9 | +her 64 67.7 67.9 -0.4 0.9834 0.9794 -0.0040 -365.79 -339.00 1.103 0.9475 0.9406 0 0 | ||
| 10 | +her 96 101.0 101.5 -0.5 0.9914 0.9902 -0.0012 -202.14 -191.50 1.052 0.9728 0.9728 0 0 | ||
| 11 | +reell 64 71.3 71.3 -0.0 0.9908 0.9880 -0.0029 -351.70 -128.39 2.697 0.9721 0.9644 0 0 | ||
| 12 | +reell 96 105.3 105.4 -0.0 0.9956 0.9948 -0.0008 -301.83 -29.16 4.499 0.9856 0.9804 0 0 | ||
| 13 | +dl8a 64 65.7 65.8 -0.1 0.9889 0.9865 -0.0025 -227.47 -378.84 0.552 0.9787 0.9723 0 0 | ||
| 14 | +dl8a 96 96.6 96.8 -0.3 0.9942 0.9934 -0.0009 -177.70 -423.47 0.374 0.9881 0.9864 0 0 | ||
| 15 | +hein 64 64.8 64.9 -0.2 0.9888 0.9874 -0.0014 -344.06 -388.31 0.853 0.9318 0.9148 0 0 | ||
| 16 | +hein 96 86.8 86.9 -0.2 0.9946 0.9930 -0.0016 -117.94 -246.46 0.528 0.9689 0.9499 0 0 | ||
lanes/opus-opusmode-r3.sweep.txtadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +# lane-opusmode r3: EC_OPUS_BW_DETECT=1 EC_OPUS_VBR_ACT=1 EC_OPUS_TF_K=1.25 (combined arm) | ||
| 2 | +# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1) | ||
| 3 | +# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo | ||
| 4 | +# source kbps ours_kbps ref_kbps rate% corr_ours corr_ref gap Q_ours Q_ref err_ratio minsec_ours minsec_ref drop_ours drop_ref | ||
| 5 | +nik 64 69.1 69.2 -0.1 0.9887 0.9864 -0.0024 -82.60 -154.78 0.651 0.9767 0.9745 0 0 | ||
| 6 | +nik 96 100.9 101.0 -0.1 0.9947 0.9940 -0.0007 -26.70 -31.55 0.957 0.9887 0.9888 0 0 | ||
| 7 | +reelo 64 63.5 63.6 -0.1 0.9893 0.9866 -0.0027 -202.81 -123.36 1.509 0.9699 0.9686 0 0 | ||
| 8 | +reelo 96 93.3 93.9 -0.6 0.9946 0.9937 -0.0008 -112.55 -125.18 0.928 0.9861 0.9854 0 0 | ||
| 9 | +her 64 67.6 67.9 -0.5 0.9833 0.9794 -0.0039 -366.09 -339.00 1.104 0.9472 0.9406 0 0 | ||
| 10 | +her 96 100.8 101.5 -0.7 0.9913 0.9902 -0.0011 -205.98 -191.50 1.071 0.9725 0.9728 0 0 | ||
| 11 | +reell 64 71.3 71.3 -0.0 0.9908 0.9880 -0.0028 -198.89 -128.39 1.440 0.9719 0.9644 0 0 | ||
| 12 | +reell 96 105.3 105.4 -0.0 0.9956 0.9948 -0.0008 -169.83 -29.16 2.516 0.9854 0.9804 0 0 | ||
| 13 | +dl8a 64 65.7 65.8 -0.2 0.9889 0.9865 -0.0024 -220.65 -378.84 0.535 0.9790 0.9723 0 0 | ||
| 14 | +dl8a 96 96.5 96.8 -0.3 0.9942 0.9934 -0.0008 -144.24 -423.47 0.315 0.9879 0.9864 0 0 | ||
| 15 | +hein 64 64.6 64.9 -0.5 0.9888 0.9874 -0.0015 -199.94 -388.31 0.470 0.9299 0.9148 0 0 | ||
| 16 | +hein 96 86.5 86.9 -0.5 0.9946 0.9930 -0.0015 -76.33 -246.46 0.404 0.9678 0.9499 0 0 | ||