| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | use std::path::{Path, PathBuf}; |
| 12 | |
| 13 | use ec_mp3::{FrameHeader, Mp3Encoder, Mp3EncoderConfig}; |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | const BAR: [(&str, [f64; 3]); 4] = [ |
| 21 | ("mp3src-mono-44100", [0.99920, 0.99983, 0.99999]), |
| 22 | ("mp3src-stereo-44100", [0.99612, 0.99847, 0.99972]), |
| 23 | ("mp3src-mono-48000", [0.99867, 0.99972, 0.99998]), |
| 24 | ("mp3src-stereo-48000", [0.99461, 0.99787, 0.99956]), |
| 25 | ]; |
| 26 | const BITRATES: [u32; 3] = [128, 192, 320]; |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | fn bar_for(name: &str, kbps: u32) -> f64 { |
| 32 | let index = BITRATES.iter().position(|k| *k == kbps).unwrap_or(0); |
| 33 | for (fixture, values) in BAR { |
| 34 | if name.starts_with(fixture) { |
| 35 | return values[index]; |
| 36 | } |
| 37 | } |
| 38 | BAR.iter() |
| 39 | .map(|(_, v)| v[index]) |
| 40 | .fold(f64::INFINITY, f64::min) |
| 41 | } |
| 42 | |
| 43 | fn workdir(test: &str) -> PathBuf { |
| 44 | let dir = std::env::temp_dir().join(format!("ec-mp3-{}-{test}", std::process::id())); |
| 45 | std::fs::create_dir_all(&dir).expect("create work dir"); |
| 46 | dir |
| 47 | } |
| 48 | |
| 49 | |
| 50 | fn read_wav(path: &Path) -> (Vec<f32>, u32, usize) { |
| 51 | let out = ec_testkit::ffmpeg() |
| 52 | .args(["-v", "error", "-i"]) |
| 53 | .arg(path) |
| 54 | .args(["-f", "f32le", "-"]) |
| 55 | .output() |
| 56 | .expect("run ffmpeg"); |
| 57 | assert!( |
| 58 | out.status.success(), |
| 59 | "ffmpeg could not read {}", |
| 60 | path.display() |
| 61 | ); |
| 62 | let samples = out |
| 63 | .stdout |
| 64 | .as_chunks::<4>() |
| 65 | .0 |
| 66 | .iter() |
| 67 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 68 | .collect(); |
| 69 | let probe = ec_testkit::ffprobe() |
| 70 | .args([ |
| 71 | "-v", |
| 72 | "error", |
| 73 | "-select_streams", |
| 74 | "a:0", |
| 75 | "-show_entries", |
| 76 | "stream=channels,sample_rate", |
| 77 | "-of", |
| 78 | "default=noprint_wrappers=1", |
| 79 | ]) |
| 80 | .arg(path) |
| 81 | .output() |
| 82 | .expect("run ffprobe"); |
| 83 | let text = String::from_utf8_lossy(&probe.stdout); |
| 84 | let field = |key: &str| { |
| 85 | text.lines() |
| 86 | .find_map(|l| l.strip_prefix(key)?.strip_prefix('=')) |
| 87 | .and_then(|v| v.trim().parse::<u32>().ok()) |
| 88 | }; |
| 89 | ( |
| 90 | samples, |
| 91 | field("sample_rate").expect("sample rate"), |
| 92 | field("channels").expect("channels") as usize, |
| 93 | ) |
| 94 | } |
| 95 | |
| 96 | fn correlation(a: &[f32], b: &[f32]) -> f64 { |
| 97 | let n = a.len().min(b.len()); |
| 98 | let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64); |
| 99 | for i in 0..n { |
| 100 | let (x, y) = (a[i] as f64, b[i] as f64); |
| 101 | ab += x * y; |
| 102 | aa += x * x; |
| 103 | bb += y * y; |
| 104 | } |
| 105 | if aa == 0.0 || bb == 0.0 { |
| 106 | return 0.0; |
| 107 | } |
| 108 | ab / (aa * bb).sqrt() |
| 109 | } |
| 110 | |
| 111 | |
| 112 | fn aligned(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) { |
| 113 | let mut best = (f64::MIN, 0usize); |
| 114 | let mut offset = 0; |
| 115 | while offset + channels < got.len() && offset <= 3000 * channels { |
| 116 | let n = (got.len() - offset).min(want.len()); |
| 117 | let skip = 1152 * channels; |
| 118 | if n <= 2 * skip { |
| 119 | break; |
| 120 | } |
| 121 | let corr = correlation( |
| 122 | &got[offset + skip..offset + n - skip], |
| 123 | &want[skip..n - skip], |
| 124 | ); |
| 125 | if corr > best.0 { |
| 126 | best = (corr, offset); |
| 127 | } |
| 128 | offset += channels; |
| 129 | } |
| 130 | best |
| 131 | } |
| 132 | |
| 133 | fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> { |
| 134 | let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { |
| 135 | bitrate_kbps: kbps, |
| 136 | vbr_quality: None, |
| 137 | }); |
| 138 | encoder |
| 139 | .push_pcm_f32(pcm, channels as u16, rate) |
| 140 | .expect("encoder accepts the fixture"); |
| 141 | encoder.finish(); |
| 142 | let mut out = Vec::new(); |
| 143 | while let Ok(frame) = encoder.next_packet() { |
| 144 | out.extend_from_slice(&frame); |
| 145 | } |
| 146 | out |
| 147 | } |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | #[test] |
| 155 | fn cbr_quality_holds_its_floor() { |
| 156 | let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); |
| 157 | let (pcm, rate, channels) = read_wav(&path); |
| 158 | let bytes = encode(&pcm, rate, channels, 192); |
| 159 | let file = workdir("cbr").join("cbr192.mp3"); |
| 160 | std::fs::write(&file, &bytes).unwrap(); |
| 161 | let decoded = decode(&file); |
| 162 | assert_eq!(decoded.len(), pcm.len()); |
| 163 | let corr = correlation(&decoded, &pcm); |
| 164 | let (err, sig) = decoded |
| 165 | .iter() |
| 166 | .zip(&pcm) |
| 167 | .fold((0.0f64, 0.0f64), |(e, s), (d, p)| { |
| 168 | (e + f64::from(d - p).powi(2), s + f64::from(*p).powi(2)) |
| 169 | }); |
| 170 | let rms = (err / sig).sqrt(); |
| 171 | println!("cbr192 corr={corr:.6} rms={:.4}%", rms * 100.0); |
| 172 | assert!(corr >= 0.999_99, "corr {corr:.6}"); |
| 173 | assert!(rms <= 0.000_25, "rms {:.4}%", rms * 100.0); |
| 174 | } |
| 175 | |
| 176 | fn decode(file: &Path) -> Vec<f32> { |
| 177 | let out = ec_testkit::ffmpeg() |
| 178 | .args(["-v", "warning", "-i"]) |
| 179 | .arg(file) |
| 180 | .args(["-f", "f32le", "-"]) |
| 181 | .output() |
| 182 | .expect("run ffmpeg"); |
| 183 | assert!( |
| 184 | out.stderr.is_empty(), |
| 185 | "ffmpeg: {}", |
| 186 | String::from_utf8_lossy(&out.stderr) |
| 187 | ); |
| 188 | out.stdout |
| 189 | .as_chunks::<4>() |
| 190 | .0 |
| 191 | .iter() |
| 192 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 193 | .collect() |
| 194 | } |
| 195 | |
| 196 | fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec<u8> { |
| 197 | let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { |
| 198 | bitrate_kbps: 0, |
| 199 | vbr_quality: Some(quality), |
| 200 | }); |
| 201 | encoder |
| 202 | .push_pcm_f32(pcm, channels as u16, rate) |
| 203 | .expect("encoder accepts the fixture"); |
| 204 | encoder.finish(); |
| 205 | let mut out = Vec::new(); |
| 206 | while let Ok(frame) = encoder.next_packet() { |
| 207 | out.extend_from_slice(&frame); |
| 208 | } |
| 209 | out |
| 210 | } |
| 211 | |
| 212 | |
| 213 | |
| 214 | |
| 215 | #[test] |
| 216 | fn vbr_frames_vary_their_bitrate_index() { |
| 217 | let name = "mp3src-stereo-48000"; |
| 218 | let path = ec_testkit::fixture(&format!("audio/{name}.wav")); |
| 219 | let (pcm, rate, channels) = read_wav(&path); |
| 220 | let bytes = encode_vbr(&pcm, rate, channels, 0.5); |
| 221 | |
| 222 | let table = [ |
| 223 | 0u32, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, |
| 224 | ]; |
| 225 | let mut indices = std::collections::BTreeSet::new(); |
| 226 | let (mut pos, mut frames) = (0usize, 0usize); |
| 227 | while pos + 4 <= bytes.len() { |
| 228 | let h = &bytes[pos..pos + 4]; |
| 229 | assert!(h[0] == 0xFF && (h[1] & 0xE0) == 0xE0, "sync lost at {pos}"); |
| 230 | let index = usize::from(h[2] >> 4); |
| 231 | let kbps = table[index.min(14)] as usize; |
| 232 | assert!(kbps > 0, "free-format header at {pos}"); |
| 233 | if frames > 0 { |
| 234 | indices.insert(index); |
| 235 | } |
| 236 | frames += 1; |
| 237 | pos += 144 * kbps * 1000 / rate as usize + usize::from((h[2] >> 1) & 1); |
| 238 | } |
| 239 | let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); |
| 240 | let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0; |
| 241 | let target = f64::from(ec_mp3::encode::bitrate_for_quality(0.5)); |
| 242 | println!("vbr frames={frames} indices={indices:?} mean={mean:.1} kbit/s"); |
| 243 | assert!(indices.len() >= 3, "only {indices:?}"); |
| 244 | assert!( |
| 245 | (mean - target).abs() <= target * 0.25, |
| 246 | "mean {mean:.1} vs {target}" |
| 247 | ); |
| 248 | |
| 249 | let work = workdir("vbr"); |
| 250 | let file = work.join("vbr.mp3"); |
| 251 | std::fs::write(&file, &bytes).unwrap(); |
| 252 | let out = ec_testkit::ffmpeg() |
| 253 | .args(["-v", "warning", "-i"]) |
| 254 | .arg(&file) |
| 255 | .args(["-f", "f32le", "-"]) |
| 256 | .output() |
| 257 | .expect("run ffmpeg"); |
| 258 | assert!( |
| 259 | out.stderr.is_empty(), |
| 260 | "ffmpeg: {}", |
| 261 | String::from_utf8_lossy(&out.stderr) |
| 262 | ); |
| 263 | let decoded: Vec<f32> = out |
| 264 | .stdout |
| 265 | .as_chunks::<4>() |
| 266 | .0 |
| 267 | .iter() |
| 268 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 269 | .collect(); |
| 270 | let corr = correlation(&decoded, &pcm); |
| 271 | let bar = bar_for(name, 192); |
| 272 | println!("vbr corr={corr:.5} bar={bar:.5}"); |
| 273 | assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}"); |
| 274 | let probe = ec_testkit::ffprobe() |
| 275 | .args(["-v", "error", "-show_format"]) |
| 276 | .arg(&file) |
| 277 | .output() |
| 278 | .expect("run ffprobe"); |
| 279 | let probe = String::from_utf8_lossy(&probe.stdout); |
| 280 | |
| 281 | assert!( |
| 282 | &bytes[36..40] == b"Xing" && bytes[36 + 16 + 9] == 0x70, |
| 283 | "no VBR-flagged Xing tag" |
| 284 | ); |
| 285 | assert!(probe.contains("format_name=mp3"), "{probe}"); |
| 286 | } |
| 287 | |
| 288 | #[test] |
| 289 | fn vbr_mean_bitrate_tracks_quality_on_music() { |
| 290 | let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); |
| 291 | let (pcm, rate, channels) = read_wav(&path); |
| 292 | let mut previous = 0.0; |
| 293 | for q in [0.25f32, 0.5, 0.75] { |
| 294 | let bytes = encode_vbr(&pcm, rate, channels, q); |
| 295 | let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); |
| 296 | let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0; |
| 297 | let target = f64::from(ec_mp3::encode::bitrate_for_quality(q)); |
| 298 | let tolerance = if q <= 0.5 { 0.70 } else { 0.25 }; |
| 299 | println!("q={q:.2} mean={mean:.1} target={target:.1}"); |
| 300 | assert!( |
| 301 | mean > previous, |
| 302 | "q={q:.2} mean {mean:.1} did not rise above {previous:.1}" |
| 303 | ); |
| 304 | assert!( |
| 305 | (mean - target).abs() <= target * tolerance, |
| 306 | "fixture is sparse/tonal, so q={q:.2} allows {:.0}%: mean {mean:.1} vs {target:.1}", |
| 307 | tolerance * 100.0, |
| 308 | ); |
| 309 | previous = mean; |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | #[test] |
| 314 | fn encodes_above_the_incumbent_bar() { |
| 315 | let sources: Vec<PathBuf> = ec_testkit::fixtures("audio", "wav") |
| 316 | .into_iter() |
| 317 | .filter(|p| { |
| 318 | let name = p.file_name().unwrap().to_string_lossy().to_string(); |
| 319 | (name.starts_with("wav16-") || name.starts_with("mp3src-")) |
| 320 | && (name.contains("mono") || name.contains("stereo")) |
| 321 | }) |
| 322 | .collect(); |
| 323 | |
| 324 | |
| 325 | |
| 326 | assert!( |
| 327 | sources.len() >= 8, |
| 328 | "only {} of the 8 mp3 encoder-matrix WAV fixtures are present", |
| 329 | sources.len() |
| 330 | ); |
| 331 | let work = workdir("encode"); |
| 332 | println!( |
| 333 | "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}", |
| 334 | "fixture", "kbps", "rate", "ch", "corr", "bar", "kbit/s" |
| 335 | ); |
| 336 | let mut failures = Vec::new(); |
| 337 | for source in &sources { |
| 338 | let (pcm, rate, channels) = read_wav(source); |
| 339 | for kbps in BITRATES { |
| 340 | let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps); |
| 341 | let bytes = encode(&pcm, rate, channels, kbps); |
| 342 | let path = work.join(format!( |
| 343 | "{}-{kbps}.mp3", |
| 344 | source.file_stem().unwrap().to_string_lossy() |
| 345 | )); |
| 346 | std::fs::write(&path, &bytes).expect("write encoded file"); |
| 347 | let out = ec_testkit::ffmpeg() |
| 348 | .args(["-v", "warning", "-i"]) |
| 349 | .arg(&path) |
| 350 | .args(["-f", "f32le", "-"]) |
| 351 | .output() |
| 352 | .expect("run ffmpeg"); |
| 353 | let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); |
| 354 | if !stderr.is_empty() { |
| 355 | failures.push(format!("{}: ffmpeg said {stderr}", path.display())); |
| 356 | } |
| 357 | let decoded: Vec<f32> = out |
| 358 | .stdout |
| 359 | .as_chunks::<4>() |
| 360 | .0 |
| 361 | .iter() |
| 362 | .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) |
| 363 | .collect(); |
| 364 | |
| 365 | |
| 366 | |
| 367 | |
| 368 | if decoded.len() != pcm.len() { |
| 369 | failures.push(format!( |
| 370 | "{}: decoded {} samples, pushed {}", |
| 371 | source.file_name().unwrap().to_string_lossy(), |
| 372 | decoded.len(), |
| 373 | pcm.len() |
| 374 | )); |
| 375 | } |
| 376 | let corr = correlation(&decoded, &pcm); |
| 377 | |
| 378 | |
| 379 | |
| 380 | let (searched, offset) = aligned(&decoded, &pcm, channels); |
| 381 | if offset != 0 && searched > corr + 1e-4 { |
| 382 | failures.push(format!( |
| 383 | "{}: lag {offset} correlates {searched:.6}, better than lag zero {corr:.6}", |
| 384 | source.file_name().unwrap().to_string_lossy(), |
| 385 | )); |
| 386 | } |
| 387 | let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); |
| 388 | let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0; |
| 389 | let name = source.file_name().unwrap().to_string_lossy(); |
| 390 | println!( |
| 391 | "{name:<30} {kbps:>5} {rate:>6} {channels:>3} {corr:>9.5} {bar:>8.5} {measured:>9.1}" |
| 392 | ); |
| 393 | |
| 394 | |
| 395 | |
| 396 | if corr < bar - 1e-5 { |
| 397 | failures.push(format!("{name} at {kbps} kbit/s: {corr:.5} < bar {bar:.5}")); |
| 398 | } |
| 399 | if (measured - kbps as f64).abs() > kbps as f64 * 0.05 { |
| 400 | failures.push(format!( |
| 401 | "{name} at {kbps} kbit/s: wrote {measured:.1} kbit/s" |
| 402 | )); |
| 403 | } |
| 404 | } |
| 405 | } |
| 406 | assert!(failures.is_empty(), "{failures:#?}"); |
| 407 | } |
| 408 | |
| 409 | fn mode_exts(bytes: &[u8]) -> Vec<u8> { |
| 410 | let mut out = Vec::new(); |
| 411 | let mut at = 0; |
| 412 | while at + 4 <= bytes.len() { |
| 413 | let Ok(header) = FrameHeader::parse(&bytes[at..]) else { |
| 414 | at += 1; |
| 415 | continue; |
| 416 | }; |
| 417 | let Some(len) = header.frame_len() else { break }; |
| 418 | out.push(header.mode_ext); |
| 419 | at += len; |
| 420 | } |
| 421 | out |
| 422 | } |
| 423 | |
| 424 | |
| 425 | |
| 426 | |
| 427 | |
| 428 | |
| 429 | |
| 430 | |
| 431 | #[test] |
| 432 | fn mid_side_follows_the_channel_correlation() { |
| 433 | let mut seed = 0x2545_f491_4f6c_dd1du64; |
| 434 | let mut noise = || { |
| 435 | seed ^= seed << 13; |
| 436 | seed ^= seed >> 7; |
| 437 | seed ^= seed << 17; |
| 438 | (seed >> 40) as f32 / 8388608.0 - 0.5 |
| 439 | }; |
| 440 | let n = 44100; |
| 441 | let (mut same, mut opposed) = (Vec::with_capacity(n * 2), Vec::with_capacity(n * 2)); |
| 442 | for i in 0..n { |
| 443 | |
| 444 | let tone = (i as f32 * 0.03).sin() * 0.4; |
| 445 | let v = tone + noise() * 0.05; |
| 446 | same.push(v); |
| 447 | same.push(v); |
| 448 | opposed.push(v); |
| 449 | opposed.push(-v); |
| 450 | } |
| 451 | for (label, pcm, want_ms) in [("same", same, true), ("opposed", opposed, false)] { |
| 452 | let bytes = encode(&pcm, 44100, 2, 128); |
| 453 | let exts = mode_exts(&bytes); |
| 454 | assert!(exts.len() > 20, "{label}: only {} frames", exts.len()); |
| 455 | let ms = exts.iter().filter(|e| *e & 2 != 0).count(); |
| 456 | |
| 457 | let body = exts.len() - 2; |
| 458 | if want_ms { |
| 459 | assert!( |
| 460 | ms >= body, |
| 461 | "{label}: only {ms} of {} frames are mid/side", |
| 462 | exts.len() |
| 463 | ); |
| 464 | } else { |
| 465 | assert_eq!(ms, 0, "{label}: {ms} frames chose mid/side"); |
| 466 | } |
| 467 | } |
| 468 | } |