| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | use std::path::{Path, PathBuf}; |
| 13 | use std::process::Command; |
| 14 | use std::time::Instant; |
| 15 | |
| 16 | use ec_mp3::Mp3Reader; |
| 17 | |
| 18 | fn fixtures() -> PathBuf { |
| 19 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") |
| 20 | } |
| 21 | |
| 22 | fn mp3_fixtures() -> Vec<PathBuf> { |
| 23 | let dir = fixtures().join("audio"); |
| 24 | let Ok(entries) = std::fs::read_dir(&dir) else { |
| 25 | return Vec::new(); |
| 26 | }; |
| 27 | let mut out: Vec<PathBuf> = entries |
| 28 | .flatten() |
| 29 | .map(|e| e.path()) |
| 30 | .filter(|p| p.extension().is_some_and(|e| e == "mp3")) |
| 31 | .collect(); |
| 32 | out.sort(); |
| 33 | out |
| 34 | } |
| 35 | |
| 36 | fn ffmpeg_decode(path: &Path) -> Option<(Vec<f32>, u32, usize)> { |
| 37 | let out = Command::new("ffmpeg") |
| 38 | .args(["-v", "error", "-i"]) |
| 39 | .arg(path) |
| 40 | .args(["-f", "f32le", "-"]) |
| 41 | .output() |
| 42 | .ok()?; |
| 43 | if !out.status.success() { |
| 44 | return None; |
| 45 | } |
| 46 | let samples = out |
| 47 | .stdout |
| 48 | .chunks_exact(4) |
| 49 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 50 | .collect(); |
| 51 | let probe = Command::new("ffprobe") |
| 52 | .args([ |
| 53 | "-v", |
| 54 | "error", |
| 55 | "-select_streams", |
| 56 | "a:0", |
| 57 | "-show_entries", |
| 58 | "stream=channels,sample_rate", |
| 59 | "-of", |
| 60 | "default=noprint_wrappers=1", |
| 61 | ]) |
| 62 | .arg(path) |
| 63 | .output() |
| 64 | .ok()?; |
| 65 | let text = String::from_utf8_lossy(&probe.stdout); |
| 66 | let field = |key: &str| { |
| 67 | text.lines() |
| 68 | .find_map(|l| l.strip_prefix(key)?.strip_prefix('=')) |
| 69 | .and_then(|v| v.trim().parse::<u32>().ok()) |
| 70 | }; |
| 71 | Some((samples, field("sample_rate")?, field("channels")? as usize)) |
| 72 | } |
| 73 | |
| 74 | fn correlation(a: &[f32], b: &[f32]) -> f64 { |
| 75 | let n = a.len().min(b.len()); |
| 76 | let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64); |
| 77 | for i in 0..n { |
| 78 | let (x, y) = (a[i] as f64, b[i] as f64); |
| 79 | ab += x * y; |
| 80 | aa += x * x; |
| 81 | bb += y * y; |
| 82 | } |
| 83 | if aa == 0.0 || bb == 0.0 { |
| 84 | return f64::from(u8::from(aa == bb)); |
| 85 | } |
| 86 | ab / (aa * bb).sqrt() |
| 87 | } |
| 88 | |
| 89 | |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | fn best_alignment(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) { |
| 95 | let mut best = (f64::MIN, 0usize); |
| 96 | let mut offset = 0; |
| 97 | while offset < got.len() && offset <= 2304 * channels { |
| 98 | let n = (got.len() - offset).min(want.len()).min(200_000); |
| 99 | let corr = correlation(&got[offset..offset + n], &want[..n]); |
| 100 | if corr > best.0 { |
| 101 | best = (corr, offset); |
| 102 | } |
| 103 | offset += channels; |
| 104 | } |
| 105 | let (_, offset) = best; |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | let skip = 1152 * channels; |
| 111 | let n = (got.len() - offset) |
| 112 | .min(want.len()) |
| 113 | .saturating_sub(2 * skip); |
| 114 | ( |
| 115 | correlation( |
| 116 | &got[offset + skip..offset + skip + n], |
| 117 | &want[skip..skip + n], |
| 118 | ), |
| 119 | offset, |
| 120 | ) |
| 121 | } |
| 122 | |
| 123 | #[test] |
| 124 | fn decodes_every_fixture_like_ffmpeg() { |
| 125 | let files = mp3_fixtures(); |
| 126 | if files.is_empty() { |
| 127 | eprintln!("no MP3 fixtures: run scripts/gen-fixtures.sh and scripts/gen-mp3-fixtures.sh"); |
| 128 | return; |
| 129 | } |
| 130 | println!( |
| 131 | "{:<34} {:>6} {:>3} {:>9} {:>9} {:>8}", |
| 132 | "fixture", "rate", "ch", "samples", "corr", "x rt" |
| 133 | ); |
| 134 | let mut worst = 1.0f64; |
| 135 | let mut failures = Vec::new(); |
| 136 | for path in &files { |
| 137 | let bytes = std::fs::read(path).expect("read fixture"); |
| 138 | let Some((want, rate, channels)) = ffmpeg_decode(path) else { |
| 139 | panic!("ffmpeg could not decode {}", path.display()); |
| 140 | }; |
| 141 | let start = Instant::now(); |
| 142 | let mut reader = Mp3Reader::new(); |
| 143 | reader.push(&bytes); |
| 144 | let frames = reader.decode_all(); |
| 145 | let elapsed = start.elapsed().as_secs_f64(); |
| 146 | let mut got = Vec::with_capacity(want.len()); |
| 147 | for frame in &frames { |
| 148 | got.extend_from_slice(&frame.samples); |
| 149 | } |
| 150 | let name = path.file_name().unwrap().to_string_lossy(); |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | let (corr, offset) = best_alignment(&got, &want, channels); |
| 156 | let seconds = got.len() as f64 / (rate as f64 * channels as f64); |
| 157 | let realtime = seconds / elapsed.max(1e-9); |
| 158 | println!( |
| 159 | "{name:<34} {rate:>6} {channels:>3} {:>9} {corr:>9.6} {realtime:>8.0} (+{offset})", |
| 160 | got.len() |
| 161 | ); |
| 162 | |
| 163 | |
| 164 | |
| 165 | let slack = 2 * 1152 * channels; |
| 166 | if got.len() + slack < want.len() || want.len() + slack < got.len() { |
| 167 | failures.push(format!( |
| 168 | "{name}: {} samples, ffmpeg {} ", |
| 169 | got.len(), |
| 170 | want.len() |
| 171 | )); |
| 172 | } |
| 173 | if corr < 0.999 { |
| 174 | failures.push(format!("{name}: correlation {corr:.6}")); |
| 175 | } |
| 176 | worst = worst.min(corr); |
| 177 | } |
| 178 | println!("worst correlation {worst:.6} over {} fixtures", files.len()); |
| 179 | assert!(failures.is_empty(), "{failures:#?}"); |
| 180 | } |