| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use std::path::{Path, PathBuf}; |
| 6 | use std::process::Command; |
| 7 | |
| 8 | use ec_aac::{AacDecoder, AacEncoder, AacEncoderConfig}; |
| 9 | |
| 10 | fn fixtures() -> PathBuf { |
| 11 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") |
| 12 | } |
| 13 | |
| 14 | fn have_ffmpeg() -> bool { |
| 15 | Command::new("ffmpeg") |
| 16 | .arg("-version") |
| 17 | .output() |
| 18 | .map(|o| o.status.success()) |
| 19 | .unwrap_or(false) |
| 20 | } |
| 21 | |
| 22 | |
| 23 | fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> { |
| 24 | let out = Command::new("ffmpeg") |
| 25 | .args(["-v", "error", "-i"]) |
| 26 | .arg(path) |
| 27 | .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) |
| 28 | .output() |
| 29 | .expect("ffmpeg runs"); |
| 30 | assert!( |
| 31 | out.status.success(), |
| 32 | "ffmpeg decode failed: {}", |
| 33 | String::from_utf8_lossy(&out.stderr) |
| 34 | ); |
| 35 | deinterleave(&bytes_to_f32(&out.stdout), channels) |
| 36 | } |
| 37 | |
| 38 | fn bytes_to_f32(bytes: &[u8]) -> Vec<f32> { |
| 39 | bytes |
| 40 | .chunks_exact(4) |
| 41 | .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) |
| 42 | .collect() |
| 43 | } |
| 44 | |
| 45 | fn deinterleave(samples: &[f32], channels: usize) -> Vec<Vec<f32>> { |
| 46 | let mut out = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels]; |
| 47 | for (i, &v) in samples.iter().enumerate() { |
| 48 | out[i % channels].push(v); |
| 49 | } |
| 50 | out |
| 51 | } |
| 52 | |
| 53 | |
| 54 | fn our_decode(path: &Path) -> (Vec<Vec<f32>>, u32) { |
| 55 | let (planes, rate, _) = our_decode_with_pns(path); |
| 56 | (planes, rate) |
| 57 | } |
| 58 | |
| 59 | fn our_decode_with_pns(path: &Path) -> (Vec<Vec<f32>>, u32, usize) { |
| 60 | let data = std::fs::read(path).expect("fixture readable"); |
| 61 | let mut decoder = AacDecoder::new(); |
| 62 | let mut planes: Vec<Vec<f32>> = Vec::new(); |
| 63 | let mut rate = 0; |
| 64 | let mut at = 0usize; |
| 65 | while at + 7 <= data.len() { |
| 66 | let header = ec_aac::parse_adts(&data[at..]).expect("adts header"); |
| 67 | let end = (at + header.frame_length).min(data.len()); |
| 68 | let frame = decoder.decode(&data[at..end], None).expect("frame decodes"); |
| 69 | rate = frame.sample_rate; |
| 70 | let ch = usize::from(frame.channels); |
| 71 | if planes.is_empty() { |
| 72 | planes = vec![Vec::new(); ch]; |
| 73 | } |
| 74 | for (i, v) in frame.samples.iter().enumerate() { |
| 75 | planes[i % ch].push(*v); |
| 76 | } |
| 77 | at = end; |
| 78 | } |
| 79 | (planes, rate, decoder.pns_aus()) |
| 80 | } |
| 81 | |
| 82 | |
| 83 | fn correlation(a: &[f32], b: &[f32]) -> f64 { |
| 84 | let n = a.len().min(b.len()); |
| 85 | assert!(n > 1024, "not enough overlap to compare: {n} samples"); |
| 86 | let (a, b) = (&a[..n], &b[..n]); |
| 87 | let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64; |
| 88 | let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64; |
| 89 | let mut num = 0.0; |
| 90 | let mut da = 0.0; |
| 91 | let mut db = 0.0; |
| 92 | for i in 0..n { |
| 93 | let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb); |
| 94 | num += x * y; |
| 95 | da += x * x; |
| 96 | db += y * y; |
| 97 | } |
| 98 | if da == 0.0 || db == 0.0 { |
| 99 | return if da == db { 1.0 } else { 0.0 }; |
| 100 | } |
| 101 | num / (da * db).sqrt() |
| 102 | } |
| 103 | |
| 104 | fn compare(path: &Path) -> Vec<f64> { |
| 105 | let (ours, _rate) = our_decode(path); |
| 106 | assert!(!ours.is_empty(), "no channels decoded from {path:?}"); |
| 107 | let theirs = ffmpeg_decode(path, ours.len()); |
| 108 | ours.iter() |
| 109 | .zip(&theirs) |
| 110 | .map(|(a, b)| correlation(a, b)) |
| 111 | .collect() |
| 112 | } |
| 113 | |
| 114 | #[test] |
| 115 | fn adts_fixtures_match_ffmpeg_per_channel() { |
| 116 | if !have_ffmpeg() { |
| 117 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 118 | return; |
| 119 | } |
| 120 | let dir = fixtures().join("audio"); |
| 121 | let mut checked = 0; |
| 122 | for name in [ |
| 123 | "aac-adts-mono-44100.aac", |
| 124 | "aac-adts-mono-48000.aac", |
| 125 | "aac-adts-stereo-44100.aac", |
| 126 | "aac-adts-stereo-48000.aac", |
| 127 | "aac-adts-5.1-44100.aac", |
| 128 | "aac-adts-5.1-48000.aac", |
| 129 | ] { |
| 130 | let path = dir.join(name); |
| 131 | if !path.exists() { |
| 132 | eprintln!("SKIP {name}: fixture missing"); |
| 133 | continue; |
| 134 | } |
| 135 | let corr = compare(&path); |
| 136 | println!("{name}: {corr:?}"); |
| 137 | for (ch, c) in corr.iter().enumerate() { |
| 138 | assert!( |
| 139 | *c >= 0.999, |
| 140 | "{name} channel {ch} correlation {c:.6} < 0.999" |
| 141 | ); |
| 142 | } |
| 143 | checked += 1; |
| 144 | } |
| 145 | assert!( |
| 146 | checked > 0, |
| 147 | "no AAC fixtures found: run scripts/gen-fixtures.sh" |
| 148 | ); |
| 149 | } |
| 150 | |
| 151 | #[test] |
| 152 | fn mp4_fixtures_match_ffmpeg_per_channel() { |
| 153 | if !have_ffmpeg() { |
| 154 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 155 | return; |
| 156 | } |
| 157 | let dir = fixtures().join("audio"); |
| 158 | let tmp = std::env::temp_dir().join("ec-aac-mp4-oracle"); |
| 159 | std::fs::create_dir_all(&tmp).expect("temp dir"); |
| 160 | let mut checked = 0; |
| 161 | for name in [ |
| 162 | "aac-mp4-mono-48000.mp4", |
| 163 | "aac-mp4-stereo-48000.mp4", |
| 164 | "aac-mp4-5.1-48000.mp4", |
| 165 | ] { |
| 166 | let path = dir.join(name); |
| 167 | if !path.exists() { |
| 168 | eprintln!("SKIP {name}: fixture missing"); |
| 169 | continue; |
| 170 | } |
| 171 | |
| 172 | |
| 173 | let adts = tmp.join(format!("{name}.aac")); |
| 174 | let out = Command::new("ffmpeg") |
| 175 | .args(["-v", "error", "-y", "-i"]) |
| 176 | .arg(&path) |
| 177 | .args(["-c:a", "copy", "-f", "adts"]) |
| 178 | .arg(&adts) |
| 179 | .output() |
| 180 | .expect("ffmpeg runs"); |
| 181 | assert!(out.status.success(), "remux failed for {name}"); |
| 182 | let corr = compare(&adts); |
| 183 | println!("{name}: {corr:?}"); |
| 184 | for (ch, c) in corr.iter().enumerate() { |
| 185 | assert!( |
| 186 | *c >= 0.999, |
| 187 | "{name} channel {ch} correlation {c:.6} < 0.999" |
| 188 | ); |
| 189 | } |
| 190 | checked += 1; |
| 191 | } |
| 192 | assert!(checked > 0, "no AAC-in-mp4 fixtures found"); |
| 193 | } |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | |
| 199 | #[test] |
| 200 | fn aac_coding_tools_match_ffmpeg_in_isolation() { |
| 201 | if !have_ffmpeg() { |
| 202 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 203 | return; |
| 204 | } |
| 205 | let dir = fixtures().join("audio"); |
| 206 | let tmp = std::env::temp_dir().join("ec-aac-tools-oracle"); |
| 207 | std::fs::create_dir_all(&tmp).expect("temp dir"); |
| 208 | let mut checked = 0; |
| 209 | for tool in ["pns", "is", "ms", "tns", "all"] { |
| 210 | let name = format!("aac-tool-{tool}-mp4-stereo-48000.m4a"); |
| 211 | let path = dir.join(&name); |
| 212 | if !path.exists() { |
| 213 | eprintln!("SKIP {name}: fixture missing"); |
| 214 | continue; |
| 215 | } |
| 216 | let adts = tmp.join(format!("{name}.aac")); |
| 217 | let out = Command::new("ffmpeg") |
| 218 | .args(["-v", "error", "-y", "-i"]) |
| 219 | .arg(&path) |
| 220 | .args(["-c:a", "copy", "-f", "adts"]) |
| 221 | .arg(&adts) |
| 222 | .output() |
| 223 | .expect("ffmpeg runs"); |
| 224 | assert!(out.status.success(), "remux failed for {name}"); |
| 225 | let corr = compare(&adts); |
| 226 | let pns = our_decode_with_pns(&adts).2; |
| 227 | assert_eq!( |
| 228 | pns > 0, |
| 229 | matches!(tool, "pns" | "all"), |
| 230 | "{name}: pns_aus={pns}" |
| 231 | ); |
| 232 | println!("{name}: {corr:?}"); |
| 233 | for (ch, c) in corr.iter().enumerate() { |
| 234 | assert!( |
| 235 | *c >= 0.999, |
| 236 | "{name} channel {ch} correlation {c:.6} < 0.999" |
| 237 | ); |
| 238 | } |
| 239 | checked += 1; |
| 240 | } |
| 241 | assert!(checked > 0, "no AAC tool-isolation fixtures found"); |
| 242 | } |
| 243 | |
| 244 | |
| 245 | |
| 246 | |
| 247 | #[test] |
| 248 | fn five_one_comes_out_in_film_order() { |
| 249 | if !have_ffmpeg() { |
| 250 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 251 | return; |
| 252 | } |
| 253 | let tmp = std::env::temp_dir().join("ec-aac-order"); |
| 254 | std::fs::create_dir_all(&tmp).expect("temp dir"); |
| 255 | let src = tmp.join("order.aac"); |
| 256 | |
| 257 | |
| 258 | let tones = [300.0, 700.0, 1100.0, 60.0, 1900.0, 2300.0]; |
| 259 | let mut cmd = Command::new("ffmpeg"); |
| 260 | cmd.args(["-v", "error", "-y"]); |
| 261 | for f in tones { |
| 262 | cmd.args([ |
| 263 | "-f", |
| 264 | "lavfi", |
| 265 | "-i", |
| 266 | &format!("sine=frequency={f}:duration=2:sample_rate=48000"), |
| 267 | ]); |
| 268 | } |
| 269 | let out = cmd |
| 270 | .args([ |
| 271 | "-filter_complex", |
| 272 | "[0:a][1:a][2:a][3:a][4:a][5:a]join=inputs=6:channel_layout=5.1:\ |
| 273 | map=0.0-FL|1.0-FR|2.0-FC|3.0-LFE|4.0-BL|5.0-BR[a]", |
| 274 | "-map", |
| 275 | "[a]", |
| 276 | "-c:a", |
| 277 | "aac", |
| 278 | "-b:a", |
| 279 | "320k", |
| 280 | "-f", |
| 281 | "adts", |
| 282 | ]) |
| 283 | .arg(&src) |
| 284 | .output() |
| 285 | .expect("ffmpeg runs"); |
| 286 | assert!( |
| 287 | out.status.success(), |
| 288 | "tone build failed: {}", |
| 289 | String::from_utf8_lossy(&out.stderr) |
| 290 | ); |
| 291 | let (ours, rate) = our_decode(&src); |
| 292 | assert_eq!(ours.len(), 6, "5.1 decodes to six channels"); |
| 293 | for (ch, plane) in ours.iter().enumerate() { |
| 294 | let peak = dominant_frequency(plane, rate); |
| 295 | let want = tones[ch]; |
| 296 | assert!( |
| 297 | (peak - want).abs() < 40.0, |
| 298 | "channel {ch} peaks at {peak:.0} Hz, expected {want:.0} Hz: \ |
| 299 | the element order was not remapped to FL, FR, FC, LFE, BL, BR" |
| 300 | ); |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | |
| 305 | fn dominant_frequency(samples: &[f32], rate: u32) -> f64 { |
| 306 | let n = samples.len().min(16384); |
| 307 | let start = samples.len() / 3; |
| 308 | let seg = &samples[start..start + n.min(samples.len() - start)]; |
| 309 | let mut best = (0.0f64, 0.0f64); |
| 310 | let mut f = 40.0; |
| 311 | while f < 4000.0 { |
| 312 | let w = 2.0 * std::f64::consts::PI * f / f64::from(rate); |
| 313 | let (mut re, mut im) = (0.0, 0.0); |
| 314 | for (i, &v) in seg.iter().enumerate() { |
| 315 | re += f64::from(v) * (w * i as f64).cos(); |
| 316 | im += f64::from(v) * (w * i as f64).sin(); |
| 317 | } |
| 318 | let mag = re * re + im * im; |
| 319 | if mag > best.1 { |
| 320 | best = (f, mag); |
| 321 | } |
| 322 | f += 5.0; |
| 323 | } |
| 324 | best.0 |
| 325 | } |
| 326 | |
| 327 | #[test] |
| 328 | fn asc_round_trips_every_sample_rate() { |
| 329 | for (index, rate) in ec_aac::SAMPLE_RATES.iter().enumerate() { |
| 330 | assert_eq!(ec_aac::sf_index_for_rate(*rate), Some(index as u8)); |
| 331 | assert_eq!(ec_aac::sample_rate_for_index(index as u8), *rate); |
| 332 | for channels in [1u16, 2, 6, 8] { |
| 333 | let bytes = ec_aac::audio_specific_config_bytes(*rate, channels); |
| 334 | let cfg = ec_aac::parse_audio_specific_config(&bytes).expect("asc parses"); |
| 335 | assert_eq!(cfg.sample_rate, *rate, "rate round trip at {rate} Hz"); |
| 336 | assert_eq!(cfg.channels, channels, "channels round trip at {rate} Hz"); |
| 337 | assert_eq!(cfg.object_type, ec_aac::AOT_AAC_LC); |
| 338 | } |
| 339 | } |
| 340 | assert_eq!(ec_aac::sf_index_for_rate(37_000), None); |
| 341 | } |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 346 | |
| 347 | #[test] |
| 348 | fn sbr_is_reported_not_silently_upsampled() { |
| 349 | |
| 350 | |
| 351 | let asc = [0x2Bu8, 0x11, 0x88]; |
| 352 | let decoder = AacDecoder::with_config_bytes(&asc).expect("HE-AAC config parses"); |
| 353 | assert_eq!(decoder.sbr_support(), ec_aac::SbrSupport::V1); |
| 354 | assert_eq!( |
| 355 | decoder.output_sample_rate(), |
| 356 | Some(48_000), |
| 357 | "a reconstructed HE-AAC stream must report the extension rate it now actually produces" |
| 358 | ); |
| 359 | |
| 360 | |
| 361 | let ps_asc = [0xEBu8, 0x11, 0x88]; |
| 362 | let ps_decoder = AacDecoder::with_config_bytes(&ps_asc).expect("HE-AAC v2 config parses"); |
| 363 | assert_eq!(ps_decoder.sbr_support(), ec_aac::SbrSupport::CoreOnly); |
| 364 | assert_eq!( |
| 365 | ps_decoder.output_sample_rate(), |
| 366 | Some(24_000), |
| 367 | "PS is still unreconstructed: must report the core rate it actually produces" |
| 368 | ); |
| 369 | |
| 370 | let plain = AacDecoder::with_config_bytes(&ec_aac::audio_specific_config_bytes(48_000, 2)) |
| 371 | .expect("LC config parses"); |
| 372 | assert_eq!(plain.sbr_support(), ec_aac::SbrSupport::NotSignalled); |
| 373 | } |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | const INCUMBENT_BAR: &[(&str, usize, u32, f64)] = &[ |
| 379 | ("mono", 1, 96, 0.9846), |
| 380 | ("stereo", 2, 128, 0.9743), |
| 381 | ("stereo", 2, 192, 0.9864), |
| 382 | ("5.1", 6, 384, 0.9648), |
| 383 | ("5.1", 6, 448, 0.9611), |
| 384 | ]; |
| 385 | |
| 386 | fn encode_to_adts(pcm: &[f32], channels: u16, rate: u32, kbps: u32) -> Vec<u8> { |
| 387 | let mut enc = AacEncoder::new(AacEncoderConfig { |
| 388 | bitrate_bps: kbps * 1000, |
| 389 | adts: true, |
| 390 | ..Default::default() |
| 391 | }); |
| 392 | enc.push_pcm(pcm, channels, rate).expect("pcm accepted"); |
| 393 | enc.finish(); |
| 394 | let mut out = Vec::new(); |
| 395 | while let Ok(p) = enc.next_packet() { |
| 396 | out.extend_from_slice(&p.data); |
| 397 | } |
| 398 | out |
| 399 | } |
| 400 | |
| 401 | |
| 402 | fn best_correlation(source: &[f32], decoded: &[f32]) -> f64 { |
| 403 | [0usize, ec_aac::FRAME_LEN, 2 * ec_aac::FRAME_LEN] |
| 404 | .into_iter() |
| 405 | .filter(|lag| decoded.len() > *lag + 1024) |
| 406 | .map(|lag| correlation(source, &decoded[lag..])) |
| 407 | .fold(f64::MIN, f64::max) |
| 408 | } |
| 409 | |
| 410 | |
| 411 | |
| 412 | #[test] |
| 413 | fn encoder_beats_the_incumbent_bar() { |
| 414 | if !have_ffmpeg() { |
| 415 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 416 | return; |
| 417 | } |
| 418 | let dir = fixtures().join("audio"); |
| 419 | let tmp = std::env::temp_dir().join("ec-aac-bar"); |
| 420 | std::fs::create_dir_all(&tmp).expect("temp dir"); |
| 421 | let mut checked = 0; |
| 422 | for (name, channels, kbps, bar) in INCUMBENT_BAR { |
| 423 | let src = dir.join(format!("flac-{name}-48000.flac")); |
| 424 | if !src.exists() { |
| 425 | eprintln!("SKIP {name}: fixture missing"); |
| 426 | continue; |
| 427 | } |
| 428 | let source = ffmpeg_decode(&src, *channels); |
| 429 | let mut interleaved = Vec::with_capacity(source[0].len() * channels); |
| 430 | for i in 0..source[0].len() { |
| 431 | for plane in &source { |
| 432 | interleaved.push(plane[i]); |
| 433 | } |
| 434 | } |
| 435 | let adts = encode_to_adts(&interleaved, *channels as u16, 48_000, *kbps); |
| 436 | let path = tmp.join(format!("{name}-{kbps}k.aac")); |
| 437 | std::fs::write(&path, &adts).expect("write"); |
| 438 | let rate = adts.len() as f64 * 8.0 * 48_000.0 / source[0].len() as f64 / 1000.0; |
| 439 | let ours = ffmpeg_decode(&path, *channels); |
| 440 | let corr: Vec<f64> = source |
| 441 | .iter() |
| 442 | .zip(&ours) |
| 443 | .map(|(a, b)| best_correlation(a, b)) |
| 444 | .collect(); |
| 445 | let worst = corr.iter().copied().fold(f64::MAX, f64::min); |
| 446 | println!( |
| 447 | "enc {name} {kbps}k: {rate:.0} kbps actual, worst channel {worst:.4} \ |
| 448 | (incumbent {bar:.4}) per-channel {corr:?}" |
| 449 | ); |
| 450 | assert!( |
| 451 | rate <= f64::from(*kbps) * 1.12, |
| 452 | "{name} {kbps}k overshot its target: {rate:.0} kbps" |
| 453 | ); |
| 454 | assert!( |
| 455 | worst >= *bar, |
| 456 | "{name} {kbps}k worst channel {worst:.4} is under the incumbent's {bar:.4}" |
| 457 | ); |
| 458 | checked += 1; |
| 459 | } |
| 460 | assert!(checked > 0, "no lossless fixtures found"); |
| 461 | } |
| 462 | |
| 463 | fn tone_pcm(rate: u32, channels: usize, secs: f64) -> Vec<f32> { |
| 464 | let frames = (f64::from(rate) * secs) as usize; |
| 465 | let mut pcm = Vec::with_capacity(frames * channels); |
| 466 | for i in 0..frames { |
| 467 | let t = i as f64 / f64::from(rate); |
| 468 | for c in 0..channels { |
| 469 | let f = 220.0 * (c + 1) as f64; |
| 470 | let v = (t * f * std::f64::consts::TAU).sin() * 0.35 |
| 471 | + (t * f * 2.5 * std::f64::consts::TAU).sin() * 0.15; |
| 472 | pcm.push(v as f32); |
| 473 | } |
| 474 | } |
| 475 | pcm |
| 476 | } |
| 477 | |
| 478 | #[test] |
| 479 | fn encoder_output_decodes_in_ffmpeg_without_warnings() { |
| 480 | if !have_ffmpeg() { |
| 481 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 482 | return; |
| 483 | } |
| 484 | let tmp = std::env::temp_dir().join("ec-aac-enc"); |
| 485 | std::fs::create_dir_all(&tmp).expect("temp dir"); |
| 486 | for (channels, kbps) in [(1u16, 96u32), (2, 128), (2, 192), (6, 384)] { |
| 487 | let rate = 48_000; |
| 488 | let pcm = tone_pcm(rate, usize::from(channels), 1.5); |
| 489 | let adts = encode_to_adts(&pcm, channels, rate, kbps); |
| 490 | assert!(!adts.is_empty(), "{channels}ch encode produced nothing"); |
| 491 | let path = tmp.join(format!("enc-{channels}ch-{kbps}k.aac")); |
| 492 | std::fs::write(&path, &adts).expect("write"); |
| 493 | let out = Command::new("ffmpeg") |
| 494 | .args(["-v", "warning", "-i"]) |
| 495 | .arg(&path) |
| 496 | .args(["-f", "null", "-"]) |
| 497 | .output() |
| 498 | .expect("ffmpeg runs"); |
| 499 | |
| 500 | |
| 501 | let log = String::from_utf8_lossy(&out.stderr); |
| 502 | let log: String = log |
| 503 | .lines() |
| 504 | .filter(|l| !l.contains("Estimating duration from bitrate")) |
| 505 | .collect::<Vec<_>>() |
| 506 | .join("\n"); |
| 507 | assert!( |
| 508 | out.status.success() && log.trim().is_empty(), |
| 509 | "ffmpeg complained about our {channels}ch/{kbps}k ADTS:\n{log}" |
| 510 | ); |
| 511 | |
| 512 | let theirs = ffmpeg_decode(&path, usize::from(channels)); |
| 513 | let ours = deinterleave(&pcm, usize::from(channels)); |
| 514 | for (ch, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 515 | |
| 516 | |
| 517 | let corr = correlation(a, &b[ec_aac::FRAME_LEN..]); |
| 518 | println!("enc {channels}ch {kbps}k channel {ch}: corr {corr:.4}"); |
| 519 | assert!( |
| 520 | corr >= 0.90, |
| 521 | "{channels}ch/{kbps}k channel {ch} correlation {corr:.4} < 0.90" |
| 522 | ); |
| 523 | } |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | |
| 528 | |
| 529 | |
| 530 | #[test] |
| 531 | fn every_codebook_is_a_complete_prefix_code() { |
| 532 | let expected = [81usize, 81, 81, 81, 81, 81, 64, 64, 169, 169, 289]; |
| 533 | for (i, cb) in ec_aac::tables::CODEBOOKS.iter().enumerate() { |
| 534 | assert_eq!( |
| 535 | cb.codes.len(), |
| 536 | expected[i], |
| 537 | "codebook {} entry count", |
| 538 | i + 1 |
| 539 | ); |
| 540 | let kraft: f64 = cb |
| 541 | .codes |
| 542 | .iter() |
| 543 | .map(|(l, _)| 2f64.powi(-i32::from(*l))) |
| 544 | .sum(); |
| 545 | assert!( |
| 546 | (kraft - 1.0).abs() < 1e-12, |
| 547 | "codebook {} Kraft sum {kraft}", |
| 548 | i + 1 |
| 549 | ); |
| 550 | assert_prefix_free(cb.codes, &format!("codebook {}", i + 1)); |
| 551 | } |
| 552 | let sf = ec_aac::tables::SCALEFACTOR_CODES; |
| 553 | assert_eq!(sf.len(), 121, "scalefactor codebook entry count"); |
| 554 | let kraft: f64 = sf.iter().map(|(l, _)| 2f64.powi(-i32::from(*l))).sum(); |
| 555 | assert!((kraft - 1.0).abs() < 1e-12, "scalefactor Kraft sum {kraft}"); |
| 556 | assert_prefix_free(sf, "scalefactor codebook"); |
| 557 | } |
| 558 | |
| 559 | fn assert_prefix_free(codes: &[(u8, u32)], what: &str) { |
| 560 | for (i, &(li, ci)) in codes.iter().enumerate() { |
| 561 | for &(lj, cj) in codes.iter().skip(i + 1) { |
| 562 | let short = li.min(lj); |
| 563 | if (ci >> (li - short)) == (cj >> (lj - short)) { |
| 564 | panic!("{what}: {ci:b}/{li} and {cj:b}/{lj} share a prefix"); |
| 565 | } |
| 566 | } |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | |
| 571 | #[test] |
| 572 | fn band_tables_span_the_window() { |
| 573 | for (i, swb) in ec_aac::tables::SWB_LONG.iter().enumerate() { |
| 574 | assert_eq!(swb[0], 0, "long index {i}"); |
| 575 | assert_eq!(*swb.last().unwrap(), 1024, "long index {i}"); |
| 576 | assert!(swb.windows(2).all(|w| w[0] < w[1]), "long index {i}"); |
| 577 | } |
| 578 | for (i, swb) in ec_aac::tables::SWB_SHORT.iter().enumerate() { |
| 579 | assert_eq!(swb[0], 0, "short index {i}"); |
| 580 | assert_eq!(*swb.last().unwrap(), 128, "short index {i}"); |
| 581 | assert!(swb.windows(2).all(|w| w[0] < w[1]), "short index {i}"); |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | |
| 586 | |
| 587 | |
| 588 | #[test] |
| 589 | fn asc_matches_the_one_ffmpeg_writes() { |
| 590 | if !have_ffmpeg() { |
| 591 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 592 | return; |
| 593 | } |
| 594 | let tmp = std::env::temp_dir().join("ec-aac-esds"); |
| 595 | std::fs::create_dir_all(&tmp).expect("temp dir"); |
| 596 | for (channels, rate) in [(1u16, 48_000u32), (2, 48_000), (2, 44_100), (6, 48_000)] { |
| 597 | let pcm = tone_pcm(rate, usize::from(channels), 0.4); |
| 598 | let adts = encode_to_adts(&pcm, channels, rate, 128); |
| 599 | let src = tmp.join(format!("asc-{channels}-{rate}.aac")); |
| 600 | std::fs::write(&src, &adts).expect("write"); |
| 601 | let mp4 = tmp.join(format!("asc-{channels}-{rate}.mp4")); |
| 602 | let out = Command::new("ffmpeg") |
| 603 | .args(["-v", "error", "-y", "-i"]) |
| 604 | .arg(&src) |
| 605 | .args(["-c:a", "copy"]) |
| 606 | .arg(&mp4) |
| 607 | .output() |
| 608 | .expect("ffmpeg runs"); |
| 609 | assert!( |
| 610 | out.status.success(), |
| 611 | "remux of our ADTS failed: {}", |
| 612 | String::from_utf8_lossy(&out.stderr) |
| 613 | ); |
| 614 | let theirs = esds_asc(&std::fs::read(&mp4).expect("read mp4")) |
| 615 | .expect("the muxer wrote a DecoderSpecificInfo"); |
| 616 | let ours = ec_aac::audio_specific_config_bytes(rate, channels); |
| 617 | assert_eq!( |
| 618 | ours, theirs, |
| 619 | "{channels}ch/{rate}Hz ASC differs from the reference muxer's" |
| 620 | ); |
| 621 | |
| 622 | let cfg = ec_aac::parse_audio_specific_config(&ours).expect("asc parses"); |
| 623 | assert_eq!((cfg.sample_rate, cfg.channels), (rate, channels)); |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | |
| 628 | |
| 629 | fn esds_asc(mp4: &[u8]) -> Option<Vec<u8>> { |
| 630 | |
| 631 | |
| 632 | |
| 633 | |
| 634 | let at = mp4.windows(4).position(|w| w == b"esds")?; |
| 635 | let mut i = at + 4 + 4; |
| 636 | while i < mp4.len() { |
| 637 | let tag = mp4[i]; |
| 638 | i += 1; |
| 639 | let mut len = 0usize; |
| 640 | loop { |
| 641 | let b = *mp4.get(i)?; |
| 642 | i += 1; |
| 643 | len = (len << 7) | usize::from(b & 0x7F); |
| 644 | if b & 0x80 == 0 { |
| 645 | break; |
| 646 | } |
| 647 | } |
| 648 | match tag { |
| 649 | 0x05 => return mp4.get(i..i + len).map(<[u8]>::to_vec), |
| 650 | |
| 651 | |
| 652 | 0x03 => { |
| 653 | let flags = *mp4.get(i + 2)?; |
| 654 | i += 3; |
| 655 | if flags & 0x80 != 0 { |
| 656 | i += 2; |
| 657 | } |
| 658 | if flags & 0x40 != 0 { |
| 659 | let url_len = usize::from(*mp4.get(i)?); |
| 660 | i += 1 + url_len; |
| 661 | } |
| 662 | if flags & 0x20 != 0 { |
| 663 | i += 2; |
| 664 | } |
| 665 | } |
| 666 | |
| 667 | |
| 668 | |
| 669 | 0x04 => i += 13, |
| 670 | |
| 671 | _ => i += len, |
| 672 | } |
| 673 | } |
| 674 | None |
| 675 | } |
| 676 | |
| 677 | |
| 678 | |
| 679 | #[test] |
| 680 | fn real_library_tracks_match_ffmpeg() { |
| 681 | if !have_ffmpeg() { |
| 682 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 683 | return; |
| 684 | } |
| 685 | let manifest = fixtures().join("real-library-manifest.tsv"); |
| 686 | let Ok(text) = std::fs::read_to_string(&manifest) else { |
| 687 | eprintln!("SKIP: no real-library manifest; run scripts/scan-real-library.sh"); |
| 688 | return; |
| 689 | }; |
| 690 | let tmp = std::env::temp_dir().join("ec-aac-real"); |
| 691 | std::fs::create_dir_all(&tmp).expect("temp dir"); |
| 692 | let mut stereo = 0; |
| 693 | let mut wide = 0; |
| 694 | let mut checked = 0; |
| 695 | for line in text.lines().skip(1) { |
| 696 | if stereo >= 3 && wide >= 2 { |
| 697 | break; |
| 698 | } |
| 699 | let path = line.split('\t').next().unwrap_or_default(); |
| 700 | if path.is_empty() || !line.to_lowercase().contains("aac") { |
| 701 | continue; |
| 702 | } |
| 703 | let file = Path::new(path); |
| 704 | if !file.exists() { |
| 705 | continue; |
| 706 | } |
| 707 | let Some((index, channels, profile)) = aac_stream(file) else { |
| 708 | continue; |
| 709 | }; |
| 710 | |
| 711 | if profile.contains("HE-AAC") { |
| 712 | continue; |
| 713 | } |
| 714 | if channels <= 2 { |
| 715 | if stereo >= 3 { |
| 716 | continue; |
| 717 | } |
| 718 | stereo += 1; |
| 719 | } else { |
| 720 | if wide >= 2 { |
| 721 | continue; |
| 722 | } |
| 723 | wide += 1; |
| 724 | } |
| 725 | let adts = tmp.join(format!("real-{checked}.aac")); |
| 726 | let out = Command::new("ffmpeg") |
| 727 | .args(["-v", "error", "-y", "-t", "20", "-i"]) |
| 728 | .arg(file) |
| 729 | .args(["-map", &format!("0:{index}"), "-c:a", "copy", "-f", "adts"]) |
| 730 | .arg(&adts) |
| 731 | .output() |
| 732 | .expect("ffmpeg runs"); |
| 733 | if !out.status.success() { |
| 734 | eprintln!("SKIP {path}: stream copy failed"); |
| 735 | continue; |
| 736 | } |
| 737 | let corr = compare(&adts); |
| 738 | let worst = corr.iter().copied().fold(f64::MAX, f64::min); |
| 739 | println!( |
| 740 | "real {channels}ch {profile} worst {worst:.6} -- {}", |
| 741 | file.file_name().unwrap_or_default().to_string_lossy() |
| 742 | ); |
| 743 | for (ch, c) in corr.iter().enumerate() { |
| 744 | assert!( |
| 745 | *c >= 0.999, |
| 746 | "channel {ch} correlation {c:.6} < 0.999 for {path}" |
| 747 | ); |
| 748 | } |
| 749 | checked += 1; |
| 750 | } |
| 751 | assert!( |
| 752 | checked >= 3, |
| 753 | "wanted at least three library tracks, swept {checked}" |
| 754 | ); |
| 755 | assert!(wide >= 1, "no multichannel AAC track was swept"); |
| 756 | } |
| 757 | |
| 758 | |
| 759 | fn aac_stream(path: &Path) -> Option<(usize, usize, String)> { |
| 760 | let out = Command::new("ffprobe") |
| 761 | .args([ |
| 762 | "-v", |
| 763 | "error", |
| 764 | "-select_streams", |
| 765 | "a", |
| 766 | "-show_entries", |
| 767 | "stream=index,codec_name,channels,profile", |
| 768 | "-of", |
| 769 | "default=noprint_wrappers=1", |
| 770 | ]) |
| 771 | .arg(path) |
| 772 | .output() |
| 773 | .ok()?; |
| 774 | let text = String::from_utf8_lossy(&out.stdout); |
| 775 | let (mut index, mut channels, mut codec, mut profile) = |
| 776 | (None, None, String::new(), String::new()); |
| 777 | for line in text.lines() { |
| 778 | let (key, value) = line.split_once('=')?; |
| 779 | match key { |
| 780 | "index" => { |
| 781 | if codec == "aac" { |
| 782 | return Some((index?, channels?, profile)); |
| 783 | } |
| 784 | index = value.parse().ok(); |
| 785 | codec.clear(); |
| 786 | profile.clear(); |
| 787 | } |
| 788 | "codec_name" => codec = value.to_string(), |
| 789 | "channels" => channels = value.parse().ok(), |
| 790 | "profile" => profile = value.to_string(), |
| 791 | _ => {} |
| 792 | } |
| 793 | } |
| 794 | if codec == "aac" { |
| 795 | return Some((index?, channels?, profile)); |
| 796 | } |
| 797 | None |
| 798 | } |
| 799 | |
| 800 | |
| 801 | #[test] |
| 802 | fn five_one_decodes_faster_than_realtime() { |
| 803 | let path = fixtures().join("audio/aac-adts-5.1-48000.aac"); |
| 804 | if !path.exists() { |
| 805 | eprintln!("SKIP: 5.1 fixture missing"); |
| 806 | return; |
| 807 | } |
| 808 | let data = std::fs::read(&path).expect("fixture readable"); |
| 809 | let rounds = 8; |
| 810 | let start = std::time::Instant::now(); |
| 811 | let mut frames = 0usize; |
| 812 | let mut rate = 48_000u32; |
| 813 | for _ in 0..rounds { |
| 814 | let mut decoder = AacDecoder::new(); |
| 815 | let mut at = 0usize; |
| 816 | frames = 0; |
| 817 | while at + 7 <= data.len() { |
| 818 | let header = ec_aac::parse_adts(&data[at..]).expect("adts header"); |
| 819 | let end = (at + header.frame_length).min(data.len()); |
| 820 | let block = decoder.decode(&data[at..end], None).expect("decodes"); |
| 821 | rate = block.sample_rate; |
| 822 | frames += block.frames(); |
| 823 | at = end; |
| 824 | } |
| 825 | } |
| 826 | let audio = (frames * rounds) as f64 / f64::from(rate); |
| 827 | let factor = audio / start.elapsed().as_secs_f64(); |
| 828 | println!( |
| 829 | "5.1 decode: {factor:.0}x realtime ({} build)", |
| 830 | if cfg!(debug_assertions) { |
| 831 | "debug" |
| 832 | } else { |
| 833 | "release" |
| 834 | } |
| 835 | ); |
| 836 | if !cfg!(debug_assertions) { |
| 837 | assert!( |
| 838 | factor >= 40.0, |
| 839 | "5.1 decode {factor:.0}x realtime is under 40x" |
| 840 | ); |
| 841 | } |
| 842 | } |
| 843 | |
| 844 | |
| 845 | |
| 846 | |
| 847 | #[test] |
| 848 | fn he_aac_library_track_decodes_to_its_core() { |
| 849 | if !have_ffmpeg() { |
| 850 | eprintln!("SKIP: ffmpeg not on PATH"); |
| 851 | return; |
| 852 | } |
| 853 | let manifest = fixtures().join("real-library-manifest.tsv"); |
| 854 | let Ok(text) = std::fs::read_to_string(&manifest) else { |
| 855 | eprintln!("SKIP: no real-library manifest"); |
| 856 | return; |
| 857 | }; |
| 858 | let tmp = std::env::temp_dir().join("ec-aac-he"); |
| 859 | std::fs::create_dir_all(&tmp).expect("temp dir"); |
| 860 | for line in text.lines().skip(1) { |
| 861 | let path = line.split('\t').next().unwrap_or_default(); |
| 862 | let file = Path::new(path); |
| 863 | if path.is_empty() || !file.exists() { |
| 864 | continue; |
| 865 | } |
| 866 | let Some((index, _, profile)) = aac_stream_matching(file, "HE-AAC") else { |
| 867 | continue; |
| 868 | }; |
| 869 | let _ = profile; |
| 870 | let adts = tmp.join("he.aac"); |
| 871 | let out = Command::new("ffmpeg") |
| 872 | .args(["-v", "error", "-y", "-t", "10", "-i"]) |
| 873 | .arg(file) |
| 874 | .args(["-map", &format!("0:{index}"), "-c:a", "copy", "-f", "adts"]) |
| 875 | .arg(&adts) |
| 876 | .output() |
| 877 | .expect("ffmpeg runs"); |
| 878 | if !out.status.success() { |
| 879 | continue; |
| 880 | } |
| 881 | let (ours, rate) = our_decode(&adts); |
| 882 | assert!(!ours.is_empty(), "the HE-AAC core decoded to nothing"); |
| 883 | |
| 884 | |
| 885 | |
| 886 | let core = tmp.join("he-core.f32"); |
| 887 | let out = Command::new("ffmpeg") |
| 888 | .args(["-v", "error", "-y", "-i"]) |
| 889 | .arg(&adts) |
| 890 | .args(["-ar", &rate.to_string(), "-f", "f32le"]) |
| 891 | .arg(&core) |
| 892 | .output() |
| 893 | .expect("ffmpeg runs"); |
| 894 | assert!( |
| 895 | out.status.success(), |
| 896 | "reference decode of the HE-AAC track failed" |
| 897 | ); |
| 898 | let theirs = deinterleave( |
| 899 | &bytes_to_f32(&std::fs::read(&core).expect("read")), |
| 900 | ours.len(), |
| 901 | ); |
| 902 | |
| 903 | |
| 904 | |
| 905 | let corr: Vec<f64> = ours |
| 906 | .iter() |
| 907 | .zip(&theirs) |
| 908 | .map(|(a, b)| pearson(&band_energies(a, rate), &band_energies(b, rate))) |
| 909 | .collect(); |
| 910 | let worst = corr.iter().copied().fold(f64::MAX, f64::min); |
| 911 | println!("HE-AAC core at {rate} Hz: band-energy match, worst channel {worst:.4} {corr:?}"); |
| 912 | assert!( |
| 913 | worst >= 0.95, |
| 914 | "the AAC-LC core of an HE-AAC track should carry the reference's \ |
| 915 | core band; worst channel {worst:.4}" |
| 916 | ); |
| 917 | return; |
| 918 | } |
| 919 | eprintln!("SKIP: no HE-AAC track in the library manifest"); |
| 920 | } |
| 921 | |
| 922 | |
| 923 | fn pearson(a: &[f32], b: &[f32]) -> f64 { |
| 924 | let n = a.len().min(b.len()); |
| 925 | let ma = a[..n].iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64; |
| 926 | let mb = b[..n].iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64; |
| 927 | let (mut num, mut da, mut db) = (0.0, 0.0, 0.0); |
| 928 | for i in 0..n { |
| 929 | let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb); |
| 930 | num += x * y; |
| 931 | da += x * x; |
| 932 | db += y * y; |
| 933 | } |
| 934 | if da == 0.0 || db == 0.0 { |
| 935 | return 1.0; |
| 936 | } |
| 937 | num / (da * db).sqrt() |
| 938 | } |
| 939 | |
| 940 | |
| 941 | |
| 942 | fn band_energies(samples: &[f32], rate: u32) -> Vec<f32> { |
| 943 | let bands = 32usize; |
| 944 | let mut out = vec![0.0f64; bands]; |
| 945 | let n = 1024usize; |
| 946 | let mut blocks = 0usize; |
| 947 | for chunk in samples.chunks_exact(n).take(400) { |
| 948 | blocks += 1; |
| 949 | for (b, slot) in out.iter_mut().enumerate() { |
| 950 | |
| 951 | let lo = 100.0 * (f64::from(rate) / 2.0 / 100.0).powf(b as f64 / bands as f64); |
| 952 | let hi = 100.0 * (f64::from(rate) / 2.0 / 100.0).powf((b + 1) as f64 / bands as f64); |
| 953 | let (mut re, mut im) = (0.0f64, 0.0f64); |
| 954 | let f = (lo * hi).sqrt(); |
| 955 | let w = 2.0 * std::f64::consts::PI * f / f64::from(rate); |
| 956 | for (i, &v) in chunk.iter().enumerate() { |
| 957 | re += f64::from(v) * (w * i as f64).cos(); |
| 958 | im += f64::from(v) * (w * i as f64).sin(); |
| 959 | } |
| 960 | *slot += (re * re + im * im).sqrt(); |
| 961 | } |
| 962 | } |
| 963 | out.iter() |
| 964 | .map(|v| ((v / blocks.max(1) as f64) + 1e-9).ln() as f32) |
| 965 | .collect() |
| 966 | } |
| 967 | |
| 968 | fn aac_stream_matching(path: &Path, want: &str) -> Option<(usize, usize, String)> { |
| 969 | let out = Command::new("ffprobe") |
| 970 | .args([ |
| 971 | "-v", |
| 972 | "error", |
| 973 | "-select_streams", |
| 974 | "a", |
| 975 | "-show_entries", |
| 976 | "stream=index,codec_name,channels,profile", |
| 977 | "-of", |
| 978 | "default=noprint_wrappers=1", |
| 979 | ]) |
| 980 | .arg(path) |
| 981 | .output() |
| 982 | .ok()?; |
| 983 | let text = String::from_utf8_lossy(&out.stdout); |
| 984 | let mut index = None; |
| 985 | let mut channels = None; |
| 986 | let mut codec = String::new(); |
| 987 | let mut profile = String::new(); |
| 988 | for line in text.lines() { |
| 989 | let (key, value) = line.split_once('=')?; |
| 990 | match key { |
| 991 | "index" => { |
| 992 | if codec == "aac" && profile.contains(want) { |
| 993 | return Some((index?, channels?, profile)); |
| 994 | } |
| 995 | index = value.parse().ok(); |
| 996 | codec.clear(); |
| 997 | profile.clear(); |
| 998 | } |
| 999 | "codec_name" => codec = value.to_string(), |
| 1000 | "channels" => channels = value.parse().ok(), |
| 1001 | "profile" => profile = value.to_string(), |
| 1002 | _ => {} |
| 1003 | } |
| 1004 | } |
| 1005 | if codec == "aac" && profile.contains(want) { |
| 1006 | return Some((index?, channels?, profile)); |
| 1007 | } |
| 1008 | None |
| 1009 | } |