| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | use std::process::Command; |
| 12 | |
| 13 | use ec_ac3::{Ac3Decoder, Downmix, Options, Syntax, bsi, eac3, syncinfo}; |
| 14 | |
| 15 | |
| 16 | const MIN_CORR: f64 = 0.999; |
| 17 | |
| 18 | |
| 19 | const MAX_RMS: f64 = 1e-3; |
| 20 | |
| 21 | fn fixtures() -> PathBuf { |
| 22 | Path::new(env!("CARGO_MANIFEST_DIR")) |
| 23 | .join("../../fixtures/audio") |
| 24 | .canonicalize() |
| 25 | .unwrap_or_else(|_| PathBuf::from("../../fixtures/audio")) |
| 26 | } |
| 27 | |
| 28 | fn have_ffmpeg() -> bool { |
| 29 | Command::new("ffmpeg") |
| 30 | .arg("-version") |
| 31 | .output() |
| 32 | .is_ok_and(|o| o.status.success()) |
| 33 | } |
| 34 | |
| 35 | |
| 36 | fn reference(path: &Path) -> Vec<f32> { |
| 37 | let out = Command::new("ffmpeg") |
| 38 | .args(["-v", "error", "-i"]) |
| 39 | .arg(path) |
| 40 | .args(["-f", "f32le", "-"]) |
| 41 | .output() |
| 42 | .expect("ffmpeg"); |
| 43 | out.stdout |
| 44 | .chunks_exact(4) |
| 45 | .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) |
| 46 | .collect() |
| 47 | } |
| 48 | |
| 49 | |
| 50 | fn decode(path: &Path, options: Options) -> (Vec<f32>, usize) { |
| 51 | let data = std::fs::read(path).expect("fixture"); |
| 52 | let mut decoder = Ac3Decoder::with_options(options); |
| 53 | let (mut out, mut channels, mut pos) = (Vec::new(), 0, 0usize); |
| 54 | while pos + 6 <= data.len() { |
| 55 | if data[pos] != 0x0B || data[pos + 1] != 0x77 { |
| 56 | pos += 1; |
| 57 | continue; |
| 58 | } |
| 59 | let Ok(size) = ec_ac3::frame_size(&data[pos..]) else { |
| 60 | break; |
| 61 | }; |
| 62 | if pos + size > data.len() { |
| 63 | break; |
| 64 | } |
| 65 | let frame = decoder |
| 66 | .decode_frame(&data[pos..pos + size]) |
| 67 | .unwrap_or_else(|e| panic!("{}: {e}", path.display())); |
| 68 | channels = frame.channels(); |
| 69 | out.extend( |
| 70 | frame.data[0] |
| 71 | .chunks_exact(4) |
| 72 | .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])), |
| 73 | ); |
| 74 | pos += size; |
| 75 | } |
| 76 | (out, channels) |
| 77 | } |
| 78 | |
| 79 | fn correlation(a: &[f32], b: &[f32]) -> (f64, f64) { |
| 80 | let n = a.len().min(b.len()); |
| 81 | let (mut sa, mut sb, mut saa, mut sbb, mut sab, mut sd) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0); |
| 82 | for i in 0..n { |
| 83 | let (x, y) = (f64::from(a[i]), f64::from(b[i])); |
| 84 | sa += x; |
| 85 | sb += y; |
| 86 | saa += x * x; |
| 87 | sbb += y * y; |
| 88 | sab += x * y; |
| 89 | sd += (x - y) * (x - y); |
| 90 | } |
| 91 | let n = n as f64; |
| 92 | let cov = sab / n - (sa / n) * (sb / n); |
| 93 | let va = saa / n - (sa / n).powi(2); |
| 94 | let vb = sbb / n - (sb / n).powi(2); |
| 95 | let corr = if va <= 0.0 || vb <= 0.0 { |
| 96 | 1.0 |
| 97 | } else { |
| 98 | cov / (va * vb).sqrt() |
| 99 | }; |
| 100 | (corr, (sd / n).sqrt()) |
| 101 | } |
| 102 | |
| 103 | #[test] |
| 104 | fn fixture_matrix_matches_ffmpeg() { |
| 105 | let dir = fixtures(); |
| 106 | if !dir.exists() || !have_ffmpeg() { |
| 107 | eprintln!("skipping: no fixtures or no ffmpeg"); |
| 108 | return; |
| 109 | } |
| 110 | let mut checked = 0; |
| 111 | for entry in std::fs::read_dir(&dir).expect("fixtures dir") { |
| 112 | let path = entry.expect("entry").path(); |
| 113 | let name = path.file_name().unwrap_or_default().to_string_lossy(); |
| 114 | if !(name.starts_with("ac3-") || name.starts_with("eac3-")) { |
| 115 | continue; |
| 116 | } |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | let options = Options { |
| 122 | dither: false, |
| 123 | ..Options::default() |
| 124 | }; |
| 125 | let (ours, channels) = decode(&path, options); |
| 126 | let theirs = reference(&path); |
| 127 | assert!(channels > 0, "{name}: no channels"); |
| 128 | assert_eq!( |
| 129 | ours.len(), |
| 130 | theirs.len(), |
| 131 | "{name}: {} samples vs ffmpeg's {}", |
| 132 | ours.len(), |
| 133 | theirs.len() |
| 134 | ); |
| 135 | for ch in 0..channels { |
| 136 | let a: Vec<f32> = ours[ch..].iter().step_by(channels).copied().collect(); |
| 137 | let b: Vec<f32> = theirs[ch..].iter().step_by(channels).copied().collect(); |
| 138 | let (corr, rms) = correlation(&a, &b); |
| 139 | assert!(corr >= MIN_CORR, "{name} ch{ch}: correlation {corr:.6}"); |
| 140 | assert!(rms <= MAX_RMS, "{name} ch{ch}: RMS delta {rms:.8}"); |
| 141 | } |
| 142 | checked += 1; |
| 143 | } |
| 144 | assert!(checked >= 12, "only {checked} fixtures checked"); |
| 145 | } |
| 146 | |
| 147 | #[test] |
| 148 | fn dither_only_adds_noise_below_the_signal() { |
| 149 | let path = fixtures().join("ac3-5.1-48000.ac3"); |
| 150 | if !path.exists() { |
| 151 | return; |
| 152 | } |
| 153 | let (with, channels) = decode(&path, Options::default()); |
| 154 | let (without, _) = decode( |
| 155 | &path, |
| 156 | Options { |
| 157 | dither: false, |
| 158 | ..Options::default() |
| 159 | }, |
| 160 | ); |
| 161 | assert_eq!(with.len(), without.len()); |
| 162 | let (corr, rms) = correlation(&with, &without); |
| 163 | assert!(channels == 6 && corr > 0.999, "correlation {corr:.6}"); |
| 164 | assert!(rms < 1e-3, "dither RMS {rms:.8}"); |
| 165 | } |
| 166 | |
| 167 | #[test] |
| 168 | fn headers_state_what_the_container_needs() { |
| 169 | let path = fixtures().join("ac3-5.1-48000.ac3"); |
| 170 | if !path.exists() { |
| 171 | return; |
| 172 | } |
| 173 | let data = std::fs::read(&path).expect("fixture"); |
| 174 | |
| 175 | |
| 176 | let sync = syncinfo::parse(&data).expect("syncinfo"); |
| 177 | assert_eq!(sync.sample_rate, 48_000); |
| 178 | assert_eq!(sync.frame_size % 2, 0); |
| 179 | let bsi = bsi::parse(&data[5..]).expect("bsi"); |
| 180 | assert_eq!(bsi.nfchans, 5); |
| 181 | assert!(bsi.lfeon); |
| 182 | assert_eq!(bsi.channels, 6); |
| 183 | assert!((1..=31).contains(&bsi.dialnorm)); |
| 184 | |
| 185 | let eac3_path = fixtures().join("eac3-5.1-48000.eac3"); |
| 186 | let data = std::fs::read(&eac3_path).expect("fixture"); |
| 187 | let hdr = eac3::bsi::parse(&data[2..]).expect("eac3 bsi"); |
| 188 | assert_eq!(hdr.sample_rate, 48_000); |
| 189 | assert_eq!(hdr.nfchans, 5); |
| 190 | assert!(hdr.bsi.lfeon); |
| 191 | assert_eq!( |
| 192 | hdr.frame_size, |
| 193 | ec_ac3::frame_size(&data).expect("frame size") |
| 194 | ); |
| 195 | } |
| 196 | |
| 197 | #[test] |
| 198 | fn frame_info_surfaces_the_metadata_the_rubric_asks_for() { |
| 199 | let path = fixtures().join("ac3-5.1-48000.ac3"); |
| 200 | if !path.exists() { |
| 201 | return; |
| 202 | } |
| 203 | let data = std::fs::read(&path).expect("fixture"); |
| 204 | let size = ec_ac3::frame_size(&data).expect("frame size"); |
| 205 | let mut decoder = Ac3Decoder::new(); |
| 206 | decoder.decode_frame(&data[..size]).expect("decode"); |
| 207 | let info = decoder.frame_info().expect("frame info"); |
| 208 | assert_eq!(info.syntax, Syntax::Ac3); |
| 209 | assert_eq!(info.sample_rate, 48_000); |
| 210 | assert!((1..=31).contains(&info.dialnorm)); |
| 211 | |
| 212 | assert_eq!(info.center_mix_level, Some(0.595)); |
| 213 | assert_eq!(info.surround_mix_level, Some(0.5)); |
| 214 | assert_eq!(info.samples, 1536); |
| 215 | } |
| 216 | |
| 217 | #[test] |
| 218 | fn stereo_downmix_folds_five_one_without_clipping() { |
| 219 | let path = fixtures().join("ac3-5.1-48000.ac3"); |
| 220 | if !path.exists() { |
| 221 | return; |
| 222 | } |
| 223 | let (stereo, channels) = decode( |
| 224 | &path, |
| 225 | Options { |
| 226 | downmix: Downmix::Stereo, |
| 227 | ..Options::default() |
| 228 | }, |
| 229 | ); |
| 230 | assert_eq!(channels, 2); |
| 231 | let (native, _) = decode(&path, Options::default()); |
| 232 | assert_eq!(stereo.len() * 3, native.len()); |
| 233 | assert!(stereo.iter().all(|v| v.abs() <= 1.0), "downmix clipped"); |
| 234 | assert!(stereo.iter().any(|v| v.abs() > 0.01), "downmix is silent"); |
| 235 | |
| 236 | let (mono, channels) = decode( |
| 237 | &path, |
| 238 | Options { |
| 239 | downmix: Downmix::Mono, |
| 240 | ..Options::default() |
| 241 | }, |
| 242 | ); |
| 243 | assert_eq!(channels, 1); |
| 244 | assert_eq!(mono.len() * 6, native.len()); |
| 245 | } |
| 246 | |
| 247 | #[test] |
| 248 | fn damaged_input_never_panics() { |
| 249 | let path = fixtures().join("ac3-stereo-48000.ac3"); |
| 250 | if !path.exists() { |
| 251 | return; |
| 252 | } |
| 253 | let data = std::fs::read(&path).expect("fixture"); |
| 254 | let size = ec_ac3::frame_size(&data).expect("frame size"); |
| 255 | let frame = &data[..size]; |
| 256 | let mut decoder = Ac3Decoder::new(); |
| 257 | |
| 258 | |
| 259 | for cut in 0..frame.len() { |
| 260 | let _ = decoder.decode_frame(&frame[..cut]); |
| 261 | } |
| 262 | |
| 263 | |
| 264 | for pos in (0..frame.len()).step_by(7) { |
| 265 | let mut broken = frame.to_vec(); |
| 266 | broken[pos] ^= 0xA5; |
| 267 | let _ = decoder.decode_frame(&broken); |
| 268 | } |
| 269 | |
| 270 | let mut noise = vec![0x0B, 0x77]; |
| 271 | let mut state = 12345u32; |
| 272 | for _ in 0..4096 { |
| 273 | state = state.wrapping_mul(1_103_515_245).wrapping_add(12345); |
| 274 | noise.push((state >> 16) as u8); |
| 275 | } |
| 276 | let _ = decoder.decode_frame(&noise); |
| 277 | } |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 285 | |
| 286 | |
| 287 | |
| 288 | #[test] |
| 289 | fn a_concatenated_tail_is_refused_by_name_not_dropped() { |
| 290 | let dir = fixtures(); |
| 291 | if !dir.join("eac3-5.1-48000.eac3").exists() { |
| 292 | eprintln!("skipping: no fixtures"); |
| 293 | return; |
| 294 | } |
| 295 | for name in ["ac3-5.1-48000.ac3", "eac3-5.1-48000.eac3"] { |
| 296 | let data = std::fs::read(dir.join(name)).expect("fixture"); |
| 297 | let first = ec_ac3::frame_size(&data).expect("first frame size"); |
| 298 | let second = ec_ac3::frame_size(&data[first..]).expect("second frame size"); |
| 299 | let mut packet = data[..first].to_vec(); |
| 300 | packet.extend_from_slice(&data[first..first + second]); |
| 301 | |
| 302 | let mut dec = Ac3Decoder::new(); |
| 303 | let err = dec |
| 304 | .decode_frame(&packet) |
| 305 | .expect_err("{name}: the tail is stream, not padding"); |
| 306 | let text = err.to_string(); |
| 307 | eprintln!("{name}: {text}"); |
| 308 | assert!( |
| 309 | text.contains("second syncframe"), |
| 310 | "{name}: the independent tail must name itself: {text}" |
| 311 | ); |
| 312 | if name.starts_with("eac3") { |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | let mut dep_packet = packet.clone(); |
| 318 | dep_packet[first + 2] = (dep_packet[first + 2] & 0x3F) | 0x40; |
| 319 | let err = dec |
| 320 | .decode_frame(&dep_packet) |
| 321 | .expect_err("the dependent tail is stream"); |
| 322 | let text = err.to_string(); |
| 323 | eprintln!("{name} (tail flipped to dependent): {text}"); |
| 324 | assert!( |
| 325 | text.contains("dependent substream"), |
| 326 | "the dependent tail must name itself: {text}" |
| 327 | ); |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 335 | #[test] |
| 336 | fn padding_that_is_not_a_syncframe_still_decodes() { |
| 337 | let path = fixtures().join("ac3-5.1-48000.ac3"); |
| 338 | if !path.exists() { |
| 339 | eprintln!("skipping: no fixtures"); |
| 340 | return; |
| 341 | } |
| 342 | let data = std::fs::read(&path).expect("fixture"); |
| 343 | let first = ec_ac3::frame_size(&data).expect("frame size"); |
| 344 | let frame = &data[..first]; |
| 345 | let mut dec = Ac3Decoder::new(); |
| 346 | let bare = dec.decode_frame(frame).expect("bare frame"); |
| 347 | for pad in [1usize, 6, 64, 1024] { |
| 348 | let mut padded = frame.to_vec(); |
| 349 | padded.resize(first + pad, 0x00); |
| 350 | let mut dec = Ac3Decoder::new(); |
| 351 | let got = dec.decode_frame(&padded).expect("padded frame decodes"); |
| 352 | assert!( |
| 353 | got.data[0].iter().eq(bare.data[0].iter()), |
| 354 | "pad of {pad} bytes changed the audio" |
| 355 | ); |
| 356 | } |
| 357 | } |