forge
Explore
Log in

Don't you dare go Hollow

Port libopus spreading_decision (tonal/hf averages, tapset, spread_weight)

Browse files at this commit

7a1f515445999899311608a1441527af1eb6e2b1Ahmet Kaan GümüşParent: e3d6c0e
  • feat
    • port libopus spreading_decision (tonal/hf averages, tapset, spread_weight)
Show full message
feat(opus-sp/r1): port libopus spreading_decision (tonal/hf averages, tapset, spread_weight)

Decoder-seen spread histogram on long frames, ours vs libopus: reelm [0,12,3442,739]
vs [0,0,3303,910]; hein [1,20,3800,151] vs [0,0,3809,138] (was a constant SPREAD_NORMAL).
Gate reelm,hein,her,reell: corr within .0001 of lane-opus-sb, reelm@64 err_ratio .69 -> .65.
crates/ec-opus/src/celt.rsmodified+2 -1
@@ -254,8 +254,9 @@ pub(crate) const PREEMPH: f32 = 0.850_006_1;
254 pub(crate) const SIG_SCALE: f32 = 32768.0;254 pub(crate) const SIG_SCALE: f32 = 32768.0;
255 255
256 pub(crate) const SPREAD_NONE: usize = 0;256 pub(crate) const SPREAD_NONE: usize = 0;
257+pub(crate) const SPREAD_LIGHT: usize = 1;
257 pub(crate) const SPREAD_NORMAL: usize = 2;258 pub(crate) const SPREAD_NORMAL: usize = 2;
258-const SPREAD_AGGRESSIVE: usize = 3;259+pub(crate) const SPREAD_AGGRESSIVE: usize = 3;
259 260
260 /// `ilog(x)`: index of the highest set bit plus one.261 /// `ilog(x)`: index of the highest set bit plus one.
261 #[inline]262 #[inline]
crates/ec-opus/src/celt_enc.rsmodified+155 -9
@@ -37,7 +37,8 @@ use ec_core::{Error, Result};
37 use crate::celt::{37 use crate::celt::{
38 self, BETA_COEF, BETA_INTRA, BITRES, CACHE_CAPS, E_BANDS, E_MEANS, E_PROB_MODEL, LOG_N,38 self, BETA_COEF, BETA_INTRA, BITRES, CACHE_CAPS, E_BANDS, E_MEANS, E_PROB_MODEL, LOG_N,
39 MAX_FINE_BITS, NB_BANDS, OVERLAP, PRED_COEF, PREEMPH, QTHETA_OFFSET, QTHETA_OFFSET_TWOPHASE,39 MAX_FINE_BITS, NB_BANDS, OVERLAP, PRED_COEF, PREEMPH, QTHETA_OFFSET, QTHETA_OFFSET_TWOPHASE,
40- SHORT_MDCT, SIG_SCALE, SMALL_ENERGY_ICDF, SPREAD_ICDF, SPREAD_NORMAL, TF_SELECT, TRIM_ICDF,40+ SHORT_MDCT, SIG_SCALE, SMALL_ENERGY_ICDF, SPREAD_AGGRESSIVE, SPREAD_ICDF, SPREAD_LIGHT,
41+ SPREAD_NONE, SPREAD_NORMAL, TF_SELECT, TRIM_ICDF,
41 bitexact_cos, bitexact_log2tan, bits2pulses, cache_index, compute_allocation_encode,42 bitexact_cos, bitexact_log2tan, bits2pulses, cache_index, compute_allocation_encode,
42 compute_qn, deinterleave_hadamard, exp_rotation, frac_mul16, get_pulses, haar1, pulses2bits,43 compute_qn, deinterleave_hadamard, exp_rotation, frac_mul16, get_pulses, haar1, pulses2bits,
43 unext,44 unext,
@@ -372,6 +373,11 @@ pub struct CeltEncoder {
372 old_band_e: Vec<f32>,373 old_band_e: Vec<f32>,
373 delayed_intra: f32,374 delayed_intra: f32,
374 consec_transient: u32,375 consec_transient: u32,
376+ // Spreading decision state (libopus celt_encoder.c:2534-2537).
377+ spread_decision: usize,
378+ tonal_average: i32,
379+ hf_average: i32,
380+ tapset_decision: i32,
375 last_coded_bands: usize,381 last_coded_bands: usize,
376 force_intra: bool,382 force_intra: bool,
377 // Constrained-VBR reservoir.383 // Constrained-VBR reservoir.
@@ -422,6 +428,10 @@ impl CeltEncoder {
422 consec_transient: 0,428 consec_transient: 0,
423 last_coded_bands: 0,429 last_coded_bands: 0,
424 force_intra: true,430 force_intra: true,
431+ spread_decision: SPREAD_NORMAL,
432+ tonal_average: 256,
433+ hf_average: 0,
434+ tapset_decision: 0,
425 vbr_reservoir: 0,435 vbr_reservoir: 0,
426 vbr_drift: 0,436 vbr_drift: 0,
427 vbr_offset: 0,437 vbr_offset: 0,
@@ -470,6 +480,10 @@ impl CeltEncoder {
470 self.consec_transient = 0;480 self.consec_transient = 0;
471 self.last_coded_bands = 0;481 self.last_coded_bands = 0;
472 self.force_intra = true;482 self.force_intra = true;
483+ self.spread_decision = SPREAD_NORMAL;
484+ self.tonal_average = 256;
485+ self.hf_average = 0;
486+ self.tapset_decision = 0;
473 self.vbr_reservoir = 0;487 self.vbr_reservoir = 0;
474 self.vbr_drift = 0;488 self.vbr_drift = 0;
475 self.vbr_offset = 0;489 self.vbr_offset = 0;
@@ -708,22 +722,33 @@ impl CeltEncoder {
708 // --- tf encode ------------------------------------------------------722 // --- tf encode ------------------------------------------------------
709 self.tf_encode(enc, start, end, is_transient, lm, tf_select, nb_compressed);723 self.tf_encode(enc, start, end, is_transient, lm, tf_select, nb_compressed);
710 724
711- // --- Spread: fixed NORMAL -------------------------------------------725+ // --- Dynalloc analysis (offsets + spread_weight) --------------------
726+ self.offsets = [0; NB_BANDS];
727+ let mut spread_weight = [0i32; NB_BANDS];
728+ self.dynalloc_analysis(
729+ start, end, c, lm, is_transient, effective_bytes, &mut spread_weight,
730+ );
731+
732+ // --- Spread decision (libopus celt_encoder.c:1933-1977) --------------
733+ // No LFE, no hybrid, no complexity field (treated as ≥ 3): the only
734+ // guards that apply are shortBlocks and nbAvailableBytes < 10*C.
712 if enc.tell() as i32 + 4 <= total_bits {735 if enc.tell() as i32 + 4 <= total_bits {
713- enc.enc_icdf(SPREAD_NORMAL, &SPREAD_ICDF, 5);736+ if short_blocks != 0 || nb_available < 10 * c as i32 {
737+ self.spread_decision = SPREAD_NORMAL;
738+ } else {
739+ self.spread_decision =
740+ self.spreading_decision(end, c, lm, &spread_weight);
741+ }
742+ enc.enc_icdf(self.spread_decision, &SPREAD_ICDF, 5);
714 }743 }
715 744
716- // --- Caps + dynalloc ------------------------------------------------745+ // --- Caps ------------------------------------------------------------
717 for i in 0..NB_BANDS {746 for i in 0..NB_BANDS {
718 let bw = (E_BANDS[i + 1] - E_BANDS[i]) << lm;747 let bw = (E_BANDS[i + 1] - E_BANDS[i]) << lm;
719 self.caps[i] =748 self.caps[i] =
720 ((CACHE_CAPS[NB_BANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * bw as i32)749 ((CACHE_CAPS[NB_BANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * bw as i32)
721 >> 2;750 >> 2;
722 }751 }
723- self.offsets = [0; NB_BANDS];
724- if effective_bytes > 50 && lm >= 1 {
725- self.dynalloc_analysis(start, end, c, lm, is_transient, effective_bytes);
726- }
727 let mut dynalloc_logp = 6u32;752 let mut dynalloc_logp = 6u32;
728 let total_bits_frac = total_bits << BITRES;753 let total_bits_frac = total_bits << BITRES;
729 let mut total_boost = 0i32;754 let mut total_boost = 0i32;
@@ -969,7 +994,7 @@ impl CeltEncoder {
969 start,994 start,
970 end,995 end,
971 short_blocks,996 short_blocks,
972- SPREAD_NORMAL,997+ self.spread_decision,
973 dual_stereo,998 dual_stereo,
974 intensity,999 intensity,
975 (nb_compressed as i32 * (8 << BITRES)) - anti_collapse_rsv,1000 (nb_compressed as i32 * (8 << BITRES)) - anti_collapse_rsv,
@@ -1146,6 +1171,7 @@ impl CeltEncoder {
1146 lm: usize,1171 lm: usize,
1147 is_transient: bool,1172 is_transient: bool,
1148 effective_bytes: i32,1173 effective_bytes: i32,
1174+ spread_weight: &mut [i32; NB_BANDS],
1149 ) {1175 ) {
1150 const LSB_DEPTH: f32 = 24.0;1176 const LSB_DEPTH: f32 = 24.0;
1151 let mut noise_floor = [0.0f32; NB_BANDS];1177 let mut noise_floor = [0.0f32; NB_BANDS];
@@ -1153,6 +1179,42 @@ impl CeltEncoder {
1153 noise_floor[i] = 0.0625 * LOG_N[i] as f32 + 0.5 + (9.0 - LSB_DEPTH) - E_MEANS[i]1179 noise_floor[i] = 0.0625 * LOG_N[i] as f32 + 0.5 + (9.0 - LSB_DEPTH) - E_MEANS[i]
1154 + 0.0062 * ((i + 5) * (i + 5)) as f32;1180 + 0.0062 * ((i + 5) * (i + 5)) as f32;
1155 }1181 }
1182+ // maxDepth = max(bandLogE - noise_floor) across channels (libopus 995-999).
1183+ let mut max_depth = -31.9f32;
1184+ for ch in 0..c {
1185+ for i in 0..end {
1186+ max_depth = max_depth.max(self.band_log_e[ch * NB_BANDS + i] - noise_floor[i]);
1187+ }
1188+ }
1189+ // Simple masking model for spread_weight (libopus celt_encoder.c:1000-1035).
1190+ let mut mask = [0.0f32; NB_BANDS];
1191+ for i in 0..end {
1192+ mask[i] = self.band_log_e[i] - noise_floor[i];
1193+ }
1194+ if c == 2 {
1195+ for i in 0..end {
1196+ mask[i] = mask[i].max(self.band_log_e[NB_BANDS + i] - noise_floor[i]);
1197+ }
1198+ }
1199+ let mut sig = [0.0f32; NB_BANDS];
1200+ sig[..end].copy_from_slice(&mask[..end]);
1201+ for i in 1..end {
1202+ mask[i] = mask[i].max(mask[i - 1] - 2.0);
1203+ }
1204+ for i in (0..end - 1).rev() {
1205+ mask[i] = mask[i].max(mask[i + 1] - 3.0);
1206+ }
1207+ for i in 0..end {
1208+ // SMR: mask is never more than 12 below the peak and never below the
1209+ // noise floor.
1210+ let smr = sig[i] - 0.0_f32.max(max_depth - 12.0).max(mask[i]);
1211+ let shift = (5).min(0.max(-((smr + 0.5).floor() as i32)));
1212+ spread_weight[i] = 32 >> shift;
1213+ }
1214+ // Dynamic allocation can't make us bust the budget (libopus 1036-1037).
1215+ if !(effective_bytes > 50 && lm >= 1) {
1216+ return;
1217+ }
1156 let median3 = |a: &[f32]| -> f32 {1218 let median3 = |a: &[f32]| -> f32 {
1157 let (x, y, z) = (a[0], a[1], a[2]);1219 let (x, y, z) = (a[0], a[1], a[2]);
1158 x.max(y).min(z).max(x.min(y))1220 x.max(y).min(z).max(x.min(y))
@@ -1246,6 +1308,90 @@ impl CeltEncoder {
1246 }1308 }
1247 }1309 }
1248 1310
1311+ /// libopus `spreading_decision` (bands.c:479-570): classifies the current
1312+ /// frame's spectral shape as `SPREAD_NONE`/`SPREAD_LIGHT`/`SPREAD_NORMAL`/
1313+ /// `SPREAD_AGGRESSIVE` by counting how concentrated the normalized band
1314+ /// coefficients are, weighted by the masking-based `spread_weight` from
1315+ /// `dynalloc_analysis`. Maintains `tonal_average` (recursive averaging)
1316+ /// and applies hysteresis against the previous decision.
1317+ ///
1318+ /// `update_hf` is always false here (no pitch prefilter), so the
1319+ /// `hf_average`/`tapset_decision` state is carried but never updated —
1320+ /// matching libopus with `pf_on = false`.
1321+ fn spreading_decision(
1322+ &mut self,
1323+ end: usize,
1324+ c: usize,
1325+ lm: usize,
1326+ spread_weight: &[i32; NB_BANDS],
1327+ ) -> usize {
1328+ let m = 1usize << lm;
1329+ let n0 = SHORT_MDCT << lm; // = M * shortMdctSize
1330+ // Last band too narrow: nothing to spread.
1331+ if m * (E_BANDS[end] - E_BANDS[end - 1]) <= 8 {
1332+ return SPREAD_NONE;
1333+ }
1334+ let mut sum = 0i32;
1335+ let mut nb_bands = 0i32;
1336+ for ch in 0..c {
1337+ for i in 0..end {
1338+ let n = m * (E_BANDS[i + 1] - E_BANDS[i]);
1339+ if n <= 8 {
1340+ continue;
1341+ }
1342+ let base = ch * n0 + m * E_BANDS[i];
1343+ let x = &self.x[base..base + n];
1344+ let mut tcount = [0i32; 3];
1345+ for j in 0..n {
1346+ // Float-mode: x2N = x[j]^2 * N; thresholds are the literal
1347+ // QCONST16 values (0.25, 0.0625, 0.015625).
1348+ let x2n = x[j] * x[j] * n as f32;
1349+ if x2n < 0.25 {
1350+ tcount[0] += 1;
1351+ }
1352+ if x2n < 0.0625 {
1353+ tcount[1] += 1;
1354+ }
1355+ if x2n < 0.015625 {
1356+ tcount[2] += 1;
1357+ }
1358+ }
1359+ // hf_sum accumulation is only used when update_hf is true
1360+ // (prefilter on), which never happens here. The branch is
1361+ // kept for structural fidelity but the result is unused.
1362+ let _hf_sum_contrib = if i > NB_BANDS - 4 {
1363+ 32 * (tcount[1] + tcount[0]) / n as i32
1364+ } else {
1365+ 0
1366+ };
1367+ let tmp = (2 * tcount[2] >= n as i32) as i32
1368+ + (2 * tcount[1] >= n as i32) as i32
1369+ + (2 * tcount[0] >= n as i32) as i32;
1370+ sum += tmp * spread_weight[i];
1371+ nb_bands += spread_weight[i];
1372+ }
1373+ }
1374+ if nb_bands == 0 {
1375+ return self.spread_decision;
1376+ }
1377+ let mut s = (sum << 8) / nb_bands;
1378+ // Recursive averaging.
1379+ s = (s + self.tonal_average) >> 1;
1380+ self.tonal_average = s;
1381+ // Hysteresis against the last decision.
1382+ let last = self.spread_decision as i32;
1383+ s = (3 * s + (((3 - last) << 7) + 64) + 2) >> 2;
1384+ if s < 80 {
1385+ SPREAD_AGGRESSIVE
1386+ } else if s < 256 {
1387+ SPREAD_NORMAL
1388+ } else if s < 384 {
1389+ SPREAD_LIGHT
1390+ } else {
1391+ SPREAD_NONE
1392+ }
1393+ }
1394+
1249 fn compute_mdcts(&mut self, short_blocks: usize, lm: usize, n: usize, c: usize) {1395 fn compute_mdcts(&mut self, short_blocks: usize, lm: usize, n: usize, c: usize) {
1250 let stride = n + OVERLAP;1396 let stride = n + OVERLAP;
1251 let (n2, blocks, plan_lm) = if short_blocks != 0 {1397 let (n2, blocks, plan_lm) = if short_blocks != 0 {