Fixtures, real library, remux round trip and a fuzz loop
Browse files at this commit1bc90804e2d5b49a4004ebfbf849fb432d60a696Parent: 7336903- test
- fixtures, real library, remux round trip and a fuzz loop
1 changed file +744 -0
- crates/ec-mp4/tests/mp4.rs +744 -0
crates/ec-mp4/tests/mp4.rsadded+744 -0
| @@ -0,0 +1,744 @@ | ||
| 1 | +//! What the fixtures say: every mp4/mov fixture demuxes into the streams | |
| 2 | +//! ffprobe reports — with the frame rate compared as an exact rational, which is | |
| 3 | +//! where 23.976 used to become 23 — remuxes into a file ffmpeg decodes, and | |
| 4 | +//! carries the boxes edith used to write by hand (`av01`, `hvc1`, `colr`, | |
| 5 | +//! `udta/name`, `tx3g`) through both directions. | |
| 6 | + | |
| 7 | +use std::fs::File; | |
| 8 | +use std::io::{BufReader, BufWriter, Cursor}; | |
| 9 | +use std::path::{Path, PathBuf}; | |
| 10 | +use std::process::Command; | |
| 11 | + | |
| 12 | +use ec_core::{ | |
| 13 | + Buf, CodecId, Demuxer, Error, MediaParameters, Muxer, Packet, SeekMode, StreamInfo, TimeBase, | |
| 14 | + Timestamp, | |
| 15 | +}; | |
| 16 | +use ec_mp4::{Mp4Demuxer, Mp4Muxer}; | |
| 17 | + | |
| 18 | +fn fixtures() -> PathBuf { | |
| 19 | + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") | |
| 20 | +} | |
| 21 | + | |
| 22 | +fn work() -> PathBuf { | |
| 23 | + let dir = std::env::temp_dir().join("ec-mp4-tests"); | |
| 24 | + std::fs::create_dir_all(&dir).expect("test work directory"); | |
| 25 | + dir | |
| 26 | +} | |
| 27 | + | |
| 28 | +fn open(path: &Path) -> Mp4Demuxer<BufReader<File>> { | |
| 29 | + Mp4Demuxer::new(BufReader::new( | |
| 30 | + File::open(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())), | |
| 31 | + )) | |
| 32 | + .unwrap_or_else(|e| panic!("{}: {e}", path.display())) | |
| 33 | +} | |
| 34 | + | |
| 35 | +/// What ffprobe calls each of our codec ids. | |
| 36 | +fn ffmpeg_name(codec: CodecId) -> &'static str { | |
| 37 | + match codec { | |
| 38 | + CodecId::H265 => "hevc", | |
| 39 | + CodecId::Av1 => "av1", | |
| 40 | + CodecId::Tx3g => "mov_text", | |
| 41 | + other => other.name(), | |
| 42 | + } | |
| 43 | +} | |
| 44 | + | |
| 45 | +/// One ffprobe field per stream, in stream order. | |
| 46 | +fn probe_field(path: &Path, entries: &str) -> Vec<String> { | |
| 47 | + let out = Command::new("ffprobe") | |
| 48 | + .args(["-v", "error", "-show_entries", entries, "-of", "csv=p=0"]) | |
| 49 | + .arg(path) | |
| 50 | + .output() | |
| 51 | + .expect("ffprobe runs"); | |
| 52 | + assert!( | |
| 53 | + out.status.success(), | |
| 54 | + "ffprobe refused {}: {}", | |
| 55 | + path.display(), | |
| 56 | + String::from_utf8_lossy(&out.stderr) | |
| 57 | + ); | |
| 58 | + String::from_utf8_lossy(&out.stdout) | |
| 59 | + .lines() | |
| 60 | + .map(|l| l.trim_end_matches(',').to_string()) | |
| 61 | + .filter(|l| !l.is_empty()) | |
| 62 | + .collect() | |
| 63 | +} | |
| 64 | + | |
| 65 | +/// The fields a remux must not change. | |
| 66 | +fn probe(path: &Path) -> String { | |
| 67 | + probe_field( | |
| 68 | + path, | |
| 69 | + "stream=index,codec_name,codec_type,width,height,r_frame_rate,sample_rate,channels", | |
| 70 | + ) | |
| 71 | + .join("\n") | |
| 72 | +} | |
| 73 | + | |
| 74 | +fn duration(path: &Path) -> f64 { | |
| 75 | + probe_field(path, "format=duration") | |
| 76 | + .first() | |
| 77 | + .and_then(|s| s.trim().parse().ok()) | |
| 78 | + .unwrap_or(0.0) | |
| 79 | +} | |
| 80 | + | |
| 81 | +/// Every mp4-family fixture: the generated video and audio corpus, plus the | |
| 82 | +/// three shapes it has none of (a `.mov`, a fragmented file and one carrying | |
| 83 | +/// timed text), made once by ffmpeg. | |
| 84 | +fn mp4_fixtures() -> Vec<PathBuf> { | |
| 85 | + let mut files: Vec<PathBuf> = ["video", "audio"] | |
| 86 | + .iter() | |
| 87 | + .flat_map(|dir| { | |
| 88 | + std::fs::read_dir(fixtures().join(dir)) | |
| 89 | + .expect("fixtures (run scripts/gen-fixtures.sh)") | |
| 90 | + .filter_map(|e| e.ok().map(|e| e.path())) | |
| 91 | + }) | |
| 92 | + .filter(|p| { | |
| 93 | + let name = p.to_string_lossy(); | |
| 94 | + name.ends_with(".mp4") || name.ends_with(".m4a") || name.ends_with(".mov") | |
| 95 | + }) | |
| 96 | + .collect(); | |
| 97 | + files.sort(); | |
| 98 | + files.extend(derived_fixtures()); | |
| 99 | + files | |
| 100 | +} | |
| 101 | + | |
| 102 | +/// A `.mov`, a fragmented mp4 and an mp4 with a timed-text track — none of which | |
| 103 | +/// the generated corpus has and all of which this crate claims. | |
| 104 | +fn derived_fixtures() -> Vec<PathBuf> { | |
| 105 | + let h264 = fixtures().join("video/h264-1080p-23.976-8bit.mp4"); | |
| 106 | + let src = h264.to_string_lossy().into_owned(); | |
| 107 | + let out = work(); | |
| 108 | + let mov = out.join("h264.mov"); | |
| 109 | + let frag = out.join("h264-fragmented.mp4"); | |
| 110 | + let jobs: [(&PathBuf, Vec<&str>); 2] = [ | |
| 111 | + (&mov, vec!["-i", &src, "-c", "copy", "-f", "mov"]), | |
| 112 | + ( | |
| 113 | + &frag, | |
| 114 | + vec![ | |
| 115 | + "-i", | |
| 116 | + &src, | |
| 117 | + "-c", | |
| 118 | + "copy", | |
| 119 | + "-movflags", | |
| 120 | + "frag_keyframe+empty_moov+default_base_moof", | |
| 121 | + ], | |
| 122 | + ), | |
| 123 | + ]; | |
| 124 | + let mut made = Vec::new(); | |
| 125 | + for (path, args) in jobs { | |
| 126 | + if !path.exists() { | |
| 127 | + let ok = Command::new("ffmpeg") | |
| 128 | + .args(["-v", "error", "-y"]) | |
| 129 | + .args(args) | |
| 130 | + .arg(path) | |
| 131 | + .status() | |
| 132 | + .expect("ffmpeg runs") | |
| 133 | + .success(); | |
| 134 | + assert!(ok, "ffmpeg could not make {}", path.display()); | |
| 135 | + } | |
| 136 | + made.push(path.clone()); | |
| 137 | + } | |
| 138 | + made | |
| 139 | +} | |
| 140 | + | |
| 141 | +/// Every packet of `src` through this crate's own writer, and how many there | |
| 142 | +/// were. | |
| 143 | +fn remux(src: &Path, dst: &Path) -> usize { | |
| 144 | + let mut demuxer = open(src); | |
| 145 | + let mut muxer = Mp4Muxer::new(BufWriter::new(File::create(dst).expect("output file"))) | |
| 146 | + .expect("muxer opens"); | |
| 147 | + for stream in demuxer.streams().to_vec() { | |
| 148 | + muxer.add_stream(stream).expect("stream declared"); | |
| 149 | + } | |
| 150 | + let mut packets = 0; | |
| 151 | + loop { | |
| 152 | + match demuxer.next_packet() { | |
| 153 | + Ok(packet) => { | |
| 154 | + muxer.write_packet(&packet).expect("packet written"); | |
| 155 | + packets += 1; | |
| 156 | + } | |
| 157 | + Err(Error::Eof) => break, | |
| 158 | + Err(e) => panic!("{}: {e}", src.display()), | |
| 159 | + } | |
| 160 | + } | |
| 161 | + muxer.finish().expect("finished"); | |
| 162 | + packets | |
| 163 | +} | |
| 164 | + | |
| 165 | +#[test] | |
| 166 | +fn every_fixture_demuxes_into_the_streams_ffprobe_reports() { | |
| 167 | + let files = mp4_fixtures(); | |
| 168 | + assert!(!files.is_empty(), "no mp4 fixtures found"); | |
| 169 | + let mut table = Vec::new(); | |
| 170 | + for path in &files { | |
| 171 | + let demuxer = open(path); | |
| 172 | + let names = probe_field(path, "stream=codec_name"); | |
| 173 | + let widths = probe_field(path, "stream=width"); | |
| 174 | + let rates = probe_field(path, "stream=r_frame_rate"); | |
| 175 | + let avg_rates = probe_field(path, "stream=avg_frame_rate"); | |
| 176 | + assert_eq!( | |
| 177 | + demuxer.streams().len(), | |
| 178 | + names.len(), | |
| 179 | + "{}: stream count", | |
| 180 | + path.display() | |
| 181 | + ); | |
| 182 | + for (i, stream) in demuxer.streams().iter().enumerate() { | |
| 183 | + assert_eq!( | |
| 184 | + ffmpeg_name(stream.params.codec), | |
| 185 | + names[i], | |
| 186 | + "{} stream {i}: codec", | |
| 187 | + path.display() | |
| 188 | + ); | |
| 189 | + if let MediaParameters::Video(video) = &stream.params.media { | |
| 190 | + let dims = widths[i] | |
| 191 | + .split(',') | |
| 192 | + .next() | |
| 193 | + .and_then(|w| w.parse::<u32>().ok()) | |
| 194 | + .unwrap_or(0); | |
| 195 | + assert_eq!(video.width, dims, "{} stream {i}: width", path.display()); | |
| 196 | + // The named bug, as a field compare: the rate comes off `stts` | |
| 197 | + // as a rational and has to be the one ffprobe read, exactly. | |
| 198 | + let ours = video.frame_rate.expect("a frame rate"); | |
| 199 | + let ours = format!("{}/{}", ours.num(), ours.den()); | |
| 200 | + assert!( | |
| 201 | + ours == rates[i] || ours == avg_rates[i], | |
| 202 | + "{} stream {i}: fps {ours}, ffprobe r={} avg={}", | |
| 203 | + path.display(), | |
| 204 | + rates[i], | |
| 205 | + avg_rates[i] | |
| 206 | + ); | |
| 207 | + if path.to_string_lossy().contains("23.976") { | |
| 208 | + assert_eq!( | |
| 209 | + video.frame_rate, | |
| 210 | + Some(TimeBase::new(24_000, 1001)), | |
| 211 | + "{}: NTSC film must stay 24000/1001", | |
| 212 | + path.display() | |
| 213 | + ); | |
| 214 | + } | |
| 215 | + } | |
| 216 | + } | |
| 217 | + let d = duration(path); | |
| 218 | + let ours = demuxer | |
| 219 | + .streams() | |
| 220 | + .iter() | |
| 221 | + .filter_map(|s| Some(s.time_base.as_secs_f64() * s.duration? as f64)) | |
| 222 | + .fold(0.0f64, f64::max); | |
| 223 | + assert!( | |
| 224 | + (d - ours).abs() <= 0.20, | |
| 225 | + "{}: duration {d} read back as {ours}", | |
| 226 | + path.display() | |
| 227 | + ); | |
| 228 | + table.push(format!( | |
| 229 | + "{:<44} {:>2} streams {:.3}s {}", | |
| 230 | + path.file_name().unwrap().to_string_lossy(), | |
| 231 | + names.len(), | |
| 232 | + ours, | |
| 233 | + names.join("+") | |
| 234 | + )); | |
| 235 | + } | |
| 236 | + println!("{}", table.join("\n")); | |
| 237 | +} | |
| 238 | + | |
| 239 | +#[test] | |
| 240 | +fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() { | |
| 241 | + let mut table = Vec::new(); | |
| 242 | + for src in &mp4_fixtures() { | |
| 243 | + let dst = work().join(format!( | |
| 244 | + "remux-{}", | |
| 245 | + src.file_name().unwrap().to_string_lossy() | |
| 246 | + )); | |
| 247 | + let packets = remux(src, &dst); | |
| 248 | + assert!(packets > 0, "{}: no packets", src.display()); | |
| 249 | + | |
| 250 | + let (before, after) = (probe(src), probe(&dst)); | |
| 251 | + assert_eq!(before, after, "{} field-compares", src.display()); | |
| 252 | + let (d0, d1) = (duration(src), duration(&dst)); | |
| 253 | + assert!( | |
| 254 | + (d0 - d1).abs() <= 0.10, | |
| 255 | + "{}: duration {d0} became {d1}", | |
| 256 | + src.display() | |
| 257 | + ); | |
| 258 | + | |
| 259 | + // ...and it decodes, which is the only claim a field compare cannot make. | |
| 260 | + let decode = Command::new("ffmpeg") | |
| 261 | + .args(["-v", "error", "-i"]) | |
| 262 | + .arg(&dst) | |
| 263 | + .args(["-f", "null", "-"]) | |
| 264 | + .output() | |
| 265 | + .expect("ffmpeg runs"); | |
| 266 | + assert!( | |
| 267 | + decode.status.success() && decode.stderr.is_empty(), | |
| 268 | + "{} does not decode: {}", | |
| 269 | + dst.display(), | |
| 270 | + String::from_utf8_lossy(&decode.stderr) | |
| 271 | + ); | |
| 272 | + table.push(format!( | |
| 273 | + "{:<44} {packets:>6} packets {d0:.3}s -> {d1:.3}s decodes", | |
| 274 | + src.file_name().unwrap().to_string_lossy() | |
| 275 | + )); | |
| 276 | + } | |
| 277 | + println!("{}", table.join("\n")); | |
| 278 | +} | |
| 279 | + | |
| 280 | +/// The four boxes edith writes by hand into the incumbent's output, written | |
| 281 | +/// here instead — and read back by ffprobe, which is what makes them real. | |
| 282 | +#[test] | |
| 283 | +fn the_hand_written_extensions_come_out_as_ffprobe_reads_them() { | |
| 284 | + // av01/av1C and hvc1/hvcC, from a file that already has one of each. | |
| 285 | + for (fixture, want) in [ | |
| 286 | + ("video/av1-1080p-23.976-8bit.mp4", "av1"), | |
| 287 | + ("video/hevc-1080p-23.976-10bit.mp4", "hevc"), | |
| 288 | + ("video/vp9-1080p-23.976-8bit.mp4", "vp9"), | |
| 289 | + ] { | |
| 290 | + let src = fixtures().join(fixture); | |
| 291 | + let dst = work().join(format!("entry-{want}.mp4")); | |
| 292 | + remux(&src, &dst); | |
| 293 | + assert_eq!( | |
| 294 | + probe_field(&dst, "stream=codec_name"), | |
| 295 | + vec![want.to_string()], | |
| 296 | + "{fixture} remuxed" | |
| 297 | + ); | |
| 298 | + } | |
| 299 | + | |
| 300 | + // colr, mdcv and clli: an SDR H.264 fixture declared as an HDR10 grade, so | |
| 301 | + // nothing in the bitstream can be the source of what ffprobe reads back. | |
| 302 | + let src = fixtures().join("video/h264-1080p-23.976-8bit.mp4"); | |
| 303 | + let dst = work().join("entry-colr.mp4"); | |
| 304 | + { | |
| 305 | + let mut demuxer = open(&src); | |
| 306 | + let mut streams = demuxer.streams().to_vec(); | |
| 307 | + if let MediaParameters::Video(video) = &mut streams[0].params.media { | |
| 308 | + video.color = ec_core::ColorInfo { | |
| 309 | + primaries: 9, | |
| 310 | + transfer: 16, | |
| 311 | + matrix: 9, | |
| 312 | + full_range: false, | |
| 313 | + }; | |
| 314 | + video.light = ec_core::ContentLight { | |
| 315 | + max_cll: Some(1000.0), | |
| 316 | + max_fall: Some(400.0), | |
| 317 | + mastering_max: Some(1000.0), | |
| 318 | + mastering_min: Some(0.005), | |
| 319 | + }; | |
| 320 | + } | |
| 321 | + let mut muxer = | |
| 322 | + Mp4Muxer::new(File::create(&dst).expect("output file")).expect("muxer opens"); | |
| 323 | + muxer.add_stream(streams[0].clone()).expect("stream"); | |
| 324 | + muxer.set_title("a movie"); | |
| 325 | + muxer | |
| 326 | + .set_track_title(0, "the picture") | |
| 327 | + .expect("track named"); | |
| 328 | + while let Ok(packet) = demuxer.next_packet() { | |
| 329 | + muxer.write_packet(&packet).expect("packet written"); | |
| 330 | + } | |
| 331 | + muxer.finish().expect("finished"); | |
| 332 | + } | |
| 333 | + assert_eq!( | |
| 334 | + probe_field( | |
| 335 | + &dst, | |
| 336 | + "stream=color_primaries,color_transfer,color_space,color_range" | |
| 337 | + ), | |
| 338 | + // ffprobe prints these in its own field order: range, space, transfer, | |
| 339 | + // primaries. | |
| 340 | + vec!["tv,bt2020nc,smpte2084,bt2020".to_string()], | |
| 341 | + "colr nclx read back" | |
| 342 | + ); | |
| 343 | + let side = String::from_utf8_lossy( | |
| 344 | + &Command::new("ffprobe") | |
| 345 | + .args(["-v", "error", "-show_streams", "-of", "json"]) | |
| 346 | + .arg(&dst) | |
| 347 | + .output() | |
| 348 | + .expect("ffprobe runs") | |
| 349 | + .stdout, | |
| 350 | + ) | |
| 351 | + .into_owned(); | |
| 352 | + assert!( | |
| 353 | + side.contains("Mastering display metadata"), | |
| 354 | + "mdcv survived: {side}" | |
| 355 | + ); | |
| 356 | + assert!( | |
| 357 | + side.contains("Content light level metadata"), | |
| 358 | + "clli survived" | |
| 359 | + ); | |
| 360 | + // ...and the two names, through our own reader, which is where a `name` box | |
| 361 | + // is *stated* (ffmpeg's mov reader keeps the movie's, not the track's). | |
| 362 | + let back = open(&dst); | |
| 363 | + assert_eq!(back.title(), Some("a movie")); | |
| 364 | + assert_eq!(back.track_title(0), Some("the picture")); | |
| 365 | + let (colour, light) = match &back.streams()[0].params.media { | |
| 366 | + MediaParameters::Video(v) => (v.color, v.light), | |
| 367 | + _ => panic!("a video stream"), | |
| 368 | + }; | |
| 369 | + assert_eq!( | |
| 370 | + (colour.primaries, colour.transfer, colour.matrix), | |
| 371 | + (9, 16, 9) | |
| 372 | + ); | |
| 373 | + assert_eq!(light.max_cll, Some(1000.0)); | |
| 374 | + assert_eq!(light.mastering_max, Some(1000.0)); | |
| 375 | + | |
| 376 | + // tx3g, written from nothing but cues and read back as timed text. | |
| 377 | + let dst = work().join("entry-tx3g.mp4"); | |
| 378 | + { | |
| 379 | + let mut muxer = | |
| 380 | + Mp4Muxer::new(File::create(&dst).expect("output file")).expect("muxer opens"); | |
| 381 | + let mut info = StreamInfo::new( | |
| 382 | + 0, | |
| 383 | + TimeBase::MILLIS, | |
| 384 | + ec_core::CodecParameters::new(CodecId::Tx3g), | |
| 385 | + ); | |
| 386 | + info.language = Some("tur".into()); | |
| 387 | + muxer.add_stream(info).expect("stream"); | |
| 388 | + muxer.set_track_title(0, "Türkçe").expect("track named"); | |
| 389 | + for (start, text) in [(0i64, "birinci"), (2_000, "ikinci"), (4_000, "üçüncü")] { | |
| 390 | + let mut payload = (text.len() as u16).to_be_bytes().to_vec(); | |
| 391 | + payload.extend_from_slice(text.as_bytes()); | |
| 392 | + let mut packet = Packet::new(0, TimeBase::MILLIS, payload); | |
| 393 | + packet.pts = Some(start); | |
| 394 | + packet.duration = Some(2_000); | |
| 395 | + packet.flags.keyframe = true; | |
| 396 | + muxer.write_packet(&packet).expect("packet written"); | |
| 397 | + } | |
| 398 | + muxer.finish().expect("finished"); | |
| 399 | + } | |
| 400 | + assert_eq!(probe_field(&dst, "stream=codec_name"), vec!["mov_text"]); | |
| 401 | + assert_eq!(probe_field(&dst, "stream_tags=language"), vec!["tur"]); | |
| 402 | + let text = String::from_utf8_lossy( | |
| 403 | + &Command::new("ffmpeg") | |
| 404 | + .args(["-v", "error", "-i"]) | |
| 405 | + .arg(&dst) | |
| 406 | + .args(["-f", "srt", "-"]) | |
| 407 | + .output() | |
| 408 | + .expect("ffmpeg runs") | |
| 409 | + .stdout, | |
| 410 | + ) | |
| 411 | + .into_owned(); | |
| 412 | + assert!( | |
| 413 | + text.contains("birinci") && text.contains("üçüncü"), | |
| 414 | + "{text}" | |
| 415 | + ); | |
| 416 | + let back = open(&dst); | |
| 417 | + assert_eq!(back.track_title(0), Some("Türkçe")); | |
| 418 | + assert_eq!(back.streams()[0].language.as_deref(), Some("tur")); | |
| 419 | +} | |
| 420 | + | |
| 421 | +/// The `esds` field the incumbent made unnameable: an AAC track's | |
| 422 | +/// `AudioSpecificConfig`, out of the file as the bytes it is. | |
| 423 | +#[test] | |
| 424 | +fn an_aac_tracks_audio_specific_config_survives_as_bytes() { | |
| 425 | + let src = fixtures().join("audio/aac-mp4-stereo-48000.mp4"); | |
| 426 | + let demuxer = open(&src); | |
| 427 | + let asc = demuxer.streams()[0] | |
| 428 | + .params | |
| 429 | + .extradata | |
| 430 | + .clone() | |
| 431 | + .expect("an AudioSpecificConfig"); | |
| 432 | + // 48 kHz stereo AAC-LC: object type 2, frequency index 3, channels 2. | |
| 433 | + assert!(asc.len() >= 2, "an AudioSpecificConfig"); | |
| 434 | + assert_eq!(asc[0] >> 3, 2, "AAC-LC"); | |
| 435 | + assert_eq!(((asc[0] & 0x7) << 1) | (asc[1] >> 7), 3, "48 kHz"); | |
| 436 | + assert_eq!((asc[1] >> 3) & 0xF, 2, "stereo"); | |
| 437 | + | |
| 438 | + // ...and back out through our own esds writer, byte for byte. | |
| 439 | + let dst = work().join("esds.mp4"); | |
| 440 | + remux(&src, &dst); | |
| 441 | + assert_eq!(open(&dst).streams()[0].params.extradata, Some(asc)); | |
| 442 | + | |
| 443 | + // The other flavours of `mp4a` and its neighbours: an entry that is not AAC | |
| 444 | + // is that codec, not a dropped track (the incumbent kept none of them). | |
| 445 | + for (fixture, want) in [ | |
| 446 | + ("audio/alac-mp4-stereo-48000.m4a", CodecId::Alac), | |
| 447 | + ("audio/aac-mp4-5.1-48000.mp4", CodecId::Aac), | |
| 448 | + ] { | |
| 449 | + let demuxer = open(&fixtures().join(fixture)); | |
| 450 | + assert_eq!(demuxer.streams()[0].params.codec, want, "{fixture}"); | |
| 451 | + } | |
| 452 | +} | |
| 453 | + | |
| 454 | +/// An `mp4a` entry holding MP3 rather than AAC, which is the case the incumbent | |
| 455 | +/// dropped on the floor: written by ffmpeg, read as MP3 here. | |
| 456 | +#[test] | |
| 457 | +fn a_non_aac_mp4a_entry_is_not_dropped() { | |
| 458 | + let dst = work().join("mp3-in-mp4.mp4"); | |
| 459 | + let src = fixtures().join("audio/mp3-stereo-44100.mp3"); | |
| 460 | + let ok = Command::new("ffmpeg") | |
| 461 | + .args(["-v", "error", "-y", "-i"]) | |
| 462 | + .arg(&src) | |
| 463 | + .args(["-c", "copy"]) | |
| 464 | + .arg(&dst) | |
| 465 | + .status() | |
| 466 | + .expect("ffmpeg runs") | |
| 467 | + .success(); | |
| 468 | + assert!(ok, "ffmpeg could not put MP3 in an mp4"); | |
| 469 | + let mut demuxer = open(&dst); | |
| 470 | + assert_eq!(demuxer.streams()[0].params.codec, CodecId::Mp3); | |
| 471 | + assert_eq!(probe_field(&dst, "stream=codec_name"), vec!["mp3"]); | |
| 472 | + let mut packets = 0; | |
| 473 | + while demuxer.next_packet().is_ok() { | |
| 474 | + packets += 1; | |
| 475 | + } | |
| 476 | + assert!(packets > 100, "{packets} MP3 packets"); | |
| 477 | +} | |
| 478 | + | |
| 479 | +/// Fragments: the same pictures, out of `moof`/`trun` instead of a sample table. | |
| 480 | +#[test] | |
| 481 | +fn a_fragmented_file_demuxes_to_the_same_packets_as_a_plain_one() { | |
| 482 | + let plain = fixtures().join("video/h264-1080p-23.976-8bit.mp4"); | |
| 483 | + let frag = work().join("h264-fragmented.mp4"); | |
| 484 | + derived_fixtures(); | |
| 485 | + let mut a = open(&plain); | |
| 486 | + let mut b = open(&frag); | |
| 487 | + assert!(b.fragment_count() > 0, "the fixture is fragmented"); | |
| 488 | + assert_eq!(a.streams().len(), b.streams().len()); | |
| 489 | + let mut n = 0; | |
| 490 | + loop { | |
| 491 | + match (a.next_packet(), b.next_packet()) { | |
| 492 | + (Ok(x), Ok(y)) => { | |
| 493 | + assert_eq!(x.data, y.data, "packet {n} bytes"); | |
| 494 | + assert_eq!(x.is_keyframe(), y.is_keyframe(), "packet {n} sync"); | |
| 495 | + n += 1; | |
| 496 | + } | |
| 497 | + (Err(_), Err(_)) => break, | |
| 498 | + (x, y) => panic!("packet {n}: {:?} against {:?}", x.is_ok(), y.is_ok()), | |
| 499 | + } | |
| 500 | + } | |
| 501 | + assert!(n >= 48, "{n} packets"); | |
| 502 | +} | |
| 503 | + | |
| 504 | +/// Seeking lands on a random access point at or before the target, on the one | |
| 505 | +/// reader the file was opened with. | |
| 506 | +#[test] | |
| 507 | +fn seeks_land_on_a_sync_sample_at_or_before_their_target() { | |
| 508 | + let path = fixtures().join("video/h264-1080p-23.976-8bit.mp4"); | |
| 509 | + let mut demuxer = open(&path); | |
| 510 | + let stream = demuxer.streams()[0].clone(); | |
| 511 | + let base = stream.time_base; | |
| 512 | + let ticks = stream.duration.expect("a duration"); | |
| 513 | + let mut state = 0x2545_F491_4F6C_DD1Du64; | |
| 514 | + let mut next = move || { | |
| 515 | + state ^= state << 13; | |
| 516 | + state ^= state >> 7; | |
| 517 | + state ^= state << 17; | |
| 518 | + state | |
| 519 | + }; | |
| 520 | + for _ in 0..100 { | |
| 521 | + let target = (next() % ticks as u64) as i64; | |
| 522 | + demuxer | |
| 523 | + .seek(0, Timestamp::new(target, base), SeekMode::SyncBefore) | |
| 524 | + .expect("seek"); | |
| 525 | + let packet = demuxer.next_packet().expect("a packet after the seek"); | |
| 526 | + assert!(packet.is_keyframe(), "seek landed on a non-sync sample"); | |
| 527 | + assert!( | |
| 528 | + packet.dts.unwrap_or(0) <= target, | |
| 529 | + "seek landed after its target" | |
| 530 | + ); | |
| 531 | + } | |
| 532 | +} | |
| 533 | + | |
| 534 | +/// Ten thousand mutations of a real file: every one is an error or a stream, and | |
| 535 | +/// none of them is a panic. | |
| 536 | +#[test] | |
| 537 | +fn ten_thousand_mutations_never_panic() { | |
| 538 | + let src = std::fs::read(fixtures().join("audio/aac-mp4-stereo-48000.mp4")).expect("a fixture"); | |
| 539 | + let mut state = 0x9E37_79B9_7F4A_7C15u64; | |
| 540 | + let mut next = move || { | |
| 541 | + state ^= state << 13; | |
| 542 | + state ^= state >> 7; | |
| 543 | + state ^= state << 17; | |
| 544 | + state | |
| 545 | + }; | |
| 546 | + let (mut opened, mut refused) = (0u32, 0u32); | |
| 547 | + for _ in 0..10_000 { | |
| 548 | + let mut data = src.clone(); | |
| 549 | + for _ in 0..1 + next() % 8 { | |
| 550 | + let at = (next() % data.len() as u64) as usize; | |
| 551 | + data[at] = (next() % 256) as u8; | |
| 552 | + } | |
| 553 | + match Mp4Demuxer::new(Cursor::new(data)) { | |
| 554 | + Ok(mut demuxer) => { | |
| 555 | + opened += 1; | |
| 556 | + for _ in 0..64 { | |
| 557 | + if demuxer.next_packet().is_err() { | |
| 558 | + break; | |
| 559 | + } | |
| 560 | + } | |
| 561 | + let _ = demuxer.seek(0, Timestamp::new(1, TimeBase::MILLIS), SeekMode::SyncBefore); | |
| 562 | + } | |
| 563 | + Err(_) => refused += 1, | |
| 564 | + } | |
| 565 | + } | |
| 566 | + println!("10000 mutations: {opened} opened, {refused} refused, 0 panics"); | |
| 567 | + assert!(opened > 0 && refused > 0, "the corpus has to reach both"); | |
| 568 | +} | |
| 569 | + | |
| 570 | +/// A truncated download is [`Error::NeedMore`], not corruption and not a panic — | |
| 571 | +/// and the prefix of a file whose `moov` is at the front still demuxes. | |
| 572 | +#[test] | |
| 573 | +fn a_truncated_file_is_need_more() { | |
| 574 | + let src = std::fs::read(fixtures().join("audio/aac-mp4-stereo-48000.mp4")).expect("a fixture"); | |
| 575 | + let cut = Mp4Demuxer::new(Cursor::new(src[..src.len() / 3].to_vec())); | |
| 576 | + assert!( | |
| 577 | + matches!(cut, Err(Error::NeedMore) | Err(Error::Corrupt { .. })), | |
| 578 | + "a truncated file must not open as a whole one" | |
| 579 | + ); | |
| 580 | + assert!(Mp4Demuxer::new(Cursor::new(Vec::new())).is_err()); | |
| 581 | + assert!(Mp4Demuxer::new(Cursor::new(b"not an mp4 at all".to_vec())).is_err()); | |
| 582 | +} | |
| 583 | + | |
| 584 | +/// A muxer round trip in memory, with the timing checked at the tick: the file | |
| 585 | +/// this writes states 1001 ticks a frame on a 24000 clock, which is the only way | |
| 586 | +/// 23.976 stays itself. | |
| 587 | +#[test] | |
| 588 | +fn ntsc_timing_survives_a_round_trip_exactly() { | |
| 589 | + let base = TimeBase::from_rate(24_000); | |
| 590 | + let mut info = StreamInfo::new(0, base, ec_core::CodecParameters::new(CodecId::H264)); | |
| 591 | + info.params.extradata = Some(Buf::copy_from_slice(&[ | |
| 592 | + 1, 0x42, 0, 0x1E, 0xFF, 0xE1, 0, 4, 0x67, 0x42, 0, 0x1E, 1, 0, 4, 0x68, 0xCE, 0x3C, 0x80, | |
| 593 | + ])); | |
| 594 | + if let MediaParameters::Video(v) = &mut info.params.media { | |
| 595 | + v.width = 320; | |
| 596 | + v.height = 240; | |
| 597 | + } | |
| 598 | + let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer"); | |
| 599 | + muxer.add_stream(info).expect("stream"); | |
| 600 | + for i in 0..48i64 { | |
| 601 | + let mut packet = Packet::new(0, base, vec![0u8; 16]); | |
| 602 | + packet.pts = Some(i * 1001); | |
| 603 | + packet.dts = Some(i * 1001); | |
| 604 | + packet.duration = Some(1001); | |
| 605 | + packet.flags.keyframe = i % 12 == 0; | |
| 606 | + muxer.write_packet(&packet).expect("packet"); | |
| 607 | + } | |
| 608 | + muxer.finish().expect("finish"); | |
| 609 | + let file = muxer.into_inner().into_inner(); | |
| 610 | + | |
| 611 | + let demuxer = Mp4Demuxer::new(Cursor::new(file)).expect("reopens"); | |
| 612 | + let stream = &demuxer.streams()[0]; | |
| 613 | + assert_eq!(stream.time_base, TimeBase::from_rate(24_000)); | |
| 614 | + assert_eq!( | |
| 615 | + stream.params.video().unwrap().frame_rate, | |
| 616 | + Some(TimeBase::new(24_000, 1001)), | |
| 617 | + "23.976 out of our own writer" | |
| 618 | + ); | |
| 619 | + assert_eq!(stream.duration, Some(48 * 1001)); | |
| 620 | + let mut demuxer = demuxer; | |
| 621 | + let mut keys = 0; | |
| 622 | + let mut n = 0; | |
| 623 | + while let Ok(packet) = demuxer.next_packet() { | |
| 624 | + assert_eq!(packet.pts, Some(n * 1001)); | |
| 625 | + assert_eq!(packet.duration, Some(1001)); | |
| 626 | + keys += u32::from(packet.is_keyframe()); | |
| 627 | + n += 1; | |
| 628 | + } | |
| 629 | + assert_eq!(n, 48); | |
| 630 | + assert_eq!(keys, 4); | |
| 631 | +} | |
| 632 | + | |
| 633 | +/// The real library, end to end: every mp4-family file the manifest lists | |
| 634 | +/// demuxes to EOF with the packet counts ffprobe counts. | |
| 635 | +/// | |
| 636 | +/// Ignored by default because it reads eleven gigabytes. Run it with | |
| 637 | +/// `cargo test -p ec-mp4 --release --test mp4 -- --ignored --nocapture`. | |
| 638 | +#[test] | |
| 639 | +#[ignore = "reads the real library end to end"] | |
| 640 | +fn the_real_library_demuxes_to_eof() { | |
| 641 | + let manifest = std::fs::read_to_string(fixtures().join("real-library-manifest.tsv")) | |
| 642 | + .expect("the real-library manifest (run scripts/scan-real-library.sh)"); | |
| 643 | + let files: Vec<&str> = manifest | |
| 644 | + .lines() | |
| 645 | + .skip(1) | |
| 646 | + .filter_map(|line| { | |
| 647 | + let mut fields = line.split('\t'); | |
| 648 | + let path = fields.next()?; | |
| 649 | + fields.next()?.contains("mp4").then_some(path) | |
| 650 | + }) | |
| 651 | + .collect(); | |
| 652 | + assert!(!files.is_empty(), "no mp4-family files in the manifest"); | |
| 653 | + | |
| 654 | + let mut table = Vec::new(); | |
| 655 | + let mut failed = Vec::new(); | |
| 656 | + for path in files { | |
| 657 | + let path = Path::new(path); | |
| 658 | + if !path.exists() { | |
| 659 | + table.push(format!("{:<58} GONE", name_of(path))); | |
| 660 | + continue; | |
| 661 | + } | |
| 662 | + let mut demuxer = open(path); | |
| 663 | + let kinds: Vec<CodecId> = demuxer.streams().iter().map(|s| s.params.codec).collect(); | |
| 664 | + let mut ours = vec![0u64; kinds.len()]; | |
| 665 | + loop { | |
| 666 | + match demuxer.next_packet() { | |
| 667 | + Ok(packet) => ours[packet.stream as usize] += 1, | |
| 668 | + Err(Error::Eof) => break, | |
| 669 | + Err(e) => { | |
| 670 | + failed.push(format!("{}: {e}", name_of(path))); | |
| 671 | + break; | |
| 672 | + } | |
| 673 | + } | |
| 674 | + } | |
| 675 | + // ffprobe counts the same packets on the same file. Two shapes are not | |
| 676 | + // a disagreement: cover art, which ffmpeg lists as an attached-picture | |
| 677 | + // video stream and which is metadata rather than a track; and a track | |
| 678 | + // whose last sample ffmpeg hands out one fewer of than its sample table | |
| 679 | + // states (`nb_frames`) — where ours equals the table, the table is what | |
| 680 | + // the file says. | |
| 681 | + let counted = Command::new("ffprobe") | |
| 682 | + .args([ | |
| 683 | + "-v", | |
| 684 | + "error", | |
| 685 | + "-count_packets", | |
| 686 | + "-show_entries", | |
| 687 | + "stream=codec_type,nb_read_packets,nb_frames:stream_disposition=attached_pic", | |
| 688 | + "-of", | |
| 689 | + "csv=p=0", | |
| 690 | + ]) | |
| 691 | + .arg(path) | |
| 692 | + .output() | |
| 693 | + .expect("ffprobe runs"); | |
| 694 | + // One line a stream: type, packets counted, frames the sample table | |
| 695 | + // states, and whether it is cover art. | |
| 696 | + let rows: Vec<Vec<String>> = String::from_utf8_lossy(&counted.stdout) | |
| 697 | + .lines() | |
| 698 | + .map(|l| { | |
| 699 | + l.split(',') | |
| 700 | + .map(|f| f.trim().to_string()) | |
| 701 | + .collect::<Vec<String>>() | |
| 702 | + }) | |
| 703 | + .filter(|row| { | |
| 704 | + matches!( | |
| 705 | + row.first().map(String::as_str), | |
| 706 | + Some("video" | "audio" | "subtitle") | |
| 707 | + ) && row.get(3).map(String::as_str) != Some("1") | |
| 708 | + }) | |
| 709 | + .collect(); | |
| 710 | + let theirs: Vec<u64> = rows | |
| 711 | + .iter() | |
| 712 | + .map(|r| r.get(1).and_then(|n| n.parse().ok()).unwrap_or(0)) | |
| 713 | + .collect(); | |
| 714 | + let tables: Vec<u64> = rows | |
| 715 | + .iter() | |
| 716 | + .map(|r| r.get(2).and_then(|n| n.parse().ok()).unwrap_or(0)) | |
| 717 | + .collect(); | |
| 718 | + let same = ours == theirs; | |
| 719 | + let by_table = !same && ours == tables; | |
| 720 | + if !same && !by_table { | |
| 721 | + failed.push(format!( | |
| 722 | + "{}: ours {ours:?} against ffprobe {theirs:?}", | |
| 723 | + name_of(path) | |
| 724 | + )); | |
| 725 | + } | |
| 726 | + table.push(format!( | |
| 727 | + "{:<58} {:<18} ours {ours:?} ffprobe {theirs:?} {}", | |
| 728 | + name_of(path), | |
| 729 | + kinds.iter().map(|c| c.name()).collect::<Vec<_>>().join("+"), | |
| 730 | + match (same, by_table) { | |
| 731 | + (true, _) => "PASS".to_string(), | |
| 732 | + (_, true) => format!("PASS (sample table {tables:?})"), | |
| 733 | + _ => "FAIL".to_string(), | |
| 734 | + } | |
| 735 | + )); | |
| 736 | + } | |
| 737 | + println!("{}", table.join("\n")); | |
| 738 | + assert!(failed.is_empty(), "{}", failed.join("\n")); | |
| 739 | +} | |
| 740 | + | |
| 741 | +fn name_of(path: &Path) -> String { | |
| 742 | + let name = path.file_name().unwrap_or_default().to_string_lossy(); | |
| 743 | + name.chars().take(56).collect() | |
| 744 | +} |