forge
Explore
Log in

Don't you dare go Hollow

SILK library gate vs libopus on real speech

Browse files at this commit

11f9cfe3939b8f6fccb263b10621a68d02d10ee7Ahmet Kaan GümüşParent: 6a058a0
  • test
    • SILK library gate vs libopus on real speech
Show full message
test(opus-silk/r1): SILK library gate vs libopus on real speech
crates/ec-opus/tests/conformance.rsmodified+227 -0
@@ -3239,6 +3239,233 @@ fn encoder_library_gate_vs_libopus() {
3239 println!("DROPOUT GATE: passed (no ours-only dropouts)");3239 println!("DROPOUT GATE: passed (no ours-only dropouts)");
3240 }3240 }
3241 3241
3242+// ---------------------------------------------------------------------------
3243+// SILK / speech-rate library gate vs libopus (lane opus-silk r1).
3244+//
3245+// Source: ~/Music/reelm.wav (real interview speech) downmixed to MONO. Rows:
3246+// 12k NB, 16k NB, 24k WB (SILK), 32k hybrid. Ours via Encoder::new(48000, 1,
3247+// Application::Voip) with set_bitrate and set_bandwidth/set_mode as needed so
3248+// Voip really picks SILK/Hybrid — the mode each row took is printed from the
3249+// first packet's TOC config byte (RFC 6716 §3.1). Reference: ffmpeg libopus
3250+// -application voip -b:a <rate>, mono, VBR on. RATE GATE ±5%, DROPOUT GATE.
3251+// SIGN RULE (verbatim): gap = ref_corr - ours_corr; MORE NEGATIVE = OURS BETTER.
3252+// Run: cargo test -p ec-opus --release --test conformance \
3253+// silk_library_gate_vs_libopus -- --ignored --nocapture
3254+// ---------------------------------------------------------------------------
3255+
3256+/// Mode label from a packet's TOC config byte (RFC 6716 §3.1): config = toc>>3.
3257+fn toc_mode_label(toc: u8) -> &'static str {
3258+ match toc >> 3 {
3259+ 0..=3 => "SILK-NB",
3260+ 4..=7 => "SILK-MB",
3261+ 8..=11 => "SILK-WB",
3262+ 12 | 13 => "Hybrid-SWB",
3263+ 14 | 15 => "Hybrid-FB",
3264+ 16..=31 => "CELT",
3265+ _ => "??",
3266+ }
3267+}
3268+
3269+// corner-cut: near-duplicate of ffmpeg_decode_pcm / ffmpeg_encode_libopus with
3270+// -ac 1 and -application voip. Parameterising the existing helpers would touch
3271+// the stereo gate's callsites; keep this lane self-contained. Ceiling: only the
3272+// SILK gate needs mono voip — merge when a second mono consumer appears.
3273+/// Decode any source into interleaved f32, 48 kHz, MONO, capped at `secs`.
3274+fn ffmpeg_decode_pcm_mono(path: &Path, secs: f64) -> Vec<f32> {
3275+ let out = Command::new("ffmpeg")
3276+ .args(["-v", "error", "-i"])
3277+ .arg(path)
3278+ .args([
3279+ "-vn", "-t", &format!("{secs}"), "-ac", "1", "-ar", "48000", "-f", "f32le",
3280+ "-acodec", "pcm_f32le", "-",
3281+ ])
3282+ .output()
3283+ .expect("ffmpeg runs");
3284+ assert!(
3285+ out.status.success(),
3286+ "ffmpeg mono decode failed for {}: {}",
3287+ path.display(),
3288+ String::from_utf8_lossy(&out.stderr)
3289+ );
3290+ out.stdout
3291+ .chunks_exact(4)
3292+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
3293+ .collect()
3294+}
3295+
3296+/// Encode `src` to a mono Ogg/Opus file with ffmpeg libopus, VoIP application,
3297+/// at `kbps` (VBR on), capped at `secs`. Realised rate read back from file size.
3298+fn ffmpeg_encode_libopus_mono_voip(src: &Path, kbps: u32, out: &Path, secs: f64) {
3299+ let res = Command::new("ffmpeg")
3300+ .args(["-y", "-v", "error", "-i"])
3301+ .arg(src)
3302+ .args([
3303+ "-vn", "-t", &format!("{secs}"), "-ac", "1", "-ar", "48000", "-c:a", "libopus",
3304+ "-application", "voip", "-b:a", &format!("{kbps}k"), "-vbr", "on",
3305+ ])
3306+ .arg(out)
3307+ .output()
3308+ .expect("ffmpeg runs");
3309+ assert!(
3310+ res.status.success(),
3311+ "ffmpeg libopus mono voip encode failed at {kbps}k: {}",
3312+ String::from_utf8_lossy(&res.stderr)
3313+ );
3314+}
3315+
3316+#[test]
3317+#[ignore]
3318+fn silk_library_gate_vs_libopus() {
3319+ const SECS: f64 = 120.0; // 2 min cap
3320+ const FRAME: usize = 960; // 20 ms at 48 kHz
3321+ const CHANNELS: usize = 1; // MONO
3322+ const MAX_LAG: usize = 2000;
3323+
3324+ let src = shellexpand("~/Music/reelm.wav");
3325+ assert!(src.exists(), "source missing: {}", src.display());
3326+
3327+ let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes");
3328+ fs::create_dir_all(&lanes_dir).unwrap();
3329+ let sweep_path = lanes_dir.join("opus-silk-r1.sweep.txt");
3330+ let scratch = lanes_dir.join("opus-silk-r1.scratch.ogg");
3331+
3332+ // Source PCM: mono, 48 kHz.
3333+ let source_pcm = ffmpeg_decode_pcm_mono(&src, SECS);
3334+ let source_frames = source_pcm.len() / CHANNELS;
3335+ assert!(source_frames > 48_000, "source too short");
3336+ let seconds = source_frames as f64 / 48000.0;
3337+ let source_i16 = to_i16(&source_pcm);
3338+
3339+ // (label, kbps, forced bandwidth, forced mode). mode/bw chosen so Voip at
3340+ // these rates really codes SILK/Hybrid, not CELT (see wants_silk/
3341+ // hybrid_choice): 12k auto-NB, 16k forced-NB (auto would pick MB), 24k
3342+ // forced-Silk+Wide (auto would pick hybrid), 32k auto-hybrid.
3343+ let rows: &[(&str, u32, Option<Bandwidth>, Option<Mode>)] = &[
3344+ ("12k-NB", 12, None, None),
3345+ ("16k-NB", 16, Some(Bandwidth::Narrow), None),
3346+ ("24k-WB", 24, Some(Bandwidth::Wide), Some(Mode::Silk)),
3347+ ("32k-Hyb", 32, None, None),
3348+ ];
3349+
3350+ let mut out_rows: Vec<String> = Vec::new();
3351+ let mut rate_violations: Vec<String> = Vec::new();
3352+ let mut dropout_violations: Vec<String> = Vec::new();
3353+
3354+ for &(tag, kbps, bw, mode) in rows {
3355+ // Reference: ffmpeg libopus, mono, voip, VBR; realised rate from size.
3356+ ffmpeg_encode_libopus_mono_voip(&src, kbps, &scratch, SECS);
3357+ let ref_bytes = fs::metadata(&scratch).map(|m| m.len() as usize).unwrap_or(0);
3358+ let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
3359+ let (ref_dec, ref_ch) = decode_ogg(&scratch);
3360+ assert_eq!(ref_ch, CHANNELS, "{tag}: ref not mono");
3361+ let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CHANNELS, MAX_LAG);
3362+
3363+ // Ours: ec-opus Voip at the reference's realised rate.
3364+ let mut enc = Encoder::new(48000, CHANNELS, Application::Voip).expect("encoder");
3365+ enc.set_bitrate((ref_kbps * 1000.0).round() as u32);
3366+ if let Some(b) = bw {
3367+ enc.set_bandwidth(Some(b));
3368+ }
3369+ if let Some(m) = mode {
3370+ enc.set_mode(Some(m));
3371+ }
3372+ enc.set_vbr_constrained(true);
3373+
3374+ // Probe which mode the encoder actually picked, from the first TOC byte.
3375+ let mut probe = enc.clone();
3376+ let mut toc_buf = [0u8; 1500];
3377+ probe
3378+ .encode_float(&source_pcm[..FRAME * CHANNELS], FRAME, &mut toc_buf)
3379+ .expect("encode probe");
3380+ let mode_label = toc_mode_label(toc_buf[0]);
3381+
3382+ let (ours_dec, ours_bytes) = roundtrip_own(&mut enc, &source_pcm, CHANNELS, FRAME);
3383+ let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0;
3384+ let ours_trim: Vec<f32> = ours_dec.into_iter().take(source_frames * CHANNELS).collect();
3385+ let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
3386+ let ours_i16 = to_i16(&ours_aligned);
3387+ let ref_i16 = to_i16(&ref_aligned);
3388+
3389+ let cmp_frames = (source_i16.len() / CHANNELS)
3390+ .min(ours_i16.len() / CHANNELS)
3391+ .min(ref_i16.len() / CHANNELS);
3392+ let trim = |v: &[i16]| -> Vec<i16> { v[..cmp_frames * CHANNELS].to_vec() };
3393+ let s_i = trim(&source_i16);
3394+ let o_i = trim(&ours_i16);
3395+ let r_i = trim(&ref_i16);
3396+ let q_ours = opus_compare(&s_i, &o_i, CHANNELS);
3397+ let q_ref = opus_compare(&s_i, &r_i, CHANNELS);
3398+ let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS);
3399+ let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS);
3400+ let err_ratio = if err_ref > 0.0 { err_ours / err_ref } else { f64::INFINITY };
3401+
3402+ let corr_ours = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS);
3403+ let corr_ref = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS);
3404+ let gap = corr_ref - corr_ours;
3405+ let (minsec_ours, drop_ours) = per_second_corr(&source_pcm, &ours_aligned, CHANNELS);
3406+ let (minsec_ref, drop_ref) = per_second_corr(&source_pcm, &ref_aligned, CHANNELS);
3407+ let rate_pct = (ours_kbps / ref_kbps - 1.0) * 100.0;
3408+
3409+ if rate_pct.abs() > 5.0 {
3410+ rate_violations.push(format!("{tag}: rate {rate_pct:+.1}% (|>5%)"));
3411+ }
3412+ if drop_ours > 0 && drop_ref == 0 {
3413+ dropout_violations.push(format!(
3414+ "{tag}: ours dropped {drop_ours}s below 0.9 corr, ref 0s"
3415+ ));
3416+ }
3417+ let row = format!(
3418+ "{tag}: mode={mode_label}, ref {ref_kbps:.1} ours {ours_kbps:.1} kbps ({rate_pct:+.1}%), \
3419+ corr o={corr_ours:.4} r={corr_ref:.4} gap={gap:+.4}, \
3420+ Q o={q_ours:.2} r={q_ref:.2}, err_ratio {err_ratio:.3}, \
3421+ minsec o={minsec_ours:.4} r={minsec_ref:.4}, drop o={drop_ours} r={drop_ref}"
3422+ );
3423+ println!("{row}");
3424+ out_rows.push(row);
3425+ }
3426+ let _ = fs::remove_file(&scratch);
3427+
3428+ // Rate gate: report violations, never panic.
3429+ let rate_gate = if rate_violations.is_empty() {
3430+ "RATE GATE: all rows within ±5%".to_string()
3431+ } else {
3432+ let mut s = "RATE GATE violations (|rate%| > 5):".to_string();
3433+ for v in &rate_violations {
3434+ s.push_str("\n ");
3435+ s.push_str(v);
3436+ }
3437+ s
3438+ };
3439+ if rate_violations.is_empty() {
3440+ println!("{rate_gate}");
3441+ } else {
3442+ eprintln!("{rate_gate}");
3443+ }
3444+ // Dropout gate: hard fail — a second the reference kept must not drop out.
3445+ assert!(
3446+ dropout_violations.is_empty(),
3447+ "DROPOUT GATE failed (ours dropped seconds ref kept):\n {}",
3448+ dropout_violations.join("\n ")
3449+ );
3450+ let drop_gate = "DROPOUT GATE: passed (no ours-only dropouts)";
3451+ println!("{drop_gate}");
3452+
3453+ // Sweep file: raw rows + GATE lines (lane deliverable).
3454+ let mut table = String::new();
3455+ table.push_str("# ec-opus SILK/speech-rate gate vs ffmpeg libopus (r1)\n");
3456+ table.push_str("# mono, 120s cap, VBR, 48kHz, Application::Voip; source reelm.wav\n");
3457+ for r in &out_rows {
3458+ table.push_str(r);
3459+ table.push('\n');
3460+ }
3461+ table.push_str(&rate_gate);
3462+ table.push('\n');
3463+ table.push_str(drop_gate);
3464+ table.push('\n');
3465+ fs::write(&sweep_path, table).unwrap();
3466+ println!("wrote {}", sweep_path.display());
3467+}
3468+
3242 // ---------------------------------------------------------------------------3469 // ---------------------------------------------------------------------------
3243 // Harness: feed identical raw PCM (.sw, s16le interleaved) to our opus_compare3470 // Harness: feed identical raw PCM (.sw, s16le interleaved) to our opus_compare
3244 // so it can be checked against the C `opus_compare` tool on the SAME bytes.3471 // so it can be checked against the C `opus_compare` tool on the SAME bytes.
lanes/opus-silk-r1.report.mdadded+69 -0
@@ -0,0 +1,69 @@
1+# opus-silk r1 — SILK / speech-rate library gate vs libopus
2+
3+Lane `lane-opus-silk`, run 2026-08-23. Measures our `ec-opus` SILK/speech-rate
4+encoder against ffmpeg libopus on real speech (`~/Music/reelm.wav`), MONO, 48 kHz,
5+`Application::Voip`, VBR constrained, 120 s cap.
6+
7+- **Source:** `~/Music/reelm.wav` downmixed to mono (`-ac 1 -ar 48000`), 120 s cap.
8+- **Ours:** `Encoder::new(48000, 1, Application::Voip)`, `set_vbr_constrained(true)`,
9+ `set_bitrate` to the reference's realised rate; `set_bandwidth`/`set_mode` per row so
10+ Voip actually codes SILK/Hybrid (mode printed from the first packet's TOC config byte,
11+ RFC 6716 §3.1).
12+- **Reference:** `ffmpeg libopus -application voip -b:a <rate>k -vbr on`, mono.
13+- **SIGN RULE:** `gap = ref_corr - ours_corr`; **more negative = ours better**.
14+- **RATE GATE** ±5% (ours_kbps vs ref_kbps); **DROPOUT GATE** ours must not drop
15+ seconds the reference kept.
16+- **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`
17+
18+## Gates
19+
20+- **RATE GATE:** all rows within ±5%. PASSED (reported, not asserted).
21+- **DROPOUT GATE:** passed (no ours-only dropouts). PASSED (asserted).
22+
23+## Results
24+
25+| 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 |
26+|----------|------------|-----------|----------|---------|-----------|----------|---------|---------|--------|-----------|-------------|------------|-----------|----------|
27+| 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 |
28+| 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 |
29+| 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 |
30+| 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 |
31+
32+### Mode per row (actual, from TOC config byte)
33+
34+- **12k-NB** → `SILK-NB` (config 0–3). Auto: per-channel 12k ≤ 12k → SILK NB (8 kHz). No forcing needed.
35+- **16k-NB** → `SILK-NB` (config 0–3). Forced `Bandwidth::Narrow`; without forcing, 16k would auto-pick SILK-MB (12 kHz).
36+- **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.
37+- **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.
38+
39+## Three worst per-row observations (measured only)
40+
41+1. **err_ratio peaks at 24k-WB (4.452).** Despite ours winning on aggregate
42+ correlation (`gap = -0.0759`, the best margin of any row), the `opus_compare`
43+ error metric is 4.45× the reference's — the worst err_ratio of the table.
44+ 32k-Hyb is close behind (4.343). The two higher-bandwidth rows (WB, Hybrid-FB)
45+ carry the largest err_ratio, while the NB rows sit lower (2.573–3.532). Ours
46+ beats ref on correlation everywhere yet loses on the compare-error metric
47+ everywhere.
48+
49+2. **Per-second correlation floor is lowest at 12k-NB (`minsec` ours = 0.2408).**
50+ The single weakest second across all rows; 16k-NB is nearly as low (0.2420).
51+ The NB rows have the shallowest per-second corr floor even though aggregate
52+ corr is respectable (0.85–0.87). Notably the reference's 12k floor is even
53+ lower (0.2079), so ours is not the absolute worst here, but 12k-NB is where
54+ the encoder is most second-to-second fragile.
55+
56+3. **Dropout seconds are highest at 12k-NB (ours 67, ref 69).** The most seconds
57+ below the 0.9 corr threshold for both encoders; counts fall monotonically with
58+ rate (ours 67 → 63 → 40 → 33). The DROPOUT GATE passes only because the
59+ reference drops *at least as many* seconds in every row (ref 69, 73, 71, 65) —
60+ ours actually drops fewer seconds than ref in all four rows, but the absolute
61+ count is high at the low rates.
62+
63+### Rate budgeting note (measured, no fix)
64+
65+Ours overshoots the reference's realised rate on the three SILK rows
66+(+3.3%, +2.4%, +1.7%) and undershoots on the hybrid row (-0.5%). All within the
67+±5% RATE GATE. Consistent with the encoder's known state: SILK packets are not
68+yet budgeted against the target rate (encoder.rs "D2b"). Reported as observed;
69+no tuning performed this lane.
lanes/opus-silk-r1.sweep.txtadded+8 -0
@@ -0,0 +1,8 @@
1+# ec-opus SILK/speech-rate gate vs ffmpeg libopus (r1)
2+# mono, 120s cap, VBR, 48kHz, Application::Voip; source reelm.wav
3+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
4+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
5+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
6+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
7+RATE GATE: all rows within ±5%
8+DROPOUT GATE: passed (no ours-only dropouts)