forge
Explore
Log in

Don't you dare go Hollow

ec-opus: a missing RFC 6716 vector FAILS under EC_REQUIRE_FIXTURES

Browse files at this commit

168b491d9341664e4f25b6958fcf9f7244f5bbcfAhmet Kaan GümüşParent: 62abc01
`rfc6716_test_vectors` continued past every absent vector with a bare
eprintln, so on a worktree -- no gitignored root `fixtures/` -- the whole
RFC 6716 Section 6 conformance claim was decided by zero vectors, green.

The per-vector arm now names the exact missing path, `scripts/link-fixtures.sh`
and `scripts/fetch-vectors.sh`, and fails under EC_REQUIRE_FIXTURES=1. The
`if path.exists()` arms at the two robustness/perf sites are optional-input
blocks inside tests that do not assert on them, so they stay as they are.

Red: EC_REQUIRE_FIXTURES=1 with `fixtures/` unlinked fails
rfc6716_test_vectors ("RFC 6716 test vector testvector01 missing at
.../opus_testvectors/testvector01.bit -- this gate would prove nothing").
Green: 1 passed with `fixtures/` linked (179.2s).
crates/ec-opus/tests/conformance.rsmodified+707 -214
@@ -412,11 +412,31 @@ const VECTORS: [&str; 12] = [
412412 /// MUST stay within the `opus_compare` threshold (quality >= 0).
413413 #[test]
414414 fn rfc6716_test_vectors() {
415+ // A missing test vector made this gate skip GREEN having decoded nothing —
416+ // the "gate skips on its own failure" class. The root `fixtures/` tree is
417+ // gitignored, so `git worktree add` hands every lane worktree a tree without
418+ // it. `EC_REQUIRE_FIXTURES=1` turns a missing vector into a hard failure
419+ // naming the exact path and the command that produces it; unset, the skip
420+ // is kept and now says what it skipped. Set it in every batch run.
421+ let base = vectors_dir();
415422 let mut table = Vec::new();
416423 for name in VECTORS {
417- let path = vectors_dir().join(format!("{name}.bit"));
424+ let path = base.join(format!("{name}.bit"));
418425 if !path.exists() {
419- eprintln!("{name}: missing, skipped (run scripts/fetch-vectors.sh)");
426+ assert!(
427+ std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
428+ "RFC 6716 test vector {name} missing at {} — this gate would prove \
429+ nothing. A worktree has no gitignored root `fixtures/`: run \
430+ scripts/link-fixtures.sh, or fetch it with scripts/fetch-vectors.sh.",
431+ path.display()
432+ );
433+ eprintln!(
434+ "SKIP RFC 6716 test vector {name} missing at {} — this gate proved \
435+ nothing; run scripts/link-fixtures.sh, or fetch it with \
436+ scripts/fetch-vectors.sh (or set EC_REQUIRE_FIXTURES=1 to make this \
437+ a failure).",
438+ path.display()
439+ );
420440 continue;
421441 }
422442 let packets = read_vector(&path);
@@ -1595,7 +1615,14 @@ fn ogg_opus_round_trip_duration_is_exact() {
15951615 let packets = encode_packets(&mut enc, &pcm, 2);
15961616 let path = temp_path("duration.opus");
15971617 let pre_skip = enc.look_ahead(960);
1598- write_ogg_opus(&path, &packets, opus_head(2, pre_skip as u16, None), 2, total, pre_skip as i64);
1618+ write_ogg_opus(
1619+ &path,
1620+ &packets,
1621+ opus_head(2, pre_skip as u16, None),
1622+ 2,
1623+ total,
1624+ pre_skip as i64,
1625+ );
15991626 let probe = Command::new("ffprobe")
16001627 .args([
16011628 "-v",
@@ -2380,7 +2407,14 @@ fn oracle_decode(
23802407 return None;
23812408 }
23822409 let path = temp_path(&format!("{name}.opus"));
2383- write_ogg_opus(&path, packets, opus_head(1, pre_skip as u16, None), 1, samples, pre_skip as i64);
2410+ write_ogg_opus(
2411+ &path,
2412+ packets,
2413+ opus_head(1, pre_skip as u16, None),
2414+ 1,
2415+ samples,
2416+ pre_skip as i64,
2417+ );
23842418 let out = Command::new("ffmpeg")
23852419 .args(["-v", "warning", "-c:a", "libopus", "-i"])
23862420 .arg(&path)
@@ -2557,7 +2591,10 @@ fn hybrid_layers_align() {
25572591 (plb - phb).abs() <= 3,
25582592 "layers misaligned: LB +{plb} vs HB +{phb}"
25592593 );
2560- assert!((phb - delay).abs() <= 2, "HB peak +{phb}, look_ahead {delay}");
2594+ assert!(
2595+ (phb - delay).abs() <= 2,
2596+ "HB peak +{phb}, look_ahead {delay}"
2597+ );
25612598 }
25622599
25632600 /// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks
@@ -2845,7 +2882,12 @@ fn ffmpeg_encode_libopus(src: &Path, kbps: u32, out: &Path, secs: f64) {
28452882 /// file — and the correlation is computed inline without per-lag allocations.
28462883 /// The delay lands the peak at a positive lag; the symmetric scan keeps the
28472884 /// gate honest if a reference decoder shifts the other way.
2848-fn align_to_source(source: &[f32], decoded: &[f32], channels: usize, max_lag: usize) -> (i32, Vec<f32>) {
2885+fn align_to_source(
2886+ source: &[f32],
2887+ decoded: &[f32],
2888+ channels: usize,
2889+ max_lag: usize,
2890+) -> (i32, Vec<f32>) {
28492891 let sf = source.len() / channels;
28502892 let df = decoded.len() / channels;
28512893 let scan_frames = sf.min(df).min(48000 * 10);
@@ -2881,7 +2923,11 @@ fn align_to_source(source: &[f32], decoded: &[f32], channels: usize, max_lag: us
28812923 }
28822924 // Build a source-length aligned copy using the chosen lag.
28832925 let mut aligned = vec![0.0f32; sf * channels];
2884- let i0 = if best_lag < 0 { (-best_lag) as usize } else { 0 };
2926+ let i0 = if best_lag < 0 {
2927+ (-best_lag) as usize
2928+ } else {
2929+ 0
2930+ };
28852931 let j0 = if best_lag < 0 { 0 } else { best_lag as usize };
28862932 let len = sf.saturating_sub(i0).min(df.saturating_sub(j0));
28872933 for i in 0..len {
@@ -3017,7 +3063,9 @@ fn reelm64_persecond_diag() {
30173063 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_dec, CHANNELS, MAX_LAG);
30183064
30193065 // Per-second correlation for both
3020- let n_frames = (source_frames).min(ours_aligned.len() / CHANNELS).min(ref_aligned.len() / CHANNELS);
3066+ let n_frames = (source_frames)
3067+ .min(ours_aligned.len() / CHANNELS)
3068+ .min(ref_aligned.len() / CHANNELS);
30213069 let sec_samples = 48000usize;
30223070 let frames_per_sec = sec_samples / FRAME; // 50
30233071
@@ -3034,11 +3082,19 @@ fn reelm64_persecond_diag() {
30343082 let s = source_pcm[(start + i) * CHANNELS + ch] as f64;
30353083 let o = ours_aligned[(start + i) * CHANNELS + ch] as f64;
30363084 let r = ref_aligned[(start + i) * CHANNELS + ch] as f64;
3037- sxy_o += s * o; sxx_o += s * s; syy_o += o * o;
3038- sxy_r += s * r; sxx_r += s * s; syy_r += r * r;
3085+ sxy_o += s * o;
3086+ sxx_o += s * s;
3087+ syy_o += o * o;
3088+ sxy_r += s * r;
3089+ sxx_r += s * s;
3090+ syy_r += r * r;
3091+ }
3092+ if sxx_o > 0.0 && syy_o > 0.0 {
3093+ acc_o += sxy_o / (sxx_o * syy_o).sqrt();
3094+ }
3095+ if sxx_r > 0.0 && syy_r > 0.0 {
3096+ acc_r += sxy_r / (sxx_r * syy_r).sqrt();
30393097 }
3040- if sxx_o > 0.0 && syy_o > 0.0 { acc_o += sxy_o / (sxx_o * syy_o).sqrt(); }
3041- if sxx_r > 0.0 && syy_r > 0.0 { acc_r += sxy_r / (sxx_r * syy_r).sqrt(); }
30423098 }
30433099 let co = acc_o / CHANNELS as f64;
30443100 let cr = acc_r / CHANNELS as f64;
@@ -3054,10 +3110,19 @@ fn reelm64_persecond_diag() {
30543110 let mut out_str = String::new();
30553111 out_str.push_str("# reelm@64k per-second diagnostic (r1, current code)\n");
30563112 out_str.push_str("# 120s cap, 20ms frames, VBR constrained, 48kHz stereo\n");
3057- out_str.push_str(&format!("# total frames: ours={} ref={}\n", diags.len(), ref_payload.len()));
3113+ out_str.push_str(&format!(
3114+ "# total frames: ours={} ref={}\n",
3115+ diags.len(),
3116+ ref_payload.len()
3117+ ));
30583118 let total_corr_o: f64 = sec_rows.iter().map(|r| r.1).sum::<f64>() / sec_rows.len() as f64;
30593119 let total_corr_r: f64 = sec_rows.iter().map(|r| r.2).sum::<f64>() / sec_rows.len() as f64;
3060- out_str.push_str(&format!("# avg corr: ours={:.4} ref={:.4} gap={:+.4}\n\n", total_corr_o, total_corr_r, total_corr_r - total_corr_o));
3120+ out_str.push_str(&format!(
3121+ "# avg corr: ours={:.4} ref={:.4} gap={:+.4}\n\n",
3122+ total_corr_o,
3123+ total_corr_r,
3124+ total_corr_r - total_corr_o
3125+ ));
30613126
30623127 // Per-second summary table
30633128 out_str.push_str("# sec\tcorr_ours\tcorr_ref\tgap\tavg_trim\tdual_n\tint_typ\tavg_B_ours\tavg_B_ref\ttf_chng_n\ttrans_n\n");
@@ -3067,19 +3132,35 @@ fn reelm64_persecond_diag() {
30673132 let sec_diags = &diags[f0..f1.min(diags.len())];
30683133 let avg_trim: f64 = if !sec_diags.is_empty() {
30693134 sec_diags.iter().map(|d| d.alloc_trim as f64).sum::<f64>() / sec_diags.len() as f64
3070- } else { -1.0 };
3135+ } else {
3136+ -1.0
3137+ };
30713138 let dual_n = sec_diags.iter().filter(|d| d.dual_stereo).count();
30723139 let int_typ = if !sec_diags.is_empty() {
30733140 sec_diags.iter().map(|d| d.intensity).max().unwrap_or(0)
3074- } else { 0 };
3141+ } else {
3142+ 0
3143+ };
30753144 let avg_b_o: f64 = if !sec_diags.is_empty() {
3076- sec_diags.iter().map(|d| d.nb_compressed as f64).sum::<f64>() / sec_diags.len() as f64
3077- } else { 0.0 };
3145+ sec_diags
3146+ .iter()
3147+ .map(|d| d.nb_compressed as f64)
3148+ .sum::<f64>()
3149+ / sec_diags.len() as f64
3150+ } else {
3151+ 0.0
3152+ };
30783153 let ref_f0 = f0.min(ref_payload.len());
30793154 let ref_f1 = f1.min(ref_payload.len());
30803155 let avg_b_r: f64 = if ref_f1 > ref_f0 {
3081- ref_payload[ref_f0..ref_f1].iter().map(|&b| b as f64).sum::<f64>() / (ref_f1 - ref_f0) as f64
3082- } else { 0.0 };
3156+ ref_payload[ref_f0..ref_f1]
3157+ .iter()
3158+ .map(|&b| b as f64)
3159+ .sum::<f64>()
3160+ / (ref_f1 - ref_f0) as f64
3161+ } else {
3162+ 0.0
3163+ };
30833164 // tf_changed: count bands where tf_res != 0 (we don't have tf_res in diag,
30843165 // but is_transient tells us if short blocks were used)
30853166 let trans_n = sec_diags.iter().filter(|d| d.is_transient).count();
@@ -3103,10 +3184,23 @@ fn reelm64_persecond_diag() {
31033184 let f5: Vec<String> = (0..5).map(|i| format!("{}", d.fine_quant[i])).collect();
31043185 out_str.push_str(&format!(
31053186 "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
3106- fi, fi * 20, d.nb_compressed, b_ref,
3107- d.is_transient as u8, d.short_blocks, d.intra as u8, d.silence as u8,
3108- d.lm, d.start, d.coded_bands, d.intensity, d.dual_stereo as u8,
3109- d.alloc_trim, d.vbr_reservoir, p5.join(","), f5.join(",")
3187+ fi,
3188+ fi * 20,
3189+ d.nb_compressed,
3190+ b_ref,
3191+ d.is_transient as u8,
3192+ d.short_blocks,
3193+ d.intra as u8,
3194+ d.silence as u8,
3195+ d.lm,
3196+ d.start,
3197+ d.coded_bands,
3198+ d.intensity,
3199+ d.dual_stereo as u8,
3200+ d.alloc_trim,
3201+ d.vbr_reservoir,
3202+ p5.join(","),
3203+ f5.join(",")
31103204 ));
31113205 }
31123206 out_str.push('\n');
@@ -3116,30 +3210,50 @@ fn reelm64_persecond_diag() {
31163210 out_str.push_str("# --- global stats ---\n");
31173211 let trim_hist: Vec<(i32, usize)> = {
31183212 let mut h = std::collections::HashMap::new();
3119- for d in &diags { *h.entry(d.alloc_trim).or_insert(0) += 1; }
3213+ for d in &diags {
3214+ *h.entry(d.alloc_trim).or_insert(0) += 1;
3215+ }
31203216 let mut v: Vec<_> = h.into_iter().collect();
31213217 v.sort();
31223218 v
31233219 };
31243220 out_str.push_str(&format!("# alloc_trim histogram: {:?}\n", trim_hist));
31253221 let dual_count = diags.iter().filter(|d| d.dual_stereo).count();
3126- out_str.push_str(&format!("# dual_stereo frames: {}/{}\n", dual_count, diags.len()));
3222+ out_str.push_str(&format!(
3223+ "# dual_stereo frames: {}/{}\n",
3224+ dual_count,
3225+ diags.len()
3226+ ));
31273227 let trans_count = diags.iter().filter(|d| d.is_transient).count();
3128- out_str.push_str(&format!("# transient frames: {}/{}\n", trans_count, diags.len()));
3228+ out_str.push_str(&format!(
3229+ "# transient frames: {}/{}\n",
3230+ trans_count,
3231+ diags.len()
3232+ ));
31293233 let intensity_hist: Vec<(usize, usize)> = {
31303234 let mut h = std::collections::HashMap::new();
3131- for d in &diags { *h.entry(d.intensity).or_insert(0) += 1; }
3235+ for d in &diags {
3236+ *h.entry(d.intensity).or_insert(0) += 1;
3237+ }
31323238 let mut v: Vec<_> = h.into_iter().collect();
31333239 v.sort();
31343240 v
31353241 };
31363242 out_str.push_str(&format!("# intensity histogram: {:?}\n", intensity_hist));
3137- let avg_b_ours: f64 = diags.iter().map(|d| d.nb_compressed as f64).sum::<f64>() / diags.len() as f64;
3138- let avg_b_ref: f64 = ref_payload.iter().map(|&b| b as f64).sum::<f64>() / ref_payload.len() as f64;
3139- out_str.push_str(&format!("# avg bytes/frame: ours={:.1} ref={:.1}\n", avg_b_ours, avg_b_ref));
3243+ let avg_b_ours: f64 =
3244+ diags.iter().map(|d| d.nb_compressed as f64).sum::<f64>() / diags.len() as f64;
3245+ let avg_b_ref: f64 =
3246+ ref_payload.iter().map(|&b| b as f64).sum::<f64>() / ref_payload.len() as f64;
3247+ out_str.push_str(&format!(
3248+ "# avg bytes/frame: ours={:.1} ref={:.1}\n",
3249+ avg_b_ours, avg_b_ref
3250+ ));
31403251 let ours_kbps = ours_bytes.iter().map(|&b| b as f64).sum::<f64>() * 8.0 / seconds / 1000.0;
31413252 let ref_kbps = ref_payload.iter().map(|&b| b as f64).sum::<f64>() * 8.0 / seconds / 1000.0;
3142- out_str.push_str(&format!("# realised kbps: ours={:.1} ref={:.1}\n", ours_kbps, ref_kbps));
3253+ out_str.push_str(&format!(
3254+ "# realised kbps: ours={:.1} ref={:.1}\n",
3255+ ours_kbps, ref_kbps
3256+ ));
31433257
31443258 let out_path = lanes_dir.join("opus-64-r1.seconds.txt");
31453259 fs::write(&out_path, out_str).unwrap();
@@ -3160,7 +3274,10 @@ fn encoder_library_gate_vs_libopus() {
31603274 ("reell", "~/Music/reell.mp4"),
31613275 ("reelm", "~/Music/reelm.wav"),
31623276 ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
3163- ("hein", "~/Downloads/reelm.mp3"),
3277+ (
3278+ "hein",
3279+ "~/Downloads/reelm.mp3",
3280+ ),
31643281 ];
31653282 let only: Vec<String> = std::env::var("SWEEP_ONLY")
31663283 .unwrap_or_default()
@@ -3198,7 +3315,9 @@ fn encoder_library_gate_vs_libopus() {
31983315 for &kbps in &[64u32, 96u32] {
31993316 // Reference: ffmpeg libopus, VBR on, realised rate from file size.
32003317 ffmpeg_encode_libopus(src, kbps, &scratch, SECS);
3201- let ref_bytes = fs::metadata(&scratch).map(|m| m.len() as usize).unwrap_or(0);
3318+ let ref_bytes = fs::metadata(&scratch)
3319+ .map(|m| m.len() as usize)
3320+ .unwrap_or(0);
32023321 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
32033322 let (ref_dec, ref_ch) = decode_ogg(&scratch);
32043323 assert_eq!(ref_ch, CHANNELS, "{tag}@{kbps}: ref not stereo");
@@ -3206,8 +3325,7 @@ fn encoder_library_gate_vs_libopus() {
32063325
32073326 // Ours: ec-opus encoder at the reference's realised rate, decoded
32083327 // by our own decoder; payload bytes give the realised rate.
3209- let mut enc =
3210- Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder");
3328+ let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder");
32113329 enc.set_bitrate((ref_kbps * 1000.0).round() as u32);
32123330 enc.set_vbr_constrained(true);
32133331 let (ours_dec, ours_bytes) = roundtrip_own(&mut enc, &source_pcm, CHANNELS, FRAME);
@@ -3233,7 +3351,11 @@ fn encoder_library_gate_vs_libopus() {
32333351 let q_ref = opus_compare(&s_i, &r_i, CHANNELS);
32343352 let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS);
32353353 let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS);
3236- let err_ratio = if err_ref > 0.0 { err_ours / err_ref } else { f64::INFINITY };
3354+ let err_ratio = if err_ref > 0.0 {
3355+ err_ours / err_ref
3356+ } else {
3357+ f64::INFINITY
3358+ };
32373359
32383360 let corr_ours = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS);
32393361 let corr_ref = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS);
@@ -3271,8 +3393,10 @@ fn encoder_library_gate_vs_libopus() {
32713393 let mut table = String::new();
32723394 table.push_str("# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1)\n");
32733395 table.push_str("# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo\n");
3274- table.push_str("# source\tkbps\tours_kbps\tref_kbps\trate%\tcorr_ours\tcorr_ref\tgap\t\
3275- Q_ours\tQ_ref\terr_ratio\tminsec_ours\tminsec_ref\tdrop_ours\tdrop_ref\n");
3396+ table.push_str(
3397+ "# source\tkbps\tours_kbps\tref_kbps\trate%\tcorr_ours\tcorr_ref\tgap\t\
3398+ Q_ours\tQ_ref\terr_ratio\tminsec_ours\tminsec_ref\tdrop_ours\tdrop_ref\n",
3399+ );
32763400 for r in &rows {
32773401 table.push_str(r);
32783402 table.push('\n');
@@ -3335,8 +3459,18 @@ fn ffmpeg_decode_pcm_mono(path: &Path, secs: f64) -> Vec<f32> {
33353459 .args(["-v", "error", "-i"])
33363460 .arg(path)
33373461 .args([
3338- "-vn", "-t", &format!("{secs}"), "-ac", "1", "-ar", "48000", "-f", "f32le",
3339- "-acodec", "pcm_f32le", "-",
3462+ "-vn",
3463+ "-t",
3464+ &format!("{secs}"),
3465+ "-ac",
3466+ "1",
3467+ "-ar",
3468+ "48000",
3469+ "-f",
3470+ "f32le",
3471+ "-acodec",
3472+ "pcm_f32le",
3473+ "-",
33403474 ])
33413475 .output()
33423476 .expect("ffmpeg runs");
@@ -3359,8 +3493,21 @@ fn ffmpeg_encode_libopus_mono_voip(src: &Path, kbps: u32, out: &Path, secs: f64)
33593493 .args(["-y", "-v", "error", "-i"])
33603494 .arg(src)
33613495 .args([
3362- "-vn", "-t", &format!("{secs}"), "-ac", "1", "-ar", "48000", "-c:a", "libopus",
3363- "-application", "voip", "-b:a", &format!("{kbps}k"), "-vbr", "on",
3496+ "-vn",
3497+ "-t",
3498+ &format!("{secs}"),
3499+ "-ac",
3500+ "1",
3501+ "-ar",
3502+ "48000",
3503+ "-c:a",
3504+ "libopus",
3505+ "-application",
3506+ "voip",
3507+ "-b:a",
3508+ &format!("{kbps}k"),
3509+ "-vbr",
3510+ "on",
33643511 ])
33653512 .arg(out)
33663513 .output()
@@ -3475,7 +3622,9 @@ fn silk_library_gate_vs_libopus() {
34753622
34763623 // Reference: ffmpeg libopus, mono, voip, VBR; realised rate from size.
34773624 ffmpeg_encode_libopus_mono_voip(&src, kbps, &ref_ogg, SECS);
3478- let ref_bytes = fs::metadata(&ref_ogg).map(|m| m.len() as usize).unwrap_or(0);
3625+ let ref_bytes = fs::metadata(&ref_ogg)
3626+ .map(|m| m.len() as usize)
3627+ .unwrap_or(0);
34793628 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
34803629 // SYMMETRY: ref decoded through ffmpeg libopus (the reference decoder),
34813630 // NOT our own decoder — so both sides cross the same decoder. (r1 used
@@ -3526,17 +3675,24 @@ fn silk_library_gate_vs_libopus() {
35263675 pre_skip,
35273676 );
35283677 let ours_dec = ffmpeg_decode(&ours_ogg, CHANNELS).expect("ffmpeg libopus decode of ours");
3529- let ours_trim: Vec<f32> = ours_dec.into_iter().take(source_frames * CHANNELS).collect();
3678+ let ours_trim: Vec<f32> = ours_dec
3679+ .into_iter()
3680+ .take(source_frames * CHANNELS)
3681+ .collect();
35303682 let (lag_ours, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
35313683
35323684 // Own-decoder aligned (extra column: decoder drift visibility).
3533- let ours_own_trim: Vec<f32> =
3534- ours_own_dec.into_iter().take(source_frames * CHANNELS).collect();
3685+ let ours_own_trim: Vec<f32> = ours_own_dec
3686+ .into_iter()
3687+ .take(source_frames * CHANNELS)
3688+ .collect();
35353689 let (_, ours_own_aligned) = align_to_source(&source_pcm, &ours_own_trim, CHANNELS, MAX_LAG);
35363690
35373691 // LAG GATE: a lag at the scan bound is an invalid measurement, not a result.
35383692 if (lag_ours as i64).abs() >= MAX_LAG as i64 {
3539- lag_violations.push(format!("{tag}: ours lag {lag_ours} hit scan bound {MAX_LAG}"));
3693+ lag_violations.push(format!(
3694+ "{tag}: ours lag {lag_ours} hit scan bound {MAX_LAG}"
3695+ ));
35403696 }
35413697 if (lag_ref as i64).abs() >= MAX_LAG as i64 {
35423698 lag_violations.push(format!("{tag}: ref lag {lag_ref} hit scan bound {MAX_LAG}"));
@@ -3555,7 +3711,11 @@ fn silk_library_gate_vs_libopus() {
35553711 let q_ref = opus_compare(&s_i, &r_i, CHANNELS);
35563712 let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS);
35573713 let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS);
3558- let err_ratio = if err_ref > 0.0 { err_ours / err_ref } else { f64::INFINITY };
3714+ let err_ratio = if err_ref > 0.0 {
3715+ err_ours / err_ref
3716+ } else {
3717+ f64::INFINITY
3718+ };
35593719
35603720 // Primary corr: band-limited reference. Secondary: full-band source.
35613721 let corr_ours_bl = corr_interleaved(&ref_source, &ours_aligned, CHANNELS);
@@ -3672,7 +3832,9 @@ fn silk_silkq_persecond_diag() {
36723832
36733833 // Reference: ffmpeg libopus mono voip VBR at 12k; realised rate from size.
36743834 ffmpeg_encode_libopus_mono_voip(&src, KBPS, &ref_ogg, SECS);
3675- let ref_bytes = fs::metadata(&ref_ogg).map(|m| m.len() as usize).unwrap_or(0);
3835+ let ref_bytes = fs::metadata(&ref_ogg)
3836+ .map(|m| m.len() as usize)
3837+ .unwrap_or(0);
36763838 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
36773839 let ref_dec = ffmpeg_decode(&ref_ogg, CHANNELS).expect("ffmpeg libopus decode of ref");
36783840 let ref_trim: Vec<f32> = ref_dec.into_iter().take(source_frames * CHANNELS).collect();
@@ -3711,11 +3873,16 @@ fn silk_silkq_persecond_diag() {
37113873 let len = enc.encode_float(block, FRAME, &mut out).expect("encode");
37123874 let d = enc.last_silk_diag().cloned();
37133875 ours_bytes.push(len);
3714- if let Some(d) = d { diags.push(d); }
3876+ if let Some(d) = d {
3877+ diags.push(d);
3878+ }
37153879 let n = dec.decode_float(&out[..len], &mut buf).expect("decode");
37163880 ours_dec.extend_from_slice(&buf[..n * CHANNELS]);
37173881 }
3718- let ours_trim: Vec<f32> = ours_dec.into_iter().take(source_frames * CHANNELS).collect();
3882+ let ours_trim: Vec<f32> = ours_dec
3883+ .into_iter()
3884+ .take(source_frames * CHANNELS)
3885+ .collect();
37193886 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
37203887
37213888 // Per-second correlation ours vs ref against the full-band source (matches
@@ -3736,11 +3903,23 @@ fn silk_silkq_persecond_diag() {
37363903 let s = source_pcm[start + i] as f64;
37373904 let o = ours_aligned[start + i] as f64;
37383905 let r = ref_aligned[start + i] as f64;
3739- sxy_o += s * o; sxx_o += s * s; syy_o += o * o;
3740- sxy_r += s * r; sxx_r += s * s; syy_r += r * r;
3906+ sxy_o += s * o;
3907+ sxx_o += s * s;
3908+ syy_o += o * o;
3909+ sxy_r += s * r;
3910+ sxx_r += s * s;
3911+ syy_r += r * r;
37413912 }
3742- let co = if sxx_o > 0.0 && syy_o > 0.0 { sxy_o / (sxx_o * syy_o).sqrt() } else { 0.0 };
3743- let cr = if sxx_r > 0.0 && syy_r > 0.0 { sxy_r / (sxx_r * syy_r).sqrt() } else { 0.0 };
3913+ let co = if sxx_o > 0.0 && syy_o > 0.0 {
3914+ sxy_o / (sxx_o * syy_o).sqrt()
3915+ } else {
3916+ 0.0
3917+ };
3918+ let cr = if sxx_r > 0.0 && syy_r > 0.0 {
3919+ sxy_r / (sxx_r * syy_r).sqrt()
3920+ } else {
3921+ 0.0
3922+ };
37443923 sec_rows.push((sec_idx, co, cr, cr - co));
37453924 start += sec_samples;
37463925 sec_idx += 1;
@@ -3752,13 +3931,20 @@ fn silk_silkq_persecond_diag() {
37523931 let mut out_str = String::new();
37533932 out_str.push_str("# reelm@12k SILK per-second diagnostic (r1)\n");
37543933 out_str.push_str("# mono, 120s cap, 20ms frames, VBR constrained, 48kHz, Application::Voip\n");
3755- out_str.push_str(&format!("# total frames: ours={} ref={}\n", diags.len(), ref_payload.len()));
3934+ out_str.push_str(&format!(
3935+ "# total frames: ours={} ref={}\n",
3936+ diags.len(),
3937+ ref_payload.len()
3938+ ));
37563939 let avg_o: f64 = sec_rows.iter().map(|r| r.1).sum::<f64>() / sec_rows.len().max(1) as f64;
37573940 let avg_r: f64 = sec_rows.iter().map(|r| r.2).sum::<f64>() / sec_rows.len().max(1) as f64;
37583941 let gap_avg = avg_r - avg_o;
37593942 out_str.push_str(&format!(
37603943 "# avg corr: ours={:.4} ref={:.4} gap={:+.4} ref_kbps={:.1} ours_kbps={:.1}\n\n",
3761- avg_o, avg_r, gap_avg, ref_kbps,
3944+ avg_o,
3945+ avg_r,
3946+ gap_avg,
3947+ ref_kbps,
37623948 ours_bytes.iter().map(|&b| b as f64).sum::<f64>() * 8.0 / seconds / 1000.0
37633949 ));
37643950
@@ -3770,27 +3956,45 @@ fn silk_silkq_persecond_diag() {
37703956 let sd = &diags[f0..f1.min(diags.len())];
37713957 let gain_mean: f64 = if !sd.is_empty() {
37723958 sd.iter().map(|d| d.gain_idx[0] as f64).sum::<f64>() / sd.len() as f64
3773- } else { -1.0 };
3959+ } else {
3960+ -1.0
3961+ };
37743962 let voiced_n = sd.iter().filter(|d| d.voiced).count();
37753963 let nlsf_int = if !sd.is_empty() {
37763964 sd.iter().map(|d| d.nlsf_interp).max().unwrap_or(0)
3777- } else { 0 };
3965+ } else {
3966+ 0
3967+ };
37783968 let avg_b_o: f64 = if !sd.is_empty() {
37793969 sd.iter().map(|d| d.bytes as f64).sum::<f64>() / sd.len() as f64
3780- } else { 0.0 };
3970+ } else {
3971+ 0.0
3972+ };
37813973 let ref_f0 = f0.min(ref_payload.len());
37823974 let ref_f1 = f1.min(ref_payload.len());
37833975 let avg_b_r: f64 = if ref_f1 > ref_f0 {
3784- ref_payload[ref_f0..ref_f1].iter().map(|&b| b as f64).sum::<f64>()
3976+ ref_payload[ref_f0..ref_f1]
3977+ .iter()
3978+ .map(|&b| b as f64)
3979+ .sum::<f64>()
37853980 / (ref_f1 - ref_f0) as f64
3786- } else { 0.0 };
3981+ } else {
3982+ 0.0
3983+ };
37873984 let ltp_mean: f64 = if !sd.is_empty() {
37883985 sd.iter().map(|d| d.ltp_gain as f64).sum::<f64>() / sd.len() as f64
3789- } else { 0.0 };
3986+ } else {
3987+ 0.0
3988+ };
37903989 let pitch_mean: f64 = if !sd.is_empty() {
3791- sd.iter().filter(|d| d.voiced).map(|d| d.pitch_l[0] as f64).sum::<f64>()
3990+ sd.iter()
3991+ .filter(|d| d.voiced)
3992+ .map(|d| d.pitch_l[0] as f64)
3993+ .sum::<f64>()
37923994 / sd.iter().filter(|d| d.voiced).count().max(1) as f64
3793- } else { 0.0 };
3995+ } else {
3996+ 0.0
3997+ };
37943998 out_str.push_str(&format!(
37953999 "{}\t{:.4}\t{:.4}\t{:+.4}\t{:.1}\t{}\t{}\t{:.1}\t{:.1}\t{:.3}\t{:.1}\n",
37964000 s, co, cr, g, gain_mean, voiced_n, nlsf_int, avg_b_o, avg_b_r, ltp_mean, pitch_mean
@@ -3809,9 +4013,18 @@ fn silk_silkq_persecond_diag() {
38094013 let b_ref = ref_payload.get(fi).copied().unwrap_or(0);
38104014 out_str.push_str(&format!(
38114015 "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{:.3}\t{}\n",
3812- fi, fi * 20, d.bytes, b_ref,
3813- d.voiced as u8, d.signal_type, d.gain_idx[0], d.lag_index,
3814- d.pitch_l[0], d.nlsf_interp, d.ltp_gain, d.nb_subfr
4016+ fi,
4017+ fi * 20,
4018+ d.bytes,
4019+ b_ref,
4020+ d.voiced as u8,
4021+ d.signal_type,
4022+ d.gain_idx[0],
4023+ d.lag_index,
4024+ d.pitch_l[0],
4025+ d.nlsf_interp,
4026+ d.ltp_gain,
4027+ d.nb_subfr
38154028 ));
38164029 }
38174030 out_str.push('\n');
@@ -3820,10 +4033,16 @@ fn silk_silkq_persecond_diag() {
38204033 // Global stats.
38214034 out_str.push_str("# --- global stats ---\n");
38224035 let voiced_count = diags.iter().filter(|d| d.voiced).count();
3823- out_str.push_str(&format!("# voiced frames: {}/{}\n", voiced_count, diags.len()));
4036+ out_str.push_str(&format!(
4037+ "# voiced frames: {}/{}\n",
4038+ voiced_count,
4039+ diags.len()
4040+ ));
38244041 let gain_hist: Vec<(i8, usize)> = {
38254042 let mut h = std::collections::HashMap::new();
3826- for d in &diags { *h.entry(d.gain_idx[0]).or_insert(0) += 1; }
4043+ for d in &diags {
4044+ *h.entry(d.gain_idx[0]).or_insert(0) += 1;
4045+ }
38274046 let mut v: Vec<_> = h.into_iter().collect();
38284047 v.sort();
38294048 v
@@ -3831,16 +4050,24 @@ fn silk_silkq_persecond_diag() {
38314050 out_str.push_str(&format!("# gain_idx[0] histogram: {:?}\n", gain_hist));
38324051 let nlsf_hist: Vec<(i32, usize)> = {
38334052 let mut h = std::collections::HashMap::new();
3834- for d in &diags { *h.entry(d.nlsf_interp).or_insert(0) += 1; }
4053+ for d in &diags {
4054+ *h.entry(d.nlsf_interp).or_insert(0) += 1;
4055+ }
38354056 let mut v: Vec<_> = h.into_iter().collect();
38364057 v.sort();
38374058 v
38384059 };
38394060 out_str.push_str(&format!("# nlsf_interp histogram: {:?}\n", nlsf_hist));
3840- let avg_b_ours: f64 = diags.iter().map(|d| d.bytes as f64).sum::<f64>() / diags.len().max(1) as f64;
3841- let avg_b_ref: f64 = ref_payload.iter().map(|&b| b as f64).sum::<f64>() / ref_payload.len().max(1) as f64;
3842- out_str.push_str(&format!("# avg bytes/frame: ours={:.1} ref={:.1}\n", avg_b_ours, avg_b_ref));
3843- let ltp_mean_all: f64 = diags.iter().map(|d| d.ltp_gain as f64).sum::<f64>() / diags.len().max(1) as f64;
4061+ let avg_b_ours: f64 =
4062+ diags.iter().map(|d| d.bytes as f64).sum::<f64>() / diags.len().max(1) as f64;
4063+ let avg_b_ref: f64 =
4064+ ref_payload.iter().map(|&b| b as f64).sum::<f64>() / ref_payload.len().max(1) as f64;
4065+ out_str.push_str(&format!(
4066+ "# avg bytes/frame: ours={:.1} ref={:.1}\n",
4067+ avg_b_ours, avg_b_ref
4068+ ));
4069+ let ltp_mean_all: f64 =
4070+ diags.iter().map(|d| d.ltp_gain as f64).sum::<f64>() / diags.len().max(1) as f64;
38444071 out_str.push_str(&format!("# mean ltp_gain: {:.4}\n", ltp_mean_all));
38454072
38464073 let out_path = lanes_dir.join("opus-silkq-r1.seconds.txt");
@@ -3902,25 +4129,37 @@ fn silk_silkq_oracle() {
39024129 ours_packets.push(out[..len].to_vec());
39034130 }
39044131
3905-
39064132 let ours_ix = collect_indices(&ours_packets);
39074133 let ref_ix = collect_indices(&ref_packets);
39084134
3909- eprintln!("ours frames: {} ref frames: {}", ours_ix.len(), ref_ix.len());
4135+ eprintln!(
4136+ "ours frames: {} ref frames: {}",
4137+ ours_ix.len(),
4138+ ref_ix.len()
4139+ );
39104140
39114141 // Print side-by-side for target seconds (50 frames/sec at 20ms).
39124142 let frames_per_sec = 50usize;
39134143 let mut out_str = String::new();
39144144 out_str.push_str("# reelm@12k SILK oracle: ours vs ffmpeg-libopus indices (r1)\n");
39154145 out_str.push_str("# mono, 120s, 20ms frames, VBR constrained, 48kHz, Application::Voip\n");
3916- out_str.push_str(&format!("# ours_frames={} ref_frames={}\n", ours_ix.len(), ref_ix.len()));
4146+ out_str.push_str(&format!(
4147+ "# ours_frames={} ref_frames={}\n",
4148+ ours_ix.len(),
4149+ ref_ix.len()
4150+ ));
39174151 out_str.push_str("# sig: 0=unvoiced 2=voiced | per: LTP codebook | nlsf_i: 4=nointerp\n");
39184152 out_str.push_str("# gains/ltp are 4 subframe indices; lag/contour only for voiced\n\n");
39194153
39204154 for &sec in TARGET_SECS {
39214155 let start = sec * frames_per_sec;
39224156 let end = start + frames_per_sec;
3923- out_str.push_str(&format!("=== second {} (frames {}–{}) ===\n", sec, start, end - 1));
4157+ out_str.push_str(&format!(
4158+ "=== second {} (frames {}–{}) ===\n",
4159+ sec,
4160+ start,
4161+ end - 1
4162+ ));
39244163 out_str.push_str("frame side sig qoff gains[4] nlsf_i lag cont per ltp[4] ltpscl seed bytes\n");
39254164 for f in start..end {
39264165 let ours = ours_ix.get(f);
@@ -3948,7 +4187,10 @@ fn silk_silkq_oracle() {
39484187 "-".to_string()
39494188 };
39504189 let ltp_str = if voiced {
3951- format!("[{},{},{},{}]", ix.ltp_index[0], ix.ltp_index[1], ix.ltp_index[2], ix.ltp_index[3])
4190+ format!(
4191+ "[{},{},{},{}]",
4192+ ix.ltp_index[0], ix.ltp_index[1], ix.ltp_index[2], ix.ltp_index[3]
4193+ )
39524194 } else {
39534195 "[-,-,-,-]".to_string()
39544196 };
@@ -3990,14 +4232,26 @@ fn silk_silkq_oracle() {
39904232 for i in 0..n {
39914233 let (o, ob) = &ours_ix[i];
39924234 let (r, rb) = &ref_ix[i];
3993- if o.signal_type != r.signal_type { sig_mismatch += 1; }
3994- if o.quant_offset_type != r.quant_offset_type { qoff_mismatch += 1; }
3995- for k in 0..4 { gain_diff_sum += (o.gains[k] as i64 - r.gains[k] as i64).abs(); }
3996- if o.nlsf_interp_coef_q2 != r.nlsf_interp_coef_q2 { nlsf_interp_diff += 1; }
4235+ if o.signal_type != r.signal_type {
4236+ sig_mismatch += 1;
4237+ }
4238+ if o.quant_offset_type != r.quant_offset_type {
4239+ qoff_mismatch += 1;
4240+ }
4241+ for k in 0..4 {
4242+ gain_diff_sum += (o.gains[k] as i64 - r.gains[k] as i64).abs();
4243+ }
4244+ if o.nlsf_interp_coef_q2 != r.nlsf_interp_coef_q2 {
4245+ nlsf_interp_diff += 1;
4246+ }
39974247 if o.signal_type == 2 && r.signal_type == 2 {
39984248 voiced_both += 1;
3999- if o.per_index != r.per_index { ltp_per_mismatch += 1; }
4000- for k in 0..4 { ltp_idx_diff_sum += (o.ltp_index[k] as i64 - r.ltp_index[k] as i64).abs(); }
4249+ if o.per_index != r.per_index {
4250+ ltp_per_mismatch += 1;
4251+ }
4252+ for k in 0..4 {
4253+ ltp_idx_diff_sum += (o.ltp_index[k] as i64 - r.ltp_index[k] as i64).abs();
4254+ }
40014255 lag_diff_sum += (o.lag_index as i64 - r.lag_index as i64).abs();
40024256 }
40034257 bytes_ours += *ob as u64;
@@ -4005,15 +4259,45 @@ fn silk_silkq_oracle() {
40054259 }
40064260 out_str.push_str("=== divergence summary (all frames) ===\n");
40074261 out_str.push_str(&format!("frames compared: {}\n", n));
4008- out_str.push_str(&format!("signal_type mismatch: {} ({:.1}%)\n", sig_mismatch, 100.0 * sig_mismatch as f64 / n as f64));
4009- out_str.push_str(&format!("quant_offset mismatch: {} ({:.1}%)\n", qoff_mismatch, 100.0 * qoff_mismatch as f64 / n as f64));
4010- out_str.push_str(&format!("avg |gain diff| per subframe: {:.2}\n", gain_diff_sum as f64 / (n as f64 * 4.0)));
4011- out_str.push_str(&format!("nlsf_interp mismatch: {} ({:.1}%)\n", nlsf_interp_diff, 100.0 * nlsf_interp_diff as f64 / n as f64));
4262+ out_str.push_str(&format!(
4263+ "signal_type mismatch: {} ({:.1}%)\n",
4264+ sig_mismatch,
4265+ 100.0 * sig_mismatch as f64 / n as f64
4266+ ));
4267+ out_str.push_str(&format!(
4268+ "quant_offset mismatch: {} ({:.1}%)\n",
4269+ qoff_mismatch,
4270+ 100.0 * qoff_mismatch as f64 / n as f64
4271+ ));
4272+ out_str.push_str(&format!(
4273+ "avg |gain diff| per subframe: {:.2}\n",
4274+ gain_diff_sum as f64 / (n as f64 * 4.0)
4275+ ));
4276+ out_str.push_str(&format!(
4277+ "nlsf_interp mismatch: {} ({:.1}%)\n",
4278+ nlsf_interp_diff,
4279+ 100.0 * nlsf_interp_diff as f64 / n as f64
4280+ ));
40124281 out_str.push_str(&format!("voiced_both: {}\n", voiced_both));
4013- out_str.push_str(&format!(" LTP per_index mismatch: {} ({:.1}%)\n", ltp_per_mismatch, 100.0 * ltp_per_mismatch as f64 / voiced_both.max(1) as f64));
4014- out_str.push_str(&format!(" avg |ltp_index diff| per subframe: {:.2}\n", ltp_idx_diff_sum as f64 / (voiced_both.max(1) as f64 * 4.0)));
4015- out_str.push_str(&format!(" avg |lag diff|: {:.2}\n", lag_diff_sum as f64 / voiced_both.max(1) as f64));
4016- out_str.push_str(&format!("total bytes: ours={} ref={} ratio={:.3}\n", bytes_ours, bytes_ref, bytes_ours as f64 / bytes_ref.max(1) as f64));
4282+ out_str.push_str(&format!(
4283+ " LTP per_index mismatch: {} ({:.1}%)\n",
4284+ ltp_per_mismatch,
4285+ 100.0 * ltp_per_mismatch as f64 / voiced_both.max(1) as f64
4286+ ));
4287+ out_str.push_str(&format!(
4288+ " avg |ltp_index diff| per subframe: {:.2}\n",
4289+ ltp_idx_diff_sum as f64 / (voiced_both.max(1) as f64 * 4.0)
4290+ ));
4291+ out_str.push_str(&format!(
4292+ " avg |lag diff|: {:.2}\n",
4293+ lag_diff_sum as f64 / voiced_both.max(1) as f64
4294+ ));
4295+ out_str.push_str(&format!(
4296+ "total bytes: ours={} ref={} ratio={:.3}\n",
4297+ bytes_ours,
4298+ bytes_ref,
4299+ bytes_ours as f64 / bytes_ref.max(1) as f64
4300+ ));
40174301
40184302 let out_path = lanes_dir.join("opus-silkq-r1.oracle.txt");
40194303 fs::write(&out_path, &out_str).unwrap();
@@ -4059,14 +4343,7 @@ fn collect_indices(packets: &[Vec<u8>]) -> Vec<(ec_opus::SilkDecIndices, usize)>
40594343 continue;
40604344 }
40614345 let mut dec = ec_opus::RangeDecoder::new(frame_data);
4062- let _ = silk.decode(
4063- &mut dec,
4064- &mut silk_pcm,
4065- payload_ms,
4066- internal_rate,
4067- 1,
4068- first,
4069- );
4346+ let _ = silk.decode(&mut dec, &mut silk_pcm, payload_ms, internal_rate, 1, first);
40704347 let ix = silk.last_indices();
40714348 let bytes = frame_data.len();
40724349 results.push((ix, bytes));
@@ -4110,7 +4387,9 @@ fn silk_spectral_divergence_12k() {
41104387
41114388 // Reference: ffmpeg libopus mono voip at 12k, decoded by ffmpeg libopus.
41124389 ffmpeg_encode_libopus_mono_voip(&src, KBPS, &ref_ogg, SECS);
4113- let ref_bytes = fs::metadata(&ref_ogg).map(|m| m.len() as usize).unwrap_or(0);
4390+ let ref_bytes = fs::metadata(&ref_ogg)
4391+ .map(|m| m.len() as usize)
4392+ .unwrap_or(0);
41144393 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
41154394 let ref_dec = ffmpeg_decode(&ref_ogg, CHANNELS).expect("ffmpeg libopus decode of ref");
41164395 let ref_trim: Vec<f32> = ref_dec.into_iter().take(source_frames * CHANNELS).collect();
@@ -4156,7 +4435,10 @@ fn silk_spectral_divergence_12k() {
41564435 let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0;
41574436 let ours_dec = ffmpeg_decode(&ours_ogg, CHANNELS).expect("ffmpeg libopus decode of ours");
41584437 let _ = fs::remove_file(&ours_ogg);
4159- let ours_trim: Vec<f32> = ours_dec.into_iter().take(source_frames * CHANNELS).collect();
4438+ let ours_trim: Vec<f32> = ours_dec
4439+ .into_iter()
4440+ .take(source_frames * CHANNELS)
4441+ .collect();
41604442 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
41614443
41624444 // opus_compare totals, per-band eb², per-frame ef² — both vs the source.
@@ -4178,9 +4460,27 @@ fn silk_spectral_divergence_12k() {
41784460 let mut bands_o = Vec::new();
41794461 let mut bands_r = Vec::new();
41804462 let mut scratch_ps = Vec::new();
4181- band_energy(&as_f64(&s_i), CHANNELS, nframes, &mut Some(&mut bands_s), &mut scratch_ps);
4182- band_energy(&as_f64(&o_i), CHANNELS, nframes, &mut Some(&mut bands_o), &mut scratch_ps);
4183- band_energy(&as_f64(&r_i), CHANNELS, nframes, &mut Some(&mut bands_r), &mut scratch_ps);
4463+ band_energy(
4464+ &as_f64(&s_i),
4465+ CHANNELS,
4466+ nframes,
4467+ &mut Some(&mut bands_s),
4468+ &mut scratch_ps,
4469+ );
4470+ band_energy(
4471+ &as_f64(&o_i),
4472+ CHANNELS,
4473+ nframes,
4474+ &mut Some(&mut bands_o),
4475+ &mut scratch_ps,
4476+ );
4477+ band_energy(
4478+ &as_f64(&r_i),
4479+ CHANNELS,
4480+ nframes,
4481+ &mut Some(&mut bands_r),
4482+ &mut scratch_ps,
4483+ );
41844484
41854485 // Oracle indices both sides; FFT frame xi -> 20 ms packet index.
41864486 let ours_ix = collect_indices(&ours_packets);
@@ -4213,7 +4513,11 @@ fn silk_spectral_divergence_12k() {
42134513 }
42144514 dol /= nframes as f64;
42154515 drl /= nframes as f64;
4216- let ratio = if eb2_r[bi] > 0.0 { eb2_o[bi] / eb2_r[bi] } else { f64::INFINITY };
4516+ let ratio = if eb2_r[bi] > 0.0 {
4517+ eb2_o[bi] / eb2_r[bi]
4518+ } else {
4519+ f64::INFINITY
4520+ };
42174521 report.push_str(&format!(
42184522 "{:5} {:5} {:6} {:+.3} {:+.3} {:.3e} {:.3e} {:>7} {:5.1}% {:5.1}%\n",
42194523 bi,
@@ -4318,7 +4622,10 @@ fn silk_spectral_divergence_12k() {
43184622 "# tail: top-1% ({k} frames) carry {:.2}% of ours' Σef2 vs {:.2}% of ref's; \
43194623 50% of ours' err sits in the worst {half_o} frames ({:.2}%) \
43204624 vs ref's worst {half_r} ({:.2}%)\n",
4321- 100.0 * sh1_o, 100.0 * sh1_r, 100.0 * halff_o, 100.0 * halff_r
4625+ 100.0 * sh1_o,
4626+ 100.0 * sh1_r,
4627+ 100.0 * halff_o,
4628+ 100.0 * halff_r
43224629 ));
43234630 // De-tailed: drop each side's worst 50 frames (of 24k FFT frames/pkt-mapped).
43244631 let clip50 = |ef2: &[f64]| -> f64 {
@@ -4351,7 +4658,11 @@ fn silk_spectral_divergence_12k() {
43514658 if i >= pkt_ef2.len() {
43524659 break;
43534660 }
4354- let mean = if pkt_cnt[i] > 0 { pkt_ef2[i] / pkt_cnt[i] as f64 } else { 0.0 };
4661+ let mean = if pkt_cnt[i] > 0 {
4662+ pkt_ef2[i] / pkt_cnt[i] as f64
4663+ } else {
4664+ 0.0
4665+ };
43554666 if ix.gains[0] >= 60 {
43564667 g_hi.0 += mean;
43574668 g_hi.1 += 1;
@@ -4373,12 +4684,28 @@ fn silk_spectral_divergence_12k() {
43734684 >20 bytes: mean ef2 {:.3e}\n",
43744685 g_hi.1,
43754686 g_hi.1 + g_lo.1,
4376- if g_hi.1 > 0 { g_hi.0 / g_hi.1 as f64 } else { f64::NAN },
4377- if g_lo.1 > 0 { g_lo.0 / g_lo.1 as f64 } else { f64::NAN },
4687+ if g_hi.1 > 0 {
4688+ g_hi.0 / g_hi.1 as f64
4689+ } else {
4690+ f64::NAN
4691+ },
4692+ if g_lo.1 > 0 {
4693+ g_lo.0 / g_lo.1 as f64
4694+ } else {
4695+ f64::NAN
4696+ },
43784697 b_lo.1,
43794698 b_lo.1 + b_hi.1,
4380- if b_lo.1 > 0 { b_lo.0 / b_lo.1 as f64 } else { f64::NAN },
4381- if b_hi.1 > 0 { b_hi.0 / b_hi.1 as f64 } else { f64::NAN },
4699+ if b_lo.1 > 0 {
4700+ b_lo.0 / b_lo.1 as f64
4701+ } else {
4702+ f64::NAN
4703+ },
4704+ if b_hi.1 > 0 {
4705+ b_hi.0 / b_hi.1 as f64
4706+ } else {
4707+ f64::NAN
4708+ },
43824709 ));
43834710
43844711 let out_path = lanes_dir.join("opus-silkq-r2.bands.txt");
@@ -4415,7 +4742,10 @@ fn opus_compare_harness() {
44154742 );
44164743 let err = opus_compare_err(&x, &y, channels);
44174744 let q = opus_compare(&x, &y, channels);
4418- println!("HARNESS err={err:.6} Q={q:.4} ch={channels} n={}", x.len() / channels);
4745+ println!(
4746+ "HARNESS err={err:.6} Q={q:.4} ch={channels} n={}",
4747+ x.len() / channels
4748+ );
44194749 }
44204750
44214751 // ---------------------------------------------------------------------------
@@ -4454,10 +4784,12 @@ fn opus_compare_harness_ours() {
44544784 let mut d_i16 = vec![0i16; n * channels];
44554785 for i in 0..n {
44564786 for ch in 0..channels {
4457- s_i16[i * channels + ch] =
4458- (src_f32[i * channels + ch] * 32768.0).round().clamp(-32768.0, 32767.0) as i16;
4459- d_i16[i * channels + ch] =
4460- (aligned[i * channels + ch] * 32768.0).round().clamp(-32768.0, 32767.0) as i16;
4787+ s_i16[i * channels + ch] = (src_f32[i * channels + ch] * 32768.0)
4788+ .round()
4789+ .clamp(-32768.0, 32767.0) as i16;
4790+ d_i16[i * channels + ch] = (aligned[i * channels + ch] * 32768.0)
4791+ .round()
4792+ .clamp(-32768.0, 32767.0) as i16;
44614793 }
44624794 }
44634795 fs::write(&out_src, bytemap(&s_i16)).unwrap();
@@ -4465,9 +4797,7 @@ fn opus_compare_harness_ours() {
44654797 let err = opus_compare_err(&s_i16, &d_i16, channels);
44664798 let q = opus_compare(&s_i16, &d_i16, channels);
44674799 let c = corr_interleaved(&src_f32[..n * channels], &aligned, channels);
4468- println!(
4469- "HARNESS_OURS lag={lag} corr={c:.4} err={err:.6} Q={q:.4} kbps={kbps} n={n}"
4470- );
4800+ println!("HARNESS_OURS lag={lag} corr={c:.4} err={err:.6} Q={q:.4} kbps={kbps} n={n}");
44714801 }
44724802
44734803 fn bytemap(p: &[i16]) -> Vec<u8> {
@@ -4533,7 +4863,8 @@ fn opus_compare_err_pinned_against_c() {
45334863
45344864 // Case 2: mild perturbation (+0.5 dB on L, quiet 1500 Hz partial on L).
45354865 let gain = 10f64.powf(0.5 / 10.0);
4536- let lp: Vec<f64> = t.iter()
4866+ let lp: Vec<f64> = t
4867+ .iter()
45374868 .zip(b0.iter())
45384869 .map(|(&tt, &bv)| bv * gain + 0.02 * (2.0 * std::f64::consts::PI * 1500.0 * tt).sin())
45394870 .collect();
@@ -4575,7 +4906,10 @@ fn spectral_divergence_vs_libopus() {
45754906 const FRAME: usize = 960;
45764907 const CHANNELS: usize = 2;
45774908 const MAX_LAG: usize = 2000;
4578- let kbps_env: u32 = std::env::var("SWEEP_KBPS").ok().and_then(|v| v.parse().ok()).unwrap_or(96);
4909+ let kbps_env: u32 = std::env::var("SWEEP_KBPS")
4910+ .ok()
4911+ .and_then(|v| v.parse().ok())
4912+ .unwrap_or(96);
45794913 #[allow(non_snake_case)]
45804914 let KBPS: u32 = kbps_env;
45814915
@@ -4586,7 +4920,10 @@ fn spectral_divergence_vs_libopus() {
45864920 ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
45874921 ("her", "~/Music/reeli.mp3"),
45884922 ("reelm", "~/Music/reelm.wav"),
4589- ("hein", "~/Downloads/reelm.mp3"),
4923+ (
4924+ "hein",
4925+ "~/Downloads/reelm.mp3",
4926+ ),
45904927 ];
45914928 let only: Vec<String> = std::env::var("SWEEP_ONLY")
45924929 .unwrap_or_else(|_| "reell,dl8a".to_owned())
@@ -4622,13 +4959,15 @@ fn spectral_divergence_vs_libopus() {
46224959
46234960 // Reference: ffmpeg libopus at 96k, VBR, decoded by our decoder.
46244961 ffmpeg_encode_libopus(src, KBPS, &scratch, SECS);
4625- let ref_bytes = fs::metadata(&scratch).map(|m| m.len() as usize).unwrap_or(0);
4962+ let ref_bytes = fs::metadata(&scratch)
4963+ .map(|m| m.len() as usize)
4964+ .unwrap_or(0);
46264965 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
46274966 let ref_pkts: Vec<Vec<u8>> = ogg_packets(&fs::read(&scratch).unwrap())
46284967 .into_iter()
46294968 .skip(2)
46304969 .collect();
4631- let (ref_dec, ref_ch) = decode_ogg(&scratch);
4970+ let (ref_dec, ref_ch) = decode_ogg(&scratch);
46324971 assert_eq!(ref_ch, CHANNELS, "{tag}: ref not stereo");
46334972 let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CHANNELS, MAX_LAG);
46344973
@@ -4641,16 +4980,18 @@ fn spectral_divergence_vs_libopus() {
46414980 let mut dbuf = vec![0.0f32; 5760 * CHANNELS];
46424981 let mut ours_dec = Vec::new();
46434982 let mut first_pkts: Vec<Vec<u8>> = Vec::new();
4644- let mut diags = Vec::new();
4983+ let mut diags = Vec::new();
46454984 let mut ours_bytes = 0usize;
46464985 for block in source_pcm.chunks(FRAME * CHANNELS) {
46474986 let mut padded = block.to_vec();
46484987 padded.resize(FRAME * CHANNELS, 0.0);
4649- let len = enc.encode_float(&padded, FRAME, &mut packet).expect("encode");
4988+ let len = enc
4989+ .encode_float(&padded, FRAME, &mut packet)
4990+ .expect("encode");
46504991 if first_pkts.len() < 10 {
46514992 first_pkts.push(packet[..len].to_vec());
46524993 }
4653- ours_bytes += len;
4994+ ours_bytes += len;
46544995 let n = dec.decode_float(&packet[..len], &mut dbuf).expect("decode");
46554996 ours_dec.extend_from_slice(&dbuf[..n * CHANNELS]);
46564997 diags.push(enc.last_celt_diag().clone());
@@ -4674,7 +5015,10 @@ fn spectral_divergence_vs_libopus() {
46745015 "{tag}@{KBPS}k transient frames: ours {ours_tr}/{} ref {ref_tr}/{ref_n}",
46755016 diags.len()
46765017 );
4677- let ours_trim: Vec<f32> = ours_dec.into_iter().take(source_frames * CHANNELS).collect();
5018+ let ours_trim: Vec<f32> = ours_dec
5019+ .into_iter()
5020+ .take(source_frames * CHANNELS)
5021+ .collect();
46785022 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
46795023 let ours_i16 = to_i16(&ours_aligned);
46805024 let ref_i16 = to_i16(&ref_aligned);
@@ -4700,9 +5044,27 @@ fn spectral_divergence_vs_libopus() {
47005044 let mut bands_o = Vec::new();
47015045 let mut bands_r = Vec::new();
47025046 let mut scratch_ps = Vec::new();
4703- band_energy(&as_f64(&s_i), CHANNELS, nframes, &mut Some(&mut bands_s), &mut scratch_ps);
4704- band_energy(&as_f64(&o_i), CHANNELS, nframes, &mut Some(&mut bands_o), &mut scratch_ps);
4705- band_energy(&as_f64(&r_i), CHANNELS, nframes, &mut Some(&mut bands_r), &mut scratch_ps);
5047+ band_energy(
5048+ &as_f64(&s_i),
5049+ CHANNELS,
5050+ nframes,
5051+ &mut Some(&mut bands_s),
5052+ &mut scratch_ps,
5053+ );
5054+ band_energy(
5055+ &as_f64(&o_i),
5056+ CHANNELS,
5057+ nframes,
5058+ &mut Some(&mut bands_o),
5059+ &mut scratch_ps,
5060+ );
5061+ band_energy(
5062+ &as_f64(&r_i),
5063+ CHANNELS,
5064+ nframes,
5065+ &mut Some(&mut bands_r),
5066+ &mut scratch_ps,
5067+ );
47065068
47075069 report.push_str(&format!(
47085070 "\n# source {tag} @{KBPS}k: ours {ours_kbps:.1} kbps, ref {ref_kbps:.1} kbps; \
@@ -4800,11 +5162,9 @@ fn spectral_divergence_vs_libopus() {
48005162 let dual = fr.iter().filter(|d| d.dual_stereo).count();
48015163 let intra = fr.iter().filter(|d| d.intra).count();
48025164 let cbb_min = fr.iter().map(|d| d.coded_bands).min().unwrap_or(0);
4803- let cbb_mean =
4804- fr.iter().map(|d| d.coded_bands).sum::<usize>() as f64 / dn as f64;
5165+ let cbb_mean = fr.iter().map(|d| d.coded_bands).sum::<usize>() as f64 / dn as f64;
48055166 let int_mean = fr.iter().map(|d| d.intensity).sum::<usize>() as f64 / dn as f64;
4806- let bits =
4807- fr.iter().map(|d| d.nb_compressed).sum::<usize>() as f64 * 8.0 / dn as f64;
5167+ let bits = fr.iter().map(|d| d.nb_compressed).sum::<usize>() as f64 * 8.0 / dn as f64;
48085168 report.push_str(&format!(
48095169 "{}\t{:.3e}\t{}/{}\t{}\t{}\t{}\t{}/{}\t{}/{}\t{:.0}\n",
48105170 s,
@@ -4829,8 +5189,7 @@ fn spectral_divergence_vs_libopus() {
48295189 let dual = diags.iter().filter(|d| d.dual_stereo).count();
48305190 let intra = diags.iter().filter(|d| d.intra).count();
48315191 let cbb_min = diags.iter().map(|d| d.coded_bands).min().unwrap_or(0);
4832- let cbb_mean =
4833- diags.iter().map(|d| d.coded_bands).sum::<usize>() as f64 / dn as f64;
5192+ let cbb_mean = diags.iter().map(|d| d.coded_bands).sum::<usize>() as f64 / dn as f64;
48345193 let int_mean = diags.iter().map(|d| d.intensity).sum::<usize>() as f64 / dn as f64;
48355194 let bits =
48365195 diags.iter().map(|d| d.nb_compressed).sum::<usize>() as f64 * 8.0 / dn as f64;
@@ -4854,9 +5213,14 @@ fn spectral_divergence_vs_libopus() {
48545213 // frame each window lands in.
48555214 let mut byf: Vec<(usize, f64)> = ef2_o.iter().cloned().enumerate().collect();
48565215 byf.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
4857- report.push_str("# top-8 metric windows by ours ef²: offset_ms ours ref | enc frame diag\n");
5216+ report
5217+ .push_str("# top-8 metric windows by ours ef²: offset_ms ours ref | enc frame diag\n");
48585218 for &(xi, v) in &byf[..byf.len().min(8)] {
4859- let rv = if xi < ef2_r.len() { ef2_r[xi] } else { f64::NAN };
5219+ let rv = if xi < ef2_r.len() {
5220+ ef2_r[xi]
5221+ } else {
5222+ f64::NAN
5223+ };
48605224 let ms = xi * WIN_STEP * 1000 / 48000;
48615225 let eidx = xi * WIN_STEP / FRAME;
48625226 let d = diags.get(eidx);
@@ -4882,9 +5246,8 @@ fn spectral_divergence_vs_libopus() {
48825246 }
48835247
48845248 // Startup behavior: first 10 encoder frames.
4885- report.push_str(
4886- "# first encoder frames: idx trans intra silence cbb_hz int_hz dual bytes\n",
4887- );
5249+ report
5250+ .push_str("# first encoder frames: idx trans intra silence cbb_hz int_hz dual bytes\n");
48885251 for (i, d) in diags.iter().take(10).enumerate() {
48895252 report.push_str(&format!(
48905253 "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
@@ -4901,11 +5264,12 @@ fn spectral_divergence_vs_libopus() {
49015264
49025265 // Per-window per-band ln-energies for the metric windows 12..=20
49035266 // (+120..+200 ms): the leak's shape, band by band.
4904- report.push_str(
4905- "# windows 12..=20: win +ms band lo-hi | lnE src/ours/ref, ch L then R\n",
4906- );
5267+ report.push_str("# windows 12..=20: win +ms band lo-hi | lnE src/ours/ref, ch L then R\n");
49075268 // WIN_CENTRE=<window index> recentres the dump on another window.
4908- let wc: usize = std::env::var("WIN_CENTRE").ok().and_then(|v| v.parse().ok()).unwrap_or(16);
5269+ let wc: usize = std::env::var("WIN_CENTRE")
5270+ .ok()
5271+ .and_then(|v| v.parse().ok())
5272+ .unwrap_or(16);
49095273 for xi in wc.saturating_sub(4)..=wc + 4 {
49105274 if xi >= nframes {
49115275 break;
@@ -4951,7 +5315,8 @@ fn spectral_divergence_vs_libopus() {
49515315 g.total_bits,
49525316 ));
49535317 for (ch, name) in [(0usize, 'L'), (1usize, 'R')] {
4954- let band = &g.old_band_e[ch * ec_opus::celt::NB_BANDS..(ch + 1) * ec_opus::celt::NB_BANDS];
5318+ let band = &g.old_band_e
5319+ [ch * ec_opus::celt::NB_BANDS..(ch + 1) * ec_opus::celt::NB_BANDS];
49555320 let e: Vec<String> = band.iter().map(|v| format!("{v:+6.1}")).collect();
49565321 frames_all.push_str(&format!(" {name} {}\n", e.join(" ")));
49575322 }
@@ -5021,8 +5386,12 @@ fn celt_silence_then_attack_decodes_bounded() {
50215386 fn reell_startup_hop_energies() {
50225387 const CH: usize = 2;
50235388 // HOP_SRC / HOP_MS pick another source and window centre (diagnostic).
5024- let src_s = std::env::var("HOP_SRC").unwrap_or_else(|_| "~/Music/reell.mp4".into());
5025- let centre_ms: f64 = std::env::var("HOP_MS").ok().and_then(|v| v.parse().ok()).unwrap_or(42.5);
5389+ let src_s =
5390+ std::env::var("HOP_SRC").unwrap_or_else(|_| "~/Music/reell.mp4".into());
5391+ let centre_ms: f64 = std::env::var("HOP_MS")
5392+ .ok()
5393+ .and_then(|v| v.parse().ok())
5394+ .unwrap_or(42.5);
50265395 let src = shellexpand(&src_s);
50275396 if !src.exists() {
50285397 return;
@@ -5030,7 +5399,10 @@ fn reell_startup_hop_energies() {
50305399 let secs = (centre_ms / 1000.0 + 1.0).max(2.0);
50315400 let pcm = ffmpeg_decode_pcm(&src, secs);
50325401 let scratch = std::env::temp_dir().join("ec-opus-reell-startup.opus");
5033- let kbps: u32 = std::env::var("HOP_KBPS").ok().and_then(|v| v.parse().ok()).unwrap_or(96);
5402+ let kbps: u32 = std::env::var("HOP_KBPS")
5403+ .ok()
5404+ .and_then(|v| v.parse().ok())
5405+ .unwrap_or(96);
50345406 ffmpeg_encode_libopus(&src, kbps, &scratch, secs);
50355407 let (ref_dec, _) = decode_ogg(&scratch);
50365408 let (lag_r, ref_al) = align_to_source(&pcm, &ref_dec, CH, 2000);
@@ -5048,11 +5420,22 @@ fn reell_startup_hop_energies() {
50485420 ours_dec.extend_from_slice(&buf[..m * CH]);
50495421 let e = enc.last_celt_diag().clone();
50505422 let d = dec.last_celt_diag().clone();
5051- frames_diag.push((n, e.is_transient, e.intra, d.tf_res.clone(), d.anti_collapse));
5423+ frames_diag.push((
5424+ n,
5425+ e.is_transient,
5426+ e.intra,
5427+ d.tf_res.clone(),
5428+ d.anti_collapse,
5429+ ));
50525430 }
50535431 let (lag_o, ours_al) = align_to_source(&pcm, &ours_dec, CH, 2000);
50545432 let first = |v: &[f32]| v.iter().position(|x| x.abs() > 1e-4).map(|i| i / CH);
5055- println!("lag ref {lag_r} ours {lag_o}; first>1e-4: src {:?} ours {:?} ref {:?}", first(&pcm), first(&ours_al), first(&ref_al));
5433+ println!(
5434+ "lag ref {lag_r} ours {lag_o}; first>1e-4: src {:?} ours {:?} ref {:?}",
5435+ first(&pcm),
5436+ first(&ours_al),
5437+ first(&ref_al)
5438+ );
50565439 let e = |v: &[f32], h: usize| -> f64 {
50575440 let a = (h * 120 * CH).min(v.len());
50585441 let b = ((h + 1) * 120 * CH).min(v.len());
@@ -5061,12 +5444,21 @@ fn reell_startup_hop_energies() {
50615444 let hc = (centre_ms / 2.5) as usize;
50625445 for f in (hc / 8).saturating_sub(1)..=(hc / 8 + 1) {
50635446 if let Some((n, t, i, tf, ac)) = frames_diag.get(f) {
5064- println!("frame {f} ({:.1} ms): bytes {n} trans {t} intra {i} ac {ac} tf {tf:?}", f as f64 * 20.0);
5447+ println!(
5448+ "frame {f} ({:.1} ms): bytes {n} trans {t} intra {i} ac {ac} tf {tf:?}",
5449+ f as f64 * 20.0
5450+ );
50655451 }
50665452 }
50675453 println!("hop(ms)\tsrc\tours\tref");
50685454 for h in hc.saturating_sub(8)..hc + 8 {
5069- println!("{:.1}\t{:.3e}\t{:.3e}\t{:.3e}", h as f64 * 2.5, e(&pcm, h), e(&ours_al, h), e(&ref_al, h));
5455+ println!(
5456+ "{:.1}\t{:.3e}\t{:.3e}\t{:.3e}",
5457+ h as f64 * 2.5,
5458+ e(&pcm, h),
5459+ e(&ours_al, h),
5460+ e(&ref_al, h)
5461+ );
50705462 }
50715463 }
50725464
@@ -5083,9 +5475,18 @@ fn celt_click_peak_offset() {
50835475 enc.set_mode(Some(ec_opus::Mode::Celt));
50845476 enc.set_bitrate(bps);
50855477 let (dec, _) = roundtrip_own(&mut enc, &click, 1, 960);
5086- let p = dec.iter().enumerate().max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()).unwrap().0;
5478+ let p = dec
5479+ .iter()
5480+ .enumerate()
5481+ .max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap())
5482+ .unwrap()
5483+ .0;
50875484 let d = enc.last_celt_diag().clone();
5088- println!("celt click {bps}: peak +{} (lm {})", p as i64 - at as i64, d.lm);
5485+ println!(
5486+ "celt click {bps}: peak +{} (lm {})",
5487+ p as i64 - at as i64,
5488+ d.lm
5489+ );
50895490 }
50905491 }
50915492
@@ -5147,7 +5548,9 @@ fn short_block_bits_vs_libopus() {
51475548
51485549 // Reference: ffmpeg libopus at KBPS, VBR.
51495550 ffmpeg_encode_libopus(src, KBPS, &scratch, SECS);
5150- let ref_bytes = fs::metadata(&scratch).map(|m| m.len() as usize).unwrap_or(0);
5551+ let ref_bytes = fs::metadata(&scratch)
5552+ .map(|m| m.len() as usize)
5553+ .unwrap_or(0);
51515554 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
51525555 let ref_pkts: Vec<Vec<u8>> = ogg_packets(&fs::read(&scratch).unwrap())
51535556 .into_iter()
@@ -5182,7 +5585,9 @@ fn short_block_bits_vs_libopus() {
51825585 for block in source_pcm.chunks(FRAME * CHANNELS) {
51835586 let mut padded = block.to_vec();
51845587 padded.resize(FRAME * CHANNELS, 0.0);
5185- let len = enc.encode_float(&padded, FRAME, &mut packet).expect("encode");
5588+ let len = enc
5589+ .encode_float(&padded, FRAME, &mut packet)
5590+ .expect("encode");
51865591 ours_bytes += len;
51875592 let toc = ec_opus::Toc::new(packet[0]);
51885593 if dec.decode_float(&packet[..len], &mut dbuf).is_ok() && toc.mode() != Mode::Silk {
@@ -5199,10 +5604,14 @@ fn short_block_bits_vs_libopus() {
51995604 ));
52005605
52015606 for (label, is_trans) in [("LONG", false), ("SHORT", true)] {
5202- let ours_t: Vec<&ec_opus::celt::CeltDecDiag> =
5203- ours_diags.iter().filter(|d| d.transient == is_trans).collect();
5204- let ref_t: Vec<&ec_opus::celt::CeltDecDiag> =
5205- ref_diags.iter().filter(|d| d.transient == is_trans).collect();
5607+ let ours_t: Vec<&ec_opus::celt::CeltDecDiag> = ours_diags
5608+ .iter()
5609+ .filter(|d| d.transient == is_trans)
5610+ .collect();
5611+ let ref_t: Vec<&ec_opus::celt::CeltDecDiag> = ref_diags
5612+ .iter()
5613+ .filter(|d| d.transient == is_trans)
5614+ .collect();
52065615 let on = ours_t.len();
52075616 let rn = ref_t.len();
52085617 if on == 0 && rn == 0 {
@@ -5235,19 +5644,18 @@ fn short_block_bits_vs_libopus() {
52355644 ours_t.iter().map(|d| d.fine_quant[i] as f64).sum::<f64>() / on.max(1) as f64;
52365645 let rm: f64 =
52375646 ref_t.iter().map(|d| d.fine_quant[i] as f64).sum::<f64>() / rn.max(1) as f64;
5238- report.push_str(&format!(
5239- "{}\t{:.2}\t{:.2}\n",
5240- CELT_EBANDS[i] * 240,
5241- om,
5242- rm
5243- ));
5647+ report.push_str(&format!("{}\t{:.2}\t{:.2}\n", CELT_EBANDS[i] * 240, om, rm));
52445648 }
52455649
52465650 // Aggregate stats.
5247- let mean = |v: &[&ec_opus::celt::CeltDecDiag], f: &dyn Fn(&ec_opus::celt::CeltDecDiag) -> f64| -> f64 {
5651+ let mean = |v: &[&ec_opus::celt::CeltDecDiag],
5652+ f: &dyn Fn(&ec_opus::celt::CeltDecDiag) -> f64|
5653+ -> f64 {
52485654 v.iter().map(|d| f(d)).sum::<f64>() / v.len().max(1) as f64
52495655 };
5250- let mean_band_hz = |v: &[&ec_opus::celt::CeltDecDiag], f: &dyn Fn(&ec_opus::celt::CeltDecDiag) -> usize| -> f64 {
5656+ let mean_band_hz = |v: &[&ec_opus::celt::CeltDecDiag],
5657+ f: &dyn Fn(&ec_opus::celt::CeltDecDiag) -> usize|
5658+ -> f64 {
52515659 let m = v.iter().map(|d| f(d)).sum::<usize>() / v.len().max(1);
52525660 CELT_EBANDS[m] as f64 * 240.0
52535661 };
@@ -5291,16 +5699,22 @@ fn short_block_bits_vs_libopus() {
52915699 ));
52925700 report.push_str("# mean dynalloc boost per band (1/8 bit) ours / ref\n");
52935701 for b in 0..nb {
5294- let mo = mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.offsets[b] as f64);
5295- let mr = mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.offsets[b] as f64);
5702+ let mo = mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| {
5703+ d.offsets[b] as f64
5704+ });
5705+ let mr = mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| {
5706+ d.offsets[b] as f64
5707+ });
52965708 if mo != 0.0 || mr != 0.0 {
52975709 report.push_str(&format!("{}\t{:.1}\t{:.1}\n", CELT_EBANDS[b] * 240, mo, mr));
52985710 }
52995711 }
53005712 report.push_str(&format!(
53015713 "# alloc_trim mean: ours {:.2} ref {:.2}\n",
5302- mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.alloc_trim as f64),
5303- mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.alloc_trim as f64),
5714+ mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.alloc_trim
5715+ as f64),
5716+ mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.alloc_trim
5717+ as f64),
53045718 ));
53055719 report.push_str(&format!(
53065720 "# coded_bands mean Hz: ours {:.0} ref {:.0}\n",
@@ -5319,8 +5733,10 @@ fn short_block_bits_vs_libopus() {
53195733 ));
53205734 report.push_str(&format!(
53215735 "# total_bits mean: ours {:.0} ref {:.0}\n",
5322- mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.total_bits as f64),
5323- mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.total_bits as f64),
5736+ mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.total_bits
5737+ as f64),
5738+ mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.total_bits
5739+ as f64),
53245740 ));
53255741 report.push_str(&format!(
53265742 "# balance mean: ours {:.0} ref {:.0}\n",
@@ -5393,7 +5809,9 @@ fn err_map_vs_libopus() {
53935809
53945810 // Reference: ffmpeg libopus, VBR — the gate's path.
53955811 ffmpeg_encode_libopus(&src, kbps_env, &scratch, SECS);
5396- let ref_bytes = fs::metadata(&scratch).map(|m| m.len() as usize).unwrap_or(0);
5812+ let ref_bytes = fs::metadata(&scratch)
5813+ .map(|m| m.len() as usize)
5814+ .unwrap_or(0);
53975815 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
53985816 let (ref_dec, ref_ch) = decode_ogg(&scratch);
53995817 assert_eq!(ref_ch, CH, "ref not stereo");
@@ -5421,7 +5839,11 @@ fn err_map_vs_libopus() {
54215839 let toc = ec_opus::Toc::new(p[0]);
54225840 let got = d.decode_float(p, &mut buf).unwrap_or(0);
54235841 if toc.mode() != Mode::Silk {
5424- ref_fd.push(FD { sample: at, enc: None, dec: d.last_celt_diag().clone() });
5842+ ref_fd.push(FD {
5843+ sample: at,
5844+ enc: None,
5845+ dec: d.last_celt_diag().clone(),
5846+ });
54255847 }
54265848 at += got;
54275849 }
@@ -5465,7 +5887,11 @@ fn err_map_vs_libopus() {
54655887
54665888 // 1 s windows.
54675889 let nwin = hop_o.len() / HOPS_PER_WIN;
5468- let sum = |h: &[f64], w: usize| h[w * HOPS_PER_WIN..(w + 1) * HOPS_PER_WIN].iter().sum::<f64>();
5890+ let sum = |h: &[f64], w: usize| {
5891+ h[w * HOPS_PER_WIN..(w + 1) * HOPS_PER_WIN]
5892+ .iter()
5893+ .sum::<f64>()
5894+ };
54695895 let tot_o: f64 = hop_o.iter().sum();
54705896 let tot_r: f64 = hop_r.iter().sum();
54715897 let mut wins: Vec<(usize, f64, f64, f64)> = (0..nwin)
@@ -5500,9 +5926,9 @@ fn err_map_vs_libopus() {
55005926 f.dec.spread,
55015927 f.dec.anti_collapse as u8,
55025928 f.dec.total_bits,
5503- ) + &e.map(|e| format!(
5504- " | ENC sb{} vbr{}", e.short_blocks, e.vbr_reservoir
5505- )).unwrap_or_default()
5929+ ) + &e
5930+ .map(|e| format!(" | ENC sb{} vbr{}", e.short_blocks, e.vbr_reservoir))
5931+ .unwrap_or_default()
55065932 };
55075933 let ref_at = |s: usize| -> Option<&FD> {
55085934 let i = ref_fd.partition_point(|f| f.sample <= s);
@@ -5569,13 +5995,19 @@ fn err_map_vs_libopus() {
55695995 )
55705996 })
55715997 .collect();
5572- out.push_str(&format!(" Δlog2E L {}\n R {}\n", d0.join(" "), d1.join(" ")));
5998+ out.push_str(&format!(
5999+ " Δlog2E L {}\n R {}\n",
6000+ d0.join(" "),
6001+ d1.join(" ")
6002+ ));
55736003 }
55746004 }
55756005 }
55766006
55776007 // The single worst ours window, frame by frame: where do decisions diverge.
5578- let worst = (0..nwin).max_by(|&a, &b| wins[a].1.total_cmp(&wins[b].1)).unwrap();
6008+ let worst = (0..nwin)
6009+ .max_by(|&a, &b| wins[a].1.total_cmp(&wins[b].1))
6010+ .unwrap();
55796011 out.push_str(&format!(
55806012 "\n== WORST WINDOW t={}..{}s, ALL FRAMES (OUR | REF) ==\n",
55816013 worst,
@@ -5583,7 +6015,9 @@ fn err_map_vs_libopus() {
55836015 ));
55846016 for fi in worst * 50..(worst + 1) * 50 {
55856017 let our = ours_fd.get(fi).map(&fmt_fd).unwrap_or_else(|| "-".into());
5586- let rf = ref_at(fi * FRAME + 480).map(&fmt_fd).unwrap_or_else(|| "-".into());
6018+ let rf = ref_at(fi * FRAME + 480)
6019+ .map(&fmt_fd)
6020+ .unwrap_or_else(|| "-".into());
55876021 out.push_str(&format!("f{fi}: OUR {our}\n REF {rf}\n"));
55886022 }
55896023
@@ -5599,31 +6033,53 @@ fn err_map_vs_libopus() {
55996033 #[ignore]
56006034 fn frame_decisions_vs_libopus() {
56016035 const CH: usize = 2;
5602- let src_s = std::env::var("FRAME_SRC")
5603- .unwrap_or_else(|_| "~/Music/reell.mp4".into());
6036+ let src_s =
6037+ std::env::var("FRAME_SRC").unwrap_or_else(|_| "~/Music/reell.mp4".into());
56046038 let src = shellexpand(&src_s);
56056039 if !src.exists() {
56066040 eprintln!("SKIP: missing {}", src.display());
56076041 return;
56086042 }
5609- let kbps: u32 = std::env::var("FRAME_KBPS").ok().and_then(|v| v.parse().ok()).unwrap_or(64);
5610- let from: usize = std::env::var("FRAME_FROM").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
5611- let to: usize = std::env::var("FRAME_TO").ok().and_then(|v| v.parse().ok()).unwrap_or(6);
6043+ let kbps: u32 = std::env::var("FRAME_KBPS")
6044+ .ok()
6045+ .and_then(|v| v.parse().ok())
6046+ .unwrap_or(64);
6047+ let from: usize = std::env::var("FRAME_FROM")
6048+ .ok()
6049+ .and_then(|v| v.parse().ok())
6050+ .unwrap_or(0);
6051+ let to: usize = std::env::var("FRAME_TO")
6052+ .ok()
6053+ .and_then(|v| v.parse().ok())
6054+ .unwrap_or(6);
56126055 let secs = (to as f64 * 0.02 + 1.0).max(2.0);
56136056 let pcm = ffmpeg_decode_pcm(&src, secs);
56146057 let scratch = std::env::temp_dir().join("ec-opus-frame-dec.opus");
56156058 ffmpeg_encode_libopus(&src, kbps, &scratch, secs);
5616- let ref_pkts: Vec<Vec<u8>> =
5617- ogg_packets(&fs::read(&scratch).unwrap()).into_iter().skip(2).collect();
6059+ let ref_pkts: Vec<Vec<u8>> = ogg_packets(&fs::read(&scratch).unwrap())
6060+ .into_iter()
6061+ .skip(2)
6062+ .collect();
56186063
56196064 let show = |tag: &str, f: usize, bytes: usize, d: &ec_opus::celt::CeltDecDiag| {
5620- let e: Vec<String> = d.old_band_e[..NB_BANDS_DIAG].iter().map(|v| format!("{v:.1}")).collect();
6065+ let e: Vec<String> = d.old_band_e[..NB_BANDS_DIAG]
6066+ .iter()
6067+ .map(|v| format!("{v:.1}"))
6068+ .collect();
56216069 println!(
56226070 "f{f} {tag}: bytes {bytes} sil {} intra {} trans {} ac {} trim {} spread {} cb {} \
56236071 tf {:?} pulses {:?} fine {:?} E {}",
5624- d.silence, d.intra, d.transient, d.anti_collapse, d.alloc_trim, d.spread,
5625- d.coded_bands, &d.tf_res[..NB_BANDS_DIAG], &d.pulses[..NB_BANDS_DIAG],
5626- &d.fine_quant[..NB_BANDS_DIAG], e.join(",")
6072+ d.silence,
6073+ d.intra,
6074+ d.transient,
6075+ d.anti_collapse,
6076+ d.alloc_trim,
6077+ d.spread,
6078+ d.coded_bands,
6079+ &d.tf_res[..NB_BANDS_DIAG],
6080+ &d.pulses[..NB_BANDS_DIAG],
6081+ &d.fine_quant[..NB_BANDS_DIAG],
6082+ e.join(",")
56276083 );
56286084 };
56296085
@@ -5634,7 +6090,11 @@ fn frame_decisions_vs_libopus() {
56346090 let ok = !p.is_empty()
56356091 && ec_opus::Toc::new(p[0]).mode() != Mode::Silk
56366092 && d.decode_float(p, &mut buf).is_ok();
5637- ref_rows.push(if ok { Some((p.len(), d.last_celt_diag().clone())) } else { None });
6093+ ref_rows.push(if ok {
6094+ Some((p.len(), d.last_celt_diag().clone()))
6095+ } else {
6096+ None
6097+ });
56386098 }
56396099
56406100 // Encode at the reference's REALISED rate, like the library gate does:
@@ -5653,7 +6113,11 @@ fn frame_decisions_vs_libopus() {
56536113 let n = enc.encode_float(block, 960, &mut out).unwrap();
56546114 let ok = ec_opus::Toc::new(out[0]).mode() != Mode::Silk
56556115 && dec.decode_float(&out[..n], &mut buf).is_ok();
5656- ours_rows.push(if ok { Some((n, dec.last_celt_diag().clone())) } else { None });
6116+ ours_rows.push(if ok {
6117+ Some((n, dec.last_celt_diag().clone()))
6118+ } else {
6119+ None
6120+ });
56576121 }
56586122
56596123 if to - from <= 40 {
@@ -5674,9 +6138,10 @@ fn frame_decisions_vs_libopus() {
56746138 let mut agg = [(0usize, [0.0f64; 8]); 2];
56756139 let mut trans_diff = 0usize;
56766140 for f in from..to {
5677- let (Some((no, o)), Some((nr, r))) =
5678- (ours_rows.get(f).and_then(|x| x.as_ref()), ref_rows.get(f).and_then(|x| x.as_ref()))
5679- else {
6141+ let (Some((no, o)), Some((nr, r))) = (
6142+ ours_rows.get(f).and_then(|x| x.as_ref()),
6143+ ref_rows.get(f).and_then(|x| x.as_ref()),
6144+ ) else {
56806145 continue;
56816146 };
56826147 if o.transient != r.transient {
@@ -5689,10 +6154,14 @@ fn frame_decisions_vs_libopus() {
56896154 let a = &mut agg[slot];
56906155 a.0 += 1;
56916156 for (k, v) in [
5692- *no as f64, *nr as f64,
5693- o.alloc_trim as f64, r.alloc_trim as f64,
5694- tf(o), tf(r),
5695- f64::from(u8::from(o.anti_collapse)), f64::from(u8::from(r.anti_collapse)),
6157+ *no as f64,
6158+ *nr as f64,
6159+ o.alloc_trim as f64,
6160+ r.alloc_trim as f64,
6161+ tf(o),
6162+ tf(r),
6163+ f64::from(u8::from(o.anti_collapse)),
6164+ f64::from(u8::from(r.anti_collapse)),
56966165 ]
56976166 .into_iter()
56986167 .enumerate()
@@ -5710,7 +6179,14 @@ fn frame_decisions_vs_libopus() {
57106179 println!(
57116180 "{name} n={n}: bytes o {:.1} r {:.1} | trim o {:.2} r {:.2} | mean tf_res o {:.3} \
57126181 r {:.3} | anti_collapse o {:.2} r {:.2}",
5713- m(0), m(1), m(2), m(3), m(4), m(5), m(6), m(7)
6182+ m(0),
6183+ m(1),
6184+ m(2),
6185+ m(3),
6186+ m(4),
6187+ m(5),
6188+ m(6),
6189+ m(7)
57146190 );
57156191 }
57166192 }
@@ -5730,7 +6206,11 @@ fn analysis_music_prob_separates_speech_from_music() {
57306206 const FRAME: usize = 960;
57316207 const CHANNELS: usize = 2;
57326208 let sources: &[(&str, &str, bool)] = &[
5733- ("hein", "~/Downloads/reelm.mp3", false),
6209+ (
6210+ "hein",
6211+ "~/Downloads/reelm.mp3",
6212+ false,
6213+ ),
57346214 ("reell", "~/Music/reell.mp4", true),
57356215 ("reelo", "~/Music/reelo.mp3", true),
57366216 ];
@@ -5781,7 +6261,10 @@ fn analysis_music_prob_separates_speech_from_music() {
57816261 bw_hist[(d.analysis_bandwidth.clamp(0, 20)) as usize] += 1;
57826262 }
57836263 }
5784- assert!(valid * 10 > n * 9, "{tag}: analysis valid on only {valid}/{n} frames");
6264+ assert!(
6265+ valid * 10 > n * 9,
6266+ "{tag}: analysis valid on only {valid}/{n} frames"
6267+ );
57856268 let bw: Vec<String> = bw_hist
57866269 .iter()
57876270 .enumerate()
@@ -5816,7 +6299,12 @@ fn analysis_music_prob_separates_speech_from_music() {
58166299 let speech: Vec<_> = means.iter().filter(|m| !m.1).collect();
58176300 let music: Vec<_> = means.iter().filter(|m| m.1).collect();
58186301 for s in &speech {
5819- assert!(s.2 < 0.5, "{}: speech music_prob {:.3} should be < 0.5", s.0, s.2);
6302+ assert!(
6303+ s.2 < 0.5,
6304+ "{}: speech music_prob {:.3} should be < 0.5",
6305+ s.0,
6306+ s.2
6307+ );
58206308 for m in &music {
58216309 assert!(
58226310 m.2 - s.2 > 0.2,
@@ -5829,6 +6317,11 @@ fn analysis_music_prob_separates_speech_from_music() {
58296317 }
58306318 }
58316319 for m in &music {
5832- assert!(m.2 > 0.5, "{}: music music_prob {:.3} should be > 0.5", m.0, m.2);
6320+ assert!(
6321+ m.2 > 0.5,
6322+ "{}: music music_prob {:.3} should be > 0.5",
6323+ m.0,
6324+ m.2
6325+ );
58336326 }
58346327 }