forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli4 days ago4021 commits

edith_parity.rs440 lines, 17.6 KiBHistoryRawDownload
1//! Parity with ffprobe, file by file: what ec-mp4 reads out of an mp4 or mov has
2//! to be what ffprobe reads out of the same bytes, sample for sample and field
3//! for field. This is the swap criterion for edith's `mp4::` demuxer: identical
4//! packet bytes, identical timestamps, identical stream metadata.
5//!
6//! The corpus is three sets, each optional where it is not in the checkout:
7//!
8//! - `fixtures/` (video, audio and the derived shapes): always, through the
9//! usual `../../fixtures` symlink.
10//! - edith's `assets/*.mp4|mov|m4a` when `EC_EDITH_ASSETS` names the directory
11//! (default `/home/user/Documents/Code/Rust/edith/assets`; skipped with a
12//! note when absent).
13//! - the generated cases from `scripts/gen-mp4-parity-corpus.sh` when
14//! `EC_MP4_PARITY_CORPUS` names its output directory.
15//!
16//! Per track, the comparison is: codec, coded size, sample rate, channels,
17//! timebase, rotation, and per sample the byte offset, size, presentation time
18//! (`cts` against ffprobe `pts`), the sync flag, and the decode time up to one
19//! constant. ffmpeg's `dts` carries a constant shift of its own (the largest
20//! composition delay), so only its differences are the same claim. Edit lists
21//! are applied on both sides, the same way ffmpeg applies them.
22//!
23//! Where edith's engine reads the file differently on purpose (it trims the
24//! picture by the edit list where ffprobe shifts it, and ignores empty edits),
25//! the edith-only values are printed in the table, not compared. See
26//! `lanes/mp4demux.report.md`.
27
28use std::collections::HashMap;
29use std::fs::File;
30use std::io::BufReader;
31use std::path::{Path, PathBuf};
32use std::process::Command;
33
34use ec_core::{CodecId, Demuxer, MediaParameters};
35use ec_mp4::{Mp4Demuxer, Sample};
36
37use crate::common::ffmpeg_name;
38
39/// One ffprobe `key=value` record block, keyed by field name.
40type Record = HashMap<String, String>;
41
42/// Every `stream=`/`packet=` block of `default=nw=1` output, split where the
43/// `first` key starts a new block.
44fn 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
60fn 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/// What ffprobe says about one stream, `None` where a field is `N/A` or absent.
76#[derive(Debug, Default)]
77struct 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)]
90struct ProbePacket {
91 pts: Option<i64>,
92 dts: Option<i64>,
93 size: u64,
94 pos: Option<u64>,
95 key: bool,
96}
97
98fn number<T: std::str::FromStr>(value: Option<&String>) -> Option<T> {
99 value.and_then(|v| v.parse().ok())
100}
101
102fn 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/// Display rotation per stream index, from the `side_data_list` of the JSON
129/// stream dump. The `side_data=rotation` entry query is not used: on a 2 GB film
130/// ffprobe spends minutes decoding for it, while the JSON dump is immediate.
131fn 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 // Stream objects open with `"index": n,` at the stream's own indent.
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/// Packets per ffprobe stream index, each list in the order ffprobe demuxes
154/// them, which for one stream is decode order.
155fn 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/// ffprobe's rotation (counter-clockwise degrees) as this crate's clockwise
177/// quarter turn: the same matrix, the other direction.
178fn 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/// One file, compared. Returns the table row and every mismatch it found.
187fn 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 // Cover art is not a track: ffprobe lists an `covr` picture as a video stream
194 // with `attached_pic` set, and this crate does not list it (a player that
195 // shows an album cover as a video stream is the bug). Dropped on both sides.
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 // The track position is the only index the two share, so the counts agree
203 // or the rest of the comparison is meaningless.
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 // Both sides name the same matrix; ffprobe counts counter-clockwise.
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 // Implicit HE-AAC (SBR with no extension frequency in the config):
243 // ffprobe decodes the first frames for the doubled output rate,
244 // and so does edith (`mp4_aac_prime`); this reader reports the core's.
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 // Per sample, against ffprobe's packets of the same stream.
261 let theirs = packets.get(&(position as u32)).cloned().unwrap_or_default();
262 // A subtitle track ends in a zero-duration sample at the movie's end, an
263 // end marker ffprobe does not hand out as a packet. Dropped on this side
264 // for the comparison only; the sample is still in the table.
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 // VP8 and VP9 carry no `stss` in these files, so the box makes every
280 // sample a sync sample, while ffprobe reads the key flag out of the
281 // bitstream. The box is what edith follows; the flag difference is named.
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/// Every mp4-family file under `dir`, recursively, into `files`.
338fn 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
355fn 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 // The real library: the local films the scan recorded as mp4-family, when
366 // they are still on this machine. A missing file is skipped, as the scan does.
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]
390fn 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/// The edith-side reading of the edit list and the sample table, on fixtures
413/// whose answers are known: an AAC track whose edit list trims one 1024-sample
414/// priming packet, and an open-GOP stream whose keyframes sit out of display
415/// order.
416#[test]
417fn 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}