forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

probe_duration.rs198 lines, 7.4 KiBHistoryRawDownload
1//! The duration `probe_media` reports for every audio and video file in `assets/`,
2//! checked against ffprobe, and the language a probe states for an mp4/mov track.
3//!
4//! The oracle is `ffprobe`'s `format=duration`, with rules that follow what
5//! ffprobe itself measures, or what a player plays:
6//!
7//! - An Ogg Opus stream's playable length is RFC 7845 section 4's: the last
8//! granule position minus the `OpusHead` pre-skip, over 48 kHz. ffprobe does
9//! not take the pre-skip off, so the oracle subtracts it from ffprobe's figure
10//! (`test_tone.opus`: 3.0065 - 312/48000 = 3.000 s, the tone's length).
11//! - A raw ADTS stream (`format_name=aac`) states no length. ffprobe's format
12//! duration there is file size over an estimated bit rate, which is a guess
13//! (3.126 s on `test_tone.aac`). Its own packet timeline is the measured length:
14//! the last packet's start plus its duration, which is 131 frames of 1024 samples
15//! (3.0418 s). The test compares against that for ADTS.
16//! - A Matroska or WebM file with a picture is reported by the engine as its
17//! picture length, the frame count over the frame rate (the timeline's contract,
18//! see `MediaFacts::duration_secs`). ffprobe reports the Segment `Info` duration,
19//! which runs past the last frame by part of a frame. The tolerance for those
20//! files is one frame on top of the 2 ms.
21//!
22//! A file the engine refuses (no duration) is skipped, and so is anything ffprobe
23//! finds no audio or video in (subtitles alone, a still). When ffprobe is not on
24//! the path the whole test is skipped.
25//!
26//! ```text
27//! cargo test --release -p engine --test probe_duration -- --nocapture
28//! ```
29
30use std::path::{Path, PathBuf};
31use std::process::Command;
32
33use engine::{StreamKind, probe_media};
34
35/// The allowed disagreement between the engine and ffprobe, in seconds.
36const TOLERANCE: f64 = 0.002;
37
38/// Files that disagree for a reason outside the rules above, with the reason.
39const ALLOWLIST: &[(&str, &str)] = &[(
40 "test_short_video_long_audio.mp4",
41 "the engine reports the picture's length (2.0 s) as its file duration, as it does \
42 for any mp4 with a picture; ffprobe reports the longest stream (the 60 s audio). \
43 The 60 s audio is listed as the audio stream's own duration.",
44)];
45
46fn assets_dir() -> PathBuf {
47 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets")
48}
49
50fn ffprobe_available() -> bool {
51 Command::new("ffprobe")
52 .arg("-version")
53 .output()
54 .is_ok_and(|o| o.status.success())
55}
56
57/// The `OpusHead` pre-skip of an Ogg Opus file (RFC 7845 section 5.1: little-endian
58/// u16 at byte 10 of the packet), `None` for a file that is not Ogg Opus.
59fn opus_pre_skip(path: &Path) -> Option<u64> {
60 let bytes = std::fs::read(path).ok()?;
61 if !bytes.starts_with(b"OggS") {
62 return None;
63 }
64 let head = bytes.windows(8).position(|w| w == b"OpusHead")?;
65 let at = head + 10;
66 Some(u64::from(u16::from_le_bytes([
67 *bytes.get(at)?,
68 *bytes.get(at + 1)?,
69 ])))
70}
71
72/// `ffprobe` with the given `-show_entries` and `-of csv=p=0`, one line per row.
73/// The csv writer ends a row with a comma and quotes a value that holds one
74/// (`"matroska,webm"`); both are taken off.
75fn ffprobe_rows(path: &Path, entries: &str) -> Vec<String> {
76 let out = Command::new("ffprobe")
77 .args(["-v", "error", "-show_entries", entries, "-of", "csv=p=0"])
78 .arg(path)
79 .output()
80 .expect("run ffprobe");
81 String::from_utf8_lossy(&out.stdout)
82 .lines()
83 .map(|l| l.trim().trim_end_matches(',').trim_matches('"').to_string())
84 .collect()
85}
86
87/// ffprobe's `format=duration`, `None` where it states none (`N/A`).
88fn ffprobe_format_secs(path: &Path) -> Option<f64> {
89 ffprobe_rows(path, "format=duration").first()?.parse().ok()
90}
91
92/// End of the last packet on the first stream, in seconds: the measured length
93/// of a stream with no stated duration.
94fn ffprobe_packet_end_secs(path: &Path) -> Option<f64> {
95 let last = ffprobe_rows(path, "packet=pts_time,duration_time")
96 .into_iter()
97 .rfind(|l| !l.is_empty())?;
98 let (pts, dur) = last.split_once(',')?;
99 Some(pts.parse::<f64>().ok()? + dur.parse::<f64>().ok()?)
100}
101
102/// Whether ffprobe finds an audio or video stream in the file.
103fn has_av(path: &Path) -> bool {
104 ffprobe_rows(path, "stream=codec_type")
105 .iter()
106 .any(|t| t == "audio" || t == "video")
107}
108
109#[test]
110fn engine_duration_matches_ffprobe_for_every_asset() {
111 if !ffprobe_available() {
112 eprintln!("ffprobe not on the path: skipped");
113 return;
114 }
115 let mut paths: Vec<PathBuf> = std::fs::read_dir(assets_dir())
116 .expect("assets directory")
117 .flatten()
118 .map(|e| e.path())
119 .filter(|p| p.is_file() && !engine::is_image(p))
120 .collect();
121 paths.sort();
122
123 let (mut checked, mut skipped, mut failures) = (0, Vec::new(), Vec::new());
124 for path in &paths {
125 let name = path.file_name().unwrap().to_string_lossy().into_owned();
126 if !has_av(path) {
127 skipped.push(format!("{name} (no audio or video for ffprobe)"));
128 continue;
129 }
130 let facts = probe_media(path);
131 let Some(engine_secs) = facts.duration_secs else {
132 skipped.push(format!("{name} (the engine refuses it)"));
133 continue;
134 };
135 let format = ffprobe_rows(path, "format=format_name")
136 .first()
137 .cloned()
138 .unwrap_or_default();
139 let oracle = if format == "aac" {
140 ffprobe_packet_end_secs(path)
141 } else if let (Some(secs), Some(pre_skip)) =
142 (ffprobe_format_secs(path), opus_pre_skip(path))
143 {
144 // RFC 7845 section 4: the playable length is the granule minus the pre-skip.
145 Some(secs - pre_skip as f64 / 48_000.0)
146 } else {
147 ffprobe_format_secs(path)
148 };
149 let Some(oracle) = oracle else {
150 skipped.push(format!("{name} (ffprobe states no duration)"));
151 continue;
152 };
153 checked += 1;
154
155 let mut tolerance = TOLERANCE;
156 let matroska = format.contains("matroska");
157 if matroska && let Some(fps) = facts.video.as_ref().and_then(|v| v.frame_rate) {
158 tolerance += 1.0 / fps;
159 }
160 let diff = (engine_secs - oracle).abs();
161 let allowed = ALLOWLIST.iter().any(|(n, _)| *n == name);
162 if diff > tolerance && !allowed {
163 failures.push(format!(
164 "{name}: engine {engine_secs:.6} s, ffprobe {oracle:.6} s, off by {diff:.6} s"
165 ));
166 }
167 }
168 eprintln!(
169 "probe_duration: {checked} checked, {} skipped",
170 skipped.len()
171 );
172 for s in &skipped {
173 eprintln!(" skipped: {s}");
174 }
175 assert!(
176 failures.is_empty(),
177 "durations off ffprobe by more than {TOLERANCE} s:\n{}",
178 failures.join("\n")
179 );
180}
181
182#[test]
183fn mov_track_language_is_und_when_none_is_stated() {
184 let path = assets_dir().join("test_qt.mov");
185 let facts = probe_media(&path);
186 for kind in [StreamKind::Video, StreamKind::Audio] {
187 let stream = facts
188 .streams
189 .iter()
190 .find(|s| s.kind == kind)
191 .unwrap_or_else(|| panic!("test_qt.mov has no {kind:?} stream"));
192 assert_eq!(
193 stream.language.as_deref(),
194 Some("und"),
195 "{kind:?} language of test_qt.mov, an mdhd code of 0x7fff (no language)"
196 );
197 }
198}