| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | use std::path::Path; |
| 17 | use std::process::Command; |
| 18 | |
| 19 | use engine::audio::AudioSession; |
| 20 | use engine::scratch::Scratch; |
| 21 | |
| 22 | fn have_ffmpeg() -> bool { |
| 23 | Command::new("ffmpeg") |
| 24 | .arg("-version") |
| 25 | .output() |
| 26 | .is_ok_and(|o| o.status.success()) |
| 27 | } |
| 28 | |
| 29 | |
| 30 | fn ffmpeg_has(kind: &str, name: &str) -> bool { |
| 31 | Command::new("ffmpeg") |
| 32 | .args(["-hide_banner", kind]) |
| 33 | .output() |
| 34 | .is_ok_and(|o| { |
| 35 | String::from_utf8_lossy(&o.stdout) |
| 36 | .lines() |
| 37 | .any(|l| l.split_whitespace().nth(1) == Some(name)) |
| 38 | }) |
| 39 | } |
| 40 | |
| 41 | |
| 42 | struct Case { |
| 43 | name: &'static str, |
| 44 | |
| 45 | ext: &'static str, |
| 46 | codec: &'static str, |
| 47 | |
| 48 | encoder: &'static str, |
| 49 | |
| 50 | extra: &'static [&'static str], |
| 51 | rate: u32, |
| 52 | |
| 53 | channels: usize, |
| 54 | |
| 55 | video: Option<&'static str>, |
| 56 | |
| 57 | decoder: Option<&'static str>, |
| 58 | } |
| 59 | |
| 60 | impl Case { |
| 61 | const fn new( |
| 62 | name: &'static str, |
| 63 | ext: &'static str, |
| 64 | codec: &'static str, |
| 65 | rate: u32, |
| 66 | channels: usize, |
| 67 | ) -> Self { |
| 68 | Self { |
| 69 | name, |
| 70 | ext, |
| 71 | codec, |
| 72 | encoder: codec, |
| 73 | extra: &[], |
| 74 | rate, |
| 75 | channels, |
| 76 | video: None, |
| 77 | decoder: None, |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | const fn extra(mut self, extra: &'static [&'static str]) -> Self { |
| 82 | self.extra = extra; |
| 83 | self |
| 84 | } |
| 85 | |
| 86 | const fn video(mut self, codec: &'static str) -> Self { |
| 87 | self.video = Some(codec); |
| 88 | self |
| 89 | } |
| 90 | |
| 91 | const fn decoder(mut self, decoder: &'static str) -> Self { |
| 92 | self.decoder = Some(decoder); |
| 93 | self |
| 94 | } |
| 95 | |
| 96 | const fn encoder(mut self, encoder: &'static str) -> Self { |
| 97 | self.encoder = encoder; |
| 98 | self |
| 99 | } |
| 100 | |
| 101 | |
| 102 | fn make(&self) -> Option<Scratch> { |
| 103 | if !have_ffmpeg() { |
| 104 | eprintln!("skipped {}: no ffmpeg to encode the fixture with", self.name); |
| 105 | return None; |
| 106 | } |
| 107 | if !ffmpeg_has("-encoders", self.encoder) { |
| 108 | eprintln!( |
| 109 | "skipped {}: this ffmpeg has no `{}` encoder to make the fixture with", |
| 110 | self.name, self.encoder |
| 111 | ); |
| 112 | return None; |
| 113 | } |
| 114 | if let Some(decoder) = self.decoder |
| 115 | && !ffmpeg_has("-decoders", decoder) |
| 116 | { |
| 117 | eprintln!( |
| 118 | "skipped {}: this ffmpeg has no `{decoder}` decoder to make the reference with", |
| 119 | self.name |
| 120 | ); |
| 121 | return None; |
| 122 | } |
| 123 | |
| 124 | let tones = [440.0, 660.0, 880.0, 110.0, 550.0, 330.0]; |
| 125 | let expr = (0..self.channels) |
| 126 | .map(|c| { |
| 127 | format!( |
| 128 | "{:.2}*sin(2*PI*{}*t)+0.15*sin(2*PI*{}*t)", |
| 129 | 0.35 - 0.02 * c as f64, |
| 130 | tones[c % tones.len()], |
| 131 | tones[(c + 2) % tones.len()] * 3.0 |
| 132 | ) |
| 133 | }) |
| 134 | .collect::<Vec<_>>() |
| 135 | .join("|"); |
| 136 | let file = Scratch::file(self.name, self.ext); |
| 137 | let mut cmd = Command::new("ffmpeg"); |
| 138 | cmd.args(["-v", "error", "-y"]) |
| 139 | .args(["-f", "lavfi", "-i"]) |
| 140 | .arg(format!("aevalsrc={expr}:s={}:d=2", self.rate)); |
| 141 | if let Some(video) = self.video { |
| 142 | cmd.args(["-f", "lavfi", "-i", "color=c=gray:s=64x64:r=10:d=2"]) |
| 143 | .args(["-c:v", video, "-pix_fmt", "yuv420p"]); |
| 144 | } |
| 145 | let out = cmd |
| 146 | .args(["-c:a", self.codec]) |
| 147 | .args(self.extra) |
| 148 | .arg(&*file) |
| 149 | .output() |
| 150 | .expect("ffmpeg runs"); |
| 151 | assert!( |
| 152 | out.status.success(), |
| 153 | "ffmpeg ({}): {}", |
| 154 | self.name, |
| 155 | String::from_utf8_lossy(&out.stderr) |
| 156 | ); |
| 157 | Some(file) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | |
| 162 | fn ffmpeg_f32(path: &Path, decoder: Option<&str>, channels: Option<&str>) -> Vec<f32> { |
| 163 | let mut cmd = Command::new("ffmpeg"); |
| 164 | cmd.args(["-v", "error"]); |
| 165 | if let Some(decoder) = decoder { |
| 166 | cmd.args(["-c:a", decoder]); |
| 167 | } |
| 168 | cmd.arg("-i").arg(path).args(["-map", "0:a:0"]); |
| 169 | if let Some(channels) = channels { |
| 170 | cmd.args(["-ac", channels]); |
| 171 | } |
| 172 | let out = cmd.args(["-f", "f32le", "-"]).output().expect("ffmpeg runs"); |
| 173 | assert!( |
| 174 | out.status.success(), |
| 175 | "ffmpeg decode: {}", |
| 176 | String::from_utf8_lossy(&out.stderr) |
| 177 | ); |
| 178 | out.stdout |
| 179 | .as_chunks::<4>() |
| 180 | .0 |
| 181 | .iter() |
| 182 | .map(|b| f32::from_le_bytes(*b)) |
| 183 | .collect() |
| 184 | } |
| 185 | |
| 186 | |
| 187 | |
| 188 | fn decode_at(path: &Path, rate: u32) -> (engine::audio::AudioMeta, Vec<f32>) { |
| 189 | let (meta, rx) = AudioSession::open_multi_streams_speed_at( |
| 190 | &[(path.to_path_buf(), 0)], |
| 191 | &[(Some(0), 0.0, f64::INFINITY)], |
| 192 | &[], |
| 193 | &[], |
| 194 | Some(rate), |
| 195 | ) |
| 196 | .expect("opens") |
| 197 | .expect("has an audio track"); |
| 198 | let mut samples = Vec::new(); |
| 199 | for chunk in rx { |
| 200 | samples.extend_from_slice(&chunk.samples); |
| 201 | } |
| 202 | (meta, samples) |
| 203 | } |
| 204 | |
| 205 | fn channel(interleaved: &[f32], channels: usize, index: usize) -> Vec<f32> { |
| 206 | interleaved |
| 207 | .iter() |
| 208 | .skip(index) |
| 209 | .step_by(channels) |
| 210 | .copied() |
| 211 | .collect() |
| 212 | } |
| 213 | |
| 214 | fn correlation(a: &[f32], b: &[f32]) -> f64 { |
| 215 | let n = a.len().min(b.len()); |
| 216 | let (mut dot, mut aa, mut bb) = (0f64, 0f64, 0f64); |
| 217 | for (&x, &y) in a[..n].iter().zip(&b[..n]) { |
| 218 | dot += f64::from(x) * f64::from(y); |
| 219 | aa += f64::from(x) * f64::from(x); |
| 220 | bb += f64::from(y) * f64::from(y); |
| 221 | } |
| 222 | dot / (aa.sqrt() * bb.sqrt()).max(f64::MIN_POSITIVE) |
| 223 | } |
| 224 | |
| 225 | |
| 226 | fn check(case: &Case, tolerance: f32) { |
| 227 | let Some(file) = case.make() else { return }; |
| 228 | let timeline = if case.channels == 1 { 1 } else { 2 }; |
| 229 | let (meta, ours) = decode_at(&file, case.rate); |
| 230 | assert_eq!( |
| 231 | (meta.sample_rate, usize::from(meta.channels)), |
| 232 | (case.rate, timeline), |
| 233 | "{}: rate and channels of the import", |
| 234 | case.name |
| 235 | ); |
| 236 | assert!(!ours.is_empty(), "{}: no sound out of the track", case.name); |
| 237 | assert!( |
| 238 | ours.iter().any(|s| s.abs() > 0.05), |
| 239 | "{}: the decode is silent", |
| 240 | case.name |
| 241 | ); |
| 242 | |
| 243 | if case.channels <= 2 { |
| 244 | let theirs = ffmpeg_f32(&file, case.decoder, None); |
| 245 | let slack = 4096 * timeline; |
| 246 | assert!( |
| 247 | ours.len().abs_diff(theirs.len()) <= slack, |
| 248 | "{}: {} samples out, {} from ffmpeg", |
| 249 | case.name, |
| 250 | ours.len(), |
| 251 | theirs.len() |
| 252 | ); |
| 253 | let n = ours.len().min(theirs.len()); |
| 254 | let worst = ours[..n] |
| 255 | .iter() |
| 256 | .zip(&theirs[..n]) |
| 257 | .map(|(o, t)| (o - t).abs()) |
| 258 | .fold(0f32, f32::max); |
| 259 | assert!( |
| 260 | worst <= tolerance, |
| 261 | "{}: worst sample differs from ffmpeg by {worst} (limit {tolerance})", |
| 262 | case.name |
| 263 | ); |
| 264 | } else { |
| 265 | let theirs = ffmpeg_f32(&file, case.decoder, Some("2")); |
| 266 | for index in 0..2 { |
| 267 | let level = ours.iter().skip(index).step_by(2).map(|s| s.abs()).fold(0f32, f32::max); |
| 268 | assert!(level > 1e-3, "{}: timeline channel {index} is silent", case.name); |
| 269 | let score = correlation(&channel(&ours, 2, index), &channel(&theirs, 2, index)); |
| 270 | assert!( |
| 271 | score > 0.98, |
| 272 | "{}: timeline channel {index} correlates {score:.4} with ffmpeg's -ac 2 decode", |
| 273 | case.name |
| 274 | ); |
| 275 | } |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | const DTS: &[&str] = &["-strict", "-2", "-b:a", "384k"]; |
| 280 | |
| 281 | const DTS_TOL: f32 = 2e-4; |
| 282 | const EXACT: f32 = 1e-4; |
| 283 | |
| 284 | #[test] |
| 285 | fn dts_stereo_in_matroska_matches_ffmpeg() { |
| 286 | check(&Case::new("ve_dts_mka", "mka", "dca", 48_000, 2).extra(DTS), DTS_TOL); |
| 287 | } |
| 288 | |
| 289 | #[test] |
| 290 | fn dts_stereo_in_matroska_video_matches_ffmpeg() { |
| 291 | check( |
| 292 | &Case::new("ve_dts_mkv", "mkv", "dca", 48_000, 2) |
| 293 | .extra(DTS) |
| 294 | .video("mpeg4"), |
| 295 | DTS_TOL, |
| 296 | ); |
| 297 | } |
| 298 | |
| 299 | #[test] |
| 300 | fn dts_51_in_matroska_folds_to_ffmpegs_stereo_by_correlation() { |
| 301 | check( |
| 302 | &Case::new("ve_dts_51_mka", "mka", "dca", 48_000, 6).extra(&["-strict", "-2", "-b:a", "1536k"]), |
| 303 | DTS_TOL, |
| 304 | ); |
| 305 | } |
| 306 | |
| 307 | #[test] |
| 308 | fn raw_dts_file_matches_ffmpeg() { |
| 309 | check( |
| 310 | &Case::new("ve_dts_raw", "dts", "dca", 48_000, 2).extra(&["-strict", "-2", "-b:a", "384k", "-f", "dts"]), |
| 311 | DTS_TOL, |
| 312 | ); |
| 313 | } |
| 314 | |
| 315 | #[test] |
| 316 | fn dts_in_mp4_matches_ffmpeg() { |
| 317 | check( |
| 318 | &Case::new("ve_dts_mp4", "mp4", "dca", 48_000, 2) |
| 319 | .extra(DTS) |
| 320 | .video("mpeg4"), |
| 321 | DTS_TOL, |
| 322 | ); |
| 323 | } |
| 324 | |
| 325 | #[test] |
| 326 | fn dts_in_transport_stream_matches_ffmpeg() { |
| 327 | check( |
| 328 | &Case::new("ve_dts_ts", "ts", "dca", 48_000, 2) |
| 329 | .extra(DTS) |
| 330 | .video("mpeg2video"), |
| 331 | DTS_TOL, |
| 332 | ); |
| 333 | } |
| 334 | |
| 335 | #[test] |
| 336 | fn dts_in_wav_matches_ffmpeg() { |
| 337 | check( |
| 338 | &Case::new("ve_dts_wav", "wav", "dca", 48_000, 2).extra(&["-strict", "-2", "-b:a", "384k", "-f", "wav"]), |
| 339 | DTS_TOL, |
| 340 | ); |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn dts_in_avi_matches_ffmpeg() { |
| 345 | check( |
| 346 | &Case::new("ve_dts_avi", "avi", "dca", 48_000, 2) |
| 347 | .extra(DTS) |
| 348 | .video("mpeg4"), |
| 349 | DTS_TOL, |
| 350 | ); |
| 351 | } |
| 352 | |
| 353 | #[test] |
| 354 | fn ima_adpcm_wav_matches_ffmpeg() { |
| 355 | check(&Case::new("ve_ima_wav", "wav", "adpcm_ima_wav", 44_100, 2), EXACT); |
| 356 | check(&Case::new("ve_ima_wav_mono", "wav", "adpcm_ima_wav", 22_050, 1), EXACT); |
| 357 | } |
| 358 | |
| 359 | #[test] |
| 360 | fn ms_adpcm_wav_matches_ffmpeg() { |
| 361 | check(&Case::new("ve_msadpcm_wav", "wav", "adpcm_ms", 44_100, 2), EXACT); |
| 362 | check(&Case::new("ve_msadpcm_wav_mono", "wav", "adpcm_ms", 22_050, 1), EXACT); |
| 363 | } |
| 364 | |
| 365 | #[test] |
| 366 | fn alaw_and_mulaw_wav_match_ffmpeg() { |
| 367 | check(&Case::new("ve_alaw_wav", "wav", "pcm_alaw", 8_000, 1), EXACT); |
| 368 | check(&Case::new("ve_mulaw_wav", "wav", "pcm_mulaw", 8_000, 1), EXACT); |
| 369 | check(&Case::new("ve_alaw_wav_st", "wav", "pcm_alaw", 44_100, 2), EXACT); |
| 370 | } |
| 371 | |
| 372 | #[test] |
| 373 | fn adpcm_and_g711_in_avi_match_ffmpeg() { |
| 374 | for (name, codec, rate) in [ |
| 375 | ("ve_ima_avi", "adpcm_ima_wav", 44_100), |
| 376 | ("ve_msadpcm_avi", "adpcm_ms", 44_100), |
| 377 | ("ve_alaw_avi", "pcm_alaw", 8_000), |
| 378 | ("ve_mulaw_avi", "pcm_mulaw", 8_000), |
| 379 | ] { |
| 380 | let channels = if rate == 8_000 { 1 } else { 2 }; |
| 381 | check(&Case::new(name, "avi", codec, rate, channels).video("mpeg4"), EXACT); |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | #[test] |
| 386 | fn ima4_and_g711_in_quicktime_match_ffmpeg() { |
| 387 | check( |
| 388 | &Case::new("ve_ima4_mov", "mov", "adpcm_ima_qt", 44_100, 2).video("mpeg4"), |
| 389 | EXACT, |
| 390 | ); |
| 391 | check( |
| 392 | &Case::new("ve_alaw_mov", "mov", "pcm_alaw", 8_000, 1).video("mpeg4"), |
| 393 | EXACT, |
| 394 | ); |
| 395 | check( |
| 396 | &Case::new("ve_mulaw_mov", "mov", "pcm_mulaw", 8_000, 1).video("mpeg4"), |
| 397 | EXACT, |
| 398 | ); |
| 399 | } |
| 400 | |
| 401 | #[test] |
| 402 | fn amr_nb_in_3gp_and_raw_matches_ffmpeg() { |
| 403 | let nb = |name, ext, extra: &'static [&'static str]| { |
| 404 | Case::new(name, ext, "libopencore_amrnb", 8_000, 1) |
| 405 | .extra(extra) |
| 406 | .decoder("libopencore_amrnb") |
| 407 | }; |
| 408 | check(&nb("ve_amrnb_3gp", "3gp", &["-b:a", "12.2k"]).video("mpeg4"), EXACT); |
| 409 | check(&nb("ve_amrnb_raw", "amr", &["-b:a", "7.95k"]), EXACT); |
| 410 | check(&nb("ve_amrnb_mov", "mov", &["-b:a", "10.2k"]).video("mpeg4"), EXACT); |
| 411 | } |
| 412 | |
| 413 | #[test] |
| 414 | fn amr_wb_in_3gp_and_raw_matches_ffmpeg() { |
| 415 | let wb = |name, ext| { |
| 416 | Case::new(name, ext, "libvo_amrwbenc", 16_000, 1) |
| 417 | .extra(if ext == "awb" { &["-f", "amr"] } else { &["-f", "3gp"] }) |
| 418 | .encoder("libvo_amrwbenc") |
| 419 | .decoder("libopencore_amrwb") |
| 420 | }; |
| 421 | check(&wb("ve_amrwb_3gp", "3gp").video("mpeg4"), EXACT); |
| 422 | check(&wb("ve_amrwb_raw", "awb"), EXACT); |
| 423 | } |
| 424 | |
| 425 | #[test] |
| 426 | fn dts_refuses_lossless_by_name_and_reports_decodable_streams() { |
| 427 | |
| 428 | let Some(file) = Case::new("ve_dts_probe", "mka", "dca", 48_000, 2).extra(DTS).make() else { |
| 429 | return; |
| 430 | }; |
| 431 | let streams = AudioSession::probe_streams(&*file).expect("lists"); |
| 432 | assert_eq!(streams.len(), 1); |
| 433 | assert!(streams[0].decodable, "{:?}", streams[0]); |
| 434 | assert_eq!((streams[0].sample_rate, streams[0].channels), (48_000, 2)); |
| 435 | assert_eq!(AudioSession::unsupported(&*file).expect("asks"), None); |
| 436 | } |
| 437 | |
| 438 | #[test] |
| 439 | fn dts_window_starts_where_asked() { |
| 440 | let Some(file) = Case::new("ve_dts_window", "mka", "dca", 48_000, 2).extra(DTS).make() else { |
| 441 | return; |
| 442 | }; |
| 443 | let (_, whole) = decode_at(&file, 48_000); |
| 444 | let (meta, rx) = AudioSession::open_at(&*file, 1.0).expect("opens").expect("has sound"); |
| 445 | let mut tail = Vec::new(); |
| 446 | for chunk in rx { |
| 447 | tail.extend_from_slice(&chunk.samples); |
| 448 | } |
| 449 | let from = 48_000 * usize::from(meta.channels); |
| 450 | let n = tail.len().min(whole.len() - from); |
| 451 | assert!(n > 40_000, "the window decoded only {n} samples"); |
| 452 | let worst = tail[..n] |
| 453 | .iter() |
| 454 | .zip(&whole[from..from + n]) |
| 455 | .map(|(a, b)| (a - b).abs()) |
| 456 | .fold(0f32, f32::max); |
| 457 | assert!(worst < 2e-3, "a window at 1 s differs from the whole decode by {worst}"); |
| 458 | } |
| 459 | |
| 460 | |
| 461 | |
| 462 | const MP2_TOL: f32 = 1e-3; |
| 463 | |
| 464 | #[test] |
| 465 | fn mp2_in_mp4_and_matroska_matches_ffmpeg() { |
| 466 | let mp2 = |name, ext| { |
| 467 | Case::new(name, ext, "mp2", 44_100, 1).extra(&["-b:a", "128k"]).video("mpeg4") |
| 468 | }; |
| 469 | check(&mp2("ve_mp2_mp4", "mp4"), MP2_TOL); |
| 470 | check(&mp2("ve_mp2_mkv", "mkv"), MP2_TOL); |
| 471 | } |
| 472 | |
| 473 | #[test] |
| 474 | fn mp2_is_named_mp2_and_decodes_in_mp4_and_matroska() { |
| 475 | for (name, ext) in [("ve_mp2_named_mp4", "mp4"), ("ve_mp2_named_mkv", "mkv")] { |
| 476 | let case = Case::new(name, ext, "mp2", 44_100, 1).extra(&["-b:a", "128k"]).video("mpeg4"); |
| 477 | let Some(file) = case.make() else { |
| 478 | return; |
| 479 | }; |
| 480 | let streams = AudioSession::probe_streams(&*file).expect("lists"); |
| 481 | assert_eq!(streams.len(), 1, "{name}"); |
| 482 | assert_eq!(streams[0].codec, "mp2", "{name}: named by its layer, not as mp3"); |
| 483 | assert!(streams[0].decodable, "{name}: {:?}", streams[0]); |
| 484 | assert_eq!(AudioSession::unsupported(&*file).expect("asks"), None, "{name}"); |
| 485 | } |
| 486 | } |