| 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::{FrameHeader, 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 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | fn worst_window_db(got: &[f32], want: &[f32], offset: usize, channels: usize) -> f64 { |
| 142 | let window = 20 * 44100 / 1000 * channels; |
| 143 | let skip = 1152 * channels; |
| 144 | let n = (got.len() - offset).min(want.len()); |
| 145 | let mut worst = f64::MIN; |
| 146 | let mut start = skip; |
| 147 | while start + window + skip <= n { |
| 148 | let (mut err, mut sig) = (0.0f64, 0.0f64); |
| 149 | for i in start..start + window { |
| 150 | let d = f64::from(got[offset + i]) - f64::from(want[i]); |
| 151 | err += d * d; |
| 152 | sig += f64::from(want[i]) * f64::from(want[i]); |
| 153 | } |
| 154 | |
| 155 | |
| 156 | |
| 157 | if sig / window as f64 > 1e-6 { |
| 158 | let db = 10.0 * (err / sig.max(1e-30)).log10(); |
| 159 | if db > worst { |
| 160 | worst = db; |
| 161 | if std::env::var_os("EC_MP3_WORST_WHERE").is_some() { |
| 162 | eprintln!( |
| 163 | " worst so far {db:+.1} dB at {:.2} s, level {:.1} dBFS", |
| 164 | start as f64 / (44100.0 * channels as f64), |
| 165 | 10.0 * (sig / window as f64).log10() |
| 166 | ); |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | start += window; |
| 171 | } |
| 172 | worst |
| 173 | } |
| 174 | |
| 175 | fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> { |
| 176 | let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { |
| 177 | bitrate_kbps: kbps, |
| 178 | vbr_quality: None, |
| 179 | }); |
| 180 | encoder |
| 181 | .push_pcm_f32(pcm, channels as u16, rate) |
| 182 | .expect("encoder accepts the fixture"); |
| 183 | encoder.finish(); |
| 184 | let mut out = Vec::new(); |
| 185 | while let Ok(frame) = encoder.next_packet() { |
| 186 | out.extend_from_slice(&frame); |
| 187 | } |
| 188 | out |
| 189 | } |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | #[test] |
| 197 | fn cbr_quality_holds_its_floor() { |
| 198 | let path = fixtures().join("audio/wav16-stereo-48000.wav"); |
| 199 | let Some((pcm, rate, channels)) = read_wav(&path) else { |
| 200 | eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); |
| 201 | return; |
| 202 | }; |
| 203 | let bytes = encode(&pcm, rate, channels, 192); |
| 204 | let file = workdir("cbr").join("cbr192.mp3"); |
| 205 | std::fs::write(&file, &bytes).unwrap(); |
| 206 | let decoded = decode(&file); |
| 207 | assert_eq!(decoded.len(), pcm.len()); |
| 208 | let corr = correlation(&decoded, &pcm); |
| 209 | let (err, sig) = decoded |
| 210 | .iter() |
| 211 | .zip(&pcm) |
| 212 | .fold((0.0f64, 0.0f64), |(e, s), (d, p)| { |
| 213 | (e + f64::from(d - p).powi(2), s + f64::from(*p).powi(2)) |
| 214 | }); |
| 215 | let rms = (err / sig).sqrt(); |
| 216 | println!("cbr192 corr={corr:.6} rms={:.4}%", rms * 100.0); |
| 217 | assert!(corr >= 0.999_99, "corr {corr:.6}"); |
| 218 | assert!(rms <= 0.000_25, "rms {:.4}%", rms * 100.0); |
| 219 | } |
| 220 | |
| 221 | fn decode(file: &Path) -> Vec<f32> { |
| 222 | let out = Command::new("ffmpeg") |
| 223 | .args(["-v", "warning", "-i"]) |
| 224 | .arg(file) |
| 225 | .args(["-f", "f32le", "-"]) |
| 226 | .output() |
| 227 | .expect("run ffmpeg"); |
| 228 | assert!( |
| 229 | out.stderr.is_empty(), |
| 230 | "ffmpeg: {}", |
| 231 | String::from_utf8_lossy(&out.stderr) |
| 232 | ); |
| 233 | out.stdout |
| 234 | .chunks_exact(4) |
| 235 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 236 | .collect() |
| 237 | } |
| 238 | |
| 239 | fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec<u8> { |
| 240 | let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { |
| 241 | bitrate_kbps: 0, |
| 242 | vbr_quality: Some(quality), |
| 243 | }); |
| 244 | encoder |
| 245 | .push_pcm_f32(pcm, channels as u16, rate) |
| 246 | .expect("encoder accepts the fixture"); |
| 247 | encoder.finish(); |
| 248 | let mut out = Vec::new(); |
| 249 | while let Ok(frame) = encoder.next_packet() { |
| 250 | out.extend_from_slice(&frame); |
| 251 | } |
| 252 | out |
| 253 | } |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | #[test] |
| 259 | fn vbr_frames_vary_their_bitrate_index() { |
| 260 | let name = "mp3src-stereo-48000"; |
| 261 | let path = fixtures().join(format!("audio/{name}.wav")); |
| 262 | let Some((pcm, rate, channels)) = read_wav(&path) else { |
| 263 | eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); |
| 264 | return; |
| 265 | }; |
| 266 | let bytes = encode_vbr(&pcm, rate, channels, 0.5); |
| 267 | |
| 268 | let table = [ |
| 269 | 0u32, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, |
| 270 | ]; |
| 271 | let mut indices = std::collections::BTreeSet::new(); |
| 272 | let (mut pos, mut frames) = (0usize, 0usize); |
| 273 | while pos + 4 <= bytes.len() { |
| 274 | let h = &bytes[pos..pos + 4]; |
| 275 | assert!(h[0] == 0xFF && (h[1] & 0xE0) == 0xE0, "sync lost at {pos}"); |
| 276 | let index = usize::from(h[2] >> 4); |
| 277 | let kbps = table[index.min(14)] as usize; |
| 278 | assert!(kbps > 0, "free-format header at {pos}"); |
| 279 | if frames > 0 { |
| 280 | indices.insert(index); |
| 281 | } |
| 282 | frames += 1; |
| 283 | pos += 144 * kbps * 1000 / rate as usize + usize::from((h[2] >> 1) & 1); |
| 284 | } |
| 285 | let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); |
| 286 | let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0; |
| 287 | let target = f64::from(ec_mp3::encode::bitrate_for_quality(0.5)); |
| 288 | println!("vbr frames={frames} indices={indices:?} mean={mean:.1} kbit/s"); |
| 289 | assert!(indices.len() >= 3, "only {indices:?}"); |
| 290 | assert!( |
| 291 | (mean - target).abs() <= target * 0.25, |
| 292 | "mean {mean:.1} vs {target}" |
| 293 | ); |
| 294 | |
| 295 | let work = workdir("vbr"); |
| 296 | let file = work.join("vbr.mp3"); |
| 297 | std::fs::write(&file, &bytes).unwrap(); |
| 298 | let out = Command::new("ffmpeg") |
| 299 | .args(["-v", "warning", "-i"]) |
| 300 | .arg(&file) |
| 301 | .args(["-f", "f32le", "-"]) |
| 302 | .output() |
| 303 | .expect("run ffmpeg"); |
| 304 | assert!( |
| 305 | out.stderr.is_empty(), |
| 306 | "ffmpeg: {}", |
| 307 | String::from_utf8_lossy(&out.stderr) |
| 308 | ); |
| 309 | let decoded: Vec<f32> = out |
| 310 | .stdout |
| 311 | .chunks_exact(4) |
| 312 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 313 | .collect(); |
| 314 | let corr = correlation(&decoded, &pcm); |
| 315 | let bar = bar_for(name, 192); |
| 316 | println!("vbr corr={corr:.5} bar={bar:.5}"); |
| 317 | assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}"); |
| 318 | let probe = Command::new("ffprobe") |
| 319 | .args(["-v", "error", "-show_format"]) |
| 320 | .arg(&file) |
| 321 | .output() |
| 322 | .expect("run ffprobe"); |
| 323 | let probe = String::from_utf8_lossy(&probe.stdout); |
| 324 | |
| 325 | assert!( |
| 326 | &bytes[36..40] == b"Xing" && bytes[36 + 16 + 9] == 0x70, |
| 327 | "no VBR-flagged Xing tag" |
| 328 | ); |
| 329 | assert!(probe.contains("format_name=mp3"), "{probe}"); |
| 330 | } |
| 331 | |
| 332 | #[test] |
| 333 | fn vbr_mean_bitrate_tracks_quality_on_music() { |
| 334 | let path = fixtures().join("audio/wav16-stereo-48000.wav"); |
| 335 | let Some((pcm, rate, channels)) = read_wav(&path) else { |
| 336 | eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); |
| 337 | return; |
| 338 | }; |
| 339 | let mut previous = 0.0; |
| 340 | for q in [0.25f32, 0.5, 0.75] { |
| 341 | let bytes = encode_vbr(&pcm, rate, channels, q); |
| 342 | let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); |
| 343 | let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0; |
| 344 | let target = f64::from(ec_mp3::encode::bitrate_for_quality(q)); |
| 345 | let tolerance = if q <= 0.5 { 0.70 } else { 0.25 }; |
| 346 | println!("q={q:.2} mean={mean:.1} target={target:.1}"); |
| 347 | assert!( |
| 348 | mean > previous, |
| 349 | "q={q:.2} mean {mean:.1} did not rise above {previous:.1}" |
| 350 | ); |
| 351 | assert!( |
| 352 | (mean - target).abs() <= target * tolerance, |
| 353 | "fixture is sparse/tonal, so q={q:.2} allows {:.0}%: mean {mean:.1} vs {target:.1}", |
| 354 | tolerance * 100.0, |
| 355 | ); |
| 356 | previous = mean; |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | #[test] |
| 361 | fn encodes_above_the_incumbent_bar() { |
| 362 | let dir = fixtures().join("audio"); |
| 363 | let mut sources: Vec<PathBuf> = std::fs::read_dir(&dir) |
| 364 | .into_iter() |
| 365 | .flatten() |
| 366 | .flatten() |
| 367 | .map(|e| e.path()) |
| 368 | .filter(|p| { |
| 369 | let name = p.file_name().map(|n| n.to_string_lossy().to_string()); |
| 370 | name.is_some_and(|n| n.starts_with("wav16-") || n.starts_with("mp3src-")) |
| 371 | && p.extension().is_some_and(|e| e == "wav") |
| 372 | }) |
| 373 | .collect(); |
| 374 | sources.sort(); |
| 375 | sources.retain(|p| { |
| 376 | let name = p.file_name().unwrap().to_string_lossy().to_string(); |
| 377 | name.contains("mono") || name.contains("stereo") |
| 378 | }); |
| 379 | if sources.is_empty() { |
| 380 | eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); |
| 381 | return; |
| 382 | } |
| 383 | let work = workdir("encode"); |
| 384 | println!( |
| 385 | "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}", |
| 386 | "fixture", "kbps", "rate", "ch", "corr", "bar", "kbit/s" |
| 387 | ); |
| 388 | let mut failures = Vec::new(); |
| 389 | for source in &sources { |
| 390 | let Some((pcm, rate, channels)) = read_wav(source) else { |
| 391 | continue; |
| 392 | }; |
| 393 | for kbps in BITRATES { |
| 394 | let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps); |
| 395 | let bytes = encode(&pcm, rate, channels, kbps); |
| 396 | let path = work.join(format!( |
| 397 | "{}-{kbps}.mp3", |
| 398 | source.file_stem().unwrap().to_string_lossy() |
| 399 | )); |
| 400 | std::fs::write(&path, &bytes).expect("write encoded file"); |
| 401 | let out = Command::new("ffmpeg") |
| 402 | .args(["-v", "warning", "-i"]) |
| 403 | .arg(&path) |
| 404 | .args(["-f", "f32le", "-"]) |
| 405 | .output() |
| 406 | .expect("run ffmpeg"); |
| 407 | let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); |
| 408 | if !stderr.is_empty() { |
| 409 | failures.push(format!("{}: ffmpeg said {stderr}", path.display())); |
| 410 | } |
| 411 | let decoded: Vec<f32> = out |
| 412 | .stdout |
| 413 | .chunks_exact(4) |
| 414 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 415 | .collect(); |
| 416 | |
| 417 | |
| 418 | |
| 419 | |
| 420 | if decoded.len() != pcm.len() { |
| 421 | failures.push(format!( |
| 422 | "{}: decoded {} samples, pushed {}", |
| 423 | source.file_name().unwrap().to_string_lossy(), |
| 424 | decoded.len(), |
| 425 | pcm.len() |
| 426 | )); |
| 427 | } |
| 428 | let corr = correlation(&decoded, &pcm); |
| 429 | |
| 430 | |
| 431 | |
| 432 | let (searched, offset) = aligned(&decoded, &pcm, channels); |
| 433 | if offset != 0 && searched > corr + 1e-4 { |
| 434 | failures.push(format!( |
| 435 | "{}: lag {offset} correlates {searched:.6}, better than lag zero {corr:.6}", |
| 436 | source.file_name().unwrap().to_string_lossy(), |
| 437 | )); |
| 438 | } |
| 439 | let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); |
| 440 | let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0; |
| 441 | let name = source.file_name().unwrap().to_string_lossy(); |
| 442 | println!( |
| 443 | "{name:<30} {kbps:>5} {rate:>6} {channels:>3} {corr:>9.5} {bar:>8.5} {measured:>9.1}" |
| 444 | ); |
| 445 | |
| 446 | |
| 447 | |
| 448 | if corr < bar - 1e-5 { |
| 449 | failures.push(format!("{name} at {kbps} kbit/s: {corr:.5} < bar {bar:.5}")); |
| 450 | } |
| 451 | if (measured - kbps as f64).abs() > kbps as f64 * 0.05 { |
| 452 | failures.push(format!( |
| 453 | "{name} at {kbps} kbit/s: wrote {measured:.1} kbit/s" |
| 454 | )); |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | assert!(failures.is_empty(), "{failures:#?}"); |
| 459 | } |
| 460 | |
| 461 | |
| 462 | |
| 463 | |
| 464 | |
| 465 | |
| 466 | |
| 467 | |
| 468 | |
| 469 | |
| 470 | |
| 471 | |
| 472 | const LIBRARY: [(&str, &str); 7] = [ |
| 473 | ("nik", "~/Music/reeln.mp4"), |
| 474 | ("reelo", "~/Music/reelo.mp3"), |
| 475 | ("her", "~/Music/reeli.mp3"), |
| 476 | ("reell", "~/Music/reell.mp4"), |
| 477 | ("reelm", "~/Music/reelm.wav"), |
| 478 | ("dl8a", "~/Downloads/8a3b6d1d19.mp3"), |
| 479 | ( |
| 480 | "hein", |
| 481 | "~/Downloads/reelm.mp3", |
| 482 | ), |
| 483 | ]; |
| 484 | |
| 485 | |
| 486 | |
| 487 | |
| 488 | |
| 489 | |
| 490 | |
| 491 | const WORST_WINDOW_EXCESS_DB: f64 = 1.0; |
| 492 | |
| 493 | |
| 494 | |
| 495 | |
| 496 | |
| 497 | |
| 498 | |
| 499 | const LAME_CORR_FLOOR: f64 = 0.0; |
| 500 | |
| 501 | fn expand(path: &str) -> PathBuf { |
| 502 | PathBuf::from(match path.strip_prefix("~/") { |
| 503 | Some(rest) => format!( |
| 504 | "{}/{rest}", |
| 505 | std::env::var("HOME").unwrap_or_else(|_| "/home".into()) |
| 506 | ), |
| 507 | None => path.to_string(), |
| 508 | }) |
| 509 | } |
| 510 | |
| 511 | |
| 512 | fn decode_source(path: &Path, seconds: u32) -> Option<Vec<f32>> { |
| 513 | let out = Command::new("ffmpeg") |
| 514 | .args(["-v", "error", "-i"]) |
| 515 | .arg(path) |
| 516 | .args([ |
| 517 | "-vn", |
| 518 | "-t", |
| 519 | &seconds.to_string(), |
| 520 | "-ac", |
| 521 | "2", |
| 522 | "-ar", |
| 523 | "44100", |
| 524 | "-f", |
| 525 | "f32le", |
| 526 | "-", |
| 527 | ]) |
| 528 | .output() |
| 529 | .ok()?; |
| 530 | if !out.status.success() || out.stdout.is_empty() { |
| 531 | return None; |
| 532 | } |
| 533 | Some( |
| 534 | out.stdout |
| 535 | .chunks_exact(4) |
| 536 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 537 | .collect(), |
| 538 | ) |
| 539 | } |
| 540 | |
| 541 | |
| 542 | |
| 543 | |
| 544 | |
| 545 | #[test] |
| 546 | #[ignore = "needs the user's library and ffmpeg's libmp3lame"] |
| 547 | fn real_library_sweep_vs_lame() { |
| 548 | let seconds = 60u32; |
| 549 | let work = workdir("lame-sweep"); |
| 550 | println!( |
| 551 | "{:<7} {:>5} {:>9} {:>9} {:>8} {:>8} {:>8} {:>8} {:>8}", |
| 552 | "source", |
| 553 | "kbps", |
| 554 | "corr_ours", |
| 555 | "corr_lame", |
| 556 | "gap", |
| 557 | "wworst_o", |
| 558 | "wworst_r", |
| 559 | "ours_kb", |
| 560 | "lame_kb" |
| 561 | ); |
| 562 | let mut rows = 0; |
| 563 | let mut failures = Vec::new(); |
| 564 | |
| 565 | |
| 566 | |
| 567 | let only = std::env::var("EC_MP3_SWEEP_ONLY").unwrap_or_default(); |
| 568 | for (name, src) in LIBRARY { |
| 569 | if !only.is_empty() && !only.split(',').any(|w| w.trim() == name) { |
| 570 | continue; |
| 571 | } |
| 572 | let src = expand(src); |
| 573 | if !src.exists() { |
| 574 | println!("{name:<7} SKIP (missing)"); |
| 575 | continue; |
| 576 | } |
| 577 | let Some(pcm) = decode_source(&src, seconds) else { |
| 578 | println!("{name:<7} SKIP (decode)"); |
| 579 | continue; |
| 580 | }; |
| 581 | let secs = pcm.len() as f64 / (44100.0 * 2.0); |
| 582 | for kbps in [128u32, 192] { |
| 583 | let ours_bytes = encode(&pcm, 44100, 2, kbps); |
| 584 | let ours_file = work.join(format!("ours-{name}-{kbps}.mp3")); |
| 585 | std::fs::write(&ours_file, &ours_bytes).expect("write ours"); |
| 586 | let lame_file = work.join(format!("lame-{name}-{kbps}.mp3")); |
| 587 | let status = Command::new("ffmpeg") |
| 588 | .args(["-y", "-v", "error", "-i"]) |
| 589 | .arg(&src) |
| 590 | .args([ |
| 591 | "-vn", |
| 592 | "-t", |
| 593 | &seconds.to_string(), |
| 594 | "-ac", |
| 595 | "2", |
| 596 | "-ar", |
| 597 | "44100", |
| 598 | "-c:a", |
| 599 | "libmp3lame", |
| 600 | "-b:a", |
| 601 | &format!("{kbps}k"), |
| 602 | ]) |
| 603 | .arg(&lame_file) |
| 604 | .status() |
| 605 | .expect("ffmpeg runs"); |
| 606 | assert!(status.success(), "libmp3lame encode of {name} at {kbps}k"); |
| 607 | |
| 608 | |
| 609 | let measure = |file: &Path| -> (f64, f64) { |
| 610 | let decoded = decode(file); |
| 611 | let (corr, offset) = aligned(&decoded, &pcm, 2); |
| 612 | (corr, worst_window_db(&decoded, &pcm, offset, 2)) |
| 613 | }; |
| 614 | let ((ours_corr, ours_worst), (lame_corr, lame_worst)) = |
| 615 | (measure(&ours_file), measure(&lame_file)); |
| 616 | let kb = |
| 617 | |p: &Path| std::fs::metadata(p).expect("size").len() as f64 * 8.0 / secs / 1000.0; |
| 618 | let gap = ours_corr - lame_corr; |
| 619 | println!( |
| 620 | "{name:<7} {kbps:>5} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} \ |
| 621 | {ours_worst:>+8.1} {lame_worst:>+8.1} {:>8.1} {:>8.1}", |
| 622 | kb(&ours_file), |
| 623 | kb(&lame_file) |
| 624 | ); |
| 625 | rows += 1; |
| 626 | if gap < LAME_CORR_FLOOR { |
| 627 | failures.push(format!( |
| 628 | "{name} at {kbps} kbit/s: {ours_corr:.5} against LAME's {lame_corr:.5}" |
| 629 | )); |
| 630 | } |
| 631 | if ours_worst - lame_worst > WORST_WINDOW_EXCESS_DB { |
| 632 | failures.push(format!( |
| 633 | "{name} at {kbps} kbit/s: worst window {ours_worst:.1} dB \ |
| 634 | against LAME's {lame_worst:.1} dB" |
| 635 | )); |
| 636 | } |
| 637 | } |
| 638 | } |
| 639 | assert!(rows > 0, "no library sources were readable"); |
| 640 | assert!(failures.is_empty(), "{failures:#?}"); |
| 641 | } |
| 642 | |
| 643 | |
| 644 | fn mode_exts(bytes: &[u8]) -> Vec<u8> { |
| 645 | let mut out = Vec::new(); |
| 646 | let mut at = 0; |
| 647 | while at + 4 <= bytes.len() { |
| 648 | let Ok(header) = FrameHeader::parse(&bytes[at..]) else { |
| 649 | at += 1; |
| 650 | continue; |
| 651 | }; |
| 652 | let Some(len) = header.frame_len() else { break }; |
| 653 | out.push(header.mode_ext); |
| 654 | at += len; |
| 655 | } |
| 656 | out |
| 657 | } |
| 658 | |
| 659 | |
| 660 | |
| 661 | |
| 662 | |
| 663 | |
| 664 | |
| 665 | |
| 666 | #[test] |
| 667 | fn mid_side_follows_the_channel_correlation() { |
| 668 | let mut seed = 0x2545_f491_4f6c_dd1du64; |
| 669 | let mut noise = || { |
| 670 | seed ^= seed << 13; |
| 671 | seed ^= seed >> 7; |
| 672 | seed ^= seed << 17; |
| 673 | (seed >> 40) as f32 / 8388608.0 - 0.5 |
| 674 | }; |
| 675 | let n = 44100; |
| 676 | let (mut same, mut opposed) = (Vec::with_capacity(n * 2), Vec::with_capacity(n * 2)); |
| 677 | for i in 0..n { |
| 678 | |
| 679 | let tone = (i as f32 * 0.03).sin() * 0.4; |
| 680 | let v = tone + noise() * 0.05; |
| 681 | same.push(v); |
| 682 | same.push(v); |
| 683 | opposed.push(v); |
| 684 | opposed.push(-v); |
| 685 | } |
| 686 | for (label, pcm, want_ms) in [("same", same, true), ("opposed", opposed, false)] { |
| 687 | let bytes = encode(&pcm, 44100, 2, 128); |
| 688 | let exts = mode_exts(&bytes); |
| 689 | assert!(exts.len() > 20, "{label}: only {} frames", exts.len()); |
| 690 | let ms = exts.iter().filter(|e| *e & 2 != 0).count(); |
| 691 | |
| 692 | let body = exts.len() - 2; |
| 693 | if want_ms { |
| 694 | assert!( |
| 695 | ms >= body, |
| 696 | "{label}: only {ms} of {} frames are mid/side", |
| 697 | exts.len() |
| 698 | ); |
| 699 | } else { |
| 700 | assert_eq!(ms, 0, "{label}: {ms} frames chose mid/side"); |
| 701 | } |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | |
| 706 | |
| 707 | |
| 708 | |
| 709 | const LAME_V_LEVELS: [u32; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; |
| 710 | |
| 711 | |
| 712 | |
| 713 | |
| 714 | |
| 715 | const VBR_CORR_FLOOR: f64 = -0.0005; |
| 716 | |
| 717 | |
| 718 | |
| 719 | |
| 720 | const VBR_WORST_EXCESS_DB: f64 = 3.5; |
| 721 | |
| 722 | |
| 723 | |
| 724 | |
| 725 | const VBR_RATE_CEILING: f64 = 8.0; |
| 726 | |
| 727 | |
| 728 | |
| 729 | |
| 730 | |
| 731 | |
| 732 | |
| 733 | |
| 734 | #[test] |
| 735 | #[ignore = "needs the user's library and ffmpeg's libmp3lame"] |
| 736 | fn real_library_vbr_vs_lame() { |
| 737 | let seconds = 60u32; |
| 738 | let work = workdir("lame-vbr"); |
| 739 | println!( |
| 740 | "{:<7} {:>4} {:>9} {:>9} {:>8} {:>8} {:>8} {:>8} {:>8} {:>4}", |
| 741 | "source", |
| 742 | "q", |
| 743 | "corr_ours", |
| 744 | "corr_lame", |
| 745 | "gap", |
| 746 | "wworst_o", |
| 747 | "wworst_r", |
| 748 | "ours_kb", |
| 749 | "lame_kb", |
| 750 | "V" |
| 751 | ); |
| 752 | let only = std::env::var("EC_MP3_SWEEP_ONLY").unwrap_or_default(); |
| 753 | let mut rows = 0; |
| 754 | let mut failures = Vec::new(); |
| 755 | for (name, src) in LIBRARY { |
| 756 | if !only.is_empty() && !only.split(',').any(|w| w.trim() == name) { |
| 757 | continue; |
| 758 | } |
| 759 | let src = expand(src); |
| 760 | if !src.exists() { |
| 761 | println!("{name:<7} SKIP (missing)"); |
| 762 | continue; |
| 763 | } |
| 764 | let Some(pcm) = decode_source(&src, seconds) else { |
| 765 | println!("{name:<7} SKIP (decode)"); |
| 766 | continue; |
| 767 | }; |
| 768 | let secs = pcm.len() as f64 / (44100.0 * 2.0); |
| 769 | let kb = |p: &Path| std::fs::metadata(p).expect("size").len() as f64 * 8.0 / secs / 1000.0; |
| 770 | |
| 771 | let lame_ladder: Vec<(u32, PathBuf, f64)> = LAME_V_LEVELS |
| 772 | .iter() |
| 773 | .map(|&level| { |
| 774 | let file = work.join(format!("lame-{name}-v{level}.mp3")); |
| 775 | let status = Command::new("ffmpeg") |
| 776 | .args(["-y", "-v", "error", "-i"]) |
| 777 | .arg(&src) |
| 778 | .args([ |
| 779 | "-vn", |
| 780 | "-t", |
| 781 | &seconds.to_string(), |
| 782 | "-ac", |
| 783 | "2", |
| 784 | "-ar", |
| 785 | "44100", |
| 786 | "-c:a", |
| 787 | "libmp3lame", |
| 788 | "-q:a", |
| 789 | &level.to_string(), |
| 790 | ]) |
| 791 | .arg(&file) |
| 792 | .status() |
| 793 | .expect("ffmpeg runs"); |
| 794 | assert!(status.success(), "libmp3lame V{level} of {name}"); |
| 795 | let rate = kb(&file); |
| 796 | (level, file, rate) |
| 797 | }) |
| 798 | .collect(); |
| 799 | for quality in [0.3f32, 0.6] { |
| 800 | let ours_bytes = encode_vbr(&pcm, 44100, 2, quality); |
| 801 | let ours_file = work.join(format!("ours-{name}-{quality}.mp3")); |
| 802 | std::fs::write(&ours_file, &ours_bytes).expect("write ours"); |
| 803 | let ours_kb = kb(&ours_file); |
| 804 | |
| 805 | let (level, lame_file) = lame_ladder |
| 806 | .iter() |
| 807 | .min_by(|a, b| { |
| 808 | (a.2 - ours_kb) |
| 809 | .abs() |
| 810 | .partial_cmp(&(b.2 - ours_kb).abs()) |
| 811 | .expect("finite") |
| 812 | }) |
| 813 | .map(|(v, f, _)| (*v, f.clone())) |
| 814 | .expect("a ladder rung"); |
| 815 | let measure = |file: &Path| -> (f64, f64) { |
| 816 | let decoded = decode(file); |
| 817 | let (corr, offset) = aligned(&decoded, &pcm, 2); |
| 818 | (corr, worst_window_db(&decoded, &pcm, offset, 2)) |
| 819 | }; |
| 820 | let ((ours_corr, ours_worst), (lame_corr, lame_worst)) = |
| 821 | (measure(&ours_file), measure(&lame_file)); |
| 822 | let lame_kb = kb(&lame_file); |
| 823 | let gap = ours_corr - lame_corr; |
| 824 | let premium = (ours_kb / lame_kb - 1.0) * 100.0; |
| 825 | println!( |
| 826 | "{name:<7} {quality:>4} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} \ |
| 827 | {ours_worst:>+8.1} {lame_worst:>+8.1} {ours_kb:>8.1} {lame_kb:>8.1} {level:>4}" |
| 828 | ); |
| 829 | rows += 1; |
| 830 | |
| 831 | |
| 832 | if gap < VBR_CORR_FLOOR && ours_kb >= lame_kb * 0.98 { |
| 833 | failures.push(format!( |
| 834 | "{name} at q{quality}: {ours_corr:.5} against LAME's {lame_corr:.5} \ |
| 835 | at {ours_kb:.1} against {lame_kb:.1} kbit/s" |
| 836 | )); |
| 837 | } |
| 838 | if ours_worst - lame_worst > VBR_WORST_EXCESS_DB { |
| 839 | failures.push(format!( |
| 840 | "{name} at q{quality}: worst window {ours_worst:.1} dB \ |
| 841 | against LAME's {lame_worst:.1} dB" |
| 842 | )); |
| 843 | } |
| 844 | if level > 0 && premium > VBR_RATE_CEILING { |
| 845 | failures.push(format!( |
| 846 | "{name} at q{quality}: {premium:+.1}% of LAME's rate (V{level})" |
| 847 | )); |
| 848 | } |
| 849 | } |
| 850 | } |
| 851 | assert!(rows > 0, "no library sources were readable"); |
| 852 | assert!(failures.is_empty(), "{failures:#?}"); |
| 853 | } |