forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-opus-metric': opus_compare port validated against C

Browse files at this commit

c74d5e8c47699122488b9e175ddd99677502c845Ahmet Kaan GümüşParent: 43fe5e787603a5
crates/ec-opus/tests/conformance.rsmodified+166 -1
@@ -2984,7 +2984,7 @@ fn encoder_library_gate_vs_libopus() {
2984 2984
2985 let mut table = String::new();2985 let mut table = String::new();
2986 table.push_str("# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1)\n");2986 table.push_str("# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1)\n");
2987- table.push_str("# both bitstreams decoded by ec-opus; 600s cap; VBR; 48kHz stereo\n");2987+ table.push_str("# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo\n");
2988 table.push_str("# source\tkbps\tours_kbps\tref_kbps\trate%\tcorr_ours\tcorr_ref\tgap\t\2988 table.push_str("# source\tkbps\tours_kbps\tref_kbps\trate%\tcorr_ours\tcorr_ref\tgap\t\
2989 Q_ours\tQ_ref\terr_ratio\tminsec_ours\tminsec_ref\tdrop_ours\tdrop_ref\n");2989 Q_ours\tQ_ref\terr_ratio\tminsec_ours\tminsec_ref\tdrop_ours\tdrop_ref\n");
2990 for r in &rows {2990 for r in &rows {
@@ -3011,3 +3011,168 @@ fn encoder_library_gate_vs_libopus() {
3011 );3011 );
3012 println!("DROPOUT GATE: passed (no ours-only dropouts)");3012 println!("DROPOUT GATE: passed (no ours-only dropouts)");
3013 }3013 }
3014+
3015+// ---------------------------------------------------------------------------
3016+// Harness: feed identical raw PCM (.sw, s16le interleaved) to our opus_compare
3017+// so it can be checked against the C `opus_compare` tool on the SAME bytes.
3018+// Run: SW_REF=a.sw SW_TEST=b.sw SW_CH=2 cargo test -p ec-opus --release \
3019+// opus_compare_harness -- --ignored --nocapture
3020+// ---------------------------------------------------------------------------
3021+#[test]
3022+#[ignore]
3023+fn opus_compare_harness() {
3024+ let ref_path = std::env::var("SW_REF").expect("SW_REF");
3025+ let test_path = std::env::var("SW_TEST").expect("SW_TEST");
3026+ let channels: usize = std::env::var("SW_CH")
3027+ .ok()
3028+ .and_then(|s| s.parse().ok())
3029+ .unwrap_or(2);
3030+ let x = read_i16(Path::new(&ref_path));
3031+ let y = read_i16(Path::new(&test_path));
3032+ assert_eq!(
3033+ x.len(),
3034+ y.len(),
3035+ "sample counts differ: {} ({} samples) vs {} ({} samples)",
3036+ ref_path,
3037+ x.len() / channels,
3038+ test_path,
3039+ y.len() / channels
3040+ );
3041+ let err = opus_compare_err(&x, &y, channels);
3042+ let q = opus_compare(&x, &y, channels);
3043+ println!("HARNESS err={err:.6} Q={q:.4} ch={channels} n={}", x.len() / channels);
3044+}
3045+
3046+// ---------------------------------------------------------------------------
3047+// Harness: read a source .sw, encode via ec-opus at SW_KBPS, decode, align,
3048+// write the aligned decoded pair to SW_OUT_SRC / SW_OUT_DEC (.sw s16le), and
3049+// print our opus_compare err/Q. The dumped .sw files can then be fed to the C
3050+// `opus_compare` tool on IDENTICAL bytes for a byte-exact cross-check.
3051+// Run: SW_SRC=in.sw SW_KBPS=96 SW_OUT_SRC=as.sw SW_OUT_DEC=ad.sw \
3052+// cargo test -p ec-opus --release opus_compare_harness_ours -- --ignored --nocapture
3053+// ---------------------------------------------------------------------------
3054+#[test]
3055+#[ignore]
3056+fn opus_compare_harness_ours() {
3057+ let src_path = std::env::var("SW_SRC").expect("SW_SRC");
3058+ let kbps: u32 = std::env::var("SW_KBPS")
3059+ .ok()
3060+ .and_then(|s| s.parse().ok())
3061+ .expect("SW_KBPS");
3062+ let channels: usize = std::env::var("SW_CH")
3063+ .ok()
3064+ .and_then(|s| s.parse().ok())
3065+ .unwrap_or(2);
3066+ let out_src = std::env::var("SW_OUT_SRC").expect("SW_OUT_SRC");
3067+ let out_dec = std::env::var("SW_OUT_DEC").expect("SW_OUT_DEC");
3068+
3069+ let src_i16 = read_i16(Path::new(&src_path));
3070+ let src_f32: Vec<f32> = src_i16.iter().map(|&v| v as f32 / 32768.0).collect();
3071+ let mut enc = Encoder::new(48000, channels, Application::Audio).expect("encoder");
3072+ enc.set_bitrate(kbps * 1000);
3073+ enc.set_vbr_constrained(true);
3074+ let (dec_f32, _bytes) = roundtrip_own(&mut enc, &src_f32, channels, 960);
3075+ let (lag, aligned) = align_to_source(&src_f32, &dec_f32, channels, 2000);
3076+ // Trim both to the common aligned length.
3077+ let n = (src_f32.len() / channels).min(aligned.len() / channels);
3078+ let mut s_i16 = vec![0i16; n * channels];
3079+ let mut d_i16 = vec![0i16; n * channels];
3080+ for i in 0..n {
3081+ for ch in 0..channels {
3082+ s_i16[i * channels + ch] =
3083+ (src_f32[i * channels + ch] * 32768.0).round().clamp(-32768.0, 32767.0) as i16;
3084+ d_i16[i * channels + ch] =
3085+ (aligned[i * channels + ch] * 32768.0).round().clamp(-32768.0, 32767.0) as i16;
3086+ }
3087+ }
3088+ fs::write(&out_src, bytemap(&s_i16)).unwrap();
3089+ fs::write(&out_dec, bytemap(&d_i16)).unwrap();
3090+ let err = opus_compare_err(&s_i16, &d_i16, channels);
3091+ let q = opus_compare(&s_i16, &d_i16, channels);
3092+ let c = corr_interleaved(&src_f32[..n * channels], &aligned, channels);
3093+ println!(
3094+ "HARNESS_OURS lag={lag} corr={c:.4} err={err:.6} Q={q:.4} kbps={kbps} n={n}"
3095+ );
3096+}
3097+
3098+fn bytemap(p: &[i16]) -> Vec<u8> {
3099+ let mut b = Vec::with_capacity(p.len() * 2);
3100+ for &v in p {
3101+ b.extend_from_slice(&v.to_le_bytes());
3102+ }
3103+ b
3104+}
3105+
3106+/// Self-contained regression guard for `opus_compare_err` / `opus_compare`.
3107+///
3108+/// The pinned numbers below were cross-validated against the reference C
3109+/// `opus_compare` tool (built from `opus_compare.c`) on byte-identical raw
3110+/// PCM, so they encode the spectral error algorithm's expected output, not
3111+/// any particular codec. Two cases:
3112+/// * identical signals -> C err=0.000000, Q=100.0 (exact)
3113+/// * mild perturbation -> C err=4.444987, Q=-593.31 (exact to 6 dp)
3114+/// The perturbation case sits in the practical error range (same band as the
3115+/// real-audio validation pairs); the identical case pins the zero-error path
3116+/// with no floating-point tolerance. No audio files or external tools needed.
3117+#[test]
3118+fn opus_compare_err_pinned_against_c() {
3119+ const N: usize = 48000 * 4; // 4 s per channel
3120+ let t: Vec<f64> = (0..N).map(|i| i as f64 / 48000.0).collect();
3121+
3122+ let base = |c: usize| -> Vec<f64> {
3123+ let ph = 0.5 * c as f64;
3124+ let ph2 = 0.3 * c as f64;
3125+ t.iter()
3126+ .map(|&tt| {
3127+ 0.3 * (2.0 * std::f64::consts::PI * 440.0 * tt).sin()
3128+ + 0.2 * (2.0 * std::f64::consts::PI * 442.0 * tt + ph).sin()
3129+ + 0.15 * (2.0 * std::f64::consts::PI * (800.0 + 200.0 * tt) * tt + ph2).sin()
3130+ })
3131+ .collect()
3132+ };
3133+ let to_i16s = |sig: &[f64]| -> Vec<i16> {
3134+ sig.iter()
3135+ .map(|&v| (v.clamp(-1.0, 1.0) * 32767.0) as i16)
3136+ .collect()
3137+ };
3138+ let stereo = |l: &[f64], r: &[f64]| -> Vec<i16> {
3139+ let mut o = Vec::with_capacity(N * 2);
3140+ let li = to_i16s(l);
3141+ let ri = to_i16s(r);
3142+ for i in 0..N {
3143+ o.push(li[i]);
3144+ o.push(ri[i]);
3145+ }
3146+ o
3147+ };
3148+
3149+ let b0 = base(0);
3150+ let b1 = base(1);
3151+
3152+ // Case 1: identical -> zero error, Q=100 (exact, no tolerance).
3153+ let a = stereo(&b0, &b1);
3154+ let err_id = opus_compare_err(&a, &a, 2);
3155+ let q_id = opus_compare(&a, &a, 2);
3156+ assert_eq!(err_id, 0.0, "identical signals must give err=0");
3157+ assert_eq!(q_id, 100.0, "identical signals must give Q=100");
3158+
3159+ // Case 2: mild perturbation (+0.5 dB on L, quiet 1500 Hz partial on L).
3160+ let gain = 10f64.powf(0.5 / 10.0);
3161+ let lp: Vec<f64> = t.iter()
3162+ .zip(b0.iter())
3163+ .map(|(&tt, &bv)| bv * gain + 0.02 * (2.0 * std::f64::consts::PI * 1500.0 * tt).sin())
3164+ .collect();
3165+ let b = stereo(&lp, &b1);
3166+ let err = opus_compare_err(&a, &b, 2);
3167+ let q = opus_compare(&a, &b, 2);
3168+ // Pinned to the C reference value (4.444987); tolerance absorbs libm
3169+ // transcendental rounding differences across toolchains.
3170+ assert!(
3171+ (err - 4.444987).abs() < 1e-3,
3172+ "pinned err drift: got {err:.6}, expected 4.444987 (C-validated)"
3173+ );
3174+ assert!(
3175+ (q - -593.31).abs() < 0.5,
3176+ "pinned Q drift: got {q:.4}, expected -593.31 (C-validated)"
3177+ );
3178+}
lanes/.gitignoreadded+6 -0
@@ -0,0 +1,6 @@
1+# C-cross-validation build/test artifacts — never committed.
2+*.sw
3+*.ogg
4+opus_compare
5+align_sw.py
6+*_al
lanes/opus-metric-r1.report.mdadded+72 -0
@@ -0,0 +1,72 @@
1+# lane-opus-metric r1 — opus_compare_err validated against C opus_compare (verdict: METRIC CORRECT, NO FIX)
2+
3+VERDICT: C vs ours ΔQ on 3 pairs (reelm@64k / dl8a@96k / reell@96k): 0.00 / 0.00 / 0.00 (all < 0.001); err_ratio after fix: range 0.866–23.640 — NO FIX NEEDED, metric is byte-exact to the C tool; proposed gate ≤z: N/A — err_ratio is a faithful but non-discriminating spectral-divergence metric (the one real defect, reelm@64k dropout, sits at err_ratio 3.145 *inside* the clean range 0.866–23.640), so it cannot separate defect from non-defect; the quality gate stays dropout + rate ±5%, err_ratio is report-only.
4+
5+## What this lane set out to do, and what it found
6+
7+The prior `opus-gate-r1.report.md` (line 10) called `opus_compare_err` "instrument suspect (alignment/phase-sensitive or unnormalised)" and refused to gate on `err_ratio` until it was "validated against opus_compare on one file." This lane performed that validation. **The suspicion is refuted.** The Rust port of `opus_compare` is faithful to the C reference to the limit of floating-point precision on every pair tested. The negative Q values and the wide `err_ratio` spread are *correct* `opus_compare` behaviour, not a porting or scaling bug.
8+
9+## Method
10+
11+1. Built the reference C tool from `opus_compare.c` (audiopus_sys 0.2.2): `cc -O2 -lm` → `lanes/opus_compare`. Usage: `./opus_compare -s ref.sw test.sw` (raw 48 kHz 16-bit stereo, interleaved, native-endian).
12+2. Produced three source files (120 s cap, reelm/dl8a/reell) as `.sw`, plus the libopus-encoded/decoded reference `.sw` and the ec-opus-encoded/decoded `.sw` for each, byte-aligned to a common length.
13+3. Ran **both** the C binary and the Rust `opus_compare_err` on byte-identical `.sw` input pairs.
14+
15+## Validation evidence — 6/6 byte-exact
16+
17+Both tools read the same int16 bytes; `opus_compare_err` casts i16→f64 and runs the identical BANDS/NBANDS=21/NFREQS=240/WIN_SIZE=480/WIN_STEP=120/Hann/DFT/masking/`re-ln(re)-1`/consecutive-frame-average/`pow(err/nframes,1/16)` pipeline.
18+
19+| pair | context | C err | Rust err | ΔQ |
20+|---|---|---|---|---|
21+| reelm64 ref | source vs libopus | 2.332549 | 2.332550 | <0.001 |
22+| dl8a96 ref | source vs libopus | 2.439208 | 2.439207 | <0.001 |
23+| reell96 ref | source vs libopus | 0.369040 | 0.369040 | <0.001 |
24+| reelm64 ours | source vs ec-opus | 6.545176 | 6.545176 | 0.00 |
25+| dl8a96 ours | source vs ec-opus | 2.162523 | 2.162523 | 0.00 |
26+| reell96 ours | source vs ec-opus | 7.880892 | 7.880892 | 0.00 |
27+
28+Absolute Δerr ≤ 1e-6 on all six. On a deliberately extreme high-error synthetic (err≈184, hard clipping) a 7.6e-6 *relative* divergence appears (libm transcendental/rounding order, not logic); it is invisible at 6 dp in the practical err range (0.37–7.88) of the real pairs. **Conclusion: `opus_compare_err` is correct. No change to the metric.**
29+
30+## Why Q is negative and err_ratio is wide — and why that is expected
31+
32+`opus_compare`'s Q mapping is `100*(1 - 0.5*ln(1+err)/ln(1.13))`: Q=100 at err=0, crosses 0 at err=0.13, and goes negative for larger err. The tool was built for **decoder conformance** (decode-the-same-bitstream-with-two-decoders → tiny spectral error → Q near 100). Feeding it **source vs lossy-encoder output** is an off-label use: a lossy encoder legitimately reshapes the spectrum (band folding, intensity stereo, cutoff, noise shaping), so err is naturally ≫0.13 and Q is naturally large-negative on *both* the reference libopus and our encoder. This is not a scale bug — it is the tool working as designed in a context it was never intended for. The `err_ratio = err_ours/err_ref` column removes the absolute-scale dependence and is therefore the scale-invariant quantity the prior report was reaching for; it is computed correctly.
33+
34+## Why err_ratio is still not a quality gate
35+
36+`err_ratio` is faithful (byte-exact) but **non-discriminating** for this off-label use. The sweep:
37+
38+- The one genuine quality defect — `reelm@64k`, where ec-opus drops a second the reference kept (corr 0.9793 < ref 0.9859, minsec .8987, `drop_ours=1`) — has err_ratio **3.145**.
39+- Clean rows (no dropout, our corr ≥ ref corr) reach err_ratio **23.640** (reell@96k, corr_ours 0.9954 ≥ ref 0.9948).
40+
41+No threshold z separates the defect (3.145) from the clean tail (up to 23.640): a gate of `≤4` would false-fire on nothing yet miss nothing either *except* it would also pass reelm@64k's 3.145 — i.e. it cannot catch the one real defect, while a gate tight enough to matter (`≤2`) would false-fire on every clean reell row and several others. The high err_ratio on reell is a **real spectral-shaping difference** between ec-opus and libopus (our CELT diverges spectrally while keeping time-domain corr ≥ ref), not a quality regression. Therefore:
42+
43+- **Quality gate = unchanged**: dropout (ours must not drop a second the reference kept) + rate ±5%. This already fires correctly on reelm@64k.
44+- **err_ratio = report-only spectral-divergence monitor.** Track it for encoder-spectral-shaping investigation (reell is the outlier worth a look), but do not gate pass/fail on it.
45+
46+## Gate sweep (3 sources × {64,96}k, metric-validated) — lanes/opus-metric-r1.sweep.txt
47+
48+```
49+source kbps ours ref rate% corr_o corr_r gap Q_ours Q_ref err_ratio minsec_o minsec_r drop_o drop_r
50+reell 64 71.2 71.3 -0.2 0.9903 0.9880 -0.0023 -1056.61 -128.39 21.263 0.9694 0.9644 0 0
51+reell 96 105.2 105.4 -0.2 0.9954 0.9948 -0.0006 -832.74 -29.16 23.640 0.9850 0.9804 0 0
52+reelm 64 63.3 63.3 -0.1 0.9793 0.9859 +0.0067 -767.51 -392.46 3.145 0.8987 0.9100 1 0
53+reelm 96 84.8 84.8 -0.0 0.9911 0.9920 +0.0009 -603.35 -231.16 3.674 0.9572 0.9511 0 0
54+dl8a 64 65.7 65.8 -0.2 0.9880 0.9865 -0.0015 -598.74 -378.84 2.032 0.9757 0.9723 0 0
55+dl8a 96 96.8 96.8 -0.0 0.9940 0.9934 -0.0007 -381.94 -423.47 0.866 0.9876 0.9864 0 0
56+```
57+
58+Reproduced bit-for-bit from the prior 14-row `opus-gate-r1.sweep.txt` (metric code unchanged → deterministic). RATE GATE: all rows within ±5%. DROPOUT GATE: fails on reelm@64k (unchanged — that is a real encoder defect, debt `enc-dropout-lowrate-transient`, out of scope for this test-only lane).
59+
60+## Regression guard added
61+
62+`opus_compare_err_pinned_against_c` (conformance.rs, non-`#[ignore]`): regenerates a deterministic 4 s stereo signal in-process (no audio files, no ffmpeg, no codec) and pins two C-validated values:
63+- identical signals → err = 0.000000, Q = 100.0 (exact, zero tolerance);
64+- mild perturbation (+0.5 dB on L, quiet 1500 Hz partial) → err = 4.444987, Q = −593.31 (±1e-3 / ±0.5 tolerance for libm cross-toolchain noise).
65+
66+Both numbers were produced by running the C `opus_compare` binary on byte-identical PCM, then confirmed by the Rust metric. This guards the spectral pipeline against future regressions without re-introducing the C binary as a test dependency.
67+
68+## Changes in this lane
69+- `crates/ec-opus/tests/conformance.rs`: fixed stale comment ("600s cap" → "120s cap"); added `opus_compare_err_pinned_against_c` regression test. (The two `#[ignore]` harness tests `opus_compare_harness` / `opus_compare_harness_ours` and the `bytemap` helper were added in the prior batch of this lane and are retained — they are the manual C-cross-validation entry points.)
70+- `lanes/opus-metric-r1.sweep.txt`: 6-row metric-validated sweep.
71+- `lanes/opus-metric-r1.report.md`: this file.
72+- NOT committed: `lanes/opus_compare` (C binary), `*.sw`, `*.ogg`, `align_sw.py` — build/test artifacts, gitignored.
lanes/opus-metric-r1.sweep.txtadded+10 -0
@@ -0,0 +1,10 @@
1+# ec-opus encoder vs ffmpeg libopus — encoders-only gate, metric-validated subset (r1)
2+# opus_compare_err validated byte-exact (<=1e-6 abs) against C opus_compare on all
3+# 3 sources x {64,96}k (6/6). 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+reell 64 71.2 71.3 -0.2 0.9903 0.9880 -0.0023 -1056.61 -128.39 21.263 0.9694 0.9644 0 0
6+reell 96 105.2 105.4 -0.2 0.9954 0.9948 -0.0006 -832.74 -29.16 23.640 0.9850 0.9804 0 0
7+reelm 64 63.3 63.3 -0.1 0.9793 0.9859 +0.0067 -767.51 -392.46 3.145 0.8987 0.9100 1 0
8+reelm 96 84.8 84.8 -0.0 0.9911 0.9920 +0.0009 -603.35 -231.16 3.674 0.9572 0.9511 0 0
9+dl8a 64 65.7 65.8 -0.2 0.9880 0.9865 -0.0015 -598.74 -378.84 2.032 0.9757 0.9723 0 0
10+dl8a 96 96.8 96.8 -0.0 0.9940 0.9934 -0.0007 -381.94 -423.47 0.866 0.9876 0.9864 0 0