From 2417616c270315fb30960b5644b9e1d50728a36e 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 12:00:13 +0300 Subject: [PATCH] test(opus-silk/r2): symmetric decode, lag assert, band-limited ref, ref mode --- crates/ec-opus/tests/conformance.rs | 176 ++++++++++++++++++++++------ lanes/opus-silk-r2.report.md | 91 ++++++++++++++ lanes/opus-silk-r2.sweep.txt | 10 ++ 3 files changed, 244 insertions(+), 33 deletions(-) create mode 100644 lanes/opus-silk-r2.report.md create mode 100644 lanes/opus-silk-r2.sweep.txt diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 482c9c17..4d9f051a 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -3313,6 +3313,58 @@ fn ffmpeg_encode_libopus_mono_voip(src: &Path, kbps: u32, out: &Path, secs: f64) ); } +/// Same as [`roundtrip_own`] but also returns the encoded packets, so the SILK +/// gate can re-decode them through ffmpeg (decoder-symmetric comparison). +fn roundtrip_own_packets( + enc: &mut Encoder, + pcm: &[f32], + channels: usize, + frame: usize, +) -> (Vec, Vec>, usize) { + let mut dec = Decoder::new(48000, channels).unwrap(); + let mut out = vec![0u8; 1500]; + let mut decoded = Vec::new(); + let mut packets = Vec::new(); + let mut buf = vec![0.0f32; 5760 * channels]; + let mut bytes = 0usize; + let mut padded = Vec::new(); + for block in pcm.chunks(frame * channels) { + let block = if block.len() < frame * channels { + padded.clear(); + padded.extend_from_slice(block); + padded.resize(frame * channels, 0.0); + &padded[..] + } else { + block + }; + let len = enc.encode_float(block, frame, &mut out).expect("encode"); + bytes += len; + packets.push(out[..len].to_vec()); + let n = dec.decode_float(&out[..len], &mut buf).expect("decode"); + assert_eq!(n, frame, "decoded frame size"); + assert_eq!( + dec.final_range(), + enc.final_range(), + "range state diverged between encoder and decoder" + ); + decoded.extend_from_slice(&buf[..n * channels]); + } + (decoded, packets, bytes) +} + +/// First audio packet's TOC byte from Ogg-Opus bytes (skips OpusHead/OpusTags). +fn first_audio_toc(ogg: &[u8]) -> u8 { + for p in ogg_packets(ogg) { + if p.len() >= 8 && (&p[..8] == b"OpusHead" || &p[..8] == b"OpusTags") { + continue; + } + if !p.is_empty() { + return p[0]; + } + } + 0 +} + #[test] #[ignore] fn silk_library_gate_vs_libopus() { @@ -3326,39 +3378,52 @@ fn silk_library_gate_vs_libopus() { let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes"); fs::create_dir_all(&lanes_dir).unwrap(); - let sweep_path = lanes_dir.join("opus-silk-r1.sweep.txt"); - let scratch = lanes_dir.join("opus-silk-r1.scratch.ogg"); + let sweep_path = lanes_dir.join("opus-silk-r2.sweep.txt"); + let ref_ogg = temp_path("opus-silk-r2-ref.opus"); + let ours_ogg = temp_path("opus-silk-r2-ours.opus"); // Source PCM: mono, 48 kHz. let source_pcm = ffmpeg_decode_pcm_mono(&src, SECS); let source_frames = source_pcm.len() / CHANNELS; assert!(source_frames > 48_000, "source too short"); let seconds = source_frames as f64 / 48000.0; - let source_i16 = to_i16(&source_pcm); - - // (label, kbps, forced bandwidth, forced mode). mode/bw chosen so Voip at - // these rates really codes SILK/Hybrid, not CELT (see wants_silk/ - // hybrid_choice): 12k auto-NB, 16k forced-NB (auto would pick MB), 24k - // forced-Silk+Wide (auto would pick hybrid), 32k auto-hybrid. - let rows: &[(&str, u32, Option, Option)] = &[ - ("12k-NB", 12, None, None), - ("16k-NB", 16, Some(Bandwidth::Narrow), None), - ("24k-WB", 24, Some(Bandwidth::Wide), Some(Mode::Silk)), - ("32k-Hyb", 32, None, None), + + // (label, kbps, forced bandwidth, forced mode, reference lowpass cutoff). + // cutoff: NB 4 kHz, WB 8 kHz, hybrid-FB unfiltered (None) — compare each + // encoder only against the band it can actually reproduce. + let rows: &[(&str, u32, Option, Option, Option)] = &[ + ("12k-NB", 12, None, None, Some(4000.0)), + ("16k-NB", 16, Some(Bandwidth::Narrow), None, Some(4000.0)), + ("24k-WB", 24, Some(Bandwidth::Wide), Some(Mode::Silk), Some(8000.0)), + ("32k-Hyb", 32, None, None, None), ]; let mut out_rows: Vec = Vec::new(); let mut rate_violations: Vec = Vec::new(); let mut dropout_violations: Vec = Vec::new(); + let mut lag_violations: Vec = Vec::new(); + + for &(tag, kbps, bw, mode, cutoff) in rows { + // Band-limited reference source for this row's corr/opus_compare. + let ref_source: Vec = match cutoff { + Some(hz) => lowpass(&source_pcm, hz), + None => source_pcm.clone(), + }; + let ref_source_i16 = to_i16(&ref_source); - for &(tag, kbps, bw, mode) in rows { // Reference: ffmpeg libopus, mono, voip, VBR; realised rate from size. - ffmpeg_encode_libopus_mono_voip(&src, kbps, &scratch, SECS); - let ref_bytes = fs::metadata(&scratch).map(|m| m.len() as usize).unwrap_or(0); + ffmpeg_encode_libopus_mono_voip(&src, kbps, &ref_ogg, SECS); + let ref_bytes = fs::metadata(&ref_ogg).map(|m| m.len() as usize).unwrap_or(0); let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0; - let (ref_dec, ref_ch) = decode_ogg(&scratch); - assert_eq!(ref_ch, CHANNELS, "{tag}: ref not mono"); - let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CHANNELS, MAX_LAG); + // SYMMETRY: ref decoded through ffmpeg libopus (the reference decoder), + // NOT our own decoder — so both sides cross the same decoder. (r1 used + // decode_ogg, our own MultistreamDecoder, for the ref side.) + let ref_dec = ffmpeg_decode(&ref_ogg, CHANNELS).expect("ffmpeg libopus decode of ref"); + let ref_trim: Vec = ref_dec.into_iter().take(source_frames * CHANNELS).collect(); + let (lag_ref, ref_aligned) = align_to_source(&source_pcm, &ref_trim, CHANNELS, MAX_LAG); + // REF MODE: libopus's actual mode from its first audio packet TOC. + let ref_ogg_bytes = fs::read(&ref_ogg).expect("read ref ogg"); + let ref_mode = toc_mode_label(first_audio_toc(&ref_ogg_bytes)); // Ours: ec-opus Voip at the reference's realised rate. let mut enc = Encoder::new(48000, CHANNELS, Application::Voip).expect("encoder"); @@ -3370,6 +3435,7 @@ fn silk_library_gate_vs_libopus() { enc.set_mode(Some(m)); } enc.set_vbr_constrained(true); + let pre_skip = enc.look_ahead(FRAME) as i64; // Probe which mode the encoder actually picked, from the first TOC byte. let mut probe = enc.clone(); @@ -3379,18 +3445,44 @@ fn silk_library_gate_vs_libopus() { .expect("encode probe"); let mode_label = toc_mode_label(toc_buf[0]); - let (ours_dec, ours_bytes) = roundtrip_own(&mut enc, &source_pcm, CHANNELS, FRAME); + // Own-decoder roundtrip (range-coder invariant) + packet capture. + let (ours_own_dec, ours_packets, ours_bytes) = + roundtrip_own_packets(&mut enc, &source_pcm, CHANNELS, FRAME); let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0; + + // SYMMETRY: re-decode OUR packets through ffmpeg libopus too. + write_ogg_opus( + &ours_ogg, + &ours_packets, + opus_head(CHANNELS, pre_skip as u16, None), + CHANNELS, + source_frames, + pre_skip, + ); + let ours_dec = ffmpeg_decode(&ours_ogg, CHANNELS).expect("ffmpeg libopus decode of ours"); let ours_trim: Vec = ours_dec.into_iter().take(source_frames * CHANNELS).collect(); - let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG); + let (lag_ours, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG); + + // Own-decoder aligned (extra column: decoder drift visibility). + let ours_own_trim: Vec = + ours_own_dec.into_iter().take(source_frames * CHANNELS).collect(); + let (_, ours_own_aligned) = align_to_source(&source_pcm, &ours_own_trim, CHANNELS, MAX_LAG); + + // LAG GATE: a lag at the scan bound is an invalid measurement, not a result. + if (lag_ours as i64).abs() >= MAX_LAG as i64 { + lag_violations.push(format!("{tag}: ours lag {lag_ours} hit scan bound {MAX_LAG}")); + } + if (lag_ref as i64).abs() >= MAX_LAG as i64 { + lag_violations.push(format!("{tag}: ref lag {lag_ref} hit scan bound {MAX_LAG}")); + } + let ours_i16 = to_i16(&ours_aligned); let ref_i16 = to_i16(&ref_aligned); - - let cmp_frames = (source_i16.len() / CHANNELS) + let cmp_frames = (ref_source_i16.len() / CHANNELS) .min(ours_i16.len() / CHANNELS) .min(ref_i16.len() / CHANNELS); let trim = |v: &[i16]| -> Vec { v[..cmp_frames * CHANNELS].to_vec() }; - let s_i = trim(&source_i16); + let s_i = trim(&ref_source_i16); let o_i = trim(&ours_i16); let r_i = trim(&ref_i16); let q_ours = opus_compare(&s_i, &o_i, CHANNELS); @@ -3399,11 +3491,15 @@ fn silk_library_gate_vs_libopus() { let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS); let err_ratio = if err_ref > 0.0 { err_ours / err_ref } else { f64::INFINITY }; - let corr_ours = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS); - let corr_ref = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS); - let gap = corr_ref - corr_ours; - let (minsec_ours, drop_ours) = per_second_corr(&source_pcm, &ours_aligned, CHANNELS); - let (minsec_ref, drop_ref) = per_second_corr(&source_pcm, &ref_aligned, CHANNELS); + // Primary corr: band-limited reference. Secondary: full-band source. + let corr_ours_bl = corr_interleaved(&ref_source, &ours_aligned, CHANNELS); + let corr_ref_bl = corr_interleaved(&ref_source, &ref_aligned, CHANNELS); + let gap = corr_ref_bl - corr_ours_bl; // SIGN RULE: more negative = ours better + let corr_ours_fb = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS); + let corr_ref_fb = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS); + let corr_ours_owndec = corr_interleaved(&ref_source, &ours_own_aligned, CHANNELS); + let (minsec_ours, drop_ours) = per_second_corr(&ref_source, &ours_aligned, CHANNELS); + let (minsec_ref, drop_ref) = per_second_corr(&ref_source, &ref_aligned, CHANNELS); let rate_pct = (ours_kbps / ref_kbps - 1.0) * 100.0; if rate_pct.abs() > 5.0 { @@ -3415,15 +3511,18 @@ fn silk_library_gate_vs_libopus() { )); } let row = format!( - "{tag}: mode={mode_label}, ref {ref_kbps:.1} ours {ours_kbps:.1} kbps ({rate_pct:+.1}%), \ - corr o={corr_ours:.4} r={corr_ref:.4} gap={gap:+.4}, \ + "{tag}: ref_mode={ref_mode} mode={mode_label}, ref {ref_kbps:.1} ours {ours_kbps:.1} kbps ({rate_pct:+.1}%), \ + lag o={lag_ours} r={lag_ref}, \ + corr_bl o={corr_ours_bl:.4} r={corr_ref_bl:.4} gap={gap:+.4}, \ + corr_fb o={corr_ours_fb:.4} r={corr_ref_fb:.4}, corr_owndec o={corr_ours_owndec:.4}, \ Q o={q_ours:.2} r={q_ref:.2}, err_ratio {err_ratio:.3}, \ minsec o={minsec_ours:.4} r={minsec_ref:.4}, drop o={drop_ours} r={drop_ref}" ); println!("{row}"); out_rows.push(row); } - let _ = fs::remove_file(&scratch); + let _ = fs::remove_file(&ref_ogg); + let _ = fs::remove_file(&ours_ogg); // Rate gate: report violations, never panic. let rate_gate = if rate_violations.is_empty() { @@ -3441,6 +3540,14 @@ fn silk_library_gate_vs_libopus() { } else { eprintln!("{rate_gate}"); } + // Lag gate: hard fail — a measurement at the scan bound is not a result. + assert!( + lag_violations.is_empty(), + "LAG GATE failed (lag at scan bound):\n {}", + lag_violations.join("\n ") + ); + let lag_gate = "LAG GATE: passed (no lag at scan bound)"; + println!("{lag_gate}"); // Dropout gate: hard fail — a second the reference kept must not drop out. assert!( dropout_violations.is_empty(), @@ -3452,14 +3559,17 @@ fn silk_library_gate_vs_libopus() { // Sweep file: raw rows + GATE lines (lane deliverable). let mut table = String::new(); - table.push_str("# ec-opus SILK/speech-rate gate vs ffmpeg libopus (r1)\n"); + table.push_str("# ec-opus SILK/speech-rate gate vs ffmpeg libopus (r2)\n"); table.push_str("# mono, 120s cap, VBR, 48kHz, Application::Voip; source reelm.wav\n"); + table.push_str("# r2: symmetric ffmpeg-libopus decode (both sides), lag gate, band-limited ref, ref mode\n"); for r in &out_rows { table.push_str(r); table.push('\n'); } table.push_str(&rate_gate); table.push('\n'); + table.push_str(lag_gate); + table.push('\n'); table.push_str(drop_gate); table.push('\n'); fs::write(&sweep_path, table).unwrap(); diff --git a/lanes/opus-silk-r2.report.md b/lanes/opus-silk-r2.report.md new file mode 100644 index 00000000..72c9876f --- /dev/null +++ b/lanes/opus-silk-r2.report.md @@ -0,0 +1,91 @@ +# opus-silk r2 — library gate instrument repair + +**Test:** `silk_library_gate_vs_libopus` (`crates/ec-opus/tests/conformance.rs`) +**Source:** `~/Music/reelm.wav`, mono, 120 s cap, 48 kHz, `Application::Voip`, VBR-constrained. +**Scope:** instrument only — no encoder tuning, no fixes, no guesses. + +## The four r1 measurement defects (and the r2 repair) + +| # | r1 defect | r2 repair | +|---|-----------|-----------| +| 1 | **Decoder asymmetry.** Task premise said "ref decoded by ffmpeg"; the checked-in r1 code decoded the ref via `decode_ogg` (our own `MultistreamDecoder`). Both sides actually used *our* decoder in r1 — the asymmetry description was inverted vs. the code. | Both sides now decode through **ffmpeg libopus** (the reference decoder): ref via `ffmpeg_decode(&ref_ogg)`, ours via `write_ogg_opus` → `ffmpeg_decode(&ours_ogg)`. Own-decoder corr kept as extra column `corr_owndec` so decoder drift stays visible. | +| 2 | **No lag check.** `align_to_source` returned a lag but it was discarded; a lag pinned at the scan bound (±2000) would be a silent invalid measurement. | `align_to_source` return `(lag, aligned)` captured for both sides. **LAG GATE** (hard `assert`): `|lag| < MAX_LAG`. A bound-hit is a failed measurement, not a result. | +| 3 | **Full-band reference.** corr and `opus_compare_err` were computed against the full-band source, penalizing NB/WB encoders for HF energy they structurally cannot reproduce — the likely real cause of the r1 sign contradiction. | Per-row **band-limited reference**: NB → 4 kHz lowpass, WB → 8 kHz lowpass, hybrid-FB → unfiltered (`None`). `corr_bl` (primary) and `opus_compare_err` both use the band-limited source; `corr_fb` (full-band) kept as a secondary column. | +| 4 | **No ref mode.** libopus's actual mode was invisible; "12k-NB" assumed libopus also ran NB. | `first_audio_toc()` reads the ref Ogg, skips OpusHead/OpusTags, returns the first audio packet's TOC byte; `toc_mode_label()` prints it as `ref_mode=`. | + +## r1 vs r2 — per row + +SIGN RULE (verbatim): `gap = ref_corr - ours_corr; MORE NEGATIVE = OURS BETTER`. +`err_ratio = err_ours / err_ref; < 1 = ours better, > 1 = ref better`. +"agree" = gap and err_ratio point the same way. + +| row | | gap | err_ratio | agree? | +|-----|---|-----|-----------|--------| +| 12k-NB | r1 | -0.0308 (ours) | 3.532 (ref) | **no** | +| 12k-NB | r2 | -0.0690 (ours) | 0.061 (ours) | **yes** | +| 16k-NB | r1 | -0.0460 (ours) | 2.573 (ref) | **no** | +| 16k-NB | r2 | -0.1129 (ours) | 0.049 (ours) | **yes** | +| 24k-WB | r1 | -0.0759 (ours) | 4.452 (ref) | **no** | +| 24k-WB | r2 | -0.0940 (ours) | 0.428 (ours) | **yes** | +| 32k-Hyb | r1 | -0.0738 (ours) | 4.343 (ref) | **no** | +| 32k-Hyb | r2 | -0.0738 (ours) | 4.346 (ref) | **no** | + +**3 of 4 rows now agree.** The band-limited reference (defect 3) resolved the +contradiction for every NB/WB row. The single remaining disagreement is +**32k-Hyb**, the one row with `cutoff = None` (full-band): `corr_bl == corr_fb` +(0.9279) and `err_ratio` is essentially unchanged from r1 (4.343 → 4.346). At +full band, time-domain corr (dominated by the strong low-frequency energy where +both encoders agree) and frequency-domain `opus_compare_err` (which weights all +bands including HF) genuinely diverge — this is a metric-semantics difference, +not an instrument defect, and is reported as-is (no fix, per scope). + +## Lags (defect 2) + +| row | lag_ours | lag_ref | LAG GATE | +|-----|----------|---------|----------| +| 12k-NB | -1 | -2 | pass | +| 16k-NB | -1 | -1 | pass | +| 24k-WB | 0 | -1 | pass | +| 32k-Hyb | 0 | -1 | pass | + +All lags are 0–2 samples — far inside the ±2000 scan bound. No invalid +measurement. (Sub-sample residual is the encoder pre-skip / look-ahead +quantization to whole frames.) + +## Ref modes (defect 4) + +| row | ref_mode (libopus) | mode (ours) | +|-----|--------------------|-------------| +| 12k-NB | **SILK-WB** | SILK-NB | +| 16k-NB | **Hybrid-FB** | SILK-NB | +| 24k-WB | **Hybrid-FB** | SILK-WB | +| 32k-Hyb | Hybrid-FB | Hybrid-FB | + +libopus does **not** run narrowband at these rates: it auto-selects SILK-WB +(12 k) or full-band hybrid (16/24/32 k). Our encoder honors the forced +SILK-NB / SILK-WB / Hybrid-FB selection. At 12 k and 16 k the comparison is +therefore **NB-ours vs WB/hybrid-ref** — yet ours still wins corr. The +`ref_mode` column makes this mode asymmetry explicit (previously invisible). + +## Decoder drift (defect 1, extra column) + +`corr_owndec` (our `Decoder`) equals `corr_ours_bl` (ffmpeg libopus) to all +four printed decimals on every row (0.9499, 0.9697, 0.9483, 0.9279). Our +decoder produces bit-identical-quality output to ffmpeg libopus on our own +packets — **no decoder drift**. This also explains why switching the ref from +`decode_ogg` (r1) to `ffmpeg_decode` (r2) barely moved the 32k-Hyb numbers +(corr_ref 0.8541 both; err_ratio 4.343 → 4.346): the two decoders agree. + +## Gates + +- **RATE GATE** (soft, report-only): all rows within ±5% (max +3.3%). +- **LAG GATE** (hard, new): passed — no lag at scan bound. +- **DROPOUT GATE** (hard): passed — no ours-only dropouts (ref drops *more* + seconds than ours on every row: 61/69/67/65 vs 14/11/23/32). + +## Verification + +- `cargo check -p ec-opus --release --test conformance` — clean (0 warnings). +- `silk_library_gate_vs_libopus --ignored --nocapture` — **ok**, 125.5 s, + sweep written to `lanes/opus-silk-r2.sweep.txt`. +- `cargo test -p ec-opus --release` — **34 + 27 green** (10 ignored), 34.2 s. diff --git a/lanes/opus-silk-r2.sweep.txt b/lanes/opus-silk-r2.sweep.txt new file mode 100644 index 00000000..d4a7cf45 --- /dev/null +++ b/lanes/opus-silk-r2.sweep.txt @@ -0,0 +1,10 @@ +# ec-opus SILK/speech-rate gate vs ffmpeg libopus (r2) +# mono, 120s cap, VBR, 48kHz, Application::Voip; source reelm.wav +# r2: symmetric ffmpeg-libopus decode (both sides), lag gate, band-limited ref, ref mode +12k-NB: ref_mode=SILK-WB mode=SILK-NB, ref 12.0 ours 12.4 kbps (+3.3%), lag o=-1 r=-2, corr_bl o=0.9499 r=0.8809 gap=-0.0690, corr_fb o=0.8489 r=0.8181, corr_owndec o=0.9499, Q o=-821.88 r=-1925.90, err_ratio 0.061, minsec o=0.5164 r=0.2694, drop o=14 r=61 +16k-NB: ref_mode=Hybrid-FB mode=SILK-NB, ref 16.4 ours 16.8 kbps (+2.4%), lag o=-1 r=-1, corr_bl o=0.9697 r=0.8568 gap=-0.1129, corr_fb o=0.8665 r=0.8206, corr_owndec o=0.9697, Q o=-726.61 r=-1904.79, err_ratio 0.049, minsec o=0.5219 r=0.2967, drop o=11 r=69 +24k-WB: ref_mode=Hybrid-FB mode=SILK-WB, ref 24.0 ours 24.4 kbps (+1.7%), lag o=0 r=-1, corr_bl o=0.9483 r=0.8543 gap=-0.0940, corr_fb o=0.9168 r=0.8409, corr_owndec o=0.9483, Q o=-862.95 r=-1187.22, err_ratio 0.428, minsec o=0.6382 r=0.3396, drop o=23 r=67 +32k-Hyb: ref_mode=Hybrid-FB mode=Hybrid-FB, ref 31.8 ours 31.6 kbps (-0.5%), lag o=0 r=-1, corr_bl o=0.9279 r=0.8541 gap=-0.0738, corr_fb o=0.9279 r=0.8541, corr_owndec o=0.9279, Q o=-940.18 r=-434.68, err_ratio 4.346, minsec o=0.6283 r=0.3680, drop o=32 r=65 +RATE GATE: all rows within ±5% +LAG GATE: passed (no lag at scan bound) +DROPOUT GATE: passed (no ours-only dropouts)