forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

real_library_containers.rs229 lines, 8.0 KiBHistoryRawDownload
1//! The mp4 demuxer against ffprobe, on the owner's own files. For each stream
2//! the packet table `ec-mp4` hands out -- payload bytes, pts, dts, duration,
3//! keyframe flag -- is compared packet for packet with
4//! `ffprobe -show_packets -show_data_hash md5`, and the stream's codec tag,
5//! time base, size or sample format is compared with ffprobe's stream entry.
6//!
7//! Each file is named by `real_library.toml` (gitignored); a key it does not
8//! name, or a path not on this machine, skips. Needs ffprobe.
9
10use crate::reallib;
11
12use std::collections::HashMap;
13use std::fs::File;
14
15use ec_core::Demuxer as _;
16use reallib::{ffprobe_packets, ffprobe_streams, have, md5_hex};
17
18/// One packet as `ec-mp4` states it, in the stream's own time base.
19#[derive(Debug, PartialEq)]
20struct Row {
21 pts: Option<i64>,
22 dts: i64,
23 duration: Option<i64>,
24 size: usize,
25 key: bool,
26 md5: String,
27}
28
29fn check_mp4(key: &str) {
30 let Some(path) = engine::real_library::film(key) else {
31 return;
32 };
33 if !have("ffprobe") {
34 eprintln!("skipped: no ffprobe to state the reference packets");
35 return;
36 }
37 let ff_streams = ffprobe_streams(&path);
38 let ff_packets = ffprobe_packets(&path);
39
40 let mut demux =
41 ec_mp4::Mp4Demuxer::new(File::open(&path).expect("open")).expect("ec-mp4 opens");
42 let streams = demux.streams().to_vec();
43 let tracks = demux.tracks().to_vec();
44
45 // ec streams are matched to ffprobe streams by their sample-entry tag, the
46 // k-th of a tag to the k-th of that tag in track order.
47 let mut ff_by_tag: HashMap<String, Vec<&reallib::FfStream>> = HashMap::new();
48 for s in &ff_streams {
49 ff_by_tag.entry(s.tag.clone()).or_default().push(s);
50 }
51 let mut taken: HashMap<String, usize> = HashMap::new();
52 let mut pairs = Vec::new();
53 for (i, info) in streams.iter().enumerate() {
54 let track = tracks
55 .iter()
56 .find(|t| t.stream == Some(i as u32))
57 .expect("every ec stream is a track");
58 let tag = String::from_utf8_lossy(&track.sample_entry).to_string();
59 let n = taken.entry(tag.clone()).or_insert(0);
60 let Some(ff) = ff_by_tag.get(&tag).and_then(|v| v.get(*n)) else {
61 panic!("{key}: ec stream {i} ({tag}) has no ffprobe stream with that tag");
62 };
63 *n += 1;
64 pairs.push((
65 i as u32,
66 ff.index,
67 (info.time_base, info.params.media.clone()),
68 (*ff).clone(),
69 ));
70 }
71 eprintln!(
72 "{key}: {} of {} ffprobe streams compared (the rest are not picture or sound tracks ec-mp4 maps)",
73 pairs.len(),
74 ff_streams.len()
75 );
76
77 // Stream metadata against ffprobe.
78 for (ec, ff_index, (tb, media), ff) in &pairs {
79 let (num, den) = ff
80 .time_base
81 .split_once('/')
82 .map(|(a, b)| (a.parse::<f64>().unwrap(), b.parse::<f64>().unwrap()))
83 .expect("ffprobe time base");
84 let ff_secs = num / den;
85 assert!(
86 (tb.as_secs_f64() - ff_secs).abs() < 1e-12,
87 "{key}: stream {ec} time base {} vs ffprobe {}",
88 tb.as_secs_f64(),
89 ff_secs
90 );
91 match media {
92 ec_core::MediaParameters::Video(v) => {
93 assert_eq!(
94 (Some(v.width), Some(v.height)),
95 (ff.width, ff.height),
96 "{key}: stream {ec} picture size"
97 );
98 }
99 ec_core::MediaParameters::Audio(a) => {
100 assert_eq!(
101 Some(a.sample_rate),
102 ff.sample_rate,
103 "{key}: stream {ec} sample rate"
104 );
105 }
106 ec_core::MediaParameters::Subtitle => {}
107 }
108 eprintln!(
109 "{key}: stream {ec} -> ffprobe {ff_index} {} {} {:?}x{:?} {:?}Hz {:?}ch",
110 ff.kind, ff.tag, ff.width, ff.height, ff.sample_rate, ff.channels
111 );
112 }
113
114 // Packet tables, per stream, in each stream's own order.
115 let mut ec_rows: HashMap<u32, Vec<Row>> = HashMap::new();
116 loop {
117 let p = match demux.next_packet() {
118 Ok(p) => p,
119 Err(ec_core::Error::Eof) => break,
120 Err(e) => panic!("{key}: ec-mp4 packet read: {e}"),
121 };
122 ec_rows.entry(p.stream).or_default().push(Row {
123 pts: p.pts,
124 dts: p.dts.or(p.pts).unwrap_or(0),
125 duration: p.duration,
126 size: p.data.len(),
127 key: p.flags.keyframe,
128 md5: md5_hex(&p.data),
129 });
130 }
131
132 for (ec, ff_index, _, _) in &pairs {
133 let want: Vec<Row> = ff_packets
134 .iter()
135 .filter(|p| p.stream == *ff_index)
136 .map(|p| Row {
137 pts: p.pts,
138 dts: p.dts.or(p.pts).unwrap_or(0),
139 duration: p.duration,
140 size: p.size,
141 key: p.key,
142 md5: p.md5.clone(),
143 })
144 .collect();
145 let got = ec_rows.remove(ec).unwrap_or_default();
146 assert_eq!(got.len(), want.len(), "{key}: stream {ec} packet count");
147 let mut differ = [0usize; 6];
148 for (g, w) in got.iter().zip(&want) {
149 differ[0] += (g.pts != w.pts) as usize;
150 differ[1] += (g.dts != w.dts) as usize;
151 differ[2] += (g.duration != w.duration) as usize;
152 differ[3] += (g.size != w.size) as usize;
153 differ[4] += (g.key != w.key) as usize;
154 differ[5] += (g.md5 != w.md5) as usize;
155 }
156 let ec_sum: i64 = got.iter().filter_map(|g| g.duration).sum();
157 eprintln!(
158 "{key}: stream {ec}: {} packets; differing pts/dts/duration/size/key/md5 = {differ:?}; \
159 sum of ec durations {ec_sum}, ffprobe stream duration_ts {:?}",
160 got.len(),
161 ff_streams
162 .iter()
163 .find(|s| s.index == *ff_index)
164 .map(|s| s.duration_ts)
165 );
166 assert_eq!(
167 differ[..2],
168 [0, 0],
169 "{key}: stream {ec}: timestamps differ from ffprobe"
170 );
171 assert_eq!(
172 differ[3..],
173 [0, 0, 0],
174 "{key}: stream {ec}: size/key/payload differ from ffprobe"
175 );
176 // A packet duration ffprobe states differently is only excused where
177 // ffprobe's own figure is unusable (N/A or 1 tick, on every packet of
178 // a fragmented VP9 track). ec-mp4 then gives the fragment's trun sample
179 // duration, which the file itself states; see the note in the report.
180 if differ[2] > 0 {
181 let unusable = want
182 .iter()
183 .filter(|w| matches!(w.duration, None | Some(1)))
184 .count();
185 assert_eq!(
186 unusable, differ[2],
187 "{key}: stream {ec}: duration differs from ffprobe on packets it states usably"
188 );
189 eprintln!(
190 "{key}: stream {ec}: {} packets where ffprobe states no usable duration (N/A or 1)",
191 unusable
192 );
193 }
194 }
195}
196
197/// H.264 + AAC-LC, 640x1138, 44.1 kHz stereo: the plain mp4 case.
198#[test]
199fn real_mp4_h264_aac_packets_match_ffprobe() {
200 check_mp4("mp4_h264_aac");
201}
202
203/// A phone recording: H.264 High 720p with full-range (yuvj420p) pixels and
204/// AAC-LC at 48 kHz.
205#[test]
206fn real_mp4_phone_h264_packets_match_ffprobe() {
207 check_mp4("mp4_phone_h264");
208}
209
210/// An H.264 4K-wide film with an AAC-LC track and a `mov_text` subtitle track;
211/// the subtitle packets are not ec-mp4 picture or sound packets, so they are
212/// not compared.
213#[test]
214fn real_mp4_mov_text_packets_match_ffprobe() {
215 check_mp4("mp4_mov_text");
216}
217
218/// An HE-AAC v1 (SBR) track in mp4: the packet table is the same shape as AAC-LC,
219/// the decode is checked in `real_library_audio`.
220#[test]
221fn real_mp4_heaac_packets_match_ffprobe() {
222 check_mp4("mp4_heaac");
223}
224
225/// VP9 Profile 0 and Opus in mp4: the packets of both tracks.
226#[test]
227fn real_mp4_vp9_opus_packets_match_ffprobe() {
228 check_mp4("vp9_opus_mp4");
229}