From 87603a569e6a6b90af7e6c4d802df97b135de1b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 23 Aug 2026 05:29:26 +0300 Subject: [PATCH] opus: validate opus_compare_err against the C opus_compare (byte-exact) Six real pairs (source vs libopus, source vs ec-opus on reelm/dl8a/reell) agree with the C tool to 1e-6 in err. Negative Q and wide err ratios are the tool's designed behaviour on source-vs-lossy input, not a scale bug. Adds opus_compare_err_pinned_against_c (synthetic signal, C-pinned err) as a regression guard, plus two ignored harness entry points. --- crates/ec-opus/tests/conformance.rs | 167 +++++++++++++++++++++++++++- lanes/.gitignore | 6 + lanes/opus-metric-r1.report.md | 72 ++++++++++++ lanes/opus-metric-r1.sweep.txt | 10 ++ 4 files changed, 254 insertions(+), 1 deletion(-) create mode 100644 lanes/.gitignore create mode 100644 lanes/opus-metric-r1.report.md create mode 100644 lanes/opus-metric-r1.sweep.txt diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index ae56eb2b..0b6b6d81 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -2984,7 +2984,7 @@ fn encoder_library_gate_vs_libopus() { let mut table = String::new(); table.push_str("# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1)\n"); - table.push_str("# both bitstreams decoded by ec-opus; 600s cap; VBR; 48kHz stereo\n"); + table.push_str("# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo\n"); table.push_str("# source\tkbps\tours_kbps\tref_kbps\trate%\tcorr_ours\tcorr_ref\tgap\t\ Q_ours\tQ_ref\terr_ratio\tminsec_ours\tminsec_ref\tdrop_ours\tdrop_ref\n"); for r in &rows { @@ -3011,3 +3011,168 @@ fn encoder_library_gate_vs_libopus() { ); println!("DROPOUT GATE: passed (no ours-only dropouts)"); } + +// --------------------------------------------------------------------------- +// Harness: feed identical raw PCM (.sw, s16le interleaved) to our opus_compare +// so it can be checked against the C `opus_compare` tool on the SAME bytes. +// Run: SW_REF=a.sw SW_TEST=b.sw SW_CH=2 cargo test -p ec-opus --release \ +// opus_compare_harness -- --ignored --nocapture +// --------------------------------------------------------------------------- +#[test] +#[ignore] +fn opus_compare_harness() { + let ref_path = std::env::var("SW_REF").expect("SW_REF"); + let test_path = std::env::var("SW_TEST").expect("SW_TEST"); + let channels: usize = std::env::var("SW_CH") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(2); + let x = read_i16(Path::new(&ref_path)); + let y = read_i16(Path::new(&test_path)); + assert_eq!( + x.len(), + y.len(), + "sample counts differ: {} ({} samples) vs {} ({} samples)", + ref_path, + x.len() / channels, + test_path, + y.len() / channels + ); + let err = opus_compare_err(&x, &y, channels); + let q = opus_compare(&x, &y, channels); + println!("HARNESS err={err:.6} Q={q:.4} ch={channels} n={}", x.len() / channels); +} + +// --------------------------------------------------------------------------- +// Harness: read a source .sw, encode via ec-opus at SW_KBPS, decode, align, +// write the aligned decoded pair to SW_OUT_SRC / SW_OUT_DEC (.sw s16le), and +// print our opus_compare err/Q. The dumped .sw files can then be fed to the C +// `opus_compare` tool on IDENTICAL bytes for a byte-exact cross-check. +// Run: SW_SRC=in.sw SW_KBPS=96 SW_OUT_SRC=as.sw SW_OUT_DEC=ad.sw \ +// cargo test -p ec-opus --release opus_compare_harness_ours -- --ignored --nocapture +// --------------------------------------------------------------------------- +#[test] +#[ignore] +fn opus_compare_harness_ours() { + let src_path = std::env::var("SW_SRC").expect("SW_SRC"); + let kbps: u32 = std::env::var("SW_KBPS") + .ok() + .and_then(|s| s.parse().ok()) + .expect("SW_KBPS"); + let channels: usize = std::env::var("SW_CH") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(2); + let out_src = std::env::var("SW_OUT_SRC").expect("SW_OUT_SRC"); + let out_dec = std::env::var("SW_OUT_DEC").expect("SW_OUT_DEC"); + + let src_i16 = read_i16(Path::new(&src_path)); + let src_f32: Vec = src_i16.iter().map(|&v| v as f32 / 32768.0).collect(); + let mut enc = Encoder::new(48000, channels, Application::Audio).expect("encoder"); + enc.set_bitrate(kbps * 1000); + enc.set_vbr_constrained(true); + let (dec_f32, _bytes) = roundtrip_own(&mut enc, &src_f32, channels, 960); + let (lag, aligned) = align_to_source(&src_f32, &dec_f32, channels, 2000); + // Trim both to the common aligned length. + let n = (src_f32.len() / channels).min(aligned.len() / channels); + let mut s_i16 = vec![0i16; n * channels]; + let mut d_i16 = vec![0i16; n * channels]; + for i in 0..n { + for ch in 0..channels { + s_i16[i * channels + ch] = + (src_f32[i * channels + ch] * 32768.0).round().clamp(-32768.0, 32767.0) as i16; + d_i16[i * channels + ch] = + (aligned[i * channels + ch] * 32768.0).round().clamp(-32768.0, 32767.0) as i16; + } + } + fs::write(&out_src, bytemap(&s_i16)).unwrap(); + fs::write(&out_dec, bytemap(&d_i16)).unwrap(); + let err = opus_compare_err(&s_i16, &d_i16, channels); + let q = opus_compare(&s_i16, &d_i16, channels); + let c = corr_interleaved(&src_f32[..n * channels], &aligned, channels); + println!( + "HARNESS_OURS lag={lag} corr={c:.4} err={err:.6} Q={q:.4} kbps={kbps} n={n}" + ); +} + +fn bytemap(p: &[i16]) -> Vec { + let mut b = Vec::with_capacity(p.len() * 2); + for &v in p { + b.extend_from_slice(&v.to_le_bytes()); + } + b +} + +/// Self-contained regression guard for `opus_compare_err` / `opus_compare`. +/// +/// The pinned numbers below were cross-validated against the reference C +/// `opus_compare` tool (built from `opus_compare.c`) on byte-identical raw +/// PCM, so they encode the spectral error algorithm's expected output, not +/// any particular codec. Two cases: +/// * identical signals -> C err=0.000000, Q=100.0 (exact) +/// * mild perturbation -> C err=4.444987, Q=-593.31 (exact to 6 dp) +/// The perturbation case sits in the practical error range (same band as the +/// real-audio validation pairs); the identical case pins the zero-error path +/// with no floating-point tolerance. No audio files or external tools needed. +#[test] +fn opus_compare_err_pinned_against_c() { + const N: usize = 48000 * 4; // 4 s per channel + let t: Vec = (0..N).map(|i| i as f64 / 48000.0).collect(); + + let base = |c: usize| -> Vec { + let ph = 0.5 * c as f64; + let ph2 = 0.3 * c as f64; + t.iter() + .map(|&tt| { + 0.3 * (2.0 * std::f64::consts::PI * 440.0 * tt).sin() + + 0.2 * (2.0 * std::f64::consts::PI * 442.0 * tt + ph).sin() + + 0.15 * (2.0 * std::f64::consts::PI * (800.0 + 200.0 * tt) * tt + ph2).sin() + }) + .collect() + }; + let to_i16s = |sig: &[f64]| -> Vec { + sig.iter() + .map(|&v| (v.clamp(-1.0, 1.0) * 32767.0) as i16) + .collect() + }; + let stereo = |l: &[f64], r: &[f64]| -> Vec { + let mut o = Vec::with_capacity(N * 2); + let li = to_i16s(l); + let ri = to_i16s(r); + for i in 0..N { + o.push(li[i]); + o.push(ri[i]); + } + o + }; + + let b0 = base(0); + let b1 = base(1); + + // Case 1: identical -> zero error, Q=100 (exact, no tolerance). + let a = stereo(&b0, &b1); + let err_id = opus_compare_err(&a, &a, 2); + let q_id = opus_compare(&a, &a, 2); + assert_eq!(err_id, 0.0, "identical signals must give err=0"); + assert_eq!(q_id, 100.0, "identical signals must give Q=100"); + + // Case 2: mild perturbation (+0.5 dB on L, quiet 1500 Hz partial on L). + let gain = 10f64.powf(0.5 / 10.0); + let lp: Vec = t.iter() + .zip(b0.iter()) + .map(|(&tt, &bv)| bv * gain + 0.02 * (2.0 * std::f64::consts::PI * 1500.0 * tt).sin()) + .collect(); + let b = stereo(&lp, &b1); + let err = opus_compare_err(&a, &b, 2); + let q = opus_compare(&a, &b, 2); + // Pinned to the C reference value (4.444987); tolerance absorbs libm + // transcendental rounding differences across toolchains. + assert!( + (err - 4.444987).abs() < 1e-3, + "pinned err drift: got {err:.6}, expected 4.444987 (C-validated)" + ); + assert!( + (q - -593.31).abs() < 0.5, + "pinned Q drift: got {q:.4}, expected -593.31 (C-validated)" + ); +} diff --git a/lanes/.gitignore b/lanes/.gitignore new file mode 100644 index 00000000..b4bf331c --- /dev/null +++ b/lanes/.gitignore @@ -0,0 +1,6 @@ +# C-cross-validation build/test artifacts — never committed. +*.sw +*.ogg +opus_compare +align_sw.py +*_al diff --git a/lanes/opus-metric-r1.report.md b/lanes/opus-metric-r1.report.md new file mode 100644 index 00000000..f206ef33 --- /dev/null +++ b/lanes/opus-metric-r1.report.md @@ -0,0 +1,72 @@ +# lane-opus-metric r1 — opus_compare_err validated against C opus_compare (verdict: METRIC CORRECT, NO FIX) + +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. + +## What this lane set out to do, and what it found + +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. + +## Method + +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). +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. +3. Ran **both** the C binary and the Rust `opus_compare_err` on byte-identical `.sw` input pairs. + +## Validation evidence — 6/6 byte-exact + +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. + +| pair | context | C err | Rust err | ΔQ | +|---|---|---|---|---| +| reelm64 ref | source vs libopus | 2.332549 | 2.332550 | <0.001 | +| dl8a96 ref | source vs libopus | 2.439208 | 2.439207 | <0.001 | +| reell96 ref | source vs libopus | 0.369040 | 0.369040 | <0.001 | +| reelm64 ours | source vs ec-opus | 6.545176 | 6.545176 | 0.00 | +| dl8a96 ours | source vs ec-opus | 2.162523 | 2.162523 | 0.00 | +| reell96 ours | source vs ec-opus | 7.880892 | 7.880892 | 0.00 | + +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.** + +## Why Q is negative and err_ratio is wide — and why that is expected + +`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. + +## Why err_ratio is still not a quality gate + +`err_ratio` is faithful (byte-exact) but **non-discriminating** for this off-label use. The sweep: + +- 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**. +- Clean rows (no dropout, our corr ≥ ref corr) reach err_ratio **23.640** (reell@96k, corr_ours 0.9954 ≥ ref 0.9948). + +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: + +- **Quality gate = unchanged**: dropout (ours must not drop a second the reference kept) + rate ±5%. This already fires correctly on reelm@64k. +- **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. + +## Gate sweep (3 sources × {64,96}k, metric-validated) — lanes/opus-metric-r1.sweep.txt + +``` +source kbps ours ref rate% corr_o corr_r gap Q_ours Q_ref err_ratio minsec_o minsec_r drop_o drop_r +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 +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 +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 +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 +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 +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 +``` + +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). + +## Regression guard added + +`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: +- identical signals → err = 0.000000, Q = 100.0 (exact, zero tolerance); +- 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). + +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. + +## Changes in this lane +- `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.) +- `lanes/opus-metric-r1.sweep.txt`: 6-row metric-validated sweep. +- `lanes/opus-metric-r1.report.md`: this file. +- NOT committed: `lanes/opus_compare` (C binary), `*.sw`, `*.ogg`, `align_sw.py` — build/test artifacts, gitignored. diff --git a/lanes/opus-metric-r1.sweep.txt b/lanes/opus-metric-r1.sweep.txt new file mode 100644 index 00000000..42d29623 --- /dev/null +++ b/lanes/opus-metric-r1.sweep.txt @@ -0,0 +1,10 @@ +# ec-opus encoder vs ffmpeg libopus — encoders-only gate, metric-validated subset (r1) +# opus_compare_err validated byte-exact (<=1e-6 abs) against C opus_compare on all +# 3 sources x {64,96}k (6/6). Both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo. +# 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 +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 +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 +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 +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 +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 +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