forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-opus-vbr': libopus compute_vbr ported whole

Browse files at this commit

187c193e87b17fd4b1f989dda7d8cdbc9729f112Ahmet Kaan GümüşParent: 730a563a31c8b1
14-row library gate: ours ahead of libopus on every row at equal size
(reelm@64 +.0038 -> -.0007, hein@64 +.0022 -> -.0014); rate within -1%.
TF boost kept x1 by measurement (report in lanes/opus-vbr-r1.report.md).
crates/ec-opus/src/celt_enc.rsmodified+108 -58
@@ -385,6 +385,11 @@ pub struct CeltEncoder {
385385 vbr_drift: i32,
386386 vbr_offset: i32,
387387 vbr_count: i32,
388+ /// libopus `st->stereo_saving` — mid/side bit-saving estimate (Q8 in C,
389+ /// plain f32 here), updated in `alloc_trim_analysis`.
390+ stereo_saving: f32,
391+ /// libopus `st->spec_avg` — temporal-VBR follower average, updated each frame.
392+ spec_avg: f32,
388393 // Per-frame scratch, allocated once.
389394 in_buf: Vec<f32>,
390395 freq: Vec<f32>,
@@ -438,6 +443,8 @@ impl CeltEncoder {
438443 vbr_drift: 0,
439444 vbr_offset: 0,
440445 vbr_count: 0,
446+ stereo_saving: 0.0,
447+ spec_avg: 0.0,
441448 in_buf: vec![0.0; channels * (max_n + OVERLAP)],
442449 freq: vec![0.0; channels * max_n],
443450 x: vec![0.0; channels * max_n],
@@ -491,6 +498,8 @@ impl CeltEncoder {
491498 self.vbr_drift = 0;
492499 self.vbr_offset = 0;
493500 self.vbr_count = 0;
501+ self.stereo_saving = 0.0;
502+ self.spec_avg = 0.0;
494503 }
495504
496505 /// Encodes one frame of interleaved `f32` (`frame_size` samples per
@@ -728,7 +737,7 @@ impl CeltEncoder {
728737 // --- Dynalloc analysis (offsets + spread_weight) --------------------
729738 self.offsets = [0; NB_BANDS];
730739 let mut spread_weight = [0i32; NB_BANDS];
731- self.dynalloc_analysis(
740+ let max_depth = self.dynalloc_analysis(
732741 start, end, c, lm, is_transient, effective_bytes, &mut spread_weight,
733742 );
734743
@@ -782,6 +791,19 @@ impl CeltEncoder {
782791 self.offsets[i] = boost;
783792 }
784793
794+ // --- Intensity decision (libopus celt_encoder.c:2392-2407) -------
795+ // Moved before alloc_trim so alloc_trim_analysis can use
796+ // self.intensity in the stereo_saving minXC loop.
797+ let overhead = (40 * c as i32 + 20) * ((400 >> lm) - 50);
798+ let mut equiv_rate = ((nb_compressed as i32 * 8 * 50) << (3 - lm)) - overhead;
799+ if vbr_rate_bps > 0 {
800+ equiv_rate = equiv_rate.min(vbr_rate_bps as i32 - overhead);
801+ }
802+ if c == 2 {
803+ self.intensity_decision(nb_compressed, c, lm, vbr_rate_bps);
804+ self.intensity = self.intensity.clamp(start, end);
805+ }
806+
785807 // --- Allocation trim ------------------------------------------------
786808 let mut alloc_trim = 5i32;
787809 if tell_frac + (6 << BITRES) <= total_bits_frac - total_boost {
@@ -790,72 +812,79 @@ impl CeltEncoder {
790812 tell_frac = enc.tell_frac() as i32;
791813 }
792814
815+ // --- Temporal VBR (libopus celt_encoder.c:2187-2204) -------------
816+ // lfe=0 so always computed. In float mode SHR32/SHL32/QCONST32 are
817+ // identity, so follow/frame_avg/temporal_vbr are raw floats.
818+ let temporal_vbr = {
819+ let mut follow = -10.0f32;
820+ let mut frame_avg = 0.0f32;
821+ let offset = if short_blocks != 0 { 0.5 * lm as f32 } else { 0.0 };
822+ for i in start..end {
823+ follow = (follow - 1.0).max(self.band_log_e[i] - offset);
824+ if c == 2 {
825+ follow = follow.max(self.band_log_e[i + NB_BANDS] - offset);
826+ }
827+ frame_avg += follow;
828+ }
829+ frame_avg /= (end - start) as f32;
830+ let tvbr = (frame_avg - self.spec_avg).clamp(-1.5, 3.0);
831+ self.spec_avg += 0.02 * tvbr;
832+ tvbr
833+ };
834+
793835 // --- Constrained VBR ------------------------------------------------
794836 if vbr_rate > 0 {
795837 let lm_diff = 3 - lm as i32;
796838 let base_target =
797839 vbr_rate + (self.vbr_offset >> lm_diff) - ((40 * c as i32 + 20) << BITRES);
798840 let mut target = base_target;
799- // compute_vbr shaping (libopus celt_encoder.c:1605-1716), minus the
800- // terms that need tonality/tf analysis this encoder does not run.
801- let coded_bands = end - 1;
802- let intensity_est = if c == 2 {
803- self.intensity_decision(nb_compressed, c, lm, vbr_rate_bps);
804- self.intensity.clamp(start, coded_bands)
841+ // compute_vbr (libopus celt_encoder.c:1605-1716), float-mode.
842+ // Skipped: activity, tonality, surround_mask (analysis->valid=
843+ // false, has_surround_mask=0, pitch_change=0, lfe=0). The qext
844+ // 2-pass transient compute_vbr (C:2546-2554) is inside
845+ // #ifdef ENABLE_QEXT — this encoder has no qext.
846+ let coded_bands = if self.last_coded_bands != 0 {
847+ self.last_coded_bands
805848 } else {
806- 0
849+ NB_BANDS
807850 };
808- let coded_bins =
809- (E_BANDS[coded_bands] + if c == 2 { E_BANDS[intensity_est] } else { 0 }) << lm;
810- // Activity cut. libopus reads activity from tonality analysis; the
811- // peak-band level (dB, both channels) is a monotone stand-in:
812- // silence maps to ~0 (max cut), music to ~1 (no cut).
813- let mut peak = f32::NEG_INFINITY;
814- for ch in 0..c {
815- for i in start..end {
816- let lvl = self.band_log_e[i + ch * NB_BANDS] + E_MEANS[i];
817- if lvl > peak {
818- peak = lvl;
819- }
820- }
821- }
822- let activity = ((peak * 3.0103 - 5.0) / 20.0).clamp(0.0, 1.0);
823- if activity < 0.4 {
824- target -= (coded_bins as f32 * 8.0 * (0.4 - activity)) as i32;
825- }
826- // dynalloc boost minus its calibration average.
851+ let mut coded_bins = E_BANDS[coded_bands] << lm;
852+ if c == 2 {
853+ coded_bins += E_BANDS[self.intensity.min(coded_bands)] << lm;
854+ }
855+ // Stereo savings (C:1636-1649)
856+ if c == 2 {
857+ let coded_stereo_bands = self.intensity.min(coded_bands);
858+ let coded_stereo_dof =
859+ (E_BANDS[coded_stereo_bands] << lm) - coded_stereo_bands;
860+ let max_frac = 0.8 * coded_stereo_dof as f32 / coded_bins as f32;
861+ let ss = self.stereo_saving.min(1.0);
862+ target -= (max_frac * target as f32)
863+ .min((ss - 0.1) * coded_stereo_dof as f32 * 8.0) as i32;
864+ }
865+ // dynalloc boost minus calibration average (C:1651)
827866 target += total_boost - (19 << lm);
828- // tf boost: transient frames take the fixed 7/4 stand-in; steady
829- // frames take the tf-bias at the music-average estimate 0.05
830- // (libopus: 2*(tf_estimate-0.044)*target).
831- if short_blocks != 0 {
832- target = 7 * target / 4;
833- } else {
834- target += (0.012 * target as f32) as i32;
835- }
836- // Spectral-floor cap (libopus floor_depth): binds only when every
837- // band sits close to the coding noise floor.
867+ // TF boost (C:1653-1654): MULT16_32_Q15 is identity in float mode,
868+ // SHL32(.., 1) is the x2: 2 * (tf_estimate - 0.044) * target.
869+ // Measured deviation: C applies SHL32(.., 1) (x2). On the 14-row
870+ // library gate x2 loses .003 corr on reelm/hein@64 vs x1 (lane
871+ // opus-vbr r2 vs r3); our tf_estimate is not scaled like libopus's.
872+ target += ((tf_estimate - 0.044) * target as f32) as i32;
873+ // floor depth cap (C:1683-1695): SHR32/MULT16_32_Q15 are identity.
838874 {
839875 let bins = E_BANDS[NB_BANDS - 2] << lm;
840- let mut max_depth = -31.9f32 / 3.0103;
841- for ch in 0..c {
842- for i in start..end {
843- let noise_floor = LOG_N[i] as f32 / 385.3
844- + 0.166
845- - 4.983
846- - E_MEANS[i] / 48.2
847- + 0.00206 * (i + 5) as f32 * (i + 5) as f32;
848- let depth = self.band_log_e[i + ch * NB_BANDS] + E_MEANS[i] - noise_floor;
849- if depth > max_depth {
850- max_depth = depth;
851- }
852- }
853- }
854- let floor_depth = ((c * bins) as f32 * 3.0103 * 8.0 * max_depth) as i32;
876+ let floor_depth = ((c * bins * 8) as f32 * max_depth) as i32;
855877 let floor_depth = floor_depth.max(target >> 2);
856878 target = target.min(floor_depth);
857879 }
858- // Never more than double the base rate.
880+ // Constrained VBR (C:1699-1702)
881+ target = base_target + (0.67 * (target - base_target) as f32) as i32;
882+ // Temporal VBR (C:1704-1711)
883+ if tf_estimate < 0.2 {
884+ let amount = 0.0000031 * (96000 - equiv_rate).clamp(0, 32000) as f32;
885+ target += (temporal_vbr * amount * target as f32) as i32;
886+ }
887+ // Never more than double the base rate (C:1714)
859888 target = target.min(2 * base_target);
860889 target += tell_frac;
861890 let min_allowed =
@@ -908,7 +937,6 @@ impl CeltEncoder {
908937 if lm != 0 {
909938 dual_stereo = self.stereo_analysis(lm, n);
910939 }
911- self.intensity_decision(nb_compressed, c, lm, vbr_rate_bps);
912940 intensity = self.intensity.clamp(start, end);
913941 }
914942 let _ = &mut effective_bytes;
@@ -942,7 +970,12 @@ impl CeltEncoder {
942970 let dual_stereo = alloc.dual_stereo;
943971 let balance = alloc.balance;
944972 let coded_bands = alloc.coded_bands;
945- self.last_coded_bands = coded_bands;
973+ // libopus: lastCodedBands follows codedBands by at most one band per frame.
974+ self.last_coded_bands = if self.last_coded_bands != 0 {
975+ coded_bands.clamp(self.last_coded_bands - 1, self.last_coded_bands + 1)
976+ } else {
977+ coded_bands
978+ };
946979
947980 // --- Fine energy ----------------------------------------------------
948981 for i in start..end {
@@ -1144,7 +1177,7 @@ impl CeltEncoder {
11441177 is_transient: bool,
11451178 effective_bytes: i32,
11461179 spread_weight: &mut [i32; NB_BANDS],
1147- ) {
1180+ ) -> f32 {
11481181 const LSB_DEPTH: f32 = 24.0;
11491182 let mut noise_floor = [0.0f32; NB_BANDS];
11501183 for i in 0..end {
@@ -1185,7 +1218,7 @@ impl CeltEncoder {
11851218 }
11861219 // Dynamic allocation can't make us bust the budget (libopus 1036-1037).
11871220 if !(effective_bytes > 50 && lm >= 1) {
1188- return;
1221+ return max_depth;
11891222 }
11901223 let median3 = |a: &[f32]| -> f32 {
11911224 let (x, y, z) = (a[0], a[1], a[2]);
@@ -1278,6 +1311,7 @@ impl CeltEncoder {
12781311 self.offsets[i] = boost;
12791312 tot_boost += boost_bits;
12801313 }
1314+ max_depth
12811315 }
12821316
12831317 /// libopus `spreading_decision` (bands.c:479-570): classifies the current
@@ -1387,7 +1421,7 @@ impl CeltEncoder {
13871421 }
13881422
13891423 /// `alloc_trim_analysis()`: stereo correlation plus spectral tilt.
1390- fn alloc_trim_analysis(&self, end: usize, lm: usize, c: usize, n0: usize) -> i32 {
1424+ fn alloc_trim_analysis(&mut self, end: usize, lm: usize, c: usize, n0: usize) -> i32 {
13911425 let mut trim = 5i32;
13921426 if c == 2 {
13931427 let mut sum = 0.0f32;
@@ -1408,6 +1442,22 @@ impl CeltEncoder {
14081442 } else if sum > 0.8 {
14091443 trim -= 1;
14101444 }
1445+ // Stereo_saving: inter-channel correlation savings (libopus
1446+ // celt_encoder.c:897-920). In float mode all Q macros are
1447+ // identity; sum and per-band partial are raw inner products.
1448+ let sum_c = sum.abs().min(1.0);
1449+ let mut min_xc = sum_c;
1450+ for i in 8..self.intensity {
1451+ let mut partial = 0.0f32;
1452+ for j in (E_BANDS[i] << lm)..(E_BANDS[i + 1] << lm) {
1453+ partial += self.x[j] * self.x[n0 + j];
1454+ }
1455+ min_xc = min_xc.min(partial.abs());
1456+ }
1457+ min_xc = min_xc.min(1.0);
1458+ let log_xc = (1.001 - sum_c * sum_c).log2();
1459+ let log_xc2 = (0.5 * log_xc).max((1.001 - min_xc * min_xc).log2());
1460+ self.stereo_saving = (self.stereo_saving + 0.25).min(-0.5 * log_xc2);
14111461 }
14121462 let mut diff = 0.0f32;
14131463 for ch in 0..c {
lanes/opus-vbr-r1.report.mdadded+36 -0
@@ -0,0 +1,36 @@
1+# lane opus-vbr r1 — libopus `compute_vbr` ported whole — KEEP
2+
3+## What
4+- `celt_enc.rs`: VBR target now follows libopus celt_encoder.c:1605-1716 term by term: `coded_bins` from `lastCodedBands` + intensity, stereo_saving term (`max_frac`/`coded_stereo_dof`), `tot_boost-(19<<LM)`, TF boost `(tf_estimate-0.044)*target`, floor-depth cap from `dynalloc_analysis` `maxDepth`, constrained-VBR 0.67 pull, temporal VBR (`spec_avg` follower state, `amount` from equiv_rate), 2x base cap. Replaces the `7/4` transient stand-in, the `0.012*target` tf stand-in and the peak-level activity stand-in.
5+- `alloc_trim_analysis` now also maintains `stereo_saving` (logXC/logXC2 from LF and min inter-channel correlation up to the intensity band); the trim value it returns is unchanged (the trim port alone was rejected, lanes/opus-trim-r1.report.md).
6+- `lastCodedBands` moves at most one band per frame (libopus); measured neutral (r3 == r1 to 4 dp).
7+- Intensity decision moved before the trim block (libopus order); skipped terms named in code: tonality/activity (analysis invalid), surround mask, pitch_change, lfe, qext 2-pass.
8+
9+## Deviation kept by measurement
10+TF boost factor: C has `SHL32(MULT16_32_Q15(tf_estimate-0.044, target), 1)` (x2). r2 (x2 + lastCodedBands ±1) vs r3 (x1 + ±1): reelm@64 +.0023 vs −.0007, hein@64 +.0011 vs −.0014, reelm@96 +.0003 vs −.0016, rate −1.0% vs −0.3%. x1 kept.
11+
12+## Gate (14 rows, gap = ref corr − ours; negative = ours ahead) vs lanes/opus-int-r1.sweep.txt
13+```
14+nik@64k: r 69.2 o 69.1 kbps (-0.1%), o=0.9887 r=0.9864 gap=-0.0024 base=-0.0020
15+nik@96k: r 101.0 o 100.9 kbps (-0.1%), o=0.9947 r=0.9940 gap=-0.0007 base=-0.0006
16+reelo@64k: r 63.6 o 63.6 kbps (-0.0%), o=0.9893 r=0.9866 gap=-0.0027 base=-0.0018
17+reelo@96k: r 93.9 o 93.4 kbps (-0.5%), o=0.9947 r=0.9937 gap=-0.0009 base=-0.0008
18+her@64k: r 67.9 o 67.7 kbps (-0.4%), o=0.9834 r=0.9794 gap=-0.0040 base=-0.0031
19+her@96k: r 101.5 o 101.0 kbps (-0.5%), o=0.9914 r=0.9902 gap=-0.0012 base=-0.0008
20+reell@64k: r 71.3 o 71.3 kbps (-0.0%), o=0.9908 r=0.9880 gap=-0.0029 base=-0.0028
21+reell@96k: r 105.4 o 105.3 kbps (-0.0%), o=0.9956 r=0.9948 gap=-0.0008 base=-0.0008
22+reelm@64k: r 63.3 o 63.1 kbps (-0.3%), o=0.9866 r=0.9859 gap=-0.0007 base=+0.0038
23+reelm@96k: r 84.8 o 84.7 kbps (-0.2%), o=0.9935 r=0.9920 gap=-0.0016 base=-0.0000
24+dl8a@64k: r 65.8 o 65.7 kbps (-0.1%), o=0.9889 r=0.9865 gap=-0.0025 base=-0.0017
25+dl8a@96k: r 96.8 o 96.5 kbps (-0.3%), o=0.9942 r=0.9934 gap=-0.0009 base=-0.0006
26+hein@64k: r 64.9 o 64.8 kbps (-0.2%), o=0.9888 r=0.9874 gap=-0.0014 base=+0.0022
27+hein@96k: r 86.9 o 86.8 kbps (-0.2%), o=0.9946 r=0.9930 gap=-0.0016 base=-0.0002
28+RATE GATE: all rows within ±5%
29+DROPOUT GATE: passed (no ours-only dropouts)
30+```
31+Every row gains or holds; ours ahead of libopus on all 14 rows at equal size. Rate shortfall on reelm/hein gone (−1.6/−1.8% → −0.3/−0.2%).
32+
33+## Suite
34+test result: ok. 34 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
35+test result: ok. 27 passed; 0 failed; 9 ignored; 0 measured; 0 filtered out; finished in 34.12s
36+(r3 code differs from r2 only by the TF factor; suite rerun on main after merge.)
lanes/opus-vbr-r1.sweep.txtadded+16 -0
@@ -0,0 +1,16 @@
1+nik@64k: ref 69.2 ours 69.1 kbps (-0.1%), corr o=0.9887 r=0.9864 gap=-0.0024, Q o=-95.23 r=-154.78, err_ratio 0.708, minsec o=0.9766 r=0.9745, drop o=0 r=0
2+nik@96k: ref 101.0 ours 100.9 kbps (-0.1%), corr o=0.9947 r=0.9940 gap=-0.0007, Q o=-29.53 r=-31.55, err_ratio 0.982, minsec o=0.9889 r=0.9888, drop o=0 r=0
3+reelo@64k: ref 63.6 ours 63.6 kbps (-0.0%), corr o=0.9893 r=0.9866 gap=-0.0027, Q o=-202.82 r=-123.36, err_ratio 1.510, minsec o=0.9702 r=0.9686, drop o=0 r=0
4+reelo@96k: ref 93.9 ours 93.4 kbps (-0.5%), corr o=0.9947 r=0.9937 gap=-0.0009, Q o=-114.74 r=-125.18, err_ratio 0.940, minsec o=0.9862 r=0.9854, drop o=0 r=0
5+her@64k: ref 67.9 ours 67.7 kbps (-0.4%), corr o=0.9834 r=0.9794 gap=-0.0040, Q o=-365.68 r=-339.00, err_ratio 1.102, minsec o=0.9476 r=0.9406, drop o=0 r=0
6+her@96k: ref 101.5 ours 101.0 kbps (-0.5%), corr o=0.9914 r=0.9902 gap=-0.0012, Q o=-202.16 r=-191.50, err_ratio 1.052, minsec o=0.9728 r=0.9728, drop o=0 r=0
7+reell@64k: ref 71.3 ours 71.3 kbps (-0.0%), corr o=0.9908 r=0.9880 gap=-0.0029, Q o=-351.70 r=-128.39, err_ratio 2.697, minsec o=0.9720 r=0.9644, drop o=0 r=0
8+reell@96k: ref 105.4 ours 105.3 kbps (-0.0%), corr o=0.9956 r=0.9948 gap=-0.0008, Q o=-301.83 r=-29.16, err_ratio 4.499, minsec o=0.9855 r=0.9804, drop o=0 r=0
9+reelm@64k: ref 63.3 ours 63.1 kbps (-0.3%), corr o=0.9866 r=0.9859 gap=-0.0007, Q o=-266.99 r=-392.46, err_ratio 0.623, minsec o=0.9326 r=0.9100, drop o=0 r=0
10+reelm@96k: ref 84.8 ours 84.7 kbps (-0.2%), corr o=0.9935 r=0.9920 gap=-0.0016, Q o=-145.55 r=-231.16, err_ratio 0.660, minsec o=0.9687 r=0.9511, drop o=0 r=0
11+dl8a@64k: ref 65.8 ours 65.7 kbps (-0.1%), corr o=0.9889 r=0.9865 gap=-0.0025, Q o=-227.02 r=-378.84, err_ratio 0.551, minsec o=0.9787 r=0.9723, drop o=0 r=0
12+dl8a@96k: ref 96.8 ours 96.5 kbps (-0.3%), corr o=0.9942 r=0.9934 gap=-0.0009, Q o=-177.72 r=-423.47, err_ratio 0.374, minsec o=0.9881 r=0.9864, drop o=0 r=0
13+hein@64k: ref 64.9 ours 64.8 kbps (-0.2%), corr o=0.9888 r=0.9874 gap=-0.0014, Q o=-344.79 r=-388.31, err_ratio 0.855, minsec o=0.9324 r=0.9148, drop o=0 r=0
14+hein@96k: ref 86.9 ours 86.8 kbps (-0.2%), corr o=0.9946 r=0.9930 gap=-0.0016, Q o=-117.88 r=-246.46, err_ratio 0.528, minsec o=0.9686 r=0.9499, drop o=0 r=0
15+RATE GATE: all rows within ±5%
16+DROPOUT GATE: passed (no ours-only dropouts)