forge
Explore
Log in

Don't you dare go Hollow

Fixture remux, seek loop and real-library sweep

Browse files at this commit

2c0d9b848d5bfb60daf6f8c0d05004a1631241b7Ahmet Kaan GümüşParent: 550709b
  • test
    • fixture remux, seek loop and real-library sweep
Show full message
test(matroska): fixture remux, seek loop and real-library sweep

Every mkv/webm/mka fixture is demuxed, written back out through this crate's
muxer and field-compared with ffprobe before ffmpeg decodes the result; a
hundred random seeks per fixture run on one reader each and every one lands
on a random-access point at or before its target.

The ignored sweep walks ten films of the real library end to end, matches
their per-stream packet counts against ffprobe and seeks twenty times in
each.
crates/ec-matroska/tests/matroska.rsadded+496 -0
@@ -0,0 +1,496 @@
1+//! What the fixtures say: every Matroska/WebM fixture demuxes, remuxes into a
2+//! file ffprobe agrees with and ffmpeg decodes, and a hundred random seeks land
3+//! on a sync point at or before their target — all on the one reader each file
4+//! was opened with.
5+
6+use std::fs::File;
7+use std::io::BufReader;
8+use std::path::{Path, PathBuf};
9+use std::process::Command;
10+
11+use ec_core::{Demuxer, Error, Muxer, SeekMode, TimeBase, Timestamp};
12+use ec_matroska::{MatroskaDemuxer, MatroskaMuxer};
13+
14+fn fixtures() -> PathBuf {
15+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
16+}
17+
18+fn work() -> PathBuf {
19+ let dir = std::env::temp_dir().join("ec-matroska-tests");
20+ std::fs::create_dir_all(&dir).expect("test work directory");
21+ dir
22+}
23+
24+/// Every Matroska the fixture tree holds, plus the WebM, the audio-only `.mka`
25+/// and the video+subtitle file ffmpeg is asked to make once — the extensions
26+/// this crate claims are exactly the ones that have to be exercised.
27+fn matroska_fixtures() -> Vec<PathBuf> {
28+ let mut files: Vec<PathBuf> = std::fs::read_dir(fixtures().join("video"))
29+ .expect("fixtures/video (run scripts/gen-fixtures.sh)")
30+ .filter_map(|e| e.ok().map(|e| e.path()))
31+ .filter(|p| {
32+ let name = p.to_string_lossy();
33+ name.ends_with(".mkv") || name.ends_with(".webm") || name.ends_with(".mk3d")
34+ })
35+ .collect();
36+ files.sort();
37+ files.extend(derived_fixtures());
38+ files
39+}
40+
41+/// The three shapes the generated corpus has none of: a WebM, an audio-only
42+/// `.mka` and a file whose picture travels with sound and subtitles.
43+fn derived_fixtures() -> Vec<PathBuf> {
44+ let src = fixtures().join("video/vp9-1080p-23.976-8bit.mkv");
45+ let subs = fixtures().join("subs/real.srt");
46+ let out = work();
47+ let webm = out.join("vp9-opus.webm");
48+ let mka = out.join("opus.mka");
49+ let subbed = out.join("h264-aac-srt.mkv");
50+ let h264 = fixtures().join("video/h264-1080p-23.976-8bit.mkv");
51+ let (src, h264, subs) = (
52+ src.to_string_lossy().into_owned(),
53+ h264.to_string_lossy().into_owned(),
54+ subs.to_string_lossy().into_owned(),
55+ );
56+ let jobs: [(&PathBuf, Vec<&str>); 3] = [
57+ (
58+ &webm,
59+ vec![
60+ "-i",
61+ &src,
62+ "-f",
63+ "lavfi",
64+ "-i",
65+ "sine=frequency=440:duration=2",
66+ "-c:v",
67+ "copy",
68+ "-c:a",
69+ "libopus",
70+ "-shortest",
71+ ],
72+ ),
73+ (
74+ &mka,
75+ vec![
76+ "-f",
77+ "lavfi",
78+ "-i",
79+ "sine=frequency=220:duration=3",
80+ "-c:a",
81+ "libopus",
82+ ],
83+ ),
84+ (
85+ &subbed,
86+ vec![
87+ "-i",
88+ &h264,
89+ "-f",
90+ "lavfi",
91+ "-i",
92+ "sine=frequency=330:duration=2",
93+ "-i",
94+ &subs,
95+ "-map",
96+ "0:v",
97+ "-map",
98+ "1:a",
99+ "-map",
100+ "2:s",
101+ "-c:v",
102+ "copy",
103+ "-c:a",
104+ "aac",
105+ "-c:s",
106+ "srt",
107+ "-shortest",
108+ ],
109+ ),
110+ ];
111+ let mut made = Vec::new();
112+ for (path, args) in jobs {
113+ if !path.exists() {
114+ let ok = Command::new("ffmpeg")
115+ .args(["-v", "error", "-y"])
116+ .args(&args)
117+ .arg(path)
118+ .status()
119+ .map(|s| s.success())
120+ .unwrap_or(false);
121+ if !ok {
122+ continue;
123+ }
124+ }
125+ made.push(path.clone());
126+ }
127+ made
128+}
129+
130+/// The fields a remux must not change, as ffprobe reads them back.
131+fn probe(path: &Path) -> String {
132+ let out = Command::new("ffprobe")
133+ .args([
134+ "-v",
135+ "error",
136+ "-show_entries",
137+ "stream=index,codec_name,codec_type,width,height,r_frame_rate,sample_rate,channels:\
138+ format=nb_streams",
139+ "-of",
140+ "compact=p=0:nk=0",
141+ ])
142+ .arg(path)
143+ .output()
144+ .expect("ffprobe runs");
145+ assert!(
146+ out.status.success(),
147+ "ffprobe refused {}: {}",
148+ path.display(),
149+ String::from_utf8_lossy(&out.stderr)
150+ );
151+ String::from_utf8_lossy(&out.stdout).into_owned()
152+}
153+
154+fn duration(path: &Path) -> f64 {
155+ let out = Command::new("ffprobe")
156+ .args([
157+ "-v",
158+ "error",
159+ "-show_entries",
160+ "format=duration",
161+ "-of",
162+ "csv=p=0",
163+ ])
164+ .arg(path)
165+ .output()
166+ .expect("ffprobe runs");
167+ String::from_utf8_lossy(&out.stdout)
168+ .trim()
169+ .parse()
170+ .unwrap_or(0.0)
171+}
172+
173+/// Every packet of `src` through this crate's own writer, and how many there
174+/// were.
175+fn remux(src: &Path, dst: &Path) -> usize {
176+ let mut demuxer = MatroskaDemuxer::new(BufReader::new(File::open(src).expect("fixture opens")))
177+ .expect("demuxes");
178+ // A WebM stays a WebM: the subset is what a browser will open, and a file
179+ // remuxed out of it under the `matroska` doc type is one it refuses.
180+ let out = File::create(dst).expect("output file");
181+ let mut muxer = match demuxer.doc_type() {
182+ "webm" => MatroskaMuxer::webm(out),
183+ _ => MatroskaMuxer::new(out),
184+ };
185+ for stream in demuxer.streams().to_vec() {
186+ muxer.add_stream(stream).expect("stream declared");
187+ }
188+ let mut packets = 0;
189+ loop {
190+ match demuxer.next_packet() {
191+ Ok(packet) => {
192+ muxer.write_packet(&packet).expect("packet written");
193+ packets += 1;
194+ }
195+ Err(Error::Eof) => break,
196+ Err(e) => panic!("{}: {e}", src.display()),
197+ }
198+ }
199+ muxer.finish().expect("finished");
200+ packets
201+}
202+
203+#[test]
204+fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() {
205+ let files = matroska_fixtures();
206+ assert!(!files.is_empty(), "no Matroska fixtures found");
207+ let mut table = Vec::new();
208+ for src in &files {
209+ let dst = work().join(format!(
210+ "remux-{}",
211+ src.file_name().unwrap().to_string_lossy()
212+ ));
213+ let packets = remux(src, &dst);
214+ assert!(packets > 0, "{}: no packets", src.display());
215+
216+ let (before, after) = (probe(src), probe(&dst));
217+ assert_eq!(before, after, "{} field-compares", src.display());
218+ let (d0, d1) = (duration(src), duration(&dst));
219+ assert!(
220+ (d0 - d1).abs() <= 0.10,
221+ "{}: duration {d0} became {d1}",
222+ src.display()
223+ );
224+
225+ // ...and it decodes, which is the only claim a field compare cannot make.
226+ let decode = Command::new("ffmpeg")
227+ .args(["-v", "error", "-i"])
228+ .arg(&dst)
229+ .args(["-f", "null", "-"])
230+ .output()
231+ .expect("ffmpeg runs");
232+ assert!(
233+ decode.status.success() && decode.stderr.is_empty(),
234+ "{} does not decode: {}",
235+ dst.display(),
236+ String::from_utf8_lossy(&decode.stderr)
237+ );
238+ table.push(format!(
239+ "{:<40} {packets:>6} packets {d0:.3}s -> {d1:.3}s decodes",
240+ src.file_name().unwrap().to_string_lossy()
241+ ));
242+ }
243+ println!("{}", table.join("\n"));
244+}
245+
246+#[test]
247+fn a_hundred_random_seeks_land_at_or_before_their_target_on_one_reader() {
248+ // xorshift, so the targets are spread and the run is reproducible without a
249+ // dependency.
250+ let mut state = 0x2545_F491_4F6C_DD1Du64;
251+ let mut next = move || {
252+ state ^= state << 13;
253+ state ^= state >> 7;
254+ state ^= state << 17;
255+ state
256+ };
257+ let mut table = Vec::new();
258+ for src in matroska_fixtures() {
259+ let secs = duration(&src).max(0.001);
260+ // ONE reader for the whole loop: reopening is what this crate exists
261+ // not to do.
262+ let mut demuxer =
263+ MatroskaDemuxer::new(BufReader::new(File::open(&src).expect("fixture opens")))
264+ .expect("demuxes");
265+ let stream = demuxer.streams()[0].index;
266+ // Where the file's own first random-access point sits, read off the same
267+ // reader before a single seek: a target in front of it can land nowhere
268+ // earlier.
269+ let first = loop {
270+ let packet = demuxer.next_packet().expect("a first keyframe");
271+ if packet.stream == stream && packet.flags.keyframe {
272+ break packet.time_base.rescale(
273+ packet.pts.unwrap_or(0),
274+ TimeBase::MILLIS,
275+ ec_core::Rounding::Down,
276+ );
277+ }
278+ };
279+ let mut landed = 0;
280+ let mut exact = 0;
281+ for _ in 0..100 {
282+ let target_ms = (next() % ((secs * 1000.0) as u64 + 1)) as i64;
283+ let target = Timestamp::new(target_ms, TimeBase::MILLIS);
284+ demuxer
285+ .seek(stream, target, SeekMode::SyncBefore)
286+ .unwrap_or_else(|e| panic!("{}: seek to {target_ms}ms: {e}", src.display()));
287+ let packet = loop {
288+ match demuxer.next_packet() {
289+ Ok(p) if p.stream == stream => break Some(p),
290+ Ok(_) => continue,
291+ Err(Error::Eof) => break None,
292+ Err(e) => panic!("{}: after seek: {e}", src.display()),
293+ }
294+ };
295+ let Some(packet) = packet else {
296+ panic!("{}: seek to {target_ms}ms reached the end", src.display());
297+ };
298+ assert!(
299+ packet.flags.keyframe,
300+ "{}: seek to {target_ms}ms landed on a non-keyframe",
301+ src.display()
302+ );
303+ let pts = packet.pts.expect("a block states its timestamp");
304+ let ms = packet
305+ .time_base
306+ .rescale(pts, TimeBase::MILLIS, ec_core::Rounding::Down);
307+ // At or before the target, or the first keyframe of the file when
308+ // the target sits in front of it.
309+ assert!(
310+ ms <= target_ms || ms == first,
311+ "{}: seek to {target_ms}ms landed at {ms}ms",
312+ src.display()
313+ );
314+ landed += 1;
315+ exact += usize::from(ms == target_ms);
316+ }
317+ assert_eq!(landed, 100);
318+ table.push(format!(
319+ "{:<40} 100/100 seeks, {exact} exact, 1 reader",
320+ src.file_name().unwrap().to_string_lossy()
321+ ));
322+ }
323+ println!("{}", table.join("\n"));
324+}
325+
326+/// A sweep of the real library: ten films, one per directory so a 60-episode
327+/// series counts once, each demuxed end to end and its packet counts compared
328+/// with ffprobe's. Ignored by default because it reads tens of gigabytes.
329+///
330+/// Run it with `cargo test -p ec-matroska --release --test matroska -- --ignored
331+/// --nocapture`.
332+#[test]
333+#[ignore = "reads the real library end to end"]
334+fn real_library_spot_sweep() {
335+ let manifest = std::fs::read_to_string(fixtures().join("real-library-manifest.tsv"))
336+ .expect("fixtures/real-library-manifest.tsv");
337+ let mut seen: Vec<String> = Vec::new();
338+ let mut files: Vec<PathBuf> = Vec::new();
339+ for line in manifest.lines().skip(1) {
340+ let mut cols = line.split('\t');
341+ let (Some(path), Some(container)) = (cols.next(), cols.next()) else {
342+ continue;
343+ };
344+ let path = PathBuf::from(path);
345+ if !container.contains("matroska") || !path.exists() {
346+ continue;
347+ }
348+ // One per directory: a series of sixty episodes is one shape, not sixty.
349+ let dir = path
350+ .parent()
351+ .unwrap_or(Path::new("/"))
352+ .to_string_lossy()
353+ .into_owned();
354+ if seen.contains(&dir) {
355+ continue;
356+ }
357+ seen.push(dir);
358+ files.push(path);
359+ }
360+ assert!(
361+ files.len() >= 10,
362+ "only {} Matroska directories",
363+ files.len()
364+ );
365+ let step = (files.len() / 10).max(1);
366+ let picked: Vec<PathBuf> = files.into_iter().step_by(step).take(10).collect();
367+
368+ let mut table = Vec::new();
369+ for path in &picked {
370+ let mut demuxer =
371+ MatroskaDemuxer::new(BufReader::new(File::open(path).expect("film opens")))
372+ .expect("demuxes");
373+ let streams: Vec<String> = demuxer
374+ .streams()
375+ .iter()
376+ .map(|s| s.params.codec.name().to_string())
377+ .collect();
378+ let text: Vec<u32> = demuxer
379+ .streams()
380+ .iter()
381+ .filter(|s| {
382+ matches!(
383+ s.params.codec,
384+ ec_core::CodecId::Srt | ec_core::CodecId::Ass | ec_core::CodecId::WebVtt
385+ )
386+ })
387+ .map(|s| s.index)
388+ .collect();
389+ let mut counts = vec![0usize; streams.len()];
390+ let mut checked = Vec::new();
391+ loop {
392+ match demuxer.next_packet() {
393+ Ok(p) => {
394+ counts[p.stream as usize] += 1;
395+ // A text track under `ContentEncodings` that came back
396+ // still compressed is not UTF-8, which is the cheapest
397+ // proof the zlib path ran.
398+ if text.contains(&p.stream) && !checked.contains(&p.stream) {
399+ checked.push(p.stream);
400+ assert!(
401+ std::str::from_utf8(&p.data).is_ok(),
402+ "{}: stream {} is not text",
403+ path.display(),
404+ p.stream
405+ );
406+ }
407+ }
408+ Err(Error::Eof) => break,
409+ Err(e) => panic!("{}: {e}", path.display()),
410+ }
411+ }
412+ // ffprobe counts the same packets on the same file; the picture track is
413+ // first in both and is the one compared exactly.
414+ let out = Command::new("ffprobe")
415+ .args([
416+ "-v",
417+ "error",
418+ "-count_packets",
419+ "-show_entries",
420+ "stream=nb_read_packets",
421+ "-of",
422+ "csv=p=0",
423+ ])
424+ .arg(path)
425+ .output()
426+ .expect("ffprobe runs");
427+ let theirs: Vec<usize> = String::from_utf8_lossy(&out.stdout)
428+ .lines()
429+ // ffprobe leaves a trailing separator on a row whose fields it
430+ // padded; the count is the first number on the line.
431+ .filter_map(|l| l.trim().trim_end_matches(',').parse().ok())
432+ .collect();
433+ assert_eq!(
434+ counts.first(),
435+ theirs.first(),
436+ "{}: picture packet count",
437+ path.display()
438+ );
439+ assert!(counts.iter().sum::<usize>() > 0);
440+
441+ // ...and twenty seeks spread over the film, on one more reader, each
442+ // landing on a random-access point at or before its target. A film is
443+ // where a cue table is worth having: the fixtures are two seconds long
444+ // and every one of their clusters is a keyframe.
445+ let mut demuxer =
446+ MatroskaDemuxer::new(BufReader::new(File::open(path).expect("film opens")))
447+ .expect("demuxes");
448+ let stream = demuxer.streams()[0].index;
449+ // Where the picture actually starts: a film whose video track begins at
450+ // 83 ms has nothing earlier to land on, and that is not a failed seek.
451+ let first = loop {
452+ let packet = demuxer.next_packet().expect("a first keyframe");
453+ if packet.stream == stream && packet.flags.keyframe {
454+ break packet.time_base.rescale(
455+ packet.pts.unwrap_or(0),
456+ TimeBase::MILLIS,
457+ ec_core::Rounding::Down,
458+ );
459+ }
460+ };
461+ let secs = duration(path).max(1.0);
462+ for i in 0..20 {
463+ let target_ms = (secs * 1000.0 * f64::from(i) / 20.0) as i64;
464+ demuxer
465+ .seek(
466+ stream,
467+ Timestamp::new(target_ms, TimeBase::MILLIS),
468+ SeekMode::SyncBefore,
469+ )
470+ .unwrap_or_else(|e| panic!("{}: seek to {target_ms}ms: {e}", path.display()));
471+ let packet = loop {
472+ match demuxer.next_packet() {
473+ Ok(p) if p.stream == stream => break p,
474+ Ok(_) => continue,
475+ Err(e) => panic!("{}: after seek: {e}", path.display()),
476+ }
477+ };
478+ let ms = packet.time_base.rescale(
479+ packet.pts.unwrap_or(0),
480+ TimeBase::MILLIS,
481+ ec_core::Rounding::Down,
482+ );
483+ assert!(
484+ packet.flags.keyframe && (ms <= target_ms || ms == first),
485+ "{}: seek to {target_ms}ms landed at {ms}ms, key {}",
486+ path.display(),
487+ packet.flags.keyframe
488+ );
489+ }
490+ table.push(format!(
491+ "{:<64} {streams:?} ours {counts:?} ffprobe {theirs:?}",
492+ path.file_name().unwrap().to_string_lossy()
493+ ));
494+ }
495+ println!("{}", table.join("\n"));
496+}