| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | use std::collections::HashMap; |
| 29 | use std::fs::File; |
| 30 | use std::io::BufReader; |
| 31 | use std::path::{Path, PathBuf}; |
| 32 | use std::process::Command; |
| 33 | |
| 34 | use ec_core::{CodecId, Demuxer, MediaParameters}; |
| 35 | use ec_mp4::{Mp4Demuxer, Sample}; |
| 36 | |
| 37 | use crate::common::ffmpeg_name; |
| 38 | |
| 39 | |
| 40 | type Record = HashMap<String, String>; |
| 41 | |
| 42 | |
| 43 | |
| 44 | fn records(text: &str, first: &str) -> Vec<Record> { |
| 45 | let mut out: Vec<Record> = Vec::new(); |
| 46 | for line in text.lines() { |
| 47 | let Some((key, value)) = line.split_once('=') else { |
| 48 | continue; |
| 49 | }; |
| 50 | if key == first { |
| 51 | out.push(Record::new()); |
| 52 | } |
| 53 | if let Some(record) = out.last_mut() { |
| 54 | record.insert(key.to_string(), value.to_string()); |
| 55 | } |
| 56 | } |
| 57 | out |
| 58 | } |
| 59 | |
| 60 | fn ffprobe(path: &Path, entries: &str, first: &str) -> Vec<Record> { |
| 61 | let out = Command::new("ffprobe") |
| 62 | .args(["-v", "error", "-show_entries", entries, "-of", "default=nw=1"]) |
| 63 | .arg(path) |
| 64 | .output() |
| 65 | .expect("ffprobe runs"); |
| 66 | assert!( |
| 67 | out.status.success(), |
| 68 | "ffprobe refused {}: {}", |
| 69 | path.display(), |
| 70 | String::from_utf8_lossy(&out.stderr) |
| 71 | ); |
| 72 | records(&String::from_utf8_lossy(&out.stdout), first) |
| 73 | } |
| 74 | |
| 75 | |
| 76 | #[derive(Debug, Default)] |
| 77 | struct ProbeStream { |
| 78 | codec: String, |
| 79 | width: Option<u32>, |
| 80 | height: Option<u32>, |
| 81 | sample_rate: Option<u32>, |
| 82 | channels: Option<u32>, |
| 83 | time_base: String, |
| 84 | duration_ts: Option<i64>, |
| 85 | rotation: Option<i32>, |
| 86 | attached_pic: bool, |
| 87 | } |
| 88 | |
| 89 | #[derive(Debug, Clone, Copy)] |
| 90 | struct ProbePacket { |
| 91 | pts: Option<i64>, |
| 92 | dts: Option<i64>, |
| 93 | size: u64, |
| 94 | pos: Option<u64>, |
| 95 | key: bool, |
| 96 | } |
| 97 | |
| 98 | fn number<T: std::str::FromStr>(value: Option<&String>) -> Option<T> { |
| 99 | value.and_then(|v| v.parse().ok()) |
| 100 | } |
| 101 | |
| 102 | fn probe_streams(path: &Path, rotations: &HashMap<u32, i32>) -> Vec<ProbeStream> { |
| 103 | ffprobe( |
| 104 | path, |
| 105 | "stream=index,codec_name,codec_type,width,height,sample_rate,channels,time_base,duration_ts:stream_disposition=attached_pic", |
| 106 | "index", |
| 107 | ) |
| 108 | .into_iter() |
| 109 | .map(|r| { |
| 110 | let index = number::<u32>(r.get("index")).unwrap_or(u32::MAX); |
| 111 | ProbeStream { |
| 112 | codec: r.get("codec_name").cloned().unwrap_or_default(), |
| 113 | width: number(r.get("width")), |
| 114 | height: number(r.get("height")), |
| 115 | sample_rate: number(r.get("sample_rate")), |
| 116 | channels: number(r.get("channels")), |
| 117 | time_base: r.get("time_base").cloned().unwrap_or_default(), |
| 118 | duration_ts: number(r.get("duration_ts")), |
| 119 | rotation: rotations.get(&index).copied(), |
| 120 | attached_pic: r |
| 121 | .get("DISPOSITION:attached_pic") |
| 122 | .is_some_and(|v| v == "1"), |
| 123 | } |
| 124 | }) |
| 125 | .collect() |
| 126 | } |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | fn rotations(path: &Path) -> HashMap<u32, i32> { |
| 132 | let out = Command::new("ffprobe") |
| 133 | .args(["-v", "error", "-show_streams", "-of", "json"]) |
| 134 | .arg(path) |
| 135 | .output() |
| 136 | .expect("ffprobe runs"); |
| 137 | let mut found = HashMap::new(); |
| 138 | let mut current = None; |
| 139 | for line in String::from_utf8_lossy(&out.stdout).lines() { |
| 140 | let line = line.trim(); |
| 141 | |
| 142 | if let Some(rest) = line.strip_prefix("\"index\": ") { |
| 143 | current = rest.trim_end_matches(',').parse::<u32>().ok(); |
| 144 | } else if let Some(rest) = line.strip_prefix("\"rotation\": ") |
| 145 | && let (Some(index), Ok(r)) = (current, rest.trim_end_matches(',').parse::<i32>()) |
| 146 | { |
| 147 | found.insert(index, r); |
| 148 | } |
| 149 | } |
| 150 | found |
| 151 | } |
| 152 | |
| 153 | |
| 154 | |
| 155 | fn probe_packets(path: &Path) -> HashMap<u32, Vec<ProbePacket>> { |
| 156 | let mut by_stream: HashMap<u32, Vec<ProbePacket>> = HashMap::new(); |
| 157 | for r in ffprobe( |
| 158 | path, |
| 159 | "packet=stream_index,pts,dts,size,pos,flags", |
| 160 | "stream_index", |
| 161 | ) { |
| 162 | let Some(index) = number::<u32>(r.get("stream_index")) else { |
| 163 | continue; |
| 164 | }; |
| 165 | by_stream.entry(index).or_default().push(ProbePacket { |
| 166 | pts: number(r.get("pts")), |
| 167 | dts: number(r.get("dts")), |
| 168 | size: number(r.get("size")).unwrap_or(0), |
| 169 | pos: number(r.get("pos")), |
| 170 | key: r.get("flags").is_some_and(|f| f.starts_with('K')), |
| 171 | }); |
| 172 | } |
| 173 | by_stream |
| 174 | } |
| 175 | |
| 176 | |
| 177 | |
| 178 | fn expected_rotation(rotation: Option<i32>) -> Option<u8> { |
| 179 | match rotation { |
| 180 | None => Some(0), |
| 181 | Some(r) if r % 90 == 0 => Some((-r / 90).rem_euclid(4) as u8), |
| 182 | Some(_) => None, |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | |
| 187 | fn compare(path: &Path) -> (String, Vec<String>) { |
| 188 | let mut problems = Vec::new(); |
| 189 | let file = File::open(path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); |
| 190 | let demuxer = Mp4Demuxer::new(BufReader::new(file)) |
| 191 | .unwrap_or_else(|e| panic!("{}: {e}", path.display())); |
| 192 | let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned(); |
| 193 | |
| 194 | |
| 195 | |
| 196 | let rotations = rotations(path); |
| 197 | let all_probed = probe_streams(path, &rotations); |
| 198 | let probed: Vec<ProbeStream> = all_probed.into_iter().filter(|p| !p.attached_pic).collect(); |
| 199 | let packets = probe_packets(path); |
| 200 | let tracks = demuxer.tracks().to_vec(); |
| 201 | if probed.len() != tracks.len() { |
| 202 | |
| 203 | |
| 204 | problems.push(format!("track count: ec {} ffprobe {}", tracks.len(), probed.len())); |
| 205 | } |
| 206 | let mut rows = Vec::new(); |
| 207 | for (position, track) in tracks.iter().enumerate() { |
| 208 | let Some(stream) = track.stream else { |
| 209 | continue; |
| 210 | }; |
| 211 | let Some(p) = probed.get(position) else { |
| 212 | problems.push(format!("track {position}: no ffprobe stream")); |
| 213 | continue; |
| 214 | }; |
| 215 | let info = demuxer.streams()[stream as usize].clone(); |
| 216 | let samples: Vec<Sample> = demuxer.samples(stream).to_vec(); |
| 217 | let tag = format!("track {position} ({})", ffmpeg_name(info.params.codec)); |
| 218 | if ffmpeg_name(info.params.codec) != p.codec { |
| 219 | problems.push(format!("{tag}: codec, ffprobe says {}", p.codec)); |
| 220 | } |
| 221 | let tb = format!("{}/{}", info.time_base.num(), info.time_base.den()); |
| 222 | if tb != p.time_base { |
| 223 | problems.push(format!("{tag}: timebase {tb} vs {}", p.time_base)); |
| 224 | } |
| 225 | match &info.params.media { |
| 226 | MediaParameters::Video(v) => { |
| 227 | if Some((v.width, v.height)) != p.width.zip(p.height) { |
| 228 | problems.push(format!( |
| 229 | "{tag}: coded size {}x{} vs ffprobe {:?}x{:?}", |
| 230 | v.width, v.height, p.width, p.height |
| 231 | )); |
| 232 | } |
| 233 | |
| 234 | if info.rotation.steps() != expected_rotation(p.rotation) { |
| 235 | problems.push(format!( |
| 236 | "{tag}: rotation {:?} vs ffprobe {:?}", |
| 237 | info.rotation, p.rotation |
| 238 | )); |
| 239 | } |
| 240 | } |
| 241 | MediaParameters::Audio(a) => { |
| 242 | |
| 243 | |
| 244 | |
| 245 | let implicit_sbr = info.params.codec == CodecId::Aac |
| 246 | && p.sample_rate == Some(a.sample_rate * 2); |
| 247 | if Some(a.sample_rate) != p.sample_rate && !implicit_sbr { |
| 248 | problems.push(format!("{tag}: rate {} vs {:?}", a.sample_rate, p.sample_rate)); |
| 249 | } |
| 250 | if Some(a.layout.channel_count() as u32) != p.channels { |
| 251 | problems.push(format!( |
| 252 | "{tag}: channels {} vs {:?}", |
| 253 | a.layout.channel_count(), |
| 254 | p.channels |
| 255 | )); |
| 256 | } |
| 257 | } |
| 258 | MediaParameters::Subtitle => {} |
| 259 | } |
| 260 | |
| 261 | let theirs = packets.get(&(position as u32)).cloned().unwrap_or_default(); |
| 262 | |
| 263 | |
| 264 | |
| 265 | let mut samples = samples; |
| 266 | if matches!(info.params.media, MediaParameters::Subtitle) |
| 267 | && samples.len() == theirs.len() + 1 |
| 268 | && samples.last().is_some_and(|s| s.duration == 0) |
| 269 | { |
| 270 | samples.pop(); |
| 271 | } |
| 272 | if theirs.len() != samples.len() { |
| 273 | problems.push(format!( |
| 274 | "{tag}: {} samples vs {} packets", |
| 275 | samples.len(), |
| 276 | theirs.len() |
| 277 | )); |
| 278 | } |
| 279 | |
| 280 | |
| 281 | |
| 282 | let box_says_all_sync = samples.iter().all(|s| s.sync); |
| 283 | let bitstream_keys = theirs.iter().filter(|p| p.key).count(); |
| 284 | let vp_box_only = matches!(info.params.codec, CodecId::Vp8 | CodecId::Vp9) |
| 285 | && box_says_all_sync |
| 286 | && bitstream_keys < samples.len(); |
| 287 | let mut dts_shift: Option<i64> = None; |
| 288 | let (mut bad_pos, mut bad_size, mut bad_pts, mut bad_sync, mut bad_dts) = (0, 0, 0, 0, 0); |
| 289 | for (ours, theirs) in samples.iter().zip(&theirs) { |
| 290 | if theirs.pos != Some(ours.offset) { |
| 291 | bad_pos += 1; |
| 292 | } |
| 293 | if u64::from(ours.size) != theirs.size { |
| 294 | bad_size += 1; |
| 295 | } |
| 296 | if theirs.pts != Some(ours.cts) { |
| 297 | bad_pts += 1; |
| 298 | } |
| 299 | if theirs.key != ours.sync && !vp_box_only { |
| 300 | bad_sync += 1; |
| 301 | } |
| 302 | match (theirs.dts, dts_shift) { |
| 303 | (Some(d), None) => dts_shift = Some(ours.dts - d), |
| 304 | (Some(d), Some(k)) if ours.dts - d != k => bad_dts += 1, |
| 305 | (None, _) => bad_dts += 1, |
| 306 | _ => {} |
| 307 | } |
| 308 | } |
| 309 | for (what, n) in [ |
| 310 | ("offset", bad_pos), |
| 311 | ("size", bad_size), |
| 312 | ("pts", bad_pts), |
| 313 | ("sync", bad_sync), |
| 314 | ("dts", bad_dts), |
| 315 | ] { |
| 316 | if n > 0 { |
| 317 | problems.push(format!("{tag}: {n} samples differ in {what}")); |
| 318 | } |
| 319 | } |
| 320 | let syncs = demuxer.sync_in_display_order(stream).len(); |
| 321 | rows.push(format!( |
| 322 | " t{position} {:<7} n={:<6} trim={:<8} first={:<6} dts-shift={:<6} edits={:?} display-syncs={syncs} duration_ts={:?}/{:?}", |
| 323 | ffmpeg_name(info.params.codec), |
| 324 | samples.len(), |
| 325 | format!("{:?}", demuxer.presentation_trim(stream)), |
| 326 | demuxer.first_frame_sample(stream), |
| 327 | dts_shift.map_or("-".into(), |k| k.to_string()), |
| 328 | track.edits.iter().map(|e| (e.segment_duration, e.media_time)).collect::<Vec<_>>(), |
| 329 | p.duration_ts, |
| 330 | info.duration, |
| 331 | )); |
| 332 | } |
| 333 | let row = format!("{name}\n{}", rows.join("\n")); |
| 334 | (row, problems) |
| 335 | } |
| 336 | |
| 337 | |
| 338 | fn collect(dir: &Path, files: &mut Vec<PathBuf>) { |
| 339 | let Ok(entries) = std::fs::read_dir(dir) else { |
| 340 | return; |
| 341 | }; |
| 342 | for entry in entries.flatten() { |
| 343 | let path = entry.path(); |
| 344 | if path.is_dir() { |
| 345 | collect(&path, files); |
| 346 | continue; |
| 347 | } |
| 348 | let name = path.to_string_lossy().to_ascii_lowercase(); |
| 349 | if [".mp4", ".m4a", ".m4v", ".mov"].iter().any(|ext| name.ends_with(ext)) { |
| 350 | files.push(path); |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | fn corpus() -> Vec<PathBuf> { |
| 356 | let mut files = Vec::new(); |
| 357 | collect(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"), &mut files); |
| 358 | let assets = std::env::var("EC_EDITH_ASSETS") |
| 359 | .unwrap_or_else(|_| "/home/user/Documents/Code/Rust/edith/assets".into()); |
| 360 | if Path::new(&assets).is_dir() { |
| 361 | collect(Path::new(&assets), &mut files); |
| 362 | } else { |
| 363 | eprintln!("edith_parity: no edith assets at {assets}; skipped"); |
| 364 | } |
| 365 | |
| 366 | |
| 367 | if let Ok(manifest) = std::fs::read_to_string( |
| 368 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"), |
| 369 | ) { |
| 370 | for line in manifest.lines().skip(1) { |
| 371 | let mut fields = line.split('\t'); |
| 372 | let (Some(path), Some(container)) = (fields.next(), fields.next()) else { |
| 373 | continue; |
| 374 | }; |
| 375 | if container.contains("mp4") && Path::new(path).is_file() { |
| 376 | files.push(PathBuf::from(path)); |
| 377 | } |
| 378 | } |
| 379 | } |
| 380 | match std::env::var("EC_MP4_PARITY_CORPUS") { |
| 381 | Ok(dir) => collect(Path::new(&dir), &mut files), |
| 382 | Err(_) => eprintln!("edith_parity: EC_MP4_PARITY_CORPUS unset; generated cases skipped"), |
| 383 | } |
| 384 | files.sort(); |
| 385 | files.dedup(); |
| 386 | files |
| 387 | } |
| 388 | |
| 389 | #[test] |
| 390 | fn every_corpus_file_matches_ffprobe_sample_for_sample() { |
| 391 | let files = corpus(); |
| 392 | assert!(!files.is_empty(), "no mp4/mov corpus; run scripts/link-fixtures.sh"); |
| 393 | let mut report = Vec::new(); |
| 394 | let mut failures = Vec::new(); |
| 395 | for path in &files { |
| 396 | let (row, problems) = compare(path); |
| 397 | report.push(row); |
| 398 | if !problems.is_empty() { |
| 399 | failures.push(format!("{}:\n {}", path.display(), problems.join("\n "))); |
| 400 | } |
| 401 | } |
| 402 | println!("{}", report.join("\n")); |
| 403 | assert!( |
| 404 | failures.is_empty(), |
| 405 | "{} of {} files differ from ffprobe:\n{}", |
| 406 | failures.len(), |
| 407 | files.len(), |
| 408 | failures.join("\n") |
| 409 | ); |
| 410 | } |
| 411 | |
| 412 | |
| 413 | |
| 414 | |
| 415 | |
| 416 | #[test] |
| 417 | fn edith_trim_and_display_order_read_the_known_fixtures() { |
| 418 | let aac = Path::new(env!("CARGO_MANIFEST_DIR")) |
| 419 | .join("../../fixtures/audio/aac-mp4-stereo-48000.mp4"); |
| 420 | let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&aac).expect("fixture"))) |
| 421 | .expect("the fixture demuxes"); |
| 422 | assert_eq!(demuxer.presentation_trim(0), Some(1024)); |
| 423 | assert_eq!(demuxer.first_frame_sample(0), 2, "the trim lands on packet 2"); |
| 424 | assert!(demuxer.sync_in_display_order(0).is_empty(), "no ctts, no reorder"); |
| 425 | |
| 426 | let gop = Path::new(env!("CARGO_MANIFEST_DIR")) |
| 427 | .join("../../fixtures/video/h264-open-gop.mp4"); |
| 428 | let demuxer = Mp4Demuxer::new(BufReader::new(File::open(&gop).expect("fixture"))) |
| 429 | .expect("the fixture demuxes"); |
| 430 | let syncs = demuxer.sync_in_display_order(0); |
| 431 | assert!(!syncs.is_empty(), "B-frames: the display table answers"); |
| 432 | assert!( |
| 433 | syncs.windows(2).all(|w| w[0].0 < w[1].0 && w[0].1 != w[1].1), |
| 434 | "display indices ascend: {syncs:?}" |
| 435 | ); |
| 436 | let samples = demuxer.samples(0); |
| 437 | for &(_, decode) in &syncs { |
| 438 | assert!(samples[decode as usize].sync, "decode {decode} is a sync sample"); |
| 439 | } |
| 440 | } |