| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | use std::path::PathBuf; |
| 14 | use std::process::Command; |
| 15 | |
| 16 | use ec_mp3::{FrameHeader, Mp3Reader}; |
| 17 | |
| 18 | fn required() -> bool { |
| 19 | std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0") |
| 20 | } |
| 21 | |
| 22 | fn have_ffmpeg() -> bool { |
| 23 | let ok = Command::new("ffmpeg") |
| 24 | .arg("-version") |
| 25 | .output() |
| 26 | .is_ok_and(|o| o.status.success()); |
| 27 | if !ok { |
| 28 | assert!( |
| 29 | !required(), |
| 30 | "EC_REQUIRE_FIXTURES is set but ffmpeg is missing" |
| 31 | ); |
| 32 | eprintln!("skip: ffmpeg not available"); |
| 33 | } |
| 34 | ok |
| 35 | } |
| 36 | |
| 37 | fn work_dir() -> PathBuf { |
| 38 | let d = std::env::temp_dir().join("ec-mp2-matrix"); |
| 39 | std::fs::create_dir_all(&d).unwrap(); |
| 40 | d |
| 41 | } |
| 42 | |
| 43 | fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: u8) -> Vec<f32> { |
| 44 | let decoder = if layer == 1 { "mp1float" } else { "mp2float" }; |
| 45 | let out = Command::new("ffmpeg") |
| 46 | .args(["-v", "error", "-c:a", decoder, "-i"]) |
| 47 | .arg(path) |
| 48 | .args(["-ac", &channels.to_string(), "-f", "f32le", "-"]) |
| 49 | .output() |
| 50 | .expect("ffmpeg"); |
| 51 | assert!( |
| 52 | out.status.success(), |
| 53 | "ffmpeg: {}", |
| 54 | String::from_utf8_lossy(&out.stderr) |
| 55 | ); |
| 56 | out.stdout |
| 57 | .as_chunks::<4>() |
| 58 | .0 |
| 59 | .iter() |
| 60 | .map(|b| f32::from_le_bytes(*b)) |
| 61 | .collect() |
| 62 | } |
| 63 | |
| 64 | |
| 65 | fn ffmpeg_decode_s16(path: &std::path::Path, channels: usize, layer: u8) -> Vec<i16> { |
| 66 | let decoder = if layer == 1 { "mp1" } else { "mp2" }; |
| 67 | let out = Command::new("ffmpeg") |
| 68 | .args(["-v", "error", "-c:a", decoder, "-i"]) |
| 69 | .arg(path) |
| 70 | .args(["-ac", &channels.to_string(), "-f", "s16le", "-"]) |
| 71 | .output() |
| 72 | .expect("ffmpeg"); |
| 73 | assert!(out.status.success()); |
| 74 | out.stdout |
| 75 | .as_chunks::<2>() |
| 76 | .0 |
| 77 | .iter() |
| 78 | .map(|b| i16::from_le_bytes(*b)) |
| 79 | .collect() |
| 80 | } |
| 81 | |
| 82 | |
| 83 | |
| 84 | fn s16_agreement(got: &[f32], want: &[i16]) -> (i32, f64) { |
| 85 | let n = got.len().min(want.len()); |
| 86 | let (mut worst, mut equal) = (0i32, 0usize); |
| 87 | for i in 0..n { |
| 88 | let g = (got[i] * 32768.0).round().clamp(-32768.0, 32767.0) as i32; |
| 89 | let d = (g - i32::from(want[i])).abs(); |
| 90 | worst = worst.max(d); |
| 91 | equal += usize::from(d == 0); |
| 92 | } |
| 93 | (worst, equal as f64 / n.max(1) as f64) |
| 94 | } |
| 95 | |
| 96 | fn our_decode(bytes: &[u8]) -> (Vec<f32>, u32, usize) { |
| 97 | let mut reader = Mp3Reader::new(); |
| 98 | reader.push(bytes); |
| 99 | let mut out = Vec::new(); |
| 100 | let (mut rate, mut ch) = (0, 0); |
| 101 | while let Ok(frame) = reader.next_frame() { |
| 102 | rate = frame.sample_rate; |
| 103 | ch = frame.channels; |
| 104 | out.extend_from_slice(&frame.samples); |
| 105 | } |
| 106 | (out, rate, ch) |
| 107 | } |
| 108 | |
| 109 | fn max_err(a: &[f32], b: &[f32]) -> (f32, usize) { |
| 110 | let n = a.len().min(b.len()); |
| 111 | let mut worst = (0.0f32, 0usize); |
| 112 | for i in 0..n { |
| 113 | let e = (a[i] - b[i]).abs(); |
| 114 | if e > worst.0 { |
| 115 | worst = (e, i); |
| 116 | } |
| 117 | } |
| 118 | worst |
| 119 | } |
| 120 | |
| 121 | struct Rng(u64); |
| 122 | impl Rng { |
| 123 | fn next(&mut self) -> u64 { |
| 124 | self.0 ^= self.0 << 13; |
| 125 | self.0 ^= self.0 >> 7; |
| 126 | self.0 ^= self.0 << 17; |
| 127 | self.0 |
| 128 | } |
| 129 | fn byte(&mut self) -> u8 { |
| 130 | (self.next() >> 24) as u8 |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | #[test] |
| 135 | fn encoder_streams_match_ffmpeg() { |
| 136 | if !have_ffmpeg() { |
| 137 | return; |
| 138 | } |
| 139 | let dir = work_dir(); |
| 140 | let sources = [ |
| 141 | "sine=frequency=1000:sample_rate={R}:duration=1.5", |
| 142 | "anoisesrc=color=pink:amplitude=0.4:sample_rate={R}:duration=1.5:seed=7", |
| 143 | "aevalsrc=0.5*sin(2*PI*(100+3000*t)*t):s={R}:d=1.5", |
| 144 | ]; |
| 145 | let cases: &[(&str, u32, u32, &str)] = &[ |
| 146 | ("mp2", 32000, 1, "32k"), |
| 147 | ("mp2", 44100, 2, "128k"), |
| 148 | ("mp2", 48000, 2, "384k"), |
| 149 | ("mp2", 48000, 1, "64k"), |
| 150 | ("mp2", 44100, 1, "192k"), |
| 151 | ("mp2", 44100, 2, "64k"), |
| 152 | ("mp2", 32000, 2, "96k"), |
| 153 | ("mp2", 16000, 1, "32k"), |
| 154 | ("mp2", 22050, 2, "64k"), |
| 155 | ("mp2", 24000, 2, "128k"), |
| 156 | ("mp2", 24000, 1, "8k"), |
| 157 | ("mp2fixed", 44100, 2, "192k"), |
| 158 | ("mp2fixed", 22050, 1, "48k"), |
| 159 | ]; |
| 160 | let mut worst_all = 0.0f32; |
| 161 | for (n, &(codec, rate, ch, br)) in cases.iter().enumerate() { |
| 162 | let src = sources[n % sources.len()].replace("{R}", &rate.to_string()); |
| 163 | let path = dir.join(format!("enc-{n}.mp2")); |
| 164 | let st = Command::new("ffmpeg") |
| 165 | .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"]) |
| 166 | .arg(ch.to_string()) |
| 167 | .args(["-c:a", codec, "-b:a", br]) |
| 168 | .arg(&path) |
| 169 | .status() |
| 170 | .unwrap(); |
| 171 | assert!(st.success(), "ffmpeg encode {codec} {rate} {ch} {br}"); |
| 172 | let bytes = std::fs::read(&path).unwrap(); |
| 173 | let want = ffmpeg_decode(&path, ch as usize, 2); |
| 174 | let (got, r, c) = our_decode(&bytes); |
| 175 | assert_eq!((r, c), (rate, ch as usize), "{codec} {rate} {ch} {br}"); |
| 176 | assert_eq!(got.len(), want.len(), "{codec} {rate} {ch} {br}: length"); |
| 177 | let (e, at) = max_err(&got, &want); |
| 178 | let (lsb, same) = s16_agreement(&got, &ffmpeg_decode_s16(&path, ch as usize, 2)); |
| 179 | eprintln!( |
| 180 | "{codec} {rate} Hz ch={ch} {br}: max abs error {e:.3e} (at {at}); vs fixed-point s16: max {lsb} LSB, {:.2}% identical", |
| 181 | same * 100.0 |
| 182 | ); |
| 183 | worst_all = worst_all.max(e); |
| 184 | assert!(e <= 1e-5, "{codec} {rate} {ch} {br}: max error {e} at {at}"); |
| 185 | } |
| 186 | eprintln!("worst over the encoder matrix: {worst_all:.3e}"); |
| 187 | } |
| 188 | |
| 189 | |
| 190 | struct BitW { |
| 191 | bytes: Vec<u8>, |
| 192 | bits: usize, |
| 193 | } |
| 194 | impl BitW { |
| 195 | fn new() -> BitW { |
| 196 | BitW { |
| 197 | bytes: Vec::new(), |
| 198 | bits: 0, |
| 199 | } |
| 200 | } |
| 201 | fn put(&mut self, v: u32, n: u32) { |
| 202 | for i in (0..n).rev() { |
| 203 | if self.bits.is_multiple_of(8) { |
| 204 | self.bytes.push(0); |
| 205 | } |
| 206 | if (v >> i) & 1 == 1 { |
| 207 | *self.bytes.last_mut().unwrap() |= 0x80 >> (self.bits % 8); |
| 208 | } |
| 209 | self.bits += 1; |
| 210 | } |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | |
| 215 | |
| 216 | fn l2_rows(table: usize) -> Vec<Vec<u32>> { |
| 217 | let a = vec![ |
| 218 | 0, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, |
| 219 | ]; |
| 220 | let b = vec![ |
| 221 | 0, 3, 5, 7, 9, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 65535, |
| 222 | ]; |
| 223 | let c = vec![0, 3, 5, 7, 9, 15, 31, 65535]; |
| 224 | let d = vec![0, 3, 5, 65535]; |
| 225 | let e = vec![ |
| 226 | 0, 3, 5, 9, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, |
| 227 | ]; |
| 228 | let f = vec![0, 3, 5, 9, 15, 31, 63, 127]; |
| 229 | let g = vec![ |
| 230 | 0, 3, 5, 7, 9, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, |
| 231 | ]; |
| 232 | let h = vec![0, 3, 5, 9]; |
| 233 | let runs: Vec<(&Vec<u32>, usize)> = match table { |
| 234 | 0 => vec![(&a, 3), (&b, 8), (&c, 12), (&d, 4)], |
| 235 | 1 => vec![(&a, 3), (&b, 8), (&c, 12), (&d, 7)], |
| 236 | 2 => vec![(&e, 2), (&f, 6)], |
| 237 | 3 => vec![(&e, 2), (&f, 10)], |
| 238 | _ => vec![(&g, 4), (&f, 7), (&h, 19)], |
| 239 | }; |
| 240 | runs.into_iter() |
| 241 | .flat_map(|(r, n)| std::iter::repeat_n(r.clone(), n)) |
| 242 | .collect() |
| 243 | } |
| 244 | |
| 245 | fn l2_table(h: &FrameHeader) -> usize { |
| 246 | if h.version != ec_mp3::Version::Mpeg1 { |
| 247 | return 4; |
| 248 | } |
| 249 | let ch = h.bitrate_kbps / h.channels() as u32; |
| 250 | let r = h.sample_rate; |
| 251 | if (r == 48000 && ch >= 56) || (56..=80).contains(&ch) { |
| 252 | 0 |
| 253 | } else if r != 48000 && ch >= 96 { |
| 254 | 1 |
| 255 | } else if r != 32000 && ch <= 48 { |
| 256 | 2 |
| 257 | } else { |
| 258 | 3 |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec<u8>> { |
| 266 | let channels = h.channels(); |
| 267 | let joint = h.mode == ec_mp3::ChannelMode::JointStereo; |
| 268 | let mut w = BitW::new(); |
| 269 | let rnd = |rng: &mut Rng, n: u32| (rng.next() >> 20) as u32 % n.max(1); |
| 270 | let (nb_sb, bound); |
| 271 | let rows: Vec<Vec<u32>>; |
| 272 | if h.layer == 1 { |
| 273 | nb_sb = 32; |
| 274 | rows = Vec::new(); |
| 275 | } else { |
| 276 | rows = l2_rows(l2_table(h)); |
| 277 | nb_sb = rows.len(); |
| 278 | } |
| 279 | bound = if joint { |
| 280 | (4 + 4 * h.mode_ext as usize).min(nb_sb) |
| 281 | } else { |
| 282 | nb_sb |
| 283 | }; |
| 284 | |
| 285 | let mut alloc = vec![vec![0u32; nb_sb]; 2]; |
| 286 | let width = |sb: usize| -> u32 { |
| 287 | if h.layer == 1 { |
| 288 | 4 |
| 289 | } else { |
| 290 | rows[sb].len().trailing_zeros() |
| 291 | } |
| 292 | }; |
| 293 | for sb in 0..nb_sb { |
| 294 | let maxcode = if h.layer == 1 { |
| 295 | 15 |
| 296 | } else { |
| 297 | rows[sb].len() as u32 |
| 298 | }; |
| 299 | let pick = |rng: &mut Rng| { |
| 300 | if rnd(rng, 100) < density { |
| 301 | 1 + rnd(rng, maxcode - 1) |
| 302 | } else { |
| 303 | 0 |
| 304 | } |
| 305 | }; |
| 306 | for ch in 0..channels { |
| 307 | alloc[ch][sb] = if sb < bound || ch == 0 { |
| 308 | pick(rng) |
| 309 | } else { |
| 310 | alloc[0][sb] |
| 311 | }; |
| 312 | } |
| 313 | if sb >= bound && channels == 2 { |
| 314 | alloc[1][sb] = alloc[0][sb]; |
| 315 | } |
| 316 | } |
| 317 | for sb in 0..nb_sb { |
| 318 | if sb < bound { |
| 319 | for a in alloc.iter().take(channels) { |
| 320 | w.put(a[sb], width(sb)); |
| 321 | } |
| 322 | } else { |
| 323 | w.put(alloc[0][sb], width(sb)); |
| 324 | } |
| 325 | } |
| 326 | let mut scfsi = vec![vec![0u32; nb_sb]; 2]; |
| 327 | if h.layer == 2 { |
| 328 | for sb in 0..nb_sb { |
| 329 | for ch in 0..channels { |
| 330 | if alloc[ch][sb] != 0 { |
| 331 | scfsi[ch][sb] = rnd(rng, 4); |
| 332 | w.put(scfsi[ch][sb], 2); |
| 333 | } |
| 334 | } |
| 335 | } |
| 336 | } |
| 337 | let protected_bits = w.bits; |
| 338 | let protected: Vec<u8> = w.bytes.clone(); |
| 339 | for sb in 0..nb_sb { |
| 340 | for ch in 0..channels { |
| 341 | if alloc[ch][sb] == 0 { |
| 342 | continue; |
| 343 | } |
| 344 | let n = if h.layer == 1 { |
| 345 | 1 |
| 346 | } else { |
| 347 | match scfsi[ch][sb] { |
| 348 | 0 => 3, |
| 349 | 2 => 1, |
| 350 | _ => 2, |
| 351 | } |
| 352 | }; |
| 353 | for _ in 0..n { |
| 354 | w.put(rnd(rng, 63), 6); |
| 355 | } |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | for _ in 0..12 { |
| 360 | for sb in 0..nb_sb { |
| 361 | let chs = if sb < bound { channels } else { 1 }; |
| 362 | for ch_alloc in alloc.iter().take(chs) { |
| 363 | let a = ch_alloc[sb]; |
| 364 | if a == 0 { |
| 365 | continue; |
| 366 | } |
| 367 | if h.layer == 1 { |
| 368 | let nb = a + 1; |
| 369 | w.put(rnd(rng, (1 << nb) - 1), nb); |
| 370 | } else { |
| 371 | let l = rows[sb][a as usize]; |
| 372 | match l { |
| 373 | 3 | 5 | 9 => { |
| 374 | let bits = [0, 0, 0, 5, 0, 7, 0, 0, 0, 10][l as usize]; |
| 375 | w.put(rnd(rng, l * l * l), bits); |
| 376 | } |
| 377 | _ => { |
| 378 | let nb = 32 - l.leading_zeros(); |
| 379 | for _ in 0..3 { |
| 380 | w.put(rnd(rng, l), nb); |
| 381 | } |
| 382 | } |
| 383 | } |
| 384 | } |
| 385 | } |
| 386 | } |
| 387 | } |
| 388 | let len = h.frame_len().unwrap(); |
| 389 | let head = if h.crc { 6 } else { 4 }; |
| 390 | if head + w.bytes.len() > len { |
| 391 | return None; |
| 392 | } |
| 393 | let mut frame = h.to_bytes().to_vec(); |
| 394 | if h.crc { |
| 395 | let c = ec_mp3::header::crc16_bits(&h.to_bytes(), &protected, protected_bits); |
| 396 | frame.extend_from_slice(&c.to_be_bytes()); |
| 397 | } |
| 398 | frame.extend_from_slice(&w.bytes); |
| 399 | frame.resize(len, 0); |
| 400 | Some(frame) |
| 401 | } |
| 402 | |
| 403 | fn random_header( |
| 404 | rng: &mut Rng, |
| 405 | layer: u8, |
| 406 | version: u8, |
| 407 | mode: u8, |
| 408 | ext: u8, |
| 409 | crc: bool, |
| 410 | ) -> FrameHeader { |
| 411 | let br = 1 + (rng.byte() % 14); |
| 412 | let sr = rng.byte() % 3; |
| 413 | let b1 = 0xE0 | (version << 3) | ((4 - layer) << 1) | u8::from(!crc); |
| 414 | FrameHeader::parse(&[0xFF, b1, (br << 4) | (sr << 2), (mode << 6) | (ext << 4)]).unwrap() |
| 415 | } |
| 416 | |
| 417 | fn compare_stream(name: &str, frames: &[Vec<u8>], tolerance: f32) -> f32 { |
| 418 | let dir = work_dir(); |
| 419 | let mut bytes = Vec::new(); |
| 420 | for f in frames { |
| 421 | bytes.extend_from_slice(f); |
| 422 | } |
| 423 | let path = dir.join(format!("{name}.mp2")); |
| 424 | std::fs::write(&path, &bytes).unwrap(); |
| 425 | let h0 = FrameHeader::parse(&frames[0]).unwrap(); |
| 426 | let ch = h0.channels(); |
| 427 | let want = ffmpeg_decode(&path, ch, h0.layer); |
| 428 | let (got, _, _) = our_decode(&bytes); |
| 429 | assert_eq!(got.len(), want.len(), "{name}: length"); |
| 430 | let (e, at) = max_err(&got, &want); |
| 431 | let (lsb, same) = s16_agreement(&got, &ffmpeg_decode_s16(&path, ch, h0.layer)); |
| 432 | eprintln!( |
| 433 | "{name}: {} frames, max abs error {e:.3e}; vs fixed-point s16: max {lsb} LSB, {:.2}% identical", |
| 434 | frames.len(), |
| 435 | same * 100.0 |
| 436 | ); |
| 437 | if e > tolerance { |
| 438 | let per = h0.samples_per_frame() * ch; |
| 439 | for (i, (g, w)) in got.chunks(per).zip(want.chunks(per)).enumerate() { |
| 440 | let (fe, fat) = max_err(g, w); |
| 441 | if fe > tolerance { |
| 442 | eprintln!( |
| 443 | " frame {i}: error {fe:.3e} at {fat} (ours {}, ffmpeg {}); header {h0:?}", |
| 444 | g[fat], w[fat] |
| 445 | ); |
| 446 | break; |
| 447 | } |
| 448 | } |
| 449 | } |
| 450 | assert!(e <= tolerance, "{name}: max error {e} at {at}"); |
| 451 | e |
| 452 | } |
| 453 | |
| 454 | #[test] |
| 455 | fn random_frames_match_ffmpeg() { |
| 456 | if !have_ffmpeg() { |
| 457 | return; |
| 458 | } |
| 459 | let mut rng = Rng(0x9E37_79B9_7F4A_7C15); |
| 460 | let mut worst = 0.0f32; |
| 461 | let mut streams = 0; |
| 462 | for layer in [2u8, 1] { |
| 463 | for version in [3u8, 2, 0] { |
| 464 | for (mode, ext) in [(3u8, 0u8), (0, 0), (2, 0), (1, 0), (1, 1), (1, 2), (1, 3)] { |
| 465 | for round in 0..8 { |
| 466 | let crc = round % 2 == 1; |
| 467 | |
| 468 | let h = loop { |
| 469 | let h = random_header(&mut rng, layer, version, mode, ext, crc); |
| 470 | if structured_frame(&mut rng, &h, 0).is_some() { |
| 471 | break h; |
| 472 | } |
| 473 | }; |
| 474 | let mut frames = Vec::new(); |
| 475 | while frames.len() < 24 { |
| 476 | let density = 5 + (rng.byte() as u32 % 90); |
| 477 | let mut d = density; |
| 478 | loop { |
| 479 | if let Some(f) = structured_frame(&mut rng, &h, d) { |
| 480 | frames.push(f); |
| 481 | break; |
| 482 | } |
| 483 | d = (d * 2 / 3).max(1); |
| 484 | } |
| 485 | } |
| 486 | let name = format!("rand-l{layer}-v{version}-m{mode}-e{ext}-r{round}"); |
| 487 | worst = worst.max(compare_stream(&name, &frames, 4e-5)); |
| 488 | streams += 1; |
| 489 | } |
| 490 | } |
| 491 | } |
| 492 | } |
| 493 | eprintln!("{streams} random streams, worst error {worst:.3e}"); |
| 494 | } |
| 495 | |
| 496 | fn have_encoder(name: &str) -> bool { |
| 497 | Command::new("ffmpeg") |
| 498 | .args(["-hide_banner", "-encoders"]) |
| 499 | .output() |
| 500 | .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(name)) |
| 501 | } |
| 502 | |
| 503 | |
| 504 | |
| 505 | #[test] |
| 506 | fn twolame_streams_match_ffmpeg() { |
| 507 | if !have_ffmpeg() { |
| 508 | return; |
| 509 | } |
| 510 | if !have_encoder("libtwolame") { |
| 511 | eprintln!("skip: ffmpeg has no libtwolame"); |
| 512 | return; |
| 513 | } |
| 514 | let dir = work_dir(); |
| 515 | let cases: &[(&str, u32, &str, u32, bool)] = &[ |
| 516 | ("joint_stereo", 44100, "64k", 2, false), |
| 517 | ("joint_stereo", 48000, "96k", 2, true), |
| 518 | ("joint_stereo", 32000, "128k", 2, false), |
| 519 | ("joint_stereo", 24000, "48k", 2, true), |
| 520 | ("stereo", 44100, "192k", 2, true), |
| 521 | ("stereo", 22050, "64k", 2, false), |
| 522 | ("dual_channel", 48000, "128k", 2, false), |
| 523 | ("mono", 44100, "64k", 1, true), |
| 524 | ("mono", 16000, "32k", 1, false), |
| 525 | ("joint_stereo", 44100, "384k", 2, true), |
| 526 | ("joint_stereo", 44100, "112k", 2, false), |
| 527 | ("mono", 48000, "56k", 1, false), |
| 528 | ]; |
| 529 | for (n, &(mode, rate, br, ch, crc)) in cases.iter().enumerate() { |
| 530 | let path = dir.join(format!("tl-{n}.mp2")); |
| 531 | let src = format!( |
| 532 | "aevalsrc=0.4*sin(2*PI*(300+1500*t)*t)|0.3*sin(2*PI*700*t)+0.05*random(1):s={rate}:d=2" |
| 533 | ); |
| 534 | let st = Command::new("ffmpeg") |
| 535 | .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"]) |
| 536 | .arg(ch.to_string()) |
| 537 | .args(["-c:a", "libtwolame", "-mode", mode, "-b:a", br]) |
| 538 | .args(["-error_protection", if crc { "1" } else { "0" }]) |
| 539 | .arg(&path) |
| 540 | .status() |
| 541 | .unwrap(); |
| 542 | assert!(st.success(), "twolame {mode} {rate} {br}"); |
| 543 | let bytes = std::fs::read(&path).unwrap(); |
| 544 | let h = FrameHeader::parse(&bytes).unwrap(); |
| 545 | assert_eq!(h.crc, crc, "{mode} {rate}: protection bit"); |
| 546 | let want = ffmpeg_decode(&path, ch as usize, 2); |
| 547 | let (got, r, c) = our_decode(&bytes); |
| 548 | assert_eq!((r, c), (rate, ch as usize)); |
| 549 | |
| 550 | |
| 551 | |
| 552 | |
| 553 | let per = 1152 * ch as usize; |
| 554 | assert!(got.len() >= want.len() && (got.len() - want.len()).is_multiple_of(per)); |
| 555 | let cut = got.len() - want.len(); |
| 556 | let skip = if cut > 0 { per } else { 0 }; |
| 557 | let (e, at) = max_err(&got[cut + skip..], &want[skip..]); |
| 558 | eprintln!("twolame {mode} {rate} Hz {br} crc={crc}: max abs error {e:.3e}"); |
| 559 | assert!(e <= 1e-5, "twolame {mode} {rate} {br}: {e} at {at}"); |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | fn layer2_frame_with_crc() -> Vec<u8> { |
| 564 | let mut rng = Rng(77); |
| 565 | |
| 566 | let h = FrameHeader::parse(&[0xFF, 0xFC, 0x84, 0x00]).unwrap(); |
| 567 | loop { |
| 568 | let f = structured_frame(&mut rng, &h, 40); |
| 569 | if let Some(f) = f { |
| 570 | return f; |
| 571 | } |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | #[test] |
| 576 | fn crc_protects_allocation_and_scfsi() { |
| 577 | let frame = layer2_frame_with_crc(); |
| 578 | assert!(FrameHeader::parse(&frame).unwrap().crc); |
| 579 | let mut reader = Mp3Reader::new(); |
| 580 | reader.push(&frame); |
| 581 | assert!(reader.next_frame().is_ok(), "good CRC decodes"); |
| 582 | |
| 583 | let mut bad = frame.clone(); |
| 584 | bad[7] ^= 0x10; |
| 585 | let mut reader = Mp3Reader::new(); |
| 586 | reader.push(&bad); |
| 587 | let err = reader.next_frame().unwrap_err(); |
| 588 | assert!(err.to_string().contains("CRC"), "{err}"); |
| 589 | |
| 590 | let mut late = frame.clone(); |
| 591 | let n = late.len() - 3; |
| 592 | late[n] ^= 0xFF; |
| 593 | let mut reader = Mp3Reader::new(); |
| 594 | reader.push(&late); |
| 595 | assert!(reader.next_frame().is_ok()); |
| 596 | } |
| 597 | |
| 598 | #[test] |
| 599 | fn free_format_layer2_is_refused_by_name() { |
| 600 | |
| 601 | let mut f = vec![0xFF, 0xFD, 0x04, 0x00]; |
| 602 | f.resize(600, 0); |
| 603 | let mut dec = ec_mp3::Mp3Decode::new(); |
| 604 | let err = dec.decode_frame(&f).unwrap_err(); |
| 605 | assert!(err.to_string().contains("free-format"), "{err}"); |
| 606 | } |
| 607 | |
| 608 | #[test] |
| 609 | fn decoder_trait_takes_layer2_packets() { |
| 610 | use ec_core::packet::{Buf, Packet}; |
| 611 | use ec_core::registry::{CodecId, Decoder}; |
| 612 | let mut rng = Rng(5); |
| 613 | let h = FrameHeader::parse(&[0xFF, 0xFD, 0x94, 0x00]).unwrap(); |
| 614 | let params = ec_mp3::layer_codec_parameters(2, 44100, 2); |
| 615 | assert_eq!(params.codec, CodecId::Mp2); |
| 616 | let mut dec = ec_mp3::Mp3Decoder::new(params).unwrap(); |
| 617 | let mut frames = 0; |
| 618 | for _ in 0..5 { |
| 619 | let f = loop { |
| 620 | if let Some(f) = structured_frame(&mut rng, &h, 30) { |
| 621 | break f; |
| 622 | } |
| 623 | }; |
| 624 | let pkt = Packet::new( |
| 625 | 0, |
| 626 | ec_core::TimeBase::try_new(1, 44100).unwrap(), |
| 627 | Buf::from(f), |
| 628 | ); |
| 629 | dec.send_packet(&pkt).unwrap(); |
| 630 | while let Ok(frame) = dec.receive_frame() { |
| 631 | let ec_core::frame::Frame::Audio(a) = frame else { |
| 632 | panic!() |
| 633 | }; |
| 634 | assert_eq!(a.samples, 1152); |
| 635 | frames += 1; |
| 636 | } |
| 637 | } |
| 638 | assert_eq!(frames, 5); |
| 639 | } |
| 640 | |
| 641 | #[test] |
| 642 | fn damaged_and_truncated_frames_never_panic() { |
| 643 | let mut rng = Rng(0xDEAD_BEEF); |
| 644 | for layer in [2u8, 1] { |
| 645 | for version in [3u8, 2, 0] { |
| 646 | for mode in [0u8, 1, 3] { |
| 647 | for _ in 0..40 { |
| 648 | let (ext, crc) = (rng.byte() % 4, rng.byte().is_multiple_of(2)); |
| 649 | let h = random_header(&mut rng, layer, version, mode, ext, crc); |
| 650 | let len = h.frame_len().unwrap(); |
| 651 | let mut f = h.to_bytes().to_vec(); |
| 652 | f.extend((4..len).map(|_| rng.byte())); |
| 653 | |
| 654 | let mut dec = ec_mp3::Mp3Decode::new(); |
| 655 | let _ = dec.decode_frame(&f); |
| 656 | for cut in [5, 6, 20, len / 2, len - 1] { |
| 657 | let _ = dec.decode_frame(&f[..cut.min(len)]); |
| 658 | let mut r = Mp3Reader::new(); |
| 659 | r.push(&f[..cut.min(len)]); |
| 660 | while r.next_frame().is_ok() {} |
| 661 | } |
| 662 | } |
| 663 | } |
| 664 | } |
| 665 | } |
| 666 | } |