diff --git a/crates/ec-opus/src/celt.rs b/crates/ec-opus/src/celt.rs index 7e1623d1..428d5414 100644 --- a/crates/ec-opus/src/celt.rs +++ b/crates/ec-opus/src/celt.rs @@ -254,8 +254,9 @@ pub(crate) const PREEMPH: f32 = 0.850_006_1; pub(crate) const SIG_SCALE: f32 = 32768.0; pub(crate) const SPREAD_NONE: usize = 0; +pub(crate) const SPREAD_LIGHT: usize = 1; pub(crate) const SPREAD_NORMAL: usize = 2; -const SPREAD_AGGRESSIVE: usize = 3; +pub(crate) const SPREAD_AGGRESSIVE: usize = 3; /// `ilog(x)`: index of the highest set bit plus one. #[inline] diff --git a/crates/ec-opus/src/celt_enc.rs b/crates/ec-opus/src/celt_enc.rs index b02c2f2d..5db6e3e1 100644 --- a/crates/ec-opus/src/celt_enc.rs +++ b/crates/ec-opus/src/celt_enc.rs @@ -37,7 +37,8 @@ use ec_core::{Error, Result}; 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, - SHORT_MDCT, SIG_SCALE, SMALL_ENERGY_ICDF, SPREAD_ICDF, SPREAD_NORMAL, TF_SELECT, TRIM_ICDF, + SHORT_MDCT, SIG_SCALE, SMALL_ENERGY_ICDF, SPREAD_AGGRESSIVE, SPREAD_ICDF, SPREAD_LIGHT, + SPREAD_NONE, SPREAD_NORMAL, TF_SELECT, TRIM_ICDF, bitexact_cos, bitexact_log2tan, bits2pulses, cache_index, compute_allocation_encode, compute_qn, deinterleave_hadamard, exp_rotation, frac_mul16, get_pulses, haar1, pulses2bits, unext, @@ -372,6 +373,11 @@ pub struct CeltEncoder { old_band_e: Vec, delayed_intra: f32, consec_transient: u32, + // Spreading decision state (libopus celt_encoder.c:2534-2537). + spread_decision: usize, + tonal_average: i32, + hf_average: i32, + tapset_decision: i32, last_coded_bands: usize, force_intra: bool, // Constrained-VBR reservoir. @@ -422,6 +428,10 @@ impl CeltEncoder { consec_transient: 0, last_coded_bands: 0, force_intra: true, + spread_decision: SPREAD_NORMAL, + tonal_average: 256, + hf_average: 0, + tapset_decision: 0, vbr_reservoir: 0, vbr_drift: 0, vbr_offset: 0, @@ -470,6 +480,10 @@ impl CeltEncoder { self.consec_transient = 0; self.last_coded_bands = 0; self.force_intra = true; + self.spread_decision = SPREAD_NORMAL; + self.tonal_average = 256; + self.hf_average = 0; + self.tapset_decision = 0; self.vbr_reservoir = 0; self.vbr_drift = 0; self.vbr_offset = 0; @@ -664,7 +678,7 @@ impl CeltEncoder { // `TF_ANALYSIS`: run the libopus Viterbi tf search when there are // enough bits; otherwise fall back to the no-analysis default (raw // `is_transient` per band codes "no tf change" under tf_select=0). - const TF_ANALYSIS: bool = false; + const TF_ANALYSIS: bool = true; let tf_select = if TF_ANALYSIS && effective_bytes >= 15 * c as i32 { let lambda = (80i32).max(20480 / effective_bytes + 2); let mut importance = [0i32; NB_BANDS]; @@ -708,22 +722,33 @@ impl CeltEncoder { // --- tf encode ------------------------------------------------------ self.tf_encode(enc, start, end, is_transient, lm, tf_select, nb_compressed); - // --- Spread: fixed NORMAL ------------------------------------------- + // --- Dynalloc analysis (offsets + spread_weight) -------------------- + self.offsets = [0; NB_BANDS]; + let mut spread_weight = [0i32; NB_BANDS]; + self.dynalloc_analysis( + start, end, c, lm, is_transient, effective_bytes, &mut spread_weight, + ); + + // --- Spread decision (libopus celt_encoder.c:1933-1977) -------------- + // No LFE, no hybrid, no complexity field (treated as ≥ 3): the only + // guards that apply are shortBlocks and nbAvailableBytes < 10*C. if enc.tell() as i32 + 4 <= total_bits { - enc.enc_icdf(SPREAD_NORMAL, &SPREAD_ICDF, 5); + if short_blocks != 0 || nb_available < 10 * c as i32 { + self.spread_decision = SPREAD_NORMAL; + } else { + self.spread_decision = + self.spreading_decision(end, c, lm, &spread_weight); + } + enc.enc_icdf(self.spread_decision, &SPREAD_ICDF, 5); } - // --- Caps + dynalloc ------------------------------------------------ + // --- Caps ------------------------------------------------------------ for i in 0..NB_BANDS { let bw = (E_BANDS[i + 1] - E_BANDS[i]) << lm; self.caps[i] = ((CACHE_CAPS[NB_BANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * bw as i32) >> 2; } - self.offsets = [0; NB_BANDS]; - if effective_bytes > 50 && lm >= 1 { - self.dynalloc_analysis(start, end, c, lm, is_transient, effective_bytes); - } let mut dynalloc_logp = 6u32; let total_bits_frac = total_bits << BITRES; let mut total_boost = 0i32; @@ -969,7 +994,7 @@ impl CeltEncoder { start, end, short_blocks, - SPREAD_NORMAL, + self.spread_decision, dual_stereo, intensity, (nb_compressed as i32 * (8 << BITRES)) - anti_collapse_rsv, @@ -1146,6 +1171,7 @@ impl CeltEncoder { lm: usize, is_transient: bool, effective_bytes: i32, + spread_weight: &mut [i32; NB_BANDS], ) { const LSB_DEPTH: f32 = 24.0; let mut noise_floor = [0.0f32; NB_BANDS]; @@ -1153,6 +1179,42 @@ impl CeltEncoder { noise_floor[i] = 0.0625 * LOG_N[i] as f32 + 0.5 + (9.0 - LSB_DEPTH) - E_MEANS[i] + 0.0062 * ((i + 5) * (i + 5)) as f32; } + // maxDepth = max(bandLogE - noise_floor) across channels (libopus 995-999). + let mut max_depth = -31.9f32; + for ch in 0..c { + for i in 0..end { + max_depth = max_depth.max(self.band_log_e[ch * NB_BANDS + i] - noise_floor[i]); + } + } + // Simple masking model for spread_weight (libopus celt_encoder.c:1000-1035). + let mut mask = [0.0f32; NB_BANDS]; + for i in 0..end { + mask[i] = self.band_log_e[i] - noise_floor[i]; + } + if c == 2 { + for i in 0..end { + mask[i] = mask[i].max(self.band_log_e[NB_BANDS + i] - noise_floor[i]); + } + } + let mut sig = [0.0f32; NB_BANDS]; + sig[..end].copy_from_slice(&mask[..end]); + for i in 1..end { + mask[i] = mask[i].max(mask[i - 1] - 2.0); + } + for i in (0..end - 1).rev() { + mask[i] = mask[i].max(mask[i + 1] - 3.0); + } + for i in 0..end { + // SMR: mask is never more than 12 below the peak and never below the + // noise floor. + let smr = sig[i] - 0.0_f32.max(max_depth - 12.0).max(mask[i]); + let shift = (5).min(0.max(-((smr + 0.5).floor() as i32))); + spread_weight[i] = 32 >> shift; + } + // Dynamic allocation can't make us bust the budget (libopus 1036-1037). + if !(effective_bytes > 50 && lm >= 1) { + return; + } let median3 = |a: &[f32]| -> f32 { let (x, y, z) = (a[0], a[1], a[2]); x.max(y).min(z).max(x.min(y)) @@ -1246,6 +1308,90 @@ impl CeltEncoder { } } + /// libopus `spreading_decision` (bands.c:479-570): classifies the current + /// frame's spectral shape as `SPREAD_NONE`/`SPREAD_LIGHT`/`SPREAD_NORMAL`/ + /// `SPREAD_AGGRESSIVE` by counting how concentrated the normalized band + /// coefficients are, weighted by the masking-based `spread_weight` from + /// `dynalloc_analysis`. Maintains `tonal_average` (recursive averaging) + /// and applies hysteresis against the previous decision. + /// + /// `update_hf` is always false here (no pitch prefilter), so the + /// `hf_average`/`tapset_decision` state is carried but never updated — + /// matching libopus with `pf_on = false`. + fn spreading_decision( + &mut self, + end: usize, + c: usize, + lm: usize, + spread_weight: &[i32; NB_BANDS], + ) -> usize { + let m = 1usize << lm; + let n0 = SHORT_MDCT << lm; // = M * shortMdctSize + // Last band too narrow: nothing to spread. + if m * (E_BANDS[end] - E_BANDS[end - 1]) <= 8 { + return SPREAD_NONE; + } + let mut sum = 0i32; + let mut nb_bands = 0i32; + for ch in 0..c { + for i in 0..end { + let n = m * (E_BANDS[i + 1] - E_BANDS[i]); + if n <= 8 { + continue; + } + let base = ch * n0 + m * E_BANDS[i]; + let x = &self.x[base..base + n]; + let mut tcount = [0i32; 3]; + for j in 0..n { + // Float-mode: x2N = x[j]^2 * N; thresholds are the literal + // QCONST16 values (0.25, 0.0625, 0.015625). + let x2n = x[j] * x[j] * n as f32; + if x2n < 0.25 { + tcount[0] += 1; + } + if x2n < 0.0625 { + tcount[1] += 1; + } + if x2n < 0.015625 { + tcount[2] += 1; + } + } + // hf_sum accumulation is only used when update_hf is true + // (prefilter on), which never happens here. The branch is + // kept for structural fidelity but the result is unused. + let _hf_sum_contrib = if i > NB_BANDS - 4 { + 32 * (tcount[1] + tcount[0]) / n as i32 + } else { + 0 + }; + let tmp = (2 * tcount[2] >= n as i32) as i32 + + (2 * tcount[1] >= n as i32) as i32 + + (2 * tcount[0] >= n as i32) as i32; + sum += tmp * spread_weight[i]; + nb_bands += spread_weight[i]; + } + } + if nb_bands == 0 { + return self.spread_decision; + } + let mut s = (sum << 8) / nb_bands; + // Recursive averaging. + s = (s + self.tonal_average) >> 1; + self.tonal_average = s; + // Hysteresis against the last decision. + let last = self.spread_decision as i32; + s = (3 * s + (((3 - last) << 7) + 64) + 2) >> 2; + if s < 80 { + SPREAD_AGGRESSIVE + } else if s < 256 { + SPREAD_NORMAL + } else if s < 384 { + SPREAD_LIGHT + } else { + SPREAD_NONE + } + } + fn compute_mdcts(&mut self, short_blocks: usize, lm: usize, n: usize, c: usize) { let stride = n + OVERLAP; let (n2, blocks, plan_lm) = if short_blocks != 0 { diff --git a/lanes/opus-sp-r1.report.md b/lanes/opus-sp-r1.report.md new file mode 100644 index 00000000..3ce8f3f2 --- /dev/null +++ b/lanes/opus-sp-r1.report.md @@ -0,0 +1,18 @@ +# lane-opus-sp r1 — spreading_decision port + TF analysis on + +## What +- `celt_enc.rs`: port of libopus `spreading_decision` (tonal_average / hf_average / tapset state, `spread_weight` from dynalloc mask). Spread histogram now matches libopus on the 14-row sweep. +- `TF_ANALYSIS = true` (was false): libopus-style tf_analysis drives tf_res instead of the `tf_res = is_transient` default. + +## Gate (14 rows, equal size, vs lanes/opus-sb-r1.sweep.txt) +- corr gap delta per row: |Δ| ≤ .0002 (reelm@64 +.0037 → +.0039; hein@96 −.0003 → −.0002); all others unchanged to 4 dp. +- err_ratio down where it mattered: reelm@64 .69 → .63, her@96 1.21 → 1.07. +- RATE GATE: all rows within ±5% (max −1.8%). DROPOUT GATE: 0 ours-only. +- Rows: lanes/opus-sp-r1.sweep.txt (EVIDENCE: scratchpad lanes/opus-sp-r2.gate14.log, 723 s). + +## Suite +`cargo test -p ec-opus --release`: 34 + 27 passed, 9 ignored (sweep tests). + +## Residue (unchanged) +- reelm@64 +.0039, hein@64 +.0022 corr behind libopus. +- Next divergence: intensity band (ours 8160 Hz vs libopus 6720 Hz); short-frame trim ours 0–2 vs libopus 0. diff --git a/lanes/opus-sp-r1.sweep.txt b/lanes/opus-sp-r1.sweep.txt new file mode 100644 index 00000000..8adbcfd3 --- /dev/null +++ b/lanes/opus-sp-r1.sweep.txt @@ -0,0 +1,16 @@ +nik@64k: ref 69.2 ours 68.7 kbps (-0.7%), corr o=0.9883 r=0.9864 gap=-0.0020, Q o=-126.20 r=-154.78, err_ratio 0.854, minsec o=0.9765 r=0.9745, drop o=0 r=0 +nik@96k: ref 101.0 ours 100.6 kbps (-0.4%), corr o=0.9947 r=0.9940 gap=-0.0006, Q o=-49.40 r=-31.55, err_ratio 1.162, minsec o=0.9888 r=0.9888, drop o=0 r=0 +reelo@64k: ref 63.6 ours 63.5 kbps (-0.1%), corr o=0.9884 r=0.9866 gap=-0.0017, Q o=-211.09 r=-123.36, err_ratio 1.569, minsec o=0.9629 r=0.9686, drop o=0 r=0 +reelo@96k: ref 93.9 ours 93.8 kbps (-0.1%), corr o=0.9945 r=0.9937 gap=-0.0008, Q o=-127.38 r=-125.18, err_ratio 1.013, minsec o=0.9855 r=0.9854, drop o=0 r=0 +her@64k: ref 67.9 ours 67.4 kbps (-0.8%), corr o=0.9826 r=0.9794 gap=-0.0031, Q o=-365.27 r=-339.00, err_ratio 1.101, minsec o=0.9450 r=0.9406, drop o=0 r=0 +her@96k: ref 101.5 ours 100.6 kbps (-0.9%), corr o=0.9911 r=0.9902 gap=-0.0008, Q o=-206.04 r=-191.50, err_ratio 1.071, minsec o=0.9715 r=0.9728, drop o=0 r=0 +reell@64k: ref 71.3 ours 71.3 kbps (-0.1%), corr o=0.9907 r=0.9880 gap=-0.0028, Q o=-323.58 r=-128.39, err_ratio 2.429, minsec o=0.9704 r=0.9644, drop o=0 r=0 +reell@96k: ref 105.4 ours 105.3 kbps (-0.0%), corr o=0.9956 r=0.9948 gap=-0.0008, Q o=-156.53 r=-29.16, err_ratio 2.349, minsec o=0.9858 r=0.9804, drop o=0 r=0 +reelm@64k: ref 63.3 ours 62.3 kbps (-1.6%), corr o=0.9821 r=0.9859 gap=+0.0039, Q o=-270.53 r=-392.46, err_ratio 0.632, minsec o=0.9101 r=0.9100, drop o=0 r=0 +reelm@96k: ref 84.8 ours 83.6 kbps (-1.5%), corr o=0.9920 r=0.9920 gap=-0.0000, Q o=-139.95 r=-231.16, err_ratio 0.640, minsec o=0.9617 r=0.9511, drop o=0 r=0 +dl8a@64k: ref 65.8 ours 65.6 kbps (-0.3%), corr o=0.9881 r=0.9865 gap=-0.0016, Q o=-276.58 r=-378.84, err_ratio 0.679, minsec o=0.9744 r=0.9723, drop o=0 r=0 +dl8a@96k: ref 96.8 ours 96.1 kbps (-0.8%), corr o=0.9940 r=0.9934 gap=-0.0006, Q o=-193.52 r=-423.47, err_ratio 0.404, minsec o=0.9860 r=0.9864, drop o=0 r=0 +hein@64k: ref 64.9 ours 63.8 kbps (-1.7%), corr o=0.9852 r=0.9874 gap=+0.0022, Q o=-284.04 r=-388.31, err_ratio 0.677, minsec o=0.9124 r=0.9148, drop o=0 r=0 +hein@96k: ref 86.9 ours 85.4 kbps (-1.8%), corr o=0.9933 r=0.9930 gap=-0.0002, Q o=-153.23 r=-246.46, err_ratio 0.643, minsec o=0.9618 r=0.9499, drop o=0 r=0 +RATE GATE: all rows within ±5% +DROPOUT GATE: passed (no ours-only dropouts)