diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 21d39df3..4d9f051a 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -3239,6 +3239,343 @@ fn encoder_library_gate_vs_libopus() { println!("DROPOUT GATE: passed (no ours-only dropouts)"); } +// --------------------------------------------------------------------------- +// SILK / speech-rate library gate vs libopus (lane opus-silk r1). +// +// Source: ~/Music/reelm.wav (real interview speech) downmixed to MONO. Rows: +// 12k NB, 16k NB, 24k WB (SILK), 32k hybrid. Ours via Encoder::new(48000, 1, +// Application::Voip) with set_bitrate and set_bandwidth/set_mode as needed so +// Voip really picks SILK/Hybrid — the mode each row took is printed from the +// first packet's TOC config byte (RFC 6716 §3.1). Reference: ffmpeg libopus +// -application voip -b:a , mono, VBR on. RATE GATE ±5%, DROPOUT GATE. +// SIGN RULE (verbatim): gap = ref_corr - ours_corr; MORE NEGATIVE = OURS BETTER. +// Run: cargo test -p ec-opus --release --test conformance \ +// silk_library_gate_vs_libopus -- --ignored --nocapture +// --------------------------------------------------------------------------- + +/// Mode label from a packet's TOC config byte (RFC 6716 §3.1): config = toc>>3. +fn toc_mode_label(toc: u8) -> &'static str { + match toc >> 3 { + 0..=3 => "SILK-NB", + 4..=7 => "SILK-MB", + 8..=11 => "SILK-WB", + 12 | 13 => "Hybrid-SWB", + 14 | 15 => "Hybrid-FB", + 16..=31 => "CELT", + _ => "??", + } +} + +// corner-cut: near-duplicate of ffmpeg_decode_pcm / ffmpeg_encode_libopus with +// -ac 1 and -application voip. Parameterising the existing helpers would touch +// the stereo gate's callsites; keep this lane self-contained. Ceiling: only the +// SILK gate needs mono voip — merge when a second mono consumer appears. +/// Decode any source into interleaved f32, 48 kHz, MONO, capped at `secs`. +fn ffmpeg_decode_pcm_mono(path: &Path, secs: f64) -> Vec { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args([ + "-vn", "-t", &format!("{secs}"), "-ac", "1", "-ar", "48000", "-f", "f32le", + "-acodec", "pcm_f32le", "-", + ]) + .output() + .expect("ffmpeg runs"); + assert!( + out.status.success(), + "ffmpeg mono decode failed for {}: {}", + path.display(), + String::from_utf8_lossy(&out.stderr) + ); + out.stdout + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect() +} + +/// Encode `src` to a mono Ogg/Opus file with ffmpeg libopus, VoIP application, +/// at `kbps` (VBR on), capped at `secs`. Realised rate read back from file size. +fn ffmpeg_encode_libopus_mono_voip(src: &Path, kbps: u32, out: &Path, secs: f64) { + let res = Command::new("ffmpeg") + .args(["-y", "-v", "error", "-i"]) + .arg(src) + .args([ + "-vn", "-t", &format!("{secs}"), "-ac", "1", "-ar", "48000", "-c:a", "libopus", + "-application", "voip", "-b:a", &format!("{kbps}k"), "-vbr", "on", + ]) + .arg(out) + .output() + .expect("ffmpeg runs"); + assert!( + res.status.success(), + "ffmpeg libopus mono voip encode failed at {kbps}k: {}", + String::from_utf8_lossy(&res.stderr) + ); +} + +/// 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() { + const SECS: f64 = 120.0; // 2 min cap + const FRAME: usize = 960; // 20 ms at 48 kHz + const CHANNELS: usize = 1; // MONO + const MAX_LAG: usize = 2000; + + let src = shellexpand("~/Music/reelm.wav"); + assert!(src.exists(), "source missing: {}", src.display()); + + 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-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; + + // (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); + + // Reference: ffmpeg libopus, mono, voip, VBR; realised rate from size. + 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; + // 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"); + enc.set_bitrate((ref_kbps * 1000.0).round() as u32); + if let Some(b) = bw { + enc.set_bandwidth(Some(b)); + } + if let Some(m) = mode { + 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(); + let mut toc_buf = [0u8; 1500]; + probe + .encode_float(&source_pcm[..FRAME * CHANNELS], FRAME, &mut toc_buf) + .expect("encode probe"); + let mode_label = toc_mode_label(toc_buf[0]); + + // 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 (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 = (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(&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); + let q_ref = opus_compare(&s_i, &r_i, CHANNELS); + let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS); + 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 }; + + // 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 { + rate_violations.push(format!("{tag}: rate {rate_pct:+.1}% (|>5%)")); + } + if drop_ours > 0 && drop_ref == 0 { + dropout_violations.push(format!( + "{tag}: ours dropped {drop_ours}s below 0.9 corr, ref 0s" + )); + } + let row = format!( + "{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(&ref_ogg); + let _ = fs::remove_file(&ours_ogg); + + // Rate gate: report violations, never panic. + let rate_gate = if rate_violations.is_empty() { + "RATE GATE: all rows within ±5%".to_string() + } else { + let mut s = "RATE GATE violations (|rate%| > 5):".to_string(); + for v in &rate_violations { + s.push_str("\n "); + s.push_str(v); + } + s + }; + if rate_violations.is_empty() { + println!("{rate_gate}"); + } 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(), + "DROPOUT GATE failed (ours dropped seconds ref kept):\n {}", + dropout_violations.join("\n ") + ); + let drop_gate = "DROPOUT GATE: passed (no ours-only dropouts)"; + println!("{drop_gate}"); + + // 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 (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(); + println!("wrote {}", sweep_path.display()); +} + // --------------------------------------------------------------------------- // 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. diff --git a/lanes/opus-silk-r1.report.md b/lanes/opus-silk-r1.report.md new file mode 100644 index 00000000..e73dc6f4 --- /dev/null +++ b/lanes/opus-silk-r1.report.md @@ -0,0 +1,69 @@ +# opus-silk r1 — SILK / speech-rate library gate vs libopus + +Lane `lane-opus-silk`, run 2026-08-23. Measures our `ec-opus` SILK/speech-rate +encoder against ffmpeg libopus on real speech (`~/Music/reelm.wav`), MONO, 48 kHz, +`Application::Voip`, VBR constrained, 120 s cap. + +- **Source:** `~/Music/reelm.wav` downmixed to mono (`-ac 1 -ar 48000`), 120 s cap. +- **Ours:** `Encoder::new(48000, 1, Application::Voip)`, `set_vbr_constrained(true)`, + `set_bitrate` to the reference's realised rate; `set_bandwidth`/`set_mode` per row so + Voip actually codes SILK/Hybrid (mode printed from the first packet's TOC config byte, + RFC 6716 §3.1). +- **Reference:** `ffmpeg libopus -application voip -b:a k -vbr on`, mono. +- **SIGN RULE:** `gap = ref_corr - ours_corr`; **more negative = ours better**. +- **RATE GATE** ±5% (ours_kbps vs ref_kbps); **DROPOUT GATE** ours must not drop + seconds the reference kept. +- **Run:** `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-opus-sb cargo test -p ec-opus --release --test conformance silk_library_gate_vs_libopus -- --ignored --nocapture` + +## Gates + +- **RATE GATE:** all rows within ±5%. PASSED (reported, not asserted). +- **DROPOUT GATE:** passed (no ours-only dropouts). PASSED (asserted). + +## Results + +| row | mode | ours kbps | ref kbps | rate % | corr ours | corr ref | gap | Q ours | Q ref | err_ratio | minsec ours | minsec ref | drop ours | drop ref | +|----------|------------|-----------|----------|---------|-----------|----------|---------|---------|--------|-----------|-------------|------------|-----------|----------| +| 12k-NB | SILK-NB | 12.4 | 12.0 | +3.3 | 0.8489 | 0.8181 | -0.0308 | -821.15 | -401.54| 3.532 | 0.2408 | 0.2079 | 67 | 69 | +| 16k-NB | SILK-NB | 16.8 | 16.4 | +2.4 | 0.8665 | 0.8205 | -0.0460 | -725.78 | -416.74| 2.573 | 0.2420 | 0.2861 | 63 | 73 | +| 24k-WB | SILK-WB | 24.4 | 24.0 | +1.7 | 0.9168 | 0.8409 | -0.0759 | -861.98 | -367.31| 4.452 | 0.5591 | 0.3300 | 40 | 71 | +| 32k-Hyb | Hybrid-FB | 31.6 | 31.8 | -0.5 | 0.9279 | 0.8541 | -0.0738 | -939.95 | -434.68| 4.343 | 0.6284 | 0.3680 | 33 | 65 | + +### Mode per row (actual, from TOC config byte) + +- **12k-NB** → `SILK-NB` (config 0–3). Auto: per-channel 12k ≤ 12k → SILK NB (8 kHz). No forcing needed. +- **16k-NB** → `SILK-NB` (config 0–3). Forced `Bandwidth::Narrow`; without forcing, 16k would auto-pick SILK-MB (12 kHz). +- **24k-WB** → `SILK-WB` (config 8–11). Forced `Mode::Silk` + `Bandwidth::Wide`; without forcing, 24k ≥ 20k would leave SILK and `hybrid_choice` would pick Hybrid-SWB. +- **32k-Hyb** → `Hybrid-FB` (config 14–15). Auto: per-channel 32k ∈ 20k..40k → Hybrid; `auto_bandwidth` equiv = 32k×0.7 = 22.4k ≥ 20k → Full. No forcing needed. + +## Three worst per-row observations (measured only) + +1. **err_ratio peaks at 24k-WB (4.452).** Despite ours winning on aggregate + correlation (`gap = -0.0759`, the best margin of any row), the `opus_compare` + error metric is 4.45× the reference's — the worst err_ratio of the table. + 32k-Hyb is close behind (4.343). The two higher-bandwidth rows (WB, Hybrid-FB) + carry the largest err_ratio, while the NB rows sit lower (2.573–3.532). Ours + beats ref on correlation everywhere yet loses on the compare-error metric + everywhere. + +2. **Per-second correlation floor is lowest at 12k-NB (`minsec` ours = 0.2408).** + The single weakest second across all rows; 16k-NB is nearly as low (0.2420). + The NB rows have the shallowest per-second corr floor even though aggregate + corr is respectable (0.85–0.87). Notably the reference's 12k floor is even + lower (0.2079), so ours is not the absolute worst here, but 12k-NB is where + the encoder is most second-to-second fragile. + +3. **Dropout seconds are highest at 12k-NB (ours 67, ref 69).** The most seconds + below the 0.9 corr threshold for both encoders; counts fall monotonically with + rate (ours 67 → 63 → 40 → 33). The DROPOUT GATE passes only because the + reference drops *at least as many* seconds in every row (ref 69, 73, 71, 65) — + ours actually drops fewer seconds than ref in all four rows, but the absolute + count is high at the low rates. + +### Rate budgeting note (measured, no fix) + +Ours overshoots the reference's realised rate on the three SILK rows +(+3.3%, +2.4%, +1.7%) and undershoots on the hybrid row (-0.5%). All within the +±5% RATE GATE. Consistent with the encoder's known state: SILK packets are not +yet budgeted against the target rate (encoder.rs "D2b"). Reported as observed; +no tuning performed this lane. diff --git a/lanes/opus-silk-r1.sweep.txt b/lanes/opus-silk-r1.sweep.txt new file mode 100644 index 00000000..b68ebd04 --- /dev/null +++ b/lanes/opus-silk-r1.sweep.txt @@ -0,0 +1,8 @@ +# ec-opus SILK/speech-rate gate vs ffmpeg libopus (r1) +# mono, 120s cap, VBR, 48kHz, Application::Voip; source reelm.wav +12k-NB: mode=SILK-NB, ref 12.0 ours 12.4 kbps (+3.3%), corr o=0.8489 r=0.8181 gap=-0.0308, Q o=-821.15 r=-401.54, err_ratio 3.532, minsec o=0.2408 r=0.2079, drop o=67 r=69 +16k-NB: mode=SILK-NB, ref 16.4 ours 16.8 kbps (+2.4%), corr o=0.8665 r=0.8205 gap=-0.0460, Q o=-725.78 r=-416.74, err_ratio 2.573, minsec o=0.2420 r=0.2861, drop o=63 r=73 +24k-WB: mode=SILK-WB, ref 24.0 ours 24.4 kbps (+1.7%), corr o=0.9168 r=0.8409 gap=-0.0759, Q o=-861.98 r=-367.31, err_ratio 4.452, minsec o=0.5591 r=0.3300, drop o=40 r=71 +32k-Hyb: mode=Hybrid-FB, ref 31.8 ours 31.6 kbps (-0.5%), corr o=0.9279 r=0.8541 gap=-0.0738, Q o=-939.95 r=-434.68, err_ratio 4.343, minsec o=0.6284 r=0.3680, drop o=33 r=65 +RATE GATE: all rows within ±5% +DROPOUT GATE: passed (no ours-only dropouts) 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)