| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | use std::path::{Path, PathBuf}; |
| 12 | use std::process::Command; |
| 13 | |
| 14 | use ec_mp3::{Mp3Encoder, Mp3EncoderConfig}; |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | const BAR: [(&str, [f64; 3]); 4] = [ |
| 22 | ("mp3src-mono-44100", [0.99920, 0.99983, 0.99999]), |
| 23 | ("mp3src-stereo-44100", [0.99612, 0.99847, 0.99972]), |
| 24 | ("mp3src-mono-48000", [0.99867, 0.99972, 0.99998]), |
| 25 | ("mp3src-stereo-48000", [0.99461, 0.99787, 0.99956]), |
| 26 | ]; |
| 27 | const BITRATES: [u32; 3] = [128, 192, 320]; |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | fn bar_for(name: &str, kbps: u32) -> f64 { |
| 33 | let index = BITRATES.iter().position(|k| *k == kbps).unwrap_or(0); |
| 34 | for (fixture, values) in BAR { |
| 35 | if name.starts_with(fixture) { |
| 36 | return values[index]; |
| 37 | } |
| 38 | } |
| 39 | BAR.iter() |
| 40 | .map(|(_, v)| v[index]) |
| 41 | .fold(f64::INFINITY, f64::min) |
| 42 | } |
| 43 | |
| 44 | fn fixtures() -> PathBuf { |
| 45 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") |
| 46 | } |
| 47 | |
| 48 | fn workdir(test: &str) -> PathBuf { |
| 49 | let dir = std::env::temp_dir().join(format!("ec-mp3-{}-{test}", std::process::id())); |
| 50 | std::fs::create_dir_all(&dir).expect("create work dir"); |
| 51 | dir |
| 52 | } |
| 53 | |
| 54 | |
| 55 | fn read_wav(path: &Path) -> Option<(Vec<f32>, u32, usize)> { |
| 56 | let out = Command::new("ffmpeg") |
| 57 | .args(["-v", "error", "-i"]) |
| 58 | .arg(path) |
| 59 | .args(["-f", "f32le", "-"]) |
| 60 | .output() |
| 61 | .ok()?; |
| 62 | if !out.status.success() { |
| 63 | return None; |
| 64 | } |
| 65 | let samples = out |
| 66 | .stdout |
| 67 | .chunks_exact(4) |
| 68 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 69 | .collect(); |
| 70 | let probe = Command::new("ffprobe") |
| 71 | .args([ |
| 72 | "-v", |
| 73 | "error", |
| 74 | "-select_streams", |
| 75 | "a:0", |
| 76 | "-show_entries", |
| 77 | "stream=channels,sample_rate", |
| 78 | "-of", |
| 79 | "default=noprint_wrappers=1", |
| 80 | ]) |
| 81 | .arg(path) |
| 82 | .output() |
| 83 | .ok()?; |
| 84 | let text = String::from_utf8_lossy(&probe.stdout); |
| 85 | let field = |key: &str| { |
| 86 | text.lines() |
| 87 | .find_map(|l| l.strip_prefix(key)?.strip_prefix('=')) |
| 88 | .and_then(|v| v.trim().parse::<u32>().ok()) |
| 89 | }; |
| 90 | Some((samples, field("sample_rate")?, field("channels")? as usize)) |
| 91 | } |
| 92 | |
| 93 | fn correlation(a: &[f32], b: &[f32]) -> f64 { |
| 94 | let n = a.len().min(b.len()); |
| 95 | let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64); |
| 96 | for i in 0..n { |
| 97 | let (x, y) = (a[i] as f64, b[i] as f64); |
| 98 | ab += x * y; |
| 99 | aa += x * x; |
| 100 | bb += y * y; |
| 101 | } |
| 102 | if aa == 0.0 || bb == 0.0 { |
| 103 | return 0.0; |
| 104 | } |
| 105 | ab / (aa * bb).sqrt() |
| 106 | } |
| 107 | |
| 108 | |
| 109 | fn aligned(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) { |
| 110 | let mut best = (f64::MIN, 0usize); |
| 111 | let mut offset = 0; |
| 112 | while offset + channels < got.len() && offset <= 3000 * channels { |
| 113 | let n = (got.len() - offset).min(want.len()); |
| 114 | let skip = 1152 * channels; |
| 115 | if n <= 2 * skip { |
| 116 | break; |
| 117 | } |
| 118 | let corr = correlation( |
| 119 | &got[offset + skip..offset + n - skip], |
| 120 | &want[skip..n - skip], |
| 121 | ); |
| 122 | if corr > best.0 { |
| 123 | best = (corr, offset); |
| 124 | } |
| 125 | offset += channels; |
| 126 | } |
| 127 | best |
| 128 | } |
| 129 | |
| 130 | fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> { |
| 131 | let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { |
| 132 | bitrate_kbps: kbps, |
| 133 | vbr_quality: None, |
| 134 | }); |
| 135 | encoder |
| 136 | .push_pcm_f32(pcm, channels as u16, rate) |
| 137 | .expect("encoder accepts the fixture"); |
| 138 | encoder.finish(); |
| 139 | let mut out = Vec::new(); |
| 140 | while let Ok(frame) = encoder.next_packet() { |
| 141 | out.extend_from_slice(&frame); |
| 142 | } |
| 143 | out |
| 144 | } |
| 145 | |
| 146 | #[test] |
| 147 | fn encodes_above_the_incumbent_bar() { |
| 148 | let dir = fixtures().join("audio"); |
| 149 | let mut sources: Vec<PathBuf> = std::fs::read_dir(&dir) |
| 150 | .into_iter() |
| 151 | .flatten() |
| 152 | .flatten() |
| 153 | .map(|e| e.path()) |
| 154 | .filter(|p| { |
| 155 | let name = p.file_name().map(|n| n.to_string_lossy().to_string()); |
| 156 | name.is_some_and(|n| n.starts_with("wav16-") || n.starts_with("mp3src-")) |
| 157 | && p.extension().is_some_and(|e| e == "wav") |
| 158 | }) |
| 159 | .collect(); |
| 160 | sources.sort(); |
| 161 | sources.retain(|p| { |
| 162 | let name = p.file_name().unwrap().to_string_lossy().to_string(); |
| 163 | name.contains("mono") || name.contains("stereo") |
| 164 | }); |
| 165 | if sources.is_empty() { |
| 166 | eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); |
| 167 | return; |
| 168 | } |
| 169 | let work = workdir("encode"); |
| 170 | println!( |
| 171 | "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}", |
| 172 | "fixture", "kbps", "rate", "ch", "corr", "bar", "kbit/s" |
| 173 | ); |
| 174 | let mut failures = Vec::new(); |
| 175 | for source in &sources { |
| 176 | let Some((pcm, rate, channels)) = read_wav(source) else { |
| 177 | continue; |
| 178 | }; |
| 179 | for kbps in BITRATES { |
| 180 | let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps); |
| 181 | let bytes = encode(&pcm, rate, channels, kbps); |
| 182 | let path = work.join(format!( |
| 183 | "{}-{kbps}.mp3", |
| 184 | source.file_stem().unwrap().to_string_lossy() |
| 185 | )); |
| 186 | std::fs::write(&path, &bytes).expect("write encoded file"); |
| 187 | let out = Command::new("ffmpeg") |
| 188 | .args(["-v", "warning", "-i"]) |
| 189 | .arg(&path) |
| 190 | .args(["-f", "f32le", "-"]) |
| 191 | .output() |
| 192 | .expect("run ffmpeg"); |
| 193 | let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); |
| 194 | if !stderr.is_empty() { |
| 195 | failures.push(format!("{}: ffmpeg said {stderr}", path.display())); |
| 196 | } |
| 197 | let decoded: Vec<f32> = out |
| 198 | .stdout |
| 199 | .chunks_exact(4) |
| 200 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 201 | .collect(); |
| 202 | let (corr, _offset) = aligned(&decoded, &pcm, channels); |
| 203 | let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); |
| 204 | let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0; |
| 205 | let name = source.file_name().unwrap().to_string_lossy(); |
| 206 | println!( |
| 207 | "{name:<30} {kbps:>5} {rate:>6} {channels:>3} {corr:>9.5} {bar:>8.5} {measured:>9.1}" |
| 208 | ); |
| 209 | |
| 210 | |
| 211 | |
| 212 | if corr < bar - 1e-5 { |
| 213 | failures.push(format!("{name} at {kbps} kbit/s: {corr:.5} < bar {bar:.5}")); |
| 214 | } |
| 215 | if (measured - kbps as f64).abs() > kbps as f64 * 0.05 { |
| 216 | failures.push(format!( |
| 217 | "{name} at {kbps} kbit/s: wrote {measured:.1} kbit/s" |
| 218 | )); |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | assert!(failures.is_empty(), "{failures:#?}"); |
| 223 | } |